aws_xray_sdk 0.6.0
aws_xray_sdk: ^0.6.0 copied to clipboard
AWS X-Ray distributed tracing for Dart. Auto-traces dart:io HTTP and Smithy SDK clients, propagates X-Amzn-Trace-Id, and sends segments via UDP. First-class Lambda support.
Changelog #
0.6.0 #
Added #
-
onDiagnostichook andXRayDiagnostic.XRayTracer(onDiagnostic:)receives anXRayDiagnosticfor contained problems that used to leave no signal. It carriescode,message, and, when there is a failure,errorandstackTrace.codeis an open string rather than an enum, so new codes can appear in any release; only the SDK creates diagnostics (no public constructor). Codes in this release:node_trimmed: a single oversized segment or subsegment was trimmed to fit the datagram (see "Oversized single nodes are trimmed" under Fixed). Reported only through senders that encode in their send call, such asUdpSender.adapter_failed: code you registered for a Smithy client threw and was contained: therequestAdapter, itswithTraceHeaderinjection, the resource extractor, theresponseAdapter, or theerrorStatushook. The call result, or the original error, is unchanged. An error thrown by the AWS call itself is yours and is never reported.daemon_address_invalid: see Changed below.
The hook is synchronous and best-effort: a callback that throws is ignored, an
asynccallback's late failure is swallowed, and while any tracer's hook is running, diagnostics raised on the same call stack are ignored. Send failures are not diagnostics; they stay ononSendError. Known limits:XRayBaseClientenrichment failures are not reported through the hook, and the reportederroris the raw thrown object, not redacted like the emitted segment, so treat it as sensitive if your hook logs it. -
XRay.configureacceptsonSendError,onSampledDropandonDiagnostic, passed to the tracer it builds. LikeserviceNameandsampling, they are ignored when you supplytracer:.
Changed #
- Behaviour change — a malformed
AWS_XRAY_DAEMON_ADDRESSis now reported.XRay.configureused to fall back to127.0.0.1:2000with no signal. It now reports once per install: as adaemon_address_invaliddiagnostic when you passonDiagnostic, otherwise as one line onstderr(the value is sanitized: URLs redacted, control and format characters replaced, shortened to about 100 characters; scheme-less userinfo such asuser:pw@host:badportis not masked). A TCP-only value such astcp:127.0.0.1:2000counts as malformed, so Lambda users with such a value will see the line after upgrading. A secondconfigureis a no-op;XRay.reset()thenconfigurereports again. Unset or empty values never report, and nothing is reported when you supplytracer:. The fallback itself is unchanged. This is the only such line that fires at configure time. - Behaviour change —
aws.queue_urlandaws.resource_namesare redacted likehttp.request.url. The emitted document drops userinfo, query strings, and fragments fromaws.queue_urland from everyaws.resource_namesentry (including URLs embedded in a longer entry), so an SQS queue URL carrying credentials or a signature no longer reaches X-Ray. Table and bucket names, ARNs, and plain queue URLs are unchanged. The in-memoryAwsDatakeeps raw values. Accepted limit: a hand-builtAwsDatawhoseresource_namesholds scheme-less credentials (user:pw@host/path) or a protocol-relative//user:pw@host/pathform that differs fromqueue_urlis not redacted; the built-in producers never create one.
Fixed #
- Oversized single nodes are trimmed instead of sent whole. A segment or
subsegment too big on its own (for example a huge
metadatavalue) could not be split, so it was sent as-is and the OS refused the datagram. The encoder now trims it to fit the 65507-byte datagram: the largestmetadatavalues become the string[truncated: N bytes](only as many as needed, and only when the marker is shorter) andmetadata.xray.truncatedis set totrue; if that is not enough, the node is reduced to its ids, timing, flags, andname(capped at 200 UTF-16 code units);http,aws,causeanduserdata is dropped in that case. Nodes that already fit are byte-for-byte unchanged. Behaviour change: an emitted document can now differ from the recorded one, and a string can appear where ametadatamap value used to be. The fix guarantees the packet fits the datagram, not that the X-Ray service accepts it. The service's behaviour on a trimmed document has not been verified end to end (a string now stands where a metadata map value was), and the exact service-side size limit (64000 vs 65536 bytes) is unconfirmed, so a trimmed document close to the limit may still be rejected by the service. Ids passed directly torunLambdaare not capped, so a huge id can still exceed the limit.
0.5.0 #
Added #
errorStatushook for Smithy clients.XRay.registerClientaccepts an optionalerrorStatus: int? Function(Object error). When it returns a status of 400 or above for a thrown error, the subsegment is classified like a response (4xx error, 429 throttle, 5xx fault) and recordshttp.response.statusinstead of always being a fault. Without the hook, behaviour is unchanged.
Changed #
The entries below change observable behaviour; review them before upgrading.
- Behaviour change — recorded URLs no longer include query strings,
userinfo, or fragments.
http.request.urlis nowscheme://host[:port]/pathon every instrumentation path (XRayHttpClient,XRayBaseClient,XRay.fromClient,handleTraced, and user-builtHttpRequestData), so presigned-URL signatures, OAuth codes, anduser:pw@credentials stay out of X-Ray. There is no setting to keep the query string. The in-memoryHttpRequestData.urlkeeps the raw value; only the emitted document is redacted. If a?or#comes before an@, that@may be part of a query: only a validhost[:port]before the?or#is kept. - Behaviour change — URLs inside exception messages are redacted too.
cause.exceptions[].messagedrops userinfo, query strings, and fragments from every URL it contains, so errors such asClientException: …, uri=https://…?X-Amz-Signature=…no longer leak whathttp.request.urlhides. This applies to caught errors, AWS error-body messages, and user-builtXRayExceptions (in the emitted JSON; the in-memorymessagekeeps its raw value). Redaction runs before the 1024-character cap (see "Exception messages are capped" below). Anything from a:followed by/or\up to the next ASCII space or control character is treated as a URL. Not caught: URLs without a scheme, bare query strings, encoded URLs (https:%2F%2Fu:p@h/p, HTML or\uescapes), userinfo containing whitespace or control characters, userinfo containing a raw/,?or#when what precedes it looks like a host or host:port (https://admin:2024/s3cret@h/preads as host, port and path), and secrets in the URL path. - Behaviour change —
Sender.sendPacketsnow throwsUnsupportedErrorby default. It was a silent no-op, so a customSenderthat only overrodesendlost everyrunLambdatrace without notice. The error names the sender class; the tracer reports it throughonSendError(when set) and never throws into the app. Direct callers ofsendPacketson such a sender now receive the error. Custom senders used withrunLambdamust overridesendPackets.UdpSender,InMemorySender, andNoopSenderare unchanged.
Fixed #
XRay.patchHttpis idempotent. Calling it twice nested two X-Ray layers, so everydart:iorequest was traced twice and oneunpatchHttp()removed only one layer. A repeat call now replaces the X-Ray layer (using the new tracer) instead of wrapping it, and a singleunpatchHttp()restores the overrides that were in place before the first patch.- Exception messages are capped and never throw.
XRayException.fromtruncates messages over 1024 UTF-16 code units and appends…[truncated](without splitting a surrogate pair). If an error'stoString()throws, the message falls back to its runtime type name; previously that dropped the whole segment when the error escapedtracer.run. onSendErrornow fires for transport failures. TheUdpSenderthe tracer builds itself (nosenderargument) swallowed resolve, bind, and datagram-send errors, soonSendErroronly ever saw encode errors. It now reports those local failures too, at most once per segment send, and never throws into the app.runLambdaalso reports a document that fails to encode (such as a cyclic metadata map) instead of dropping it silently. A user-suppliedUdpSenderkeeps reporting through its ownonError.- One refused datagram no longer silences tracing for good. When the OS
refuses a datagram (for example one over the datagram limit, or over 9216
bytes on macOS's default UDP limit), Dart's socket returns 0 instead of
throwing, and every later send on that socket did the same.
UdpSenderignored this and kept the socket, so all later traces were lost with no error. A short send is now reported throughonError(and the tracer'sonSendError), and the socket is replaced so the next send gets through. handleTracedflags failed requests. The server segment recorded the response status but no flags, so a 500 looked healthy in X-Ray. A 4xx status now setserror, 429 setsthrottleanderror, and 5xx setsfault, matching client subsegments. The same applies to any segment closed byrun()that carries anhttp.response.status. New:Segment.applyStatus(int), the segment counterpart ofSubsegment.applyStatus.- Large Lambda traces are no longer dropped.
runLambdasent the whole handler subsegment tree as a single UDP datagram, so a large invocation exceeded the datagram limit and the entire trace was lost. It now uses the same recursive split as standalone segments: the handler document is emitted without its children, and each child becomes its own subsegment document linked byparent_id. Small documents are unchanged, byte for byte. - Split threshold lowered to the real UDP limit. The encoder split
documents above 65536 bytes, but an IPv4 UDP datagram carries at most 65507,
so documents of 65508 to 65536 bytes were sent as one datagram and failed.
The cap is now 65507 bytes for both
encode()and Lambda documents. AWS_XRAY_DAEMON_ADDRESSparsing is stricter and broader.configurenow understands[v6]:port, bare IPv6 literals (::1), and the dualtcp:h:p udp:h:pform in either order (theudp:address is used). Malformed values (bad or out-of-range port, empty host,tcp:-only) fall back to127.0.0.1:2000instead of producing a half-parsed address.- Malformed incoming trace headers no longer leak into traces.
TraceId.tryParse(and soTraceId.parseRootString) now requires hex in the timestamp and random parts (non-hex ids were accepted and later failed an assert in debug builds).handleTraced,tracer.trace()andLambdaTraceCapture.context()dropParentwhen theRootis invalid (a fresh trace is started) or the parent is not 16 hex characters. - One unencodable metadata value no longer drops the whole segment. A
DateTime, custom object, orNaN/Infinityin metadata madejsonEncodethrow, so the segment was lost. Such values now fall back totoJson(), thentoString(), then the placeholder"<unencodable:Type>". Documents with only JSON-native values encode byte for byte as before. - A throwing Smithy adapter no longer breaks the AWS call. In
XRay.fromClientclients, arequestAdapterthat throws now sends the call untraced. AwithTraceHeaderthat throws sends the original request, still traced. AresponseAdapterthat throws after a successful call returns the response and closes the subsegment without response data. Only the transport's own error reaches the caller, as the same object with its original stack trace. XRayBaseClientno longer faults AWS calls with odd request bodies. A resource field of the wrong JSON type (for example"TableName": 123) threw aTypeErrorthat replaced a 200 response, or the transport's own error. Such fields are now left out of theawsblock. Tracing work after the response arrives is guarded, so a successful response always reaches the caller, and a transport error is rethrown unchanged.
0.4.1 #
Docs and release-tooling release — no library code changes.
- One-button releases: the "Release" workflow now auto-increments the version (patch/minor/major choice, patch by default) and generates a CHANGELOG section from commits when none is written, then tags and triggers the publish pipeline. A manual pubspec bump / hand-written section still wins. Releases are never created on merges to main.
- Docs modernized to the
trace()API: README and examples now lead withtracer.trace()/XRay.trace();run()is documented for its two remaining use cases (pre-built segments,runLambdaInvocationinternals). Architecture and tracing-behavior docs updated to match, including the LambdaInvoke→aws.function_namecapture and full-URL recording.
0.4.0 #
One-call tracing ergonomics: configure once, then trace any unit of work in a single line — plus distributed-trace continuation and Lambda handler polish. All changes are backward-compatible.
Added #
XRayTracer.trace(name, fn)— the one-call entry point: creates the segment, runsfninside the trace zone, closes, and sends. AcceptsFutureOrso any function drops in,user:for the segment's user field, andhttpMethod:/urlPath:for the sampling decision.- Distributed-trace continuation.
trace(..., traceHeader:)takes the incomingX-Amzn-Trace-Idheader and links this service into the caller's trace (Root=becomes the trace id,Parent=the parent id); the local sampling strategy stays authoritative, matchinghandleTraced. XRay.trace(...)andXRay.capture(...)— static facades over the process-wide tracer, so afterXRay.configure()the full trace lifecycle (root span, nested spans, annotations, metadata) needs no tracer threading. Both are safe no-ops beforeconfigure()runs.
Changed #
XRay.runLambdaInvocationnow accepts aFutureOr-returningfn(handler actions drop in without() async =>coercion) and an optionaltracer:parameter to pin an instance instead of the global — consistent with the rest of the facade.- Internal layout reorganized: zone-context machinery moved to
lib/src/context/, theX-Amzn-Trace-Idformatter tolib/src/models/, and AWS partition-suffix knowledge consolidated inlib/src/aws/region.dart(isAwsHost). No public-API impact. - Examples modernized to the
trace()/capture()API, with a rewrittenadvanced_tracing.dartdemonstratingcaptureAsyncnesting and a stub-free look at what each example emits.
Fixed #
handleTracednow records the full request URL (requestedUri) in the segment'shttp.request.urlinstead of only the path + query, per the X-Ray segment schema.- The path-based custom-sampler demo in
example/sampling_strategies.dartactually exercises the sampler now (it never forwardedurlPathinto the sampling decision before) and prints each operation's sampled result.
0.3.1 #
Added #
package:httpAWS tracing now recognizes the Lambda data-planeInvokecall.XRayBaseClientreads the operation (Invoke) and target function from the REST path (/2015-03-31/functions/{name}/invocations), recording it asaws.function_nameand adding the function toaws.resource_namesso the invoked Lambda appears as its own node in the X-Ray service map.AwsData.functionName, serialized asfunction_namein theawsblock per the X-Ray segment schema.
0.3.0 #
Stable release of the 0.3.0 line. Functionally identical to 0.3.0-beta.2 —
no API or behavior changes since the beta — with documentation and example
polish. For the full set of changes since 0.2.1, see the 0.3.0-beta.1 and
0.3.0-beta.2 sections below. Headline additions across the line:
- Zero-config setup.
XRay.configure()builds a tracer from the AWS environment, installs a process-wide default (XRay.tracer), and patches HTTP in one idempotent call;XRay.reset()returns to the unconfigured no-op state. package:httptracing.XRay.aws()/XRay.httpClientFor()wrap anhttp.Clientforaws_client/aws_*_apiSDKs, resolving the global tracer per request.- Lambda ergonomics.
LambdaTraceCapturecaptures theLambda-Runtime-Trace-Idheader per invocation andXRay.runLambdaInvocationcollapses the parent-decision branch into one call. InMemorySenderfor asserting on emitted segments and Lambda packets in tests, plusXRayTracer.onSampledDrop/onSendErrordiagnostics.
Changed #
- Examples and docs updated: the AWS SDK client example now prints the
subsegments it produces (via
InMemorySender), and the README/AGENT docs were corrected to match the shipped API surface.
0.3.0-beta.2 #
Second beta of the 0.3.0 line. This release tightens the beta.1 APIs and fixes trace-fidelity edge cases found during integration testing.
Added #
InMemorySender, exported from the package barrel, for tests that need to assert on emitted segments or Lambda packets without UDP or tracer mocks.XRay.annotate(Map<String, Object>)andXRay.metadata(key, value)facade helpers for adding data through the process-wide tracer.TraceId.parseRootString(header)for log-enrichment callers that only need the validated root trace id as a string.XRayTracer.onSampledDropandXRayTracer.onSendErrorhooks to distinguish intentional sampled-out drops from send failures without faulting traced code.
Changed #
XRay.aws()andXRayBaseClient(inner)now resolve the global tracer per request when no explicit tracer is passed. Clients created beforeXRay.configure()now trace after configuration.- The unconfigured no-op tracer reports
isSampled == falseoutside a trace zone, so it does not advertiseSampled=1for traces it will never emit. contextMissingPolicyis mutable onXRayTracerfor runtime diagnostics and tests.ReservoirSamplernow uses a monotonicStopwatchclock instead of wall time, avoiding sampling-window resets from clock adjustments.- Oversized segment encoding recursively splits large subsegment trees into independent subsegment documents where possible.
- Child subsegments are serialized in start-time order for clearer timelines when concurrent work closes out of order.
Fixed #
- AWS endpoint detection now covers standard, China, ISO, and ISO-B partitions,
matching region extraction and preserving AWS metadata/error parsing outside
.amazonaws.com. - AWS query-protocol XML error parsing now handles namespace prefixes, tag attributes, CDATA, XML entities, malformed UTF-8, and out-of-range numeric entities without crashing the request path.
LambdaTraceCapturestores captured runtime trace headers in a zone-local slot duringrun(), preventing interleaved invocations from reading each other's header.- Unsampled
runLambdainvocations now skip subsegment serialization and notifyonSampledDropbefore any send/encoding work. - Annotation key sanitization now emits a warn-once diagnostic when keys are changed, making lossy collisions visible.
0.3.0-beta.1 #
First beta of the 0.3.0 line. Themes: zero-config setup ergonomics, segment-level HTTP recording for the server middleware, and a packaged Lambda trace-header capture. Pre-release — published for integration testing.
Added #
- Zero-config setup.
XRay.configure({fromEnv, serviceName, sampling, tracer, patchDartIoHttp})builds a tracer from the standard AWS environment (AWS_XRAY_DAEMON_ADDRESS, IPv6-literal safe;AWS_LAMBDA_FUNCTION_NAME), installs it as the process-wide default, and patches HTTP — in one idempotent call.XRay.reset()returns to the unconfigured state. - Global default tracer.
XRay.tracergetter/setter andXRay.isConfigured. Until configured, the default is a no-op that discards everything, so instrumentation runs unconditionally without null checks. XRay.aws({inner})and an optional-tracerXRay.httpClientForreturn a pre-wrappedpackage:httpclient (using the global tracer) foraws_client/aws_*_apiconstructors.XRayBaseClient(inner)now accepts an optional tracer, defaulting to the global default tracer.XRay.runLambdaInvocation(capture, name, fn)runs one Lambda invocation, parenting under theAWS::Lambda::Functionfacade when a trace header was captured or starting a fresh segment otherwise.LambdaTraceCapturepackages theLambda-Runtime-Trace-Idcapture (http.runWithClient-based) and exposes a parsedLambdaTraceContext(traceId,parentId,sampled) — no runtime fork needed.XRayTracer.annotateAll(Map)adds many annotations in one call.XRayTracer.currentTraceIdconvenience getter for the active trace id.- Segment HTTP data.
Segment.http(withSegment.withHttp);handleTracednow records the request (method, url, traced) and response (status, content_length) on the segment for the X-Ray service map, and forwards the request method/path into the sampling decision.Segment.httpwas removed in 0.2.0 as structurally unusable; it is reintroduced now that the middleware populates it.
Changed #
handleTracedreads the sampling decision inside the run zone, so an unsampled trace is correctly markedSampled=0on the outgoing header (previously could fail open toSampled=1).- A handler that throws before setting a status no longer records a misleading
200; the response block is omitted so the faulted segment stands alone.
Documentation #
- README: zero-config setup, the
aws_client/aws_*_apirecipe, and theLambdaTraceCapture-based Lambda example (replacing a hand-rolled shim). doc/architecture.md: updated for the new facade/tracer API surface.
0.2.1 #
Documentation #
- Consolidated the two overlapping HTTP sections in the README into one
HTTP tracingsection (dart:iopatch,package:httpclient, response-body lifecycle), added a contents nav, and removed a duplicate daemon-setup section. - Corrected the
AOT-safefeature claim and dropped the misleadingFlutter safelabel — the package usesdart:ioand is not Flutter-web compatible (matchingdoc/tracing-behavior.md).
0.2.0 #
First release since 0.1.0. Contains breaking changes (allowed pre-1.0).
Major themes: nested/live tracing, package:http and server-side support,
automatic double-trace suppression, a hardened non-faulting transport, annotation
validation, and a dead-code cleanup.
Breaking changes #
- Removed uninstrumented / dead API. Each can be restored from git history
once the matching instrumentation exists:
SqlDataandSubsegment.withSql(no SQL instrumentation existed).HttpRequestData.userAgent,clientIp, andxForwardedFor(never populated).Cause.workingDirectory(never populated).Segment.service,Segment.http, andSegment.aws(structurally always null —Segmentexposed no way to set them).- The unused helpers
namespaceForClientandnamespaceFor<T>.
HttpApiSenderwas removed — SigV4 signing is not yet implemented; useUdpSender(the default) for all deployments.- The stale
awsServiceNamespacesmap was removed — Smithy client registration now defaults directly to the valid X-Ray namespaceaws. - Registry internals are no longer exported from the package barrel. Use
XRay.registerClient/XRay.fromClient; direct access toclientRegistry,descriptorFor, andClientDescriptorwas an implementation detail. - Annotation values are now sanitized.
annotatekeeps the same signature but no longer stores arbitrary keys/values verbatim (see Annotation validation below) — a caller relying on invalid keys/values reaching X-Ray unchanged will see different output. SmithyResponseAdapternow returns AWS response metadata. Adapter records must include nullablerequestId,region, anderrorCodefields in addition tostatusCodeandcontentLength. This letsXRay.fromClientpopulateaws.request_id,aws.region, and AWS throttling flags.
New features #
Nested & live tracing
XRayTracer.captureAsync(name, fn)runs a block as a nested subsegment. Manual subsegments and auto-instrumented HTTP/AWS calls opened inside it become its children, so traces reflect the real call tree (previously all subsegments were flat siblings). Each scope is bound to a forkedZone, so concurrent captures stay independent.XRayTracer.annotate(key, value)/addMetadata(key, value)mutate the entity currently being traced (the activecaptureAsyncsubsegment, or the segment itself). Previously annotations could only be set atSegment.begintime.TraceContext— the live handle passed to acaptureAsyncblock (annotate/addMetadata/setError/setFault).- An uncaught error from
run/runLambda/captureAsyncnow marks the enclosing entity as faulted with a cause.
package:http and server-side tracing
XRayBaseClientwraps apackage:httpBaseClient, tracing each request with the same subsegment + AWS metadata extraction as thedart:iopath.- HTTP instrumentation now sets
http.request.traced = truewhen the SDK injectsX-Amzn-Trace-Id, allowing downstream service-to-service linkage in X-Ray. handleTraced(request, tracer, handler)—dart:ioHttpServermiddleware that continues an incomingX-Amzn-Trace-Id, runs the handler in a trace zone, and injects the trace header into the response for downstream propagation.XRay.untracedHttpClient()builds anHttpClientthat is never wrapped bypatchHttp, for calls that should emit no subsegment.
Automatic double-trace suppression
XRayBaseClientandXRay.fromClientrun their inner send insiderunWithoutDartIoTracing(a zone flag);XRayHttpClientstands down when it is set. A request passing through both a wrapper and apatchHttp-patcheddart:ioclient is now traced exactly once.- Smithy client namespaces are normalized to X-Ray schema values (
awsorremote) so custom orAWS::...registration values cannot produce invalid subsegment namespaces.
AWS trace fidelity
- Smithy client wrappers record
aws.request_idwhen the response adapter supplies it and recordaws.regionfrom the adapter or request URL. - AWS throttles are detected from known AWS error codes such as
ProvisionedThroughputExceededException,ThrottlingException,RequestLimitExceeded,TooManyRequestsException, andSlowDown, not only from HTTP429. - Error-status responses that do not throw now synthesize a remote HTTP
causeso 4xx/5xx subsegments have diagnostic detail.
Transport & sampling
UdpSendergained an optionalonError(Object)callback (silent by default) and a re-openableclose(); it resolves + binds once (memoized), uses an IP-literal fast path, and contains all resolution/bind/send errors.XRayTracergaineddaemonHost/daemonPortconstructor parameters and acontextMissingPolicy(ContextMissingPolicy.ignore/logError/runtimeError) controlling what happens when trace data is recorded with no active trace zone.ReservoirSampleraccepts an injectablenowclock (DateTime Function()) for deterministic tests.
Annotation validation (X-Ray best practices)
- Annotation keys and values are validated at every entry point
(
XRayTracer.annotate, theTraceContexthandle,Segment.annotate,Subsegment.annotate) by sanitizing, never throwing: invalid key characters (outside[A-Za-z0-9_]) become_, and a non-scalar value (notString/bool/int/double) is coerced to itstoString(). A malformed annotation never drops the trace or faults the traced operation. Metadata remains unvalidated (any JSON-serializable value) by design.
Fixes #
- Non-faulting transport guarantee. A
Sender(or scope-serialization) failure during finalization can no longer fault or mask the traced operation —run/runLambda/closeSegment/close()contain transport errors for anySender, not justUdpSender. Fixes a throw in the finalizationfinallysupersedingfn's return value or original exception. UdpSendercould fault the traced operation. Removed a per-send DNSlookup+bind, a socket-bind race under concurrency, and unguardedlookup/binderrors escaping into the awaitedrun().XRayHttpClientdouble-recorded a subsegment when a response body stream errored then completed (consumed withcancelOnError: false). The fault path and the done path are now mutually exclusive.- Undrained HTTP responses no longer drop spans. If an instrumented
dart:ioorpackage:httpresponse body is never consumed, trace finalization emits the subsegment once withmetadata.xray.incomplete = trueand the request/response data known so far. - Manual subsegment close is idempotent. Re-closing a subsegment, including a late close after an incomplete-response sweep, records the first outcome once.
handleTracedreported the wrongSampled=flag. The response header's sampling flag was read after the trace zone closed (fail-opentrue), so it always emittedSampled=1; it now reports the real decision.Segment.withFault(err)/Segment.withError(err)record exceptions directly on segments (previously onlySubsegmentsupported this).Segment.close()is idempotent — calling it on an already-closed segment preserves the original timing.XRayHttpClientpreserves the request scheme for host/port overloads (get/post/openusehttp, not an unconditionalhttps) and closes the traced subsegment ondetachSocket()raw-socket upgrades.- Removed debug
stderr.writelnlogging fromrunLambdaand per-packetdart:developerlogging fromUdpSender.
Internal & architecture #
- Runtime trace state is a mutable
TraceScopeentity tree (internal), serialized to the immutableSegment/Subsegmentdocuments at scope close;Subsegment.open(...)materializes an accumulated scope. runLambdaemits its handler span via the subsegment model (consistentnowSeconds()timing, nested children, fault capture) instead of a hand-built document.- Extracted
_runZonedintracer.dart(shared byrun/runLambda); reusedencodeSubsegmentDocin the encoder's oversize-split path; removed the unimplemented HTTP API sender stub; de-duplicated HTTP metadata, AWS region, throttle-code, and trace-header helpers.
Documentation & tests #
- Documented X-Ray annotation/metadata constraints, the
ContextMissingPolicyoptions, local sampler semantics + no-centralized-fallback behavior, the double-trace suppression model, and the Lambda subsegment contract (README +doc/architecture.md). - Documented the HTTP tracing lifecycle, including incomplete spans for
undrained responses and the single-use request expectation for
XRayBaseClient. - Added a
Segment/SubsegmentJSON golden test and broad coverage for the HTTP clients,runLambda, transport containment,UdpSenderrobustness, annotation validation,handleTraced, and the resource extractors.
0.1.0 #
Initial release.
Core tracing #
XRayTracerwith Zone-based context propagation (run,runLambda)- Immutable
SegmentandSubsegmentvalue objects with annotation and metadata support TraceIdgeneration and parsing (Root/Parent/Sampledheader fields)FixedRateSamplerandReservoirSampler
Transport #
UdpSender— fire-and-forget UDP to the X-Ray daemon (IPv4 / IPv6, 64 KB split)encodeSubsegmentDoc— encode an independent subsegment document for LambdaNoopSenderfor tests and local development
HTTP instrumentation #
XRayHttpClientwrapsdart:ioHttpClient; auto-traces every requestXRay.patchHttp/XRay.unpatchHttpfor globaldart:iopatching- Automatic
namespace='aws'for*.amazonaws.comhosts
AWS SDK wrappers #
XRay.registerClient<T>/XRay.fromClient<T>for Smithy-generated clientsResourceExtractorbuilt-ins for DynamoDB, S3, KMS, SQS, and SNS
Lambda support #
XRayTracer.runLambdaemits a subsegment document parented to the auto-createdAWS::Lambda::Functionsegment instead of a competing top-level segmentAWS_XRAY_DAEMON_ADDRESSenv-var parsing for link-local daemon address