@babelqueue/sqs 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,6 +68,12 @@ dedupe on `meta.id` if the side effect must not repeat. The loop never stops on
68
68
  `onUnknownUrn` to observe. The envelope is unchanged (`schema_version` stays `1`); SQS
69
69
  is purely additive.
70
70
 
71
+ **Version gate (§3.7).** Before the body is decoded the consumer reads the `bq-schema-version`
72
+ message attribute. A missing or blank value (empty or only ASCII whitespace) changes nothing; any
73
+ other value that is not exactly `"1"` (`"2"`, `"x"`, `"01"`, `" 1"` — never trimmed) rejects the
74
+ message **undecoded**: it reaches `onError` (with an empty envelope) and is left undeleted, so it is
75
+ redelivered and the `RedrivePolicy` below moves it to the DLQ.
76
+
71
77
  > **Poison messages — configure a `RedrivePolicy`.** With the `0 s` default, a handler
72
78
  > that always fails is retried back-to-back until the queue's native `RedrivePolicy`
73
79
  > (`maxReceiveCount`) moves the message to its dead-letter queue. Without one, such a
package/dist/index.cjs CHANGED
@@ -87,6 +87,12 @@ function headersOf(message) {
87
87
  }
88
88
  return out;
89
89
  }
90
+ var BLANK_ASCII = /^[ \t\n\v\f\r]*$/;
91
+ function unsupportedSchemaVersion(message) {
92
+ const raw = message.MessageAttributes?.["bq-schema-version"]?.StringValue;
93
+ if (typeof raw !== "string" || BLANK_ASCII.test(raw)) return void 0;
94
+ return raw === String(import_core.SCHEMA_VERSION) ? void 0 : raw;
95
+ }
90
96
  function queueNameFromUrl(queueUrl) {
91
97
  const segments = queueUrl.split("/").filter(Boolean);
92
98
  return segments[segments.length - 1] ?? "default";
@@ -178,6 +184,17 @@ var SqsConsumer = class {
178
184
  }
179
185
  }
