@babelqueue/pulsar 1.2.0 → 1.4.0
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 +89 -8
- package/dist/index.cjs +239 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +137 -9
- package/dist/index.d.ts +137 -9
- package/dist/index.js +239 -19
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { BabelQueueError, EnvelopeCodec, SCHEMA_VERSION, UnknownUrnError } from "@babelqueue/core";
|
|
2
|
+
import { BabelQueueError, EnvelopeCodec, SCHEMA_VERSION, UnknownUrnError, annotate, buildPoisonRecord } from "@babelqueue/core";
|
|
3
3
|
|
|
4
4
|
// src/headers.ts
|
|
5
5
|
function sanitizeHeaders(headers) {
|
|
@@ -77,12 +77,19 @@ var PulsarPublisher = class {
|
|
|
77
77
|
return envelope.meta.id;
|
|
78
78
|
}
|
|
79
79
|
};
|
|
80
|
+
var DEFAULT_MAX_ATTEMPTS = 3;
|
|
80
81
|
var MAX_ATTEMPTS = 2 ** 31 - 1;
|
|
81
82
|
function parseAttempts(raw) {
|
|
82
83
|
if (typeof raw !== "string" || !/^[0-9]+$/.test(raw)) return void 0;
|
|
83
84
|
const value = Number(raw);
|
|
84
85
|
return value <= MAX_ATTEMPTS ? value : void 0;
|
|
85
86
|
}
|
|
87
|
+
function reconcileAttempts(properties, bodyAttempts, redeliveryCount) {
|
|
88
|
+
let attempts = bodyAttempts;
|
|
89
|
+
const fromProperty = parseAttempts(properties["bq-attempts"]);
|
|
90
|
+
if (fromProperty !== void 0) attempts = fromProperty;
|
|
91
|
+
return redeliveryCount > attempts ? redeliveryCount : attempts;
|
|
92
|
+
}
|
|
86
93
|
var BLANK_ASCII = /^[ \t\n\v\f\r]*$/;
|
|
87
94
|
function unsupportedSchemaVersion(properties) {
|
|
88
95
|
const raw = properties["bq-schema-version"];
|
|
@@ -101,10 +108,62 @@ var PulsarConsumer = class {
|
|
|
101
108
|
this.consumer = consumer;
|
|
102
109
|
this.handlers = handlers;
|
|
103
110
|
this.options = options;
|
|
111
|
+
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
112
|
+
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
|
|
113
|
+
throw new BabelQueueError(`maxAttempts must be an integer of at least 1, got ${String(maxAttempts)}.`);
|
|
114
|
+
}
|
|
115
|
+
this.maxAttempts = maxAttempts;
|
|
116
|
+
this.checkRetryBound(maxAttempts);
|
|
117
|
+
this.warn = options.onWarn ?? ((message) => console.warn(message));
|
|
104
118
|
}
|
|
105
119
|
consumer;
|
|
106
120
|
handlers;
|
|
107
121
|
options;
|
|
122
|
+
maxAttempts;
|
|
123
|
+
builtRetryProducer;
|
|
124
|
+
warn;
|
|
125
|
+
/**
|
|
126
|
+
* Setup check: on `Exclusive` / `Failover` (and an undeclared type) a negative acknowledgement does not advance the native
|
|
127
|
+
* redelivery count, so a retry needs a re-publish. Fail loudly here instead of looping at run time.
|
|
128
|
+
*/
|
|
129
|
+
checkRetryBound(maxAttempts) {
|
|
130
|
+
const declared = this.options.subscriptionType;
|
|
131
|
+
if (declared !== void 0 && !["Exclusive", "Shared", "Failover", "KeyShared"].includes(declared.replace("_", ""))) {
|
|
132
|
+
throw new BabelQueueError(`Unknown subscriptionType "${String(declared)}".`);
|
|
133
|
+
}
|
|
134
|
+
const type = declared === void 0 ? "Exclusive" : declared.replace("_", "");
|
|
135
|
+
if (type !== "Exclusive" && type !== "Failover") return;
|
|
136
|
+
if (maxAttempts === 1 || this.options.retryProducer !== void 0) return;
|
|
137
|
+
if (this.options.client !== void 0 && this.retryTopic() !== void 0) return;
|
|
138
|
+
const shown = declared === void 0 ? "An undeclared subscriptionType (treated as Exclusive)" : `A ${type} subscription`;
|
|
139
|
+
if (this.options.client !== void 0) {
|
|
140
|
+
throw new BabelQueueError(
|
|
141
|
+
`${shown} with a client needs the \`topic\` option (the topic this consumer reads) to build the retry producer: pulsar-client's Consumer cannot report its own topic.`
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
throw new BabelQueueError(
|
|
145
|
+
`${shown} needs a retryProducer (or a client plus a topic) to bound retries: a negative acknowledgement does not advance the redelivery count there, so a retry would never reach maxAttempts. Pass a client plus topic (the topic you subscribed to), or a retryProducer, or declare subscriptionType: "Shared" / "Key_Shared".`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
retryTopic() {
|
|
149
|
+
const configured = this.options.topic;
|
|
150
|
+
if (configured !== void 0 && configured !== "") return configured;
|
|
151
|
+
const own = typeof this.consumer.getTopic === "function" ? this.consumer.getTopic() : void 0;
|
|
152
|
+
return own !== void 0 && own !== "" ? own : void 0;
|
|
153
|
+
}
|
|
154
|
+
/** The retry producer: the one given, else one built (once) from the client; undefined when neither exists. */
|
|
155
|
+
async resolveRetryProducer() {
|
|
156
|
+
if (this.options.retryProducer !== void 0) return this.options.retryProducer;
|
|
157
|
+
const client = this.options.client;
|
|
158
|
+
const topic = this.retryTopic();
|
|
159
|
+
if (client === void 0 || topic === void 0) return void 0;
|
|
160
|
+
this.builtRetryProducer ??= client.createProducer({ topic }).catch((error) => {
|
|
161
|
+
this.builtRetryProducer = void 0;
|
|
162
|
+
this.warn(`babelqueue: creating the retry producer on ${topic} failed (${errorText(error)}).`);
|
|
163
|
+
return void 0;
|
|
164
|
+
});
|
|
165
|
+
return this.builtRetryProducer;
|
|
166
|
+
}
|
|
108
167
|
/** Receive one message (up to the receive timeout), route + settle it. Returns 1, or 0 on timeout. */
|
|
109
168
|
async poll() {
|
|
110
169
|
let message;
|
|
@@ -134,32 +193,26 @@ var PulsarConsumer = class {
|
|
|
134
193
|
{},
|
|
135
194
|
message
|
|
136
195
|
);
|
|
137
|
-
await this.
|
|
196
|
+
await this.settleVersionGated(message);
|
|
138
197
|
return;
|
|
139
198
|
}
|
|
140
|
-
const envelope = EnvelopeCodec.decode(decodePayload(message.getData()));
|
|
141
199
|
const redeliveryCount = typeof message.getRedeliveryCount === "function" ? message.getRedeliveryCount() : 0;
|
|
142
|
-
const
|
|
143
|
-
let attempts = typeof bodyAttempts === "number" && Number.isInteger(bodyAttempts) ? bodyAttempts : 0;
|
|
144
|
-
const fromProperty = parseAttempts(properties["bq-attempts"]);
|
|
145
|
-
if (fromProperty !== void 0) attempts = fromProperty;
|
|
146
|
-
if (redeliveryCount > attempts) attempts = redeliveryCount;
|
|
147
|
-
if (typeof bodyAttempts === "number" && Number.isInteger(bodyAttempts) && bodyAttempts !== attempts) {
|
|
148
|
-
envelope.attempts = attempts;
|
|
149
|
-
}
|
|
200
|
+
const envelope = EnvelopeCodec.decode(decodePayload(message.getData()));
|
|
150
201
|
const bodyUrn = EnvelopeCodec.urn(envelope);
|
|
151
202
|
const rawJob = properties["bq-job"];
|
|
152
203
|
const propertyUrn = typeof rawJob === "string" ? rawJob.trim() : "";
|
|
153
204
|
const urn = propertyUrn !== "" ? propertyUrn : bodyUrn;
|
|
154
205
|
if (!EnvelopeCodec.accepts(envelope)) {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
message
|
|
159
|
-
);
|
|
160
|
-
await this.consumer.negativeAcknowledge(message);
|
|
206
|
+
const error = new BabelQueueError("Rejected a non-conformant BabelQueue envelope from Apache Pulsar.");
|
|
207
|
+
this.options.onError?.(error, envelope, message);
|
|
208
|
+
await this.settle("poison", reconcileAttempts(properties, 0, redeliveryCount) + 1, null, message, error);
|
|
161
209
|
return;
|
|
162
210
|
}
|
|
211
|
+
const bodyAttempts = envelope.attempts;
|
|
212
|
+
const attempts = reconcileAttempts(properties, bodyAttempts, redeliveryCount);
|
|
213
|
+
if (bodyAttempts !== attempts) {
|
|
214
|
+
envelope.attempts = attempts;
|
|
215
|
+
}
|
|
163
216
|
if (propertyUrn !== "" && bodyUrn !== "" && propertyUrn !== bodyUrn) {
|
|
164
217
|
this.notifyRoutingMismatch(propertyUrn, bodyUrn, envelope);
|
|
165
218
|
}
|
|
@@ -169,8 +222,9 @@ var PulsarConsumer = class {
|
|
|
169
222
|
await this.options.onUnknownUrn(envelope, message);
|
|
170
223
|
await this.consumer.acknowledge(message);
|
|
171
224
|
} else {
|
|
172
|
-
|
|
173
|
-
|
|
225
|
+
const error = new UnknownUrnError(urn);
|
|
226
|
+
this.options.onError?.(error, envelope, message);
|
|
227
|
+
await this.settle("unknown_urn", attempts + 1, envelope, message, error);
|
|
174
228
|
}
|
|
175
229
|
return;
|
|
176
230
|
}
|
|
@@ -179,8 +233,140 @@ var PulsarConsumer = class {
|
|
|
179
233
|
await this.consumer.acknowledge(message);
|
|
180
234
|
} catch (error) {
|
|
181
235
|
this.options.onError?.(error, envelope, message);
|
|
236
|
+
await this.settle("failed", attempts + 1, envelope, message, error);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Settle a version-gated delivery on its first delivery (ADR-0037 decision 1, broker-bindings §5.7): it is
|
|
241
|
+
* never decoded, never reaches a handler or {@link PulsarConsumerOptions.onUnknownUrn}, and is never retried,
|
|
242
|
+
* whatever `bq-attempts`, the redelivery count or `maxAttempts` say. This consumer has no unknown-URN
|
|
243
|
+
* strategy option, so it behaves as `fail`: with a {@link PulsarConsumerOptions.deadLetterProducer} the body is
|
|
244
|
+
* written to `<queue>.dlq` exactly as received (no `dead_letter` block, no re-encoding) and acknowledged only
|
|
245
|
+
* after the write; without one it is acknowledged and dropped (logged). A failed write leaves the delivery
|
|
246
|
+
* negatively acknowledged (never acknowledged, never counted as a retry): the gate rejects the redelivery
|
|
247
|
+
* again, so the write is tried again.
|
|
248
|
+
*/
|
|
249
|
+
async settleVersionGated(message) {
|
|
250
|
+
const producer = this.options.deadLetterProducer;
|
|
251
|
+
if (producer === void 0) {
|
|
252
|
+
this.warn("babelqueue: dropped a version-gated Apache Pulsar message (dead-lettering is off).");
|
|
253
|
+
await this.consumer.acknowledge(message);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
const data = message.getData();
|
|
258
|
+
await producer.send({
|
|
259
|
+
data: typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data),
|
|
260
|
+
properties: { ...safeProperties(message) }
|
|
261
|
+
});
|
|
262
|
+
} catch (writeError) {
|
|
263
|
+
this.warn(
|
|
264
|
+
`babelqueue: dead-letter write of a version-gated message to ${producer.getTopic()} failed (${errorText(writeError)}); the message is left for redelivery.`
|
|
265
|
+
);
|
|
182
266
|
await this.consumer.negativeAcknowledge(message);
|
|
267
|
+
return;
|
|
183
268
|
}
|
|
269
|
+
await this.consumer.acknowledge(message);
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The settle decision of a retryable outcome (ADR-0036 decisions 1 and 2). `counted` is the reconciled
|
|
273
|
+
* attempts plus one for this delivery. A poison body with dead-lettering on is recorded without retry;
|
|
274
|
+
* every other outcome retries (`negativeAcknowledge`: the native redelivery count advances, so the
|
|
275
|
+
* next delivery counts one more) while `counted < maxAttempts`, then dead-letters or drops.
|
|
276
|
+
*/
|
|
277
|
+
async settle(kind, counted, envelope, message, error) {
|
|
278
|
+
const producer = this.options.deadLetterProducer;
|
|
279
|
+
if (kind === "poison" && producer !== void 0) {
|
|
280
|
+
await this.deadLetter(producer, kind, counted, null, message, error);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (counted < this.maxAttempts) {
|
|
284
|
+
await this.retry(counted, envelope, message);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (producer !== void 0) {
|
|
288
|
+
await this.deadLetter(producer, kind, counted, envelope, message, error);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
this.warn(
|
|
292
|
+
`babelqueue: dropped a ${kind} Apache Pulsar message after ${counted} of ${this.maxAttempts} deliveries (dead-lettering is off).`
|
|
293
|
+
);
|
|
294
|
+
await this.consumer.acknowledge(message);
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Retry one delivery. With a {@link PulsarConsumerOptions.retryProducer}: re-publish to the consumer's
|
|
298
|
+
* own topic carrying `bq-attempts = counted` (reconcile = max(bq-attempts, RedeliveryCount) on the next
|
|
299
|
+
* delivery), then acknowledge the original — only after the send succeeded. Otherwise `negativeAcknowledge`.
|
|
300
|
+
*/
|
|
301
|
+
async retry(counted, envelope, message) {
|
|
302
|
+
const producer = await this.resolveRetryProducer();
|
|
303
|
+
if (producer === void 0) {
|
|
304
|
+
await this.consumer.negativeAcknowledge(message);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
try {
|
|
308
|
+
await producer.send(this.retryMessage(counted, envelope, message));
|
|
309
|
+
} catch (writeError) {
|
|
310
|
+
this.warn(
|
|
311
|
+
`babelqueue: retry re-publish to ${producer.getTopic()} failed (${errorText(writeError)}); the message is left for redelivery.`
|
|
312
|
+
);
|
|
313
|
+
await this.consumer.negativeAcknowledge(message);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
await this.consumer.acknowledge(message);
|
|
317
|
+
}
|
|
318
|
+
retryMessage(counted, envelope, message) {
|
|
319
|
+
const carried = headersOf(message);
|
|
320
|
+
delete carried["bq-delay"];
|
|
321
|
+
if (envelope !== null) {
|
|
322
|
+
return keepRoute(toPulsarMessage({ ...envelope, attempts: counted }, carried), message);
|
|
323
|
+
}
|
|
324
|
+
const data = message.getData();
|
|
325
|
+
return keepRoute(
|
|
326
|
+
{
|
|
327
|
+
data: typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data),
|
|
328
|
+
properties: { ...carried, "bq-attempts": String(counted) }
|
|
329
|
+
},
|
|
330
|
+
message
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Write the DLQ record, then acknowledge the original — only after the send succeeded. A failed send
|
|
335
|
+
* leaves the original negatively acknowledged, so it is redelivered and the write is tried again.
|
|
336
|
+
*/
|
|
337
|
+
async deadLetter(producer, kind, counted, envelope, message, error) {
|
|
338
|
+
try {
|
|
339
|
+
await producer.send(this.deadLetterMessage(producer, kind, counted, envelope, message, error));
|
|
340
|
+
} catch (writeError) {
|
|
341
|
+
this.warn(
|
|
342
|
+
`babelqueue: dead-letter write to ${producer.getTopic()} failed (${errorText(writeError)}); the message is left for redelivery.`
|
|
343
|
+
);
|
|
344
|
+
await this.consumer.negativeAcknowledge(message);
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
await this.consumer.acknowledge(message);
|
|
348
|
+
}
|
|
349
|
+
deadLetterMessage(producer, kind, counted, envelope, message, error) {
|
|
350
|
+
const details = {
|
|
351
|
+
attempts: counted,
|
|
352
|
+
error: error instanceof Error ? error.message : null,
|
|
353
|
+
exception: error instanceof Error ? error.name : null
|
|
354
|
+
};
|
|
355
|
+
if (envelope === null) {
|
|
356
|
+
const original2 = this.options.queue ?? stripDlqSuffix(topicName(producer.getTopic()));
|
|
357
|
+
const delivered = counted - 1;
|
|
358
|
+
const deadLetter = annotate({ attempts: delivered }, kind, original2, {
|
|
359
|
+
...details,
|
|
360
|
+
attempts: delivered
|
|
361
|
+
}).dead_letter;
|
|
362
|
+
const data = message.getData();
|
|
363
|
+
const body = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
|
|
364
|
+
const record = buildPoisonRecord(body, JSON.stringify(deadLetter));
|
|
365
|
+
return keepRoute({ data: Buffer.from(record, "utf8"), properties: poisonProperties(record) }, message);
|
|
366
|
+
}
|
|
367
|
+
const original = envelope.meta?.queue || this.options.queue || stripDlqSuffix(topicName(producer.getTopic()));
|
|
368
|
+
const annotated = annotate({ ...envelope, attempts: counted }, kind, original, details);
|
|
369
|
+
return keepRoute(toPulsarMessage(annotated), message);
|
|
184
370
|
}
|
|
185
371
|
notifyRoutingMismatch(propertyUrn, bodyUrn, envelope) {
|
|
186
372
|
const hook = this.options.onRoutingMismatch;
|
|
@@ -200,7 +386,41 @@ function safeProperties(message) {
|
|
|
200
386
|
return {};
|
|
201
387
|
}
|
|
202
388
|
}
|
|
389
|
+
function keepRoute(outgoing, incoming) {
|
|
390
|
+
const route = safeProperties(incoming)["bq-job"];
|
|
391
|
+
if (typeof route === "string" && route.trim() !== "") {
|
|
392
|
+
outgoing.properties = { ...outgoing.properties, "bq-job": route };
|
|
393
|
+
}
|
|
394
|
+
return outgoing;
|
|
395
|
+
}
|
|
396
|
+
function errorText(error) {
|
|
397
|
+
return error instanceof Error ? error.message : String(error);
|
|
398
|
+
}
|
|
399
|
+
function stripDlqSuffix(topic) {
|
|
400
|
+
return topic.endsWith(".dlq") && topic.length > 4 ? topic.slice(0, -4) : topic;
|
|
401
|
+
}
|
|
402
|
+
function poisonProperties(recordJson) {
|
|
403
|
+
const properties = {};
|
|
404
|
+
let record;
|
|
405
|
+
try {
|
|
406
|
+
record = JSON.parse(recordJson);
|
|
407
|
+
} catch {
|
|
408
|
+
return properties;
|
|
409
|
+
}
|
|
410
|
+
if (record === null || typeof record !== "object") return properties;
|
|
411
|
+
const top = record;
|
|
412
|
+
const str = (value) => typeof value === "string" && value !== "" ? value : void 0;
|
|
413
|
+
const job = str(top["job"]) ?? str(top["urn"]);
|
|
414
|
+
if (job) properties["bq-job"] = job;
|
|
415
|
+
const trace = str(top["trace_id"]);
|
|
416
|
+
if (trace) properties["bq-trace-id"] = trace;
|
|
417
|
+
const meta = top["meta"] !== null && typeof top["meta"] === "object" ? top["meta"] : {};
|
|
418
|
+
const id = str(meta["id"]);
|
|
419
|
+
if (id) properties["bq-message-id"] = id;
|
|
420
|
+
return properties;
|
|
421
|
+
}
|
|
203
422
|
export {
|
|
423
|
+
DEFAULT_MAX_ATTEMPTS,
|
|
204
424
|
PulsarConsumer,
|
|
205
425
|
PulsarPublisher,
|
|
206
426
|
headersOf,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Apache Pulsar adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Apache Pulsar, so a\n * Pulsar-based Node service speaks the same contract (envelope shape, URN identity, trace\n * propagation) as the .NET, Java, Python and Go SDKs.\n *\n * import Pulsar from \"pulsar-client\";\n * import { PulsarPublisher, PulsarConsumer } from \"@babelqueue/pulsar\";\n *\n * const client = new Pulsar.Client({ serviceUrl: \"pulsar://localhost:6650\" });\n *\n * const producer = await client.createProducer({ topic: \"orders\" });\n * await new PulsarPublisher(producer).publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const sub = await client.subscribe({\n * topic: \"orders\", subscription: \"babelqueue\", subscriptionType: \"Shared\",\n * });\n * const consumer = new PulsarConsumer(sub, {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §5 of the broker-bindings contract: the canonical envelope is the message\n * payload, projected onto native Pulsar message properties (string→string) — `bq-job` = URN,\n * `bq-trace-id` = trace_id, `bq-message-id` = meta.id, plus `bq-schema-version` /\n * `bq-source-lang` / `bq-attempts`. The envelope is unchanged (`schema_version` stays 1);\n * Pulsar is purely additive. A failed handler `negativeAcknowledge`s the message, so it is\n * redelivered (at-least-once) and `getRedeliveryCount()` is incremented. Per §5.2 / §5.7 the\n * consumer routes on the `bq-job` property (the body's URN is used only when the property is\n * absent or blank) and takes `attempts` from the authoritative `bq-attempts` property (the\n * body's value is used only when the property is absent or not a plain ASCII-decimal integer\n * that fits a 32-bit int), reconciled to `max(bq-attempts, getRedeliveryCount())` — no −1,\n * because Pulsar's redelivery count is 0-based. The handler still receives the body's envelope.\n *\n * **Version gate (§5.7 step 3).** Before the body is decoded the consumer reads the\n * `bq-schema-version` property. A missing or blank value (empty or only ASCII whitespace) changes nothing; any value other than\n * the core's supported `SCHEMA_VERSION` (`\"2\"`, `\"x\"`, `\"01\"`, ...) rejects the message undecoded\n * through the same path as a non-conformant envelope — `onError` (with an error naming the\n * version, and an empty envelope since nothing was decoded) and a `negativeAcknowledge`.\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 native Pulsar **message properties** beside the contract `bq-*`\n * properties — the contract properties win a key collision (merge-not-clobber), and blanks are\n * dropped. On consume the inbound `getProperties()` are surfaced as a `Record<string,string>` so\n * the core's `otel` extract sees the `traceparent` and links the consumer span as a child. A\n * header-less publish is byte-identical. GR-1: the wire envelope (the payload) is never touched.\n */\n\nimport { BabelQueueError, EnvelopeCodec, SCHEMA_VERSION, UnknownUrnError } from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { mergeInto } from \"./headers.js\";\n\n// --- Minimal Pulsar shapes (a structural subset of pulsar-client) --------------\n\n/** A message to send (structural subset of pulsar-client `ProducerMessage`). */\nexport interface PulsarProducerMessage {\n data: Buffer;\n properties?: { [key: string]: string };\n /** Relative delay in milliseconds before the message becomes available (native `deliverAfter`). */\n deliverAfter?: number;\n}\n\n/**\n * The subset of the Pulsar producer this adapter calls. A `Producer` from `pulsar-client`\n * satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface PulsarProducer {\n getTopic(): string;\n send(message: PulsarProducerMessage): Promise<unknown>;\n}\n\n/** A received message (structural subset of pulsar-client `Message`). */\nexport interface PulsarReceivedMessage {\n getData(): Buffer | string;\n getProperties(): { [key: string]: string };\n getRedeliveryCount(): number;\n}\n\n/**\n * The subset of the Pulsar consumer this adapter calls. A `Consumer` from `pulsar-client`\n * satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface PulsarConsumerClient {\n receive(timeoutMs?: number): Promise<PulsarReceivedMessage>;\n acknowledge(message: PulsarReceivedMessage): Promise<void> | void;\n negativeAcknowledge(message: PulsarReceivedMessage): Promise<void> | void;\n}\n\n// --- Property projection (contract §5.2) ---------------------------------------\n\n/** Bare topic name (the part after the last `/`), used as `meta.queue`. */\nfunction topicName(topic: string): string {\n const slash = topic.lastIndexOf(\"/\");\n return slash >= 0 ? topic.slice(slash + 1) : topic;\n}\n\n/**\n * Project the envelope's contract fields onto native Pulsar message properties\n * (string→string): `bq-job` = URN, `bq-trace-id` = trace_id, `bq-message-id` = meta.id, plus\n * `bq-schema-version` / `bq-source-lang` / `bq-attempts`. The body stays authoritative.\n */\nexport function pulsarProperties(envelope: Envelope): { [key: string]: string } {\n const properties: { [key: string]: string } = {};\n if (envelope.job) properties[\"bq-job\"] = envelope.job;\n if (envelope.trace_id) properties[\"bq-trace-id\"] = envelope.trace_id;\n if (envelope.meta.id) properties[\"bq-message-id\"] = envelope.meta.id;\n if (envelope.meta.schema_version != null) {\n properties[\"bq-schema-version\"] = String(envelope.meta.schema_version);\n }\n if (envelope.meta.lang) properties[\"bq-source-lang\"] = envelope.meta.lang;\n properties[\"bq-attempts\"] = String(envelope.attempts ?? 0);\n return properties;\n}\n\n/**\n * Project the envelope onto a native Pulsar producer message (payload + properties). When `extra`\n * is given, those out-of-band headers (e.g. a `traceparent`, ADR-0028) are merged beside the\n * contract `bq-*` properties without clobbering them (the contract wins a key collision).\n */\nexport function toPulsarMessage(envelope: Envelope, extra?: HeaderCarrier | null): PulsarProducerMessage {\n return {\n data: Buffer.from(EnvelopeCodec.encode(envelope), \"utf8\"),\n properties: mergeInto(pulsarProperties(envelope), extra),\n };\n}\n\n/**\n * Read a received message's native properties back into a flat {@link HeaderCarrier} via\n * `getProperties()`. Returns an empty object when there are none. Both the contract `bq-*`\n * properties and any out-of-band rider (e.g. `traceparent`) surface — the core's `otel` extract\n * reads only the keys it knows.\n */\nexport function headersOf(message: PulsarReceivedMessage): HeaderCarrier {\n const props = typeof message.getProperties === \"function\" ? message.getProperties() : undefined;\n const out: HeaderCarrier = {};\n if (!props) return out;\n for (const key of Object.keys(props)) {\n const value = props[key];\n if (value != null && value !== \"\") out[key] = value;\n }\n return out;\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link PulsarPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /** Schedule native delayed delivery this many milliseconds from now (`deliverAfter`). */\n delayMs?: number;\n /**\n * Out-of-band transport headers carried as native Pulsar message properties beside the contract\n * `bq-*` properties (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s\n * `publish`. The contract properties win a key collision; an empty/omitted carrier leaves the\n * message unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one Pulsar topic with the §5 property projection. */\nexport class PulsarPublisher {\n constructor(private readonly producer: PulsarProducer) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it with the §5 property projection,\n * and return the message id (`meta.id`). A positive `delayMs` schedules native delayed\n * delivery via `deliverAfter` and mirrors `bq-delay`.\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: topicName(this.producer.getTopic()),\n traceId: options.traceId,\n });\n const message = toPulsarMessage(envelope, options.headers);\n\n if (options.delayMs != null && options.delayMs > 0) {\n message.properties = { ...message.properties, \"bq-delay\": String(options.delayMs) };\n message.deliverAfter = options.delayMs;\n }\n\n await this.producer.send(message);\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw Pulsar message, and the out-of-band\n * {@link HeaderCarrier} read from the message's properties (empty when there are none). Pass\n * `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of the\n * producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: PulsarReceivedMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link PulsarConsumer}. */\nexport interface PulsarConsumerOptions {\n /** Called instead of erroring when a message's URN has no handler (then the message is acknowledged). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: PulsarReceivedMessage) => 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: PulsarReceivedMessage) => void;\n /** Per-receive timeout in ms (default 1000). A timeout yields an empty poll, not an error. */\n receiveTimeoutMs?: number;\n /**\n * Optional diagnostic hook, called when the `bq-job` property and the body's URN differ (the\n * property wins and the message is routed on it). `envelope` is the body's envelope. Separate\n * from {@link PulsarConsumerOptions.onError}: it is not an error, and anything it throws (or\n * rejects with) is swallowed — it never changes how the message is handled or acknowledged.\n */\n onRoutingMismatch?: (propertyUrn: string, bodyUrn: string, envelope: IncomingEnvelope) => unknown;\n}\n\n/** `bq-attempts` is valid only as ASCII digits that fit a signed 32-bit int (matches Java/.NET, GR-5). */\nconst MAX_ATTEMPTS = 2 ** 31 - 1;\n\nfunction parseAttempts(raw: string | undefined): number | undefined {\n if (typeof raw !== \"string\" || !/^[0-9]+$/.test(raw)) return undefined;\n const value = Number(raw);\n return value <= MAX_ATTEMPTS ? value : undefined;\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` value when it is present, non-blank and not the supported version\n * (compared against the core's `SCHEMA_VERSION`, exact string match: `\"01\"`, `\" 1\"`, `\"1.0\"` are\n * rejected). Blank means the empty string or only ASCII whitespace (the same set in every SDK, GR-5);\n * NBSP, U+0085, U+FEFF, U+3000 and the like are not blank. `undefined` when the message may be decoded.\n */\nfunction unsupportedSchemaVersion(properties: { [key: string]: string }): string | undefined {\n const raw: unknown = properties[\"bq-schema-version\"];\n if (typeof raw !== \"string\" || BLANK_ASCII.test(raw)) return undefined;\n return raw === String(SCHEMA_VERSION) ? undefined : raw;\n}\n\nfunction isReceiveTimeout(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return /timeout/i.test(message);\n}\n\nfunction decodePayload(data: Buffer | string): string {\n return typeof data === \"string\" ? data : data.toString(\"utf8\");\n}\n\n/**\n * Receives from a Pulsar subscription, decodes + validates each message, routes it to the\n * handler for its URN, and acknowledges it on success. A throwing handler\n * `negativeAcknowledge`s the message — the broker redelivers it and increments\n * `getRedeliveryCount()` (at-least-once). Routing uses the `bq-job` property (body URN as the\n * fallback); `attempts` is the `bq-attempts` property (body value as the fallback) reconciled to\n * `max(.., getRedeliveryCount())` for the handler.\n */\nexport class PulsarConsumer {\n constructor(\n private readonly consumer: PulsarConsumerClient,\n private readonly handlers: BabelHandlers,\n private readonly options: PulsarConsumerOptions = {},\n ) {}\n\n /** Receive one message (up to the receive timeout), route + settle it. Returns 1, or 0 on timeout. */\n async poll(): Promise<number> {\n let message: PulsarReceivedMessage;\n try {\n message = await this.consumer.receive(this.options.receiveTimeoutMs ?? 1000);\n } catch (error) {\n if (isReceiveTimeout(error)) return 0;\n throw error;\n }\n await this.handle(message);\n return 1;\n }\n\n /** Poll until `signal` aborts. */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: PulsarReceivedMessage): Promise<void> {\n const properties = safeProperties(message);\n\n // §5.7 step 3: gate on bq-schema-version before the body is decoded.\n const rejectedVersion = unsupportedSchemaVersion(properties);\n if (rejectedVersion !== undefined) {\n this.options.onError?.(\n new BabelQueueError(\n `Rejected a message from Apache Pulsar with unsupported bq-schema-version \"${rejectedVersion}\" (supported: ${SCHEMA_VERSION}).`,\n ),\n {},\n message,\n );\n await this.consumer.negativeAcknowledge(message);\n return;\n }\n\n const envelope = EnvelopeCodec.decode(decodePayload(message.getData()));\n\n // attempts: the authoritative bq-attempts property (the body's value when it is absent or\n // invalid), then max(.., getRedeliveryCount()): the redelivery count is 0-based, so it maps\n // directly with no −1; the max never lowers a higher count republished from another SDK\n // (the Go/Python transports retry by re-sending with attempts+1).\n const redeliveryCount = typeof message.getRedeliveryCount === \"function\" ? message.getRedeliveryCount() : 0;\n // A body without an integer attempts stays as sent, so accepts() below still rejects it\n // (the property can't repair a non-conformant body); the value is written only on a change.\n const bodyAttempts = envelope.attempts;\n let attempts = typeof bodyAttempts === \"number\" && Number.isInteger(bodyAttempts) ? bodyAttempts : 0;\n const fromProperty = parseAttempts(properties[\"bq-attempts\"]);\n if (fromProperty !== undefined) attempts = fromProperty;\n if (redeliveryCount > attempts) attempts = redeliveryCount;\n if (typeof bodyAttempts === \"number\" && Number.isInteger(bodyAttempts) && bodyAttempts !== attempts) {\n envelope.attempts = attempts;\n }\n\n // routing: the bq-job property wins; the body's URN is the fallback. A body with no URN is\n // still rejected below, whatever bq-job says.\n const bodyUrn = EnvelopeCodec.urn(envelope);\n const rawJob: unknown = properties[\"bq-job\"];\n const propertyUrn = typeof rawJob === \"string\" ? rawJob.trim() : \"\";\n const urn = propertyUrn !== \"\" ? propertyUrn : bodyUrn;\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from Apache Pulsar.\"),\n envelope,\n message,\n );\n await this.consumer.negativeAcknowledge(message);\n return;\n }\n\n // Diagnostics only, and only for an accepted envelope (07a Java/.NET order): after accepts()\n // and the attempts reconcile, so the hook sees the same envelope the handler gets.\n if (propertyUrn !== \"\" && bodyUrn !== \"\" && propertyUrn !== bodyUrn) {\n this.notifyRoutingMismatch(propertyUrn, bodyUrn, envelope);\n }\n\n const handler = this.handlers[urn];\n if (!handler) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.consumer.acknowledge(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n await this.consumer.negativeAcknowledge(message);\n }\n return;\n }\n\n try {\n await handler(envelope as Envelope, message, headersOf(message));\n await this.consumer.acknowledge(message);\n } catch (error) {\n // Negative-ack releases the message — the broker redelivers and increments the count.\n this.options.onError?.(error, envelope, message);\n await this.consumer.negativeAcknowledge(message);\n }\n }\n\n private notifyRoutingMismatch(propertyUrn: string, bodyUrn: string, envelope: IncomingEnvelope): void {\n const hook = this.options.onRoutingMismatch;\n if (hook === undefined) return;\n try {\n const result = hook(propertyUrn, bodyUrn, envelope);\n Promise.resolve(result).catch(() => undefined);\n } catch {\n // A diagnostic hook must never disturb consumption.\n }\n }\n}\n\nfunction safeProperties(message: PulsarReceivedMessage): { [key: string]: string } {\n try {\n const properties = typeof message.getProperties === \"function\" ? message.getProperties() : undefined;\n return properties ?? {};\n } catch {\n return {};\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. A nullish input yields an empty 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\n/**\n * Merge out-of-band `extra` headers onto an already-built `base` map **without clobbering** the\n * contract headers in `base` (they win a key collision) and dropping blanks. Returns `base`,\n * mutated in place.\n */\nexport function mergeInto(base: { [key: string]: string }, extra: HeaderCarrier | null | undefined): { [key: string]: string } {\n for (const [key, value] of Object.entries(sanitizeHeaders(extra))) {\n if (key in base) continue; // the contract header already there wins\n base[key] = value;\n }\n return base;\n}\n"],"mappings":";AAiDA,SAAS,iBAAiB,eAAe,gBAAgB,uBAAuB;;;AClCzE,SAAS,gBAAgB,SAA0D;AACxF,QAAM,MAAqB,CAAC;AAC5B,MAAI,CAAC,QAAS,QAAO;AACrB,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AK,QAAQ;AAC1B,QAAI,SAAS,OAAW;AACxB,QAAI;AACF,YAAM,SAAS,KAAK,aAAa,SAAS,QAAQ;AAClD,cAAQ,QAAQ,MAAM,EAAE,MAAM,MAAM,MAAS;AAAA,IAC/C,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEA,SAAS,eAAe,SAA2D;AACjF,MAAI;AACF,UAAM,aAAa,OAAO,QAAQ,kBAAkB,aAAa,QAAQ,cAAc,IAAI;AAC3F,WAAO,cAAc,CAAC;AAAA,EACxB,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Apache Pulsar adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Apache Pulsar, so a\n * Pulsar-based Node service speaks the same contract (envelope shape, URN identity, trace\n * propagation) as the .NET, Java, Python and Go SDKs.\n *\n * import Pulsar from \"pulsar-client\";\n * import { PulsarPublisher, PulsarConsumer } from \"@babelqueue/pulsar\";\n *\n * const client = new Pulsar.Client({ serviceUrl: \"pulsar://localhost:6650\" });\n *\n * const producer = await client.createProducer({ topic: \"orders\" });\n * await new PulsarPublisher(producer).publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const sub = await client.subscribe({\n * topic: \"orders\", subscription: \"babelqueue\", subscriptionType: \"Shared\",\n * });\n * const consumer = new PulsarConsumer(sub, {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * }, { subscriptionType: \"Shared\" }); // declare it (or pass `client` together with `topic`): see PulsarConsumerOptions\n * await consumer.run();\n *\n * This implements §5 of the broker-bindings contract: the canonical envelope is the message\n * payload, projected onto native Pulsar message properties (string→string) — `bq-job` = URN,\n * `bq-trace-id` = trace_id, `bq-message-id` = meta.id, plus `bq-schema-version` /\n * `bq-source-lang` / `bq-attempts`. The envelope is unchanged (`schema_version` stays 1);\n * Pulsar is purely additive. A failed handler `negativeAcknowledge`s the message, so it is\n * redelivered (at-least-once) and `getRedeliveryCount()` is incremented — up to `maxAttempts`\n * deliveries (default 3, ADR-0036): the message that exhausts them is written to `<queue>.dlq`\n * (when a `deadLetterProducer` is given) or acknowledged and dropped. A body that does not decode\n * into an envelope (including an object with no valid identity) is poison: it never reaches a\n * handler, and with dead-lettering on it is recorded in `<queue>.dlq` in the ADR-0035 shape without\n * retry. Per §5.2 / §5.7 the\n * consumer routes on the `bq-job` property (the body's URN is used only when the property is\n * absent or blank) and takes `attempts` from the authoritative `bq-attempts` property (the\n * body's value is used only when the property is absent or not a plain ASCII-decimal integer\n * that fits a 32-bit int), reconciled to `max(bq-attempts, getRedeliveryCount())` — no −1,\n * because Pulsar's redelivery count is 0-based. The handler still receives the body's envelope.\n *\n * **Version gate (§5.7 step 3).** Before the body is decoded the consumer reads the\n * `bq-schema-version` property. A missing or blank value (empty or only ASCII whitespace) changes nothing; any value other than\n * the core's supported `SCHEMA_VERSION` (`\"2\"`, `\"x\"`, `\"01\"`, ...) rejects the message undecoded:\n * `onError` (with an error naming the version, and an empty envelope since nothing was decoded),\n * then it is settled on its first delivery (ADR-0037 decision 1) — with a `deadLetterProducer` the\n * body, byte for byte, goes to `<queue>.dlq` and the message is acknowledged after the write (a failed\n * write is a `negativeAcknowledge`, never an acknowledgement); without one it is acknowledged and\n * dropped (logged). Never retried, whatever `bq-attempts`, the redelivery count or `maxAttempts` say.\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 native Pulsar **message properties** beside the contract `bq-*`\n * properties — the contract properties win a key collision (merge-not-clobber), and blanks are\n * dropped. On consume the inbound `getProperties()` are surfaced as a `Record<string,string>` so\n * the core's `otel` extract sees the `traceparent` and links the consumer span as a child. A\n * header-less publish is byte-identical. GR-1: the wire envelope (the payload) is never touched.\n */\n\nimport { BabelQueueError, EnvelopeCodec, SCHEMA_VERSION, UnknownUrnError, annotate, buildPoisonRecord } from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { mergeInto } from \"./headers.js\";\n\n// --- Minimal Pulsar shapes (a structural subset of pulsar-client) --------------\n\n/** A message to send (structural subset of pulsar-client `ProducerMessage`). */\nexport interface PulsarProducerMessage {\n data: Buffer;\n properties?: { [key: string]: string };\n /** Relative delay in milliseconds before the message becomes available (native `deliverAfter`). */\n deliverAfter?: number;\n}\n\n/**\n * The subset of the Pulsar producer this adapter calls. A `Producer` from `pulsar-client`\n * satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface PulsarProducer {\n getTopic(): string;\n send(message: PulsarProducerMessage): Promise<unknown>;\n}\n\n/** A received message (structural subset of pulsar-client `Message`). */\nexport interface PulsarReceivedMessage {\n getData(): Buffer | string;\n getProperties(): { [key: string]: string };\n getRedeliveryCount(): number;\n}\n\n/**\n * The subset of the Pulsar consumer this adapter calls. A `Consumer` from `pulsar-client`\n * satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface PulsarConsumerClient {\n /**\n * The topic the subscription reads. pulsar-client's `Consumer` has **no** such method (only its `Producer`\n * does), so with it the topic comes from the {@link PulsarConsumerOptions.topic} option; a custom\n * subscription wrapper may provide this to make `topic` unnecessary.\n */\n getTopic?(): string;\n receive(timeoutMs?: number): Promise<PulsarReceivedMessage>;\n acknowledge(message: PulsarReceivedMessage): Promise<void> | void;\n negativeAcknowledge(message: PulsarReceivedMessage): Promise<void> | void;\n}\n\n/**\n * The subset of the Pulsar client this adapter calls to build its own retry producer. A `Client` from\n * `pulsar-client` satisfies it structurally.\n */\nexport interface PulsarClientLike {\n createProducer(config: { topic: string }): Promise<PulsarProducer>;\n}\n\n/** The subscription type, as pulsar-client names it (`Key_Shared` is accepted as an alias of `KeyShared`). */\nexport type PulsarSubscriptionType = \"Exclusive\" | \"Shared\" | \"Failover\" | \"KeyShared\" | \"Key_Shared\";\n\n// --- Property projection (contract §5.2) ---------------------------------------\n\n/** Bare topic name (the part after the last `/`), used as `meta.queue`. */\nfunction topicName(topic: string): string {\n const slash = topic.lastIndexOf(\"/\");\n return slash >= 0 ? topic.slice(slash + 1) : topic;\n}\n\n/**\n * Project the envelope's contract fields onto native Pulsar message properties\n * (string→string): `bq-job` = URN, `bq-trace-id` = trace_id, `bq-message-id` = meta.id, plus\n * `bq-schema-version` / `bq-source-lang` / `bq-attempts`. The body stays authoritative.\n */\nexport function pulsarProperties(envelope: Envelope): { [key: string]: string } {\n const properties: { [key: string]: string } = {};\n if (envelope.job) properties[\"bq-job\"] = envelope.job;\n if (envelope.trace_id) properties[\"bq-trace-id\"] = envelope.trace_id;\n if (envelope.meta.id) properties[\"bq-message-id\"] = envelope.meta.id;\n if (envelope.meta.schema_version != null) {\n properties[\"bq-schema-version\"] = String(envelope.meta.schema_version);\n }\n if (envelope.meta.lang) properties[\"bq-source-lang\"] = envelope.meta.lang;\n properties[\"bq-attempts\"] = String(envelope.attempts ?? 0);\n return properties;\n}\n\n/**\n * Project the envelope onto a native Pulsar producer message (payload + properties). When `extra`\n * is given, those out-of-band headers (e.g. a `traceparent`, ADR-0028) are merged beside the\n * contract `bq-*` properties without clobbering them (the contract wins a key collision).\n */\nexport function toPulsarMessage(envelope: Envelope, extra?: HeaderCarrier | null): PulsarProducerMessage {\n return {\n data: Buffer.from(EnvelopeCodec.encode(envelope), \"utf8\"),\n properties: mergeInto(pulsarProperties(envelope), extra),\n };\n}\n\n/**\n * Read a received message's native properties back into a flat {@link HeaderCarrier} via\n * `getProperties()`. Returns an empty object when there are none. Both the contract `bq-*`\n * properties and any out-of-band rider (e.g. `traceparent`) surface — the core's `otel` extract\n * reads only the keys it knows.\n */\nexport function headersOf(message: PulsarReceivedMessage): HeaderCarrier {\n const props = typeof message.getProperties === \"function\" ? message.getProperties() : undefined;\n const out: HeaderCarrier = {};\n if (!props) return out;\n for (const key of Object.keys(props)) {\n const value = props[key];\n if (value != null && value !== \"\") out[key] = value;\n }\n return out;\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link PulsarPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /** Schedule native delayed delivery this many milliseconds from now (`deliverAfter`). */\n delayMs?: number;\n /**\n * Out-of-band transport headers carried as native Pulsar message properties beside the contract\n * `bq-*` properties (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s\n * `publish`. The contract properties win a key collision; an empty/omitted carrier leaves the\n * message unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one Pulsar topic with the §5 property projection. */\nexport class PulsarPublisher {\n constructor(private readonly producer: PulsarProducer) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it with the §5 property projection,\n * and return the message id (`meta.id`). A positive `delayMs` schedules native delayed\n * delivery via `deliverAfter` and mirrors `bq-delay`.\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: topicName(this.producer.getTopic()),\n traceId: options.traceId,\n });\n const message = toPulsarMessage(envelope, options.headers);\n\n if (options.delayMs != null && options.delayMs > 0) {\n message.properties = { ...message.properties, \"bq-delay\": String(options.delayMs) };\n message.deliverAfter = options.delayMs;\n }\n\n await this.producer.send(message);\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw Pulsar message, and the out-of-band\n * {@link HeaderCarrier} read from the message's properties (empty when there are none). Pass\n * `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of the\n * producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: PulsarReceivedMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link PulsarConsumer}. */\nexport interface PulsarConsumerOptions {\n /** Called instead of erroring when a message's URN has no handler (then the message is acknowledged). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: PulsarReceivedMessage) => 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: PulsarReceivedMessage) => void;\n /** Per-receive timeout in ms (default 1000). A timeout yields an empty poll, not an error. */\n receiveTimeoutMs?: number;\n /**\n * Optional diagnostic hook, called when the `bq-job` property and the body's URN differ (the\n * property wins and the message is routed on it). `envelope` is the body's envelope. Separate\n * from {@link PulsarConsumerOptions.onError}: it is not an error, and anything it throws (or\n * rejects with) is swallowed — it never changes how the message is handled or acknowledged.\n */\n onRoutingMismatch?: (propertyUrn: string, bodyUrn: string, envelope: IncomingEnvelope) => unknown;\n /**\n * The total number of deliveries a message gets, the first included (default 3; `1` = no retry;\n * ADR-0036 decision 1). A failing handler, an unmapped URN without {@link onUnknownUrn} and a poison\n * body with dead-lettering off are retried (`negativeAcknowledge`) while `reconciled attempts + 1`\n * is below it; the delivery that reaches it is dead-lettered (when {@link deadLetterProducer} is\n * set) or acknowledged and dropped. Must be an integer of at least 1.\n */\n maxAttempts?: number;\n /**\n * A producer on the dead-letter topic (by convention `<queue>.dlq`). Dead-lettering is on exactly\n * when it is set; the SDK does not use Pulsar's native `DeadLetterPolicy`. The original message is\n * acknowledged only after the record was sent; a failed send leaves it negatively acknowledged so\n * it is redelivered and the write is tried again.\n */\n deadLetterProducer?: PulsarProducer;\n /**\n * A producer on the consumer's **own** topic. A retry re-publishes the message to that topic with\n * `bq-attempts` (and the body's `attempts`) raised to the counted value and then acknowledges the\n * original — the Go model. The count then lives in the message itself, so the bound holds on every\n * subscription type. Optional when {@link client} is given (the consumer builds the producer itself);\n * a failed re-publish leaves the original negatively acknowledged (never lost).\n *\n * Without a producer or a client a retry is a `negativeAcknowledge`, which advances the native\n * redelivery count only on `Shared` / `Key_Shared`: on `Exclusive` / `Failover` it stays 0 and the retry\n * would never reach `maxAttempts`, so that combination is rejected at construction (see\n * {@link subscriptionType}).\n */\n retryProducer?: PulsarProducer;\n /**\n * The Pulsar client the consumer builds its retry producer from, lazily on the first retry, on\n * {@link topic}. Needs `topic` (pulsar-client's `Consumer` cannot tell its topic). Ignored when\n * {@link retryProducer} is given.\n */\n client?: PulsarClientLike;\n /**\n * The topic the retry producer is created on — the topic the consumer reads. Required together with\n * {@link client} (a pulsar-client `Consumer` has no `getTopic()`); a subscription wrapper that provides\n * `getTopic()` makes it optional.\n */\n topic?: string;\n /**\n * The subscription type the consumer was created with. `Exclusive` and `Failover` cannot bound a\n * nack-driven retry (a negative acknowledgement does not advance the redelivery count there), so with\n * `maxAttempts > 1` they require a {@link retryProducer} or a {@link client}. **Not declaring it counts as\n * `Exclusive`** (pulsar-client's own default, and the fail-closed choice): without a `retryProducer` or a\n * `client` the constructor throws `BabelQueueError`. Declare `\"Shared\"` or `\"Key_Shared\"` to keep the\n * `negativeAcknowledge` retry without a producer.\n */\n subscriptionType?: PulsarSubscriptionType;\n /**\n * The queue name written to `dead_letter.original_queue` of a poison record (a decodable envelope\n * uses its own `meta.queue`). Defaults to the {@link deadLetterProducer} topic without its `.dlq`\n * suffix.\n */\n queue?: string;\n /** Receives the \"message dropped\" and \"dead-letter write failed\" warnings (default `console.warn`). */\n onWarn?: (message: string) => void;\n}\n\n/** What a retryable outcome is about: the reason written to `dead_letter.reason`. */\ntype SettleKind = \"failed\" | \"unknown_urn\" | \"poison\";\n\n/** Default total number of deliveries (ADR-0036 decision 1). */\nexport const DEFAULT_MAX_ATTEMPTS = 3;\n\n/** `bq-attempts` is valid only as ASCII digits that fit a signed 32-bit int (matches Java/.NET, GR-5). */\nconst MAX_ATTEMPTS = 2 ** 31 - 1;\n\nfunction parseAttempts(raw: string | undefined): number | undefined {\n if (typeof raw !== \"string\" || !/^[0-9]+$/.test(raw)) return undefined;\n const value = Number(raw);\n return value <= MAX_ATTEMPTS ? value : undefined;\n}\n\n/**\n * The reconciled attempt count of a delivery (broker-bindings §5.5): the `bq-attempts` property when\n * valid, else `bodyAttempts` (0 when the body has none), floored by the 0-based native redelivery count.\n */\nfunction reconcileAttempts(\n properties: { [key: string]: string },\n bodyAttempts: number,\n redeliveryCount: number,\n): number {\n let attempts = bodyAttempts;\n const fromProperty = parseAttempts(properties[\"bq-attempts\"]);\n if (fromProperty !== undefined) attempts = fromProperty;\n return redeliveryCount > attempts ? redeliveryCount : attempts;\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` value when it is present, non-blank and not the supported version\n * (compared against the core's `SCHEMA_VERSION`, exact string match: `\"01\"`, `\" 1\"`, `\"1.0\"` are\n * rejected). Blank means the empty string or only ASCII whitespace (the same set in every SDK, GR-5);\n * NBSP, U+0085, U+FEFF, U+3000 and the like are not blank. `undefined` when the message may be decoded.\n */\nfunction unsupportedSchemaVersion(properties: { [key: string]: string }): string | undefined {\n const raw: unknown = properties[\"bq-schema-version\"];\n if (typeof raw !== \"string\" || BLANK_ASCII.test(raw)) return undefined;\n return raw === String(SCHEMA_VERSION) ? undefined : raw;\n}\n\nfunction isReceiveTimeout(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n return /timeout/i.test(message);\n}\n\nfunction decodePayload(data: Buffer | string): string {\n return typeof data === \"string\" ? data : data.toString(\"utf8\");\n}\n\n/**\n * Receives from a Pulsar subscription, decodes + validates each message, routes it to the\n * handler for its URN, and acknowledges it on success. A throwing handler\n * `negativeAcknowledge`s the message — the broker redelivers it and increments\n * `getRedeliveryCount()` (at-least-once; with a `retryProducer` the message is instead re-published with\n * `bq-attempts` + 1, which also bounds `Exclusive` / `Failover` subscriptions) — until `maxAttempts` deliveries are used up; the last one is\n * dead-lettered to `<queue>.dlq` or acknowledged and dropped (ADR-0036). Routing uses the `bq-job`\n * property (body URN as the fallback); `attempts` is the `bq-attempts` property (body value as the\n * fallback) reconciled to `max(.., getRedeliveryCount())` for the handler.\n */\nexport class PulsarConsumer {\n private readonly maxAttempts: number;\n private builtRetryProducer: Promise<PulsarProducer | undefined> | undefined;\n private readonly warn: (message: string) => void;\n\n constructor(\n private readonly consumer: PulsarConsumerClient,\n private readonly handlers: BabelHandlers,\n private readonly options: PulsarConsumerOptions = {},\n ) {\n const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw new BabelQueueError(`maxAttempts must be an integer of at least 1, got ${String(maxAttempts)}.`);\n }\n this.maxAttempts = maxAttempts;\n this.checkRetryBound(maxAttempts);\n this.warn = options.onWarn ?? ((message) => console.warn(message));\n }\n\n /**\n * Setup check: on `Exclusive` / `Failover` (and an undeclared type) a negative acknowledgement does not advance the native\n * redelivery count, so a retry needs a re-publish. Fail loudly here instead of looping at run time.\n */\n private checkRetryBound(maxAttempts: number): void {\n const declared = this.options.subscriptionType;\n if (declared !== undefined && ![\"Exclusive\", \"Shared\", \"Failover\", \"KeyShared\"].includes(declared.replace(\"_\", \"\"))) {\n throw new BabelQueueError(`Unknown subscriptionType \"${String(declared)}\".`);\n }\n // An undeclared type is treated as Exclusive (fail closed).\n const type = declared === undefined ? \"Exclusive\" : declared.replace(\"_\", \"\");\n if (type !== \"Exclusive\" && type !== \"Failover\") return;\n if (maxAttempts === 1 || this.options.retryProducer !== undefined) return;\n if (this.options.client !== undefined && this.retryTopic() !== undefined) return;\n const shown = declared === undefined ? \"An undeclared subscriptionType (treated as Exclusive)\" : `A ${type} subscription`;\n if (this.options.client !== undefined) {\n // A client alone cannot name the topic: pulsar-client's Consumer has no getTopic().\n throw new BabelQueueError(\n `${shown} with a client needs the \\`topic\\` option (the topic this consumer reads) to build the retry producer: ` +\n \"pulsar-client's Consumer cannot report its own topic.\",\n );\n }\n throw new BabelQueueError(\n `${shown} needs a retryProducer (or a client plus a topic) to bound retries: ` +\n \"a negative acknowledgement does not advance the redelivery count there, so a retry would never reach maxAttempts. \" +\n 'Pass a client plus topic (the topic you subscribed to), or a retryProducer, or declare subscriptionType: \"Shared\" / \"Key_Shared\".',\n );\n }\n\n private retryTopic(): string | undefined {\n const configured = this.options.topic;\n if (configured !== undefined && configured !== \"\") return configured;\n const own = typeof this.consumer.getTopic === \"function\" ? this.consumer.getTopic() : undefined;\n return own !== undefined && own !== \"\" ? own : undefined;\n }\n\n /** The retry producer: the one given, else one built (once) from the client; undefined when neither exists. */\n private async resolveRetryProducer(): Promise<PulsarProducer | undefined> {\n if (this.options.retryProducer !== undefined) return this.options.retryProducer;\n const client = this.options.client;\n const topic = this.retryTopic();\n if (client === undefined || topic === undefined) return undefined;\n this.builtRetryProducer ??= client.createProducer({ topic }).catch((error: unknown) => {\n this.builtRetryProducer = undefined; // try again on the next retry\n this.warn(`babelqueue: creating the retry producer on ${topic} failed (${errorText(error)}).`);\n return undefined;\n });\n return this.builtRetryProducer;\n }\n\n /** Receive one message (up to the receive timeout), route + settle it. Returns 1, or 0 on timeout. */\n async poll(): Promise<number> {\n let message: PulsarReceivedMessage;\n try {\n message = await this.consumer.receive(this.options.receiveTimeoutMs ?? 1000);\n } catch (error) {\n if (isReceiveTimeout(error)) return 0;\n throw error;\n }\n await this.handle(message);\n return 1;\n }\n\n /** Poll until `signal` aborts. */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: PulsarReceivedMessage): Promise<void> {\n const properties = safeProperties(message);\n\n // §5.7 step 3: gate on bq-schema-version before the body is decoded.\n const rejectedVersion = unsupportedSchemaVersion(properties);\n if (rejectedVersion !== undefined) {\n this.options.onError?.(\n new BabelQueueError(\n `Rejected a message from Apache Pulsar with unsupported bq-schema-version \"${rejectedVersion}\" (supported: ${SCHEMA_VERSION}).`,\n ),\n {},\n message,\n );\n await this.settleVersionGated(message);\n return;\n }\n\n const redeliveryCount = typeof message.getRedeliveryCount === \"function\" ? message.getRedeliveryCount() : 0;\n const envelope = EnvelopeCodec.decode(decodePayload(message.getData()));\n\n // routing: the bq-job property wins; the body's URN is the fallback. A body with no URN is\n // still rejected below, whatever bq-job says.\n const bodyUrn = EnvelopeCodec.urn(envelope);\n const rawJob: unknown = properties[\"bq-job\"];\n const propertyUrn = typeof rawJob === \"string\" ? rawJob.trim() : \"\";\n const urn = propertyUrn !== \"\" ? propertyUrn : bodyUrn;\n\n if (!EnvelopeCodec.accepts(envelope)) {\n // Poison (ADR-0036 decisions 2 and 4): a body that does not decode into an envelope, including an\n // object with no valid identity, never reaches a handler. Its attempts come from the transport\n // alone (bq-attempts, the redelivery count): there is no decodable body to read them from.\n const error = new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from Apache Pulsar.\");\n this.options.onError?.(error, envelope, message);\n await this.settle(\"poison\", reconcileAttempts(properties, 0, redeliveryCount) + 1, null, message, error);\n return;\n }\n\n // attempts: the authoritative bq-attempts property (the body's value when it is absent or\n // invalid), then max(.., getRedeliveryCount()): the redelivery count is 0-based, so it maps\n // directly with no −1; the max never lowers a higher count republished from another SDK\n // (the Go/Python transports retry by re-sending with attempts+1).\n // accepts() above guarantees an integer body attempts; the value is written only on a change.\n const bodyAttempts = envelope.attempts as number;\n const attempts = reconcileAttempts(properties, bodyAttempts, redeliveryCount);\n if (bodyAttempts !== attempts) {\n envelope.attempts = attempts;\n }\n\n // Diagnostics only, and only for an accepted envelope (07a Java/.NET order): after accepts()\n // and the attempts reconcile, so the hook sees the same envelope the handler gets.\n if (propertyUrn !== \"\" && bodyUrn !== \"\" && propertyUrn !== bodyUrn) {\n this.notifyRoutingMismatch(propertyUrn, bodyUrn, envelope);\n }\n\n const handler = this.handlers[urn];\n if (!handler) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.consumer.acknowledge(message);\n } else {\n const error = new UnknownUrnError(urn);\n this.options.onError?.(error, envelope, message);\n await this.settle(\"unknown_urn\", attempts + 1, envelope as Envelope, message, error);\n }\n return;\n }\n\n try {\n await handler(envelope as Envelope, message, headersOf(message));\n await this.consumer.acknowledge(message);\n } catch (error) {\n this.options.onError?.(error, envelope, message);\n await this.settle(\"failed\", attempts + 1, envelope as Envelope, message, error);\n }\n }\n\n /**\n * Settle a version-gated delivery on its first delivery (ADR-0037 decision 1, broker-bindings §5.7): it is\n * never decoded, never reaches a handler or {@link PulsarConsumerOptions.onUnknownUrn}, and is never retried,\n * whatever `bq-attempts`, the redelivery count or `maxAttempts` say. This consumer has no unknown-URN\n * strategy option, so it behaves as `fail`: with a {@link PulsarConsumerOptions.deadLetterProducer} the body is\n * written to `<queue>.dlq` exactly as received (no `dead_letter` block, no re-encoding) and acknowledged only\n * after the write; without one it is acknowledged and dropped (logged). A failed write leaves the delivery\n * negatively acknowledged (never acknowledged, never counted as a retry): the gate rejects the redelivery\n * again, so the write is tried again.\n */\n private async settleVersionGated(message: PulsarReceivedMessage): Promise<void> {\n const producer = this.options.deadLetterProducer;\n if (producer === undefined) {\n this.warn(\"babelqueue: dropped a version-gated Apache Pulsar message (dead-lettering is off).\");\n await this.consumer.acknowledge(message);\n return;\n }\n try {\n const data = message.getData();\n await producer.send({\n data: typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data),\n properties: { ...safeProperties(message) },\n });\n } catch (writeError) {\n this.warn(\n `babelqueue: dead-letter write of a version-gated message to ${producer.getTopic()} failed (${errorText(writeError)}); the message is left for redelivery.`,\n );\n await this.consumer.negativeAcknowledge(message);\n return;\n }\n await this.consumer.acknowledge(message);\n }\n\n /**\n * The settle decision of a retryable outcome (ADR-0036 decisions 1 and 2). `counted` is the reconciled\n * attempts plus one for this delivery. A poison body with dead-lettering on is recorded without retry;\n * every other outcome retries (`negativeAcknowledge`: the native redelivery count advances, so the\n * next delivery counts one more) while `counted < maxAttempts`, then dead-letters or drops.\n */\n private async settle(\n kind: SettleKind,\n counted: number,\n envelope: Envelope | null,\n message: PulsarReceivedMessage,\n error: unknown,\n ): Promise<void> {\n const producer = this.options.deadLetterProducer;\n if (kind === \"poison\" && producer !== undefined) {\n await this.deadLetter(producer, kind, counted, null, message, error);\n return;\n }\n if (counted < this.maxAttempts) {\n await this.retry(counted, envelope, message);\n return;\n }\n if (producer !== undefined) {\n await this.deadLetter(producer, kind, counted, envelope, message, error);\n return;\n }\n this.warn(\n `babelqueue: dropped a ${kind} Apache Pulsar message after ${counted} of ${this.maxAttempts} deliveries (dead-lettering is off).`,\n );\n await this.consumer.acknowledge(message);\n }\n\n /**\n * Retry one delivery. With a {@link PulsarConsumerOptions.retryProducer}: re-publish to the consumer's\n * own topic carrying `bq-attempts = counted` (reconcile = max(bq-attempts, RedeliveryCount) on the next\n * delivery), then acknowledge the original — only after the send succeeded. Otherwise `negativeAcknowledge`.\n */\n private async retry(counted: number, envelope: Envelope | null, message: PulsarReceivedMessage): Promise<void> {\n const producer = await this.resolveRetryProducer();\n if (producer === undefined) {\n await this.consumer.negativeAcknowledge(message);\n return;\n }\n try {\n await producer.send(this.retryMessage(counted, envelope, message));\n } catch (writeError) {\n this.warn(\n `babelqueue: retry re-publish to ${producer.getTopic()} failed (${errorText(writeError)}); the message is left for redelivery.`,\n );\n await this.consumer.negativeAcknowledge(message);\n return;\n }\n await this.consumer.acknowledge(message);\n }\n\n private retryMessage(counted: number, envelope: Envelope | null, message: PulsarReceivedMessage): PulsarProducerMessage {\n // Out-of-band headers (e.g. a traceparent) ride along; the contract bq-* properties are rebuilt and win,\n // and the one-shot bq-delay of the first publish is not repeated.\n const carried = headersOf(message);\n delete carried[\"bq-delay\"];\n if (envelope !== null) {\n return keepRoute(toPulsarMessage({ ...envelope, attempts: counted }, carried), message);\n }\n // A poison body is retried byte for byte (there is no envelope to re-encode); only the counter moves.\n const data = message.getData();\n return keepRoute(\n {\n data: typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data),\n properties: { ...carried, \"bq-attempts\": String(counted) },\n },\n message,\n );\n }\n\n /**\n * Write the DLQ record, then acknowledge the original — only after the send succeeded. A failed send\n * leaves the original negatively acknowledged, so it is redelivered and the write is tried again.\n */\n private async deadLetter(\n producer: PulsarProducer,\n kind: SettleKind,\n counted: number,\n envelope: Envelope | null,\n message: PulsarReceivedMessage,\n error: unknown,\n ): Promise<void> {\n try {\n await producer.send(this.deadLetterMessage(producer, kind, counted, envelope, message, error));\n } catch (writeError) {\n this.warn(\n `babelqueue: dead-letter write to ${producer.getTopic()} failed (${errorText(writeError)}); the message is left for redelivery.`,\n );\n await this.consumer.negativeAcknowledge(message);\n return;\n }\n await this.consumer.acknowledge(message);\n }\n\n private deadLetterMessage(\n producer: PulsarProducer,\n kind: SettleKind,\n counted: number,\n envelope: Envelope | null,\n message: PulsarReceivedMessage,\n error: unknown,\n ): PulsarProducerMessage {\n const details = {\n attempts: counted,\n error: error instanceof Error ? error.message : null,\n exception: error instanceof Error ? error.name : null,\n };\n if (envelope === null) {\n // ADR-0035: the original bytes are kept; only the dead_letter block is added.\n const original = this.options.queue ?? stripDlqSuffix(topicName(producer.getTopic()));\n // No retry decision was taken, so the value is informational: the delivered count.\n const delivered = counted - 1;\n const deadLetter = annotate({ attempts: delivered } as unknown as Envelope, kind, original, {\n ...details,\n attempts: delivered,\n }).dead_letter;\n const data = message.getData();\n const body = typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data);\n const record = buildPoisonRecord(body, JSON.stringify(deadLetter));\n return keepRoute({ data: Buffer.from(record, \"utf8\"), properties: poisonProperties(record) }, message);\n }\n // The envelope as the next hop will see it: attempts is the counted value, the same one that was\n // compared against maxAttempts and that dead_letter.attempts records.\n const original = envelope.meta?.queue || this.options.queue || stripDlqSuffix(topicName(producer.getTopic()));\n const annotated = annotate({ ...envelope, attempts: counted }, kind, original, details);\n return keepRoute(toPulsarMessage(annotated), message);\n }\n\n private notifyRoutingMismatch(propertyUrn: string, bodyUrn: string, envelope: IncomingEnvelope): void {\n const hook = this.options.onRoutingMismatch;\n if (hook === undefined) return;\n try {\n const result = hook(propertyUrn, bodyUrn, envelope);\n Promise.resolve(result).catch(() => undefined);\n } catch {\n // A diagnostic hook must never disturb consumption.\n }\n }\n}\n\nfunction safeProperties(message: PulsarReceivedMessage): { [key: string]: string } {\n try {\n const properties = typeof message.getProperties === \"function\" ? message.getProperties() : undefined;\n return properties ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Keep the route a delivery arrived on: when the incoming message carries a non-blank `bq-job` property\n * (the consumer routes on it, §5.2/§5.7) the re-published retry or DLQ message carries the same value, even\n * if the body names another URN. Otherwise the second delivery could reach a different handler (Go's\n * `publishKeepingRoute`).\n */\nfunction keepRoute(outgoing: PulsarProducerMessage, incoming: PulsarReceivedMessage): PulsarProducerMessage {\n const route: unknown = safeProperties(incoming)[\"bq-job\"];\n if (typeof route === \"string\" && route.trim() !== \"\") {\n outgoing.properties = { ...outgoing.properties, \"bq-job\": route };\n }\n return outgoing;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** `orders.dlq` -> `orders`: the queue a DLQ topic belongs to (a name without the suffix is kept). */\nfunction stripDlqSuffix(topic: string): string {\n return topic.endsWith(\".dlq\") && topic.length > 4 ? topic.slice(0, -4) : topic;\n}\n\n/**\n * Contract `bq-*` properties for a poison DLQ record, projected from whatever the body carries (a body\n * that is not an object, or carries none of them, yields none).\n */\nfunction poisonProperties(recordJson: string): { [key: string]: string } {\n const properties: { [key: string]: string } = {};\n let record: unknown;\n try {\n record = JSON.parse(recordJson);\n } catch {\n return properties; // nested deeper than JSON.parse can recurse\n }\n if (record === null || typeof record !== \"object\") return properties;\n const top = record as Record<string, unknown>;\n const str = (value: unknown): string | undefined => (typeof value === \"string\" && value !== \"\" ? value : undefined);\n const job = str(top[\"job\"]) ?? str(top[\"urn\"]);\n if (job) properties[\"bq-job\"] = job;\n const trace = str(top[\"trace_id\"]);\n if (trace) properties[\"bq-trace-id\"] = trace;\n const meta = top[\"meta\"] !== null && typeof top[\"meta\"] === \"object\" ? (top[\"meta\"] as Record<string, unknown>) : {};\n const id = str(meta[\"id\"]);\n if (id) properties[\"bq-message-id\"] = id;\n return properties;\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. A nullish input yields an empty 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\n/**\n * Merge out-of-band `extra` headers onto an already-built `base` map **without clobbering** the\n * contract headers in `base` (they win a key collision) and dropping blanks. Returns `base`,\n * mutated in place.\n */\nexport function mergeInto(base: { [key: string]: string }, extra: HeaderCarrier | null | undefined): { [key: string]: string } {\n for (const [key, value] of Object.entries(sanitizeHeaders(extra))) {\n if (key in base) continue; // the contract header already there wins\n base[key] = value;\n }\n return base;\n}\n"],"mappings":";AAyDA,SAAS,iBAAiB,eAAe,gBAAgB,iBAAiB,UAAU,yBAAyB;;;AC1CtG,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;AAOO,SAAS,UAAU,MAAiC,OAAoE;AAC7H,aA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K,CAAC;AAC7C,MAAI,IAAK,YAAW,QAAQ,IAAI;AAChC,QAAM,QAAQ,IAAI,IAAI,UAAU,CAAC;AACjC,MAAI,MAAO,YAAW,aAAa,IAAI;AACvC,QAAM,OAAO,IAAI,MAAM,MAAM,QAAQ,OAAO,IAAI,MAAM,MAAM,WAAY,IAAI,MAAM,IAAgC,CAAC;AACnH,QAAM,KAAK,IAAI,KAAK,IAAI,CAAC;AACzB,MAAI,GAAI,YAAW,eAAe,IAAI;AACtC,SAAO;AACT;","names":["original"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@babelqueue/pulsar",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Apache Pulsar adapter for BabelQueue — canonical-envelope publisher and a URN-routed consumer.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"babelqueue",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"test": "node --import tsx --test test/*.test.ts"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@babelqueue/core": "^1.
|
|
53
|
+
"@babelqueue/core": "^1.13.0"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
56
|
"pulsar-client": "^1.8.0"
|