xray

package
v1.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 27 Imported by: 0

README

X-Ray

Parity grade: A · SDK aws-sdk-go-v2/service/xray@v1.39.4 · last audited 2026-08-10 (b72533e7a)

Coverage

Metric Value
Operations audited 38 (35 ok, 1 partial, 2 deferred)
Feature families 3 (3 ok)
Known gaps 7
Deferred items 1
Resource leaks clean
Known gaps
  • GetInsightSummaries' GroupARN/GroupName filter is honored at the wire/query layer (6flj sweep, 2026-08-15) but the insight DETECTOR itself (detectInsights, insights.go) has no per-group filter-expression evaluation -- every detected insight is unconditionally labelled GroupName="default" regardless of how many real Group records a caller has created or what their FilterExpression says. A request scoped to "default" gets every detected insight (correct behavior only by coincidence of there being one implicit group); a request scoped to any other real group correctly gets an empty result now, but not because that group's filter was evaluated -- because no insight is ever labelled with it. True per-group detection would require evaluating each group's FilterExpression against live segment traffic, a detector redesign out of scope for a wire-shape fix.
  • GetTraceSummariesInput's optional Sampling (bool) and SamplingStrategy (Name/Value) request members have no effect: gopherstack has no sampling engine on the trace-summary read path (Sampling is parsed and discarded; SamplingStrategy is not modeled at all). Every call returns the full unsampled TraceSummaries set regardless of what a client requests, which is a safe superset (never a truncation a client wouldn't expect), not a correctness bug -- but flagged here as a real, never-modelled request member per 6flj's checklist.
  • PutTelemetryRecords ring buffer (100 entries) not persisted across restart; low-risk, AWS telemetry data itself is operational/ephemeral by nature (unchanged this pass)
  • Insight.RootCauseServiceId, RootCauseServiceRequestImpactStatistics, TopAnomalousServices, and GetInsightImpactGraph's Services remain always empty/unset -- these claim a cross-service root-cause/topology determination that gopherstack's insight detector (detectInsights in insights.go, a single-service fault-rate-threshold heuristic with no service-graph awareness) does not perform. NARROWED this pass: Categories and ClientRequestImpactStatistics were moved OUT of this gap and implemented (see GetInsight/GetInsightSummaries ops) once it was established they need no anomaly-detection algorithm at all -- Categories has exactly one possible enum value (FAULT) given gopherstack's detector, and ClientRequestImpactStatistics is a direct surfacing of the w.Total/w.FaultCount counters the detector already computes to decide whether to open the insight. The remaining fields genuinely require cross-service causality analysis this detector was never designed to do; judged out of scope, same as before.
  • SamplingRateBoost's runtime boost-trigger VALUE (the actual BoostRate number X-Ray would compute) is NOT implemented and never will be guessed: AWS does not publish the algorithm (API_SamplingBoostStatisticsDocument.html describes the inputs, AnomalyCount/SampledAnomalyCount/TotalCount, only qualitatively), so SamplingTargetDocument.SamplingBoost is always left unset. An earlier draft of this pass computed a fabricated rate (linear interpolation between FixedRate and MaxRate by anomaly ratio) and was reverted on review: a fabricated quota/price/rate is worse than an absent one, because a client reads and acts on it without rechecking a plausible-looking number. NARROWED this pass: the WIRE gap (SamplingBoostStatisticsDocuments/UnprocessedBoostStatistics were previously silently absent regardless of the algorithm question) IS fixed -- documents for known rules are now accepted, documents for unknown rules are now reported in UnprocessedBoostStatistics. The net effect for a client: submitting a boost document for a rule with SamplingRateBoost configured is accepted and produces no error, but also produces no observable SamplingBoost on the returned target -- an honest 'accepted, no engine behind it' gap.
  • PutResourcePolicy's BypassPolicyLockoutCheck field is parsed but LockoutPreventionException is never raised. RE-VERIFIED this pass (WebFetch against docs.aws.amazon.com/xray/latest/api/API_PutResourcePolicy.html): the real check is 'the policy would prevent THE CALLER OF THIS REQUEST from calling PutResourcePolicy in the future' -- i.e. it evaluates the submitted policy document against the calling IAM principal's identity, not against any abstract/generic principal. gopherstack's xray package never resolves or threads a calling principal into request handling at all (grep confirms zero use of pkgs/awsmeta, which only carries Account/Region/Partition/RequestID, not a principal ARN) -- there is no 'the caller' value in scope to evaluate against. This is a genuine architectural gap distinct from the six other 'blocked' claims resolved this campaign: those were blocked by unimplemented-but-available logic, this one is blocked by an identity concept the request pipeline does not carry at all. Implementing a real per-principal check would require adding caller-identity plumbing to the whole service (or repo-wide), which is out of scope for a resource-policy op. The parameter is still accepted (matches wire shape) but has no effect, which is safe (never falsely rejects a real client's request) even though it under-enforces relative to real AWS.
  • ThrottledException is declared in the modeled error set for every X-Ray operation but is never emitted anywhere in gopherstack (no rate limiting is modeled). This is consistent with the rest of gopherstack's emulation approach (no service throttles by default) and is not treated as a gap specific to X-Ray.
Deferred
  • none; all routed ops covered by ops/families above

