better-ship 0.39.1 → 0.40.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.
Files changed (46) hide show
  1. package/dist/{application-Dsz-o9Aj.js → application-xXTCe8o0.js} +104 -38
  2. package/dist/application-xXTCe8o0.js.map +1 -0
  3. package/dist/application.d.ts +2 -2
  4. package/dist/application.js +1 -1
  5. package/dist/cloudflare/queue.d.ts +55 -48
  6. package/dist/cloudflare/queue.d.ts.map +1 -1
  7. package/dist/cloudflare/queue.js +27 -14
  8. package/dist/cloudflare/queue.js.map +1 -1
  9. package/dist/cloudflare.d.ts +8 -8
  10. package/dist/cloudflare.d.ts.map +1 -1
  11. package/dist/cloudflare.js +24 -29
  12. package/dist/cloudflare.js.map +1 -1
  13. package/dist/{index-BMY7ylgk.d.ts → index-Db2GV9ZP.d.ts} +111 -72
  14. package/dist/index-Db2GV9ZP.d.ts.map +1 -0
  15. package/dist/{metrics-CdTF_lWR.d.ts → metrics-DRCoGBNF.d.ts} +2 -2
  16. package/dist/{metrics-CdTF_lWR.d.ts.map → metrics-DRCoGBNF.d.ts.map} +1 -1
  17. package/dist/{outbox-repository-options-q-CGUoCr.d.ts → outbox-repository-options-Cmf0vbBQ.d.ts} +4 -6
  18. package/dist/{outbox-repository-options-q-CGUoCr.d.ts.map → outbox-repository-options-Cmf0vbBQ.d.ts.map} +1 -1
  19. package/dist/{outbox-repository-options-Ca67c3c9.js → outbox-repository-options-Dd-s5SxA.js} +4 -8
  20. package/dist/{outbox-repository-options-Ca67c3c9.js.map → outbox-repository-options-Dd-s5SxA.js.map} +1 -1
  21. package/dist/postgres.d.ts +8 -8
  22. package/dist/postgres.d.ts.map +1 -1
  23. package/dist/postgres.js +23 -27
  24. package/dist/postgres.js.map +1 -1
  25. package/dist/posthog/metrics.d.ts +1 -1
  26. package/dist/posthog/server.d.ts +2 -2
  27. package/dist/resend.d.ts +1 -1
  28. package/dist/sentry/server.d.ts +1 -1
  29. package/dist/testing/outbox-repository.d.ts +1 -1
  30. package/dist/testing/outbox-repository.js +35 -50
  31. package/dist/testing/outbox-repository.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/application/index.ts +6 -9
  34. package/src/application/outbox-publisher.ts +15 -0
  35. package/src/application/outbox-relay.ts +132 -66
  36. package/src/application/outbox-repository.ts +18 -18
  37. package/src/application/outbox-wake.ts +8 -0
  38. package/src/application/unit-of-work.ts +2 -2
  39. package/src/infrastructure/cloudflare/d1-outbox-repository.ts +36 -52
  40. package/src/infrastructure/cloudflare/queue/queue-client.ts +41 -23
  41. package/src/infrastructure/cloudflare/queue/wait-until-wake.ts +2 -2
  42. package/src/infrastructure/outbox-repository-options.ts +2 -4
  43. package/src/infrastructure/postgres/postgres-outbox-repository.ts +31 -41
  44. package/src/infrastructure/testing/outbox-repository-contract.ts +36 -37
  45. package/dist/application-Dsz-o9Aj.js.map +0 -1
  46. package/dist/index-BMY7ylgk.d.ts.map +0 -1
@@ -1,4 +1,4 @@
1
- import { D as unreachable, O as DatabaseError, d as classifyFailure, r as createLogger, tt as AppError } from "./core-DOBZeYSX.js";
1
+ import { D as unreachable, O as DatabaseError, d as classifyFailure, r as createLogger, s as exponentialDelayCapMs, tt as AppError } from "./core-DOBZeYSX.js";
2
2
  import { panic } from "better-result";
3
3
 
4
4
  //#region src/application/analytics-service.ts
@@ -140,75 +140,141 @@ var MessageBus = class {
140
140
  //#region src/application/outbox-relay.ts
141
141
  const logger = createLogger("outbox-relay");
142
142
  /**
143
- * Publishes committed events with bounded durable retries. Ported from Typist's relay with per-row exhaustion.
144
- * Send failures are recorded; repository failures propagate to the wake or scheduled boundary.
143
+ * Moves committed events out of the outbox: claims due rows, sends their events through the publisher,
144
+ * and records each result on its row. A repository failure propagates to the caller.
145
145
  */
146
146
  var OutboxRelay = class {
147
147
  publisher;
148
- repository;
148
+ outboxRepo;
149
+ now;
149
150
  options;
150
- constructor(publisher, repository, options = {}) {
151
+ constructor(publisher, outboxRepo, options = {}, now = () => /* @__PURE__ */ new Date()) {
151
152
  this.publisher = publisher;
152
- this.repository = repository;
153
+ this.outboxRepo = outboxRepo;
154
+ this.now = now;
153
155
  this.options = {
154
156
  batchSize: options.batchSize ?? 50,
155
157
  maxBatches: options.maxBatches ?? 10,
156
- maxAttempts: options.maxAttempts ?? 10
158
+ maxAttempts: options.maxAttempts ?? 10,
159
+ retryBaseDelayMs: options.retryBaseDelayMs ?? 1e3,
160
+ retryMaxDelayMs: options.retryMaxDelayMs ?? 6e4
157
161
  };
158
162
  }
159
- /** Return the claimed count, including released and dead-lettered rows. Zero means no due rows. */
163
+ /**
164
+ * Runs one batch: claims due rows, marks rows with no attempt left failed, and publishes the rest.
165
+ * Called by `drain()`. Returns the claimed count; zero means no row was due.
166
+ */
160
167
  async flush() {
161
- const claim = await this.repository.claimPending(this.options.batchSize);
162
- const exhausted = claim.messages.filter((row) => row.attempts > this.options.maxAttempts);
163
- await this.deadLetter(claim, exhausted, "exhausted", "Claim attempt limit exceeded");
164
- const pending = claim.messages.filter((row) => row.attempts <= this.options.maxAttempts);
165
- if (pending.length === 0) return claim.messages.length;
166
- let oversized;
168
+ const batch = await this.outboxRepo.claimDueRows(this.options.batchSize);
169
+ const { exhaustedRows, dueRows } = this.splitByAttemptsLeft(batch.rows);
170
+ await this.markFailed(batch.token, exhaustedRows, "exhausted", "Claim attempt limit exceeded");
171
+ if (dueRows.length > 0) await this.publishDueRows(batch.token, dueRows);
172
+ return batch.rows.length;
173
+ }
174
+ /** Sends the rows' events, marks the delivered rows published, and fails or retries the rest by their error. */
175
+ async publishDueRows(claimToken, dueRows) {
176
+ const rejectedEvents = await this.publishEvents(dueRows);
177
+ const rejectedEventIds = new Set(rejectedEvents.map(({ message: event }) => event.id));
178
+ const deliveredRows = dueRows.filter((row) => !rejectedEventIds.has(row.payload.id));
179
+ if (deliveredRows.length > 0) await this.outboxRepo.markPublished(claimToken, deliveredRows);
180
+ for (const [error, rows] of rowsByError(rejectedEvents, dueRows)) await this.failOrRetry(claimToken, rows, error);
181
+ }
182
+ /** Publishes the rows' events. A thrown publish counts as every event rejected with that error. */
183
+ async publishEvents(rows) {
184
+ const events = rows.map((row) => row.payload);
167
185
  try {
168
- oversized = await this.publisher.sendBatchPartial(pending.map((row) => row.payload));
186
+ return await this.publisher.publish(events);
169
187
  } catch (error) {
170
- await this.handleSendFailure(claim, pending, error);
171
- return claim.messages.length;
188
+ return events.map((event) => ({
189
+ message: event,
190
+ error
191
+ }));
172
192
  }
173
- const oversizedIds = new Set(oversized.map((event) => event.id));
174
- await this.deadLetter(claim, pending.filter((row) => oversizedIds.has(row.payload.id)), "oversized", "Exceeds queue message size limit");
175
- const sent = pending.filter((row) => !oversizedIds.has(row.payload.id));
176
- if (sent.length > 0) await this.repository.markPublished(claim, sent);
177
- return claim.messages.length;
178
193
  }
179
- /** Drain until an empty claim or the batch limit; return the total claimed count. */
194
+ /**
195
+ * Runs batches until no row is due: at most `maxBatches` × `batchSize` rows, 500 by default. Called
196
+ * after a commit through `waitUntilWake`, and by the app's cron sweep. Returns the total claimed count.
197
+ */
180
198
  async drain() {
181
199
  let total = 0;
182
- for (let batch = 0; batch < this.options.maxBatches; batch += 1) {
200
+ for (let batchCount = 0; batchCount < this.options.maxBatches; batchCount += 1) {
183
201
  const claimed = await this.flush();
184
202
  total += claimed;
185
203
  if (claimed === 0) break;
186
204
  }
187
205
  return total;
188
206
  }
189
- async handleSendFailure(claim, pending, cause) {
207
+ /**
208
+ * Decides fail or retry for rows whose events were not delivered: the whole send failed, or one event
209
+ * was rejected. Marks them failed on a terminal error or a last attempt; releases the rest for retry.
210
+ */
211
+ async failOrRetry(claimToken, rows, cause) {
190
212
  const classification = classifyFailure(cause);
191
- const message = cause instanceof Error ? cause.message : "Publisher rejected with a non-error value";
213
+ const errorMessage = cause instanceof Error ? cause.message : "Publisher rejected with a non-error value";
192
214
  if (classification === "terminal") {
193
- await this.deadLetter(claim, pending, "terminal", message, cause);
215
+ await this.markFailed(claimToken, rows, "terminal", errorMessage, cause);
194
216
  return;
195
217
  }
196
- const exhausted = pending.filter((row) => row.attempts >= this.options.maxAttempts);
197
- await this.deadLetter(claim, exhausted, "exhausted", message, cause);
198
- const retry = pending.filter((row) => row.attempts < this.options.maxAttempts);
199
- if (retry.length > 0) await this.repository.releaseClaim(claim, retry);
218
+ const { exhaustedRows, retryRows } = this.splitByLastAttempt(rows);
219
+ await this.markFailed(claimToken, exhaustedRows, "exhausted", errorMessage, cause);
220
+ await this.releaseForRetry(claimToken, retryRows);
200
221
  }
201
- async deadLetter(claim, messages, reason, errorMessage, cause) {
202
- if (messages.length === 0) return;
203
- await this.repository.deadLetter(claim, messages, reason, errorMessage);
204
- logger.error("outbox_messages_dead_lettered", {
222
+ /** Releases rows for another attempt. Each row waits longer the more attempts it has used. */
223
+ async releaseForRetry(claimToken, rows) {
224
+ const now = this.now().getTime();
225
+ for (const attempts of new Set(rows.map((row) => row.attempts))) {
226
+ const delayMs = exponentialDelayCapMs(this.options.retryBaseDelayMs, this.options.retryMaxDelayMs, attempts);
227
+ const rowsWithSameDelay = rows.filter((row) => row.attempts === attempts);
228
+ await this.outboxRepo.releaseClaim(claimToken, rowsWithSameDelay, new Date(now + delayMs));
229
+ }
230
+ }
231
+ /** Splits claimed rows: rows whose last run crashed with no attempt left, and rows that may run now. */
232
+ splitByAttemptsLeft(rows) {
233
+ return {
234
+ exhaustedRows: rows.filter((row) => this.hasNoAttemptLeft(row)),
235
+ dueRows: rows.filter((row) => !this.hasNoAttemptLeft(row))
236
+ };
237
+ }
238
+ /** Splits failed rows: rows that just used their last attempt, and rows that may retry. */
239
+ splitByLastAttempt(rows) {
240
+ return {
241
+ exhaustedRows: rows.filter((row) => this.isLastAttempt(row)),
242
+ retryRows: rows.filter((row) => !this.isLastAttempt(row))
243
+ };
244
+ }
245
+ /** True when the row used every attempt before this claim: its last run crashed, so it must not run again. */
246
+ hasNoAttemptLeft(row) {
247
+ return row.attempts > this.options.maxAttempts;
248
+ }
249
+ /** True when the run that just failed was the row's last allowed attempt, so it must not be retried. */
250
+ isLastAttempt(row) {
251
+ return row.attempts >= this.options.maxAttempts;
252
+ }
253
+ /** Calls `outboxRepo.markFailed`, then logs one error. Does nothing for an empty list. */
254
+ async markFailed(claimToken, rows, reason, errorMessage, cause) {
255
+ if (rows.length === 0) return;
256
+ await this.outboxRepo.markFailed(claimToken, rows, reason, errorMessage);
257
+ logger.error("outbox_rows_failed", {
205
258
  error: cause,
206
- claimToken: claim.token,
207
- count: messages.length,
259
+ claimToken,
260
+ count: rows.length,
208
261
  reason
209
262
  });
210
263
  }
211
264
  };
265
+ /** Groups the rejected events' rows by error object, so one error decides fail or retry for all its rows at once. */
266
+ function rowsByError(rejectedEvents, rows) {
267
+ const rowByEventId = new Map(rows.map((row) => [row.payload.id, row]));
268
+ const groups = /* @__PURE__ */ new Map();
269
+ for (const { message: event, error } of rejectedEvents) {
270
+ const row = rowByEventId.get(event.id);
271
+ if (row === void 0) continue;
272
+ const group = groups.get(error) ?? [];
273
+ group.push(row);
274
+ groups.set(error, group);
275
+ }
276
+ return groups;
277
+ }
212
278
 
213
279
  //#endregion
214
280
  //#region src/application/outbox-retention.ts
@@ -289,4 +355,4 @@ var UnitOfWorkAlreadyActiveError = class extends AppError {
289
355
 
290
356
  //#endregion
291
357
  export { MessageBus as a, RecordingEmailService as c, OutboxRelay as i, NULL_METRICS_SERVICE as l, UnitOfWork as n, MessageAlreadyProcessedError as o, OutboxRetention as r, recordEmailEvent as s, UnitOfWorkAlreadyActiveError as t, NULL_ANALYTICS as u };
292
- //# sourceMappingURL=application-Dsz-o9Aj.js.map
358
+ //# sourceMappingURL=application-xXTCe8o0.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-xXTCe8o0.js","names":["logger"],"sources":["../src/application/analytics-service.ts","../src/application/metrics-service.ts","../src/application/email-service.ts","../src/application/record-email-event.ts","../src/application/message-already-processed.error.ts","../src/application/message-bus.ts","../src/application/outbox-relay.ts","../src/application/outbox-retention.ts","../src/application/unit-of-work.ts","../src/application/unit-of-work.errors.ts"],"sourcesContent":["import type { AnalyticsEventInput, AnalyticsProperties, AnalyticsTarget } from '@/core'\n\n/** The properties of one event name; an untyped service accepts any properties. */\nexport type AnalyticsPropertiesOf<\n TEvent extends AnalyticsEventInput,\n TName extends TEvent['name'],\n> = string extends TEvent['name']\n ? TEvent['properties']\n : Extract<TEvent, { readonly name: TName }>['properties']\n\n/** Product analytics without an SDK dependency, ported from Typist and Porte. */\nexport interface AnalyticsService<TEvent extends AnalyticsEventInput = AnalyticsEventInput> {\n /** Attach traits to one person. */\n identify(distinctId: string, properties?: AnalyticsProperties): void\n /** Merge a previous ID into this person; the application must establish that both identify the same person. */\n alias(distinctId: string, previousDistinctId: string): void\n /** Schedule an event for a person; returning does not confirm remote acceptance. */\n track<TName extends TEvent['name']>(\n name: TName,\n properties: AnalyticsPropertiesOf<TEvent, TName>,\n target: AnalyticsTarget,\n ): void\n /** Schedule an event without creating a person profile for its distinct ID. */\n trackAnonymous<TName extends TEvent['name']>(\n name: TName,\n properties: AnalyticsPropertiesOf<TEvent, TName>,\n target: AnalyticsTarget,\n ): void\n}\n\n/**\n * Reports to nobody. The composition root selects this service when analytics is disabled.\n * `satisfies` keeps its own type, so it serves an `AnalyticsService` of any event map.\n */\nexport const NULL_ANALYTICS = {\n identify: () => {},\n alias: () => {},\n track: (\n _name: string,\n _properties: AnalyticsEventInput['properties'],\n _target: AnalyticsTarget,\n ) => {},\n trackAnonymous: (\n _name: string,\n _properties: AnalyticsEventInput['properties'],\n _target: AnalyticsTarget,\n ) => {},\n} satisfies AnalyticsService\n","/** A metric dimension; use a small, bounded value set and never user or request IDs. */\nexport type MetricAttributeValue = string | number | boolean\n\n/** Dimensions shared by observations in one time series. */\nexport type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>\n\n/** Unit and dimensions for an operational measurement. */\nexport interface MetricOptions {\n readonly attributes?: MetricAttributes\n readonly unit?: string\n}\n\n/** Operational measurements, ported from Typist's metrics-service.ts; applications own metric names. */\nexport interface MetricsService<TName extends string = string> {\n /** Add a nonnegative value to a total; the default increment is one. */\n count(name: TName, value?: number, options?: MetricOptions): void\n /** Record a current value. */\n gauge(name: TName, value: number, options?: MetricOptions): void\n /** Record one observation in a distribution. */\n histogram(name: TName, value: number, options?: MetricOptions): void\n}\n\n/** Records nothing when the composition root disables metrics. */\nexport const NULL_METRICS_SERVICE: MetricsService = {\n count: () => {},\n gauge: () => {},\n histogram: () => {},\n}\n","import type { EmailIdempotencyKey } from '@/core'\n\n/** A media type such as `application/pdf`. */\nexport type MimeType = `${string}/${string}`\n\n/** A file to attach. Binary content is bytes; the adapter encodes it for the provider. */\nexport type EmailAttachment = {\n readonly filename: string\n readonly content: string | Uint8Array\n /** Optional MIME metadata; Resend accepts filename and content without it. */\n readonly contentType?: MimeType\n}\n\n/**\n * One transactional email. Resend accepts 50 recipients, 75 tags with ASCII names and values,\n * and 40 MB of attachments after base64. Sources: https://resend.com/docs/api-reference/emails/send-email\n * and https://resend.com/docs/dashboard/emails/tags\n */\nexport type OutboundEmail = {\n /** Override the default for this email, for example \"Display Name <address@domain.com>\". */\n readonly from?: string\n readonly to: string | readonly string[]\n readonly subject: string\n readonly html: string\n /** Optional stable identity of this send. Resend deduplicates supplied keys for 24 hours. */\n readonly idempotencyKey?: EmailIdempotencyKey\n /** Resend generates plain text from html when omitted. An empty string disables that generation. */\n readonly text?: string\n readonly replyTo?: string\n /** Labels the provider stores with the email and returns on every delivery event. */\n readonly tags?: Readonly<Record<string, string>>\n readonly attachments?: readonly EmailAttachment[]\n}\n\n/** Received email headers, without the body or attachments. */\nexport type ReceivedEmail = { readonly headers: Readonly<Record<string, string>> }\n\n/** One attachment of a received email. `downloadUrl` is a signed link that stops working at `expiresAt`. */\nexport type ReceivedAttachment = {\n readonly filename: string | null\n readonly contentType: string\n readonly size: number\n readonly downloadUrl: string\n readonly expiresAt: string\n}\n\n/** A received email's sender, plain text body, and attachments, for an application that reads mail it receives. */\nexport type ReceivedContent = {\n /** The sender as the email states it, for example \"Display Name <address@domain.com>\". */\n readonly from: string\n readonly text: string | null\n readonly attachments: readonly ReceivedAttachment[]\n}\n\n/** The provider accepted the email and assigned its id. */\nexport type EmailAccepted = { readonly providerId: string }\n\n/**\n * The adapter supplies the default sender and maps provider errors. Each email can override the sender.\n * A provider rejection throws `EmailServiceError`; unexpected SDK rejections propagate unchanged.\n */\nexport interface IEmailService {\n /** Resolve after provider acceptance; this does not confirm delivery to the recipient. */\n sendEmail(email: OutboundEmail): Promise<EmailAccepted>\n}\n\n/** Records every send for a test. Provider ids count up as `recorded-1`, `recorded-2`. */\nexport class RecordingEmailService implements IEmailService {\n /** Sends in call order, including repeated idempotency keys. */\n readonly sent: OutboundEmail[] = []\n\n /** Record the send before returning its provider id. */\n async sendEmail(email: OutboundEmail): Promise<EmailAccepted> {\n this.sent.push(email)\n return { providerId: `recorded-${this.sent.length}` }\n }\n}\n","import type { BounceType, DomainCommand, EmailAddress, RecordEmailEventPayload } from '@/core'\n\nimport type { IUnitOfWork } from './unit-of-work.ts'\n\n/** What a bounce records for one address. */\nexport type EmailBounceRecord = {\n readonly type: BounceType\n readonly subType: string | null\n}\n\n/**\n * The application's deliverability state per address. An implementation keeps the higher bounce\n * severity with `shouldUpdateBounce`, and treats an unknown address as nothing to record.\n */\nexport interface IEmailDeliverabilityStore {\n /** Keep the higher severity atomically. Equal severity permits replacement; the store owns timestamp ordering. */\n recordBounce(address: EmailAddress, bounce: EmailBounceRecord): Promise<void>\n /** Record a complaint without clearing existing suppression state. */\n recordComplaint(address: EmailAddress): Promise<void>\n}\n\n/** The repositories the handler needs from the unit of work. */\nexport type RecordEmailEventRepos = { readonly emailDeliverability: IEmailDeliverabilityStore }\n\n/** The container slice the handler reads. */\nexport type RecordEmailEventDeps = { readonly uow: IUnitOfWork<RecordEmailEventRepos> }\n\n/** The command, under whatever name the application registered the payload. */\nexport type RecordEmailEventCommand = DomainCommand & RecordEmailEventPayload\n\n/**\n * Record a bounce or a complaint for every recipient inside the command's unit of work.\n * The command id is the provider's event id, so a redelivered webhook is `MessageAlreadyProcessedError`.\n */\nexport async function recordEmailEvent(\n command: RecordEmailEventCommand,\n deps: RecordEmailEventDeps,\n): Promise<void> {\n await deps.uow.run(command.id, async ({ emailDeliverability }) => {\n for (const address of command.recipients) {\n if (command.event.type === 'bounced') {\n // oxlint-disable-next-line no-await-in-loop -- Finish each transaction write before starting another; a failure must leave no pending writes.\n await emailDeliverability.recordBounce(address, {\n type: command.event.bounceType,\n subType: command.event.bounceSubType,\n })\n } else {\n // oxlint-disable-next-line no-await-in-loop -- A rejected write must stop the transaction before another write starts.\n await emailDeliverability.recordComplaint(address)\n }\n }\n })\n}\n","import { AppError, DatabaseError, type MessageId } from '@/core'\n\n/** The message's effects already committed. A caller can skip duplicate delivery without repeating those effects. */\nexport class MessageAlreadyProcessedError extends AppError {\n readonly _tag = 'MessageAlreadyProcessedError'\n readonly classification = 'terminal'\n\n constructor(\n readonly messageId: MessageId,\n options?: { readonly cause: unknown },\n ) {\n super(`message ${messageId} already processed`, options)\n }\n\n /** Recognize only the processed-message primary key; preserve other failures unchanged at the call site. */\n static from(cause: unknown, messageId: MessageId): MessageAlreadyProcessedError | undefined {\n if (cause instanceof MessageAlreadyProcessedError) return cause\n if (!(cause instanceof DatabaseError)) return undefined\n const details = cause.details\n const duplicate =\n details.database === 'd1'\n ? details.kind === 'unique' &&\n details.table === 'processed_messages' &&\n details.column === 'message_id'\n : details.code === '23505' &&\n details.table_name === 'processed_messages' &&\n details.constraint_name === 'processed_messages_pkey'\n if (!duplicate) return undefined\n return new MessageAlreadyProcessedError(messageId, { cause })\n }\n}\n","import { panic } from 'better-result'\n\nimport {\n createLogger,\n unreachable,\n type DomainCommand,\n type DomainEvent,\n type DomainMessage,\n type DomainQuery,\n} from '@/core'\n\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { Handlers, MessageResult, RegistryMessage } from './registry.ts'\n\nconst logger = createLogger('message-bus')\n\n/** The port an entrypoint dispatches through. `AppDeps` names this as `IMessageBus<typeof registry>`. */\nexport interface IMessageBus<TRegistry extends Handlers<never>> {\n handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>>\n}\n\n/**\n * Routes one message to its slot. The bus opens no transaction and keeps no outbox:\n * a handler that writes opens the unit of work itself.\n */\nexport class MessageBus<Deps, TRegistry extends Handlers<Deps>> implements IMessageBus<TRegistry> {\n constructor(\n private readonly deps: Deps,\n private readonly registry: TRegistry,\n ) {}\n\n /** Resolves to the handler's own value for a command or query, and to void for an event. */\n async handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>> {\n // SAFETY: the slot for this name is what `MessageResult` names, and dispatch returns its value.\n return (await this.dispatch(message)) as MessageResult<TMessage, TRegistry>\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- one table holds every slot's value; `handle` names it.\n private dispatch(message: DomainMessage): Promise<unknown> {\n if (message.type === 'command') return this.handleCommand(message)\n if (message.type === 'query') return this.handleQuery(message)\n if (message.type === 'event') return this.handleEvent(message)\n // A message parsed at a boundary cannot reach here; one that does must not resolve silently.\n return unreachable(message)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleCommand(command: DomainCommand): Promise<unknown> {\n // `satisfies` proved the registry complete, so a missing slot is a broken registry object.\n const handler = this.registry.commands[command.name]\n if (handler === undefined) return panic(`No handler for command ${command.name}`)\n logger.debug('handling_command', { name: command.name, id: command.id })\n return handler(command, this.deps)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleQuery(query: DomainQuery): Promise<unknown> {\n const handler = this.registry.queries[query.name]\n if (handler === undefined) return panic(`No handler for query ${query.name}`)\n return handler(query, this.deps)\n }\n\n /**\n * Subscribers run one after another, so one unit of work finishes before the next starts.\n * Every subscriber still runs. One failure is rethrown as is. Several are thrown as one `AggregateError`.\n * A `MessageAlreadyProcessedError` means that subscriber already committed on an earlier delivery, so it counts as delivered.\n */\n private async handleEvent(event: DomainEvent): Promise<void> {\n const subscriptions = this.registry.events[event.name] ?? []\n const failures: unknown[] = []\n for (const [subscriber, subscription] of subscriptions.entries()) {\n try {\n await subscription(event, this.deps)\n } catch (reason) {\n if (reason instanceof MessageAlreadyProcessedError) {\n // The bus swallows this error, so this line is the only record that the skip happened.\n logger.info('duplicate_subscriber_ignored', {\n event: event.name,\n id: event.id,\n subscriber,\n })\n continue\n }\n failures.push(reason)\n }\n }\n if (failures.length === 1) throw failures[0]\n if (failures.length > 1) {\n throw new AggregateError(failures, `${event.name}: ${failures.length} subscribers failed`)\n }\n }\n}\n","import { classifyFailure, createLogger, exponentialDelayCapMs, type DomainEvent } from '@/core'\n\nimport type { IOutboxPublisher, RejectedMessage } from './outbox-publisher.ts'\nimport type { IOutboxRepository, OutboxFailureReason, OutboxRow } from './outbox-repository.ts'\n\n/** Optional limits for one relay; durable attempts exclude the publisher's immediate retries. */\nexport type OutboxRelayOptions = {\n readonly batchSize?: number\n readonly maxBatches?: number\n readonly maxAttempts?: number\n /** The wait before the first retry; each later retry doubles it. */\n readonly retryBaseDelayMs?: number\n /** The longest wait before a retry. */\n readonly retryMaxDelayMs?: number\n}\n\nconst logger = createLogger('outbox-relay')\n\n/**\n * Moves committed events out of the outbox: claims due rows, sends their events through the publisher,\n * and records each result on its row. A repository failure propagates to the caller.\n */\nexport class OutboxRelay {\n private readonly options: Required<OutboxRelayOptions>\n\n constructor(\n private readonly publisher: IOutboxPublisher,\n private readonly outboxRepo: IOutboxRepository,\n options: OutboxRelayOptions = {},\n private readonly now: () => Date = () => new Date(),\n ) {\n this.options = {\n batchSize: options.batchSize ?? 50,\n maxBatches: options.maxBatches ?? 10,\n maxAttempts: options.maxAttempts ?? 10,\n retryBaseDelayMs: options.retryBaseDelayMs ?? 1_000,\n retryMaxDelayMs: options.retryMaxDelayMs ?? 60_000,\n }\n }\n\n /**\n * Runs one batch: claims due rows, marks rows with no attempt left failed, and publishes the rest.\n * Called by `drain()`. Returns the claimed count; zero means no row was due.\n */\n async flush(): Promise<number> {\n const batch = await this.outboxRepo.claimDueRows(this.options.batchSize)\n const { exhaustedRows, dueRows } = this.splitByAttemptsLeft(batch.rows)\n await this.markFailed(batch.token, exhaustedRows, 'exhausted', 'Claim attempt limit exceeded')\n if (dueRows.length > 0) await this.publishDueRows(batch.token, dueRows)\n // drain() keeps going while a claim finds rows, even if every row was exhausted.\n return batch.rows.length\n }\n\n /** Sends the rows' events, marks the delivered rows published, and fails or retries the rest by their error. */\n private async publishDueRows(\n claimToken: string,\n dueRows: ReadonlyArray<OutboxRow>,\n ): Promise<void> {\n const rejectedEvents = await this.publishEvents(dueRows)\n const rejectedEventIds = new Set(rejectedEvents.map(({ message: event }) => event.id))\n const deliveredRows = dueRows.filter((row) => !rejectedEventIds.has(row.payload.id))\n if (deliveredRows.length > 0) await this.outboxRepo.markPublished(claimToken, deliveredRows)\n for (const [error, rows] of rowsByError(rejectedEvents, dueRows)) {\n // oxlint-disable-next-line no-await-in-loop -- Each error decides fail or retry for its own rows.\n await this.failOrRetry(claimToken, rows, error)\n }\n }\n\n /** Publishes the rows' events. A thrown publish counts as every event rejected with that error. */\n private async publishEvents(\n rows: ReadonlyArray<OutboxRow>,\n ): Promise<readonly RejectedMessage<DomainEvent>[]> {\n const events = rows.map((row) => row.payload)\n try {\n return await this.publisher.publish(events)\n } catch (error) {\n return events.map((event) => ({ message: event, error }))\n }\n }\n\n /**\n * Runs batches until no row is due: at most `maxBatches` × `batchSize` rows, 500 by default. Called\n * after a commit through `waitUntilWake`, and by the app's cron sweep. Returns the total claimed count.\n */\n async drain(): Promise<number> {\n let total = 0\n for (let batchCount = 0; batchCount < this.options.maxBatches; batchCount += 1) {\n // oxlint-disable-next-line no-await-in-loop -- An empty claim must stop the drain before another claim starts.\n const claimed = await this.flush()\n total += claimed\n if (claimed === 0) break\n }\n return total\n }\n\n /**\n * Decides fail or retry for rows whose events were not delivered: the whole send failed, or one event\n * was rejected. Marks them failed on a terminal error or a last attempt; releases the rest for retry.\n */\n private async failOrRetry(\n claimToken: string,\n rows: ReadonlyArray<OutboxRow>,\n cause: unknown,\n ): Promise<void> {\n const classification = classifyFailure(cause)\n const errorMessage =\n cause instanceof Error ? cause.message : 'Publisher rejected with a non-error value'\n if (classification === 'terminal') {\n await this.markFailed(claimToken, rows, 'terminal', errorMessage, cause)\n return\n }\n const { exhaustedRows, retryRows } = this.splitByLastAttempt(rows)\n await this.markFailed(claimToken, exhaustedRows, 'exhausted', errorMessage, cause)\n await this.releaseForRetry(claimToken, retryRows)\n }\n\n /** Releases rows for another attempt. Each row waits longer the more attempts it has used. */\n private async releaseForRetry(claimToken: string, rows: ReadonlyArray<OutboxRow>): Promise<void> {\n const now = this.now().getTime()\n for (const attempts of new Set(rows.map((row) => row.attempts))) {\n const delayMs = exponentialDelayCapMs(\n this.options.retryBaseDelayMs,\n this.options.retryMaxDelayMs,\n attempts,\n )\n const rowsWithSameDelay = rows.filter((row) => row.attempts === attempts)\n // oxlint-disable-next-line no-await-in-loop -- Stop releasing rows on the first database failure.\n await this.outboxRepo.releaseClaim(claimToken, rowsWithSameDelay, new Date(now + delayMs))\n }\n }\n\n /** Splits claimed rows: rows whose last run crashed with no attempt left, and rows that may run now. */\n private splitByAttemptsLeft(rows: ReadonlyArray<OutboxRow>) {\n return {\n exhaustedRows: rows.filter((row) => this.hasNoAttemptLeft(row)),\n dueRows: rows.filter((row) => !this.hasNoAttemptLeft(row)),\n }\n }\n\n /** Splits failed rows: rows that just used their last attempt, and rows that may retry. */\n private splitByLastAttempt(rows: ReadonlyArray<OutboxRow>) {\n return {\n exhaustedRows: rows.filter((row) => this.isLastAttempt(row)),\n retryRows: rows.filter((row) => !this.isLastAttempt(row)),\n }\n }\n\n /** True when the row used every attempt before this claim: its last run crashed, so it must not run again. */\n private hasNoAttemptLeft(row: OutboxRow): boolean {\n // The claim already counted this run, so a row on its last allowed run equals the limit.\n return row.attempts > this.options.maxAttempts\n }\n\n /** True when the run that just failed was the row's last allowed attempt, so it must not be retried. */\n private isLastAttempt(row: OutboxRow): boolean {\n return row.attempts >= this.options.maxAttempts\n }\n\n /** Calls `outboxRepo.markFailed`, then logs one error. Does nothing for an empty list. */\n private async markFailed(\n claimToken: string,\n rows: ReadonlyArray<OutboxRow>,\n reason: OutboxFailureReason,\n errorMessage: string,\n cause?: unknown,\n ): Promise<void> {\n if (rows.length === 0) return\n await this.outboxRepo.markFailed(claimToken, rows, reason, errorMessage)\n logger.error('outbox_rows_failed', {\n error: cause,\n claimToken,\n count: rows.length,\n reason,\n })\n }\n}\n\n/** Groups the rejected events' rows by error object, so one error decides fail or retry for all its rows at once. */\nfunction rowsByError(\n rejectedEvents: readonly RejectedMessage<DomainEvent>[],\n rows: ReadonlyArray<OutboxRow>,\n): Map<unknown, OutboxRow[]> {\n const rowByEventId = new Map(rows.map((row) => [row.payload.id, row]))\n const groups = new Map<unknown, OutboxRow[]>()\n for (const { message: event, error } of rejectedEvents) {\n const row = rowByEventId.get(event.id)\n if (row === undefined) continue\n const group = groups.get(error) ?? []\n group.push(row)\n groups.set(error, group)\n }\n return groups\n}\n","import type { IOutboxRetentionRepository } from './outbox-repository.ts'\n\n/** Typist's retention defaults; receipt retention must cover the application's supported replay period. */\nexport type OutboxRetentionOptions = {\n readonly publishedRetentionMs?: number\n readonly failedRetentionMs?: number\n readonly receiptRetentionMs?: number\n readonly batchSize?: number\n readonly maxBatches?: number\n}\n\n/** Deleted records per category during one bounded sweep. */\nexport type OutboxRetentionResult = {\n readonly published: number\n readonly failed: number\n readonly receipts: number\n}\n\n/** Bounded cleanup ported from Typist's message retention handler. The application schedules each sweep. */\nexport class OutboxRetention {\n private readonly options: Required<OutboxRetentionOptions>\n\n constructor(\n private readonly repository: IOutboxRetentionRepository,\n options: OutboxRetentionOptions = {},\n ) {\n this.options = {\n publishedRetentionMs: options.publishedRetentionMs ?? 86_400_000,\n failedRetentionMs: options.failedRetentionMs ?? 30 * 86_400_000,\n receiptRetentionMs: options.receiptRetentionMs ?? 7 * 86_400_000,\n batchSize: options.batchSize ?? 1_000,\n maxBatches: options.maxBatches ?? 10,\n }\n }\n\n /** Calculate all cutoffs from one supplied time; propagate repository failures to the calling boundary. */\n async sweep(at: Date): Promise<OutboxRetentionResult> {\n const { publishedRetentionMs, failedRetentionMs, receiptRetentionMs } = this.options\n const published = await this.deleteBatches((size) =>\n this.repository.deletePublishedBefore(new Date(at.getTime() - publishedRetentionMs), size),\n )\n const failed = await this.deleteBatches((size) =>\n this.repository.deleteFailedBefore(new Date(at.getTime() - failedRetentionMs), size),\n )\n const receipts = await this.deleteBatches((size) =>\n this.repository.deleteReceiptsBefore(new Date(at.getTime() - receiptRetentionMs), size),\n )\n return { published, failed, receipts }\n }\n\n private async deleteBatches(deleteBatch: (size: number) => Promise<number>): Promise<number> {\n let total = 0\n for (let batch = 0; batch < this.options.maxBatches; batch += 1) {\n // oxlint-disable-next-line no-await-in-loop -- The delete count decides whether another batch is needed.\n const deleted = await deleteBatch(this.options.batchSize)\n total += deleted\n if (deleted < this.options.batchSize) break\n }\n return total\n }\n}\n","import type { MessageId } from '@/core'\n\nimport type { IEventCollector } from './event-collector.ts'\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { IMessageStore } from './message-store.ts'\nimport type { IOutboxWake } from './outbox-wake.ts'\nimport type { ITransaction } from './transaction.ts'\n\n/**\n * Commits the processed-message record, repository writes, and emitted events together before resolving.\n * An existing record rejects with `MessageAlreadyProcessedError`; external effects must run through the outbox after commit.\n * Nested calls reject with `UnitOfWorkAlreadyActiveError`.\n */\nexport interface IUnitOfWork<Repos> {\n run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T>\n}\n\nexport type UnitOfWorkDeps<Tx, Repos> = {\n readonly transaction: ITransaction<Tx>\n /** The processed-messages and outbox repository for this transaction. */\n readonly messageStore: (tx: Tx) => IMessageStore\n /** Repositories participate in the current transaction. */\n readonly createRepositories: (tx: Tx) => Repos\n readonly eventCollector: IEventCollector\n readonly relay: IOutboxWake\n}\n\n/** The unit of work: the boundary, the repositories, the events. Every database call is a port. */\nexport class UnitOfWork<Tx, Repos> implements IUnitOfWork<Repos> {\n constructor(private readonly deps: UnitOfWorkDeps<Tx, Repos>) {}\n\n async run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T> {\n const { transaction, messageStore, createRepositories, eventCollector, relay } = this.deps\n let written = 0\n\n let value: T\n try {\n value = await transaction.transaction(async (tx) => {\n const store = messageStore(tx)\n await store.claim(messageId)\n const repos = createRepositories(tx)\n const result = await work(repos)\n const pending = eventCollector.collect()\n await store.persistEvents(pending)\n written = pending.length\n return result\n })\n } catch (error) {\n throw MessageAlreadyProcessedError.from(error, messageId) ?? error\n }\n\n if (written > 0) relay.wake()\n return value\n }\n}\n","import { AppError } from '@/core'\n\n/** A boundary was opened inside another. One message, one atomic scope. */\nexport class UnitOfWorkAlreadyActiveError extends AppError {\n readonly _tag = 'UnitOfWorkAlreadyActiveError'\n readonly classification = 'terminal'\n\n constructor() {\n super('a unit of work is already active')\n }\n}\n"],"mappings":";;;;;;;;AAkCA,MAAa,iBAAiB;CAC5B,gBAAgB,CAAC;CACjB,aAAa,CAAC;CACd,QACE,OACA,aACA,YACG,CAAC;CACN,iBACE,OACA,aACA,YACG,CAAC;AACR;;;;;ACxBA,MAAa,uBAAuC;CAClD,aAAa,CAAC;CACd,aAAa,CAAC;CACd,iBAAiB,CAAC;AACpB;;;;;ACwCA,IAAa,wBAAb,MAA4D;;CAE1D,AAAS,OAAwB,CAAC;;CAGlC,MAAM,UAAU,OAA8C;EAC5D,KAAK,KAAK,KAAK,KAAK;EACpB,OAAO,EAAE,YAAY,YAAY,KAAK,KAAK,SAAS;CACtD;AACF;;;;;;;;AC1CA,eAAsB,iBACpB,SACA,MACe;CACf,MAAM,KAAK,IAAI,IAAI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K,WAAW,qBAAqB,IAAI,KAAK,GAAG,QAAQ,IAAI,kBAAkB,GAAG,IAAI,CACxF;EACqC;CACvC;CAEA,MAAc,cAAc,aAAiE;EAC3F,IAAI,QAAQ;EACZ,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,YAAY,SAAS,GAAG;GAE/D,MAAM,UAAU,MAAM,YAAY,KAAK,QAAQ,SAAS;GACxD,SAAS;GACT,IAAI,UAAU,KAAK,QAAQ,WAAW;EACxC;EACA,OAAO;CACT;AACF;;;;;AChCA,IAAa,aAAb,MAAiE;CAClC;CAA7B,YAAY,AAAiB,MAAiC;EAAjC;CAAkC;CAE/D,MAAM,IAAO,WAAsB,MAAgD;EACjF,MAAM,EAAE,aAAa,cAAc,oBAAoB,gBAAgB,UAAU,KAAK;EACtF,IAAI,UAAU;EAEd,IAAI;EACJ,IAAI;GACF,QAAQ,MAAM,YAAY,YAAY,OAAO,OAAO;IAClD,MAAM,QAAQ,aAAa,EAAE;IAC7B,MAAM,MAAM,MAAM,SAAS;IAE3B,MAAM,SAAS,MAAM,KADP,mBAAmB,EACH,CAAC;IAC/B,MAAM,UAAU,eAAe,QAAQ;IACvC,MAAM,MAAM,cAAc,OAAO;IACjC,UAAU,QAAQ;IAClB,OAAO;GACT,CAAC;EACH,SAAS,OAAO;GACd,MAAM,6BAA6B,KAAK,OAAO,SAAS,KAAK;EAC/D;EAEA,IAAI,UAAU,GAAG,MAAM,KAAK;EAC5B,OAAO;CACT;AACF;;;;;ACnDA,IAAa,+BAAb,cAAkD,SAAS;CACzD,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,kCAAkC;CAC1C;AACF"}
@@ -1,3 +1,3 @@
1
1
  import { G as DomainMessage, K as DomainQuery, U as DomainCommand, W as DomainEvent, q as MessageId } from "./index-CtIdbnEZ.js";
2
- import { $ as MetricsService, A as IOutboxRepository, B as OutboundEmail, C as UnitOfWorkDeps, D as OutboxRelay, E as IOutboxRelay, F as IEventCollector, G as applyObservabilityUser, H as ReceivedContent, I as EmailAccepted, J as ObservabilityService, K as setObservabilityUserHook, L as EmailAttachment, M as OutboxClaim, N as OutboxMessage, O as OutboxRelayOptions, P as IMessageStore, Q as MetricOptions, R as IEmailService, S as UnitOfWork, T as IOutboxPublisher, U as ReceivedEmail, V as ReceivedAttachment, W as RecordingEmailService, X as MetricAttributeValue, Y as ObservabilityUser, Z as MetricAttributes, _ as RecordEmailEventCommand, a as OutboxRetentionResult, at as EventHandler, b as recordEmailEvent, c as CommandRegistry, d as MessageRegistry, et as NULL_METRICS_SERVICE, f as MessageResult, g as IEmailDeliverabilityStore, h as EmailBounceRecord, i as OutboxRetentionOptions, it as CommandHandler, j as IOutboxRetentionRepository, k as DeadLetterReason, l as EventRegistry, m as RegistryMessage, n as MessageAlreadyProcessedError, nt as AnalyticsService, o as IMessageBus, ot as QueryHandler, p as QueryRegistry, q as ObservabilityScope, r as OutboxRetention, rt as NULL_ANALYTICS, s as MessageBus, t as UnitOfWorkAlreadyActiveError, tt as AnalyticsPropertiesOf, u as Handlers, v as RecordEmailEventDeps, w as ITransaction, x as IUnitOfWork, y as RecordEmailEventRepos, z as MimeType } from "./index-BMY7ylgk.js";
3
- export { type AnalyticsPropertiesOf, type AnalyticsService, type CommandHandler, type CommandRegistry, type DeadLetterReason, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAccepted, type EmailAttachment, type EmailBounceRecord, type EventHandler, type EventRegistry, type Handlers, type IEmailDeliverabilityStore, type IEmailService, type IEventCollector, type IMessageBus, type IMessageStore, type IOutboxPublisher, type IOutboxRelay, type IOutboxRepository, type IOutboxRetentionRepository, type ITransaction, type IUnitOfWork, MessageAlreadyProcessedError, MessageBus, type MessageId, type MessageRegistry, type MessageResult, type MetricAttributeValue, type MetricAttributes, type MetricOptions, type MetricsService, type MimeType, NULL_ANALYTICS, NULL_METRICS_SERVICE, type ObservabilityScope, type ObservabilityService, type ObservabilityUser, type OutboundEmail, type OutboxClaim, type OutboxMessage, OutboxRelay, type OutboxRelayOptions, OutboxRetention, type OutboxRetentionOptions, type OutboxRetentionResult, type QueryHandler, type QueryRegistry, type ReceivedAttachment, type ReceivedContent, type ReceivedEmail, type RecordEmailEventCommand, type RecordEmailEventDeps, type RecordEmailEventRepos, RecordingEmailService, type RegistryMessage, UnitOfWork, UnitOfWorkAlreadyActiveError, type UnitOfWorkDeps, applyObservabilityUser, recordEmailEvent, setObservabilityUserHook };
2
+ import { $ as MetricOptions, A as IUnitOfWork, B as MimeType, C as RegistryMessage, D as RecordEmailEventDeps, E as RecordEmailEventCommand, F as IMessageStore, G as RecordingEmailService, H as ReceivedAttachment, I as IEventCollector, J as ObservabilityScope, K as applyObservabilityUser, L as EmailAccepted, M as UnitOfWorkDeps, N as ITransaction, O as RecordEmailEventRepos, P as IOutboxWake, Q as MetricAttributes, R as EmailAttachment, S as QueryRegistry, T as IEmailDeliverabilityStore, U as ReceivedContent, V as OutboundEmail, W as ReceivedEmail, X as ObservabilityUser, Y as ObservabilityService, Z as MetricAttributeValue, _ as CommandRegistry, a as OutboxRetentionResult, at as CommandHandler, b as MessageRegistry, c as IOutboxRepository, d as OutboxFailureReason, et as MetricsService, f as OutboxRow, g as MessageBus, h as IMessageBus, i as OutboxRetentionOptions, it as NULL_ANALYTICS, j as UnitOfWork, k as recordEmailEvent, l as IOutboxRetentionRepository, m as RejectedMessage, n as MessageAlreadyProcessedError, nt as AnalyticsPropertiesOf, o as OutboxRelay, ot as EventHandler, p as IOutboxPublisher, q as setObservabilityUserHook, r as OutboxRetention, rt as AnalyticsService, s as OutboxRelayOptions, st as QueryHandler, t as UnitOfWorkAlreadyActiveError, tt as NULL_METRICS_SERVICE, u as OutboxBatch, v as EventRegistry, w as EmailBounceRecord, x as MessageResult, y as Handlers, z as IEmailService } from "./index-Db2GV9ZP.js";
3
+ export { type AnalyticsPropertiesOf, type AnalyticsService, type CommandHandler, type CommandRegistry, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAccepted, type EmailAttachment, type EmailBounceRecord, type EventHandler, type EventRegistry, type Handlers, type IEmailDeliverabilityStore, type IEmailService, type IEventCollector, type IMessageBus, type IMessageStore, type IOutboxPublisher, type IOutboxRepository, type IOutboxRetentionRepository, type IOutboxWake, type ITransaction, type IUnitOfWork, MessageAlreadyProcessedError, MessageBus, type MessageId, type MessageRegistry, type MessageResult, type MetricAttributeValue, type MetricAttributes, type MetricOptions, type MetricsService, type MimeType, NULL_ANALYTICS, NULL_METRICS_SERVICE, type ObservabilityScope, type ObservabilityService, type ObservabilityUser, type OutboundEmail, type OutboxBatch, type OutboxFailureReason, OutboxRelay, type OutboxRelayOptions, OutboxRetention, type OutboxRetentionOptions, type OutboxRetentionResult, type OutboxRow, type QueryHandler, type QueryRegistry, type ReceivedAttachment, type ReceivedContent, type ReceivedEmail, type RecordEmailEventCommand, type RecordEmailEventDeps, type RecordEmailEventRepos, RecordingEmailService, type RegistryMessage, type RejectedMessage, UnitOfWork, UnitOfWorkAlreadyActiveError, type UnitOfWorkDeps, applyObservabilityUser, recordEmailEvent, setObservabilityUserHook };
@@ -1,4 +1,4 @@
1
- import { a as MessageBus, c as RecordingEmailService, i as OutboxRelay, l as NULL_METRICS_SERVICE, n as UnitOfWork, o as MessageAlreadyProcessedError, r as OutboxRetention, s as recordEmailEvent, t as UnitOfWorkAlreadyActiveError, u as NULL_ANALYTICS } from "./application-Dsz-o9Aj.js";
1
+ import { a as MessageBus, c as RecordingEmailService, i as OutboxRelay, l as NULL_METRICS_SERVICE, n as UnitOfWork, o as MessageAlreadyProcessedError, r as OutboxRetention, s as recordEmailEvent, t as UnitOfWorkAlreadyActiveError, u as NULL_ANALYTICS } from "./application-xXTCe8o0.js";
2
2
  import { n as setObservabilityUserHook, t as applyObservabilityUser } from "./request-user-B4rh1c2-.js";
3
3
 
4
4
  export { MessageAlreadyProcessedError, MessageBus, NULL_ANALYTICS, NULL_METRICS_SERVICE, OutboxRelay, OutboxRetention, RecordingEmailService, UnitOfWork, UnitOfWorkAlreadyActiveError, applyObservabilityUser, recordEmailEvent, setObservabilityUserHook };
@@ -1,10 +1,51 @@
1
1
  import { Jt as AppError, U as DomainCommand, W as DomainEvent, Yt as FailureClassification } from "../index-CtIdbnEZ.js";
2
- import { D as OutboxRelay, E as IOutboxRelay } from "../index-BMY7ylgk.js";
2
+ import { P as IOutboxWake, m as RejectedMessage, o as OutboxRelay } from "../index-Db2GV9ZP.js";
3
3
  import { z } from "zod";
4
4
  //#region src/infrastructure/cloudflare/queue/queue-message.d.ts
5
5
  /** A message a queue carries: a command from outside the request, or an event from the outbox. */
6
6
  type QueueMessage = DomainCommand | DomainEvent;
7
7
  //#endregion
8
+ //#region src/infrastructure/cloudflare/queue/queue.errors.d.ts
9
+ /** The Queue binding calls the client makes. Each is safe to repeat. */
10
+ type QueueOperation = 'send' | 'send_batch' | 'send_dlq';
11
+ /** Classify a raw Queue binding failure: the code table first, then Cloudflare's signals, then transport. */
12
+ export declare function classifyQueueError(cause: unknown): FailureClassification;
13
+ /** A send through a Queue binding failed. The classification says whether an immediate retry may help. */
14
+ export declare class QueueSendError extends AppError {
15
+ readonly _tag = "QueueSendError";
16
+ readonly classification: FailureClassification;
17
+ readonly operation: QueueOperation;
18
+ constructor(args: {
19
+ readonly operation: QueueOperation;
20
+ readonly cause: unknown;
21
+ });
22
+ }
23
+ /**
24
+ * A message over the per-message cap can never be sent on any queue; the dead letter has the
25
+ * same cap. The client detects it before the send, so it never comes from a platform error.
26
+ */
27
+ export declare class OversizedMessageError extends AppError {
28
+ readonly _tag = "OversizedMessageError";
29
+ readonly classification = "terminal";
30
+ readonly messageName: string;
31
+ readonly bytes: number;
32
+ readonly limit: number;
33
+ constructor(args: {
34
+ readonly messageName: string;
35
+ readonly bytes: number;
36
+ readonly limit: number;
37
+ });
38
+ }
39
+ /**
40
+ * The dead letter did not accept an unparseable message. Always transient, whatever the send
41
+ * failure was, so the source delivery retries instead of acknowledging and losing the body.
42
+ */
43
+ export declare class DeadLetterUnavailableError extends AppError {
44
+ readonly _tag = "DeadLetterUnavailableError";
45
+ readonly classification = "transient";
46
+ constructor(cause: unknown);
47
+ }
48
+ //#endregion
8
49
  //#region src/infrastructure/cloudflare/queue/queue-client.d.ts
9
50
  /** Cloudflare's delivery delay, in seconds. */
10
51
  type QueueSendOptions = {
@@ -26,8 +67,12 @@ type QueueClientOptions<TMessage extends QueueMessage, Lane extends string> = {
26
67
  interface IQueueClient<TMessage extends QueueMessage> {
27
68
  send(message: TMessage, options?: QueueSendOptions): Promise<void>;
28
69
  sendBatch(messages: ReadonlyArray<TMessage>): Promise<void>;
29
- /** Sends every message within the limits and returns the oversized ones. */
30
- sendBatchPartial<Sent extends TMessage>(messages: ReadonlyArray<Sent>): Promise<ReadonlyArray<Sent>>;
70
+ /**
71
+ * Sends every message it can and resolves with each one it could not send: an oversized message with
72
+ * `OversizedMessageError`, a message of a failed `sendBatch` call with that call's `QueueSendError`.
73
+ * This is how `QueueClient` fits `IOutboxPublisher`.
74
+ */
75
+ publish<Sent extends TMessage>(messages: ReadonlyArray<Sent>): Promise<ReadonlyArray<RejectedMessage<Sent, OversizedMessageError | QueueSendError>>>;
31
76
  /** Parks a delivered message's body as it arrived. */
32
77
  sendToDlq(message: Message): Promise<void>;
33
78
  }
@@ -42,10 +87,13 @@ export declare class QueueClient<TMessage extends QueueMessage, Lane extends str
42
87
  send(message: TMessage, options?: QueueSendOptions): Promise<void>;
43
88
  /** Rejects the whole batch before any send when one message is oversized. */
44
89
  sendBatch(messages: ReadonlyArray<TMessage>): Promise<void>;
45
- sendBatchPartial<Sent extends TMessage>(messages: ReadonlyArray<Sent>): Promise<ReadonlyArray<Sent>>;
90
+ publish<Sent extends TMessage>(messages: ReadonlyArray<Sent>): Promise<ReadonlyArray<RejectedMessage<Sent, OversizedMessageError | QueueSendError>>>;
46
91
  sendToDlq(message: Message): Promise<void>;
47
- /** Each lane's chunks retry on their own, so one failed chunk does not resend the others. */
48
- private sendSizedBatch;
92
+ /**
93
+ * Sends the messages in as few `sendBatch` calls as the lanes and Cloudflare's limits allow. Each call
94
+ * retries on its own; resolves with the messages of every call that still failed, with that call's error.
95
+ */
96
+ private sendInBatches;
49
97
  private queueFor;
50
98
  private callQueue;
51
99
  }
@@ -113,47 +161,6 @@ export declare function isOversized(sized: SizedMessage<QueueMessage>): boolean;
113
161
  /** Split a batch at the message-count and byte limits, keeping the order. */
114
162
  export declare function chunkByLimits<TMessage>(sized: ReadonlyArray<SizedMessage<TMessage>>): TMessage[][];
115
163
  //#endregion
116
- //#region src/infrastructure/cloudflare/queue/queue.errors.d.ts
117
- /** The Queue binding calls the client makes. Each is safe to repeat. */
118
- type QueueOperation = 'send' | 'send_batch' | 'send_dlq';
119
- /** Classify a raw Queue binding failure: the code table first, then Cloudflare's signals, then transport. */
120
- export declare function classifyQueueError(cause: unknown): FailureClassification;
121
- /** A send through a Queue binding failed. The classification says whether an immediate retry may help. */
122
- export declare class QueueSendError extends AppError {
123
- readonly _tag = "QueueSendError";
124
- readonly classification: FailureClassification;
125
- readonly operation: QueueOperation;
126
- constructor(args: {
127
- readonly operation: QueueOperation;
128
- readonly cause: unknown;
129
- });
130
- }
131
- /**
132
- * A message over the per-message cap can never be sent on any queue; the dead letter has the
133
- * same cap. The client detects it before the send, so it never comes from a platform error.
134
- */
135
- export declare class OversizedMessageError extends AppError {
136
- readonly _tag = "OversizedMessageError";
137
- readonly classification = "terminal";
138
- readonly messageName: string;
139
- readonly bytes: number;
140
- readonly limit: number;
141
- constructor(args: {
142
- readonly messageName: string;
143
- readonly bytes: number;
144
- readonly limit: number;
145
- });
146
- }
147
- /**
148
- * The dead letter did not accept an unparseable message. Always transient, whatever the send
149
- * failure was, so the source delivery retries instead of acknowledging and losing the body.
150
- */
151
- export declare class DeadLetterUnavailableError extends AppError {
152
- readonly _tag = "DeadLetterUnavailableError";
153
- readonly classification = "transient";
154
- constructor(cause: unknown);
155
- }
156
- //#endregion
157
164
  //#region src/infrastructure/cloudflare/queue/redelivery-policy.d.ts
158
165
  /** How the consumer settles one failed message: acknowledge it, or have Cloudflare redeliver it after a delay. */
159
166
  type RedeliveryDecision = {
@@ -174,7 +181,7 @@ export declare function decideRedelivery(cause: unknown, attempt: number): Redel
174
181
  //#endregion
175
182
  //#region src/infrastructure/cloudflare/queue/wait-until-wake.d.ts
176
183
  /** Register delivery after commit; log a failed drain once and leave recovery to the scheduled sweep. */
177
- export declare function waitUntilWake(context: Pick<ExecutionContext, 'waitUntil'>, relay: Pick<OutboxRelay, 'drain'>): IOutboxRelay;
184
+ export declare function waitUntilWake(context: Pick<ExecutionContext, 'waitUntil'>, relay: Pick<OutboxRelay, 'drain'>): IOutboxWake;
178
185
  //#endregion
179
186
  export type { DispatchBus, DispatchWrapper, IQueueClient, QueueBinding, QueueClientOptions, QueueMessage, QueueOperation, QueueSendOptions, RedeliveryDecision, SizedMessage };
180
187
  //# sourceMappingURL=queue.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"queue.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/queue/queue-message.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/queue.errors.ts","../../src/infrastructure/cloudflare/queue/redelivery-policy.ts","../../src/infrastructure/cloudflare/queue/wait-until-wake.ts"],"mappings":";;;;;KAGY,eAAe,gBAAgB;;;;KCa/B;WAA8B;;;KAG9B,aAAa,QAAQ,KAAK,MAAM;;;;;KAMhC,mBAAmB,iBAAiB,cAAc;WACnD,QAAQ,SAAS,OAAO,MAAM,aAAa;;WAE3C,YAAY,KAAK;WACjB,SAAS,SAAS,aAAa;;;UAIzB,aAAa,iBAAiB;EAC7C,KAAK,SAAS,UAAU,UAAU,mBAAmB;EACrD,UAAU,UAAU,cAAc,YAAY;;EAE9C,iBAAiB,aAAa,UAC5B,UAAU,cAAc,QACvB,QAAQ,cAA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,KAAK,wBACX"}
1
+ {"version":3,"file":"queue.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/queue/queue-message.ts","../../src/infrastructure/cloudflare/queue/queue.errors.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/redelivery-policy.ts","../../src/infrastructure/cloudflare/queue/wait-until-wake.ts"],"mappings":";;;;;KAGY,eAAe,gBAAgB;;;;KCA/B;;wBA4CI,mBAAmB,iBAAiB;;qBASvC,uBAAuB;WACzB;WACA,gBAAgB;WAChB,WAAW;EAEpB,YAAY;aAAiB,WAAW;aAAyB;;;;;;;qBAWtD,8BAA8B;WAChC;WACA;WACA;WACA;WACA;EAET,YAAY;aACD;aACA;aACA;;;;;;;qBAeA,mCAAmC;WACrC;WACA;EAET,YAAY;;;;;KCpFF;WAA8B;;;KAG9B,aAAa,QAAQ,KAAK,MAAM;;;;;KAMhC,mBAAmB,iBAAiB,cAAc;WACnD,QAAQ,SAAS,OAAO,MAAM,aAAa;;WAE3C,YAAY,KAAK;WACjB,SAAS,SAAS,aAAa;;;UAIzB,aAAa,iBAAiB;EAC7C,KAAK,SAAS,UAAU,UAAU,mBAAmB;EACrD,UAAU,UAAU,cAAc,YAAY;;;;;;EAM9C,QAAQ,aAAa,UACnB,UAAU,cAAc,QACvB,QAAQ,cAAc,gBAAgB,MAAM,wBAAwB;;EAEvE,UAAU,SAAS,UAAU;;;;;;qBA8BlB,YACX,iBAAiB,cACjB,gCACW,aAAa;mBACK;EAA7B,YAA6B,SAAS,mBAAmB,UAAU;;EAG7D,KAAK,SAAS,UAAU,UAAU,mBAAmB;;EA4BrD,UAAU,UAAU,cAAc,YAAY;EAQ9C,QAAQ,aAAa,UACzB,UAAU,cAAc,QACvB,QAAQ,cAAc,gBAAgB,MAAM,wBAAwB;EASjE,UAAU,SAAS,UAAU;;;;;UAWrB;UAkCN;UAIM;;;;;KCtKJ,gBAAgB,iBAAiB,iBAC3C,SAAS,UACT,iBACA,WAAW,kBACR;;KAGO,YAAY,iBAAiB;EAEvC,OAAO,SAAS,WAAW;;;;;;;qBAQhB,cAAc,iBAAiB;mBAQvB;mBACA;mBACA;mBACA;;;;;;;EAJnB,YACmB,KAAK,YAAY,WACjB,aAAa,KAAK,aAAa,yBAC/B,QAAQ,EAAE,QAAQ,WAClB,eAAc,gBAAgB;;EAI3C,aAAa,OAAO,eAAe;UAc3B;;UA+CA;;UAMA;;;;;UAaN;;;;;;;;;qBCtHG;WACX;WACA;WACA;;;wBAIc,kBAAkB,SAAS;;KAK/B,aAAa;WAAuB,SAAS;WAAmB;;;wBAG5D,aAAa,iBAAiB,cAC5C,UAAU,cAAc,YACvB,aAAa;;wBAKA,YAAY,OAAO,aAAa;;wBAKhC,cAAc,UAC5B,OAAO,cAAc,aAAa,aACjC;;;;KCpBS;WACG;WAAwB;;WAExB;WACA,gBAAgB,QAAQ;WACxB;;;;;;;;wBASC,iBAAiB,gBAAgB,kBAAkB;;;;wBCxBnD,cACd,SAAS,KAAK,gCACd,OAAO,KAAK,wBACX"}
@@ -1,5 +1,5 @@
1
1
  import { b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, f as retryAfterSecondsOf, l as spreadJitterMs, r as createLogger, tt as AppError, u as classifyBoundaryError } from "../core-DOBZeYSX.js";
2
- import { o as MessageAlreadyProcessedError } from "../application-Dsz-o9Aj.js";
2
+ import { o as MessageAlreadyProcessedError } from "../application-xXTCe8o0.js";
3
3
  import { Result } from "better-result";
4
4
 
5
5
  //#region src/infrastructure/cloudflare/queue/queue-limits.ts
@@ -194,12 +194,16 @@ var QueueClient = class {
194
194
  const sized = sizeMessages(messages);
195
195
  const oversized = sized.find(isOversized);
196
196
  if (oversized) throw oversizedError(oversized);
197
- await this.sendSizedBatch(sized);
197
+ const [failed] = await this.sendInBatches(sized);
198
+ if (failed) throw failed.error;
198
199
  }
199
- async sendBatchPartial(messages) {
200
+ async publish(messages) {
200
201
  const sized = sizeMessages(messages);
201
- await this.sendSizedBatch(sized.filter((item) => !isOversized(item)));
202
- return sized.flatMap((item) => isOversized(item) ? [item.message] : []);
202
+ const unsent = await this.sendInBatches(sized.filter((item) => !isOversized(item)));
203
+ return [...sized.filter((item) => isOversized(item)).map((item) => ({
204
+ message: item.message,
205
+ error: oversizedError(item)
206
+ })), ...unsent];
203
207
  }
204
208
  async sendToDlq(message) {
205
209
  logger$2.debug("sending_to_dlq", { queueMessageId: message.id });
@@ -207,8 +211,11 @@ var QueueClient = class {
207
211
  await this.options.deadLetter.send(message.body);
208
212
  });
209
213
  }
210
- /** Each lane's chunks retry on their own, so one failed chunk does not resend the others. */
211
- async sendSizedBatch(sized) {
214
+ /**
215
+ * Sends the messages in as few `sendBatch` calls as the lanes and Cloudflare's limits allow. Each call
216
+ * retries on its own; resolves with the messages of every call that still failed, with that call's error.
217
+ */
218
+ async sendInBatches(sized) {
212
219
  const byLane = /* @__PURE__ */ new Map();
213
220
  for (const item of sized) {
214
221
  const lane = this.options.laneOf(item.message);
@@ -223,14 +230,20 @@ var QueueClient = class {
223
230
  count: items.length
224
231
  }))
225
232
  });
226
- const sends = [];
227
- for (const [lane, items] of byLane) {
228
- const queue = this.options.queues[lane];
229
- for (const group of chunkByLimits(items)) sends.push(this.callQueue("send_batch", async () => {
230
- await queue.sendBatch(group.map((body) => ({ body })));
233
+ const calls = [...byLane].flatMap(([lane, items]) => chunkByLimits(items).map((messages) => ({
234
+ queue: this.options.queues[lane],
235
+ messages
236
+ })));
237
+ return (await Promise.allSettled(calls.map(({ queue, messages }) => this.callQueue("send_batch", async () => {
238
+ await queue.sendBatch(messages.map((body) => ({ body })));
239
+ })))).flatMap((result, index) => {
240
+ if (result.status === "fulfilled") return [];
241
+ const error = result.reason;
242
+ return (calls[index]?.messages ?? []).map((message) => ({
243
+ message,
244
+ error
231
245
  }));
232
- }
233
- await Promise.all(sends);
246
+ });
234
247
  }
235
248
  queueFor(message) {
236
249
  return this.options.queues[this.options.laneOf(message)];