Reliability & governance helpers
Last updated:
Beyond produce/consume, @babelqueue/core ships optional, zero-dependency helpers that
mechanise the reliability and governance contracts the wire spec defines. None touch the
frozen envelope (schema_version: 1); each is a tooling layer over the codec. They are the
Node face of the cross-SDK spec — follow the linked spec page for the full contract.
Idempotency
Wrap(store, handler) makes a handler run at most once per meta.id, even on
at-least-once redelivery. The Store methods may be sync or async, so a Redis/DB backend
drops straight in.
import { Wrap, InMemoryStore } from "@babelqueue/core";
const store = new InMemoryStore(); // tests / single process
const handler = Wrap(store, async (env) => { await chargeOnce(env.data); });
The in-memory InMemoryStore is the reference; for a fleet, implement the Store interface
(seen / remember / forget) over a shared backend. See
Idempotency and the
store deep-dive.
Transactional outbox
Outbox / OutboxRelay remove the producer dual write: persist the encoded envelope in
the same DB transaction as your business row, then a relay publishes the durable rows
verbatim.
import { Outbox, OutboxRelay, InMemoryOutboxStore } from "@babelqueue/core";
const store = new InMemoryOutboxStore(); // production: a DB-backed OutboxStore
const outbox = new Outbox(store);
// inside YOUR DB transaction, beside the business write — no commit of its own:
const id = await outbox.write(envelope); // encodes via EnvelopeCodec, calls store.save()
// later, a relay drains the durable rows to the broker:
const res = await new OutboxRelay(transport, store).drain(); // res.published / res.failed
OutboxStore is the four-method async contract (save / fetchUnpublished /
markPublished / markFailed); the relay forwards through an OutboxTransport. The
transaction boundary is yours. See Transactional Outbox.
DLQ redrive & replay-bypass
resetForRedrive(envelope) resets a dead-lettered envelope for re-publish (dead_letter
removed, attempts to 0, everything else preserved); the replay guard skips effects that
already fired on a deliberate replay. The delivered headers are passed explicitly (the same
seam the OTel wrapHandler uses):
import { bypassExternalEffects } from "@babelqueue/core";
async function handler(env, headers) {
await saveOrder(env.data); // idempotent core
await bypassExternalEffects(headers, () => sendEmail(env.data)); // skipped on replay
}
RedriveIO.publishWithHeaders stamps the bq-replay-bypass marker on a header-carrying
transport. See DLQ redrive & replay-bypass.
GDPR field encryption
protect / unprotect encrypt only the data leaves a schema marks x-gdpr-sensitive, in
place. Cipher is caller-bound and AesGcmCipher (on the built-in node:crypto) is the
reference. Validate cleartext — protect after validation on produce, unprotect before
validation on consume.
import { protect, unprotect, AesGcmCipher } from "@babelqueue/core";
const cipher = new AesGcmCipher(key); // or implement Cipher over a KMS
protect(data, schema, cipher); // producer: encrypt marked leaves
try {
unprotect(data, schema, cipher); // consumer: inverse
} catch (e) {
// DecryptError → wrong key / tampered → retry / dead-letter
}
OpenTelemetry (spans, metrics and traceparent)
The @babelqueue/core/otel subpath emits a send <queue> span on publish and a
process <queue> span per handled message, plus the standard metrics, and — on a
header-carrying transport — injects/extracts the W3C traceparent so a consumer span is a true
child of the producer span (degrading to trace_id correlation otherwise). Every
babelqueue-node-adapters transport carries the header on its native metadata channel.
@opentelemetry/api is the only optional dependency.
Dashboard-breaking change. Spans are now
send <queue>/process <queue>(they werepublish <urn>/process <urn>), and the URN is thebabelqueue.urnattribute. Passsystemsomessaging.systemis the broker. Not passing it is deprecated. The migration table is in Observability.
The options are an options object:
| Option | Applies to | Meaning |
|---|---|---|
system: "kafka" |
wrapHandler, publish, createDeadLetterObserver |
the messaging.system value (the broker) |
consumerGroup: "billing" |
wrapHandler |
messaging.consumer.group.name, consumer span only |
meter |
wrapHandler, publish, createDeadLetterObserver |
an OpenTelemetry Meter; without it nothing is recorded as a metric |
SEMCONV_VERSION (1.44.0) and SEMCONV_SCHEMA_URL are exported next to them. wrapHandler
takes its options as the fourth argument (the third is the delivered headers, see below).
import { wrapHandler, publish, createDeadLetterObserver } from "@babelqueue/core/otel";
import type { HeaderCarrier } from "@babelqueue/core";
import { RabbitMQConsumer, RabbitMQPublisher } from "@babelqueue/rabbitmq";
const otelOptions = { system: "rabbitmq", meter };
// consumer: "process <queue>" span + consumed / retries / duration metrics.
// The adapter hands the delivered headers to the handler's third argument; give them to
// wrapHandler so the span is a child of the producer span (ADR-0028).
const consumer = new RabbitMQConsumer(
channel,
"orders",
{
"urn:babel:orders:created": (envelope, _message, headers) =>
wrapHandler(tracer, onOrderCreated, headers, otelOptions)(envelope),
},
{
// dead-letter observer: feeds babelqueue.dlq.messages from the adapter
deadLetterObserver: createDeadLetterObserver(otelOptions),
},
);
// producer: "send <queue>" span + sent metric. The carrier receives the span's traceparent;
// the adapter writes it onto the message, beside the envelope.
const publisher = RabbitMQPublisher.create(channel, "orders");
const headers: HeaderCarrier = {};
await publish(
tracer,
"urn:babel:orders:created",
{ order_id: 1042 },
(envelope) => publisher.publishEnvelope(envelope, { headers }),
{ queue: "orders", headers, ...otelOptions },
);
publisher.publishEnvelope(envelope, { headers }) sends the envelope publish built, exactly as
given, so the producer span’s messaging.message.id is the meta.id that reaches the wire: the
ids match. (publisher.publish(urn, data, …) still builds its own envelope; do not use it as the
send callback.) publishEnvelope does not stamp meta.queue, so pass queue equal to the
publisher’s destination — without it meta.queue is "default", the span is named
send default, and a dead-letter record or a redrive points at the wrong queue. The eight
adapter packages (every one but @babelqueue/nestjs) have publishEnvelope; @babelqueue/bullmq
exposes it as a function, publishEnvelope(queue, envelope, options).
Without the headers argument on wrapHandler, and without headers on publish and the
adapter’s publish, no traceparent travels and the consumer span falls back to the
trace_id-derived parent. The metric instruments are created once per meter, so calling
wrapHandler per delivery is cheap. The other adapters expose the same headers
(@babelqueue/rabbitmq also has a headersOf(...) extractor).
Where the observer is wired. The Node core has no consume runtime, so each adapter package
that writes DLQ records takes the observer as an optional deadLetterObserver option on its
consumer options: @babelqueue/rabbitmq (RabbitMQConsumerOptions), @babelqueue/sqs
(SqsConsumerOptions), @babelqueue/redis (RedisConsumerOptions), @babelqueue/kafka
(KafkaConsumerOptions), @babelqueue/pulsar (PulsarConsumerOptions), @babelqueue/artemis
(ArtemisConsumerOptions), @babelqueue/azure-service-bus (AsbConsumerOptions) and
@babelqueue/bullmq (ProcessorOptions). @babelqueue/nestjs writes no DLQ records. The
observer is called after a confirmed DLQ write (or, on Azure Service Bus, a successful native
deadLetterMessage); a throw or a rejected promise is logged and never changes how the message
is settled. It is not called when DLQ writing is disabled (for example deadLetterQueue: null).
What babelqueue.dlq.messages counts. It counts a dead-letter the SDK itself carried out
and confirmed: a record written to the BabelQueue DLQ, and a native dead-letter the SDK
initiated (on Azure Service Bus, the SDK’s own DeadLetterMessage / deadLetter call made when
the BabelQueue DLQ is off). There is no attribute that tells the two apart. It does not count a
dead-letter the broker makes on its own (MaxDeliveryCount, SQS RedrivePolicy), the SQS
native no-op, a failed DLQ write, or a message dropped because DLQ writing is disabled.
On Azure Service Bus, do not add this counter to the broker’s own dead-letter metric: the
messages the SDK dead-letters natively are in both, so the sum counts them twice.
To put trace_id, meta.id and job on your log lines, see
Log correlation. The span shape, attribute tables, system
values, the migration from the earlier publish <urn> shape and the full metric list are in
Observability.
Per-URN schema validation
await schema.validate(provider, urn, data) (producer guard, async; rejects with InvalidPayloadError —
schema.check resolves with the violation instead of rejecting) / schema.wrap(provider, handler)
(consumer safety net) validate a message’s data against the JSON Schema registered for its
URN; schema.MapProvider embeds schemas in code. These live on the schema namespace export
(import { schema } from "@babelqueue/core"). See
Per-URN schema validation.