From 610e2088a4e971231fefd7739fed2ab14359a3ca Mon Sep 17 00:00:00 2001 From: Sagnik Ghosh Date: Sun, 15 Nov 2026 10:40:05 +0530 Subject: [PATCH] Carrier helpers: pass operation context into queue jobs, headers and SQS messages runtime-core gains CARRIER_KEY ("autter"), injectCarrier(target, carrier, format?) and extractCarrier(source): thin wrappers over parseCarrier for a job payload, HTTP headers (case-insensitive name) and SQS MessageAttributes. injectCarrier returns a copy and never mutates; extractCarrier returns undefined for anything malformed or oversized and never throws. Carrier v1 is unchanged: ids only, no attributes, user context or baggage. runtime-node: runtimeContext.inject(target, format?) returns a copy carrying the current operation's carrier, and the target unchanged outside an operation. withRuntimeOperation's `from` now also accepts a payload, headers, MessageAttributes or a whole SQS message that contains the key. runtime-next's browser/edge root stand-ins get a matching inject. Docs: BullMQ, SQS and Celery recipes in docs/OPERATION-LOGGING.md. Co-Authored-By: Claude Opus 5.5 --- docs/OPERATION-LOGGING.md | 78 +++++++++- packages/runtime-core/src/carrier.ts | 136 ++++++++++++++++++ packages/runtime-core/src/index.ts | 4 + packages/runtime-core/test/core.test.mjs | 113 +++++++++++++++ packages/runtime-next/src/server-stand-ins.ts | 2 + packages/runtime-node/src/logger.ts | 39 ++++- .../runtime-node/test/operations.test.mjs | 98 +++++++++++++ 7 files changed, 459 insertions(+), 11 deletions(-) diff --git a/docs/OPERATION-LOGGING.md b/docs/OPERATION-LOGGING.md index 10fa605..4705b92 100644 --- a/docs/OPERATION-LOGGING.md +++ b/docs/OPERATION-LOGGING.md @@ -61,8 +61,11 @@ await runtime.shutdown(); `withRuntimeOperation(name, fn, attributes?, options?)` runs the callback in an always-recorded process span and emits one completed operation summary (`autter.operation.kind = "operation"`; request middleware emits `"request"` summaries). `options.from` -continues work from a `runtimeContext.carrier()` (parent link, request id, and an -OTel span link to the producer trace); `options.waitUntil` receives the log flush +continues work handed over from another operation (parent link, request id, and an +OTel span link to the producer trace): it takes a `runtimeContext.carrier()` or +anything `runtimeContext.inject()` produced, see +[Queues, workers and other processes](#queues-workers-and-other-processes); +`options.waitUntil` receives the log flush promise once the summary is emitted. It returns the callback's result and rethrows its original error. An unhandled callback error records an exception in the trace; the log summary is related evidence, not a second issue. @@ -86,8 +89,8 @@ the existing `autter.outcome` trace event, including the reporting call site. `createRuntimeLogger(attributes?)` creates a logger with `debug`, `info`, `warn`, and `error` methods. `runtimeLogger` is the default instance; `runtimeContext` -exposes the same methods plus `set`, `outcome`, `id`, `requestId`, `fork` and -`carrier` for the current operation from anywhere in its call tree. +exposes the same methods plus `set`, `outcome`, `id`, `requestId`, `fork`, +`carrier` and `inject` for the current operation from anywhere in its call tree. **Inline messages (1.5.0).** Inside an operation, `debug` and `info` messages are folded into its summary as `autter.operation.logs` — `{ t, level, message, @@ -100,12 +103,73 @@ diagnostic context; use `captureException` for exception grouping or declare a failed operation outcome for business-failure grouping. Logs inherit the active operation ID, name, parent operation ID, and application attributes, plus the active OTel trace/span IDs. Concurrent operations keep separate contexts. -Async context does not cross a queue or process by itself: put -`runtimeContext.carrier()` in the job payload and pass it as -`withRuntimeOperation(name, fn, {}, { from: payload.autter })` in the consumer. +Async context does not cross a queue or process by itself; see +[Queues, workers and other processes](#queues-workers-and-other-processes). `runtimeContext.fork(name, fn)` links a child to its parent even when the child outlives it; `runInBackground(name, fn)` does the same without awaiting. +## Queues, workers and other processes + +The producer adds the current operation's carrier to what it hands over with +`runtimeContext.inject(target, format?)`; the consumer passes what it received +as `withRuntimeOperation(name, fn, {}, { from })`. The consumer's summary then +has `autter.operation.parent_id` (the producer operation), the producer's +`autter.request.id` and `autter.parent_trace_id`. The consumer's trace is +linked to the producer's (an OTel span link), not continued: it gets its own +trace id, and the request id is what joins the two. + +The carrier is `{ v: 1, op, req?, traceparent? }` under the key `autter`: ids +only, never operation attributes, user context or baggage. `inject` returns a +copy and never changes `target`. Outside an operation, or when `target` is not a +plain object or `Headers`, it returns `target` unchanged. It never throws. +`from` ignores anything missing or malformed, and a carrier string over 1,024 +characters; the operation then starts unlinked. + +| `format` | Where the carrier goes | Consumer passes as `from` | +| --- | --- | --- | +| `"payload"` (default) | `{ ...data, autter: carrier }` | the payload | +| `"headers"` | header `autter: ` (a `Headers` instance is always treated as headers) | the headers (any case) | +| `"sqs"` | `{ autter: { DataType: "String", StringValue: } }` | `MessageAttributes`, or the whole message | + +BullMQ (the job payload): + +```ts +import { runtimeContext, withRuntimeOperation } from "@autter/runtime-node"; + +// Producer, inside a request or operation +await queue.add("resize", runtimeContext.inject({ imageId })); + +// Worker +new Worker("images", (job) => + withRuntimeOperation(job.name, () => resize(job.data.imageId), {}, { from: job.data }), +); +``` + +SQS (a message attribute, so the body stays yours): + +```ts +// Producer +await sqs.send(new SendMessageCommand({ + QueueUrl, + MessageBody: JSON.stringify(order), + MessageAttributes: runtimeContext.inject({}, "sqs"), +})); + +// Consumer: ReceiveMessage needs MessageAttributeNames: ["autter"] (or ["All"]). +// A Lambda SQS record works as is (its messageAttributes are read too). +for (const message of Messages ?? []) { + await withRuntimeOperation("fulfil-order", () => fulfil(JSON.parse(message.Body!)), {}, { + from: message, + }); +} +``` + +Celery (Python): no Autter helper is needed. OpenTelemetry's Celery +instrumentation already continues the trace from the code that sends the task +to the worker that runs it: call `CeleryInstrumentor().instrument()` in both +processes, after `init_tracing()`, as in +[`examples/python/celery`](../examples/python/celery). + ## Collection and privacy - Logs are OTLP/HTTP log records. Both OTLP JSON and protobuf are accepted. diff --git a/packages/runtime-core/src/carrier.ts b/packages/runtime-core/src/carrier.ts index 5bd646e..6b24dff 100644 --- a/packages/runtime-core/src/carrier.ts +++ b/packages/runtime-core/src/carrier.ts @@ -83,3 +83,139 @@ export function parseCarrier(input: unknown): RuntimeCarrier | null { : {}), }); } + +/** Key (and header / SQS message attribute name) a carrier travels under. */ +export const CARRIER_KEY = "autter"; + +/** + * Where `injectCarrier` puts the carrier: + * - `"payload"` (default): a plain job payload object, as `{ ...payload, autter: carrier }`; + * - `"headers"`: an HTTP header map, as the header `autter: ` + * (a `Headers` instance is always treated as headers); + * - `"sqs"`: AWS SQS `MessageAttributes`, as + * `{ autter: { DataType: "String", StringValue: } }`. + */ +export type CarrierFormat = "payload" | "headers" | "sqs"; + +// Case-insensitive lookups read at most this many keys of a source object. +const MAX_SCANNED_KEYS = 256; + +const hasOwn = (value: object, key: string): boolean => + Object.prototype.hasOwnProperty.call(value, key); + +function isPlainObject(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function isHeaders(value: unknown): value is Headers { + return typeof Headers !== "undefined" && value instanceof Headers; +} + +/** + * Return a copy of `target` that carries `carrier` (see `CarrierFormat`). + * Never mutates `target`: plain objects come back as shallow copies and a + * `Headers` instance as a new `Headers`. Only the carrier's own fields are + * written (`{ v: 1, op, req?, traceparent? }`), never attributes or user + * context. When there is nothing to inject (no valid carrier) or the target + * cannot hold it (not a plain object or `Headers`), `target` is returned + * unchanged. Never throws. + */ +export function injectCarrier( + target: T, + carrier: RuntimeCarrier | null | undefined, + format: CarrierFormat = "payload", +): T { + try { + const valid = carrier ? parseCarrier(carrier) : null; + if (!valid) return target; + const json = JSON.stringify(valid); + if (isHeaders(target)) { + const copy = new Headers(target); + copy.set(CARRIER_KEY, json); + return copy as T; + } + if (!isPlainObject(target)) return target; + if (format === "headers") { + const copy: Record = {}; + for (const key of Object.keys(target)) + if (key.toLowerCase() !== CARRIER_KEY) copy[key] = target[key]; + copy[CARRIER_KEY] = json; + return copy as T; + } + if (format === "sqs") + return { + ...target, + [CARRIER_KEY]: { DataType: "String", StringValue: json }, + } as T; + return { ...target, [CARRIER_KEY]: valid } as T; + } catch { + return target; + } +} + +/** A carrier value found under the key: JSON string, header list, SQS attribute or object. */ +function carrierFromValue(value: unknown): RuntimeCarrier | null { + if (typeof value === "string") return parseCarrier(value); + if (Array.isArray(value)) + return value.length === 1 && typeof value[0] === "string" + ? parseCarrier(value[0]) + : null; + if (!value || typeof value !== "object") return null; + const raw = value as Record; + // SQS MessageAttributes (SDK: StringValue/DataType; Lambda events: stringValue/dataType). + const stringValue = raw.StringValue ?? raw.stringValue; + if (stringValue !== undefined) { + const dataType = raw.DataType ?? raw.dataType; + return typeof stringValue === "string" && + (dataType === undefined || (typeof dataType === "string" && dataType.startsWith("String"))) + ? parseCarrier(stringValue) + : null; + } + return parseCarrier(raw); +} + +function valueUnderKey(source: Record): unknown { + if (hasOwn(source, CARRIER_KEY)) return source[CARRIER_KEY]; + // Header maps: names are case-insensitive. + let scanned = 0; + for (const key in source) { + if (++scanned > MAX_SCANNED_KEYS) break; + if (hasOwn(source, key) && key.toLowerCase() === CARRIER_KEY) return source[key]; + } + return undefined; +} + +function extractFrom(source: unknown, depth: number): RuntimeCarrier | null { + if (typeof source === "string") return parseCarrier(source); + if (isHeaders(source)) return carrierFromValue(source.get(CARRIER_KEY)); + if (!source || typeof source !== "object" || Array.isArray(source)) return null; + const raw = source as Record; + const value = valueUnderKey(raw); + if (value !== undefined) return carrierFromValue(value); + // The carrier itself. + if (hasOwn(raw, "v") && hasOwn(raw, "op")) return parseCarrier(raw); + // A whole SQS message (SDK `MessageAttributes`, Lambda `messageAttributes`). + if (depth === 0) { + const attributes = raw.MessageAttributes ?? raw.messageAttributes; + if (attributes && typeof attributes === "object") return extractFrom(attributes, 1); + } + return null; +} + +/** + * Read a carrier from what a consumer received: the carrier itself (object + * or JSON string), a job payload with an `autter` key, HTTP headers (a + * `Headers` instance or a header map; the name is case-insensitive), SQS + * `MessageAttributes`, or a whole SQS message. Validated like `parseCarrier` + * (same size and format limits; invalid optional fields are dropped). + * Returns undefined for anything missing, malformed or oversized. Never throws. + */ +export function extractCarrier(source: unknown): RuntimeCarrier | undefined { + try { + return extractFrom(source, 0) ?? undefined; + } catch { + return undefined; + } +} diff --git a/packages/runtime-core/src/index.ts b/packages/runtime-core/src/index.ts index 36a2132..48e9d74 100644 --- a/packages/runtime-core/src/index.ts +++ b/packages/runtime-core/src/index.ts @@ -97,10 +97,14 @@ export { type OtlpResource, } from "./otlp-logs.js"; export { + CARRIER_KEY, createCarrier, + extractCarrier, + injectCarrier, parseCarrier, formatTraceparent, parseTraceparent, + type CarrierFormat, type RuntimeCarrier, } from "./carrier.js"; export { diff --git a/packages/runtime-core/test/core.test.mjs b/packages/runtime-core/test/core.test.mjs index 918aaa7..951517e 100644 --- a/packages/runtime-core/test/core.test.mjs +++ b/packages/runtime-core/test/core.test.mjs @@ -16,6 +16,9 @@ import { codeFingerprint, parseCarrier, createCarrier, + injectCarrier, + extractCarrier, + CARRIER_KEY, resolveRequestId, normalizeRoutePath, compileIgnore, @@ -158,6 +161,116 @@ test("carriers round-trip and reject malformed input", () => { assert.deepEqual(parseCarrier({ v: 1, op: "op-1", req: "bad id!", traceparent: "junk" }), { v: 1, op: "op-1" }); }); +const CARRIER = createCarrier({ + op: "6f1c2b9e-1111-4222-8333-944455556666", + req: "req-abcdef12", + traceparent: "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", +}); + +test("injectCarrier/extractCarrier round-trip a job payload under the autter key, without mutating it", () => { + assert.equal(CARRIER_KEY, "autter"); + const data = { imageId: 42, sizes: [1, 2] }; + const job = injectCarrier(data, CARRIER); + assert.notEqual(job, data, "a shallow copy, not the input"); + assert.deepEqual(data, { imageId: 42, sizes: [1, 2] }, "the input is untouched"); + assert.deepEqual(job, { imageId: 42, sizes: [1, 2], autter: CARRIER }); + assert.equal(job.sizes, data.sizes, "shallow: nested values are shared"); + assert.deepEqual(extractCarrier(job), CARRIER); + // Through a queue that serialises payloads as JSON. + assert.deepEqual(extractCarrier(JSON.parse(JSON.stringify(job))), CARRIER); + // A payload whose own fields look like a carrier: the autter key wins. + assert.deepEqual(extractCarrier({ v: 1, op: "resize", autter: CARRIER }), CARRIER); + // The carrier itself, as an object or a JSON string, is accepted too. + assert.deepEqual(extractCarrier(CARRIER), CARRIER); + assert.deepEqual(extractCarrier(JSON.stringify(CARRIER)), CARRIER); + // An existing carrier is replaced, not merged. + const again = injectCarrier({ autter: { v: 1, op: "older" } }, CARRIER); + assert.deepEqual(again.autter, CARRIER); +}); + +test("injectCarrier writes only the carrier fields (no attributes, user context or baggage)", () => { + const job = injectCarrier({}, { ...CARRIER, user: { email: "a@example.com" }, attributes: { x: 1 }, baggage: "k=v" }); + assert.deepEqual(Object.keys(job.autter).sort(), ["op", "req", "traceparent", "v"]); + const headers = injectCarrier({}, { ...CARRIER, user: "a@example.com" }, "headers"); + assert.deepEqual(Object.keys(JSON.parse(headers.autter)).sort(), ["op", "req", "traceparent", "v"]); +}); + +test("injectCarrier/extractCarrier round-trip HTTP headers (case-insensitive name, string value)", () => { + const headers = { "content-type": "application/json", Autter: "stale" }; + const out = injectCarrier(headers, CARRIER, "headers"); + assert.deepEqual(headers, { "content-type": "application/json", Autter: "stale" }, "input untouched"); + assert.equal(typeof out.autter, "string"); + assert.equal(out.Autter, undefined, "a differently-cased old header is replaced, not duplicated"); + assert.equal(out["content-type"], "application/json"); + assert.deepEqual(extractCarrier(out), CARRIER); + // Received with another case, or as Node's single-entry header list. + assert.deepEqual(extractCarrier({ AUTTER: out.autter }), CARRIER); + assert.deepEqual(extractCarrier({ autter: [out.autter] }), CARRIER); + assert.equal(extractCarrier({ autter: [out.autter, out.autter] }), undefined); + // A fetch Headers instance: a new Headers comes back, the input is untouched. + const fetchHeaders = new Headers({ accept: "text/plain" }); + const copy = injectCarrier(fetchHeaders, CARRIER); + assert.ok(copy instanceof Headers); + assert.notEqual(copy, fetchHeaders); + assert.equal(fetchHeaders.has("autter"), false); + assert.equal(copy.get("accept"), "text/plain"); + assert.deepEqual(extractCarrier(copy), CARRIER); + assert.deepEqual(extractCarrier(new Headers({ AUTTER: JSON.stringify(CARRIER) })), CARRIER); +}); + +test("injectCarrier/extractCarrier round-trip SQS MessageAttributes and whole SQS messages", () => { + const attributes = { tenant: { DataType: "String", StringValue: "t1" } }; + const out = injectCarrier(attributes, CARRIER, "sqs"); + assert.deepEqual(Object.keys(attributes), ["tenant"], "input untouched"); + assert.equal(out.tenant, attributes.tenant); + assert.equal(out.autter.DataType, "String"); + assert.deepEqual(JSON.parse(out.autter.StringValue), CARRIER); + assert.deepEqual(extractCarrier(out), CARRIER); + // A received message (AWS SDK) and a Lambda SQS event record (lower-case keys). + assert.deepEqual(extractCarrier({ Body: "{}", MessageAttributes: out }), CARRIER); + assert.deepEqual( + extractCarrier({ body: "{}", messageAttributes: { autter: { dataType: "String", stringValue: out.autter.StringValue } } }), + CARRIER, + ); + // A non-string attribute type is not a carrier. + assert.equal(extractCarrier({ autter: { DataType: "Binary", StringValue: out.autter.StringValue } }), undefined); +}); + +test("extractCarrier returns undefined for missing, malformed or oversized input and never throws", () => { + const hostile = new Proxy({}, { get() { throw new Error("boom"); }, has() { throw new Error("boom"); }, ownKeys() { throw new Error("boom"); }, getOwnPropertyDescriptor() { throw new Error("boom"); } }); + const malformed = [ + undefined, null, 0, 42, true, "", "not json", "[]", [], [CARRIER], {}, { other: 1 }, + { autter: null }, { autter: 7 }, { autter: "not json" }, { autter: { v: 2, op: "x" } }, + { autter: { v: 1, op: "bad op id!" } }, { autter: { v: 1 } }, { v: 1, op: "x".repeat(129) }, + { autter: JSON.stringify({ ...CARRIER, pad: "x".repeat(1100) }) }, + { MessageAttributes: { autter: { DataType: "String", StringValue: "x".repeat(2000) } } }, + { MessageAttributes: { MessageAttributes: { autter: { DataType: "String", StringValue: JSON.stringify(CARRIER) } } } }, + { autter: { StringValue: 5 } }, + Object.create({ autter: CARRIER }), + hostile, + { autter: hostile }, + ]; + malformed.forEach((input, index) => assert.equal(extractCarrier(input), undefined, `malformed input #${index}`)); + // Invalid optional fields are dropped, as parseCarrier does. + assert.deepEqual(extractCarrier({ autter: { v: 1, op: "op-1", req: "bad id!", traceparent: "junk" } }), { v: 1, op: "op-1" }); +}); + +test("injectCarrier leaves the target unchanged when there is nothing to inject or nowhere to put it", () => { + const data = { a: 1 }; + assert.equal(injectCarrier(data, undefined), data); + assert.equal(injectCarrier(data, null), data); + assert.equal(injectCarrier(data, { v: 2, op: "x" }), data); + assert.deepEqual(data, { a: 1 }); + const list = [1, 2]; + assert.equal(injectCarrier(list, CARRIER), list); + assert.equal(injectCarrier("text", CARRIER), "text"); + assert.equal(injectCarrier(null, CARRIER), null); + class Job { constructor() { this.id = 1; } } + const instance = new Job(); + assert.equal(injectCarrier(instance, CARRIER), instance, "class instances are not copied (that would drop their prototype)"); + assert.equal(injectCarrier(Object.freeze({ a: 1 }), CARRIER).autter.op, CARRIER.op, "frozen input is fine: it is copied"); +}); + test("request helpers: ids, route normalisation, ignore globs, outcomes", () => { assert.equal(resolveRequestId("abc12345"), "abc12345"); assert.match(resolveRequestId("short"), /^[0-9a-f-]{36}$/); diff --git a/packages/runtime-next/src/server-stand-ins.ts b/packages/runtime-next/src/server-stand-ins.ts index 3b2ba41..27733f7 100644 --- a/packages/runtime-next/src/server-stand-ins.ts +++ b/packages/runtime-next/src/server-stand-ins.ts @@ -135,6 +135,8 @@ export function serverStandIns(build: RootBuild): ServerStandIns { return fn(operation()); }, carrier: () => undefined, + // No operation here, so nothing to carry: the target comes back unchanged. + inject: (target) => target, }, flushRuntimeLogs: async () => ({ ok: true, errors: [] }), runtimeLogStats: () => ({ buffered: 0, dropped: 0 }), diff --git a/packages/runtime-node/src/logger.ts b/packages/runtime-node/src/logger.ts index f711cda..18aab1c 100644 --- a/packages/runtime-node/src/logger.ts +++ b/packages/runtime-node/src/logger.ts @@ -14,11 +14,12 @@ import { createInlineLogState, createRuntimeEvent, errorAttributes, + extractCarrier, + injectCarrier, isError, formatTraceparent, maxLevel, mergeContext, - parseCarrier, parseTraceparent, stackAttributesLast, toSpanAttributes, @@ -118,8 +119,14 @@ export interface RuntimeOperation { } export interface RuntimeOperationOptions { - /** Carrier from `runtimeContext.carrier()` (object or JSON string): links parent op, request id and trace. */ - from?: RuntimeCarrier | string | null; + /** + * Where this work was handed over from: links parent op, request id and + * trace. A carrier from `runtimeContext.carrier()` (object or JSON + * string), or what `runtimeContext.inject()` produced: a job payload, + * HTTP headers, SQS `MessageAttributes` or a whole SQS message. Anything + * malformed is ignored (the operation starts unlinked). + */ + from?: RuntimeCarrier | string | object | null; /** Receives the log flush promise once the operation completes (serverless `waitUntil`). */ waitUntil?: (promise: Promise) => void; } @@ -672,7 +679,7 @@ function startOperation( internal: StartInternal = {}, ): Promise { const parent = internal.forkParent ?? local.getStore(); - const carrier = options.from ? parseCarrier(options.from) : null; + const carrier = options.from ? (extractCarrier(options.from) ?? null) : null; const traceparent = carrier?.traceparent ? parseTraceparent(carrier.traceparent) : null; @@ -867,6 +874,30 @@ export const runtimeContext = { ...(traceparent ? { traceparent } : {}), }); }, + /** + * A copy of `target` carrying the current operation's carrier, for work + * handed to a queue or another process: + * + * queue.add("resize", runtimeContext.inject(data)); // payload: data.autter + * fetch(url, { headers: runtimeContext.inject(headers, "headers") }); + * MessageAttributes: runtimeContext.inject({}, "sqs"), + * + * The consumer passes what it received as `withRuntimeOperation(name, fn, + * {}, { from })`. Only `{ v: 1, op, req?, traceparent? }` is added, never + * attributes or user context. Never mutates `target`; outside an + * operation (or when `target` cannot hold it) returns `target` itself, + * unchanged. Never throws. + */ + // The format is spelled out (not `CarrierFormat`) so declarations of + // packages that re-export runtimeContext can name the type. + inject(target: T, format: "payload" | "headers" | "sqs" = "payload"): T { + try { + const carrier = runtimeContext.carrier(); + return carrier ? injectCarrier(target, carrier, format) : target; + } catch { + return target; + } + }, }; export type RuntimeContextHandle = typeof runtimeContext; diff --git a/packages/runtime-node/test/operations.test.mjs b/packages/runtime-node/test/operations.test.mjs index 9f57b2a..7169749 100644 --- a/packages/runtime-node/test/operations.test.mjs +++ b/packages/runtime-node/test/operations.test.mjs @@ -6,6 +6,7 @@ import { withRuntimeOperation, runtimeContext, runInBackground, + withRuntimeRequest, withLlmCall, trackLlmCall, captureException, @@ -112,6 +113,103 @@ test("carrier round trip links parent, request id and the producer trace", async } }); +test("a consumer started from an injected job payload is linked to the producer: parent op, request id, trace link", async () => { + const c = await collector(); + const sdk = initAutterServer({ + service: "queue", + apiKey: "k", + endpoint: c.endpoint, + captureGlobalErrors: false, + autoFlush: false, + memoryMetrics: false, + logging: { console: false }, + }); + const runtime = captureRuntime(); + try { + const queue = []; + let producerId; + let producerTrace; + // The producer: an operation inside a request enqueues a job (a queue serialises it as JSON). + const handler = withRuntimeRequest(async () => { + await withRuntimeOperation("enqueue", async () => { + producerId = runtimeContext.id; + const data = { imageId: 7 }; + const job = runtimeContext.inject(data); + assert.deepEqual(data, { imageId: 7 }, "inject does not mutate the payload"); + producerTrace = job.autter.traceparent.split("-")[1]; + queue.push(JSON.stringify({ name: "resize", data: job })); + }); + return new Response("queued", { status: 202 }); + }); + const response = await handler(new Request("http://localhost/images", { method: "POST", headers: { "x-request-id": "req-carrier-1" } })); + assert.equal(response.status, 202); + + // The consumer, as a worker would run it: `{ from: job.data }`. + const job = JSON.parse(queue.shift()); + let seen; + await withRuntimeOperation(job.name, async () => { + seen = { id: runtimeContext.id, requestId: runtimeContext.requestId }; + }, {}, { from: job.data }); + assert.equal(seen.requestId, "req-carrier-1", "the request id is carried into the consumer"); + assert.notEqual(seen.id, producerId, "the consumer is its own operation"); + expectOperation(runtime, "resize") + .toHaveRequestId("req-carrier-1") + .toHaveContext({ + "autter.operation.parent_id": producerId, + "autter.parent_trace_id": producerTrace, + }); + + // Headers and SQS message attributes link the same way. + let headers; + let attributes; + await withRuntimeOperation("produce-more", async () => { + producerId = runtimeContext.id; + headers = runtimeContext.inject({ "content-type": "application/json" }, "headers"); + attributes = runtimeContext.inject({}, "sqs"); + }); + await withRuntimeOperation("from-headers", async () => {}, {}, { from: { AUTTER: headers.autter } }); + expectOperation(runtime, "from-headers").toHaveContext({ "autter.operation.parent_id": producerId }); + await withRuntimeOperation("from-sqs", async () => {}, {}, { from: { Body: "{}", MessageAttributes: attributes } }); + expectOperation(runtime, "from-sqs").toHaveContext({ "autter.operation.parent_id": producerId }); + + await sdk.shutdown(); + const consumer = c.spans().find((s) => s.name === "resize"); + assert.ok(consumer, "consumer span exported"); + assert.equal(consumer.links[0].traceId, producerTrace, "linked to the producer trace"); + assert.notEqual(consumer.traceId, producerTrace, "linked, not continued"); + } finally { + runtime.stop(); + await c.close(); + } +}); + +test("runtimeContext.inject outside an operation returns the target unchanged; a bad `from` starts unlinked", async () => { + const runtime = captureRuntime(); + try { + const data = { imageId: 7 }; + assert.equal(runtimeContext.carrier(), undefined); + assert.equal(runtimeContext.inject(data), data); + assert.deepEqual(data, { imageId: 7 }, "no autter key added"); + assert.equal(runtimeContext.inject(data, "headers"), data); + assert.equal(runtimeContext.inject(data, "sqs"), data); + assert.equal(runtimeContext.inject(undefined), undefined); + assert.equal(runtimeContext.inject("text"), "text"); + // Inside an operation, a target that cannot hold a key comes back as it was. + await withRuntimeOperation("producer", async () => { + const list = [1]; + assert.equal(runtimeContext.inject(list), list); + assert.equal(runtimeContext.inject(null), null); + }); + for (const from of ["not json", { autter: "junk" }, { autter: { v: 2, op: "x" } }, { other: 1 }, []]) { + await withRuntimeOperation("unlinked", async () => {}, {}, { from }); + const summary = expectOperation(runtime, "unlinked"); + assert.equal(summary.attributes["autter.operation.parent_id"], undefined, `from ${JSON.stringify(from)}`); + } + } finally { + runtime.stop(); + } +}); + test("coded errors on spans: autter.error.* on span and event, internal on the span only", async () => { const c = await collector(); const sdk = initAutterServer({