More

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGroupNotFound is returned when an X-Ray group is not found.
	ErrGroupNotFound = awserr.New("InvalidRequestException", awserr.ErrNotFound)
	// ErrGroupAlreadyExists is returned when an X-Ray group already exists.
	ErrGroupAlreadyExists = awserr.New("GroupAlreadyExistsException", awserr.ErrConflict)
	// ErrSamplingRuleNotFound is returned when a sampling rule is not found.
	ErrSamplingRuleNotFound = awserr.New("InvalidRequestException", awserr.ErrNotFound)
	// ErrSamplingRuleAlreadyExists is returned when a sampling rule already exists.
	ErrSamplingRuleAlreadyExists = awserr.New("RuleAlreadyExistsException", awserr.ErrConflict)
	// ErrInsightNotFound is returned when an X-Ray insight is not found.
	ErrInsightNotFound = awserr.New("InvalidRequestException", awserr.ErrNotFound)
	// ErrResourcePolicyNotFound is returned when a resource policy is not found.
	ErrResourcePolicyNotFound = awserr.New("InvalidRequestException", awserr.ErrNotFound)
	// ErrIndexingRuleNotFound is returned when an indexing rule is not found.
	// UpdateIndexingRule's modeled error set uses ResourceNotFoundException here
	// (unlike GetGroup/DeleteGroup/etc., which only ever return InvalidRequestException).
	ErrIndexingRuleNotFound = awserr.New("ResourceNotFoundException", awserr.ErrNotFound)
	// ErrValidation is returned when a request fails field-level validation.
	ErrValidation = awserr.New("InvalidRequestException", awserr.ErrInvalidParameter)
	// ErrInvalidSamplingRule is returned when sampling rule fields fail validation.
	ErrInvalidSamplingRule = awserr.New("InvalidSamplingRuleException", awserr.ErrInvalidParameter)
	// ErrInvalidPolicyRevisionID is returned when a policy revision ID does not match.
	ErrInvalidPolicyRevisionID = awserr.New("InvalidPolicyRevisionIdException", awserr.ErrConflict)
	// ErrMalformedPolicyDocument is returned when a policy document is not valid JSON.
	ErrMalformedPolicyDocument = awserr.New("MalformedPolicyDocumentException", awserr.ErrInvalidParameter)
	// ErrTooManyPolicies is returned when the max policy count is exceeded.
	ErrTooManyPolicies = awserr.New("InvalidRequestException", awserr.ErrInvalidParameter)
	// ErrBatchGetTracesLimit is returned when more than 5 trace IDs are requested.
	ErrBatchGetTracesLimit = awserr.New("InvalidRequestException", awserr.ErrInvalidParameter)
	// ErrDefaultRuleUndeletable is returned when the built-in Default sampling rule is deleted.
	ErrDefaultRuleUndeletable = awserr.New("InvalidRequestException", awserr.ErrInvalidParameter)
	// ErrPolicySizeLimitExceeded is returned when a resource policy document exceeds the maximum size.
	ErrPolicySizeLimitExceeded = awserr.New("PolicySizeLimitExceededException", awserr.ErrInvalidParameter)
	// ErrRuleLimitExceeded is returned when the maximum number of sampling rules is exceeded.
	ErrRuleLimitExceeded = awserr.New("RuleLimitExceededException", awserr.ErrInvalidParameter)
	// ErrTooManyTags is returned when a resource would exceed the maximum number of tags.
	ErrTooManyTags = awserr.New("TooManyTagsException", awserr.ErrInvalidParameter)
	// ErrResourceNotFound is returned for operations whose modeled error is
	// ResourceNotFoundException rather than InvalidRequestException (TagResource,
	// UntagResource, ListTagsForResource, UpdateIndexingRule, and the trace-retrieval
	// token operations StartTraceRetrieval/CancelTraceRetrieval/ListRetrievedTraces/
	// GetRetrievedTracesGraph -- confirmed against each operation's declared error set
	// in aws-sdk-go-v2/service/xray's deserializers.go).
	ErrResourceNotFound = awserr.New("ResourceNotFoundException", awserr.ErrNotFound)
	// ErrTraceRetrievalNotFound is returned when a RetrievalToken passed to
	// CancelTraceRetrieval, ListRetrievedTraces, or GetRetrievedTracesGraph does not
	// correspond to a retrieval started by StartTraceRetrieval. All three declare
	// ResourceNotFoundException in their modeled error set.
	ErrTraceRetrievalNotFound = awserr.New("ResourceNotFoundException", awserr.ErrNotFound)
)
View Source
var ErrNilAppContext = errors.New("xray: nil app context")

ErrNilAppContext is returned when Init is called with a nil AppContext.

Functions

func EvaluateFilter

func EvaluateFilter(expr string, summary TraceSummaryData) bool

EvaluateFilter is exported for tests.

func ValidateSamplingRule

func ValidateSamplingRule(rule SamplingRule) error

ValidateSamplingRule validates sampling rule fields per AWS constraints.

Types

type AnnotationOccurrence added in v1.3.1

type AnnotationOccurrence struct {
	Value      any
	ServiceIDs []TraceSummaryServiceID
}

AnnotationOccurrence holds one distinct value observed for an annotation key within a trace, together with the services that reported it -- mirrors the real API's per-key map[string][]ValueWithServiceIds shape, where different segments/services within one trace can report different values for the same annotation key.

type ConfigProvider

type ConfigProvider interface {
	GetXRaySettings() Settings
}

ConfigProvider is a private interface to extract X-Ray configuration from the abstract AppContext Config.

type EncryptionConfig

type EncryptionConfig struct {
	KeyID  string `json:"KeyId,omitempty"`
	Status string `json:"Status"`
	Type   string `json:"Type"`
}

EncryptionConfig represents X-Ray encryption configuration.