180
186
  async handle(message) {
187
+ const rejectedVersion = unsupportedSchemaVersion(message);
188
+ if (rejectedVersion !== void 0) {
189
+ this.options.onError?.(
190
+ new import_core.BabelQueueError(
191
+ `Rejected a message from SQS with unsupported bq-schema-version "${rejectedVersion}" (supported: ${import_core.SCHEMA_VERSION}).`
192
+ ),
193
+ {},
194
+ message
195
+ );
196
+ return;
197
+ }
181
198
  const envelope = import_core.EnvelopeCodec.decode(message.Body ?? "");
182
199
  const receiveCount = message.Attributes?.["ApproximateReceiveCount"];
183
200
  if (receiveCount !== void 0) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Amazon SQS adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Amazon SQS,\n * so an SQS-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the PHP/Laravel, Python, Go, Java and .NET SDKs.\n *\n * import { SQS } from \"@aws-sdk/client-sqs\";\n * import { SqsPublisher, SqsConsumer } from \"@babelqueue/sqs\";\n *\n * const sqs = new SQS({ region: \"eu-central-1\" });\n * const url = \"https://sqs.eu-central-1.amazonaws.com/123456789012/orders\";\n *\n * await new SqsPublisher(sqs, url).publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new SqsConsumer(sqs, url, {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §3 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native SQS `MessageAttributes`. The envelope is\n * unchanged (`schema_version` stays 1); SQS is purely additive. Retry is SQS-native\n * (a failed handler's message is released via `ChangeMessageVisibility` after\n * `releaseDelay`, default 0 s — pair the queue with a `RedrivePolicy`); the\n * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as\n * `attempts = count − 1`.\n *\n * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop\n * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`\n * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and\n * the merged set is bounded by SQS's **10-attribute limit** (contract attributes are seeded first,\n * so a rider only lands while headroom remains). On consume the inbound `MessageAttributes` are\n * surfaced as a `Record<string,string>` so the core's `otel` extract sees the `traceparent` and\n * links the consumer span as a child. A header-less publish is byte-identical. This mirrors the Go\n * `/sqs` and PHP `SqsTransport` wiring. GR-1: the wire envelope body is never touched.\n */\n\nimport { BabelQueueError, EnvelopeCodec, UnknownUrnError, UnknownUrnStrategy, annotate } from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { sanitizeHeaders } from \"./headers.js\";\n\n/** SQS allows at most 10 user message attributes per message. */\nconst MAX_ATTRIBUTES = 10;\n\n/** The SQS ceiling for a `VisibilityTimeout` (12 hours, in seconds). */\nexport const MAX_VISIBILITY_TIMEOUT = 43_200;\n\n// --- Minimal SQS shapes (a structural subset of @aws-sdk/client-sqs) -----------\n\nexport interface SqsMessageAttributeValue {\n DataType: string;\n StringValue?: string;\n}\n\nexport interface SqsMessage {\n Body?: string;\n ReceiptHandle?: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n Attributes?: Record<string, string>;\n}\n\nexport interface SendMessageInput {\n QueueUrl: string;\n MessageBody: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n MessageGroupId?: string;\n MessageDeduplicationId?: string;\n}\n\nexport interface ReceiveMessageInput {\n QueueUrl: string;\n MaxNumberOfMessages?: number;\n WaitTimeSeconds?: number;\n VisibilityTimeout?: number;\n MessageAttributeNames?: string[];\n AttributeNames?: string[];\n}\n\n/**\n * The subset of the AWS SQS client this adapter calls. The aggregated `SQS` class\n * from `@aws-sdk/client-sqs` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface SqsApi {\n sendMessage(input: SendMessageInput): Promise<{ MessageId?: string } | unknown>;\n receiveMessage(input: ReceiveMessageInput): Promise<{ Messages?: SqsMessage[] }>;\n deleteMessage(input: { QueueUrl: string; ReceiptHandle: string }): Promise<unknown>;\n /**\n * The §3.5 release primitive. Optional so existing structural clients keep compiling; it is\n * required (checked at construction) when a consumer sets `releaseDelay` or the `release`\n * unknown-URN strategy explicitly. Without it the default handler-failure release degrades to\n * leaving the message for visibility-timeout redelivery. The aggregated `SQS` class from\n * `@aws-sdk/client-sqs` provides it.\n */\n changeMessageVisibility?(input: ChangeMessageVisibilityInput): Promise<unknown>;\n}\n\nexport interface ChangeMessageVisibilityInput {\n QueueUrl: string;\n ReceiptHandle: string;\n VisibilityTimeout: number;\n}\n\n// --- Attribute projection (contract §3.2) --------------------------------------\n\nconst str = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"String\",\n StringValue: String(value),\n});\nconst num = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"Number\",\n StringValue: String(value),\n});\n\n/**\n * Project the envelope's contract fields onto native SQS `MessageAttributes` — a\n * redundant, routable view of the body (the body stays authoritative).\n */\nexport function toMessageAttributes(envelope: Envelope): Record<string, SqsMessageAttributeValue> {\n const attrs: Record<string, SqsMessageAttributeValue> = {};\n if (envelope.job) attrs[\"bq-job\"] = str(envelope.job);\n if (envelope.trace_id) attrs[\"bq-trace-id\"] = str(envelope.trace_id);\n if (envelope.meta.id) attrs[\"bq-message-id\"] = str(envelope.meta.id);\n if (envelope.meta.schema_version != null) {\n attrs[\"bq-schema-version\"] = num(envelope.meta.schema_version);\n }\n if (envelope.meta.lang) attrs[\"bq-source-lang\"] = str(envelope.meta.lang);\n if (envelope.meta.created_at != null) {\n attrs[\"bq-created-at\"] = num(envelope.meta.created_at);\n }\n return attrs;\n}\n\n/**\n * Overlay the out-of-band `headers` onto the contract attribute projection as String\n * `MessageAttributes`, without overwriting an existing `bq-*` attribute (the contract wins a key\n * collision) and skipping blanks. Keys are merged in sorted order and the merge stops at the\n * 10-attribute SQS ceiling, so unbounded riders can never push the message past the limit (SQS\n * rejects the whole send otherwise) — the contract attributes are always preserved first. Mirrors\n * Go's `mergeAttributes` / PHP's `SqsTransport::attributes`.\n */\nexport function mergeAttributes(\n base: Record<string, SqsMessageAttributeValue>,\n headers: HeaderCarrier | null | undefined,\n): Record<string, SqsMessageAttributeValue> {\n const clean = sanitizeHeaders(headers);\n for (const key of Object.keys(clean).sort()) {\n if (key in base) continue; // never clobber a contract bq-* attribute\n if (Object.keys(base).length >= MAX_ATTRIBUTES) break; // respect the SQS 10-attribute cap\n base[key] = str(clean[key]);\n }\n return base;\n}\n\n/**\n * Map inbound SQS `MessageAttributes` onto a flat {@link HeaderCarrier} (the consume-side\n * counterpart of {@link mergeAttributes}), reading each attribute's `StringValue`. Returns an empty\n * object when there are none. Both the contract `bq-*` attributes and any out-of-band rider (e.g.\n * `traceparent`) surface — the core's `otel` extract reads only the keys it knows.\n */\nexport function headersOf(message: SqsMessage): HeaderCarrier {\n const attrs = message.MessageAttributes;\n const out: HeaderCarrier = {};\n if (!attrs) return out;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key]?.StringValue;\n if (value != null && value !== \"\") out[key] = value;\n }\n return out;\n}\n\nfunction queueNameFromUrl(queueUrl: string): string {\n const segments = queueUrl.split(\"/\").filter(Boolean);\n return segments[segments.length - 1] ?? \"default\";\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link SqsPublisher}. */\nexport interface SqsPublisherOptions {\n /** Treat the queue as FIFO: set `MessageGroupId` and (unless content dedup) `MessageDeduplicationId`. */\n fifo?: boolean;\n /** FIFO ordering group (default: the queue name from the URL). */\n messageGroupId?: string;\n /** Use the queue's content-based dedup instead of `meta.id` as the dedup id. */\n contentDedup?: boolean;\n}\n\n/** Options for {@link SqsPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /**\n * Out-of-band transport headers carried as String `MessageAttributes` beside the contract `bq-*`\n * attributes (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s `publish`.\n * The contract attributes win a key collision and the merged set is capped at SQS's 10-attribute\n * limit; an empty/omitted carrier leaves the publish unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one SQS queue with the §3 attribute projection. */\nexport class SqsPublisher {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly options: SqsPublisherOptions = {},\n ) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it as the message body with\n * the projected `MessageAttributes`, and return the message id (`meta.id`).\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: queueNameFromUrl(this.queueUrl),\n traceId: options.traceId,\n });\n const input: SendMessageInput = {\n QueueUrl: this.queueUrl,\n MessageBody: EnvelopeCodec.encode(envelope),\n MessageAttributes: mergeAttributes(toMessageAttributes(envelope), options.headers),\n };\n if (this.options.fifo) {\n input.MessageGroupId = this.options.messageGroupId ?? queueNameFromUrl(this.queueUrl);\n if (!this.options.contentDedup) {\n input.MessageDeduplicationId = envelope.meta.id;\n }\n }\n await this.client.sendMessage(input);\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw SQS message, and the out-of-band\n * {@link HeaderCarrier} read from the message's `MessageAttributes` (empty when there are none).\n * Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of\n * the producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: SqsMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link SqsConsumer}. */\nexport interface SqsConsumerOptions {\n /**\n * Called when a message's URN has no handler. Without `unknownUrn` the message is then deleted\n * (the original behaviour); with `unknownUrn` set it is a notification hook and the strategy\n * decides the message's fate.\n */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;\n /**\n * Unknown-URN strategy per contract §3.5 — `fail` | `delete` | `release` | `dead_letter`\n * ({@link UnknownUrnStrategy}). Omitted keeps the original behaviour (`onUnknownUrn` → delete,\n * otherwise report and leave for visibility-timeout redelivery, i.e. `fail`). `release` uses\n * `ChangeMessageVisibility` with {@link unknownUrnReleaseDelay}; `dead_letter` sends the annotated\n * envelope to {@link deadLetterQueueUrl} then deletes, degrading to `delete` when no DLQ is set.\n */\n unknownUrn?: string;\n /** Backoff (seconds) for the `release` unknown-URN strategy (default 0 = redeliver now). */\n unknownUrnReleaseDelay?: number;\n /**\n * Backoff before a failed message is redelivered. A failed handler always releases the message\n * via `ChangeMessageVisibility(ReceiptHandle, VisibilityTimeout)` (contract §3.5); this sets the\n * `VisibilityTimeout` — a number of seconds, or a function of the (reconciled) `attempts`\n * returning seconds (e.g. an exponential backoff). Clamped to `0…43200`. Default `0`: the message\n * is visible again immediately. A permanently failing handler therefore retries without pause\n * until the queue's `RedrivePolicy` (`maxReceiveCount`) moves it to the DLQ — configure one.\n */\n releaseDelay?: number | ((attempts: number) => number);\n /**\n * The cross-language `<queue>.dlq` URL for the `dead_letter` strategy (opt-in; default none). A\n * `.fifo` DLQ is sent with `MessageGroupId` (the source queue name) and `MessageDeduplicationId`\n * (`meta.id`).\n */\n deadLetterQueueUrl?: string | null;\n /**\n * Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), a throwing handler,\n * a throwing `onUnknownUrn` under an `unknownUrn` strategy, a failed release / dead-letter send, or\n * a failed delete after successful processing (an {@link SqsDeleteError} wrapping the broker\n * error; never released). The message is then left for visibility-timeout redelivery. The loop\n * never stops on these.\n */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: SqsMessage) => void;\n /** Long-poll wait seconds (default 20). */\n waitTimeSeconds?: number;\n /** Reservation window applied on receive (seconds). */\n visibilityTimeout?: number;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n}\n\n/**\n * Reported via `onError` when `DeleteMessage` fails for a message whose processing already succeeded\n * (a handler returned normally, or the unknown-URN strategy chose `delete` / `dead_letter`). The\n * broker error is `cause`. Distinct from a handler failure: the message is NOT released, so it is\n * redelivered only after its visibility timeout expires (at-least-once; dedupe on `meta.id` with the\n * idempotency helper if the side effect must not repeat).\n */\nexport class SqsDeleteError extends BabelQueueError {\n constructor(cause: unknown) {\n super(\"Failed to delete a processed SQS message; it will be redelivered after its visibility timeout.\");\n this.name = \"SqsDeleteError\";\n this.cause = cause;\n }\n}\n\n/**\n * Polls an SQS queue, decodes + validates each message, routes it to the handler\n * registered for its URN, and deletes it on success. A throwing handler's message is released via\n * `ChangeMessageVisibility` after `releaseDelay` (default 0 s, contract §3.5); if the release itself\n * fails the message is left for visibility-timeout redelivery (at-least-once);\n * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler. An unmapped URN\n * follows the `unknownUrn` strategy (`fail` | `delete` | `release` | `dead_letter`).\n */\nexport class SqsConsumer {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly handlers: BabelHandlers,\n private readonly options: SqsConsumerOptions = {},\n ) {\n const strategy = options.unknownUrn;\n if (strategy !== undefined && !(Object.values(UnknownUrnStrategy) as string[]).includes(strategy)) {\n throw new BabelQueueError(`Unknown unknownUrn strategy \"${strategy}\".`);\n }\n const needsRelease = options.releaseDelay != null || strategy === UnknownUrnStrategy.RELEASE;\n if (needsRelease && typeof client.changeMessageVisibility !== \"function\") {\n throw new BabelQueueError(\n \"SqsConsumer release requires a client with changeMessageVisibility (contract §3.5).\",\n );\n }\n }\n\n /** Receive one batch, route each message, delete the ones handled. Returns the batch size. */\n async poll(): Promise<number> {\n const input: ReceiveMessageInput = {\n QueueUrl: this.queueUrl,\n MaxNumberOfMessages: this.options.maxMessages ?? 10,\n WaitTimeSeconds: this.options.waitTimeSeconds ?? 20,\n MessageAttributeNames: [\"All\"],\n AttributeNames: [\"ApproximateReceiveCount\"],\n };\n if (this.options.visibilityTimeout != null) {\n input.VisibilityTimeout = this.options.visibilityTimeout;\n }\n const result = await this.client.receiveMessage(input);\n const messages = result.Messages ?? [];\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts (each poll long-polls, so this does not busy-loop). */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: SqsMessage): Promise<void> {\n const envelope = EnvelopeCodec.decode(message.Body ?? \"\");\n\n const receiveCount = message.Attributes?.[\"ApproximateReceiveCount\"];\n if (receiveCount !== undefined) {\n const native = Number.parseInt(receiveCount, 10) - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (Number.isFinite(native) && native > current) {\n envelope.attempts = native;\n }\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from SQS.\"),\n envelope,\n message,\n );\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n await this.unknown(urn, envelope as Envelope, message);\n return;\n }\n\n try {\n await handler(envelope, message, headersOf(message));\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n await this.guard(envelope, message, async () => {\n const delay = this.options.releaseDelay ?? 0;\n const attempts = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n await this.release(message, typeof delay === \"function\" ? delay(attempts) : delay);\n });\n return;\n }\n // Outside the handler's try: a failed delete is not a handler failure. It is reported as an\n // SqsDeleteError and the message is NOT released — releasing at the (default 0 s) backoff would\n // redeliver an already-processed message immediately; it returns on visibility expiry instead.\n await this.guard(envelope, message, () => this.deleteHandled(message));\n }\n\n /**\n * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a\n * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so\n * visibility expiry still redelivers it. Never lets the error stop the consume loop.\n */\n private async guard(envelope: IncomingEnvelope, message: SqsMessage, step: () => Promise<void>): Promise<void> {\n try {\n await step();\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n }\n }\n\n /** Apply the unknown-URN strategy (contract §3.5). */\n private async unknown(urn: string, envelope: Envelope, message: SqsMessage): Promise<void> {\n const strategy = this.options.unknownUrn;\n if (strategy === undefined) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.delete(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n return;\n }\n\n await this.guard(envelope, message, async () => {\n await this.options.onUnknownUrn?.(envelope, message);\n });\n switch (strategy) {\n case UnknownUrnStrategy.DELETE:\n await this.guard(envelope, message, () => this.deleteHandled(message));\n return;\n case UnknownUrnStrategy.RELEASE:\n await this.guard(envelope, message, () => this.release(message, this.options.unknownUrnReleaseDelay ?? 0));\n return;\n case UnknownUrnStrategy.DEAD_LETTER:\n await this.guard(envelope, message, async () => {\n await this.deadLetter(envelope, \"unknown_urn\");\n await this.deleteHandled(message);\n });\n return;\n default:\n // FAIL: surface and do NOT delete — visibility expiry redelivers, native redrive quarantines.\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n }\n\n /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */\n private async release(message: SqsMessage, seconds: number): Promise<void> {\n if (!message.ReceiptHandle || !this.client.changeMessageVisibility) return;\n const timeout = Number.isFinite(seconds)\n ? Math.min(MAX_VISIBILITY_TIMEOUT, Math.max(0, Math.floor(seconds)))\n : 0;\n await this.client.changeMessageVisibility({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n VisibilityTimeout: timeout,\n });\n }\n\n /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */\n private async deadLetter(envelope: Envelope, reason: string): Promise<void> {\n const dlq = this.options.deadLetterQueueUrl;\n if (!dlq) return;\n const source = envelope.meta?.queue ?? queueNameFromUrl(this.queueUrl);\n const annotated = annotate(envelope, reason, source, {\n attempts: envelope.attempts ?? 0,\n });\n const input: SendMessageInput = {\n QueueUrl: dlq,\n MessageBody: EnvelopeCodec.encode(annotated),\n MessageAttributes: toMessageAttributes(annotated),\n };\n if (dlq.endsWith(\".fifo\")) {\n // A FIFO DLQ (`<queue>.dlq.fifo`) rejects a send without a group; dedup on meta.id (§3.2).\n input.MessageGroupId = source;\n if (annotated.meta?.id) input.MessageDeduplicationId = annotated.meta.id;\n }\n await this.client.sendMessage(input);\n }\n\n /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */\n private async deleteHandled(message: SqsMessage): Promise<void> {\n try {\n await this.delete(message);\n } catch (error) {\n throw new SqsDeleteError(error);\n }\n }\n\n private async delete(message: SqsMessage): Promise<void> {\n if (!message.ReceiptHandle) return;\n await this.client.deleteMessage({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n });\n }\n}\n","/**\n * Pure, dependency-free helpers for the out-of-band transport-header seam (ADR-0028) — the Node\n * adapter mirror of Go's `sanitizeHeaders` and PHP's `Support\\Headers`. They fold an injected\n * {@link HeaderCarrier} (e.g. a W3C `traceparent`) onto a transport's metadata channel **without\n * clobbering** the contract headers it already carries.\n *\n * Headers ride beside the frozen wire envelope (GR-1), never inside it.\n */\n\nimport type { HeaderCarrier } from \"@babelqueue/core\";\n\n/**\n * Copy `headers`, dropping blank keys and blank values. Returns an empty object when nothing\n * survives, so a caller can treat the result as \"no headers\". A nullish input yields an empty\n * object.\n */\nexport function sanitizeHeaders(headers: HeaderCarrier | null | undefined): HeaderCarrier {\n const out: HeaderCarrier = {};\n if (!headers) return out;\n for (const key of Object.keys(headers)) {\n const value = headers[key];\n if (key === \"\" || value == null || value === \"\") continue;\n out[key] = value;\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsCA,kBAA8F;;;ACtBvF,SAAS,gBAAgB,SAA0D;AACxF,QAAM,MAAqB,CAAC;AAC5B,MAAI,CAAC,QAAS,QAAO;AACrB,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,QAAQ,QAAQ,GAAG;AACzB,QAAI,QAAQ,MAAM,SAAS,QAAQ,UAAU,GAAI;AACjD,QAAI,GAA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AAS,MAAM,SAAS,iBAAiB,KAAK,QAAQ;AACrE,UAAM,gBAAY,sBAAS,UAAU,QAAQ,QAAQ;AAAA,MACnD,UAAU,SAAS,YAAY;AAAA,IACjC,CAAC;AACD,UAAM,QAA0B;AAAA,MAC9B,UAAU;AAAA,MACV,aAAa,0BAAc,OAAO,SAAS;AAAA,MAC3C,mBAAmB,oBAAoB,SAAS;AAAA,IAClD;AACA,QAAI,IAAI,SAAS,OAAO,GAAG;AAEzB,YAAM,iBAAiB;AACvB,UAAI,UAAU,MAAM,GAAI,OAAM,yBAAyB,UAAU,KAAK;AAAA,IACxE;AACA,UAAM,KAAK,OAAO,YAAY,KAAK;AAAA,EACrC;AAAA;AAAA,EAGA,MAAc,cAAc,SAAoC;AAC9D,QAAI;AACF,YAAM,KAAK,OAAO,OAAO;AAAA,IAC3B,SAAS,OAAO;AACd,YAAM,IAAI,eAAe,KAAK;AAAA,IAChC;AAAA,EACF;AAAA,EAEA,MAAc,OAAO,SAAoC;AACvD,QAAI,CAAC,QAAQ,cAAe;AAC5B,UAAM,KAAK,OAAO,cAAc;AAAA,MAC9B,UAAU,KAAK;AAAA,MACf,eAAe,QAAQ;AAAA,IACzB,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Amazon SQS adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Amazon SQS,\n * so an SQS-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the PHP/Laravel, Python, Go, Java and .NET SDKs.\n *\n * import { SQS } from \"@aws-sdk/client-sqs\";\n * import { SqsPublisher, SqsConsumer } from \"@babelqueue/sqs\";\n *\n * const sqs = new SQS({ region: \"eu-central-1\" });\n * const url = \"https://sqs.eu-central-1.amazonaws.com/123456789012/orders\";\n *\n * await new SqsPublisher(sqs, url).publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new SqsConsumer(sqs, url, {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §3 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native SQS `MessageAttributes`. The envelope is\n * unchanged (`schema_version` stays 1); SQS is purely additive. Retry is SQS-native\n * (a failed handler's message is released via `ChangeMessageVisibility` after\n * `releaseDelay`, default 0 s — pair the queue with a `RedrivePolicy`); the\n * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as\n * `attempts = count − 1`.\n *\n * **Version gate (§3.7).** Before the body is decoded the consumer reads the `bq-schema-version`\n * message attribute. A missing or blank value (empty or only ASCII whitespace) changes nothing; any\n * value other than the core's supported `SCHEMA_VERSION` (`\"2\"`, `\"x\"`, `\"01\"`, ...) rejects the\n * message undecoded through the same path as a non-conformant envelope — `onError` (with an error\n * naming the version, and an empty envelope since nothing was decoded) and the message is left\n * undeleted, so it is redelivered and the queue's `RedrivePolicy` moves it to the DLQ.\n *\n * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop\n * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`\n * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and\n * the merged set is bounded by SQS's **10-attribute limit** (contract attributes are seeded first,\n * so a rider only lands while headroom remains). On consume the inbound `MessageAttributes` are\n * surfaced as a `Record<string,string>` so the core's `otel` extract sees the `traceparent` and\n * links the consumer span as a child. A header-less publish is byte-identical. This mirrors the Go\n * `/sqs` and PHP `SqsTransport` wiring. GR-1: the wire envelope body is never touched.\n */\n\nimport {\n BabelQueueError,\n EnvelopeCodec,\n SCHEMA_VERSION,\n UnknownUrnError,\n UnknownUrnStrategy,\n annotate,\n} from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { sanitizeHeaders } from \"./headers.js\";\n\n/** SQS allows at most 10 user message attributes per message. */\nconst MAX_ATTRIBUTES = 10;\n\n/** The SQS ceiling for a `VisibilityTimeout` (12 hours, in seconds). */\nexport const MAX_VISIBILITY_TIMEOUT = 43_200;\n\n// --- Minimal SQS shapes (a structural subset of @aws-sdk/client-sqs) -----------\n\nexport interface SqsMessageAttributeValue {\n DataType: string;\n StringValue?: string;\n}\n\nexport interface SqsMessage {\n Body?: string;\n ReceiptHandle?: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n Attributes?: Record<string, string>;\n}\n\nexport interface SendMessageInput {\n QueueUrl: string;\n MessageBody: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n MessageGroupId?: string;\n MessageDeduplicationId?: string;\n}\n\nexport interface ReceiveMessageInput {\n QueueUrl: string;\n MaxNumberOfMessages?: number;\n WaitTimeSeconds?: number;\n VisibilityTimeout?: number;\n MessageAttributeNames?: string[];\n AttributeNames?: string[];\n}\n\n/**\n * The subset of the AWS SQS client this adapter calls. The aggregated `SQS` class\n * from `@aws-sdk/client-sqs` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface SqsApi {\n sendMessage(input: SendMessageInput): Promise<{ MessageId?: string } | unknown>;\n receiveMessage(input: ReceiveMessageInput): Promise<{ Messages?: SqsMessage[] }>;\n deleteMessage(input: { QueueUrl: string; ReceiptHandle: string }): Promise<unknown>;\n /**\n * The §3.5 release primitive. Optional so existing structural clients keep compiling; it is\n * required (checked at construction) when a consumer sets `releaseDelay` or the `release`\n * unknown-URN strategy explicitly. Without it the default handler-failure release degrades to\n * leaving the message for visibility-timeout redelivery. The aggregated `SQS` class from\n * `@aws-sdk/client-sqs` provides it.\n */\n changeMessageVisibility?(input: ChangeMessageVisibilityInput): Promise<unknown>;\n}\n\nexport interface ChangeMessageVisibilityInput {\n QueueUrl: string;\n ReceiptHandle: string;\n VisibilityTimeout: number;\n}\n\n// --- Attribute projection (contract §3.2) --------------------------------------\n\nconst str = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"String\",\n StringValue: String(value),\n});\nconst num = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"Number\",\n StringValue: String(value),\n});\n\n/**\n * Project the envelope's contract fields onto native SQS `MessageAttributes` — a\n * redundant, routable view of the body (the body stays authoritative).\n */\nexport function toMessageAttributes(envelope: Envelope): Record<string, SqsMessageAttributeValue> {\n const attrs: Record<string, SqsMessageAttributeValue> = {};\n if (envelope.job) attrs[\"bq-job\"] = str(envelope.job);\n if (envelope.trace_id) attrs[\"bq-trace-id\"] = str(envelope.trace_id);\n if (envelope.meta.id) attrs[\"bq-message-id\"] = str(envelope.meta.id);\n if (envelope.meta.schema_version != null) {\n attrs[\"bq-schema-version\"] = num(envelope.meta.schema_version);\n }\n if (envelope.meta.lang) attrs[\"bq-source-lang\"] = str(envelope.meta.lang);\n if (envelope.meta.created_at != null) {\n attrs[\"bq-created-at\"] = num(envelope.meta.created_at);\n }\n return attrs;\n}\n\n/**\n * Overlay the out-of-band `headers` onto the contract attribute projection as String\n * `MessageAttributes`, without overwriting an existing `bq-*` attribute (the contract wins a key\n * collision) and skipping blanks. Keys are merged in sorted order and the merge stops at the\n * 10-attribute SQS ceiling, so unbounded riders can never push the message past the limit (SQS\n * rejects the whole send otherwise) — the contract attributes are always preserved first. Mirrors\n * Go's `mergeAttributes` / PHP's `SqsTransport::attributes`.\n */\nexport function mergeAttributes(\n base: Record<string, SqsMessageAttributeValue>,\n headers: HeaderCarrier | null | undefined,\n): Record<string, SqsMessageAttributeValue> {\n const clean = sanitizeHeaders(headers);\n for (const key of Object.keys(clean).sort()) {\n if (key in base) continue; // never clobber a contract bq-* attribute\n if (Object.keys(base).length >= MAX_ATTRIBUTES) break; // respect the SQS 10-attribute cap\n base[key] = str(clean[key]);\n }\n return base;\n}\n\n/**\n * Map inbound SQS `MessageAttributes` onto a flat {@link HeaderCarrier} (the consume-side\n * counterpart of {@link mergeAttributes}), reading each attribute's `StringValue`. Returns an empty\n * object when there are none. Both the contract `bq-*` attributes and any out-of-band rider (e.g.\n * `traceparent`) surface — the core's `otel` extract reads only the keys it knows.\n */\nexport function headersOf(message: SqsMessage): HeaderCarrier {\n const attrs = message.MessageAttributes;\n const out: HeaderCarrier = {};\n if (!attrs) return out;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key]?.StringValue;\n if (value != null && value !== \"\") out[key] = value;\n }\n return out;\n}\n\n/** Blank = empty or only ASCII whitespace (space, \\t, \\n, \\v, \\f, \\r) — not `String.prototype.trim()`'s wider set. */\nconst BLANK_ASCII = /^[ \\t\\n\\v\\f\\r]*$/;\n\n/**\n * The `bq-schema-version` message attribute when it is present, non-blank and not the supported\n * version (compared against the core's `SCHEMA_VERSION`, exact string match: `\"01\"`, `\" 1\"`, `\"1.0\"`\n * are rejected). Blank means the empty string or only ASCII whitespace (the same set in every SDK,\n * GR-5); NBSP, U+0085, U+FEFF, U+3000 and the like are not blank. `undefined` when the message may\n * be decoded.\n */\nfunction unsupportedSchemaVersion(message: SqsMessage): string | undefined {\n const raw: unknown = message.MessageAttributes?.[\"bq-schema-version\"]?.StringValue;\n if (typeof raw !== \"string\" || BLANK_ASCII.test(raw)) return undefined;\n return raw === String(SCHEMA_VERSION) ? undefined : raw;\n}\n\nfunction queueNameFromUrl(queueUrl: string): string {\n const segments = queueUrl.split(\"/\").filter(Boolean);\n return segments[segments.length - 1] ?? \"default\";\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link SqsPublisher}. */\nexport interface SqsPublisherOptions {\n /** Treat the queue as FIFO: set `MessageGroupId` and (unless content dedup) `MessageDeduplicationId`. */\n fifo?: boolean;\n /** FIFO ordering group (default: the queue name from the URL). */\n messageGroupId?: string;\n /** Use the queue's content-based dedup instead of `meta.id` as the dedup id. */\n contentDedup?: boolean;\n}\n\n/** Options for {@link SqsPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /**\n * Out-of-band transport headers carried as String `MessageAttributes` beside the contract `bq-*`\n * attributes (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s `publish`.\n * The contract attributes win a key collision and the merged set is capped at SQS's 10-attribute\n * limit; an empty/omitted carrier leaves the publish unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one SQS queue with the §3 attribute projection. */\nexport class SqsPublisher {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly options: SqsPublisherOptions = {},\n ) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it as the message body with\n * the projected `MessageAttributes`, and return the message id (`meta.id`).\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: queueNameFromUrl(this.queueUrl),\n traceId: options.traceId,\n });\n const input: SendMessageInput = {\n QueueUrl: this.queueUrl,\n MessageBody: EnvelopeCodec.encode(envelope),\n MessageAttributes: mergeAttributes(toMessageAttributes(envelope), options.headers),\n };\n if (this.options.fifo) {\n input.MessageGroupId = this.options.messageGroupId ?? queueNameFromUrl(this.queueUrl);\n if (!this.options.contentDedup) {\n input.MessageDeduplicationId = envelope.meta.id;\n }\n }\n await this.client.sendMessage(input);\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw SQS message, and the out-of-band\n * {@link HeaderCarrier} read from the message's `MessageAttributes` (empty when there are none).\n * Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of\n * the producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: SqsMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link SqsConsumer}. */\nexport interface SqsConsumerOptions {\n /**\n * Called when a message's URN has no handler. Without `unknownUrn` the message is then deleted\n * (the original behaviour); with `unknownUrn` set it is a notification hook and the strategy\n * decides the message's fate.\n */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;\n /**\n * Unknown-URN strategy per contract §3.5 — `fail` | `delete` | `release` | `dead_letter`\n * ({@link UnknownUrnStrategy}). Omitted keeps the original behaviour (`onUnknownUrn` → delete,\n * otherwise report and leave for visibility-timeout redelivery, i.e. `fail`). `release` uses\n * `ChangeMessageVisibility` with {@link unknownUrnReleaseDelay}; `dead_letter` sends the annotated\n * envelope to {@link deadLetterQueueUrl} then deletes, degrading to `delete` when no DLQ is set.\n */\n unknownUrn?: string;\n /** Backoff (seconds) for the `release` unknown-URN strategy (default 0 = redeliver now). */\n unknownUrnReleaseDelay?: number;\n /**\n * Backoff before a failed message is redelivered. A failed handler always releases the message\n * via `ChangeMessageVisibility(ReceiptHandle, VisibilityTimeout)` (contract §3.5); this sets the\n * `VisibilityTimeout` — a number of seconds, or a function of the (reconciled) `attempts`\n * returning seconds (e.g. an exponential backoff). Clamped to `0…43200`. Default `0`: the message\n * is visible again immediately. A permanently failing handler therefore retries without pause\n * until the queue's `RedrivePolicy` (`maxReceiveCount`) moves it to the DLQ — configure one.\n */\n releaseDelay?: number | ((attempts: number) => number);\n /**\n * The cross-language `<queue>.dlq` URL for the `dead_letter` strategy (opt-in; default none). A\n * `.fifo` DLQ is sent with `MessageGroupId` (the source queue name) and `MessageDeduplicationId`\n * (`meta.id`).\n */\n deadLetterQueueUrl?: string | null;\n /**\n * Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), a throwing handler,\n * a throwing `onUnknownUrn` under an `unknownUrn` strategy, a failed release / dead-letter send, or\n * a failed delete after successful processing (an {@link SqsDeleteError} wrapping the broker\n * error; never released). The message is then left for visibility-timeout redelivery. The loop\n * never stops on these.\n */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: SqsMessage) => void;\n /** Long-poll wait seconds (default 20). */\n waitTimeSeconds?: number;\n /** Reservation window applied on receive (seconds). */\n visibilityTimeout?: number;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n}\n\n/**\n * Reported via `onError` when `DeleteMessage` fails for a message whose processing already succeeded\n * (a handler returned normally, or the unknown-URN strategy chose `delete` / `dead_letter`). The\n * broker error is `cause`. Distinct from a handler failure: the message is NOT released, so it is\n * redelivered only after its visibility timeout expires (at-least-once; dedupe on `meta.id` with the\n * idempotency helper if the side effect must not repeat).\n */\nexport class SqsDeleteError extends BabelQueueError {\n constructor(cause: unknown) {\n super(\"Failed to delete a processed SQS message; it will be redelivered after its visibility timeout.\");\n this.name = \"SqsDeleteError\";\n this.cause = cause;\n }\n}\n\n/**\n * Polls an SQS queue, decodes + validates each message, routes it to the handler\n * registered for its URN, and deletes it on success. A throwing handler's message is released via\n * `ChangeMessageVisibility` after `releaseDelay` (default 0 s, contract §3.5); if the release itself\n * fails the message is left for visibility-timeout redelivery (at-least-once);\n * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler. An unmapped URN\n * follows the `unknownUrn` strategy (`fail` | `delete` | `release` | `dead_letter`).\n */\nexport class SqsConsumer {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly handlers: BabelHandlers,\n private readonly options: SqsConsumerOptions = {},\n ) {\n const strategy = options.unknownUrn;\n if (strategy !== undefined && !(Object.values(UnknownUrnStrategy) as string[]).includes(strategy)) {\n throw new BabelQueueError(`Unknown unknownUrn strategy \"${strategy}\".`);\n }\n const needsRelease = options.releaseDelay != null || strategy === UnknownUrnStrategy.RELEASE;\n if (needsRelease && typeof client.changeMessageVisibility !== \"function\") {\n throw new BabelQueueError(\n \"SqsConsumer release requires a client with changeMessageVisibility (contract §3.5).\",\n );\n }\n }\n\n /** Receive one batch, route each message, delete the ones handled. Returns the batch size. */\n async poll(): Promise<number> {\n const input: ReceiveMessageInput = {\n QueueUrl: this.queueUrl,\n MaxNumberOfMessages: this.options.maxMessages ?? 10,\n WaitTimeSeconds: this.options.waitTimeSeconds ?? 20,\n MessageAttributeNames: [\"All\"],\n AttributeNames: [\"ApproximateReceiveCount\"],\n };\n if (this.options.visibilityTimeout != null) {\n input.VisibilityTimeout = this.options.visibilityTimeout;\n }\n const result = await this.client.receiveMessage(input);\n const messages = result.Messages ?? [];\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts (each poll long-polls, so this does not busy-loop). */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: SqsMessage): Promise<void> {\n // §3.7: gate on the bq-schema-version attribute before the body is decoded. The message is\n // not deleted, so SQS redelivers it and the queue's RedrivePolicy moves it to the DLQ.\n const rejectedVersion = unsupportedSchemaVersion(message);\n if (rejectedVersion !== undefined) {\n this.options.onError?.(\n new BabelQueueError(\n `Rejected a message from SQS with unsupported bq-schema-version \"${rejectedVersion}\" (supported: ${SCHEMA_VERSION}).`,\n ),\n {},\n message,\n );\n return;\n }\n\n const envelope = EnvelopeCodec.decode(message.Body ?? \"\");\n\n const receiveCount = message.Attributes?.[\"ApproximateReceiveCount\"];\n if (receiveCount !== undefined) {\n const native = Number.parseInt(receiveCount, 10) - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (Number.isFinite(native) && native > current) {\n envelope.attempts = native;\n }\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from SQS.\"),\n envelope,\n message,\n );\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n await this.unknown(urn, envelope as Envelope, message);\n return;\n }\n\n try {\n await handler(envelope, message, headersOf(message));\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n await this.guard(envelope, message, async () => {\n const delay = this.options.releaseDelay ?? 0;\n const attempts = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n await this.release(message, typeof delay === \"function\" ? delay(attempts) : delay);\n });\n return;\n }\n // Outside the handler's try: a failed delete is not a handler failure. It is reported as an\n // SqsDeleteError and the message is NOT released — releasing at the (default 0 s) backoff would\n // redeliver an already-processed message immediately; it returns on visibility expiry instead.\n await this.guard(envelope, message, () => this.deleteHandled(message));\n }\n\n /**\n * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a\n * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so\n * visibility expiry still redelivers it. Never lets the error stop the consume loop.\n */\n private async guard(envelope: IncomingEnvelope, message: SqsMessage, step: () => Promise<void>): Promise<void> {\n try {\n await step();\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n }\n }\n\n /** Apply the unknown-URN strategy (contract §3.5). */\n private async unknown(urn: string, envelope: Envelope, message: SqsMessage): Promise<void> {\n const strategy = this.options.unknownUrn;\n if (strategy === undefined) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.delete(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n return;\n }\n\n await this.guard(envelope, message, async () => {\n await this.options.onUnknownUrn?.(envelope, message);\n });\n switch (strategy) {\n case UnknownUrnStrategy.DELETE:\n await this.guard(envelope, message, () => this.deleteHandled(message));\n return;\n case UnknownUrnStrategy.RELEASE:\n await this.guard(envelope, message, () => this.release(message, this.options.unknownUrnReleaseDelay ?? 0));\n return;\n case UnknownUrnStrategy.DEAD_LETTER:\n await this.guard(envelope, message, async () => {\n await this.deadLetter(envelope, \"unknown_urn\");\n await this.deleteHandled(message);\n });\n return;\n default:\n // FAIL: surface and do NOT delete — visibility expiry redelivers, native redrive quarantines.\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n }\n\n /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */\n private async release(message: SqsMessage, seconds: number): Promise<void> {\n if (!message.ReceiptHandle || !this.client.changeMessageVisibility) return;\n const timeout = Number.isFinite(seconds)\n ? Math.min(MAX_VISIBILITY_TIMEOUT, Math.max(0, Math.floor(seconds)))\n : 0;\n await this.client.changeMessageVisibility({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n VisibilityTimeout: timeout,\n });\n }\n\n /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */\n private async deadLetter(envelope: Envelope, reason: string): Promise<void> {\n const dlq = this.options.deadLetterQueueUrl;\n if (!dlq) return;\n const source = envelope.meta?.queue ?? queueNameFromUrl(this.queueUrl);\n const annotated = annotate(envelope, reason, source, {\n attempts: envelope.attempts ?? 0,\n });\n const input: SendMessageInput = {\n QueueUrl: dlq,\n MessageBody: EnvelopeCodec.encode(annotated),\n MessageAttributes: toMessageAttributes(annotated),\n };\n if (dlq.endsWith(\".fifo\")) {\n // A FIFO DLQ (`<queue>.dlq.fifo`) rejects a send without a group; dedup on meta.id (§3.2).\n input.MessageGroupId = source;\n if (annotated.meta?.id) input.MessageDeduplicationId = annotated.meta.id;\n }\n await this.client.sendMessage(input);\n }\n\n /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */\n private async deleteHandled(message: SqsMessage): Promise<void> {\n try {\n await this.delete(message);\n } catch (error) {\n throw new SqsDeleteError(error);\n }\n }\n\n private async delete(message: SqsMessage): Promise<void> {\n if (!message.ReceiptHandle) return;\n await this.client.deleteMessage({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n });\n }\n}\n","/**\n * Pure, dependency-free helpers for the out-of-band transport-header seam (ADR-0028) — the Node\n * adapter mirror of Go's `sanitizeHeaders` and PHP's `Support\\Headers`. They fold an injected\n * {@link HeaderCarrier} (e.g. a W3C `traceparent`) onto a transport's metadata channel **without\n * clobbering** the contract headers it already carries.\n *\n * Headers ride beside the frozen wire envelope (GR-1), never inside it.\n */\n\nimport type { HeaderCarrier } from \"@babelqueue/core\";\n\n/**\n * Copy `headers`, dropping blank keys and blank values. Returns an empty object when nothing\n * survives, so a caller can treat the result as \"no headers\". A nullish input yields an empty\n * object.\n */\nexport function sanitizeHeaders(headers: HeaderCarrier | null | undefined): HeaderCarrier {\n const out: HeaderCarrier = {};\n if (!headers) return out;\n for (const key of Object.keys(headers)) {\n const value = headers[key];\n if (key === \"\" || value == null || value === \"\") continue;\n out[key] = value;\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6CA,kBAOO;;;ACpCA,SAAS,gBAAgB,SAA0D;AACxF,QAAM,MAAqB,CAAC;AAC5B,MAAI,CAAC,QAAS,QAAO;AACrB,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,QAAQ,QAAQ,GAAG;AACzB,QAAI,QAAQ,MAAM,SAAS,QAAQ,UAAU,GAAI;AACjD,QAAI,GAAG,IAAI;AAAA,EACb;AACA,SAAO;AACT;;;ADiCA,IAAM,iBAAiB;AAGhB,IAAM,yBAAyB;AA2DtC,IAAM,MAAM,CAAC,WAA8C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa,OAAO,KAAK;AAC3B;AACA,IAAM,MAAM,CAAC,WAA8C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa,OAAO,KAAK;AAC3B;AAMO,SAAS,oBAAoB,UAA8D;AAChG,QAAM,QAAkD,CAAC;AACzD,MAAI,SAAS,IAAK,OAAM,QAAQ,IAAI,IAAI,SAAS,GAAG;AACpD,MAAI,SAAS,SAAU,OAAM,aAAa,IAAI,IAAI,SAAS,QAAQ;AACnE,MAAI,SAAS,KAAK,GAAI,OAAM,eAAe,IAAI,IAAI,SAAS,KAAK,EAAE;AACnE,MAAI,SAAS,KAAK,kBAAkB,MAAM;AACxC,UAAM,mBAAmB,IAAI,IAAI,SAAS,KAAK,cAAc;AAAA,EAC/D;AACA,MAAI,SAAS,KAAK,KAAM,OAAM,gBAAgB,IAAI,IAAI,SAAS,KAAK,IAAI;AACxE,MAAI,SAAS,KAAK,cAAc,MAAM;AACpC,UAAM,eAAe,IAAI,IAAI,SAAS,KAAK,UAAU;AAAA,EACvD;AACA,SAAO;AACT;AAUO,SAAS,gBAC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KAAK,OAAO,YAAY,KAAK;AAAA,EACrC;AAAA;AAAA,EAGA,MAAc,cAAc,SAAoC;AAC9D,QAAI;AACF,YAAM,KAAK,OAAO,OAAO;AAAA,IAC3B,SAAS,OAAO;AACd,YAAM,IAAI,eAAe,KAAK;AAAA,IAChC;AAAA,EACF;AAAA,EAEA,MAAc,OAAO,SAAoC;AACvD,QAAI,CAAC,QAAQ,cAAe;AAC5B,UAAM,KAAK,OAAO,cAAc;AAAA,MAC9B,UAAU,KAAK;AAAA,MACf,eAAe,QAAQ;AAAA,IACzB,CAAC;AAAA,EACH;AACF;","names":[]}
