@babelqueue/sqs 1.1.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
@@ -54,11 +54,43 @@ For LocalStack/ElasticMQ, point the `SQS` client's `endpoint` there.
54
54
  | `meta.created_at` | `MessageAttributes.bq-created-at` (Number, ms) |
55
55
  | `attempts` | reconciled to `ApproximateReceiveCount − 1` on receive |
56
56
  | reserve / ack | visibility timeout → `DeleteMessage` |
57
-
58
- Retry is **SQS-native**: a throwing handler leaves the message undeleted, so SQS
59
- redelivers it after the visibility timeout (at-least-once). The loop never stops on a
60
- bad message — use `onError` / `onUnknownUrn` to observe. The envelope is unchanged
61
- (`schema_version` stays `1`); SQS is purely additive.
57
+ | release (nack) | `ChangeMessageVisibility(ReceiptHandle, VisibilityTimeout = releaseDelay)` |
58
+
59
+ Retry is **SQS-native** (contract §3.5): a throwing handler's message is never deleted;
60
+ it is released with `ChangeMessageVisibility`, so SQS redelivers it after
61
+ `releaseDelay` seconds (**default `0`** — visible again immediately; a number or a
62
+ function of `attempts`, clamped to `0…43200`). If the release call itself fails, the
63
+ error goes to `onError` and the message is redelivered after the visibility timeout
64
+ (at-least-once). A `DeleteMessage` that fails *after* a successful handler is not a
65
+ handler failure: it reaches `onError` as an `SqsDeleteError` (broker error in `cause`)
66
+ and the message is **not** released — it returns only after its visibility timeout, so
67
+ dedupe on `meta.id` if the side effect must not repeat. The loop never stops on a bad message — use `onError` /
68
+ `onUnknownUrn` to observe. The envelope is unchanged (`schema_version` stays `1`); SQS
69
+ is purely additive.
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
+
77
+ > **Poison messages — configure a `RedrivePolicy`.** With the `0 s` default, a handler
78
+ > that always fails is retried back-to-back until the queue's native `RedrivePolicy`
79
+ > (`maxReceiveCount`) moves the message to its dead-letter queue. Without one, such a
80
+ > message loops forever. Give every consumed queue a `RedrivePolicy` (e.g.
81
+ > `maxReceiveCount` 3–5 → `<queue>.dlq`), and/or pass a backoff:
82
+ >
83
+ > ```ts
84
+ > new SqsConsumer(sqs, url, handlers, {
85
+ > releaseDelay: (attempts) => Math.min(2 ** attempts * 5, 900),
86
+ > });
87
+ > ```
88
+
89
+ An unmapped URN follows `unknownUrn`: `fail` (report, leave), `delete`, `release`
90
+ (`ChangeMessageVisibility` after `unknownUrnReleaseDelay`, default `0`) or
91
+ `dead_letter` (annotated envelope to the opt-in `deadLetterQueueUrl`, then delete; a
92
+ `.fifo` DLQ gets `MessageGroupId` + `MessageDeduplicationId`). Without `unknownUrn`,
93
+ `onUnknownUrn` is called and the message deleted, or — with no hook — reported and left.
62
94
 
63
95
  ## Test
64
96
 
package/dist/index.cjs CHANGED
@@ -20,7 +20,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ MAX_VISIBILITY_TIMEOUT: () => MAX_VISIBILITY_TIMEOUT,
23
24
  SqsConsumer: () => SqsConsumer,
25
+ SqsDeleteError: () => SqsDeleteError,
24
26
  SqsPublisher: () => SqsPublisher,
25
27
  headersOf: () => headersOf,
26
28
  mergeAttributes: () => mergeAttributes,