type Group

type Group struct {
	CreatedAt             time.Time             `json:"createdAt"`
	GroupARN              string                `json:"groupARN"`
	GroupName             string                `json:"groupName"`
	FilterExpression      string                `json:"filterExpression"`
	InsightsConfiguration InsightsConfiguration `json:"insightsConfiguration"`
}

Group represents an X-Ray group used to filter trace data.

type Handler

type Handler struct {
	Backend StorageBackend
	// contains filtered or unexported fields
}

Handler is the Echo HTTP handler for AWS X-Ray operations.

func NewHandler

func NewHandler(backend StorageBackend) *Handler

NewHandler creates a new X-Ray handler backed by backend.

func (*Handler) ChaosOperations

func (h *Handler) ChaosOperations() []string

ChaosOperations returns all operations that can be fault-injected.

func (*Handler) ChaosRegions

func (h *Handler) ChaosRegions() []string

ChaosRegions returns all regions this X-Ray instance handles.

func (*Handler) ChaosServiceName

func (h *Handler) ChaosServiceName() string

ChaosServiceName returns the lowercase AWS service name for fault rule matching.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation extracts the X-Ray operation name from the request path.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource extracts the primary resource identifier from the request body.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations returns the list of supported X-Ray operations.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler function for X-Ray requests.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority returns the routing priority.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears all backend state.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable by delegating to the backend.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher returns a function that matches X-Ray REST API requests. X-Ray uses POST with specific well-known paths, except /EncryptionConfig which also accepts GET.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable by delegating to the backend.

func (*Handler) StartWorker

func (h *Handler) StartWorker(ctx context.Context) error

StartWorker starts the background janitor if configured.

func (*Handler) WithJanitor

func (h *Handler) WithJanitor(interval, ttl time.Duration, taskTimeout ...time.Duration) *Handler

WithJanitor attaches a background janitor to the handler. The optional taskTimeout variadic parameter sets TaskTimeout on the janitor. If Backend is not an *InMemoryBackend the call is a no-op.

type InMemoryBackend

type InMemoryBackend struct {
	// contains filtered or unexported fields
}

InMemoryBackend is the in-memory store for X-Ray resources.

func NewInMemoryBackend

func NewInMemoryBackend(accountID, region string) *InMemoryBackend

NewInMemoryBackend creates a new InMemoryBackend with the given accountID and region.

func (*InMemoryBackend) AddInsightEventInternal

func (b *InMemoryBackend) AddInsightEventInternal(event InsightEvent)

AddInsightEventInternal seeds an event for an insight directly for testing.

func (*InMemoryBackend) AddInsightInternal

func (b *InMemoryBackend) AddInsightInternal(insight Insight)

AddInsightInternal seeds an insight directly for testing.

func (*InMemoryBackend) AddResourcePolicyInternal

func (b *InMemoryBackend) AddResourcePolicyInternal(policy ResourcePolicy)

AddResourcePolicyInternal seeds a resource policy directly for testing.

func (*InMemoryBackend) AddTraceRetrievalInternal

func (b *InMemoryBackend) AddTraceRetrievalInternal(retrieval TraceRetrieval)

AddTraceRetrievalInternal seeds a trace retrieval token directly for testing.

func (*InMemoryBackend) CancelTraceRetrieval

func (b *InMemoryBackend) CancelTraceRetrieval(retrievalToken string) error

CancelTraceRetrieval marks a trace retrieval as cancelled. Returns ErrTraceRetrievalNotFound if the token was never created by StartTraceRetrieval (real AWS declares ResourceNotFoundException for CancelTraceRetrieval on unknown tokens).

func (*InMemoryBackend) CreateGroup

func (b *InMemoryBackend) CreateGroup(name, filterExpr string) (*Group, error)

CreateGroup creates a new X-Ray group with the given name and filter expression.

func (*InMemoryBackend) CreateGroupWithInsights

func (b *InMemoryBackend) CreateGroupWithInsights(name, filterExpr string, ic InsightsConfiguration) (*Group, error)

CreateGroupWithInsights creates a new group with full InsightsConfiguration.

func (*InMemoryBackend) CreateSamplingRule

func (b *InMemoryBackend) CreateSamplingRule(rule SamplingRule) (*SamplingRule, error)

CreateSamplingRule creates a new sampling rule. Returns ErrRuleLimitExceeded if the account already has maxSamplingRules rules.

func (*InMemoryBackend) DeleteGroup

func (b *InMemoryBackend) DeleteGroup(name string) error

DeleteGroup removes the group with the given name.

func (*InMemoryBackend) DeleteGroupByARN

func (b *InMemoryBackend) DeleteGroupByARN(name, arn string) error

DeleteGroupByARN removes the group with the given ARN or name.

func (*InMemoryBackend) DeleteResourcePolicy

func (b *InMemoryBackend) DeleteResourcePolicy(policyName, policyRevisionID string) error

DeleteResourcePolicy removes the resource policy with the given name. If policyRevisionID is non-empty, it must match the stored policy's current revision ID, or ErrInvalidPolicyRevisionID is returned (matches real AWS: providing a PolicyRevisionId makes the delete atomic and guards against a concurrent PutResourcePolicy).

func (*InMemoryBackend) DeleteSamplingRule

func (b *InMemoryBackend) DeleteSamplingRule(ruleName, ruleARN string) (*SamplingRule, error)