package/dist/index.d.cts CHANGED
@@ -28,6 +28,13 @@ import { Envelope, HeaderCarrier, IncomingEnvelope, BabelQueueError } from '@bab
28
28
  * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as
29
29
  * `attempts = count − 1`.
30
30
  *
31
+ * **Version gate (§3.7).** Before the body is decoded the consumer reads the `bq-schema-version`
32
+ * message attribute. A missing or blank value (empty or only ASCII whitespace) changes nothing; any
33
+ * value other than the core's supported `SCHEMA_VERSION` (`"2"`, `"x"`, `"01"`, ...) rejects the
34
+ * message undecoded through the same path as a non-conformant envelope — `onError` (with an error
35
+ * naming the version, and an empty envelope since nothing was decoded) and the message is left
36
+ * undeleted, so it is redelivered and the queue's `RedrivePolicy` moves it to the DLQ.
37
+ *
31
38
  * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop
32
39
  * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`
33
40
  * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and
package/dist/index.d.ts CHANGED
@@ -28,6 +28,13 @@ import { Envelope, HeaderCarrier, IncomingEnvelope, BabelQueueError } from '@bab
28
28
  * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as
29
29
  * `attempts = count − 1`.
30
30
  *
31
+ * **Version gate (§3.7).** Before the body is decoded the consumer reads the `bq-schema-version`
32
+ * message attribute. A missing or blank value (empty or only ASCII whitespace) changes nothing; any
33
+ * value other than the core's supported `SCHEMA_VERSION` (`"2"`, `"x"`, `"01"`, ...) rejects the
34
+ * message undecoded through the same path as a non-conformant envelope — `onError` (with an error
35
+ * naming the version, and an empty envelope since nothing was decoded) and the message is left
36
+ * undeleted, so it is redelivered and the queue's `RedrivePolicy` moves it to the DLQ.
37
+ *
31
38
  * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop
32
39
  * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`