@@ -43,6 +45,7 @@ function sanitizeHeaders(headers) {
43
45
 
44
46
  // src/index.ts
45
47
  var MAX_ATTRIBUTES = 10;
48
+ var MAX_VISIBILITY_TIMEOUT = 43200;
46
49
  var str = (value) => ({
47
50
  DataType: "String",
48
51
  StringValue: String(value)
@@ -84,6 +87,12 @@ function headersOf(message) {
84
87
  }
85
88
  return out;
86
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
+ }
87
96
  function queueNameFromUrl(queueUrl) {
88
97
  const segments = queueUrl.split("/").filter(Boolean);
89
98
  return segments[segments.length - 1] ?? "default";
@@ -121,12 +130,29 @@ var SqsPublisher = class {
121
130
  return envelope.meta.id;
122
131
  }
123
132
  };
133
+ var SqsDeleteError = class extends import_core.BabelQueueError {
134
+ constructor(cause) {
135
+ super("Failed to delete a processed SQS message; it will be redelivered after its visibility timeout.");
136
+ this.name = "SqsDeleteError";
137
+ this.cause = cause;
138
+ }
139
+ };
124
140
  var SqsConsumer = class {
125
141
  constructor(client, queueUrl, handlers, options = {}) {
126
142
  this.client = client;
127
143
  this.queueUrl = queueUrl;
128
144
  this.handlers = handlers;
129
145
  this.options = options;
146
+ const strategy = options.unknownUrn;
147
+ if (strategy !== void 0 && !Object.values(import_core.UnknownUrnStrategy).includes(strategy)) {
148
+ throw new import_core.BabelQueueError(`Unknown unknownUrn strategy "${strategy}".`);
149
+ }
150
+ const needsRelease = options.releaseDelay != null || strategy === import_core.UnknownUrnStrategy.RELEASE;
151
+ if (needsRelease && typeof client.changeMessageVisibility !== "function") {
152
+ throw new import_core.BabelQueueError(
153
+ "SqsConsumer release requires a client with changeMessageVisibility (contract \xA73.5)."
154
+ );
155
+ }
130
156
  }
131
157
  client;
132
158
  queueUrl;
@@ -158,6 +184,17 @@ var SqsConsumer = class {
158
184
  }
159
185
  }
160
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
+ }
161
198
  const envelope = import_core.EnvelopeCodec.decode(message.Body ?? "");
162
199
  const receiveCount = message.Attributes?.["ApproximateReceiveCount"];
163
200
  if (receiveCount !== void 0) {
@@ -178,6 +215,38 @@ var SqsConsumer = class {
178
215
  const urn = import_core.EnvelopeCodec.urn(envelope);
179
216
  const handler = this.handlers[urn];
180
217
  if (!handler) {
218
+ await this.unknown(urn, envelope, message);
219
+ return;
220
+ }
221
+ try {
222
+ await handler(envelope, message, headersOf(message));
223
+ } catch (error) {
224
+ this.options.onError?.(error, envelope, message);
225
+ await this.guard(envelope, message, async () => {
226
+ const delay = this.options.releaseDelay ?? 0;
227
+ const attempts = typeof envelope.attempts === "number" ? envelope.attempts : 0;
228
+ await this.release(message, typeof delay === "function" ? delay(attempts) : delay);
229
+ });
230
+ return;
231
+ }
232
+ await this.guard(envelope, message, () => this.deleteHandled(message));
233
+ }
234
+ /**
235
+ * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a
236
+ * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so
237
+ * visibility expiry still redelivers it. Never lets the error stop the consume loop.
238
+ */
239
+ async guard(envelope, message, step) {
240
+ try {
241
+ await step();
242
+ } catch (error) {
243
+ this.options.onError?.(error, envelope, message);
244
+ }
245
+ }
246
+ /** Apply the unknown-URN strategy (contract §3.5). */
247
+ async unknown(urn, envelope, message) {
248
+ const strategy = this.options.unknownUrn;
249
+ if (strategy === void 0) {
181
250
  if (this.options.onUnknownUrn) {
182
251
  await this.options.onUnknownUrn(envelope, message);
183
252
  await this.delete(message);
@@ -186,11 +255,61 @@ var SqsConsumer = class {
186
255
  }
187
256
  return;
188
257
  }
258
+ await this.guard(envelope, message, async () => {
259
+ await this.options.onUnknownUrn?.(envelope, message);
260
+ });
261
+ switch (strategy) {
262
+ case import_core.UnknownUrnStrategy.DELETE:
263
+ await this.guard(envelope, message, () => this.deleteHandled(message));
264
+ return;
265
+ case import_core.UnknownUrnStrategy.RELEASE:
266
+ await this.guard(envelope, message, () => this.release(message, this.options.unknownUrnReleaseDelay ?? 0));
267
+ return;
268
+ case import_core.UnknownUrnStrategy.DEAD_LETTER:
269
+ await this.guard(envelope, message, async () => {
270
+ await this.deadLetter(envelope, "unknown_urn");
271
+ await this.deleteHandled(message);
272
+ });
273
+ return;
274
+ default:
275
+ this.options.onError?.(new import_core.UnknownUrnError(urn), envelope, message);
276
+ }
277
+ }
278
+ /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */
279
+ async release(message, seconds) {
280
+ if (!message.ReceiptHandle || !this.client.changeMessageVisibility) return;
281
+ const timeout = Number.isFinite(seconds) ? Math.min(MAX_VISIBILITY_TIMEOUT, Math.max(0, Math.floor(seconds))) : 0;
282
+ await this.client.changeMessageVisibility({
283
+ QueueUrl: this.queueUrl,
284
+ ReceiptHandle: message.ReceiptHandle,
285
+ VisibilityTimeout: timeout
286
+ });
287
+ }
288
+ /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */
289
+ async deadLetter(envelope, reason) {
290
+ const dlq = this.options.deadLetterQueueUrl;
291
+ if (!dlq) return;
292
+ const source = envelope.meta?.queue ?? queueNameFromUrl(this.queueUrl);
293
+ const annotated = (0, import_core.annotate)(envelope, reason, source, {
294
+ attempts: envelope.attempts ?? 0
295
+ });
296
+ const input = {
297
+ QueueUrl: dlq,
298
+ MessageBody: import_core.EnvelopeCodec.encode(annotated),
299
+ MessageAttributes: toMessageAttributes(annotated)
300
+ };
301
+ if (dlq.endsWith(".fifo")) {
302
+ input.MessageGroupId = source;
303
+ if (annotated.meta?.id) input.MessageDeduplicationId = annotated.meta.id;
304
+ }
305
+ await this.client.sendMessage(input);
306
+ }
307
+ /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */
308
+ async deleteHandled(message) {
189
309
  try {
190
- await handler(envelope, message, headersOf(message));
191
310
  await this.delete(message);
192
311
  } catch (error) {
193
- this.options.onError?.(error, envelope, message);
312
+ throw new SqsDeleteError(error);
194
313
  }
195
314
  }
196
315
  async delete(message) {
@@ -203,7 +322,9 @@ var SqsConsumer = class {
203
322
  };
204
323
  // Annotate the CommonJS export names for ESM import in node:
205
324
  0 && (module.exports = {
325
+ MAX_VISIBILITY_TIMEOUT,
206
326
  SqsConsumer,
327
+ SqsDeleteError,
207
328
  SqsPublisher,
208
329
  headersOf,
209
330
  mergeAttributes,
@@ -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 leaves the message for visibility-timeout redelivery); 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 } 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// --- 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\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 /** Called instead of erroring when a message's URN has no handler (then the message is deleted). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;\n /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */\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 * 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 leaves the\n * message undeleted — SQS redelivers it after the visibility timeout (at-least-once);\n * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler.\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\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 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 try {\n await handler(envelope, message, headersOf(message));\n await this.delete(message);\n } catch (error) {\n // Leave the message undeleted — SQS redelivers after the visibility timeout.\n this.options.onError?.(error, envelope, message);\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;AAqCA,kBAAgE;;;ACrBzD,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;;;ADkBA,IAAM,iBAAiB;AA6CvB,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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AQ;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,Q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AAAA;AAAA,EAGA,MAAc,WAAW,UAAoB,QAA+B;AAC1E,UAAM,MAAM,KAAK,QAAQ;AACzB,QAAI,CAAC,IAAK;AACV,UAAM,SAAS,SAAS,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":[]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
1
+ import { Envelope, HeaderCarrier, IncomingEnvelope, BabelQueueError } from '@babelqueue/core';
2
2
 
3
3
  /**
4
4
  * Amazon SQS adapter for BabelQueue.
@@ -23,10 +23,18 @@ import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
23
23
  * This implements §3 of the broker-bindings contract: the canonical envelope is the
24
24
  * message body, projected onto native SQS `MessageAttributes`. The envelope is
25
25
  * unchanged (`schema_version` stays 1); SQS is purely additive. Retry is SQS-native
26
- * (a failed handler leaves the message for visibility-timeout redelivery); the
26
+ * (a failed handler's message is released via `ChangeMessageVisibility` after
27
+ * `releaseDelay`, default 0 s — pair the queue with a `RedrivePolicy`); the
27
28
  * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as
28
29
  * `attempts = count − 1`.
29
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
+ *
30
38
  * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop
31
39
  * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`
32
40
  * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and
@@ -37,6 +45,8 @@ import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
37
45
  * `/sqs` and PHP `SqsTransport` wiring. GR-1: the wire envelope body is never touched.
38
46
  */
39
47
 
48
+ /** The SQS ceiling for a `VisibilityTimeout` (12 hours, in seconds). */
49
+ declare const MAX_VISIBILITY_TIMEOUT = 43200;
40
50
  interface SqsMessageAttributeValue {
41
51
  DataType: string;
42
52
  StringValue?: string;
@@ -77,6 +87,19 @@ interface SqsApi {
77
87
  QueueUrl: string;
78
88
  ReceiptHandle: string;
79
89
  }): Promise<unknown>;
90
+ /**
91
+ * The §3.5 release primitive. Optional so existing structural clients keep compiling; it is
92
+ * required (checked at construction) when a consumer sets `releaseDelay` or the `release`
93
+ * unknown-URN strategy explicitly. Without it the default handler-failure release degrades to
94
+ * leaving the message for visibility-timeout redelivery. The aggregated `SQS` class from
95
+ * `@aws-sdk/client-sqs` provides it.
96
+ */
97
+ changeMessageVisibility?(input: ChangeMessageVisibilityInput): Promise<unknown>;
98
+ }
99
+ interface ChangeMessageVisibilityInput {
100
+ QueueUrl: string;
101
+ ReceiptHandle: string;
102
+ VisibilityTimeout: number;
80
103
  }
81
104
  /**
82
105
  * Project the envelope's contract fields onto native SQS `MessageAttributes` — a
@@ -143,9 +166,44 @@ type BabelHandler = (envelope: Envelope, message: SqsMessage, headers: HeaderCar
143
166
  type BabelHandlers = Record<string, BabelHandler>;
144
167
  /** Options for {@link SqsConsumer}. */
145
168
  interface SqsConsumerOptions {
146
- /** Called instead of erroring when a message's URN has no handler (then the message is deleted). */
169
+ /**
170
+ * Called when a message's URN has no handler. Without `unknownUrn` the message is then deleted
171
+ * (the original behaviour); with `unknownUrn` set it is a notification hook and the strategy
172
+ * decides the message's fate.
173
+ */
147
174
  onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;
148
- /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */
175
+ /**
176
+ * Unknown-URN strategy per contract §3.5 — `fail` | `delete` | `release` | `dead_letter`
177
+ * ({@link UnknownUrnStrategy}). Omitted keeps the original behaviour (`onUnknownUrn` → delete,
178
+ * otherwise report and leave for visibility-timeout redelivery, i.e. `fail`). `release` uses
179
+ * `ChangeMessageVisibility` with {@link unknownUrnReleaseDelay}; `dead_letter` sends the annotated
180
+ * envelope to {@link deadLetterQueueUrl} then deletes, degrading to `delete` when no DLQ is set.
181
+ */
182
+ unknownUrn?: string;
183
+ /** Backoff (seconds) for the `release` unknown-URN strategy (default 0 = redeliver now). */
184
+ unknownUrnReleaseDelay?: number;
185
+ /**
186
+ * Backoff before a failed message is redelivered. A failed handler always releases the message
187
+ * via `ChangeMessageVisibility(ReceiptHandle, VisibilityTimeout)` (contract §3.5); this sets the
188
+ * `VisibilityTimeout` — a number of seconds, or a function of the (reconciled) `attempts`
189
+ * returning seconds (e.g. an exponential backoff). Clamped to `0…43200`. Default `0`: the message
190
+ * is visible again immediately. A permanently failing handler therefore retries without pause
191
+ * until the queue's `RedrivePolicy` (`maxReceiveCount`) moves it to the DLQ — configure one.
192
+ */
193
+ releaseDelay?: number | ((attempts: number) => number);
194
+ /**
195
+ * The cross-language `<queue>.dlq` URL for the `dead_letter` strategy (opt-in; default none). A
196
+ * `.fifo` DLQ is sent with `MessageGroupId` (the source queue name) and `MessageDeduplicationId`
197
+ * (`meta.id`).
198
+ */
199
+ deadLetterQueueUrl?: string | null;
200
+ /**
201
+ * Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), a throwing handler,
202
+ * a throwing `onUnknownUrn` under an `unknownUrn` strategy, a failed release / dead-letter send, or
203
+ * a failed delete after successful processing (an {@link SqsDeleteError} wrapping the broker
204
+ * error; never released). The message is then left for visibility-timeout redelivery. The loop
205
+ * never stops on these.
206
+ */
149
207
  onError?: (error: unknown, envelope: IncomingEnvelope, message: SqsMessage) => void;
150
208
  /** Long-poll wait seconds (default 20). */
151
209
  waitTimeSeconds?: number;
@@ -154,11 +212,23 @@ interface SqsConsumerOptions {
154
212
  /** Max messages per receive (default 10). */
155
213
  maxMessages?: number;
156
214
  }
215
+ /**
216
+ * Reported via `onError` when `DeleteMessage` fails for a message whose processing already succeeded
217
+ * (a handler returned normally, or the unknown-URN strategy chose `delete` / `dead_letter`). The
218
+ * broker error is `cause`. Distinct from a handler failure: the message is NOT released, so it is
219
+ * redelivered only after its visibility timeout expires (at-least-once; dedupe on `meta.id` with the
220
+ * idempotency helper if the side effect must not repeat).
221
+ */
222
+ declare class SqsDeleteError extends BabelQueueError {
223
+ constructor(cause: unknown);
224
+ }
157
225
  /**
158
226
  * Polls an SQS queue, decodes + validates each message, routes it to the handler
159
- * registered for its URN, and deletes it on success. A throwing handler leaves the
160
- * message undeleted — SQS redelivers it after the visibility timeout (at-least-once);
161
- * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler.
227
+ * registered for its URN, and deletes it on success. A throwing handler's message is released via
228
+ * `ChangeMessageVisibility` after `releaseDelay` (default 0 s, contract §3.5); if the release itself
229
+ * fails the message is left for visibility-timeout redelivery (at-least-once);
230
+ * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler. An unmapped URN
231
+ * follows the `unknownUrn` strategy (`fail` | `delete` | `release` | `dead_letter`).
162
232
  */
163
233
  declare class SqsConsumer {
164
234
  private readonly client;
@@ -171,7 +241,21 @@ declare class SqsConsumer {
171
241
  /** Poll until `signal` aborts (each poll long-polls, so this does not busy-loop). */
172
242
  run(signal?: AbortSignal): Promise<void>;
173
243
  private handle;
244
+ /**
245
+ * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a
246
+ * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so
247
+ * visibility expiry still redelivers it. Never lets the error stop the consume loop.
248
+ */
249
+ private guard;
250
+ /** Apply the unknown-URN strategy (contract §3.5). */
251
+ private unknown;
252
+ /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */
253
+ private release;
254
+ /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */
255
+ private deadLetter;
256
+ /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */
257
+ private deleteHandled;
174
258
  private delete;
175
259
  }
176
260
 
177
- export { type BabelHandler, type BabelHandlers, type PublishOptions, type ReceiveMessageInput, type SendMessageInput, type SqsApi, SqsConsumer, type SqsConsumerOptions, type SqsMessage, type SqsMessageAttributeValue, SqsPublisher, type SqsPublisherOptions, headersOf, mergeAttributes, toMessageAttributes };
261
+ export { type BabelHandler, type BabelHandlers, type ChangeMessageVisibilityInput, MAX_VISIBILITY_TIMEOUT, type PublishOptions, type ReceiveMessageInput, type SendMessageInput, type SqsApi, SqsConsumer, type SqsConsumerOptions, SqsDeleteError, type SqsMessage, type SqsMessageAttributeValue, SqsPublisher, type SqsPublisherOptions, headersOf, mergeAttributes, toMessageAttributes };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
1
+ import { Envelope, HeaderCarrier, IncomingEnvelope, BabelQueueError } from '@babelqueue/core';
2
2
 
3
3
  /**
4
4
  * Amazon SQS adapter for BabelQueue.
@@ -23,10 +23,18 @@ import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
23
23
  * This implements §3 of the broker-bindings contract: the canonical envelope is the
24
24
  * message body, projected onto native SQS `MessageAttributes`. The envelope is
25
25
  * unchanged (`schema_version` stays 1); SQS is purely additive. Retry is SQS-native
26
- * (a failed handler leaves the message for visibility-timeout redelivery); the
26
+ * (a failed handler's message is released via `ChangeMessageVisibility` after
27
+ * `releaseDelay`, default 0 s — pair the queue with a `RedrivePolicy`); the
27
28
  * authoritative attempt count is `ApproximateReceiveCount`, surfaced to handlers as
28
29
  * `attempts = count − 1`.
29
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
+ *
30
38
  * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop
31
39
  * span linkage) rides as additional String `MessageAttributes` **beside** the contract `bq-*`
32
40
  * attributes where `bq-trace-id` already lives — the contract attributes win a key collision, and
@@ -37,6 +45,8 @@ import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
37
45
  * `/sqs` and PHP `SqsTransport` wiring. GR-1: the wire envelope body is never touched.
38
46
  */
39
47
 
48
+ /** The SQS ceiling for a `VisibilityTimeout` (12 hours, in seconds). */
49
+ declare const MAX_VISIBILITY_TIMEOUT = 43200;
40
50
  interface SqsMessageAttributeValue {
41
51
  DataType: string;
42
52
  StringValue?: string;
@@ -77,6 +87,19 @@ interface SqsApi {
77
87
  QueueUrl: string;
78
88
  ReceiptHandle: string;
79
89
  }): Promise<unknown>;
90
+ /**
91
+ * The §3.5 release primitive. Optional so existing structural clients keep compiling; it is
92
+ * required (checked at construction) when a consumer sets `releaseDelay` or the `release`
93
+ * unknown-URN strategy explicitly. Without it the default handler-failure release degrades to
94
+ * leaving the message for visibility-timeout redelivery. The aggregated `SQS` class from
95
+ * `@aws-sdk/client-sqs` provides it.
96
+ */
97
+ changeMessageVisibility?(input: ChangeMessageVisibilityInput): Promise<unknown>;
98
+ }
99
+ interface ChangeMessageVisibilityInput {
100
+ QueueUrl: string;
101
+ ReceiptHandle: string;
102
+ VisibilityTimeout: number;
80
103
  }
81
104
  /**
82
105
  * Project the envelope's contract fields onto native SQS `MessageAttributes` — a
@@ -143,9 +166,44 @@ type BabelHandler = (envelope: Envelope, message: SqsMessage, headers: HeaderCar
143
166
  type BabelHandlers = Record<string, BabelHandler>;
144
167
  /** Options for {@link SqsConsumer}. */
145
168
  interface SqsConsumerOptions {
146
- /** Called instead of erroring when a message's URN has no handler (then the message is deleted). */
169
+ /**
170
+ * Called when a message's URN has no handler. Without `unknownUrn` the message is then deleted
171
+ * (the original behaviour); with `unknownUrn` set it is a notification hook and the strategy
172
+ * decides the message's fate.
173
+ */
147
174
  onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;
148
- /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */
175
+ /**
176
+ * Unknown-URN strategy per contract §3.5 — `fail` | `delete` | `release` | `dead_letter`
177
+ * ({@link UnknownUrnStrategy}). Omitted keeps the original behaviour (`onUnknownUrn` → delete,
178
+ * otherwise report and leave for visibility-timeout redelivery, i.e. `fail`). `release` uses
179
+ * `ChangeMessageVisibility` with {@link unknownUrnReleaseDelay}; `dead_letter` sends the annotated
180
+ * envelope to {@link deadLetterQueueUrl} then deletes, degrading to `delete` when no DLQ is set.
181
+ */
182
+ unknownUrn?: string;
183
+ /** Backoff (seconds) for the `release` unknown-URN strategy (default 0 = redeliver now). */
184
+ unknownUrnReleaseDelay?: number;
185
+ /**
186
+ * Backoff before a failed message is redelivered. A failed handler always releases the message
187
+ * via `ChangeMessageVisibility(ReceiptHandle, VisibilityTimeout)` (contract §3.5); this sets the
188
+ * `VisibilityTimeout` — a number of seconds, or a function of the (reconciled) `attempts`
189
+ * returning seconds (e.g. an exponential backoff). Clamped to `0…43200`. Default `0`: the message
190
+ * is visible again immediately. A permanently failing handler therefore retries without pause
191
+ * until the queue's `RedrivePolicy` (`maxReceiveCount`) moves it to the DLQ — configure one.
192
+ */
193
+ releaseDelay?: number | ((attempts: number) => number);
194
+ /**
195
+ * The cross-language `<queue>.dlq` URL for the `dead_letter` strategy (opt-in; default none). A
196
+ * `.fifo` DLQ is sent with `MessageGroupId` (the source queue name) and `MessageDeduplicationId`
197
+ * (`meta.id`).
198
+ */
199
+ deadLetterQueueUrl?: string | null;
200
+ /**
201
+ * Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), a throwing handler,
202
+ * a throwing `onUnknownUrn` under an `unknownUrn` strategy, a failed release / dead-letter send, or
203
+ * a failed delete after successful processing (an {@link SqsDeleteError} wrapping the broker
204
+ * error; never released). The message is then left for visibility-timeout redelivery. The loop
205
+ * never stops on these.
206
+ */
149
207
  onError?: (error: unknown, envelope: IncomingEnvelope, message: SqsMessage) => void;
150
208
  /** Long-poll wait seconds (default 20). */
151
209
  waitTimeSeconds?: number;
@@ -154,11 +212,23 @@ interface SqsConsumerOptions {
154
212
  /** Max messages per receive (default 10). */
155
213
  maxMessages?: number;
156
214
  }
215
+ /**
216
+ * Reported via `onError` when `DeleteMessage` fails for a message whose processing already succeeded
217
+ * (a handler returned normally, or the unknown-URN strategy chose `delete` / `dead_letter`). The
218
+ * broker error is `cause`. Distinct from a handler failure: the message is NOT released, so it is
219
+ * redelivered only after its visibility timeout expires (at-least-once; dedupe on `meta.id` with the
220
+ * idempotency helper if the side effect must not repeat).
221
+ */
222
+ declare class SqsDeleteError extends BabelQueueError {
223
+ constructor(cause: unknown);
224
+ }
157
225
  /**
158
226
  * Polls an SQS queue, decodes + validates each message, routes it to the handler
159
- * registered for its URN, and deletes it on success. A throwing handler leaves the
160
- * message undeleted — SQS redelivers it after the visibility timeout (at-least-once);
161
- * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler.
227
+ * registered for its URN, and deletes it on success. A throwing handler's message is released via
228
+ * `ChangeMessageVisibility` after `releaseDelay` (default 0 s, contract §3.5); if the release itself
229
+ * fails the message is left for visibility-timeout redelivery (at-least-once);
230
+ * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler. An unmapped URN
231
+ * follows the `unknownUrn` strategy (`fail` | `delete` | `release` | `dead_letter`).
162
232
  */
163
233
  declare class SqsConsumer {
164
234
  private readonly client;
@@ -171,7 +241,21 @@ declare class SqsConsumer {
171
241
  /** Poll until `signal` aborts (each poll long-polls, so this does not busy-loop). */
172
242
  run(signal?: AbortSignal): Promise<void>;
173
243
  private handle;
244
+ /**
245
+ * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a
246
+ * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so
247
+ * visibility expiry still redelivers it. Never lets the error stop the consume loop.
248
+ */
249
+ private guard;
250
+ /** Apply the unknown-URN strategy (contract §3.5). */
251
+ private unknown;
252
+ /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */
253
+ private release;
254
+ /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */
255
+ private deadLetter;
256
+ /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */
257
+ private deleteHandled;
174
258
  private delete;
175
259
  }
176
260
 
177
- export { type BabelHandler, type BabelHandlers, type PublishOptions, type ReceiveMessageInput, type SendMessageInput, type SqsApi, SqsConsumer, type SqsConsumerOptions, type SqsMessage, type SqsMessageAttributeValue, SqsPublisher, type SqsPublisherOptions, headersOf, mergeAttributes, toMessageAttributes };
261
+ export { type BabelHandler, type BabelHandlers, type ChangeMessageVisibilityInput, MAX_VISIBILITY_TIMEOUT, type PublishOptions, type ReceiveMessageInput, type SendMessageInput, type SqsApi, SqsConsumer, type SqsConsumerOptions, SqsDeleteError, type SqsMessage, type SqsMessageAttributeValue, SqsPublisher, type SqsPublisherOptions, headersOf, mergeAttributes, toMessageAttributes };
package/dist/index.js CHANGED
@@ -1,5 +1,12 @@
1
1
  // src/index.ts
2
- import { BabelQueueError, EnvelopeCodec, UnknownUrnError } 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) {
@@ -15,6 +22,7 @@ function sanitizeHeaders(headers) {
15
22
 
16
23
  // src/index.ts
17
24
  var MAX_ATTRIBUTES = 10;
25
+ var MAX_VISIBILITY_TIMEOUT = 43200;
18
26
  var str = (value) => ({
19
27
  DataType: "String",
20
28
  StringValue: String(value)
@@ -56,6 +64,12 @@ function headersOf(message) {
56
64
  }
57
65
  return out;
58
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
+ }
59
73
  function queueNameFromUrl(queueUrl) {
60
74
  const segments = queueUrl.split("/").filter(Boolean);
61
75
  return segments[segments.length - 1] ?? "default";
@@ -93,12 +107,29 @@ var SqsPublisher = class {
93
107
  return envelope.meta.id;
94
108
  }
95
109
  };
110
+ var SqsDeleteError = class extends BabelQueueError {
111
+ constructor(cause) {
112
+ super("Failed to delete a processed SQS message; it will be redelivered after its visibility timeout.");
113
+ this.name = "SqsDeleteError";
114
+ this.cause = cause;
115
+ }
116
+ };
96
117
  var SqsConsumer = class {
97
118
  constructor(client, queueUrl, handlers, options = {}) {
98
119
  this.client = client;
99
120
  this.queueUrl = queueUrl;
100
121
  this.handlers = handlers;
101
122
  this.options = options;
123
+ const strategy = options.unknownUrn;
124
+ if (strategy !== void 0 && !Object.values(UnknownUrnStrategy).includes(strategy)) {
125
+ throw new BabelQueueError(`Unknown unknownUrn strategy "${strategy}".`);
126
+ }
127
+ const needsRelease = options.releaseDelay != null || strategy === UnknownUrnStrategy.RELEASE;
128
+ if (needsRelease && typeof client.changeMessageVisibility !== "function") {
129
+ throw new BabelQueueError(
130
+ "SqsConsumer release requires a client with changeMessageVisibility (contract \xA73.5)."
131
+ );
132
+ }
102
133
  }
103
134
  client;
104
135
  queueUrl;
@@ -130,6 +161,17 @@ var SqsConsumer = class {
130
161
  }
131
162
  }
132
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
+ }
133
175
  const envelope = EnvelopeCodec.decode(message.Body ?? "");
134
176
  const receiveCount = message.Attributes?.["ApproximateReceiveCount"];
135
177
  if (receiveCount !== void 0) {
@@ -150,6 +192,38 @@ var SqsConsumer = class {
150
192
  const urn = EnvelopeCodec.urn(envelope);
151
193
  const handler = this.handlers[urn];
152
194
  if (!handler) {
195
+ await this.unknown(urn, envelope, message);
196
+ return;
197
+ }
198
+ try {
199
+ await handler(envelope, message, headersOf(message));
200
+ } catch (error) {
201
+ this.options.onError?.(error, envelope, message);
202
+ await this.guard(envelope, message, async () => {
203
+ const delay = this.options.releaseDelay ?? 0;
204
+ const attempts = typeof envelope.attempts === "number" ? envelope.attempts : 0;
205
+ await this.release(message, typeof delay === "function" ? delay(attempts) : delay);
206
+ });
207
+ return;
208
+ }
209
+ await this.guard(envelope, message, () => this.deleteHandled(message));
210
+ }
211
+ /**
212
+ * Run a release / dead-letter step; a failure (e.g. `MessageNotInflight`, a missing IAM grant, a
213
+ * throwing `releaseDelay`) is reported to `onError` and the message is left undeleted, so
214
+ * visibility expiry still redelivers it. Never lets the error stop the consume loop.
215
+ */
216
+ async guard(envelope, message, step) {
217
+ try {
218
+ await step();
219
+ } catch (error) {
220
+ this.options.onError?.(error, envelope, message);
221
+ }
222
+ }
223
+ /** Apply the unknown-URN strategy (contract §3.5). */
224
+ async unknown(urn, envelope, message) {
225
+ const strategy = this.options.unknownUrn;
226
+ if (strategy === void 0) {
153
227
  if (this.options.onUnknownUrn) {
154
228
  await this.options.onUnknownUrn(envelope, message);
155
229
  await this.delete(message);
@@ -158,11 +232,61 @@ var SqsConsumer = class {
158
232
  }
159
233
  return;
160
234
  }
235
+ await this.guard(envelope, message, async () => {
236
+ await this.options.onUnknownUrn?.(envelope, message);
237
+ });
238
+ switch (strategy) {
239
+ case UnknownUrnStrategy.DELETE:
240
+ await this.guard(envelope, message, () => this.deleteHandled(message));
241
+ return;
242
+ case UnknownUrnStrategy.RELEASE:
243
+ await this.guard(envelope, message, () => this.release(message, this.options.unknownUrnReleaseDelay ?? 0));
244
+ return;
245
+ case UnknownUrnStrategy.DEAD_LETTER:
246
+ await this.guard(envelope, message, async () => {
247
+ await this.deadLetter(envelope, "unknown_urn");
248
+ await this.deleteHandled(message);
249
+ });
250
+ return;
251
+ default:
252
+ this.options.onError?.(new UnknownUrnError(urn), envelope, message);
253
+ }
254
+ }
255
+ /** Make the message visible again after `seconds` via `ChangeMessageVisibility`; never deletes. */
256
+ async release(message, seconds) {
257
+ if (!message.ReceiptHandle || !this.client.changeMessageVisibility) return;
258
+ const timeout = Number.isFinite(seconds) ? Math.min(MAX_VISIBILITY_TIMEOUT, Math.max(0, Math.floor(seconds))) : 0;
259
+ await this.client.changeMessageVisibility({
260
+ QueueUrl: this.queueUrl,
261
+ ReceiptHandle: message.ReceiptHandle,
262
+ VisibilityTimeout: timeout
263
+ });
264
+ }
265
+ /** Send the annotated envelope to the opt-in DLQ; a no-op (→ plain delete) when none is set. */
266
+ async deadLetter(envelope, reason) {
267
+ const dlq = this.options.deadLetterQueueUrl;
268
+ if (!dlq) return;
269
+ const source = envelope.meta?.queue ?? queueNameFromUrl(this.queueUrl);
270
+ const annotated = annotate(envelope, reason, source, {
271
+ attempts: envelope.attempts ?? 0
272
+ });
273
+ const input = {
274
+ QueueUrl: dlq,
275
+ MessageBody: EnvelopeCodec.encode(annotated),
276
+ MessageAttributes: toMessageAttributes(annotated)
277
+ };
278
+ if (dlq.endsWith(".fifo")) {
279
+ input.MessageGroupId = source;
280
+ if (annotated.meta?.id) input.MessageDeduplicationId = annotated.meta.id;
281
+ }
282
+ await this.client.sendMessage(input);
283
+ }
284
+ /** Delete a message whose processing already succeeded; a broker failure becomes an SqsDeleteError. */
285
+ async deleteHandled(message) {
161
286
  try {
162
- await handler(envelope, message, headersOf(message));
163
287
  await this.delete(message);
164
288
  } catch (error) {
165
- this.options.onError?.(error, envelope, message);
289
+ throw new SqsDeleteError(error);
166
290
  }
167
291
  }
168
292
  async delete(message) {
@@ -174,7 +298,9 @@ var SqsConsumer = class {
174
298
  }
175
299
  };
176
300
  export {
301
+ MAX_VISIBILITY_TIMEOUT,
177
302
  SqsConsumer,
303
+ SqsDeleteError,
178
304
  SqsPublisher,
179
305
  headersOf,
180
306
  mergeAttributes,
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 leaves the message for visibility-timeout redelivery); 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 } 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// --- 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\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 /** Called instead of erroring when a message's URN has no handler (then the message is deleted). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: SqsMessage) => unknown | Promise<unknown>;\n /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */\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 * 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 leaves the\n * message undeleted — SQS redelivers it after the visibility timeout (at-least-once);\n * `attempts` is reconciled to `ApproximateReceiveCount − 1` for the handler.\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\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 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 try {\n await handler(envelope, message, headersOf(message));\n await this.delete(message);\n } catch (error) {\n // Leave the message undeleted — SQS redelivers after the visibility timeout.\n this.options.onError?.(error, envelope, message);\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":";AAqCA,SAAS,iBAAiB,eAAe,uBAAuB;;;ACrBzD,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;;;ADkBA,IAAM,iBAAiB;AA6CvB,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,gBACd,MACA,SAC0C;AAC1C,QAAM,QAAQ,gBAAgB,OAAO;AACrC,aAAW,OAAO,OAAO,KAAK,KAAK,EAAE,KAAK,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,cAAc,QAAQ,QAAQ,GAAG;AACpC,WAAK,QAAQ;AAAA,QACX,IAAI,gBAAgB,yDAAyD;AAAA,QAC7E;AAAA,QACA;AAAA,MACF;AACA;AAAA,IACF;AAEA,UAAM,MAAM,cAAc,IAAI,QAAQ;AACtC,UAAM,UAAU,KAAK,SAAS,GAAG;AACjC,QAAI,CAAC,SAAS;AACZ,UAAI,KAAK,QAAQ,cAAc;AAC7B,cAAM,KAAK,QAAQ,aAAa,UAAU,OAAO;AACjD,cAAM,KAAK,OAAO,OAAO;AAAA,MAC3B,OAAO;AACL,aAAK,QAAQ,UAAU,IAAI,gBAAgB,GAAG,GAAG,UAAU,OAAO;AAAA,MACpE;AACA;AAAA,IACF;AAEA,QAAI;AACF,YAAM,QAAQ,UAAU,SAAS,UAAU,OAAO,CAAC;AACnD,YAAM,KAAK,OAAO,OAAO;AAAA,IAC3B,SAAS,OAAO;AAEd,WAAK,QAAQ,UAAU,OAAO,UAAU,OAAO;AAAA,IACjD;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":";AA6CA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;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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ACA,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":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelqueue/sqs",
3
- "version": "1.1.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
  ".": {
@@ -50,7 +50,7 @@
50
50
  "test": "node --import tsx --test test/*.test.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@babelqueue/core": "^1.4.0"
53
+ "@babelqueue/core": "^1.8.0"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "@aws-sdk/client-sqs": "^3.0.0"