DeleteSamplingRule removes the sampling rule identified by ruleName (if non-empty, else ruleARN) and returns it. The built-in "Default" rule cannot be deleted, whether identified by name or ARN; attempting to do so returns ErrDefaultRuleUndeletable.

func (*InMemoryBackend) GetAllParsedSegments

func (b *InMemoryBackend) GetAllParsedSegments() map[string][]*Segment

GetAllParsedSegments returns all parsed segments, keyed by trace ID.

func (*InMemoryBackend) GetEncryptionConfig

func (b *InMemoryBackend) GetEncryptionConfig() *EncryptionConfig

GetEncryptionConfig returns the current X-Ray encryption configuration. If the current status is UPDATING, this call advances it to ACTIVE.

func (*InMemoryBackend) GetGroup

func (b *InMemoryBackend) GetGroup(name string) (*Group, error)

GetGroup returns the group with the given name, or by ARN if name is empty.

func (*InMemoryBackend) GetGroupByARN

func (b *InMemoryBackend) GetGroupByARN(arn string) (*Group, error)

GetGroupByARN returns the group with the given ARN.

func (*InMemoryBackend) GetGroups

func (b *InMemoryBackend) GetGroups() []Group

GetGroups returns all groups sorted by name.

func (*InMemoryBackend) GetIndexingRules

func (b *InMemoryBackend) GetIndexingRules() []*IndexingRule

GetIndexingRules returns all indexing rules.

func (*InMemoryBackend) GetInsight

func (b *InMemoryBackend) GetInsight(insightID string) (*Insight, error)

GetInsight returns the insight with the given ID.

func (*InMemoryBackend) GetInsightEvents

func (b *InMemoryBackend) GetInsightEvents(insightID string) ([]*InsightEvent, error)

GetInsightEvents returns all events for the given insight ID.

func (*InMemoryBackend) GetInsightSummaries

func (b *InMemoryBackend) GetInsightSummaries(
	states []string, groupName string, startTime, endTime time.Time,
) ([]Insight, error)

GetInsightSummaries returns insight summaries whose active window overlaps [startTime, endTime] and whose GroupName matches groupName, optionally filtered by state. If states is empty, all states are returned. "ALL" matches both ACTIVE and CLOSED. Unknown states return ErrValidation.

groupName scoping is honest but not full parity: this backend's insight detector (detectInsights) has no per-group filter-expression evaluation -- every detected insight is unconditionally labelled with the fixed group name "default" regardless of how many real Group records exist or their FilterExpression. Filtering by groupName here correctly returns empty for any group other than "default" (previously the group filter was discarded entirely and every group got the same "default" insights back), but a request for "default" is not itself scoped to a real Group's filter expression -- see PARITY.md.

func (*InMemoryBackend) GetParsedSegments

func (b *InMemoryBackend) GetParsedSegments(traceID string) []*Segment

GetParsedSegments returns a copy of the parsed segments for a given trace ID.

func (*InMemoryBackend) GetRetrievedTracesGraph

func (b *InMemoryBackend) GetRetrievedTracesGraph(retrievalToken string) (string, []*Trace, error)

GetRetrievedTracesGraph returns the status and services for a retrieval token. Returns ErrTraceRetrievalNotFound if the token was never created by StartTraceRetrieval.

func (*InMemoryBackend) GetSamplingRules

func (b *InMemoryBackend) GetSamplingRules() []SamplingRule

GetSamplingRules returns all sampling rules sorted by priority (ascending), then by name for stability.

func (*InMemoryBackend) GetSamplingStatisticSummaries

func (b *InMemoryBackend) GetSamplingStatisticSummaries() []SamplingStatisticSummary

GetSamplingStatisticSummaries returns accumulated sampling statistic summaries.

func (*InMemoryBackend) GetSamplingTargets

GetSamplingTargets returns target documents for the provided stat documents. Rules that do not exist are returned in the unprocessed list. Documents with an empty ClientID are returned in the unprocessed list. Statistics from known rules are accumulated for GetSamplingStatisticSummaries. boostDocs are validated against known rules (unknown rules go to the returned unprocessedBoost list) but never produce a SamplingBoost: AWS does not publish its boost-trigger algorithm (API_SamplingBoostStatisticsDocument.html describes the inputs only qualitatively), and a fabricated boost rate is worse than an absent one -- a client can read and act on it. SamplingTargetDocument.SamplingBoost is therefore always left unset; see PARITY.md.

func (*InMemoryBackend) GetServiceGraph

func (b *InMemoryBackend) GetServiceGraph(startTime, endTime time.Time) []map[string]any

GetServiceGraph returns a service graph derived from stored traces in the time window.

func (*InMemoryBackend) GetTimeSeriesServiceStatistics

func (b *InMemoryBackend) GetTimeSeriesServiceStatistics(startTime, endTime time.Time, period int) []map[string]any

GetTimeSeriesServiceStatistics returns per-period bucketed statistics for segments in the time window.

func (*InMemoryBackend) GetTrace

func (b *InMemoryBackend) GetTrace(traceID string) *Trace

GetTrace returns the trace with the given ID, or nil if not found.

func (*InMemoryBackend) GetTraceGraph

func (b *InMemoryBackend) GetTraceGraph(traceIDs []string) []map[string]any

GetTraceGraph returns a service graph scoped to the given trace IDs.

func (*InMemoryBackend) GetTraceSegmentDestination

func (b *InMemoryBackend) GetTraceSegmentDestination() string

GetTraceSegmentDestination returns the current trace segment destination.

func (*InMemoryBackend) GetTraceSummaries

func (b *InMemoryBackend) GetTraceSummaries() []Trace

