@projected/messaging 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,188 @@
1
+ import {
2
+ DependencyFailure,
3
+ OperationDefect,
4
+ Result,
5
+ isInfrastructureError,
6
+ noTelemetry,
7
+ propagate,
8
+ traceCarrier,
9
+ type AnyContracts,
10
+ type AnyOperationContract,
11
+ type Application,
12
+ type CommandQueue,
13
+ type IdGenerator,
14
+ type OperationResult,
15
+ type Principal,
16
+ type Telemetry,
17
+ } from "@projected/application";
18
+ import { z } from "zod";
19
+ import type { Disposition, MessageTransport, Subscription } from "./transport.js";
20
+
21
+ const PrincipalSchema = z.object({
22
+ id: z.string(),
23
+ kind: z.enum(["user", "service"]),
24
+ permissions: z.array(z.string()),
25
+ claims: z.record(z.string(), z.unknown()),
26
+ });
27
+
28
+ /** A command travelling through a broker. The same `{ type, version, data }` shape as an HTTP batch item. */
29
+ export const CommandMessage = z.object({
30
+ kind: z.literal("command"),
31
+ type: z.string(),
32
+ version: z.number().int().positive(),
33
+ data: z.unknown(),
34
+ metadata: z.object({
35
+ messageId: z.string(),
36
+ correlationId: z.string(),
37
+ causationId: z.string().optional(),
38
+ /** On whose behalf the command was sent. Trusted only as far as the broker is (see `consumeCommands`). */
39
+ principal: PrincipalSchema.optional(),
40
+ }),
41
+ });
42
+ export type CommandMessage = z.infer<typeof CommandMessage>;
43
+
44
+ export interface CommandQueueOptions {
45
+ readonly topic: string;
46
+ readonly ids: IdGenerator;
47
+ /** Records a producer span per command and puts its trace context in the message headers. */
48
+ readonly telemetry?: Telemetry;
49
+ }
50
+
51
+ /**
52
+ * A {@link CommandQueue} over a {@link MessageTransport}: send another service's (or your own)
53
+ * commands for asynchronous processing. Input is validated before sending, so a malformed
54
+ * command fails here rather than in someone else's dead-letter queue. The sender's principal
55
+ * travels with the command.
56
+ */
57
+ export function commandQueue<C extends AnyContracts>(
58
+ contracts: C,
59
+ transport: MessageTransport,
60
+ options: CommandQueueOptions,
61
+ ): CommandQueue<C> {
62
+ const telemetry = options.telemetry ?? noTelemetry;
63
+ return {
64
+ contracts,
65
+ enqueue: async (contract, input, context) => {
66
+ const { type, version, key } = contract as AnyOperationContract;
67
+ const data = (contract as AnyOperationContract).input.safeParse(input);
68
+ if (!data.success) {
69
+ return Result.err(
70
+ new DependencyFailure({
71
+ dependency: contracts.name,
72
+ message: `${contracts.name}: invalid input for command ${key}`,
73
+ cause: data.error,
74
+ }),
75
+ );
76
+ }
77
+ return telemetry.span(
78
+ `send ${contracts.name}/${key}`,
79
+ { kind: "producer", attributes: { "messaging.destination.name": options.topic, "projected.operation.type": type } },
80
+ async () => {
81
+ const messageId = options.ids.next();
82
+ const metadata = propagate(context);
83
+ const body: CommandMessage = {
84
+ kind: "command",
85
+ type,
86
+ version,
87
+ data: input,
88
+ metadata: {
89
+ messageId,
90
+ correlationId: metadata.correlationId ?? messageId,
91
+ ...(metadata.causationId === undefined ? {} : { causationId: metadata.causationId }),
92
+ ...(metadata.principal === undefined
93
+ ? {}
94
+ : {
95
+ principal: {
96
+ ...metadata.principal,
97
+ permissions: [...metadata.principal.permissions],
98
+ claims: { ...metadata.principal.claims },
99
+ },
100
+ }),
101
+ },
102
+ };
103
+ const headers: Record<string, string> = {};
104
+ telemetry.inject(headers);
105
+ const published = await transport.publish(options.topic, { id: messageId, body, headers });
106
+ return published.map(() => ({ messageId }));
107
+ },
108
+ );
109
+ },
110
+ };
111
+ }
112
+
113
+ export interface ConsumeCommandsOptions {
114
+ readonly topic: string;
115
+ /** Competing-consumer group. Defaults to the application's name. */
116
+ readonly group?: string;
117
+ /**
118
+ * Whose authority the commands run with. `"from-message"` (the default) trusts the principal
119
+ * the sender attached — right when only your own services can publish to the topic. Pass a
120
+ * fixed service principal when the topic is shared more widely.
121
+ */
122
+ readonly principal?: "from-message" | Principal;
123
+ /** Observe each business outcome — async commands have no caller waiting for it. */
124
+ readonly onOutcome?: (command: CommandMessage, result: OperationResult) => void;
125
+ /** Called for messages that cannot be processed and are dead-lettered. */
126
+ readonly onRejected?: (body: unknown, reason: string) => void;
127
+ }
128
+
129
+ /**
130
+ * The messaging driving adapter: run queued commands through the application. Business
131
+ * outcomes (success or a declared error) are acknowledged; infrastructure errors are retried;
132
+ * unknown operations, invalid input, refused access and defects are dead-lettered. The message
133
+ * id is the idempotency key, so a redelivered command is never run twice when the application
134
+ * has idempotency configured.
135
+ */
136
+ export function consumeCommands<C extends AnyContracts>(
137
+ app: Application<C>,
138
+ transport: MessageTransport,
139
+ options: ConsumeCommandsOptions,
140
+ ): Promise<Subscription> {
141
+ const telemetry = app.telemetry;
142
+ return transport.subscribe(
143
+ options.topic,
144
+ (message): Promise<Disposition> =>
145
+ telemetry.continueFrom(traceCarrier(message.headers), () =>
146
+ telemetry.span(
147
+ `receive ${options.topic}`,
148
+ { kind: "consumer", attributes: { "messaging.destination.name": options.topic, "messaging.message.id": message.id } },
149
+ async (span): Promise<Disposition> => {
150
+ const parsed = CommandMessage.safeParse(message.body);
151
+ if (!parsed.success) {
152
+ options.onRejected?.(message.body, "not a command message");
153
+ span.fail("not a command message");
154
+ return "dead-letter";
155
+ }
156
+ const command = parsed.data;
157
+ const principal =
158
+ options.principal === undefined || options.principal === "from-message"
159
+ ? command.metadata.principal
160
+ : options.principal;
161
+ const outcome = await app.dispatch({
162
+ kind: "command",
163
+ type: command.type,
164
+ version: command.version,
165
+ input: command.data,
166
+ metadata: {
167
+ messageId: command.metadata.messageId,
168
+ correlationId: command.metadata.correlationId,
169
+ causationId: command.metadata.causationId,
170
+ idempotencyKey: command.metadata.messageId,
171
+ ...(principal === undefined ? {} : { principal }),
172
+ },
173
+ });
174
+ if (outcome.isOk()) {
175
+ options.onOutcome?.(command, outcome.value);
176
+ return "ack";
177
+ }
178
+ // In progress elsewhere, conflicting or unavailable: all may succeed on redelivery.
179
+ if (isInfrastructureError(outcome.error) || outcome.error._tag === "RequestInProgress") return "retry";
180
+ options.onRejected?.(message.body, OperationDefect.is(outcome.error) ? "defect" : outcome.error.message);
181
+ span.fail(outcome.error.message);
182
+ return "dead-letter";
183
+ },
184
+ ),
185
+ ),
186
+ { group: options.group ?? app.contracts.name },
187
+ );
188
+ }
package/src/events.ts ADDED
@@ -0,0 +1,103 @@
1
+ import {
2
+ OperationDefect,
3
+ handleTraced,
4
+ noTelemetry,
5
+ traceCarrier,
6
+ type AnyEventDefinition,
7
+ type EventHandler,
8
+ type RecordedEvent,
9
+ type Telemetry,
10
+ } from "@projected/application";
11
+ import { z } from "zod";
12
+ import type { Disposition, MessageTransport, Subscription } from "./transport.js";
13
+
14
+ /** A recorded event travelling through a broker. Exactly the {@link RecordedEvent} shape. */
15
+ export const EventMessage = z.object({
16
+ eventId: z.string(),
17
+ stream: z.string(),
18
+ streamVersion: z.number().int().positive(),
19
+ globalPosition: z.number().int().positive(),
20
+ type: z.string(),
21
+ schemaVersion: z.number().int().positive(),
22
+ data: z.unknown(),
23
+ metadata: z.record(z.string(), z.unknown()),
24
+ recordedAt: z.string(),
25
+ });
26
+
27
+ export interface EventRelayOptions {
28
+ /** Kebab-case; also the relay's checkpoint name. */
29
+ readonly name: string;
30
+ readonly topic: string;
31
+ /** Only relay these events. Defaults to every event in the store. */
32
+ readonly events?: readonly AnyEventDefinition[];
33
+ }
34
+
35
+ /** The trace context an event was recorded under, if any. */
36
+ const eventTrace = (recorded: RecordedEvent) => {
37
+ const trace = recorded.metadata.trace;
38
+ return traceCarrier(typeof trace === "object" && trace !== null ? (trace as Record<string, unknown>) : undefined);
39
+ };
40
+
41
+ /**
42
+ * An event handler that publishes recorded events to a topic. Register it with the
43
+ * application's event handling: it reads the store from its checkpoint, so the event store acts
44
+ * as the outbox and nothing is lost between "saved" and "published". At-least-once. Events are
45
+ * keyed by stream, so a partitioned broker keeps each aggregate's events in order, and carry the
46
+ * trace they were recorded under.
47
+ */
48
+ export function eventRelay(transport: MessageTransport, options: EventRelayOptions): EventHandler {
49
+ const types = options.events?.map((definition) => definition.type);
50
+ const handles = (type: string) => types === undefined || types.includes(type);
51
+ return {
52
+ name: options.name,
53
+ eventTypes: types ?? [],
54
+ handles,
55
+ handle: async (recorded) =>
56
+ transport.publish(options.topic, {
57
+ id: recorded.eventId,
58
+ key: recorded.stream,
59
+ body: recorded,
60
+ headers: eventTrace(recorded) ?? {},
61
+ }),
62
+ };
63
+ }
64
+
65
+ export interface ConsumeEventsOptions {
66
+ readonly topic: string;
67
+ /** Competing-consumer group. Defaults to the handler's name, so each handler sees every event. */
68
+ readonly group?: string;
69
+ /** Each handled event gets a span, continuing the trace it was recorded under. */
70
+ readonly telemetry?: Telemetry;
71
+ readonly onRejected?: (body: unknown, reason: string) => void;
72
+ }
73
+
74
+ /**
75
+ * Feed events published by another service (through {@link eventRelay}) to one of your event
76
+ * handlers — typically a projection built from that service's event definitions.
77
+ */
78
+ export function consumeEvents(
79
+ handler: EventHandler,
80
+ transport: MessageTransport,
81
+ options: ConsumeEventsOptions,
82
+ ): Promise<Subscription> {
83
+ const telemetry = options.telemetry ?? noTelemetry;
84
+ return transport.subscribe(
85
+ options.topic,
86
+ async (message): Promise<Disposition> => {
87
+ const parsed = EventMessage.safeParse(message.body);
88
+ if (!parsed.success) {
89
+ options.onRejected?.(message.body, "not an event message");
90
+ return "dead-letter";
91
+ }
92
+ const recorded = parsed.data as RecordedEvent;
93
+ if (!handler.handles(recorded.type)) return "ack";
94
+ const outcome = await handleTraced(handler, recorded, telemetry);
95
+ if (outcome.isOk()) return "ack";
96
+ // A defect will not pass on redelivery: set the event aside. Anything else may.
97
+ if (!OperationDefect.is(outcome.error)) return "retry";
98
+ options.onRejected?.(message.body, outcome.error.message);
99
+ return "dead-letter";
100
+ },
101
+ { group: options.group ?? handler.name },
102
+ );
103
+ }
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @projected/messaging — asynchronous driving and driven adapters. Import it only from
3
+ * `src/infrastructure/**`.
4
+ */
5
+ export {
6
+ DEAD_LETTER_REASON_HEADER,
7
+ REPLAY_HEADER,
8
+ deadLetterTopic,
9
+ type Disposition,
10
+ type Message,
11
+ type MessageTransport,
12
+ type OutgoingMessage,
13
+ type SubscribeOptions,
14
+ type Subscription,
15
+ transportReadiness,
16
+ } from "./transport.js";
17
+ export { inMemoryTransport, type InMemoryDelivery, type InMemoryTransport, type InMemoryTransportOptions } from "./memory.js";
18
+ export { CommandMessage, commandQueue, consumeCommands, type CommandQueueOptions, type ConsumeCommandsOptions } from "./commands.js";
19
+ export { EventMessage, consumeEvents, eventRelay, type ConsumeEventsOptions, type EventRelayOptions } from "./events.js";
20
+ export { deadLetterReplay, type DeadLetterReplayOptions } from "./replay.js";
21
+ export { sleep, withTimeout } from "./timing.js";
package/src/memory.ts ADDED
@@ -0,0 +1,298 @@
1
+ import { DependencyUnavailable, Result } from "@projected/application";
2
+ import {
3
+ DEAD_LETTER_REASON_HEADER,
4
+ deadLetterTopic,
5
+ type Disposition,
6
+ type Message,
7
+ type MessageTransport,
8
+ type OutgoingMessage,
9
+ type Subscription,
10
+ } from "./transport.js";
11
+
12
+ /**
13
+ * When `publish` returns, and who delivers:
14
+ *
15
+ * - `"acknowledged"` — the transport delivers at once, and `publish` returns when every consumer
16
+ * group subscribed to the topic has handled the message. A relay or policy only moves its
17
+ * checkpoint past an event once its consumers are done, so a crash loses nothing: after a
18
+ * restart they publish it again. At-least-once, as with a broker.
19
+ * - `"async"` — the transport delivers at once, and `publish` returns as soon as the message is
20
+ * queued. Faster; a message not yet handled when the process dies is lost.
21
+ * - `"queued"` — nothing is delivered until {@link InMemoryTransport.drain}: for tests that step
22
+ * through.
23
+ */
24
+ export type InMemoryDelivery = "acknowledged" | "async" | "queued";
25
+
26
+ export interface InMemoryTransportOptions {
27
+ /** Defaults to `"acknowledged"`. */
28
+ readonly delivery?: InMemoryDelivery;
29
+ /** Deliveries per message before it is dead-lettered. Defaults to 3. */
30
+ readonly maxAttempts?: number;
31
+ /** Wait before delivery `attempt + 1`, except when queued. Defaults to 50 ms doubling, at most 2 s. */
32
+ readonly retryDelayMs?: (attempt: number) => number;
33
+ /**
34
+ * Messages kept per topic for consumer groups that subscribe later, and at most waiting for a
35
+ * group with no subscriber; also the length of `published` and `deadLetters`. Defaults to 10 000.
36
+ */
37
+ readonly retain?: number;
38
+ /** How long an acknowledged `publish` waits for its consumers before it fails. Defaults to 30 s. */
39
+ readonly ackTimeoutMs?: number;
40
+ /** A consumer that threw (its message is retried), or a message dropped for lack of room. */
41
+ readonly onError?: (error: unknown) => void;
42
+ /** A message set aside, and why. Dead letters live in memory: log or store them to keep them. */
43
+ readonly onDeadLetter?: (message: Message, reason: string) => void;
44
+ }
45
+
46
+ /** A {@link MessageTransport} within one process, with no broker. */
47
+ export interface InMemoryTransport extends MessageTransport {
48
+ /**
49
+ * Deliver what is waiting. Queued: deliver everything, retries included, and return the number
50
+ * of deliveries. Otherwise: wait until nothing is waiting or being delivered.
51
+ */
52
+ drain(): Promise<number>;
53
+ /** Deliver what is waiting, then stop: later publishes fail, and so does `ping()`. */
54
+ close(): Promise<void>;
55
+ /** The latest messages published, oldest first. */
56
+ readonly published: readonly Message[];
57
+ /** The latest messages dead-lettered, oldest first. */
58
+ readonly deadLetters: readonly Message[];
59
+ }
60
+
61
+ type Handler = (message: Message) => Promise<Disposition>;
62
+
63
+ /** One message waiting for one group, and the publisher waiting on it, if any. */
64
+ interface Pending {
65
+ readonly message: Message;
66
+ settle?: ((handled: boolean) => void) | undefined;
67
+ }
68
+
69
+ interface Group {
70
+ readonly name: string;
71
+ readonly members: Handler[];
72
+ next: number;
73
+ readonly pending: Pending[];
74
+ /** The group's delivery loop while it runs: one message at a time, in order. */
75
+ running?: Promise<void> | undefined;
76
+ }
77
+
78
+ interface Topic {
79
+ readonly log: Message[];
80
+ readonly groups: Map<string, Group>;
81
+ }
82
+
83
+ const defaultRetryDelay = (attempt: number) => Math.min(50 * 2 ** (attempt - 1), 2_000);
84
+
85
+ /** Tell the waiting publisher, once, whether its group handled the message. */
86
+ const settle = (pending: Pending, handled: boolean) => {
87
+ const waiting = pending.settle;
88
+ pending.settle = undefined;
89
+ waiting?.(handled);
90
+ };
91
+
92
+ /** A copy as a broker would give it back: through JSON. */
93
+ const asJson = <T>(value: T): T => (value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T));
94
+
95
+ /**
96
+ * Create an {@link InMemoryTransport}: a broker's semantics within one process — consumer groups
97
+ * that each get every message, members of a group taking turns, per-key order, bounded
98
+ * redelivery and `<topic>.dead-letter` — so that `consumeCommands`, `consumeEvents` and
99
+ * `eventRelay` work the same with or without Kafka or NATS. Each group handles one message at a
100
+ * time; a message asking to be retried is redelivered before anything after it.
101
+ *
102
+ * With `"acknowledged"` delivery, subscribe consumers before relays start: a message published
103
+ * while a topic has no consumer group is kept only in memory, for groups that subscribe later.
104
+ */
105
+ export function inMemoryTransport(options: InMemoryTransportOptions = {}): InMemoryTransport {
106
+ const delivery = options.delivery ?? "acknowledged";
107
+ const maxAttempts = options.maxAttempts ?? 3;
108
+ const retryDelay = options.retryDelayMs ?? defaultRetryDelay;
109
+ const retain = options.retain ?? 10_000;
110
+ const ackTimeoutMs = options.ackTimeoutMs ?? 30_000;
111
+ const onError = options.onError ?? (() => undefined);
112
+
113
+ const topics = new Map<string, Topic>();
114
+ const published: Message[] = [];
115
+ const deadLetters: Message[] = [];
116
+ let closed = false;
117
+ let deliveries = 0;
118
+
119
+ const keepLast = <T>(list: T[], item: T, onDrop?: (dropped: T) => void) => {
120
+ list.push(item);
121
+ while (list.length > retain) {
122
+ const dropped = list.shift();
123
+ if (dropped !== undefined) onDrop?.(dropped);
124
+ }
125
+ };
126
+ const topicOf = (name: string): Topic => {
127
+ let topic = topics.get(name);
128
+ if (topic === undefined) topics.set(name, (topic = { log: [], groups: new Map() }));
129
+ return topic;
130
+ };
131
+ const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
132
+
133
+ const deadLetter = (message: Message, reason: string) => {
134
+ const dead: Message = { ...message, topic: deadLetterTopic(message.topic), headers: { ...message.headers, [DEAD_LETTER_REASON_HEADER]: reason }, attempt: 1 };
135
+ keepLast(deadLetters, dead);
136
+ options.onDeadLetter?.(dead, reason);
137
+ enqueue(dead);
138
+ };
139
+
140
+ /** Hand `message` to every group of its topic, each telling `waitFor` how it went; returns how many groups. */
141
+ const enqueue = (message: Message, waitFor?: (handled: boolean) => void): number => {
142
+ const topic = topicOf(message.topic);
143
+ keepLast(topic.log, message);
144
+ let groups = 0;
145
+ for (const group of topic.groups.values()) {
146
+ groups++;
147
+ keepLast(group.pending, { message, ...(waitFor === undefined ? {} : { settle: waitFor }) }, (dropped) => {
148
+ settle(dropped, false);
149
+ onError(new Error(`in-memory transport: group ${group.name} dropped ${dropped.message.id} on ${message.topic}, more than ${retain} waiting`));
150
+ });
151
+ schedule(group);
152
+ }
153
+ return groups;
154
+ };
155
+
156
+ /** Deliver the group's head message once, and say what became of it. */
157
+ const deliverHead = async (group: Group, retryAt: "now" | "later"): Promise<"done" | "retry" | "idle"> => {
158
+ const head = group.pending[0];
159
+ const member = group.members[group.next % Math.max(group.members.length, 1)];
160
+ if (head === undefined || member === undefined) return "idle";
161
+ group.next++;
162
+ deliveries++;
163
+ let disposition: Disposition;
164
+ try {
165
+ disposition = await member(head.message);
166
+ } catch (error) {
167
+ onError(error);
168
+ disposition = "retry";
169
+ }
170
+ const { message } = head;
171
+ if (disposition === "retry" && message.attempt < maxAttempts) {
172
+ // In place: nothing after it reaches the group first, so per-key order holds.
173
+ group.pending[0] = { ...head, message: { ...message, attempt: message.attempt + 1 } };
174
+ if (retryAt === "later") await wait(retryDelay(message.attempt));
175
+ return "retry";
176
+ }
177
+ group.pending.shift();
178
+ if (disposition !== "ack") deadLetter(message, disposition === "dead-letter" ? "rejected" : `failed ${maxAttempts} deliveries`);
179
+ settle(head, true);
180
+ return "done";
181
+ };
182
+
183
+ /** Start the group's delivery loop on a later tick, never inside the publisher's call. */
184
+ const schedule = (group: Group) => {
185
+ if (delivery === "queued" || group.running !== undefined || closed) return;
186
+ group.running = (async () => {
187
+ await wait(0);
188
+ while (!closed && (await deliverHead(group, "later")) !== "idle");
189
+ })().finally(() => {
190
+ group.running = undefined;
191
+ if (!closed && group.pending.length > 0 && group.members.length > 0) schedule(group);
192
+ });
193
+ };
194
+
195
+ const allGroups = () => [...topics.values()].flatMap((topic) => [...topic.groups.values()]);
196
+ const busy = () => allGroups().filter((group) => group.running !== undefined || (group.pending.length > 0 && group.members.length > 0));
197
+
198
+ const drain = async (): Promise<number> => {
199
+ const before = deliveries;
200
+ if (closed) return 0;
201
+ for (let groups = busy(); groups.length > 0; groups = busy()) {
202
+ if (delivery === "queued") {
203
+ for (const group of groups) while ((await deliverHead(group, "now")) !== "idle");
204
+ } else {
205
+ groups.forEach(schedule);
206
+ await Promise.all(groups.map((group) => group.running));
207
+ }
208
+ }
209
+ return deliveries - before;
210
+ };
211
+
212
+ const unavailable = (message: string) => Result.err(new DependencyUnavailable({ dependency: "in-memory transport", message: `in-memory transport: ${message}` }));
213
+
214
+ return {
215
+ get published() {
216
+ return [...published];
217
+ },
218
+ get deadLetters() {
219
+ return [...deadLetters];
220
+ },
221
+
222
+ ping: async () => (closed ? unavailable("closed") : Result.ok(undefined)),
223
+
224
+ publish: async (topicName, outgoing: OutgoingMessage) => {
225
+ if (closed) return unavailable(`closed, cannot publish to ${topicName}`);
226
+ let message: Message;
227
+ try {
228
+ message = { id: outgoing.id, key: outgoing.key ?? outgoing.id, topic: topicName, body: asJson(outgoing.body), headers: asJson({ ...outgoing.headers }), attempt: 1 };
229
+ } catch {
230
+ // A broker would fail to serialize it too; nothing was sent.
231
+ return unavailable(`the body for ${topicName} is not JSON`);
232
+ }
233
+ keepLast(published, message);
234
+ if (delivery !== "acknowledged") {
235
+ enqueue(message);
236
+ return Result.ok(undefined);
237
+ }
238
+ // A group nobody listens to cannot acknowledge: it keeps the message, and the publisher hears
239
+ // at once that it is not done — rather than at its timeout, or never.
240
+ const absent = [...(topics.get(topicName)?.groups.values() ?? [])].filter((group) => group.members.length === 0).map((group) => group.name);
241
+ if (absent.length > 0) {
242
+ enqueue(message);
243
+ return unavailable(`no subscriber in group ${absent.join(", ")} for ${topicName}; kept for it`);
244
+ }
245
+ let outstanding = 0;
246
+ let failed = false;
247
+ let done: () => void = () => {};
248
+ const acknowledged = new Promise<void>((resolve) => (done = resolve));
249
+ outstanding = enqueue(message, (handled) => {
250
+ failed ||= !handled;
251
+ if (--outstanding === 0) done();
252
+ });
253
+ if (outstanding === 0) return Result.ok(undefined);
254
+ let timer: ReturnType<typeof setTimeout> | undefined;
255
+ const timedOut = new Promise<"timeout">((resolve) => (timer = setTimeout(() => resolve("timeout"), ackTimeoutMs)));
256
+ const outcome = await Promise.race([acknowledged, timedOut]);
257
+ clearTimeout(timer);
258
+ if (outcome === "timeout") return unavailable(`no acknowledgement for ${message.id} on ${topicName} within ${ackTimeoutMs} ms`);
259
+ return failed ? unavailable(`${message.id} on ${topicName} was not acknowledged before its consumers stopped`) : Result.ok(undefined);
260
+ },
261
+
262
+ subscribe: async (topicName, handler, subscribeOptions = {}) => {
263
+ if (closed) throw new Error(`in-memory transport: closed, cannot subscribe to ${topicName}`);
264
+ const topic = topicOf(topicName);
265
+ const name = subscribeOptions.group ?? "default";
266
+ let group = topic.groups.get(name);
267
+ if (group === undefined) {
268
+ group = { name, members: [], next: 0, pending: topic.log.map((message) => ({ message })) };
269
+ topic.groups.set(name, group);
270
+ }
271
+ const joined = group;
272
+ joined.members.push(handler);
273
+ schedule(joined);
274
+ return {
275
+ close: async () => {
276
+ const index = joined.members.indexOf(handler);
277
+ if (index === -1) return;
278
+ joined.members.splice(index, 1);
279
+ if (joined.members.length > 0) return;
280
+ await joined.running;
281
+ // Publishers waiting on this group learn now, rather than at their timeout.
282
+ for (const pending of joined.pending) settle(pending, false);
283
+ },
284
+ } satisfies Subscription;
285
+ },
286
+
287
+ drain,
288
+
289
+ close: async () => {
290
+ if (closed) return;
291
+ if (delivery !== "queued") await drain();
292
+ closed = true;
293
+ const groups = allGroups();
294
+ await Promise.all(groups.map((group) => group.running));
295
+ for (const group of groups) for (const pending of group.pending) settle(pending, false);
296
+ },
297
+ };
298
+ }
package/src/replay.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { Result, defineOperatorTask, z, type DependencyUnavailable, type OperatorTask } from "@projected/application";
2
+ import { sleep } from "./timing.js";
3
+ import { DEAD_LETTER_REASON_HEADER, REPLAY_HEADER, deadLetterTopic, type MessageTransport } from "./transport.js";
4
+
5
+ export interface DeadLetterReplayOptions {
6
+ /** The topics whose dead letters may be replayed: the ones this service consumes. */
7
+ readonly topics: readonly [string, ...string[]];
8
+ /**
9
+ * The consumer group reading the dead-letter topics. The broker keeps its position, so each
10
+ * dead letter is replayed once. Defaults to `projected-dead-letter-replay`.
11
+ */
12
+ readonly group?: string;
13
+ /** Finish once no dead letter has arrived for this long. Defaults to 2 s. */
14
+ readonly idleMs?: number;
15
+ /** Finish after this long, whatever is still arriving; the rest waits for the next run. Defaults to 60 s. */
16
+ readonly maxMs?: number;
17
+ }
18
+
19
+ /**
20
+ * The `replay-dead-letters` operator task: publish a topic's dead letters back to the topic, under
21
+ * their own ids, once whatever made them fail is fixed. Commands rerun (a dead-lettered command
22
+ * never completed, so its idempotency key is free) and events reach their consumers again.
23
+ *
24
+ * ```ts
25
+ * createApplication(contracts, { ..., operatorTasks: [deadLetterReplay(transport, { topics: ["billing.commands"] })] });
26
+ * ```
27
+ */
28
+ export function deadLetterReplay(transport: MessageTransport, options: DeadLetterReplayOptions): OperatorTask {
29
+ const group = options.group ?? "projected-dead-letter-replay";
30
+ const idleMs = options.idleMs ?? 2000;
31
+ const maxMs = options.maxMs ?? 60_000;
32
+ return defineOperatorTask({
33
+ name: "replay-dead-letters",
34
+ description: `Publish a topic's dead letters back to it, once what made them fail is fixed. Topics: ${options.topics.join(", ")}.`,
35
+ input: z.object({ topic: z.enum(options.topics) }),
36
+ run: async ({ topic }) => {
37
+ const replay = globalThis.crypto.randomUUID();
38
+ const started = Date.now();
39
+ let lastArrival = started;
40
+ let replayed = 0;
41
+ let failure: DependencyUnavailable | undefined;
42
+ const subscription = await transport.subscribe(
43
+ deadLetterTopic(topic),
44
+ async (message) => {
45
+ lastArrival = Date.now();
46
+ const { [DEAD_LETTER_REASON_HEADER]: _reason, ...headers } = message.headers;
47
+ const published = await transport.publish(topic, {
48
+ id: message.id,
49
+ key: message.key ?? message.id,
50
+ body: message.body,
51
+ headers: { ...headers, [REPLAY_HEADER]: replay },
52
+ });
53
+ if (published.isErr()) {
54
+ failure = published.error;
55
+ // Unacknowledged, so not lost: redelivered to the next run (or dead-lettered again once the transport gives up).
56
+ return "retry";
57
+ }
58
+ replayed++;
59
+ return "ack";
60
+ },
61
+ { group },
62
+ );
63
+ while (failure === undefined && Date.now() - lastArrival < idleMs && Date.now() - started < maxMs) await sleep(Math.min(idleMs, 50));
64
+ await subscription.close();
65
+ return failure === undefined ? Result.ok({ topic, replayed }) : Result.err(failure);
66
+ },
67
+ });
68
+ }