forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook-dlq.ts
More file actions
356 lines (303 loc) · 10.2 KB
/
Copy pathwebhook-dlq.ts
File metadata and controls
356 lines (303 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/**
* Webhook DLQ (Dead Letter Queue) Storage
*
* Persists failed webhook deliveries to durable SQLite storage for later inspection and replay.
* Implements deduplication to prevent duplicate reprocessing on replay.
*
* Capacity Management:
* - Default max capacity: 10000 entries
* - Overflow policy: oldest-evict (removes oldest entry when at capacity)
*
* Poison Message Handling:
* - Max replay attempts: 5 (configurable)
* - Messages exceeding max attempts are permanently dropped
*
* @module queue/webhook-dlq
*/
import DatabaseConstructor from '../db/betterSqlite3';
import type BetterSqlite3 from 'better-sqlite3';
import path from 'path';
import * as crypto from 'crypto';
import { Counter, Registry } from 'prom-client';
import { DLQOperation } from '../webhookMetrics';
export interface WebhookDLQEntry {
id: string;
webhookId: string;
url: string;
body: Record<string, unknown>;
retryCount: number;
webhookSecret?: string;
failedAt: string;
lastError: string;
dedupeKey: string;
replayedAt?: string;
replayAttempts: number;
createdAt: string;
updatedAt: string;
}
export interface WebhookDLQQuery {
limit?: number;
offset?: number;
since?: string;
until?: string;
}
export interface ReplayResult {
success: boolean;
entryId: string;
deduplicated: boolean;
message?: string;
}
export interface DLQConfig {
maxCapacity: number;
maxReplayAttempts: number;
}
const DEFAULT_DLQ_CONFIG: DLQConfig = {
maxCapacity: 10000,
maxReplayAttempts: 5,
};
let dlqMetricsCounter: Counter<string> | null = null;
export function initializeDLQMetrics(registry: Registry): void {
if (dlqMetricsCounter) return;
dlqMetricsCounter = new Counter({
name: 'webhook_dlq_operations_total',
help: 'Total number of DLQ operations',
labelNames: ['operation'] as const,
registers: [registry],
});
}
export function resetDLQMetrics(): void {
dlqMetricsCounter = null;
}
function incrementDLQMetric(operation: DLQOperation): void {
if (dlqMetricsCounter) {
dlqMetricsCounter.inc({ operation });
}
}
class WebhookDLQStorage {
private db: ReturnType<typeof DatabaseConstructor>;
private config: DLQConfig;
constructor(dbPath?: string, config: Partial<DLQConfig> = {}) {
const resolvedPath = dbPath || process.env.WEBHOOK_DLQ_PATH || path.join(process.cwd(), 'data', 'webhook-dlq.db');
this.db = new DatabaseConstructor(resolvedPath);
this.config = { ...DEFAULT_DLQ_CONFIG, ...config };
this.initialize();
}
private initialize(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS webhook_dlq (
id TEXT PRIMARY KEY,
webhook_id TEXT NOT NULL,
url TEXT NOT NULL,
body TEXT NOT NULL,
retry_count INTEGER NOT NULL DEFAULT 0,
webhook_secret TEXT,
failed_at TEXT NOT NULL,
last_error TEXT NOT NULL,
dedupe_key TEXT NOT NULL,
replayed_at TEXT,
replay_attempts INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(dedupe_key)
)
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_webhook_dlq_failed_at ON webhook_dlq(failed_at)
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_webhook_dlq_dedupe_key ON webhook_dlq(dedupe_key)
`);
// Migration: Add replay_attempts column if it doesn't exist
try {
this.db.exec(`ALTER TABLE webhook_dlq ADD COLUMN replay_attempts INTEGER NOT NULL DEFAULT 0`);
} catch {
// Column already exists, ignore
}
}
private generateDedupeKey(webhookId: string, payload: Record<string, unknown>): string {
const content = `${webhookId}:${JSON.stringify(payload)}`;
return crypto.createHash('sha256').update(content).digest('hex');
}
async addEntry(
webhookId: string,
url: string,
body: Record<string, unknown>,
retryCount: number,
lastError: string,
webhookSecret?: string
): Promise<string> {
const id = crypto.randomUUID();
const now = new Date().toISOString();
const dedupeKey = this.generateDedupeKey(webhookId, body);
// Check capacity and evict oldest if necessary
const currentCount = await this.getPendingCount();
if (currentCount >= this.config.maxCapacity) {
await this.evictOldest();
incrementDLQMetric('drop_overflow');
}
const stmt = this.db.prepare(`
INSERT INTO webhook_dlq (
id, webhook_id, url, body, retry_count, webhook_secret,
failed_at, last_error, dedupe_key, replay_attempts, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
try {
stmt.run(
id,
webhookId,
url,
JSON.stringify(body),
retryCount,
webhookSecret || null,
now,
lastError,
dedupeKey,
0,
now,
now
);
incrementDLQMetric('enqueue');
} catch (err: unknown) {
const sqliteErr = err as { code?: string };
if (sqliteErr.code === 'SQLITE_CONSTRAINT_UNIQUE') {
throw new Error('DUPLICATE_ENTRY');
}
throw err;
}
return id;
}
private async getPendingCount(): Promise<number> {
const stmt = this.db.prepare('SELECT COUNT(*) as count FROM webhook_dlq WHERE replayed_at IS NULL');
const result = stmt.get() as { count: number };
return result.count;
}
private async evictOldest(): Promise<void> {
const stmt = this.db.prepare(`
DELETE FROM webhook_dlq
WHERE id = (
SELECT id FROM webhook_dlq
WHERE replayed_at IS NULL
ORDER BY failed_at ASC
LIMIT 1
)
`);
stmt.run();
}
getEntry(id: string): WebhookDLQEntry | null {
const stmt = this.db.prepare('SELECT * FROM webhook_dlq WHERE id = ?');
const row = stmt.get(id) as Record<string, unknown> | undefined;
if (!row) return null;
return this.mapRowToEntry(row);
}
listEntries(query: WebhookDLQQuery = {}): WebhookDLQEntry[] {
const { limit = 50, offset = 0, since, until } = query;
let sql = 'SELECT * FROM webhook_dlq WHERE 1=1';
const params: unknown[] = [];
if (since) {
sql += ' AND failed_at >= ?';
params.push(since);
}
if (until) {
sql += ' AND failed_at <= ?';
params.push(until);
}
sql += ' ORDER BY failed_at DESC LIMIT ? OFFSET ?';
params.push(limit, offset);
const stmt = this.db.prepare(sql);
const rows = stmt.all(...params) as Record<string, unknown>[];
return rows.map(row => this.mapRowToEntry(row));
}
markReplayed(id: string): boolean {
const now = new Date().toISOString();
const stmt = this.db.prepare(`
UPDATE webhook_dlq SET replayed_at = ?, updated_at = ? WHERE id = ?
`);
const result = stmt.run(now, now, id);
return result.changes > 0;
}
incrementReplayAttempts(id: string): { success: boolean; attempts: number; maxExceeded: boolean } {
const entry = this.getEntry(id);
if (!entry) {
return { success: false, attempts: 0, maxExceeded: false };
}
const newAttempts = entry.replayAttempts + 1;
const maxExceeded = newAttempts >= this.config.maxReplayAttempts;
if (maxExceeded) {
// Drop the poison message permanently
this.deleteEntry(id);
incrementDLQMetric('drop_poison');
return { success: true, attempts: newAttempts, maxExceeded: true };
}
const now = new Date().toISOString();
const stmt = this.db.prepare(`
UPDATE webhook_dlq SET replay_attempts = ?, updated_at = ? WHERE id = ?
`);
stmt.run(newAttempts, now, id);
return { success: true, attempts: newAttempts, maxExceeded: false };
}
getMaxReplayAttempts(): number {
return this.config.maxReplayAttempts;
}
deleteEntry(id: string): boolean {
const stmt = this.db.prepare('DELETE FROM webhook_dlq WHERE id = ?');
const result = stmt.run(id);
return result.changes > 0;
}
checkDedupe(webhookId: string, body: Record<string, unknown>): { exists: boolean; entryId?: string } {
const dedupeKey = this.generateDedupeKey(webhookId, body);
const stmt = this.db.prepare('SELECT id FROM webhook_dlq WHERE dedupe_key = ? AND replayed_at IS NULL');
const row = stmt.get(dedupeKey) as { id: string } | undefined;
return {
exists: !!row,
entryId: row?.id
};
}
async getStats(): Promise<{ total: number; pending: number; replayed: number }> {
const totalStmt = this.db.prepare('SELECT COUNT(*) as count FROM webhook_dlq');
const pendingStmt = this.db.prepare('SELECT COUNT(*) as count FROM webhook_dlq WHERE replayed_at IS NULL');
const replayedStmt = this.db.prepare('SELECT COUNT(*) as count FROM webhook_dlq WHERE replayed_at IS NOT NULL');
const total = (totalStmt.get() as { count: number }).count;
const pending = (pendingStmt.get() as { count: number }).count;
const replayed = (replayedStmt.get() as { count: number }).count;
return { total, pending, replayed };
}
close(): void {
this.db.close();
}
private mapRowToEntry(row: Record<string, unknown>): WebhookDLQEntry {
return {
id: row.id as string,
webhookId: row.webhook_id as string,
url: row.url as string,
body: JSON.parse(row.body as string),
retryCount: row.retry_count as number,
webhookSecret: row.webhook_secret as string | undefined,
failedAt: row.failed_at as string,
lastError: row.last_error as string,
dedupeKey: row.dedupe_key as string,
replayedAt: row.replayed_at as string | undefined,
replayAttempts: (row.replay_attempts as number) ?? 0,
createdAt: row.created_at as string,
updatedAt: row.updated_at as string,
};
}
}
let instance: WebhookDLQStorage | null = null;
export { WebhookDLQStorage };
export function getWebhookDLQStorage(dbPath?: string): WebhookDLQStorage {
// Under test, hand out an ephemeral in-memory store per call so unit tests
// are isolated from one another and never read/write the on-disk DLQ file.
if (process.env.NODE_ENV === 'test') {
return new WebhookDLQStorage(dbPath ?? ':memory:');
}
if (!instance) {
instance = new WebhookDLQStorage(dbPath);
}
return instance;
}
export function clearWebhookDLQInstance(): void {
if (instance) {
instance.close();
instance = null;
}
}