GetTraceSummaries returns all trace summaries sorted by start time (newest first).

func (*InMemoryBackend) LastRuleModification

func (b *InMemoryBackend) LastRuleModification() time.Time

LastRuleModification returns the timestamp of the last sampling rule modification.

func (*InMemoryBackend) ListResourcePolicies

func (b *InMemoryBackend) ListResourcePolicies() []ResourcePolicy

ListResourcePolicies returns all resource policies sorted by name.

func (*InMemoryBackend) ListRetrievedTraces

func (b *InMemoryBackend) ListRetrievedTraces(retrievalToken string) (string, []*Trace, error)

ListRetrievedTraces returns the status and traces associated with a retrieval token. Returns ErrTraceRetrievalNotFound if the token was never created by StartTraceRetrieval.

func (*InMemoryBackend) ListTagsForResource

func (b *InMemoryBackend) ListTagsForResource(resourceARN string) ([]map[string]string, error)

ListTagsForResource returns all tags for the given resource ARN as a slice of key/value maps. Returns ErrResourceNotFound if resourceARN is not a known group or sampling rule.

func (*InMemoryBackend) PutEncryptionConfig

func (b *InMemoryBackend) PutEncryptionConfig(encType, keyID string) (*EncryptionConfig, error)

PutEncryptionConfig updates the X-Ray encryption configuration. encType must be one of "NONE" or "KMS". keyID is only used when encType is "KMS". When encType is KMS the keyID must match alias/..., ARN, or UUID format. The status is initially set to UPDATING; the next GET will advance it to ACTIVE.

func (*InMemoryBackend) PutResourcePolicy

func (b *InMemoryBackend) PutResourcePolicy(policyName, policyDocument, revisionID string) (*ResourcePolicy, error)

PutResourcePolicy creates or updates a resource policy with the given name and document. Returns ErrTooManyPolicies if the account already has maxResourcePolicies. Returns ErrPolicySizeLimitExceeded if policyDocument exceeds maxResourcePolicySizeBytes. Returns ErrInvalidPolicyRevisionID if revisionID doesn't match the stored one. Returns ErrMalformedPolicyDocument if policyDocument is not valid JSON.

func (*InMemoryBackend) PutTelemetryRecords

func (b *InMemoryBackend) PutTelemetryRecords(records []TelemetryRecord)

PutTelemetryRecords stores telemetry records in a ring buffer.

func (*InMemoryBackend) PutTraceSegments

func (b *InMemoryBackend) PutTraceSegments(segments []string) []string

PutTraceSegments stores raw segment JSON strings, parses them into typed Segment structs, and returns the list of unprocessed segment IDs (empty slice means all segments were accepted).

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all backend state, resetting to an empty store.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state from a JSON snapshot.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state to JSON.

func (*InMemoryBackend) StartTraceRetrieval

func (b *InMemoryBackend) StartTraceRetrieval(traceIDs []string) string

StartTraceRetrieval creates a new retrieval job for the given trace IDs and returns a token.

func (*InMemoryBackend) TagResource

func (b *InMemoryBackend) TagResource(resourceARN string, tags map[string]string) error

TagResource adds or updates tags on a resource identified by ARN. Tags are stored in a per-ARN map on the backend. Returns ErrResourceNotFound if resourceARN is not a known group or sampling rule. Returns ErrTooManyTags if applying tags would exceed maxTagsPerResource.

func (*InMemoryBackend) TaggedResources added in v1.3.1

func (b *InMemoryBackend) TaggedResources() []TaggedEntry

TaggedResources returns every X-Ray group or sampling rule ARN that currently has at least one tag applied via TagResource.

func (*InMemoryBackend) UntagResource

func (b *InMemoryBackend) UntagResource(resourceARN string, tagKeys []string) error

UntagResource removes the specified tag keys from a resource. Returns ErrResourceNotFound if resourceARN is not a known group or sampling rule.

func (*InMemoryBackend) UpdateGroup

func (b *InMemoryBackend) UpdateGroup(name, filterExpr string) (*Group, error)

UpdateGroup updates the filter expression for the group with the given name.

func (*InMemoryBackend) UpdateGroupByARN

func (b *InMemoryBackend) UpdateGroupByARN(
	name, arn string,
	filterExpr *string,
	insights *InsightsConfiguration,
) (*Group, error)

UpdateGroupByARN updates a group by ARN or name. filterExpr and insights are pointer-semantic: a nil pointer leaves the corresponding field unchanged, matching the real UpdateGroupInput shape where FilterExpression and InsightsConfiguration are both independently optional (unlike CreateGroup, omitting one on update must not reset the other to its zero value).

func (*InMemoryBackend) UpdateIndexingRule

func (b *InMemoryBackend) UpdateIndexingRule(name string, rule *ProbabilisticRuleValue) (*IndexingRule, error)

UpdateIndexingRule updates the named indexing rule's probabilistic sampling percentage (the actual point of UpdateIndexingRule per the real API: its request carries a required Rule.Probabilistic.DesiredSamplingPercentage). gopherstack applies the desired percentage immediately as the actual percentage too, since there is no gradual-rollout simulation to model here. Returns ErrIndexingRuleNotFound if no rule with that name exists.

func (*InMemoryBackend) UpdateSamplingRule

func (b *InMemoryBackend) UpdateSamplingRule(ruleName string, updates SamplingRule) (*SamplingRule, error)

UpdateSamplingRule updates the mutable fields of an existing sampling rule. It accepts a SamplingRule struct where non-zero values are applied (legacy API).

