-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathqueue.ts
More file actions
655 lines (572 loc) · 16.5 KB
/
queue.ts
File metadata and controls
655 lines (572 loc) · 16.5 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import {
createRedisClient,
type Redis,
type Callback,
type RedisOptions,
type Result,
} from "@internal/redis";
import { Logger } from "@trigger.dev/core/logger";
import { nanoid } from "nanoid";
import { z } from "zod";
export interface MessageCatalogSchema {
[key: string]: z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>;
}
export type MessageCatalogKey<TMessageCatalog extends MessageCatalogSchema> = keyof TMessageCatalog;
export type MessageCatalogValue<
TMessageCatalog extends MessageCatalogSchema,
TKey extends MessageCatalogKey<TMessageCatalog>,
> = z.infer<TMessageCatalog[TKey]>;
export type AnyMessageCatalog = MessageCatalogSchema;
export type QueueItem<TMessageCatalog extends MessageCatalogSchema> = {
id: string;
job: MessageCatalogKey<TMessageCatalog>;
item: MessageCatalogValue<TMessageCatalog, MessageCatalogKey<TMessageCatalog>>;
visibilityTimeoutMs: number;
attempt: number;
timestamp: Date;
deduplicationKey?: string;
};
export type AnyQueueItem = {
id: string;
job: string;
item: any;
visibilityTimeoutMs: number;
attempt: number;
timestamp: Date;
deduplicationKey?: string;
};
export class SimpleQueue<TMessageCatalog extends MessageCatalogSchema> {
name: string;
private redis: Redis;
private schema: TMessageCatalog;
private logger: Logger;
constructor({
name,
schema,
redisOptions,
logger,
}: {
name: string;
schema: TMessageCatalog;
redisOptions: RedisOptions;
logger?: Logger;
}) {
this.name = name;
this.logger = logger ?? new Logger("SimpleQueue", "debug");
this.redis = createRedisClient(
{
...redisOptions,
keyPrefix: `${redisOptions.keyPrefix ?? ""}{queue:${name}:}`,
retryStrategy(times) {
const delay = Math.min(times * 50, 1000);
return delay;
},
maxRetriesPerRequest: 20,
},
{
onError: (error) => {
this.logger.error(`RedisWorker queue redis client error:`, {
error,
keyPrefix: redisOptions.keyPrefix,
});
},
}
);
this.#registerCommands();
this.schema = schema;
}
async enqueue({
id,
job,
item,
attempt,
availableAt,
visibilityTimeoutMs,
}: {
id?: string;
job: MessageCatalogKey<TMessageCatalog>;
item: MessageCatalogValue<TMessageCatalog, MessageCatalogKey<TMessageCatalog>>;
attempt?: number;
availableAt?: Date;
visibilityTimeoutMs: number;
}): Promise<void> {
try {
const score = availableAt ? availableAt.getTime() : Date.now();
const deduplicationKey = nanoid();
const serializedItem = JSON.stringify({
job,
item,
visibilityTimeoutMs,
attempt,
deduplicationKey,
});
const result = await this.redis.enqueueItem(
`queue`,
`items`,
id ?? nanoid(),
score,
serializedItem
);
if (result !== 1) {
throw new Error("Enqueue operation failed");
}
} catch (e) {
this.logger.error(`SimpleQueue ${this.name}.enqueue(): error enqueuing`, {
queue: this.name,
error: e,
id,
item,
});
throw e;
}
}
async enqueueOnce({
id,
job,
item,
attempt,
availableAt,
visibilityTimeoutMs,
}: {
id: string;
job: MessageCatalogKey<TMessageCatalog>;
item: MessageCatalogValue<TMessageCatalog, MessageCatalogKey<TMessageCatalog>>;
attempt?: number;
availableAt?: Date;
visibilityTimeoutMs: number;
}): Promise<boolean> {
if (!id) {
throw new Error("enqueueOnce requires an id");
}
try {
const score = availableAt ? availableAt.getTime() : Date.now();
const deduplicationKey = nanoid();
const serializedItem = JSON.stringify({
job,
item,
visibilityTimeoutMs,
attempt,
deduplicationKey,
});
const result = await this.redis.enqueueItemOnce(`queue`, `items`, id, score, serializedItem);
// 1 if inserted, 0 if already exists
return result === 1;
} catch (e) {
this.logger.error(`SimpleQueue ${this.name}.enqueueOnce(): error enqueuing`, {
queue: this.name,
error: e,
id,
item,
});
throw e;
}
}
async dequeue(count: number = 1): Promise<Array<QueueItem<TMessageCatalog>>> {
const now = Date.now();
try {
const results = await this.redis.dequeueItems(`queue`, `items`, now, count);
if (!results || results.length === 0) {
return [];
}
const dequeuedItems: Array<QueueItem<TMessageCatalog>> = [];
for (const [id, serializedItem, score] of results) {
const parsedItem = JSON.parse(serializedItem) as any;
if (typeof parsedItem.job !== "string") {
this.logger.error(`Invalid item in queue`, { queue: this.name, id, item: parsedItem });
continue;
}
const timestamp = new Date(Number(score));
const schema = this.schema[parsedItem.job];
if (!schema) {
this.logger.error(`Invalid item in queue, schema not found`, {
queue: this.name,
id,
item: parsedItem,
job: parsedItem.job,
timestamp,
availableJobs: Object.keys(this.schema),
});
continue;
}
const validatedItem = schema.safeParse(parsedItem.item);
if (!validatedItem.success) {
this.logger.error("Invalid item in queue", {
queue: this.name,
id,
item: parsedItem,
errors: validatedItem.error,
attempt: parsedItem.attempt,
timestamp,
});
continue;
}
const visibilityTimeoutMs = parsedItem.visibilityTimeoutMs as number;
dequeuedItems.push({
id,
job: parsedItem.job,
item: validatedItem.data,
visibilityTimeoutMs,
attempt: parsedItem.attempt ?? 0,
timestamp,
deduplicationKey: parsedItem.deduplicationKey,
});
}
return dequeuedItems;
} catch (e) {
this.logger.error(`SimpleQueue ${this.name}.dequeue(): error dequeuing`, {
queue: this.name,
error: e,
count,
});
throw e;
}
}
async ack(id: string, deduplicationKey?: string): Promise<void> {
try {
const result = await this.redis.ackItem(`queue`, `items`, id, deduplicationKey ?? "");
if (result !== 1) {
this.logger.debug(
`SimpleQueue ${this.name}.ack(): ack operation returned ${result}. This means it was not removed from the queue.`,
{
queue: this.name,
id,
deduplicationKey,
result,
}
);
}
} catch (e) {
this.logger.error(`SimpleQueue ${this.name}.ack(): error acknowledging item`, {
queue: this.name,
error: e,
id,
deduplicationKey,
});
throw e;
}
}
async reschedule(id: string, availableAt: Date): Promise<void> {
await this.redis.zadd(`queue`, "XX", availableAt.getTime(), id);
}
async size({ includeFuture = false }: { includeFuture?: boolean } = {}): Promise<number> {
try {
if (includeFuture) {
// If includeFuture is true, return the total count of all items
return await this.redis.zcard(`queue`);
} else {
// If includeFuture is false, return the count of items available now
const now = Date.now();
return await this.redis.zcount(`queue`, "-inf", now);
}
} catch (e) {
this.logger.error(`SimpleQueue ${this.name}.size(): error getting queue size`, {
queue: this.name,
error: e,
includeFuture,
});
throw e;
}
}
async getJob(id: string): Promise<QueueItem<TMessageCatalog> | null> {
const result = await this.redis.getJob(`queue`, `items`, id);
if (!result) {
return null;
}
const [_, score, serializedItem] = result;
const item = JSON.parse(serializedItem) as QueueItem<TMessageCatalog>;
return {
id,
job: item.job,
item: item.item,
visibilityTimeoutMs: item.visibilityTimeoutMs,
attempt: item.attempt ?? 0,
timestamp: new Date(Number(score)),
deduplicationKey: item.deduplicationKey ?? undefined,
};
}
async moveToDeadLetterQueue(id: string, errorMessage: string): Promise<void> {
try {
this.logger.debug(`SimpleQueue ${this.name}.moveToDeadLetterQueue(): moving item to DLQ`, {
queue: this.name,
id,
errorMessage,
});
const result = await this.redis.moveToDeadLetterQueue(
`queue`,
`items`,
`dlq`,
`dlq:items`,
id,
errorMessage
);
if (result !== 1) {
throw new Error("Move to Dead Letter Queue operation failed");
}
} catch (e) {
this.logger.error(
`SimpleQueue ${this.name}.moveToDeadLetterQueue(): error moving item to DLQ`,
{
queue: this.name,
error: e,
id,
errorMessage,
}
);
throw e;
}
}
async sizeOfDeadLetterQueue(): Promise<number> {
try {
return await this.redis.zcard(`dlq`);
} catch (e) {
this.logger.error(`SimpleQueue ${this.name}.dlqSize(): error getting DLQ size`, {
queue: this.name,
error: e,
});
throw e;
}
}
async redriveFromDeadLetterQueue(id: string): Promise<void> {
try {
const result = await this.redis.redriveFromDeadLetterQueue(
`queue`,
`items`,
`dlq`,
`dlq:items`,
id
);
if (result !== 1) {
throw new Error("Redrive from Dead Letter Queue operation failed");
}
} catch (e) {
this.logger.error(
`SimpleQueue ${this.name}.redriveFromDeadLetterQueue(): error redriving item from DLQ`,
{
queue: this.name,
error: e,
id,
}
);
throw e;
}
}
async close(): Promise<void> {
await this.redis.quit();
}
#registerCommands() {
this.redis.defineCommand("enqueueItem", {
numberOfKeys: 2,
lua: `
local queue = KEYS[1]
local items = KEYS[2]
local id = ARGV[1]
local score = ARGV[2]
local serializedItem = ARGV[3]
redis.call('ZADD', queue, score, id)
redis.call('HSET', items, id, serializedItem)
return 1
`,
});
this.redis.defineCommand("dequeueItems", {
numberOfKeys: 2,
lua: `
local queue = KEYS[1]
local items = KEYS[2]
local now = tonumber(ARGV[1])
local count = tonumber(ARGV[2])
local result = redis.call('ZRANGEBYSCORE', queue, '-inf', now, 'WITHSCORES', 'LIMIT', 0, count)
if #result == 0 then
return {}
end
local dequeued = {}
for i = 1, #result, 2 do
local id = result[i]
local score = tonumber(result[i + 1])
if score > now then
break
end
local serializedItem = redis.call('HGET', items, id)
if serializedItem then
local item = cjson.decode(serializedItem)
local visibilityTimeoutMs = tonumber(item.visibilityTimeoutMs)
local invisibleUntil = now + visibilityTimeoutMs
redis.call('ZADD', queue, invisibleUntil, id)
table.insert(dequeued, {id, serializedItem, score})
else
-- Remove the orphaned queue entry if no corresponding item exists
redis.call('ZREM', queue, id)
end
end
return dequeued
`,
});
this.redis.defineCommand("getJob", {
numberOfKeys: 2,
lua: `
local queue = KEYS[1]
local items = KEYS[2]
local jobId = ARGV[1]
local serializedItem = redis.call('HGET', items, jobId)
if serializedItem == false then
return nil
end
-- get the score from the queue sorted set
local score = redis.call('ZSCORE', queue, jobId)
return { jobId, score, serializedItem }
`,
});
this.redis.defineCommand("ackItem", {
numberOfKeys: 2,
lua: `
local queueKey = KEYS[1]
local itemsKey = KEYS[2]
local id = ARGV[1]
local deduplicationKey = ARGV[2]
-- Get the item from the hash
local item = redis.call('HGET', itemsKey, id)
if not item then
return -1
end
-- Only check deduplicationKey if a non-empty one was passed in
if deduplicationKey and deduplicationKey ~= "" then
local success, parsed = pcall(cjson.decode, item)
if success then
if parsed.deduplicationKey and parsed.deduplicationKey ~= deduplicationKey then
return 0
end
end
end
-- Remove from sorted set and hash
redis.call('ZREM', queueKey, id)
redis.call('HDEL', itemsKey, id)
return 1
`,
});
this.redis.defineCommand("moveToDeadLetterQueue", {
numberOfKeys: 4,
lua: `
local queue = KEYS[1]
local items = KEYS[2]
local dlq = KEYS[3]
local dlqItems = KEYS[4]
local id = ARGV[1]
local errorMessage = ARGV[2]
local item = redis.call('HGET', items, id)
if not item then
return 0
end
local parsedItem = cjson.decode(item)
parsedItem.errorMessage = errorMessage
local time = redis.call('TIME')
local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
redis.call('ZREM', queue, id)
redis.call('HDEL', items, id)
redis.call('ZADD', dlq, now, id)
redis.call('HSET', dlqItems, id, cjson.encode(parsedItem))
return 1
`,
});
this.redis.defineCommand("redriveFromDeadLetterQueue", {
numberOfKeys: 4,
lua: `
local queue = KEYS[1]
local items = KEYS[2]
local dlq = KEYS[3]
local dlqItems = KEYS[4]
local id = ARGV[1]
local item = redis.call('HGET', dlqItems, id)
if not item then
return 0
end
local parsedItem = cjson.decode(item)
parsedItem.errorMessage = nil
local time = redis.call('TIME')
local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
redis.call('ZREM', dlq, id)
redis.call('HDEL', dlqItems, id)
redis.call('ZADD', queue, now, id)
redis.call('HSET', items, id, cjson.encode(parsedItem))
return 1
`,
});
this.redis.defineCommand("enqueueItemOnce", {
numberOfKeys: 2,
lua: `
local queue = KEYS[1]
local items = KEYS[2]
local id = ARGV[1]
local score = ARGV[2]
local serializedItem = ARGV[3]
-- Only add if not exists
local added = redis.call('HSETNX', items, id, serializedItem)
if added == 1 then
redis.call('ZADD', queue, 'NX', score, id)
return 1
else
return 0
end
`,
});
}
}
declare module "@internal/redis" {
interface RedisCommander<Context> {
enqueueItem(
//keys
queue: string,
items: string,
//args
id: string,
score: number,
serializedItem: string,
callback?: Callback<number>
): Result<number, Context>;
dequeueItems(
//keys
queue: string,
items: string,
//args
now: number,
count: number,
callback?: Callback<Array<[string, string, string]>>
): Result<Array<[string, string, string]>, Context>;
ackItem(
queue: string,
items: string,
id: string,
deduplicationKey: string,
callback?: Callback<number>
): Result<number, Context>;
redriveFromDeadLetterQueue(
queue: string,
items: string,
dlq: string,
dlqItems: string,
id: string,
callback?: Callback<number>
): Result<number, Context>;
moveToDeadLetterQueue(
queue: string,
items: string,
dlq: string,
dlqItems: string,
id: string,
errorMessage: string,
callback?: Callback<number>
): Result<number, Context>;
enqueueItemOnce(
queue: string,
items: string,
id: string,
score: number,
serializedItem: string,
callback?: Callback<number>
): Result<number, Context>;
getJob(
queue: string,
items: string,
id: string,
callback?: Callback<[string, string, string] | null>
): Result<[string, string, string] | null, Context>;
}
}