33
40
  * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and
package/dist/index.js CHANGED
@@ -1,5 +1,12 @@
1
1
  // src/index.ts
2
- import { BabelQueueError, EnvelopeCodec, UnknownUrnError, UnknownUrnStrategy, annotate } from "@babelqueue/core";
2
+ import {
3
+ BabelQueueError,
4
+ EnvelopeCodec,
5
+ SCHEMA_VERSION,
6
+ UnknownUrnError,
7
+ UnknownUrnStrategy,
8
+ annotate
9
+ } from "@babelqueue/core";
3
10
 
4
11
  // src/headers.ts
5
12
  function sanitizeHeaders(headers) {
@@ -57,6 +64,12 @@ function headersOf(message) {
57
64
  }
58
65
  return out;
59
66
  }
67
+ var BLANK_ASCII = /^[ \t\n\v\f\r]*$/;
68
+ function unsupportedSchemaVersion(message) {
69
+ const raw = message.MessageAttributes?.["bq-schema-version"]?.StringValue;
70
+ if (typeof raw !== "string" || BLANK_ASCII.test(raw)) return void 0;
71
+ return raw === String(SCHEMA_VERSION) ? void 0 : raw;
72
+ }
60
73
  function queueNameFromUrl(queueUrl) {
61
74
  const segments = queueUrl.split("/").filter(Boolean);
62
75
  return segments[segments.length - 1] ?? "default";
@@ -148,6 +161,17 @@ var SqsConsumer = class {
148
161
  }
149
162
  }