func (*InMemoryBackend) UpdateSamplingRuleWithPointers

func (b *InMemoryBackend) UpdateSamplingRuleWithPointers(
	ruleName, ruleARN string,
	updates SamplingRuleUpdate,
) (*SamplingRule, error)

UpdateSamplingRuleWithPointers applies pointer-semantic updates so zero values apply. The rule is identified by ruleName if non-empty, otherwise by ruleARN (matching the real SamplingRuleUpdate shape, which allows specifying either but not both).

func (*InMemoryBackend) UpdateTraceSegmentDestination

func (b *InMemoryBackend) UpdateTraceSegmentDestination(destination string) string

UpdateTraceSegmentDestination sets the trace segment destination and returns it.

type IndexingRule

type IndexingRule struct {
	ModifiedAt time.Time               `json:"modifiedAt"`
	Rule       *ProbabilisticRuleValue `json:"rule,omitempty"`
	Name       string                  `json:"name"`
}

IndexingRule represents an X-Ray CloudWatch Logs indexing rule.

type Insight

type Insight struct {
	StartTime                     time.Time                `json:"startTime"`
	EndTime                       time.Time                `json:"endTime,omitzero"`
	LastUpdateTime                time.Time                `json:"lastUpdateTime"`
	ClientRequestImpactStatistics *RequestImpactStatistics `json:"clientRequestImpactStatistics,omitempty"`
	InsightID                     string                   `json:"insightId"`
	GroupARN                      string                   `json:"groupARN"`
	GroupName                     string                   `json:"groupName"`
	State                         string                   `json:"state"`
	Summary                       string                   `json:"summary"`
	Categories                    []string                 `json:"categories,omitempty"`
}

Insight represents an X-Ray insight.

type InsightEvent

type InsightEvent struct {
	EventTime time.Time `json:"eventTime"`
	InsightID string    `json:"insightId"`
	Summary   string    `json:"summary"`
}

InsightEvent represents an event within an X-Ray insight.

type InsightsConfiguration

type InsightsConfiguration struct {
	InsightsEnabled      bool `json:"InsightsEnabled"`
	NotificationsEnabled bool `json:"NotificationsEnabled"`
}

InsightsConfiguration holds insight notification/notification settings for a group.

type Janitor

type Janitor struct {
	Backend  *InMemoryBackend
	Interval time.Duration
	TraceTTL time.Duration
	// TaskTimeout bounds each individual janitor task. When non-zero, each task
	// runs with a child context that expires after this duration, preventing a
	// stalled operation from blocking the janitor loop indefinitely.
	TaskTimeout time.Duration
}

Janitor is the X-Ray background worker that evicts old traces to prevent unbounded growth of in-memory state.

func NewJanitor

func NewJanitor(backend *InMemoryBackend, interval, traceTTL time.Duration) *Janitor

NewJanitor creates a new X-Ray Janitor for the given backend. Zero values for interval or traceTTL fall back to defaults.

func (*Janitor) Run

func (j *Janitor) Run(ctx context.Context)

Run runs the janitor loop until ctx is cancelled.

func (*Janitor) SweepOnce

func (j *Janitor) SweepOnce(ctx context.Context)

SweepOnce runs a single sweep pass. Exposed for testing.

type ProbabilisticRuleValue added in v1.2.0

type ProbabilisticRuleValue struct {
	DesiredSamplingPercentage float64 `json:"desiredSamplingPercentage"`
	ActualSamplingPercentage  float64 `json:"actualSamplingPercentage"`
}

ProbabilisticRuleValue holds the probabilistic sampling percentage configuration for an indexing rule.

type Provider

type Provider struct{}

Provider implements service.Provider for the X-Ray service.

func (*Provider) Init

Init initializes the X-Ray service backend and handler.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the logical name of the provider.

type RequestImpactStatistics added in v1.3.1

type RequestImpactStatistics struct {
	OkCount    int64 `json:"okCount"`
	FaultCount int64 `json:"faultCount"`
	TotalCount int64 `json:"totalCount"`
}

RequestImpactStatistics holds the ok/fault/total request counts for a service over an insight's detection window.

type ResourcePolicy

type ResourcePolicy struct {
	LastUpdatedTime  time.Time `json:"lastUpdatedTime"`
	PolicyName       string    `json:"policyName"`
	PolicyDocument   string    `json:"policyDocument"`
	PolicyRevisionID string    `json:"policyRevisionId"`
}

ResourcePolicy represents a resource-based policy attached to the X-Ray account.

type SamplingBoostStatisticsDocument added in v1.3.1

type SamplingBoostStatisticsDocument struct {
	RuleName            string
	ServiceName         string
	TotalCount          int32
	AnomalyCount        int32
	SampledAnomalyCount int32
}

SamplingBoostStatisticsDocument is a single boost-statistics document submitted in GetSamplingTargets for rules using SamplingRateBoost.

type SamplingRateBoost added in v1.2.0

type SamplingRateBoost struct {
	MaxRate               float64 `json:"maxRate"`
	CooldownWindowMinutes int32   `json:"cooldownWindowMinutes"`
}

SamplingRateBoost holds the configuration for temporary sampling-rate boosts.

type SamplingRule

