@warlock.js/herald 5.19.1 → 5.21.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/llms-full.txt CHANGED
@@ -6,225 +6,225 @@
6
6
 
7
7
  ## consume-message `@warlock.js/herald/consume-message/SKILL.md`
8
8
 
9
- ---
10
- name: consume-message
11
- description: "Consume messages in @warlock.js/herald; use when you need to consume message."
12
- ---
13
-
14
- # Consume messages
15
-
16
- Subscribe to a channel; receive each message with a flow-control `ctx`.
17
-
18
- ## Minimal subscribe
19
-
20
- ```ts
21
- import { herald } from "@warlock.js/herald";
22
-
23
- herald()
24
- .channel<{ userId: number; email: string }>("user.created")
25
- .subscribe(async (message, ctx) => {
26
- try {
27
- await sendWelcomeEmail(message.payload.email);
28
- await ctx.ack(); // success — message removed from queue
29
- } catch (error) {
30
- await ctx.nack(true); // failure — requeue for redelivery
31
- }
32
- });
33
- ```
34
-
35
- **Smart auto-ack is on by default** (when `autoAck` is unset or `false`). The consumer runs with manual-ack enabled, and herald acks/nacks based on how your handler ends:
36
-
37
- - Handler returns without calling any `ctx` method → herald **auto-acks**.
38
- - Handler **throws** → herald **auto-nacks** (requeue, or DLQ/reject once retries are exhausted — see below).
39
- - Handler calls `ctx.ack()` / `ctx.nack()` / `ctx.reject()` / `ctx.retry()` → herald respects that and does nothing further.
40
-
41
- So the `try/catch` above is optional — letting the error throw produces the same auto-nack. Call `ctx` methods explicitly only when you want a *non-default* outcome (reject without requeue, route to DLQ, delayed retry). The one mode that loses messages is `autoAck: true`, where the broker acks on delivery before your handler runs.
42
-
43
- ## Message context — flow control
44
-
45
- ```ts
46
- ctx.ack(); // acknowledge — message removed from the queue
47
- ctx.nack(requeue?); // negative ack — requeue (true) or send to DLQ (false)
48
- ctx.reject(); // shorthand for nack(false)
49
- ctx.retry(delayMs); // delayed retry — requeue after delay
50
- ctx.reply(payload); // for request-response pattern (see request-and-respond skill)
51
- ```
52
-
53
- Pick by intent:
54
-
55
- | Intent | Use |
56
- | --- | --- |
57
- | Processed cleanly | `ctx.ack()` |
58
- | Transient failure, try again | `ctx.nack(true)` or `ctx.retry(5000)` |
59
- | Permanent failure, send to DLQ | `ctx.nack(false)` or `ctx.reject()` |
60
- | Validation failure (bad message) | `ctx.reject()` — don't requeue |
61
-
62
- ## Subscribe options
63
-
64
- ```ts
65
- await channel.subscribe(handler, {
66
- group: "email-workers", // consumer group / tag — multiple consumers share work
67
- prefetch: 10, // concurrency — how many in-flight messages this consumer holds
68
- autoAck: false, // default; keep it false in production
69
- exclusive: false, // single consumer only on this channel?
70
- retry: {
71
- maxRetries: 3, // redelivery ceiling on handler throw (delay not auto-applied — see below)
72
- delay: 1000,
73
- },
74
- deadLetter: {
75
- channel: "user.created.failed",
76
- preserveOriginal: true,
77
- },
78
- });
79
- ```
80
-
81
- `group` is the unit of "share work" — N consumers in the same group split messages across them. Different groups each receive every message (fanout).
82
-
83
- `prefetch` is the per-consumer concurrency cap. Higher = throughput; lower = even spread. For CPU-bound handlers, set ~= CPU cores. For IO-bound, can go higher (50+).
84
-
85
- ## Retry policy
86
-
87
- ```ts
88
- retry: {
89
- maxRetries: 3,
90
- delay: 1000, // see the caveat below — delay is not auto-applied
91
- }
92
- ```
93
-
94
- `maxRetries` is the part that does the work: when a handler **throws**, herald reads the message's `x-retry-count` header and, while it's under `maxRetries`, republishes with the header incremented so the count actually advances (a plain requeue never advances it — the broker doesn't add that header). Once `x-retry-count` reaches `maxRetries`, it dead-letters (if `deadLetter` is configured) or drops the message with a loud `log.error` — a poison message can no longer ping-pong forever. This is shared by the automatic throw path and the explicit `ctx.retry()` call, so both honor the same cap.
95
-
96
- **Caveat on `delay`.** `RetryOptions.delay` (number or `(attempt) => number`) is **not applied on the automatic throw path** — a thrown handler requeues immediately, with no wait. The only place a delay takes effect is the explicit `ctx.retry(delayMs)` call, which republishes the message with an `x-delay` header — and even that needs the RabbitMQ delayed-message-exchange plugin installed, or the delay is ignored. So if you need real backoff, call `ctx.retry(ms)` from inside the handler and install the plugin; don't rely on the channel-level `retry.delay` for timing.
97
-
98
- ## Dead-letter queue
99
-
100
- ```ts
101
- deadLetter: {
102
- channel: "user.created.failed",
103
- preserveOriginal: true, // accepted, but currently a no-op (see note)
104
- }
105
- ```
106
-
107
- The DLQ always forwards the full original payload plus the message metadata, so `preserveOriginal` makes no observable difference today — the field is part of the type but the RabbitMQ driver doesn't branch on it yet. Set it or omit it; behaviour is the same.
108
-
109
- Messages that exhausted retries land in `user.created.failed`. Subscribe to it separately for alerting / manual inspection:
110
-
111
- ```ts
112
- herald().channel("user.created.failed").subscribe(async (message, ctx) => {
113
- await alerts.notify(`Failed: ${JSON.stringify(message.payload)}`);
114
- await ctx.ack();
115
- });
116
- ```
117
-
118
- ## Decorator-style consumers — `@Consumable` + `EventConsumer`
119
-
120
- For class-based consumers that pair with the [`EventMessage`](@warlock.js/herald/publish-message/SKILL.md) producer layer. This is a **different handler shape** from the raw `.subscribe()` above — ack/nack is automatic, and you get the unwrapped payload plus an event-metadata object (no `ctx`):
121
-
122
- ```ts
123
- import { Consumable, EventConsumer } from "@warlock.js/herald";
124
- import type { ConsumedEventMessage } from "@warlock.js/herald";
125
-
126
- @Consumable() // or @Consumable({ broker: "analytics" }) to target a non-default broker
127
- export class UserCreatedConsumer extends EventConsumer<{ id: number; email: string }> {
128
- public static eventName = "user.created";
129
-
130
- // handle(payload, event) — NOT (message, ctx). No ctx.ack() here.
131
- public async handle(payload: { id: number; email: string }, event: ConsumedEventMessage) {
132
- await sendWelcomeEmail(payload.email);
133
- // return cleanly → herald acks. throw → herald retries (bounded — see below).
134
- }
135
- }
136
- ```
137
-
138
- The handler receives the **already-unwrapped payload** as the first argument and a `ConsumedEventMessage` as the second — `{ messageId, eventName, payload, version?, occurredAt?, metadata?, message }` (where `message` is the raw `Message` if you need `message.metadata.headers`). There is **no `ctx`**: the framework auto-acks when `handle` resolves, so you never call `ack`/`nack` yourself in this style.
139
-
140
- **A throw is a bounded retry, not an infinite requeue.** `handle` throwing routes through the same bounded-retry routine the raw `.subscribe()` throw path uses (below) — republishes with an incremented `x-retry-count`, capped at `maxRetries: 3` (there's no per-consumer `retry`/`deadLetter` config yet, so the cap is always the default). Once the cap is hit, the message is dropped with a loud `log.error` — never a silent, unbounded ack/nack loop.
141
-
142
- Wiring: the channel name comes from `static eventName`, and `@Consumable` self-registers the moment the class module is **imported** — if a broker is already connected it subscribes immediately, otherwise it buffers and subscribes once `connectToBroker` fires. So the only wiring you need is to import the consumer file on the boot path (e.g. your module's `main.ts`).
143
-
144
- **Pair it with the producer:** an `EventConsumer` expects the envelope shape that `publishEvent(new SomeEvent(...))` emits — it reads `envelope.payload`. Don't point one at a channel fed by a bare `channel(name).publish(rawBody)`; the payload nesting won't match.
145
-
146
- ### Validation + version gating
147
-
148
- Two optional gates run before `handle`, both driven by fields on the class:
149
-
150
- ```ts
151
- import { Consumable, EventConsumer } from "@warlock.js/herald";
152
- import { v } from "@warlock.js/seal";
153
-
154
- @Consumable()
155
- export class UserCreatedConsumer extends EventConsumer {
156
- public static eventName = "user.created";
157
-
158
- // Only accept events whose `version` falls in [minVersion, maxVersion].
159
- // Out-of-range events are acked and skipped (not requeued).
160
- public static minVersion = 2;
161
- public static maxVersion = 3;
162
-
163
- // Seal schema — invalid payloads are nacked before handle() runs.
164
- public schema = v.object({ id: v.int(), email: v.string().email() });
165
-
166
- public async handle(payload, event) {
167
- // payload is validated + version-accepted here
168
- }
169
- }
170
- ```
171
-
172
- ### `defineConsumer` — no-class shorthand
173
-
174
- ```ts
175
- import { defineConsumer } from "@warlock.js/herald";
176
-
177
- export const userCreatedConsumer = defineConsumer<{ id: number; email: string }>("user.created", {
178
- schema: userCreatedSchema, // optional seal validation
179
- handle: async (payload, event) => {
180
- await sendWelcomeEmail(payload.email);
181
- },
182
- });
183
- ```
184
-
185
- `defineConsumer` self-registers via `@Consumable` internally, so importing the module is all the wiring it needs — same as the class form. (`subscribeConsumer(SomeConsumerClass)` is the imperative equivalent if you'd rather register explicitly.)
186
-
187
- ## Subscription handle
188
-
189
- `subscribe()` resolves to a `Subscription` you can manage:
190
-
191
- ```ts
192
- const subscription = await channel.subscribe(handler);
193
-
194
- subscription.id; // the consumer id (string)
195
- subscription.isActive(); // boolean
196
-
197
- await subscription.unsubscribe(); // cancel the consumer on the broker
198
- await subscription.pause(); // also cancels the consumer (RabbitMQ has no native pause)
199
- ```
200
-
201
- On the RabbitMQ driver, `pause()` and `unsubscribe()` both cancel the consumer; `resume()` is **not supported and throws** — create a fresh subscription to start consuming again. You can also cancel by id from the channel: `await channel.unsubscribeById(consumerId)`, or drop every consumer on the channel with `await channel.stopConsuming()`.
202
-
203
- ## Channel admin
204
-
205
- The channel exposes queue-management helpers beyond pub/sub:
206
-
207
- ```ts
208
- const { messageCount, consumerCount } = await channel.stats(); // queue depth + live consumers
209
- const purged = await channel.purge(); // drop all pending messages, returns the count
210
- const ok = await channel.exists(); // does the queue exist on the broker?
211
- await channel.assert(); // create the queue with its options (idempotent)
212
- await channel.delete(); // remove the queue entirely
213
- ```
214
-
215
- `assert()` runs lazily on the first `publish` / `subscribe`, so you rarely call it directly — reach for it only to pre-create a queue before any traffic.
216
-
217
- ## Things NOT to do
218
-
219
- - Don't catch the handler's error and return normally. Smart auto-ack reads a clean return as success and **acks** — silently dropping the work. Let it throw (auto-nack) or call `ctx.reject()` / `ctx.nack(false)` deliberately.
220
- - Don't `ctx.nack(true)` in an infinite loop. With no `retry` policy, a perpetually-failing message ping-pongs forever. Set `retry.maxRetries` + a `deadLetter` so failures eventually move out.
221
- - Don't ignore the `deadLetter` channel. Subscribe to it (or at least monitor its depth) — DLQ growth means real failures piling up.
222
- - Don't use `autoAck: true` for messages that matter. The broker acks on delivery, so a crash mid-handling loses the message.
223
-
224
- ## See also
225
-
226
- - [`@warlock.js/herald/publish-message/SKILL.md`](@warlock.js/herald/publish-message/SKILL.md) — the producing side
227
- - [`@warlock.js/herald/request-and-respond/SKILL.md`](@warlock.js/herald/request-and-respond/SKILL.md) — when you need to reply to a message
9
+ ---
10
+ name: consume-message
11
+ description: 'Subscribe to a channel via .subscribe(handler, options?) — handler receives (message, ctx). Control flow via ctx.ack / ctx.nack(requeue?) / ctx.reject / ctx.retry(delayMs). Configure prefetch, retry policy, dead-letter, consumer groups. Triggers: `subscribe`, `ctx.ack`, `ctx.nack`, `ctx.reject`, `ctx.retry`, `prefetch`, `group`, `retry`, `deadLetter`, `@Consumable`, `EventConsumer`, `defineConsumer`, `autoAck`; "consume messages from a queue", "implement a worker", "background queue processor", "set up retry and dead-letter", "class-based event consumer"; typical import `import { herald, Consumable, EventConsumer } from "@warlock.js/herald"`. Skip: setup — `@warlock.js/herald/herald-basics/SKILL.md`; producing — `@warlock.js/herald/publish-message/SKILL.md`; RPC reply — `@warlock.js/herald/request-and-respond/SKILL.md`; competing libs `amqplib`, `bullmq`, `kafkajs`; NestJS `@MessagePattern` / `@EventPattern`.'
12
+ ---
13
+
14
+ # Consume messages
15
+
16
+ Subscribe to a channel; receive each message with a flow-control `ctx`.
17
+
18
+ ## Minimal subscribe
19
+
20
+ ```ts
21
+ import { herald } from "@warlock.js/herald";
22
+
23
+ herald()
24
+ .channel<{ userId: number; email: string }>("user.created")
25
+ .subscribe(async (message, ctx) => {
26
+ try {
27
+ await sendWelcomeEmail(message.payload.email);
28
+ await ctx.ack(); // success — message removed from queue
29
+ } catch (error) {
30
+ await ctx.nack(true); // failure — requeue for redelivery
31
+ }
32
+ });
33
+ ```
34
+
35
+ **Smart auto-ack is on by default** (when `autoAck` is unset or `false`). The consumer runs with manual-ack enabled, and herald acks/nacks based on how your handler ends:
36
+
37
+ - Handler returns without calling any `ctx` method → herald **auto-acks**.
38
+ - Handler **throws** → herald **auto-nacks** (requeue, or DLQ/reject once retries are exhausted — see below).
39
+ - Handler calls `ctx.ack()` / `ctx.nack()` / `ctx.reject()` / `ctx.retry()` → herald respects that and does nothing further.
40
+
41
+ So the `try/catch` above is optional — letting the error throw produces the same auto-nack. Call `ctx` methods explicitly only when you want a *non-default* outcome (reject without requeue, route to DLQ, delayed retry). The one mode that loses messages is `autoAck: true`, where the broker acks on delivery before your handler runs.
42
+
43
+ ## Message context — flow control
44
+
45
+ ```ts
46
+ ctx.ack(); // acknowledge — message removed from the queue
47
+ ctx.nack(requeue?); // negative ack — requeue (true) or send to DLQ (false)
48
+ ctx.reject(); // shorthand for nack(false)
49
+ ctx.retry(delayMs); // delayed retry — requeue after delay
50
+ ctx.reply(payload); // for request-response pattern (see request-and-respond skill)
51
+ ```
52
+
53
+ Pick by intent:
54
+
55
+ | Intent | Use |
56
+ | --- | --- |
57
+ | Processed cleanly | `ctx.ack()` |
58
+ | Transient failure, try again | `ctx.nack(true)` or `ctx.retry(5000)` |
59
+ | Permanent failure, send to DLQ | `ctx.nack(false)` or `ctx.reject()` |
60
+ | Validation failure (bad message) | `ctx.reject()` — don't requeue |
61
+
62
+ ## Subscribe options
63
+
64
+ ```ts
65
+ await channel.subscribe(handler, {
66
+ group: "email-workers", // consumer group / tag — multiple consumers share work
67
+ prefetch: 10, // concurrency — how many in-flight messages this consumer holds
68
+ autoAck: false, // default; keep it false in production
69
+ exclusive: false, // single consumer only on this channel?
70
+ retry: {
71
+ maxRetries: 3, // redelivery ceiling on handler throw (delay not auto-applied — see below)
72
+ delay: 1000,
73
+ },
74
+ deadLetter: {
75
+ channel: "user.created.failed",
76
+ preserveOriginal: true,
77
+ },
78
+ });
79
+ ```
80
+
81
+ `group` is the unit of "share work" — N consumers in the same group split messages across them. Different groups each receive every message (fanout).
82
+
83
+ `prefetch` is the per-consumer concurrency cap. Higher = throughput; lower = even spread. For CPU-bound handlers, set ~= CPU cores. For IO-bound, can go higher (50+).
84
+
85
+ ## Retry policy
86
+
87
+ ```ts
88
+ retry: {
89
+ maxRetries: 3,
90
+ delay: 1000, // see the caveat below — delay is not auto-applied
91
+ }
92
+ ```
93
+
94
+ `maxRetries` is the part that does the work: when a handler **throws**, herald reads the message's `x-retry-count` header and, while it's under `maxRetries`, republishes with the header incremented so the count actually advances (a plain requeue never advances it — the broker doesn't add that header). Once `x-retry-count` reaches `maxRetries`, it dead-letters (if `deadLetter` is configured) or drops the message with a loud `log.error` — a poison message can no longer ping-pong forever. This is shared by the automatic throw path and the explicit `ctx.retry()` call, so both honor the same cap.
95
+
96
+ **Caveat on `delay`.** `RetryOptions.delay` (number or `(attempt) => number`) is **not applied on the automatic throw path** — a thrown handler requeues immediately, with no wait. The only place a delay takes effect is the explicit `ctx.retry(delayMs)` call, which republishes the message with an `x-delay` header — and even that needs the RabbitMQ delayed-message-exchange plugin installed, or the delay is ignored. So if you need real backoff, call `ctx.retry(ms)` from inside the handler and install the plugin; don't rely on the channel-level `retry.delay` for timing.
97
+
98
+ ## Dead-letter queue
99
+
100
+ ```ts
101
+ deadLetter: {
102
+ channel: "user.created.failed",
103
+ preserveOriginal: true, // accepted, but currently a no-op (see note)
104
+ }
105
+ ```
106
+
107
+ The DLQ always forwards the full original payload plus the message metadata, so `preserveOriginal` makes no observable difference today — the field is part of the type but the RabbitMQ driver doesn't branch on it yet. Set it or omit it; behaviour is the same.
108
+
109
+ Messages that exhausted retries land in `user.created.failed`. Subscribe to it separately for alerting / manual inspection:
110
+
111
+ ```ts
112
+ herald().channel("user.created.failed").subscribe(async (message, ctx) => {
113
+ await alerts.notify(`Failed: ${JSON.stringify(message.payload)}`);
114
+ await ctx.ack();
115
+ });
116
+ ```
117
+
118
+ ## Decorator-style consumers — `@Consumable` + `EventConsumer`
119
+
120
+ For class-based consumers that pair with the [`EventMessage`](@warlock.js/herald/publish-message/SKILL.md) producer layer. This is a **different handler shape** from the raw `.subscribe()` above — ack/nack is automatic, and you get the unwrapped payload plus an event-metadata object (no `ctx`):
121
+
122
+ ```ts
123
+ import { Consumable, EventConsumer } from "@warlock.js/herald";
124
+ import type { ConsumedEventMessage } from "@warlock.js/herald";
125
+
126
+ @Consumable() // or @Consumable({ broker: "analytics" }) to target a non-default broker
127
+ export class UserCreatedConsumer extends EventConsumer<{ id: number; email: string }> {
128
+ public static eventName = "user.created";
129
+
130
+ // handle(payload, event) — NOT (message, ctx). No ctx.ack() here.
131
+ public async handle(payload: { id: number; email: string }, event: ConsumedEventMessage) {
132
+ await sendWelcomeEmail(payload.email);
133
+ // return cleanly → herald acks. throw → herald retries (bounded — see below).
134
+ }
135
+ }
136
+ ```
137
+
138
+ The handler receives the **already-unwrapped payload** as the first argument and a `ConsumedEventMessage` as the second — `{ messageId, eventName, payload, version?, occurredAt?, metadata?, message }` (where `message` is the raw `Message` if you need `message.metadata.headers`). There is **no `ctx`**: the framework auto-acks when `handle` resolves, so you never call `ack`/`nack` yourself in this style.
139
+
140
+ **A throw is a bounded retry, not an infinite requeue.** `handle` throwing routes through the same bounded-retry routine the raw `.subscribe()` throw path uses (below) — republishes with an incremented `x-retry-count`, capped at `maxRetries: 3` (there's no per-consumer `retry`/`deadLetter` config yet, so the cap is always the default). Once the cap is hit, the message is dropped with a loud `log.error` — never a silent, unbounded ack/nack loop.
141
+
142
+ Wiring: the channel name comes from `static eventName`, and `@Consumable` self-registers the moment the class module is **imported** — if a broker is already connected it subscribes immediately, otherwise it buffers and subscribes once `connectToBroker` fires. So the only wiring you need is to import the consumer file on the boot path (e.g. your module's `main.ts`).
143
+
144
+ **Pair it with the producer:** an `EventConsumer` expects the envelope shape that `publishEvent(new SomeEvent(...))` emits — it reads `envelope.payload`. Don't point one at a channel fed by a bare `channel(name).publish(rawBody)`; the payload nesting won't match.
145
+
146
+ ### Validation + version gating
147
+
148
+ Two optional gates run before `handle`, both driven by fields on the class:
149
+
150
+ ```ts
151
+ import { Consumable, EventConsumer } from "@warlock.js/herald";
152
+ import { v } from "@warlock.js/seal";
153
+
154
+ @Consumable()
155
+ export class UserCreatedConsumer extends EventConsumer {
156
+ public static eventName = "user.created";
157
+
158
+ // Only accept events whose `version` falls in [minVersion, maxVersion].
159
+ // Out-of-range events are acked and skipped (not requeued).
160
+ public static minVersion = 2;
161
+ public static maxVersion = 3;
162
+
163
+ // Seal schema — invalid payloads are nacked before handle() runs.
164
+ public schema = v.object({ id: v.int(), email: v.string().email() });
165
+
166
+ public async handle(payload, event) {
167
+ // payload is validated + version-accepted here
168
+ }
169
+ }
170
+ ```
171
+
172
+ ### `defineConsumer` — no-class shorthand
173
+
174
+ ```ts
175
+ import { defineConsumer } from "@warlock.js/herald";
176
+
177
+ export const userCreatedConsumer = defineConsumer<{ id: number; email: string }>("user.created", {
178
+ schema: userCreatedSchema, // optional seal validation
179
+ handle: async (payload, event) => {
180
+ await sendWelcomeEmail(payload.email);
181
+ },
182
+ });
183
+ ```
184
+
185
+ `defineConsumer` self-registers via `@Consumable` internally, so importing the module is all the wiring it needs — same as the class form. (`subscribeConsumer(SomeConsumerClass)` is the imperative equivalent if you'd rather register explicitly.)
186
+
187
+ ## Subscription handle
188
+
189
+ `subscribe()` resolves to a `Subscription` you can manage:
190
+
191
+ ```ts
192
+ const subscription = await channel.subscribe(handler);
193
+
194
+ subscription.id; // the consumer id (string)
195
+ subscription.isActive(); // boolean
196
+
197
+ await subscription.unsubscribe(); // cancel the consumer on the broker
198
+ await subscription.pause(); // also cancels the consumer (RabbitMQ has no native pause)
199
+ ```
200
+
201
+ On the RabbitMQ driver, `pause()` and `unsubscribe()` both cancel the consumer; `resume()` is **not supported and throws** — create a fresh subscription to start consuming again. You can also cancel by id from the channel: `await channel.unsubscribeById(consumerId)`, or drop every consumer on the channel with `await channel.stopConsuming()`.
202
+
203
+ ## Channel admin
204
+
205
+ The channel exposes queue-management helpers beyond pub/sub:
206
+
207
+ ```ts
208
+ const { messageCount, consumerCount } = await channel.stats(); // queue depth + live consumers
209
+ const purged = await channel.purge(); // drop all pending messages, returns the count
210
+ const ok = await channel.exists(); // does the queue exist on the broker?
211
+ await channel.assert(); // create the queue with its options (idempotent)
212
+ await channel.delete(); // remove the queue entirely
213
+ ```
214
+
215
+ `assert()` runs lazily on the first `publish` / `subscribe`, so you rarely call it directly — reach for it only to pre-create a queue before any traffic.
216
+
217
+ ## Things NOT to do
218
+
219
+ - Don't catch the handler's error and return normally. Smart auto-ack reads a clean return as success and **acks** — silently dropping the work. Let it throw (auto-nack) or call `ctx.reject()` / `ctx.nack(false)` deliberately.
220
+ - Don't `ctx.nack(true)` in an infinite loop. With no `retry` policy, a perpetually-failing message ping-pongs forever. Set `retry.maxRetries` + a `deadLetter` so failures eventually move out.
221
+ - Don't ignore the `deadLetter` channel. Subscribe to it (or at least monitor its depth) — DLQ growth means real failures piling up.
222
+ - Don't use `autoAck: true` for messages that matter. The broker acks on delivery, so a crash mid-handling loses the message.
223
+
224
+ ## See also
225
+
226
+ - [`@warlock.js/herald/publish-message/SKILL.md`](@warlock.js/herald/publish-message/SKILL.md) — the producing side
227
+ - [`@warlock.js/herald/request-and-respond/SKILL.md`](@warlock.js/herald/request-and-respond/SKILL.md) — when you need to reply to a message
228
228
 
229
229
 
230
230
  ## herald-basics `@warlock.js/herald/herald-basics/SKILL.md`
@@ -334,255 +334,255 @@ herald("analytics").channel("events").publish({ /* ... */ }); // → analytics
334
334
 
335
335
  ## publish-message `@warlock.js/herald/publish-message/SKILL.md`
336
336
 
337
- ---
338
- name: publish-message
339
- description: "Publish messages in @warlock.js/herald; use when you need to publish message."
340
- ---
341
-
342
- # Publish messages
343
-
344
- Push messages into a channel. The consumer side picks them up via [`@warlock.js/herald/consume-message/SKILL.md`](@warlock.js/herald/consume-message/SKILL.md).
345
-
346
- ## Single publish
347
-
348
- ```ts
349
- import { herald } from "@warlock.js/herald";
350
-
351
- await herald().channel("user.created").publish({
352
- userId: 1,
353
- email: "ada@example.com",
354
- });
355
- ```
356
-
357
- Returns when the broker has accepted the message (not when a consumer has handled it — that's `.request()` territory).
358
-
359
- ## Typed channels
360
-
361
- ```ts
362
- type UserPayload = { userId: number; email: string };
363
-
364
- const channel = herald().channel<UserPayload>("user.created");
365
-
366
- await channel.publish({ userId: 1, email: "test@example.com" }); // ✅ typed
367
- await channel.publish({ userId: "1" } as never); // ❌ compile error
368
- ```
369
-
370
- Share the payload type between producer and consumer via a common `types/` file.
371
-
372
- ## Schema-validated publish
373
-
374
- ```ts
375
- import { v } from "@warlock.js/seal";
376
-
377
- const userSchema = v.object({
378
- userId: v.int(),
379
- email: v.string().email(),
380
- });
381
-
382
- const channel = herald().channel("user.created", { schema: userSchema });
383
-
384
- await channel.publish({ userId: 1, email: "invalid" }); // Throws — fails .email()
385
- ```
386
-
387
- The schema runs `validate()` before the message hits the broker. Invalid payloads never leave the producer. See [`@warlock.js/seal/seal-basics/SKILL.md`](@warlock.js/seal/seal-basics/SKILL.md).
388
-
389
- ## Publish options
390
-
391
- ```ts
392
- await channel.publish(payload, {
393
- priority: 5, // 0-9, higher = served first
394
- expiration: 60_000, // ms — message expires if not consumed (RabbitMQ uses `expiration`, not `ttl`)
395
- delay: 5_000, // ms — delayed delivery (requires RabbitMQ delay plugin)
396
- persistent: true, // survive broker restart (default true)
397
- correlationId: "uuid", // for tracking across services
398
- headers: {
399
- tenantId: "42",
400
- source: "billing-service",
401
- },
402
- });
403
- ```
404
-
405
- The headers field is free-form — consumers read `message.metadata.headers?.tenantId` to route or filter (headers live under `message.metadata`, alongside `messageId`, `correlationId`, `timestamp`, and `retryCount`).
406
-
407
- ## Batch publishing
408
-
409
- ```ts
410
- await channel.publishBatch([
411
- { userId: 1, email: "a@example.com" },
412
- { userId: 2, email: "b@example.com" },
413
- { userId: 3, email: "c@example.com" },
414
- ], {
415
- // Options apply to every message in the batch
416
- persistent: true,
417
- });
418
- ```
419
-
420
- Under the hood `publishBatch` iterates and calls `.publish()` per message — there's no AMQP-level batching today. It's an ergonomic shape for "emit these N items" (bulk import, fanout to many recipients), not a throughput optimization. The same `options` apply to every message.
421
-
422
- ## Publish + transaction (outbox pattern)
423
-
424
- Don't publish inside a database transaction — if the transaction rolls back but the publish already happened, you've emitted an event for a state that never persisted.
425
-
426
- The outbox pattern: write to an `outbox` table inside the transaction, dispatch from the outbox via a worker after commit:
427
-
428
- ```ts
429
- await transaction(async () => {
430
- await Order.create(orderData);
431
- await Outbox.create({
432
- channel: "order.created",
433
- payload: { orderId: order.id, ... },
434
- status: "pending",
435
- });
436
- });
437
-
438
- // In a separate worker:
439
- const pending = await Outbox.where("status", "pending").get();
440
- for (const row of pending) {
441
- await herald().channel(row.get("channel")).publish(row.get("payload"));
442
- await row.merge({ status: "sent", sent_at: new Date() }).save();
443
- }
444
- ```
445
-
446
- Full recipe at `domains/cascade/docs/recipes/outbox-pattern.md`.
447
-
448
- ## Broadcasting use-case results
449
-
450
- `@warlock.js/herald` ships `heraldBroadcast()` — a channel adapter that lets a `@warlock.js/core` `useCase()` publish its result to the bus automatically on success. Register it once in the use-cases config; each use case opts in with `broadcast: true`.
451
-
452
- ```ts title="src/config/use-cases.ts"
453
- import { type UseCaseConfigurations } from "@warlock.js/core";
454
- import { heraldBroadcast } from "@warlock.js/herald";
455
-
456
- export default {
457
- broadcast: {
458
- enabled: true,
459
- channels: [heraldBroadcast({ broker: "default" })], // omit broker for the default
460
- },
461
- } satisfies UseCaseConfigurations;
462
- ```
463
-
464
- ```ts
465
- // The use case opts in — channel name defaults to the use case name.
466
- export const createUserUseCase = useCase({
467
- name: "users.create", // → publishes to channel "users.create"
468
- schema: createUserSchema,
469
- handler: async (data) => User.create(data),
470
- broadcast: true,
471
- });
472
- ```
473
-
474
- The adapter publishes the broadcast envelope's `payload` to `channel(event.event)`. It's structurally typed, so herald keeps no dependency on core. See [`@warlock.js/core/write-use-case/SKILL.md`](@warlock.js/core/write-use-case/SKILL.md) for the `broadcast` option (payload projection, custom event name, payload-safety rules).
475
-
476
- ## Event classes (`EventMessage`) — the typed event layer
477
-
478
- Raw `channel(name).publish(payload)` is the low-level path. For domain events that travel between modules, herald ships a higher-level pair: define the event once as a class, publish instances of it, and consume them with an [`EventConsumer`](@warlock.js/herald/consume-message/SKILL.md). The channel name comes from the event's `eventName` — no string to keep in sync across producer and consumer.
479
-
480
- ```ts
481
- import { defineEvent, publishEvent } from "@warlock.js/herald";
482
-
483
- // `defineEvent<IncomingData, OutgoingData>` — `toJSON` projects the wire payload.
484
- const UserCreatedEvent = defineEvent<User, { id: number; email: string }>("user.created", {
485
- toJSON: (user) => ({ id: user.id, email: user.email }),
486
- // schema?: an @warlock.js/seal ObjectValidator (held on the instance; the consumer side validates)
487
- });
488
-
489
- // `publishEvent` serializes the instance and publishes to channel "user.created" on the default broker.
490
- await publishEvent(new UserCreatedEvent(user));
491
- ```
492
-
493
- `publishEvent(event)` is shorthand for `herald().publish(event)` — it calls `event.serialize()` and sends an **envelope**: `{ payload, metadata, messageId, eventName, version, occurredAt }`. That nesting is why an `EventConsumer` reads `envelope.payload`, not the raw body — pair this only with the consumer side, not a bare `.subscribe()`.
494
-
495
- Set an optional `version` on the event (instance field) to drive the consumer's `minVersion` / `maxVersion` acceptance gate. The class form (`class X extends EventMessage`) is equivalent — override `toJSON()` and set `eventName`, `version`, `schema` as fields.
496
-
497
- ## Things NOT to do
498
-
499
- - Don't publish inside a transaction. Use the outbox pattern.
500
- - Don't pass non-JSON-serializable values (functions, `BigInt`, class instances with methods). Serialization happens at the broker boundary; functions go silent, BigInt throws.
501
- - Don't `expiration: 0` — set a real expiry or omit. `0` means "expire immediately."
502
- - Don't omit `persistent: true` for messages where loss matters. Default is `true` in this lib, but worth being explicit when the message represents money / customer state.
503
- - Don't put secrets in headers. Headers travel in plaintext (encrypted only by TLS in transit, not at rest in the broker).
504
-
505
- ## See also
506
-
507
- - [`@warlock.js/herald/consume-message/SKILL.md`](@warlock.js/herald/consume-message/SKILL.md) — the receiving side
508
- - [`@warlock.js/herald/request-and-respond/SKILL.md`](@warlock.js/herald/request-and-respond/SKILL.md) — when you need a reply
337
+ ---
338
+ name: publish-message
339
+ description: 'Publish messages to a channel — .publish(payload, options?) for single, .publishBatch([...], options?) for batch, with priority / ttl / delay / persistent / correlationId / headers options. Optional schema validation via .channel(name, {schema}). Triggers: `publish`, `publishBatch`, `channel`, `priority`, `ttl`, `delay`, `persistent`, `correlationId`, `headers`, `schema`; "publish a message", "emit an event after a domain change", "fan out a notification", "schedule delayed work", "batch publish"; typical import `import { herald } from "@warlock.js/herald"`. Skip: setup — `@warlock.js/herald/herald-basics/SKILL.md`; consuming — `@warlock.js/herald/consume-message/SKILL.md`; RPC — `@warlock.js/herald/request-and-respond/SKILL.md`; competing libs `amqplib`, `kafkajs`, `bullmq`; NestJS `ClientProxy.emit`.'
340
+ ---
341
+
342
+ # Publish messages
343
+
344
+ Push messages into a channel. The consumer side picks them up via [`@warlock.js/herald/consume-message/SKILL.md`](@warlock.js/herald/consume-message/SKILL.md).
345
+
346
+ ## Single publish
347
+
348
+ ```ts
349
+ import { herald } from "@warlock.js/herald";
350
+
351
+ await herald().channel("user.created").publish({
352
+ userId: 1,
353
+ email: "ada@example.com",
354
+ });
355
+ ```
356
+
357
+ Returns when the broker has accepted the message (not when a consumer has handled it — that's `.request()` territory).
358
+
359
+ ## Typed channels
360
+
361
+ ```ts
362
+ type UserPayload = { userId: number; email: string };
363
+
364
+ const channel = herald().channel<UserPayload>("user.created");
365
+
366
+ await channel.publish({ userId: 1, email: "test@example.com" }); // ✅ typed
367
+ await channel.publish({ userId: "1" } as never); // ❌ compile error
368
+ ```
369
+
370
+ Share the payload type between producer and consumer via a common `types/` file.
371
+
372
+ ## Schema-validated publish
373
+
374
+ ```ts
375
+ import { v } from "@warlock.js/seal";
376
+
377
+ const userSchema = v.object({
378
+ userId: v.int(),
379
+ email: v.string().email(),
380
+ });
381
+
382
+ const channel = herald().channel("user.created", { schema: userSchema });
383
+
384
+ await channel.publish({ userId: 1, email: "invalid" }); // Throws — fails .email()
385
+ ```
386
+
387
+ The schema runs `validate()` before the message hits the broker. Invalid payloads never leave the producer. See [`@warlock.js/seal/seal-basics/SKILL.md`](@warlock.js/seal/seal-basics/SKILL.md).
388
+
389
+ ## Publish options
390
+
391
+ ```ts
392
+ await channel.publish(payload, {
393
+ priority: 5, // 0-9, higher = served first
394
+ expiration: 60_000, // ms — message expires if not consumed (RabbitMQ uses `expiration`, not `ttl`)
395
+ delay: 5_000, // ms — delayed delivery (requires RabbitMQ delay plugin)
396
+ persistent: true, // survive broker restart (default true)
397
+ correlationId: "uuid", // for tracking across services
398
+ headers: {
399
+ tenantId: "42",
400
+ source: "billing-service",
401
+ },
402
+ });
403
+ ```
404
+
405
+ The headers field is free-form — consumers read `message.metadata.headers?.tenantId` to route or filter (headers live under `message.metadata`, alongside `messageId`, `correlationId`, `timestamp`, and `retryCount`).
406
+
407
+ ## Batch publishing
408
+
409
+ ```ts
410
+ await channel.publishBatch([
411
+ { userId: 1, email: "a@example.com" },
412
+ { userId: 2, email: "b@example.com" },
413
+ { userId: 3, email: "c@example.com" },
414
+ ], {
415
+ // Options apply to every message in the batch
416
+ persistent: true,
417
+ });
418
+ ```
419
+
420
+ Under the hood `publishBatch` iterates and calls `.publish()` per message — there's no AMQP-level batching today. It's an ergonomic shape for "emit these N items" (bulk import, fanout to many recipients), not a throughput optimization. The same `options` apply to every message.
421
+
422
+ ## Publish + transaction (outbox pattern)
423
+
424
+ Don't publish inside a database transaction — if the transaction rolls back but the publish already happened, you've emitted an event for a state that never persisted.
425
+
426
+ The outbox pattern: write to an `outbox` table inside the transaction, dispatch from the outbox via a worker after commit:
427
+
428
+ ```ts
429
+ await transaction(async () => {
430
+ await Order.create(orderData);
431
+ await Outbox.create({
432
+ channel: "order.created",
433
+ payload: { orderId: order.id, ... },
434
+ status: "pending",
435
+ });
436
+ });
437
+
438
+ // In a separate worker:
439
+ const pending = await Outbox.where("status", "pending").get();
440
+ for (const row of pending) {
441
+ await herald().channel(row.get("channel")).publish(row.get("payload"));
442
+ await row.merge({ status: "sent", sent_at: new Date() }).save();
443
+ }
444
+ ```
445
+
446
+ Full recipe at `domains/cascade/docs/recipes/outbox-pattern.md`.
447
+
448
+ ## Broadcasting use-case results
449
+
450
+ `@warlock.js/herald` ships `heraldBroadcast()` — a channel adapter that lets a `@warlock.js/core` `useCase()` publish its result to the bus automatically on success. Register it once in the use-cases config; each use case opts in with `broadcast: true`.
451
+
452
+ ```ts title="src/config/use-cases.ts"
453
+ import { type UseCaseConfigurations } from "@warlock.js/core";
454
+ import { heraldBroadcast } from "@warlock.js/herald";
455
+
456
+ export default {
457
+ broadcast: {
458
+ enabled: true,
459
+ channels: [heraldBroadcast({ broker: "default" })], // omit broker for the default
460
+ },
461
+ } satisfies UseCaseConfigurations;
462
+ ```
463
+
464
+ ```ts
465
+ // The use case opts in — channel name defaults to the use case name.
466
+ export const createUserUseCase = useCase({
467
+ name: "users.create", // → publishes to channel "users.create"
468
+ schema: createUserSchema,
469
+ handler: async (data) => User.create(data),
470
+ broadcast: true,
471
+ });
472
+ ```
473
+
474
+ The adapter publishes the broadcast envelope's `payload` to `channel(event.event)`. It's structurally typed, so herald keeps no dependency on core. See [`@warlock.js/core/write-use-case/SKILL.md`](@warlock.js/core/write-use-case/SKILL.md) for the `broadcast` option (payload projection, custom event name, payload-safety rules).
475
+
476
+ ## Event classes (`EventMessage`) — the typed event layer
477
+
478
+ Raw `channel(name).publish(payload)` is the low-level path. For domain events that travel between modules, herald ships a higher-level pair: define the event once as a class, publish instances of it, and consume them with an [`EventConsumer`](@warlock.js/herald/consume-message/SKILL.md). The channel name comes from the event's `eventName` — no string to keep in sync across producer and consumer.
479
+
480
+ ```ts
481
+ import { defineEvent, publishEvent } from "@warlock.js/herald";
482
+
483
+ // `defineEvent<IncomingData, OutgoingData>` — `toJSON` projects the wire payload.
484
+ const UserCreatedEvent = defineEvent<User, { id: number; email: string }>("user.created", {
485
+ toJSON: (user) => ({ id: user.id, email: user.email }),
486
+ // schema?: an @warlock.js/seal ObjectValidator (held on the instance; the consumer side validates)
487
+ });
488
+
489
+ // `publishEvent` serializes the instance and publishes to channel "user.created" on the default broker.
490
+ await publishEvent(new UserCreatedEvent(user));
491
+ ```
492
+
493
+ `publishEvent(event)` is shorthand for `herald().publish(event)` — it calls `event.serialize()` and sends an **envelope**: `{ payload, metadata, messageId, eventName, version, occurredAt }`. That nesting is why an `EventConsumer` reads `envelope.payload`, not the raw body — pair this only with the consumer side, not a bare `.subscribe()`.
494
+
495
+ Set an optional `version` on the event (instance field) to drive the consumer's `minVersion` / `maxVersion` acceptance gate. The class form (`class X extends EventMessage`) is equivalent — override `toJSON()` and set `eventName`, `version`, `schema` as fields.
496
+
497
+ ## Things NOT to do
498
+
499
+ - Don't publish inside a transaction. Use the outbox pattern.
500
+ - Don't pass non-JSON-serializable values (functions, `BigInt`, class instances with methods). Serialization happens at the broker boundary; functions go silent, BigInt throws.
501
+ - Don't `expiration: 0` — set a real expiry or omit. `0` means "expire immediately."
502
+ - Don't omit `persistent: true` for messages where loss matters. Default is `true` in this lib, but worth being explicit when the message represents money / customer state.
503
+ - Don't put secrets in headers. Headers travel in plaintext (encrypted only by TLS in transit, not at rest in the broker).
504
+
505
+ ## See also
506
+
507
+ - [`@warlock.js/herald/consume-message/SKILL.md`](@warlock.js/herald/consume-message/SKILL.md) — the receiving side
508
+ - [`@warlock.js/herald/request-and-respond/SKILL.md`](@warlock.js/herald/request-and-respond/SKILL.md) — when you need a reply
509
509
 
510
510
 
511
511
  ## request-and-respond `@warlock.js/herald/request-and-respond/SKILL.md`
512
512
 
513
- ---
514
- name: request-and-respond
515
- description: "Request-response over the bus in @warlock.js/herald; use when you need to request and respond."
516
- ---
517
-
518
- # Request-response over the bus
519
-
520
- Most messaging is fire-and-forget. When you need a reply, use the request/respond pair — a reply-queue + correlation-id pattern under the hood, surfaced as a typed promise.
521
-
522
- ## Shape
523
-
524
- ```ts
525
- // Caller (client)
526
- const response = await herald()
527
- .channel<RequestPayload>("compute.tax")
528
- .request<TaxResponse>({ amount: 1000, country: "US" }, { timeout: 30_000 });
529
-
530
- // Responder (server)
531
- herald()
532
- .channel<RequestPayload>("compute.tax")
533
- .respond(async (message, ctx) => {
534
- const tax = await computeTax(message.payload);
535
- return { tax, currency: "USD" }; // ← the return value IS the reply
536
- });
537
- ```
538
-
539
- `request` returns a promise that resolves with the responder's return value. `respond` registers a handler and **automatically replies with whatever the handler returns** (then acks) — so just `return` the response; you don't call `ctx.reply()` yourself inside a `respond` handler. (`ctx.reply` is the lower-level primitive used when you wire a plain `.subscribe()` as a responder by hand.)
540
-
541
- ## Timeout
542
-
543
- ```ts
544
- await channel.request(payload, { timeout: 30_000 });
545
- ```
546
-
547
- The promise rejects if no reply arrives within `timeout` ms. Pick a sane number — too short rejects mid-work; too long lets a hung responder block the caller.
548
-
549
- ## When to use it vs HTTP
550
-
551
- | Use HTTP | Use request/respond |
552
- | --- | --- |
553
- | Stateless, fast, idempotent ops | Slow / queued ops where the caller can wait |
554
- | Public API surface | Internal service-to-service |
555
- | Frontend consumption | Backend orchestration |
556
- | Synchronous user-facing flow | Async-but-needs-result patterns |
557
-
558
- The bus adds queue persistence and retry. HTTP is faster for sub-100ms ops; the bus shines when the operation has variable duration or needs a queue's backpressure.
559
-
560
- ## When NOT to use it
561
-
562
- - "I need a result in under 50ms" — too much overhead on the bus.
563
- - "The responder might be down for hours" — request will time out repeatedly; consider `publish` + write the result somewhere the caller polls.
564
- - "Many callers, the response is the same for all" — cache the result and use `publish` for invalidation.
565
-
566
- ## Multiple responders
567
-
568
- `respond(handler)` takes no options — there's no `group` knob here. If multiple consumers `respond()` to the same channel, they all sit on the same queue, so RabbitMQ round-robins between them: **one responder handles each request, and the caller gets exactly one reply.** That's the "share work across responders" pattern — a synchronous worker pool. Make every responder functionally identical, since the caller has no say in which one answers.
569
-
570
- For "multiple replies expected" patterns, use a regular `subscribe` + a request id, then the caller listens on a result channel.
571
-
572
- ## Correlation across replies
573
-
574
- Each `request()` generates its own correlation ID and an exclusive reply queue under the hood. The reply carries the same ID; the client matches it to the awaiting promise and resolves. You don't manage correlation IDs manually — and you shouldn't pass your own `correlationId` on a `request()`, since herald overwrites it with the one it uses to match the reply. To thread your own trace id (e.g. a transaction id for logs) through to the responder, put it in `headers` instead — the responder reads it from `message.metadata.headers`.
575
-
576
- ## Things NOT to do
577
-
578
- - Don't use request/respond for high-throughput, low-latency ops. The reply-queue round-trip adds at least one broker hop. HTTP is the right tool.
579
- - Don't return huge payloads from `respond`. Reply messages travel through the broker; a multi-MB response is a load on the bus and on memory. For big results, write to S3 / cache and reply with a reference.
580
- - Don't forget to `respond` in long-lived consumers. If the responder crashes, every caller's request will time out — they don't know why.
581
- - Don't set timeout to `Infinity`. A stuck request becomes a leaked promise — set a real timeout and handle the rejection.
582
-
583
- ## See also
584
-
585
- - [`@warlock.js/herald/publish-message/SKILL.md`](@warlock.js/herald/publish-message/SKILL.md) — fire-and-forget pattern
586
- - [`@warlock.js/herald/consume-message/SKILL.md`](@warlock.js/herald/consume-message/SKILL.md) — subscribe + ctx flow control (including `ctx.reply`)
513
+ ---
514
+ name: request-and-respond
515
+ description: 'Synchronous-style RPC over the message bus — channel.request<R>(payload, {timeout}) waits for a reply, channel.respond(handler) registers the responder, ctx.reply(response) sends the answer. Triggers: `channel.request`, `channel.respond`, `ctx.reply`, `timeout`, `correlationId`, `headers.correlationId`; "RPC over message bus", "request-response across services", "wait for a reply", "internal service-to-service call instead of HTTP"; typical import `import { herald } from "@warlock.js/herald"`. Skip: setup — `@warlock.js/herald/herald-basics/SKILL.md`; fire-and-forget — `@warlock.js/herald/publish-message/SKILL.md`; consumer ctx flow — `@warlock.js/herald/consume-message/SKILL.md`; competing libs `amqplib` RPC, `nats` request/reply; NestJS `ClientProxy.send`; gRPC; HTTP.'
516
+ ---
517
+
518
+ # Request-response over the bus
519
+
520
+ Most messaging is fire-and-forget. When you need a reply, use the request/respond pair — a reply-queue + correlation-id pattern under the hood, surfaced as a typed promise.
521
+
522
+ ## Shape
523
+
524
+ ```ts
525
+ // Caller (client)
526
+ const response = await herald()
527
+ .channel<RequestPayload>("compute.tax")
528
+ .request<TaxResponse>({ amount: 1000, country: "US" }, { timeout: 30_000 });
529
+
530
+ // Responder (server)
531
+ herald()
532
+ .channel<RequestPayload>("compute.tax")
533
+ .respond(async (message, ctx) => {
534
+ const tax = await computeTax(message.payload);
535
+ return { tax, currency: "USD" }; // ← the return value IS the reply
536
+ });
537
+ ```
538
+
539
+ `request` returns a promise that resolves with the responder's return value. `respond` registers a handler and **automatically replies with whatever the handler returns** (then acks) — so just `return` the response; you don't call `ctx.reply()` yourself inside a `respond` handler. (`ctx.reply` is the lower-level primitive used when you wire a plain `.subscribe()` as a responder by hand.)
540
+
541
+ ## Timeout
542
+
543
+ ```ts
544
+ await channel.request(payload, { timeout: 30_000 });
545
+ ```
546
+
547
+ The promise rejects if no reply arrives within `timeout` ms. Pick a sane number — too short rejects mid-work; too long lets a hung responder block the caller.
548
+
549
+ ## When to use it vs HTTP
550
+
551
+ | Use HTTP | Use request/respond |
552
+ | --- | --- |
553
+ | Stateless, fast, idempotent ops | Slow / queued ops where the caller can wait |
554
+ | Public API surface | Internal service-to-service |
555
+ | Frontend consumption | Backend orchestration |
556
+ | Synchronous user-facing flow | Async-but-needs-result patterns |
557
+
558
+ The bus adds queue persistence and retry. HTTP is faster for sub-100ms ops; the bus shines when the operation has variable duration or needs a queue's backpressure.
559
+
560
+ ## When NOT to use it
561
+
562
+ - "I need a result in under 50ms" — too much overhead on the bus.
563
+ - "The responder might be down for hours" — request will time out repeatedly; consider `publish` + write the result somewhere the caller polls.
564
+ - "Many callers, the response is the same for all" — cache the result and use `publish` for invalidation.
565
+
566
+ ## Multiple responders
567
+
568
+ `respond(handler)` takes no options — there's no `group` knob here. If multiple consumers `respond()` to the same channel, they all sit on the same queue, so RabbitMQ round-robins between them: **one responder handles each request, and the caller gets exactly one reply.** That's the "share work across responders" pattern — a synchronous worker pool. Make every responder functionally identical, since the caller has no say in which one answers.
569
+
570
+ For "multiple replies expected" patterns, use a regular `subscribe` + a request id, then the caller listens on a result channel.
571
+
572
+ ## Correlation across replies
573
+
574
+ Each `request()` generates its own correlation ID and an exclusive reply queue under the hood. The reply carries the same ID; the client matches it to the awaiting promise and resolves. You don't manage correlation IDs manually — and you shouldn't pass your own `correlationId` on a `request()`, since herald overwrites it with the one it uses to match the reply. To thread your own trace id (e.g. a transaction id for logs) through to the responder, put it in `headers` instead — the responder reads it from `message.metadata.headers`.
575
+
576
+ ## Things NOT to do
577
+
578
+ - Don't use request/respond for high-throughput, low-latency ops. The reply-queue round-trip adds at least one broker hop. HTTP is the right tool.
579
+ - Don't return huge payloads from `respond`. Reply messages travel through the broker; a multi-MB response is a load on the bus and on memory. For big results, write to S3 / cache and reply with a reference.
580
+ - Don't forget to `respond` in long-lived consumers. If the responder crashes, every caller's request will time out — they don't know why.
581
+ - Don't set timeout to `Infinity`. A stuck request becomes a leaked promise — set a real timeout and handle the rejection.
582
+
583
+ ## See also
584
+
585
+ - [`@warlock.js/herald/publish-message/SKILL.md`](@warlock.js/herald/publish-message/SKILL.md) — fire-and-forget pattern
586
+ - [`@warlock.js/herald/consume-message/SKILL.md`](@warlock.js/herald/consume-message/SKILL.md) — subscribe + ctx flow control (including `ctx.reply`)
587
587
 
588
588