| 1 | import { type Database, type Pool, schema } from '@ghost/db'; |
| 2 | import { |
| 3 | Inject, |
| 4 | Injectable, |
| 5 | Logger, |
| 6 | type OnApplicationBootstrap, |
| 7 | type OnApplicationShutdown, |
| 8 | } from '@nestjs/common'; |
| 9 | import { and, asc |
| 10 | |
| 11 | import { |
| 12 | DATABASE, |
| 13 | DATABASE_CONNECTION, |
| 14 | } from '../../database/database.module.js'; |
| 15 | import { OUTBOX_CHANNEL, type |
| 16 | import { NotifierService } |
| 17 | import { WebhookFanoutService } |
| 18 | |
| 19 | const BATCH_SIZE = 20 |
| 20 | // Only retries failed events: new ones arrive by NOTIFY. Longer than Railway's 10 idle minutes, so the API can sleep. |
| 21 | const RETRY_INTERVAL_MS = 15 |
| 22 | const RECONNECT_DELAY_MS = 5000 |
| 23 | // After this many failures an event is set aside with its last error rather than retried forever. |
| 24 | const MAX_ATTEMPTS = 5 |
| 25 | |
| 26 | type Listener |
| 27 | release(destroy: |
| 28 | removeAllListeners(event: |
| 29 | }; |
| 30 | |
| 31 | /** 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`. */ |
| 32 | @Injectable() |
| 33 | export class OutboxService |
| 34 | implements OnApplicationBootstrap |
| 35 | { |
| 36 | private readonly logger |
| 37 | private timer?: |
| 38 | private draining?: |
| 39 | private listener?: |
| 40 | private reconnect?: |
| 41 | private rerun = |
| 42 | private stopped = |
| 43 | |
| 44 | constructor( |
| 45 | @Inject(DATABASE) |
| 46 | private readonly notifier |
| 47 | private readonly webhooks |
| 48 | @Inject(DATABASE_CONNECTION) |
| 49 | private readonly connection |
| 50 | ) {} |
| 51 | |
| 52 | async onApplicationBootstrap() { |
| 53 | this.timer = |
| 54 | await this.listen |
| 55 | } |
| 56 | |
| 57 | async onApplicationShutdown() { |
| 58 | this.stopped = |
| 59 | clearInterval(this.timer |
| 60 | clearTimeout(this.reconnect |
| 61 | this.dropListener(); |
| 62 | await this.draining |
| 63 | } |
| 64 | |
| 65 | /** An idle LISTEN connection sends nothing, unlike polling, so it does not keep the container awake. */ |
| 66 | private async listen |
| 67 | this.reconnect = |
| 68 | if (this.stopped |
| 69 | try { |
| 70 | const client = |
| 71 | if (this.stopped |
| 72 | client.release(); |
| 73 | return; |
| 74 | } |
| 75 | this.listener = |
| 76 | client.on('notification |
| 77 | client.on('error |
| 78 | // stays attached after a drop, so a late error on a destroyed client cannot crash the process |
| 79 | if (this.listener |
| 80 | this.logger.warn |
| 81 | this.dropListener(); |
| 82 | this.retryListen(); |
| 83 | }); |
| 84 | await client.query |
| 85 | // Events committed while nobody listened got no NOTIFY. |
| 86 | this.wake(); |
| 87 | } catch (error) |
| 88 | this.logger.warn |
| 89 | `Outbox listener failed: ${error instanceof |
| 90 | ); |
| 91 | this.dropListener(); |
| 92 | this.retryListen(); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /** Destroys the connection rather than pooling it: a pooled client would keep the LISTEN and wake the outbox for whoever borrows it next. */ |
| 97 | private dropListener() { |
| 98 | const client = |
| 99 | if (!client) |
| 100 | this.listener = |
| 101 | client.removeAllListeners('notification |
| 102 | client.release(true) |
| 103 | } |
| 104 | |
| 105 | private retryListen() { |
| 106 | if (this.stopped |
| 107 | this.reconnect = |
| 108 | } |
| 109 | |
| 110 | private wake() { |
| 111 | if (this.stopped |
| 112 | // A NOTIFY mid-drain may name a row the drain already looked past. |
| 113 | if (this.draining |
| 114 | this.rerun = |
| 115 | return; |
| 116 | } |
| 117 | this.draining = |
| 118 | .catch((error: |
| 119 | this.logger.error |
| 120 | `Draining the outbox failed: ${error instanceof |
| 121 | ), |
| 122 | ) |
| 123 | .finally(() => |
| 124 | this.draining = |
| 125 | if (this.rerun |
| 126 | this.rerun = |
| 127 | this.wake(); |
| 128 | } |
| 129 | }); |
| 130 | } |
| 131 | |
| 132 | /** Works through pending events until a batch comes up short. A failed event waits for the next drain, and does not stop this one reaching the rows behind it. */ |
| 133 | async drain() { |
| 134 | const failed = |
| 135 | while ((await this |
| 136 | } |
| 137 | |
| 138 | // ponytail: rows stay locked while consumers run, emails included; a lease column would let a slow batch release them sooner. |
| 139 | private processBatch(failed |
| 140 | return this.db |
| 141 | const events = |
| 142 | .select() |
| 143 | .from(schema.outboxEvent |
| 144 | .where( |
| 145 | and( |
| 146 | isNull(schema.outboxEvent |
| 147 | // one array parameter, not one per id, so a long run of failures stays under Postgres's parameter limit |
| 148 | failed.size |
| 149 | ? sql`${schema |
| 150 | : undefined, |
| 151 | ), |
| 152 | ) |
| 153 | .orderBy(asc(schema |
| 154 | .limit(BATCH_SIZE) |
| 155 | // several API instances share the outbox: each claims rows the others have not |
| 156 | .for('update', |
| 157 | |
| 158 | for (const event |
| 159 | const attempts = |
| 160 | try { |
| 161 | // written by `publishEvent`, which checked the payload against its type |
| 162 | await this.dispatch |
| 163 | await tx |
| 164 | .update(schema.outboxEvent |
| 165 | .set({ attempts |
| 166 | .where(eq(schema |
| 167 | } catch (error) |
| 168 | const message = |
| 169 | error instanceof Error |
| 170 | this.logger.warn |
| 171 | `Event ${event.id |
| 172 | ); |
| 173 | await tx |
| 174 | .update(schema.outboxEvent |
| 175 | .set({ |
| 176 | attempts, |
| 177 | lastError: message, |
| 178 | processedAt: attempts >= |
| 179 | }) |
| 180 | .where(eq(schema |
| 181 | if (attempts < |
| 182 | } |
| 183 | } |
| 184 | return events.length; |
| 185 | }); |
| 186 | } |
| 187 | |
| 188 | private async dispatch |
| 189 | // A retry runs both again; webhook jobs are keyed by event and endpoint, so none is queued twice. |
| 190 | await this.notifier |
| 191 | await this.webhooks |
| 192 | } |
| 193 | } |