type SamplingRule struct {
	CreatedAt         time.Time          `json:"createdAt"`
	ModifiedAt        time.Time          `json:"modifiedAt"`
	SamplingRateBoost *SamplingRateBoost `json:"samplingRateBoost,omitempty"`
	Attributes        map[string]string  `json:"attributes,omitempty"`
	RuleARN           string             `json:"ruleARN"`
	RuleName          string             `json:"ruleName"`
	ResourceARN       string             `json:"resourceARN"`
	ServiceName       string             `json:"serviceName"`
	ServiceType       string             `json:"serviceType"`
	Host              string             `json:"host"`
	HTTPMethod        string             `json:"httpMethod"`
	URLPath           string             `json:"urlPath"`
	FixedRate         float64            `json:"fixedRate"`
	Priority          int32              `json:"priority"`
	ReservoirSize     int32              `json:"reservoirSize"`
}

SamplingRule represents an X-Ray sampling rule that controls the rate of data collection.

type SamplingRuleUpdate

type SamplingRuleUpdate struct {
	ResourceARN       *string
	ServiceName       *string
	ServiceType       *string
	Host              *string
	HTTPMethod        *string
	URLPath           *string
	FixedRate         *float64
	Priority          *int32
	ReservoirSize     *int32
	SamplingRateBoost *SamplingRateBoost
	Attributes        map[string]string
}

SamplingRuleUpdate holds pointer-semantic updates for UpdateSamplingRule. A nil pointer means "no change"; a non-nil pointer (even to zero/empty) means "apply".

type SamplingStatisticSummary

type SamplingStatisticSummary struct {
	Timestamp    time.Time `json:"timestamp"`
	RuleName     string    `json:"ruleName"`
	RequestCount int32     `json:"requestCount"`
	SampledCount int32     `json:"sampledCount"`
	BorrowCount  int32     `json:"borrowCount"`
}

SamplingStatisticSummary holds aggregated request sampling data for a rule.

type SamplingStatisticsDocument

type SamplingStatisticsDocument struct {
	RuleName     string
	ClientID     string
	RequestCount int32
	SampledCount int32
	BorrowCount  int32
}

SamplingStatisticsDocument is a single document submitted in GetSamplingTargets.

type SamplingTargetResult

type SamplingTargetResult struct {
	ReservoirQuotaTTL time.Time
	RuleName          string
	FixedRate         float64
	ReservoirSize     int32
}

SamplingTargetResult holds the per-document results of GetSamplingTargets. It has no SamplingBoost field: AWS's boost-trigger algorithm is unpublished (see GetSamplingTargets), so gopherstack never computes one. The wire view (samplingTargetDocumentView.SamplingBoost) still declares the field for shape completeness -- it is simply always omitted.

type Segment