150
163
  async handle(message) {
164
+ const rejectedVersion = unsupportedSchemaVersion(message);
165
+ if (rejectedVersion !== void 0) {
166
+ this.options.onError?.(
167
+ new BabelQueueError(
168
+ `Rejected a message from SQS with unsupported bq-schema-version "${rejectedVersion}" (supported: ${SCHEMA_VERSION}).`
169
+ ),
170
+ {},
171
+ message
172
+ );
173
+ return;
174
+ }
151
175
  const envelope = EnvelopeCodec.decode(message.Body ?? "");
152
176
  const receiveCount = message.Attributes?.["ApproximateReceiveCount"];
153
177
  if (receiveCount !== void 0) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Amazon SQS adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Amazon SQS,\n * so an SQS-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the PHP/Laravel, Python, Go, Java and .NET SDKs.\n *\n * import { SQS } from \"@aws-sdk/client-sqs\";\n * import { SqsPublisher, SqsConsumer } from \"@babelqueue/sqs\";\n *\n * const sqs = new SQS({ region: \"eu-central-1\" });\n * const url = \"https://sqs.eu-central-1.amazonaws.com/123456789012/orders\";\n *\n * await new SqsPublisher(sqs, url).publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new SqsConsumer(sqs, url, {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §3 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native SQS `MessageAttributes`. The envelope is\n * unchanged (`schema_version` stays 1); SQS is purely additive. Retry is SQS-native\n * (a failed handler's message is released via `ChangeMessageVisibility` after\n * `releaseDelay`, default 0 s — pair the queue with a `RedrivePolicy`); the\n * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as\n * `attempts = count − 1`.\n *\n * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop\n * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`\n * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and\n * the merged set is bounded by SQS's **10-attribute limit** (contract attributes are seeded first,\n * so a rider only lands while headroom remains). On consume the inbound `MessageAttributes` are\n * surfaced as a `Record<string,string>` so the core's `otel` extract sees the `traceparent` and\n * links the consumer span as a child. A header-less publish is byte-identical. This mirrors the Go\n * `/sqs` and PHP `SqsTransport` wiring. GR-1: the wire envelope body is never touched.\n */\n\nimport { BabelQueueError, EnvelopeCodec, UnknownUrnError, UnknownUrnStrategy, annotate } from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { sanitizeHeaders } from \"./headers.js\";\n\n/** SQS allows at most 10 user message attributes per message. */\nconst MAX_ATTRIBUTES = 10;\n\n/** The SQS ceiling for a `VisibilityTimeout` (12 hours, in seconds). */\nexport const MAX_VISIBILITY_TIMEOUT = 43_200;\n\n// --- Minimal SQS shapes (a structural subset of @aws-sdk/client-sqs) -----------\n\nexport interface SqsMessageAttributeValue {\n DataType: string;\n StringValue?: string;\n}\n\nexport interface SqsMessage {\n Body?: string;\n ReceiptHandle?: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n Attributes?: Record<string, string>;\n}\n\nexport interface SendMessageInput {\n QueueUrl: string;\n MessageBody: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n MessageGroupId?: string;\n MessageDeduplicationId?: string;\n}\n\nexport interface ReceiveMessageInput {\n QueueUrl: string;\n MaxNumberOfMessages?: number;\n WaitTimeSeconds?: number;\n VisibilityTimeout?: number;\n MessageAttributeNames?: string[];\n AttributeNames?: string[];\n}\n\n/**\n * The subset of the AWS SQS client this adapter calls. The aggregated `SQS` class\n * from `@aws-sdk/client-sqs` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface SqsApi {\n sendMessage(input: SendMessageInput): Promise<{ MessageId?: string } | unknown>;\n receiveMessage(input: ReceiveMessageInput): Promise<{ Messages?: SqsMessage[] }>;\n deleteMessage(input: { QueueUrl: string; ReceiptHandle: string }): Promise<unknown>;\n /**\n * The §3.5 release primitive. Optional so existing structural clients keep compiling; it is\n * required (checked at construction) when a consumer sets `releaseDelay` or the `release`\n * unknown-URN strategy explicitly. Without it the default handler-failure release degrades to\n * leaving the message for visibility-timeout redelivery. The aggregated `SQS` class from\n * `@aws-sdk/client-sqs` provides it.\n */\n changeMessageVisibility?(input: ChangeMessageVisibilityInput): Promise<unknown>;\n}\n\nexport interface ChangeMessageVisibilityInput {\n QueueUrl: string;\n ReceiptHandle: string;\n VisibilityTimeout: number;\n}\n\n// --- Attribute projection (contract §3.2) --------------------------------------\n\nconst str = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"String\",\n StringValue: String(value),\n});\nconst num = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"Number\",\n StringValue: String(value),\n});\n\n/**\n * Project the envelope's contract fields onto native SQS `MessageAttributes` — a\n * redundant, routable view of the body (the body stays authoritative).\n */\nexport function toMessageAttributes(envelope: Envelope): Record<string, SqsMessageAttributeValue> {\n const attrs: Record<string, SqsMessageAttributeValue> = {};\n if (envelope.job) attrs[\"bq-job\"] = str(envelope.job);\n if (envelope.trace_id) attrs[\"bq-trace-id\"] = str(envelope.trace_id);\n if (envelope.meta.id) attrs[\"bq-message-id\"] = str(envelope.meta.id);\n if (envelope.meta.schema_version != null) {\n attrs[\"bq-schema-version\"] = num(envelope.meta.schema_version);\n }\n if (envelope.meta.lang) attrs[\"bq-source-lang\"] = str(envelope.meta.lang);\n if (envelope.meta.created_at != null) {\n attrs[\"bq-created-at\"] = num(envelope.meta.created_at);\n }\n return attrs;\n}\n\n/**\n * Overlay the out-of-band `headers` onto the contract attribute projection as String\n * `MessageAttributes`, without overwriting an existing `bq-*` attribute (the contract wins a key\n * collision) and skipping blanks. Keys are merged in sorted order and the merge stops at the\n * 10-attribute SQS ceiling, so unbounded riders can never push the message past the limit (SQS\n * rejects the whole send otherwise) — the contract attributes are always preserved first. Mirrors\n * Go's `mergeAttributes` / PHP's `SqsTransport::attributes`.\n */\nexport function mergeAttributes(\n base: Record<string, SqsMessageAttributeValue>,\n headers: HeaderCarrier | null | undefined,\n): Record<string, SqsMessageAttributeValue> {\n const clean = sanitizeHeaders(headers);\n for (const key of Object.keys(clean).sort()) {\n if (key in base) continue; // never clobber a contract bq-* attribute\n if (Object.keys(base).length >= MAX_ATTRIBUTES) break; // respect the SQS 10-attribute cap\n base[key] = str(clean[key]);\n }\n return base;\n}\n\n/**\n * Map inbound SQS `MessageAttributes` onto a flat {@link HeaderCarrier} (the consume-side\n * counterpart of {@link mergeAttributes}), reading each attribute's `StringValue`. Returns an empty\n * object when there are none. Both the contract `bq-*` attributes and any out-of-band rider (e.g.\n * `traceparent`) surface — the core's `otel` extract reads only the keys it knows.\n */\nexport function headersOf(message: SqsMessage): HeaderCarrier {\n const attrs = message.MessageAttributes;\n const out: HeaderCarrier = {};\n if (!attrs) return out;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key]?.StringValue;\n if (value != null && value !== \"\") out[key] = value;\n }\n return out;\n}\n\nfunction queueNameFromUrl(queueUrl: string): string {\n const segments = queueUrl.split(\"/\").filter(Boolean);\n return segments[segments.length - 1] ?? \"default\";\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link SqsPublisher}. */\nexport interface SqsPublisherOptions {\n /** Treat the queue as FIFO: set `MessageGroupId` and (unless content dedup) `MessageDeduplicationId`. */\n fifo?: boolean;\n /** FIFO ordering group (default: the queue name from the URL). */\n messageGroupId?: string;\n /** Use the queue's content-based dedup instead of `meta.id` as the dedup id. */\n contentDedup?: boolean;\n}\n\n/** Options for {@link SqsPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /**\n * Out-of-band transport headers carried as String `MessageAttributes` beside the contract `bq-*`\n * attributes (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s `publish`.\n * The contract attributes win a key collision and the merged set is capped at SQS's 10-attribute\n * limit; an empty/omitted carrier leaves the publish unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one SQS queue with the §3 attribute projection. */\nexport class SqsPublisher {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly options: SqsPublisherOptions = {},\n ) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it as the message body with\n * the projected `MessageAttributes`, and return the message id (`meta.id`).\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: queueNameFromUrl(this.queueUrl),\n traceId: options.traceId,\n });\n const input: SendMessageInput = {\n QueueUrl: this.queueUrl,\n MessageBody: EnvelopeCodec.encode(envelope),\n MessageAttributes: mergeAttributes(toMessageAttributes(envelope), options.headers),\n };\n if (this.options.fifo) {\n input.MessageGroupId = this.options.messageGroupId ?? queueNameFromUrl(this.queueUrl);\n if (!this.options.contentDedup) {\n input.MessageDeduplicationId = envelope.meta.id;\n }\n }\n await this.client.sendMessage(input);\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw SQS message, and the out-of-band\n * {@link HeaderCarrier} read from the message's `MessageAttributes` (empty when there are none).\n * Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of\n * the producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: SqsMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link SqsConsumer}. */\nexport interface SqsConsumerOptions {\n /**\n * Called when a message's URN has no handler. Without `unknownUrn` the message is then deleted\n * (the original behaviour); with `unknownUrn` set it is a notification hook and the strategy\n * decides the message's fate.\n */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;\n /**\n * Unknown-URN strategy per contract §3.5 — `fail` | `delete` | `release` | `dead_letter`\n * ({@link UnknownUrnStrategy}). Omitted keeps the original behaviour (`onUnknownUrn` → delete,\n * otherwise report and leave for visibility-timeout redelivery, i.e. `fail`). `release` uses\n * `ChangeMessageVisibility` with {@link unknownUrnReleaseDelay}; `dead_letter` sends the annotated\n * envelope to {@link deadLetterQueueUrl} then deletes, degrading to `delete` when no DLQ is set.\n */\n unknownUrn?: string;\n /** Backoff (seconds) for the `release` unknown-URN strategy (default 0 = redeliver now). */\n unknownUrnReleaseDelay?: number;\n /**\n * Backoff before a failed message is redelivered. A failed handler always releases the message\n * via `ChangeMessageVisibility(ReceiptHandle, VisibilityTimeout)` (contract §3.5); this sets the\n * `VisibilityTimeout` — a number of seconds, or a function of the (reconciled) `attempts`\n * returning seconds (e.g. an exponential backoff). Clamped to `0…43200`. Default `0`: the message\n * is visible again immediately. A permanently failing handler therefore retries without pause\n * until the queue's `RedrivePolicy` (`maxReceiveCount`) moves it to the DLQ — configure one.\n */\n releaseDelay?: number | ((attempts: number) => number);\n /**\n * The cross-language `<queue>.dlq` URL for the `dead_letter` strategy (opt-in; default none). A\n * `.fifo` DLQ is sent with `MessageGroupId` (the source queue name) and `MessageDeduplicationId`\n * (`meta.id`).\n */\n deadLetterQueueUrl?: string | null;\n /**\n * Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), a throwing handler,\n * a throwing `onUnknownUrn` under an `unknownUrn` strategy, a failed release / dead-letter send, or\n * a failed delete after successful processing (an {@link SqsDeleteError} wrapping the broker\n * error; never released). The message is then left for visibility-timeout redelivery. The loop\n * never stops on these.\n */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: SqsMessage) => void;\n /** Long-poll wait seconds (default 20). */\n waitTimeSeconds?: number;\n /** Reservation window applied on receive (seconds). */\n visibilityTimeout?: number;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n}\n\n/**\n * Reported via `onError` when `DeleteMessage` fails for a message whose processing already succeeded\n * (a handler returned normally, or the unknown-URN strategy chose `delete` / `dead_letter`). The\n * broker error is `cause`. Distinct from a handler failure: the message is NOT released, so it is\n * redelivered only after its visibility timeout expires (at-least-once; dedupe on `meta.id` with the\n * idempotency helper if the side effect must not repeat).\n */\nexport class SqsDeleteError extends BabelQueueError {\n constructor(cause: unknown) {\n super(\"Failed to delete a processed SQS message; it will be redelivered after its visibility timeout.\");\n this.name = \"SqsDeleteError\";\n this.cause = cause;\n }\n}\n\n/**\n * Polls an SQS queue, decodes + validates each message, routes it to the handler\n * registered for its URN, and deletes it on success. A throwing handler's message is released via\n * `ChangeMessageVisibility` after `releaseDelay` (default 0 s, contract §3.5); if the release itself\n * fails the message is left for visibility-timeout redelivery (at-least-once);\n * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler. An unmapped URN\n * follows the `unknownUrn` strategy (`fail` | `delete` | `release` | `dead_letter`).\n */\nexport class SqsConsumer {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly handlers: BabelHandlers,\n private readonly options: SqsConsumerOptions = {},\n ) {\n const strategy = options.unknownUrn;\n if (strategy !== undefined && !(Object.values(UnknownUrnStrategy) as string[]).includes(strategy)) {\n throw new BabelQueueError(`Unknown unknownUrn strategy \"${strategy}\".`);\n }\n const needsRelease = options.releaseDelay != null || strategy === UnknownUrnStrategy.RELEASE;\n if (needsRelease && typeof client.changeMessageVisibility !== \"function\") {\n throw new BabelQueueError(\n \"SqsConsumer release requires a client with changeMessageVisibility (contract §3.5).\",\n );\n }\n }\n\n /** Receive one batch, route each message, delete the ones handled. Returns the batch size. */\n async poll(): Promise<number> {\n const input: ReceiveMessageInput = {\n QueueUrl: this.queueUrl,\n MaxNumberOfMessages: this.options.maxMessages ?? 10,\n WaitTimeSeconds: this.options.waitTimeSeconds ?? 20,\n MessageAttributeNames: [\"All\"],\n AttributeNames: [\"ApproximateReceiveCount\"],\n };\n if (this.options.visibilityTimeout != null) {\n input.VisibilityTimeout = this.options.visibilityTimeout;\n }\n const result = await this.client.receiveMessage(input);\n const messages = result.Messages ?? [];\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts (each poll long-polls, so this does not busy-loop). */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: SqsMessage): Promise<void> {\n const envelope = EnvelopeCodec.decode(message.Body ?? \"\");\n\n const receiveCount = message.Attributes?.[\"ApproximateReceiveCount\"];\n if (receiveCount !== undefined) {\n const native = Number.parseInt(receiveCount, 10) - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (Number.isFinite(native) && native > current) {\n envelope.attempts = native;\n }\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from SQS.\"),\n envelope,\n message,\n );\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n await this.unknown(urn, envelope as Envelope, message);\n return;\n }\n\n try {\n await handler(envelope, message, headersOf(message));\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n await this.guard(envelope, message, async () => {\n const delay = this.options.releaseDelay ?? 0;\n const attempts = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n await this.release(message, typeof delay === \"function\" ? delay(attempts) : delay);\n });\n return;\n }\n // Outside the handler's try: a failed delete is not a handler failure. It is reported as an\n // SqsDeleteError and the message is NOT released — releasing at the (default 0 s) backoff would\n // redeliver an already-processed message immediately; it returns on visibility expiry instead.\n await this.guard(envelope, message, () => this.deleteHandled(message));\n }\n\n /**\n * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a\n * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so\n * visibility expiry still redelivers it. Never lets the error stop the consume loop.\n */\n private async guard(envelope: IncomingEnvelope, message: SqsMessage, step: () => Promise<void>): Promise<void> {\n try {\n await step();\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n }\n }\n\n /** Apply the unknown-URN strategy (contract §3.5). */\n private async unknown(urn: string, envelope: Envelope, message: SqsMessage): Promise<void> {\n const strategy = this.options.unknownUrn;\n if (strategy === undefined) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.delete(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n return;\n }\n\n await this.guard(envelope, message, async () => {\n await this.options.onUnknownUrn?.(envelope, message);\n });\n switch (strategy) {\n case UnknownUrnStrategy.DELETE:\n await this.guard(envelope, message, () => this.deleteHandled(message));\n return;\n case UnknownUrnStrategy.RELEASE:\n await this.guard(envelope, message, () => this.release(message, this.options.unknownUrnReleaseDelay ?? 0));\n return;\n case UnknownUrnStrategy.DEAD_LETTER:\n await this.guard(envelope, message, async () => {\n await this.deadLetter(envelope, \"unknown_urn\");\n await this.deleteHandled(message);\n });\n return;\n default:\n // FAIL: surface and do NOT delete — visibility expiry redelivers, native redrive quarantines.\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n }\n\n /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */\n private async release(message: SqsMessage, seconds: number): Promise<void> {\n if (!message.ReceiptHandle || !this.client.changeMessageVisibility) return;\n const timeout = Number.isFinite(seconds)\n ? Math.min(MAX_VISIBILITY_TIMEOUT, Math.max(0, Math.floor(seconds)))\n : 0;\n await this.client.changeMessageVisibility({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n VisibilityTimeout: timeout,\n });\n }\n\n /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */\n private async deadLetter(envelope: Envelope, reason: string): Promise<void> {\n const dlq = this.options.deadLetterQueueUrl;\n if (!dlq) return;\n const source = envelope.meta?.queue ?? queueNameFromUrl(this.queueUrl);\n const annotated = annotate(envelope, reason, source, {\n attempts: envelope.attempts ?? 0,\n });\n const input: SendMessageInput = {\n QueueUrl: dlq,\n MessageBody: EnvelopeCodec.encode(annotated),\n MessageAttributes: toMessageAttributes(annotated),\n };\n if (dlq.endsWith(\".fifo\")) {\n // A FIFO DLQ (`<queue>.dlq.fifo`) rejects a send without a group; dedup on meta.id (§3.2).\n input.MessageGroupId = source;\n if (annotated.meta?.id) input.MessageDeduplicationId = annotated.meta.id;\n }\n await this.client.sendMessage(input);\n }\n\n /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */\n private async deleteHandled(message: SqsMessage): Promise<void> {\n try {\n await this.delete(message);\n } catch (error) {\n throw new SqsDeleteError(error);\n }\n }\n\n private async delete(message: SqsMessage): Promise<void> {\n if (!message.ReceiptHandle) return;\n await this.client.deleteMessage({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n });\n }\n}\n","/**\n * Pure, dependency-free helpers for the out-of-band transport-header seam (ADR-0028) — the Node\n * adapter mirror of Go's `sanitizeHeaders` and PHP's `Support\\Headers`. They fold an injected\n * {@link HeaderCarrier} (e.g. a W3C `traceparent`) onto a transport's metadata channel **without\n * clobbering** the contract headers it already carries.\n *\n * Headers ride beside the frozen wire envelope (GR-1), never inside it.\n */\n\nimport type { HeaderCarrier } from \"@babelqueue/core\";\n\n/**\n * Copy `headers`, dropping blank keys and blank values. Returns an empty object when nothing\n * survives, so a caller can treat the result as \"no headers\". A nullish input yields an empty\n * object.\n */\nexport function sanitizeHeaders(headers: HeaderCarrier | null | undefined): HeaderCarrier {\n const out: HeaderCarrier = {};\n if (!headers) return out;\n for (const key of Object.keys(headers)) {\n const value = headers[key];\n if (key === \"\" || value == null || value === \"\") continue;\n out[key] = value;\n }\n return out;\n}\n"],"mappings":";AAsCA,SAAS,iBAAiB,eAAe,iBAAiB,oBAAoB,gBAAgB;;;ACtBvF,SAAS,gBAAgB,SAA0D;AACxF,QAAM,MAAqB,CAAC;AAC5B,MAAI,CAAC,QAAS,QAAO;AACrB,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,QAAQ,QAAQ,GAAG;AACzB,QAAI,QAAQ,MAAM,SAAS,QAAQ,UAAU,GAAI;AACjD,QAAI,GAAG,IAAI;AAAA,EACb;AACA,SA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AAQ;AACrE,UAAM,YAAY,SAAS,UAAU,QAAQ,QAAQ;AAAA,MACnD,UAAU,SAAS,YAAY;AAAA,IACjC,CAAC;AACD,UAAM,QAA0B;AAAA,MAC9B,UAAU;AAAA,MACV,aAAa,cAAc,OAAO,SAAS;AAAA,MAC3C,mBAAmB,oBAAoB,SAAS;AAAA,IAClD;AACA,QAAI,IAAI,SAAS,OAAO,GAAG;AAEzB,YAAM,iBAAiB;AACvB,UAAI,UAAU,MAAM,GAAI,OAAM,yBAAyB,UAAU,KAAK;AAAA,IACxE;AACA,UAAM,KAAK,OAAO,YAAY,KAAK;AAAA,EACrC;AAAA;AAAA,EAGA,MAAc,cAAc,SAAoC;AAC9D,QAAI;AACF,YAAM,KAAK,OAAO,OAAO;AAAA,IAC3B,SAAS,OAAO;AACd,YAAM,IAAI,eAAe,KAAK;AAAA,IAChC;AAAA,EACF;AAAA,EAEA,MAAc,OAAO,SAAoC;AACvD,QAAI,CAAC,QAAQ,cAAe;AAC5B,UAAM,KAAK,OAAO,cAAc;AAAA,MAC9B,UAAU,KAAK;AAAA,MACf,eAAe,QAAQ;AAAA,IACzB,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Amazon SQS adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Amazon SQS,\n * so an SQS-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the PHP/Laravel, Python, Go, Java and .NET SDKs.\n *\n * import { SQS } from \"@aws-sdk/client-sqs\";\n * import { SqsPublisher, SqsConsumer } from \"@babelqueue/sqs\";\n *\n * const sqs = new SQS({ region: \"eu-central-1\" });\n * const url = \"https://sqs.eu-central-1.amazonaws.com/123456789012/orders\";\n *\n * await new SqsPublisher(sqs, url).publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new SqsConsumer(sqs, url, {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §3 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native SQS `MessageAttributes`. The envelope is\n * unchanged (`schema_version` stays 1); SQS is purely additive. Retry is SQS-native\n * (a failed handler's message is released via `ChangeMessageVisibility` after\n * `releaseDelay`, default 0 s — pair the queue with a `RedrivePolicy`); the\n * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as\n * `attempts = count − 1`.\n *\n * **Version gate (§3.7).** Before the body is decoded the consumer reads the `bq-schema-version`\n * message attribute. A missing or blank value (empty or only ASCII whitespace) changes nothing; any\n * value other than the core's supported `SCHEMA_VERSION` (`\"2\"`, `\"x\"`, `\"01\"`, ...) rejects the\n * message undecoded through the same path as a non-conformant envelope — `onError` (with an error\n * naming the version, and an empty envelope since nothing was decoded) and the message is left\n * undeleted, so it is redelivered and the queue's `RedrivePolicy` moves it to the DLQ.\n *\n * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop\n * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`\n * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and\n * the merged set is bounded by SQS's **10-attribute limit** (contract attributes are seeded first,\n * so a rider only lands while headroom remains). On consume the inbound `MessageAttributes` are\n * surfaced as a `Record<string,string>` so the core's `otel` extract sees the `traceparent` and\n * links the consumer span as a child. A header-less publish is byte-identical. This mirrors the Go\n * `/sqs` and PHP `SqsTransport` wiring. GR-1: the wire envelope body is never touched.\n */\n\nimport {\n BabelQueueError,\n EnvelopeCodec,\n SCHEMA_VERSION,\n UnknownUrnError,\n UnknownUrnStrategy,\n annotate,\n} from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { sanitizeHeaders } from \"./headers.js\";\n\n/** SQS allows at most 10 user message attributes per message. */\nconst MAX_ATTRIBUTES = 10;\n\n/** The SQS ceiling for a `VisibilityTimeout` (12 hours, in seconds). */\nexport const MAX_VISIBILITY_TIMEOUT = 43_200;\n\n// --- Minimal SQS shapes (a structural subset of @aws-sdk/client-sqs) -----------\n\nexport interface SqsMessageAttributeValue {\n DataType: string;\n StringValue?: string;\n}\n\nexport interface SqsMessage {\n Body?: string;\n ReceiptHandle?: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n Attributes?: Record<string, string>;\n}\n\nexport interface SendMessageInput {\n QueueUrl: string;\n MessageBody: string;\n MessageAttributes?: Record<string, SqsMessageAttributeValue>;\n MessageGroupId?: string;\n MessageDeduplicationId?: string;\n}\n\nexport interface ReceiveMessageInput {\n QueueUrl: string;\n MaxNumberOfMessages?: number;\n WaitTimeSeconds?: number;\n VisibilityTimeout?: number;\n MessageAttributeNames?: string[];\n AttributeNames?: string[];\n}\n\n/**\n * The subset of the AWS SQS client this adapter calls. The aggregated `SQS` class\n * from `@aws-sdk/client-sqs` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface SqsApi {\n sendMessage(input: SendMessageInput): Promise<{ MessageId?: string } | unknown>;\n receiveMessage(input: ReceiveMessageInput): Promise<{ Messages?: SqsMessage[] }>;\n deleteMessage(input: { QueueUrl: string; ReceiptHandle: string }): Promise<unknown>;\n /**\n * The §3.5 release primitive. Optional so existing structural clients keep compiling; it is\n * required (checked at construction) when a consumer sets `releaseDelay` or the `release`\n * unknown-URN strategy explicitly. Without it the default handler-failure release degrades to\n * leaving the message for visibility-timeout redelivery. The aggregated `SQS` class from\n * `@aws-sdk/client-sqs` provides it.\n */\n changeMessageVisibility?(input: ChangeMessageVisibilityInput): Promise<unknown>;\n}\n\nexport interface ChangeMessageVisibilityInput {\n QueueUrl: string;\n ReceiptHandle: string;\n VisibilityTimeout: number;\n}\n\n// --- Attribute projection (contract §3.2) --------------------------------------\n\nconst str = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"String\",\n StringValue: String(value),\n});\nconst num = (value: unknown): SqsMessageAttributeValue => ({\n DataType: \"Number\",\n StringValue: String(value),\n});\n\n/**\n * Project the envelope's contract fields onto native SQS `MessageAttributes` — a\n * redundant, routable view of the body (the body stays authoritative).\n */\nexport function toMessageAttributes(envelope: Envelope): Record<string, SqsMessageAttributeValue> {\n const attrs: Record<string, SqsMessageAttributeValue> = {};\n if (envelope.job) attrs[\"bq-job\"] = str(envelope.job);\n if (envelope.trace_id) attrs[\"bq-trace-id\"] = str(envelope.trace_id);\n if (envelope.meta.id) attrs[\"bq-message-id\"] = str(envelope.meta.id);\n if (envelope.meta.schema_version != null) {\n attrs[\"bq-schema-version\"] = num(envelope.meta.schema_version);\n }\n if (envelope.meta.lang) attrs[\"bq-source-lang\"] = str(envelope.meta.lang);\n if (envelope.meta.created_at != null) {\n attrs[\"bq-created-at\"] = num(envelope.meta.created_at);\n }\n return attrs;\n}\n\n/**\n * Overlay the out-of-band `headers` onto the contract attribute projection as String\n * `MessageAttributes`, without overwriting an existing `bq-*` attribute (the contract wins a key\n * collision) and skipping blanks. Keys are merged in sorted order and the merge stops at the\n * 10-attribute SQS ceiling, so unbounded riders can never push the message past the limit (SQS\n * rejects the whole send otherwise) — the contract attributes are always preserved first. Mirrors\n * Go's `mergeAttributes` / PHP's `SqsTransport::attributes`.\n */\nexport function mergeAttributes(\n base: Record<string, SqsMessageAttributeValue>,\n headers: HeaderCarrier | null | undefined,\n): Record<string, SqsMessageAttributeValue> {\n const clean = sanitizeHeaders(headers);\n for (const key of Object.keys(clean).sort()) {\n if (key in base) continue; // never clobber a contract bq-* attribute\n if (Object.keys(base).length >= MAX_ATTRIBUTES) break; // respect the SQS 10-attribute cap\n base[key] = str(clean[key]);\n }\n return base;\n}\n\n/**\n * Map inbound SQS `MessageAttributes` onto a flat {@link HeaderCarrier} (the consume-side\n * counterpart of {@link mergeAttributes}), reading each attribute's `StringValue`. Returns an empty\n * object when there are none. Both the contract `bq-*` attributes and any out-of-band rider (e.g.\n * `traceparent`) surface — the core's `otel` extract reads only the keys it knows.\n */\nexport function headersOf(message: SqsMessage): HeaderCarrier {\n const attrs = message.MessageAttributes;\n const out: HeaderCarrier = {};\n if (!attrs) return out;\n for (const key of Object.keys(attrs)) {\n const value = attrs[key]?.StringValue;\n if (value != null && value !== \"\") out[key] = value;\n }\n return out;\n}\n\n/** Blank = empty or only ASCII whitespace (space, \\t, \\n, \\v, \\f, \\r) — not `String.prototype.trim()`'s wider set. */\nconst BLANK_ASCII = /^[ \\t\\n\\v\\f\\r]*$/;\n\n/**\n * The `bq-schema-version` message attribute when it is present, non-blank and not the supported\n * version (compared against the core's `SCHEMA_VERSION`, exact string match: `\"01\"`, `\" 1\"`, `\"1.0\"`\n * are rejected). Blank means the empty string or only ASCII whitespace (the same set in every SDK,\n * GR-5); NBSP, U+0085, U+FEFF, U+3000 and the like are not blank. `undefined` when the message may\n * be decoded.\n */\nfunction unsupportedSchemaVersion(message: SqsMessage): string | undefined {\n const raw: unknown = message.MessageAttributes?.[\"bq-schema-version\"]?.StringValue;\n if (typeof raw !== \"string\" || BLANK_ASCII.test(raw)) return undefined;\n return raw === String(SCHEMA_VERSION) ? undefined : raw;\n}\n\nfunction queueNameFromUrl(queueUrl: string): string {\n const segments = queueUrl.split(\"/\").filter(Boolean);\n return segments[segments.length - 1] ?? \"default\";\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link SqsPublisher}. */\nexport interface SqsPublisherOptions {\n /** Treat the queue as FIFO: set `MessageGroupId` and (unless content dedup) `MessageDeduplicationId`. */\n fifo?: boolean;\n /** FIFO ordering group (default: the queue name from the URL). */\n messageGroupId?: string;\n /** Use the queue's content-based dedup instead of `meta.id` as the dedup id. */\n contentDedup?: boolean;\n}\n\n/** Options for {@link SqsPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /**\n * Out-of-band transport headers carried as String `MessageAttributes` beside the contract `bq-*`\n * attributes (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s `publish`.\n * The contract attributes win a key collision and the merged set is capped at SQS's 10-attribute\n * limit; an empty/omitted carrier leaves the publish unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one SQS queue with the §3 attribute projection. */\nexport class SqsPublisher {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly options: SqsPublisherOptions = {},\n ) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it as the message body with\n * the projected `MessageAttributes`, and return the message id (`meta.id`).\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: queueNameFromUrl(this.queueUrl),\n traceId: options.traceId,\n });\n const input: SendMessageInput = {\n QueueUrl: this.queueUrl,\n MessageBody: EnvelopeCodec.encode(envelope),\n MessageAttributes: mergeAttributes(toMessageAttributes(envelope), options.headers),\n };\n if (this.options.fifo) {\n input.MessageGroupId = this.options.messageGroupId ?? queueNameFromUrl(this.queueUrl);\n if (!this.options.contentDedup) {\n input.MessageDeduplicationId = envelope.meta.id;\n }\n }\n await this.client.sendMessage(input);\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw SQS message, and the out-of-band\n * {@link HeaderCarrier} read from the message's `MessageAttributes` (empty when there are none).\n * Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of\n * the producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: SqsMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link SqsConsumer}. */\nexport interface SqsConsumerOptions {\n /**\n * Called when a message's URN has no handler. Without `unknownUrn` the message is then deleted\n * (the original behaviour); with `unknownUrn` set it is a notification hook and the strategy\n * decides the message's fate.\n */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;\n /**\n * Unknown-URN strategy per contract §3.5 — `fail` | `delete` | `release` | `dead_letter`\n * ({@link UnknownUrnStrategy}). Omitted keeps the original behaviour (`onUnknownUrn` → delete,\n * otherwise report and leave for visibility-timeout redelivery, i.e. `fail`). `release` uses\n * `ChangeMessageVisibility` with {@link unknownUrnReleaseDelay}; `dead_letter` sends the annotated\n * envelope to {@link deadLetterQueueUrl} then deletes, degrading to `delete` when no DLQ is set.\n */\n unknownUrn?: string;\n /** Backoff (seconds) for the `release` unknown-URN strategy (default 0 = redeliver now). */\n unknownUrnReleaseDelay?: number;\n /**\n * Backoff before a failed message is redelivered. A failed handler always releases the message\n * via `ChangeMessageVisibility(ReceiptHandle, VisibilityTimeout)` (contract §3.5); this sets the\n * `VisibilityTimeout` — a number of seconds, or a function of the (reconciled) `attempts`\n * returning seconds (e.g. an exponential backoff). Clamped to `0…43200`. Default `0`: the message\n * is visible again immediately. A permanently failing handler therefore retries without pause\n * until the queue's `RedrivePolicy` (`maxReceiveCount`) moves it to the DLQ — configure one.\n */\n releaseDelay?: number | ((attempts: number) => number);\n /**\n * The cross-language `<queue>.dlq` URL for the `dead_letter` strategy (opt-in; default none). A\n * `.fifo` DLQ is sent with `MessageGroupId` (the source queue name) and `MessageDeduplicationId`\n * (`meta.id`).\n */\n deadLetterQueueUrl?: string | null;\n /**\n * Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), a throwing handler,\n * a throwing `onUnknownUrn` under an `unknownUrn` strategy, a failed release / dead-letter send, or\n * a failed delete after successful processing (an {@link SqsDeleteError} wrapping the broker\n * error; never released). The message is then left for visibility-timeout redelivery. The loop\n * never stops on these.\n */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: SqsMessage) => void;\n /** Long-poll wait seconds (default 20). */\n waitTimeSeconds?: number;\n /** Reservation window applied on receive (seconds). */\n visibilityTimeout?: number;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n}\n\n/**\n * Reported via `onError` when `DeleteMessage` fails for a message whose processing already succeeded\n * (a handler returned normally, or the unknown-URN strategy chose `delete` / `dead_letter`). The\n * broker error is `cause`. Distinct from a handler failure: the message is NOT released, so it is\n * redelivered only after its visibility timeout expires (at-least-once; dedupe on `meta.id` with the\n * idempotency helper if the side effect must not repeat).\n */\nexport class SqsDeleteError extends BabelQueueError {\n constructor(cause: unknown) {\n super(\"Failed to delete a processed SQS message; it will be redelivered after its visibility timeout.\");\n this.name = \"SqsDeleteError\";\n this.cause = cause;\n }\n}\n\n/**\n * Polls an SQS queue, decodes + validates each message, routes it to the handler\n * registered for its URN, and deletes it on success. A throwing handler's message is released via\n * `ChangeMessageVisibility` after `releaseDelay` (default 0 s, contract §3.5); if the release itself\n * fails the message is left for visibility-timeout redelivery (at-least-once);\n * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler. An unmapped URN\n * follows the `unknownUrn` strategy (`fail` | `delete` | `release` | `dead_letter`).\n */\nexport class SqsConsumer {\n constructor(\n private readonly client: SqsApi,\n private readonly queueUrl: string,\n private readonly handlers: BabelHandlers,\n private readonly options: SqsConsumerOptions = {},\n ) {\n const strategy = options.unknownUrn;\n if (strategy !== undefined && !(Object.values(UnknownUrnStrategy) as string[]).includes(strategy)) {\n throw new BabelQueueError(`Unknown unknownUrn strategy \"${strategy}\".`);\n }\n const needsRelease = options.releaseDelay != null || strategy === UnknownUrnStrategy.RELEASE;\n if (needsRelease && typeof client.changeMessageVisibility !== \"function\") {\n throw new BabelQueueError(\n \"SqsConsumer release requires a client with changeMessageVisibility (contract §3.5).\",\n );\n }\n }\n\n /** Receive one batch, route each message, delete the ones handled. Returns the batch size. */\n async poll(): Promise<number> {\n const input: ReceiveMessageInput = {\n QueueUrl: this.queueUrl,\n MaxNumberOfMessages: this.options.maxMessages ?? 10,\n WaitTimeSeconds: this.options.waitTimeSeconds ?? 20,\n MessageAttributeNames: [\"All\"],\n AttributeNames: [\"ApproximateReceiveCount\"],\n };\n if (this.options.visibilityTimeout != null) {\n input.VisibilityTimeout = this.options.visibilityTimeout;\n }\n const result = await this.client.receiveMessage(input);\n const messages = result.Messages ?? [];\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts (each poll long-polls, so this does not busy-loop). */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: SqsMessage): Promise<void> {\n // §3.7: gate on the bq-schema-version attribute before the body is decoded. The message is\n // not deleted, so SQS redelivers it and the queue's RedrivePolicy moves it to the DLQ.\n const rejectedVersion = unsupportedSchemaVersion(message);\n if (rejectedVersion !== undefined) {\n this.options.onError?.(\n new BabelQueueError(\n `Rejected a message from SQS with unsupported bq-schema-version \"${rejectedVersion}\" (supported: ${SCHEMA_VERSION}).`,\n ),\n {},\n message,\n );\n return;\n }\n\n const envelope = EnvelopeCodec.decode(message.Body ?? \"\");\n\n const receiveCount = message.Attributes?.[\"ApproximateReceiveCount\"];\n if (receiveCount !== undefined) {\n const native = Number.parseInt(receiveCount, 10) - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (Number.isFinite(native) && native > current) {\n envelope.attempts = native;\n }\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from SQS.\"),\n envelope,\n message,\n );\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n await this.unknown(urn, envelope as Envelope, message);\n return;\n }\n\n try {\n await handler(envelope, message, headersOf(message));\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n await this.guard(envelope, message, async () => {\n const delay = this.options.releaseDelay ?? 0;\n const attempts = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n await this.release(message, typeof delay === \"function\" ? delay(attempts) : delay);\n });\n return;\n }\n // Outside the handler's try: a failed delete is not a handler failure. It is reported as an\n // SqsDeleteError and the message is NOT released — releasing at the (default 0 s) backoff would\n // redeliver an already-processed message immediately; it returns on visibility expiry instead.\n await this.guard(envelope, message, () => this.deleteHandled(message));\n }\n\n /**\n * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a\n * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so\n * visibility expiry still redelivers it. Never lets the error stop the consume loop.\n */\n private async guard(envelope: IncomingEnvelope, message: SqsMessage, step: () => Promise<void>): Promise<void> {\n try {\n await step();\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n }\n }\n\n /** Apply the unknown-URN strategy (contract §3.5). */\n private async unknown(urn: string, envelope: Envelope, message: SqsMessage): Promise<void> {\n const strategy = this.options.unknownUrn;\n if (strategy === undefined) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.delete(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n return;\n }\n\n await this.guard(envelope, message, async () => {\n await this.options.onUnknownUrn?.(envelope, message);\n });\n switch (strategy) {\n case UnknownUrnStrategy.DELETE:\n await this.guard(envelope, message, () => this.deleteHandled(message));\n return;\n case UnknownUrnStrategy.RELEASE:\n await this.guard(envelope, message, () => this.release(message, this.options.unknownUrnReleaseDelay ?? 0));\n return;\n case UnknownUrnStrategy.DEAD_LETTER:\n await this.guard(envelope, message, async () => {\n await this.deadLetter(envelope, \"unknown_urn\");\n await this.deleteHandled(message);\n });\n return;\n default:\n // FAIL: surface and do NOT delete — visibility expiry redelivers, native redrive quarantines.\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n }\n }\n\n /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */\n private async release(message: SqsMessage, seconds: number): Promise<void> {\n if (!message.ReceiptHandle || !this.client.changeMessageVisibility) return;\n const timeout = Number.isFinite(seconds)\n ? Math.min(MAX_VISIBILITY_TIMEOUT, Math.max(0, Math.floor(seconds)))\n : 0;\n await this.client.changeMessageVisibility({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n VisibilityTimeout: timeout,\n });\n }\n\n /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */\n private async deadLetter(envelope: Envelope, reason: string): Promise<void> {\n const dlq = this.options.deadLetterQueueUrl;\n if (!dlq) return;\n const source = envelope.meta?.queue ?? queueNameFromUrl(this.queueUrl);\n const annotated = annotate(envelope, reason, source, {\n attempts: envelope.attempts ?? 0,\n });\n const input: SendMessageInput = {\n QueueUrl: dlq,\n MessageBody: EnvelopeCodec.encode(annotated),\n MessageAttributes: toMessageAttributes(annotated),\n };\n if (dlq.endsWith(\".fifo\")) {\n // A FIFO DLQ (`<queue>.dlq.fifo`) rejects a send without a group; dedup on meta.id (§3.2).\n input.MessageGroupId = source;\n if (annotated.meta?.id) input.MessageDeduplicationId = annotated.meta.id;\n }\n await this.client.sendMessage(input);\n }\n\n /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */\n private async deleteHandled(message: SqsMessage): Promise<void> {\n try {\n await this.delete(message);\n } catch (error) {\n throw new SqsDeleteError(error);\n }\n }\n\n private async delete(message: SqsMessage): Promise<void> {\n if (!message.ReceiptHandle) return;\n await this.client.deleteMessage({\n QueueUrl: this.queueUrl,\n ReceiptHandle: message.ReceiptHandle,\n });\n }\n}\n","/**\n * Pure, dependency-free helpers for the out-of-band transport-header seam (ADR-0028) — the Node\n * adapter mirror of Go's `sanitizeHeaders` and PHP's `Support\\Headers`. They fold an injected\n * {@link HeaderCarrier} (e.g. a W3C `traceparent`) onto a transport's metadata channel **without\n * clobbering** the contract headers it already carries.\n *\n * Headers ride beside the frozen wire envelope (GR-1), never inside it.\n */\n\nimport type { HeaderCarrier } from \"@babelqueue/core\";\n\n/**\n * Copy `headers`, dropping blank keys and blank values. Returns an empty object when nothing\n * survives, so a caller can treat the result as \"no headers\". A nullish input yields an empty\n * object.\n */\nexport function sanitizeHeaders(headers: HeaderCarrier | null | undefined): HeaderCarrier {\n const out: HeaderCarrier = {};\n if (!headers) return out;\n for (const key of Object.keys(headers)) {\n const value = headers[key];\n if (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AoC;AAC9D,QAAI;AACF,YAAM,KAAK,OAAO,OAAO;AAAA,IAC3B,SAAS,OAAO;AACd,YAAM,IAAI,eAAe,KAAK;AAAA,IAChC;AAAA,EACF;AAAA,EAEA,MAAc,OAAO,SAAoC;AACvD,QAAI,CAAC,QAAQ,cAAe;AAC5B,UAAM,KAAK,OAAO,cAAc;AAAA,MAC9B,UAAU,KAAK;AAAA,MACf,eAAe,QAAQ;AAAA,IACzB,CAAC;AAAA,EACH;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelqueue/sqs",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Amazon SQS adapter for BabelQueue — canonical-envelope publisher and a URN-routed consumer.",
5
5
  "keywords": [
6
6
  "babelqueue",
@@ -20,7 +20,7 @@
20
20
  "directory": "packages/sqs"
21
21
  },
22
22
  "license": "MIT",
23
- "author": "Muhammet Şafak <info@muhammetsafak.com.tr>",
23
+ "author": "Muhammet Şafak <info@muhammetsafak.com>",
24
24
  "type": "module",
25
25
  "exports": {
26
26
  ".": {