| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { |
| 3 | Inject, |
| 4 | Injectable, |
| 5 | Logger, |
| 6 | type OnApplicationBootstrap, |
| 7 | type OnApplicationShutdown, |
| 8 | } from '@nestjs/common'; |
| 9 | import { asc, eq |
| 10 | |
| 11 | import { DATABASE } |
| 12 | import type { StoredEvent |
| 13 | import { NotifierService } |
| 14 | import { WebhookFanoutService } |
| 15 | |
| 16 | const BATCH_SIZE = 20 |
| 17 | const POLL_INTERVAL_MS = 2000 |
| 18 | // After this many failures an event is set aside with its last error rather than retried forever. |
| 19 | const MAX_ATTEMPTS = 5 |
| 20 | |
| 21 | /** Hands each committed event to every consumer, at least once and oldest first. A consumer added later, such as webhook delivery, is one more call in `dispatch`. */ |
| 22 | @Injectable() |
| 23 | export class OutboxService |
| 24 | implements OnApplicationBootstrap |
| 25 | { |
| 26 | private readonly logger |
| 27 | private timer?: |
| 28 | private draining?: |
| 29 | |
| 30 | constructor( |
| 31 | @Inject(DATABASE) |
| 32 | private readonly notifier |
| 33 | private readonly webhooks |
| 34 | ) {} |
| 35 | |
| 36 | onApplicationBootstrap() { |
| 37 | this.timer = |
| 38 | this.draining ??= |
| 39 | .catch((error: |
| 40 | this.logger.error |
| 41 | `Draining the outbox failed: ${error instanceof |
| 42 | ), |
| 43 | ) |
| 44 | .finally(() => |
| 45 | this.draining = |
| 46 | }); |
| 47 | }, POLL_INTERVAL_MS); |
| 48 | } |
| 49 | |
| 50 | async onApplicationShutdown() { |
| 51 | clearInterval(this.timer |
| 52 | await this.draining |
| 53 | } |
| 54 | |
| 55 | /** Works through pending events until a batch comes up short. A failed event waits for the next poll. */ |
| 56 | async drain() { |
| 57 | while ((await this |
| 58 | } |
| 59 | |
| 60 | // ponytail: rows stay locked while consumers run, emails included; a lease column would let a slow batch release them sooner. |
| 61 | private processBatch() { |
| 62 | return this.db |
| 63 | const events = |
| 64 | .select() |
| 65 | .from(schema.outboxEvent |
| 66 | .where(isNull(schema |
| 67 | .orderBy(asc(schema |
| 68 | .limit(BATCH_SIZE) |
| 69 | // several API instances share the outbox: each claims rows the others have not |
| 70 | .for('update', |
| 71 | |
| 72 | let handled = |
| 73 | for (const event |
| 74 | const attempts = |
| 75 | try { |
| 76 | // written by `publishEvent`, which checked the payload against its type |
| 77 | await this.dispatch |
| 78 | await tx |
| 79 | .update(schema.outboxEvent |
| 80 | .set({ attempts |
| 81 | .where(eq(schema |
| 82 | handled++; |
| 83 | } catch (error) |
| 84 | const message = |
| 85 | error instanceof Error |
| 86 | this.logger.warn |
| 87 | `Event ${event.id |
| 88 | ); |
| 89 | await tx |
| 90 | .update(schema.outboxEvent |
| 91 | .set({ |
| 92 | attempts, |
| 93 | lastError: message, |
| 94 | processedAt: attempts >= |
| 95 | }) |
| 96 | .where(eq(schema |
| 97 | } |
| 98 | } |
| 99 | return handled; |
| 100 | }); |
| 101 | } |
| 102 | |
| 103 | private async dispatch |
| 104 | // A retry runs both again; webhook jobs are keyed by event and endpoint, so none is queued twice. |
| 105 | await this.notifier |
| 106 | await this.webhooks |
| 107 | } |
| 108 | } |