type Segment struct {
	AWS         map[string]any `json:"aws,omitempty"`
	Annotations map[string]any `json:"annotations,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	HTTP        *SegmentHTTP   `json:"http,omitempty"`
	Namespace   string         `json:"namespace,omitempty"`
	Document    string         `json:"-"`
	TraceID     string         `json:"trace_id"`
	ID          string         `json:"id"`
	ParentID    string         `json:"parent_id,omitempty"`
	Name        string         `json:"name"`
	Origin      string         `json:"origin,omitempty"`
	Subsegments []Segment      `json:"subsegments,omitempty"`
	StartTime   float64        `json:"start_time"`
	EndTime     float64        `json:"end_time,omitempty"`
	Error       bool           `json:"error"`
	Fault       bool           `json:"fault"`
	Throttle    bool           `json:"throttle"`
}

Segment is a parsed X-Ray segment document.

type SegmentHTTP

type SegmentHTTP struct {
	Request  *SegmentHTTPRequest  `json:"request,omitempty"`
	Response *SegmentHTTPResponse `json:"response,omitempty"`
}

SegmentHTTP holds HTTP request/response data from a segment.

type SegmentHTTPRequest

type SegmentHTTPRequest struct {
	URL       string `json:"url,omitempty"`
	Method    string `json:"method,omitempty"`
	UserAgent string `json:"user_agent,omitempty"`
	ClientIP  string `json:"client_ip,omitempty"`
}

SegmentHTTPRequest holds HTTP request fields from a segment.

type SegmentHTTPResponse

type SegmentHTTPResponse struct {
	Status        int `json:"status,omitempty"`
	ContentLength int `json:"content_length,omitempty"`
}

SegmentHTTPResponse holds HTTP response fields from a segment.

type Settings

type Settings struct {
	JanitorInterval time.Duration `json:"janitor_interval" env:"XRAY_JANITOR_INTERVAL" default:"1m"  help:"Janitor tick interval."`                         //nolint:lll // Kong struct tag makes this line long
	TraceTTL        time.Duration `json:"trace_ttl"        env:"XRAY_TRACE_TTL"        default:"30m" help:"TTL for stored traces before they are evicted."` //nolint:lll // Kong struct tag makes this line long
}

Settings holds service-level configuration for the X-Ray backend. Fields are picked up by the Kong CLI parser when this struct is embedded in the root CLI command.

type StorageBackend

type StorageBackend interface {
	CreateGroup(name, filterExpr string) (*Group, error)
	CreateGroupWithInsights(name, filterExpr string, ic InsightsConfiguration) (*Group, error)
	GetGroup(name string) (*Group, error)
	GetGroupByARN(arn string) (*Group, error)
	GetGroups() []Group
	UpdateGroup(name, filterExpr string) (*Group, error)
	UpdateGroupByARN(name, arn string, filterExpr *string, insights *InsightsConfiguration) (*Group, error)
	DeleteGroup(name string) error
	DeleteGroupByARN(name, arn string) error
	CreateSamplingRule(rule SamplingRule) (*SamplingRule, error)
	GetSamplingRules() []SamplingRule
	UpdateSamplingRule(ruleName string, updates SamplingRule) (*SamplingRule, error)
	UpdateSamplingRuleWithPointers(ruleName, ruleARN string, updates SamplingRuleUpdate) (*SamplingRule, error)
	DeleteSamplingRule(ruleName, ruleARN string) (*SamplingRule, error)
	PutTraceSegments(segments []string) []string
	GetTraceSummaries() []Trace
	GetTrace(traceID string) *Trace
	GetParsedSegments(traceID string) []*Segment
	GetAllParsedSegments() map[string][]*Segment
	Reset()
	GetEncryptionConfig() *EncryptionConfig
	PutEncryptionConfig(encType, keyID string) (*EncryptionConfig, error)
	Snapshot(ctx context.Context) []byte
	Restore(ctx context.Context, data []byte) error
	// Insight operations
	GetInsight(insightID string) (*Insight, error)
	GetInsightEvents(insightID string) ([]*InsightEvent, error)
	GetInsightSummaries(states []string, groupName string, startTime, endTime time.Time) ([]Insight, error)
	// Resource policy operations
	CancelTraceRetrieval(retrievalToken string) error
	DeleteResourcePolicy(policyName, policyRevisionID string) error
	ListResourcePolicies() []ResourcePolicy
	PutResourcePolicy(policyName, policyDocument, revisionID string) (*ResourcePolicy, error)
	// Indexing rules
	GetIndexingRules() []*IndexingRule
	// Retrieval
	GetRetrievedTracesGraph(retrievalToken string) (string, []*Trace, error)
	// Sampling statistics
	GetSamplingStatisticSummaries() []SamplingStatisticSummary
	GetSamplingTargets(
		docs []SamplingStatisticsDocument,
		boostDocs []SamplingBoostStatisticsDocument,
	) ([]SamplingTargetResult, []UnprocessedStatisticsResult, []UnprocessedStatisticsResult)
	LastRuleModification() time.Time
	// Service graph operations
	GetServiceGraph(startTime, endTime time.Time) []map[string]any
	GetTraceGraph(traceIDs []string) []map[string]any
	GetTimeSeriesServiceStatistics(startTime, endTime time.Time, period int) []map[string]any
	// Destination
	GetTraceSegmentDestination() string
	UpdateTraceSegmentDestination(destination string) string
	// Retrieval list
	ListRetrievedTraces(retrievalToken string) (string, []*Trace, error)
	// Tags
	ListTagsForResource(resourceARN string) ([]map[string]string, error)
	StartTraceRetrieval(traceIDs []string) string
	TagResource(resourceARN string, tags map[string]string) error
	UntagResource(resourceARN string, tagKeys []string) error
	// Indexing rule update
	UpdateIndexingRule(name string, rule *ProbabilisticRuleValue) (*IndexingRule, error)
	// Telemetry
	PutTelemetryRecords(records []TelemetryRecord)
}

StorageBackend defines the interface for X-Ray backend implementations. All mutating methods must be safe for concurrent use.

type TaggedEntry added in v1.3.1

type TaggedEntry struct {
	Tags map[string]string
	ARN  string
}

TaggedEntry pairs a resource ARN with its tags.

type TelemetryRecord

type TelemetryRecord struct {
	Timestamp              time.Time `json:"timestamp"`
	SegmentsReceivedCount  int32     `json:"segmentsReceivedCount"`
	SegmentsSentCount      int32     `json:"segmentsSentCount"`
	SegmentsSpilloverCount int32     `json:"segmentsSpilloverCount"`
	SegmentsRejectedCount  int32     `json:"segmentsRejectedCount"`
}

TelemetryRecord holds a single telemetry data point.

type Trace

type Trace struct {
	StartTime time.Time `json:"startTime"`
	TraceID   string    `json:"traceID"`
	Segments  []string  `json:"segments"`
}

Trace represents a collected X-Ray trace with its constituent segments.

type TraceRetrieval

type TraceRetrieval struct {
	StartTime      time.Time `json:"startTime"`
	RetrievalToken string    `json:"retrievalToken"`
	Status         string    `json:"status"`
}

TraceRetrieval represents an ongoing trace retrieval operation.

type TraceSummaryData

type TraceSummaryData struct {
	Annotations  map[string][]AnnotationOccurrence
	HTTP         *TraceSummaryHTTP
	EntryPoint   *TraceSummaryServiceID
	TraceID      string
	Users        []string
	ServiceIDs   []TraceSummaryServiceID
	Duration     float64
	ResponseTime float64
	Revision     int
	HasFault     bool
	HasError     bool
	HasThrottle  bool
	IsPartial    bool
}

TraceSummaryData holds derived data for GetTraceSummaries response.

func BuildTraceSummary

func BuildTraceSummary(traceID string, segs []*Segment) TraceSummaryData

BuildTraceSummary derives TraceSummaryData from parsed segments.

type TraceSummaryHTTP

type TraceSummaryHTTP struct {
	HTTPURL    string
	HTTPMethod string
	ClientIP   string
	UserAgent  string
	HTTPStatus int
}

TraceSummaryHTTP holds HTTP fields for a trace summary.

type TraceSummaryServiceID

type TraceSummaryServiceID struct {
	Name string
	Type string
}

TraceSummaryServiceID is a service identifier in a trace summary.

type UnprocessedStatisticsResult

type UnprocessedStatisticsResult struct {
	RuleName  string
	ErrorCode string
	Message   string
}

UnprocessedStatisticsResult holds results for unknown rule names.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL