pg-boss 12.4.0 → 12.5.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.
package/dist/plans.js ADDED
@@ -0,0 +1,885 @@
1
+ const DEFAULT_SCHEMA = 'pgboss';
2
+ const MIGRATE_RACE_MESSAGE = 'division by zero';
3
+ const CREATE_RACE_MESSAGE = 'already exists';
4
+ const FIFTEEN_MINUTES = 60 * 15;
5
+ const FORTEEN_DAYS = 60 * 60 * 24 * 14;
6
+ const SEVEN_DAYS = 60 * 60 * 24 * 7;
7
+ const JOB_STATES = Object.freeze({
8
+ created: 'created',
9
+ retry: 'retry',
10
+ active: 'active',
11
+ completed: 'completed',
12
+ cancelled: 'cancelled',
13
+ failed: 'failed'
14
+ });
15
+ const QUEUE_POLICIES = Object.freeze({
16
+ standard: 'standard',
17
+ short: 'short',
18
+ singleton: 'singleton',
19
+ stately: 'stately',
20
+ exclusive: 'exclusive'
21
+ });
22
+ const QUEUE_DEFAULTS = {
23
+ expire_seconds: FIFTEEN_MINUTES,
24
+ retention_seconds: FORTEEN_DAYS,
25
+ deletion_seconds: SEVEN_DAYS,
26
+ retry_limit: 2,
27
+ retry_delay: 0,
28
+ warning_queued: 0,
29
+ retry_backoff: false,
30
+ partition: false
31
+ };
32
+ const COMMON_JOB_TABLE = 'job_common';
33
+ function create(schema, version, options) {
34
+ const commands = [
35
+ options?.createSchema ? createSchema(schema) : '',
36
+ createEnumJobState(schema),
37
+ createTableVersion(schema),
38
+ createTableQueue(schema),
39
+ createTableSchedule(schema),
40
+ createTableSubscription(schema),
41
+ createTableJob(schema),
42
+ createPrimaryKeyJob(schema),
43
+ createTableJobCommon(schema, COMMON_JOB_TABLE),
44
+ createQueueFunction(schema),
45
+ deleteQueueFunction(schema),
46
+ insertVersion(schema, version)
47
+ ];
48
+ return locked(schema, commands);
49
+ }
50
+ function createSchema(schema) {
51
+ return `CREATE SCHEMA IF NOT EXISTS ${schema}`;
52
+ }
53
+ function createEnumJobState(schema) {
54
+ // ENUM definition order is important
55
+ // base type is numeric and first values are less than last values
56
+ return `
57
+ CREATE TYPE ${schema}.job_state AS ENUM (
58
+ '${JOB_STATES.created}',
59
+ '${JOB_STATES.retry}',
60
+ '${JOB_STATES.active}',
61
+ '${JOB_STATES.completed}',
62
+ '${JOB_STATES.cancelled}',
63
+ '${JOB_STATES.failed}'
64
+ )
65
+ `;
66
+ }
67
+ function createTableVersion(schema) {
68
+ return `
69
+ CREATE TABLE ${schema}.version (
70
+ version int primary key,
71
+ cron_on timestamp with time zone
72
+ )
73
+ `;
74
+ }
75
+ function createTableQueue(schema) {
76
+ return `
77
+ CREATE TABLE ${schema}.queue (
78
+ name text NOT NULL,
79
+ policy text NOT NULL,
80
+ retry_limit int NOT NULL,
81
+ retry_delay int NOT NULL,
82
+ retry_backoff bool NOT NULL,
83
+ retry_delay_max int,
84
+ expire_seconds int NOT NULL,
85
+ retention_seconds int NOT NULL,
86
+ deletion_seconds int NOT NULL,
87
+ dead_letter text REFERENCES ${schema}.queue (name) CHECK (dead_letter IS DISTINCT FROM name),
88
+ partition bool NOT NULL,
89
+ table_name text NOT NULL,
90
+ deferred_count int NOT NULL default 0,
91
+ queued_count int NOT NULL default 0,
92
+ warning_queued int NOT NULL default 0,
93
+ active_count int NOT NULL default 0,
94
+ total_count int NOT NULL default 0,
95
+ singletons_active text[],
96
+ monitor_on timestamp with time zone,
97
+ maintain_on timestamp with time zone,
98
+ created_on timestamp with time zone not null default now(),
99
+ updated_on timestamp with time zone not null default now(),
100
+ PRIMARY KEY (name)
101
+ )
102
+ `;
103
+ }
104
+ function createTableSchedule(schema) {
105
+ return `
106
+ CREATE TABLE ${schema}.schedule (
107
+ name text REFERENCES ${schema}.queue ON DELETE CASCADE,
108
+ key text not null DEFAULT '',
109
+ cron text not null,
110
+ timezone text,
111
+ data jsonb,
112
+ options jsonb,
113
+ created_on timestamp with time zone not null default now(),
114
+ updated_on timestamp with time zone not null default now(),
115
+ PRIMARY KEY (name, key)
116
+ )
117
+ `;
118
+ }
119
+ function createTableSubscription(schema) {
120
+ return `
121
+ CREATE TABLE ${schema}.subscription (
122
+ event text not null,
123
+ name text not null REFERENCES ${schema}.queue ON DELETE CASCADE,
124
+ created_on timestamp with time zone not null default now(),
125
+ updated_on timestamp with time zone not null default now(),
126
+ PRIMARY KEY(event, name)
127
+ )
128
+ `;
129
+ }
130
+ function createTableJob(schema) {
131
+ return `
132
+ CREATE TABLE ${schema}.job (
133
+ id uuid not null default gen_random_uuid(),
134
+ name text not null,
135
+ priority integer not null default(0),
136
+ data jsonb,
137
+ state ${schema}.job_state not null default '${JOB_STATES.created}',
138
+ retry_limit integer not null default ${QUEUE_DEFAULTS.retry_limit},
139
+ retry_count integer not null default 0,
140
+ retry_delay integer not null default ${QUEUE_DEFAULTS.retry_delay},
141
+ retry_backoff boolean not null default ${QUEUE_DEFAULTS.retry_backoff},
142
+ retry_delay_max integer,
143
+ expire_seconds int not null default ${QUEUE_DEFAULTS.expire_seconds},
144
+ deletion_seconds int not null default ${QUEUE_DEFAULTS.deletion_seconds},
145
+ singleton_key text,
146
+ singleton_on timestamp without time zone,
147
+ start_after timestamp with time zone not null default now(),
148
+ created_on timestamp with time zone not null default now(),
149
+ started_on timestamp with time zone,
150
+ completed_on timestamp with time zone,
151
+ keep_until timestamp with time zone NOT NULL default now() + interval '${QUEUE_DEFAULTS.retention_seconds}',
152
+ output jsonb,
153
+ dead_letter text,
154
+ policy text
155
+ ) PARTITION BY LIST (name)
156
+ `;
157
+ }
158
+ const JOB_COLUMNS_MIN = 'id, name, data, expire_seconds as "expireInSeconds"';
159
+ const JOB_COLUMNS_ALL = `${JOB_COLUMNS_MIN},
160
+ policy,
161
+ state,
162
+ priority,
163
+ retry_limit as "retryLimit",
164
+ retry_count as "retryCount",
165
+ retry_delay as "retryDelay",
166
+ retry_backoff as "retryBackoff",
167
+ retry_delay_max as "retryDelayMax",
168
+ start_after as "startAfter",
169
+ started_on as "startedOn",
170
+ singleton_key as "singletonKey",
171
+ singleton_on as "singletonOn",
172
+ deletion_seconds as "deleteAfterSeconds",
173
+ created_on as "createdOn",
174
+ completed_on as "completedOn",
175
+ keep_until as "keepUntil",
176
+ dead_letter as "deadLetter",
177
+ output
178
+ `;
179
+ function createTableJobCommon(schema, table) {
180
+ const format = (command) => command.replaceAll('.job', `.${table}`) + ';';
181
+ return `
182
+ CREATE TABLE ${schema}.${table} (LIKE ${schema}.job INCLUDING GENERATED INCLUDING DEFAULTS);
183
+ ${format(createPrimaryKeyJob(schema))}
184
+ ${format(createQueueForeignKeyJob(schema))}
185
+ ${format(createQueueForeignKeyJobDeadLetter(schema))}
186
+ ${format(createIndexJobPolicyShort(schema))}
187
+ ${format(createIndexJobPolicySingleton(schema))}
188
+ ${format(createIndexJobPolicyStately(schema))}
189
+ ${format(createIndexJobPolicyExclusive(schema))}
190
+ ${format(createIndexJobThrottle(schema))}
191
+ ${format(createIndexJobFetch(schema))}
192
+
193
+ ALTER TABLE ${schema}.job ATTACH PARTITION ${schema}.${table} DEFAULT;
194
+ `;
195
+ }
196
+ function createQueueFunction(schema) {
197
+ return `
198
+ CREATE FUNCTION ${schema}.create_queue(queue_name text, options jsonb)
199
+ RETURNS VOID AS
200
+ $$
201
+ DECLARE
202
+ tablename varchar := CASE WHEN options->>'partition' = 'true'
203
+ THEN 'j' || encode(sha224(queue_name::bytea), 'hex')
204
+ ELSE '${COMMON_JOB_TABLE}'
205
+ END;
206
+ queue_created_on timestamptz;
207
+ BEGIN
208
+
209
+ WITH q as (
210
+ INSERT INTO ${schema}.queue (
211
+ name,
212
+ policy,
213
+ retry_limit,
214
+ retry_delay,
215
+ retry_backoff,
216
+ retry_delay_max,
217
+ expire_seconds,
218
+ retention_seconds,
219
+ deletion_seconds,
220
+ warning_queued,
221
+ dead_letter,
222
+ partition,
223
+ table_name
224
+ )
225
+ VALUES (
226
+ queue_name,
227
+ options->>'policy',
228
+ COALESCE((options->>'retryLimit')::int, ${QUEUE_DEFAULTS.retry_limit}),
229
+ COALESCE((options->>'retryDelay')::int, ${QUEUE_DEFAULTS.retry_delay}),
230
+ COALESCE((options->>'retryBackoff')::bool, ${QUEUE_DEFAULTS.retry_backoff}),
231
+ (options->>'retryDelayMax')::int,
232
+ COALESCE((options->>'expireInSeconds')::int, ${QUEUE_DEFAULTS.expire_seconds}),
233
+ COALESCE((options->>'retentionSeconds')::int, ${QUEUE_DEFAULTS.retention_seconds}),
234
+ COALESCE((options->>'deleteAfterSeconds')::int, ${QUEUE_DEFAULTS.deletion_seconds}),
235
+ COALESCE((options->>'warningQueueSize')::int, ${QUEUE_DEFAULTS.warning_queued}),
236
+ options->>'deadLetter',
237
+ COALESCE((options->>'partition')::bool, ${QUEUE_DEFAULTS.partition}),
238
+ tablename
239
+ )
240
+ ON CONFLICT DO NOTHING
241
+ RETURNING created_on
242
+ )
243
+ SELECT created_on into queue_created_on from q;
244
+
245
+ IF queue_created_on IS NULL OR options->>'partition' IS DISTINCT FROM 'true' THEN
246
+ RETURN;
247
+ END IF;
248
+
249
+ EXECUTE format('CREATE TABLE ${schema}.%I (LIKE ${schema}.job INCLUDING DEFAULTS)', tablename);
250
+
251
+ EXECUTE format('${formatPartitionCommand(createPrimaryKeyJob(schema))}', tablename);
252
+ EXECUTE format('${formatPartitionCommand(createQueueForeignKeyJob(schema))}', tablename);
253
+ EXECUTE format('${formatPartitionCommand(createQueueForeignKeyJobDeadLetter(schema))}', tablename);
254
+
255
+ EXECUTE format('${formatPartitionCommand(createIndexJobFetch(schema))}', tablename);
256
+ EXECUTE format('${formatPartitionCommand(createIndexJobThrottle(schema))}', tablename);
257
+
258
+ IF options->>'policy' = 'short' THEN
259
+ EXECUTE format('${formatPartitionCommand(createIndexJobPolicyShort(schema))}', tablename);
260
+ ELSIF options->>'policy' = 'singleton' THEN
261
+ EXECUTE format('${formatPartitionCommand(createIndexJobPolicySingleton(schema))}', tablename);
262
+ ELSIF options->>'policy' = 'stately' THEN
263
+ EXECUTE format('${formatPartitionCommand(createIndexJobPolicyStately(schema))}', tablename);
264
+ ELSIF options->>'policy' = 'exclusive' THEN
265
+ EXECUTE format('${formatPartitionCommand(createIndexJobPolicyExclusive(schema))}', tablename);
266
+ END IF;
267
+
268
+ EXECUTE format('ALTER TABLE ${schema}.%I ADD CONSTRAINT cjc CHECK (name=%L)', tablename, queue_name);
269
+ EXECUTE format('ALTER TABLE ${schema}.job ATTACH PARTITION ${schema}.%I FOR VALUES IN (%L)', tablename, queue_name);
270
+ END;
271
+ $$
272
+ LANGUAGE plpgsql;
273
+ `;
274
+ }
275
+ function formatPartitionCommand(command) {
276
+ return command
277
+ .replace('.job', '.%1$I')
278
+ .replace('job_i', '%1$s_i')
279
+ .replaceAll("'", "''");
280
+ }
281
+ function deleteQueueFunction(schema) {
282
+ return `
283
+ CREATE FUNCTION ${schema}.delete_queue(queue_name text)
284
+ RETURNS VOID AS
285
+ $$
286
+ DECLARE
287
+ v_table varchar;
288
+ v_partition bool;
289
+ BEGIN
290
+ SELECT table_name, partition
291
+ FROM ${schema}.queue
292
+ WHERE name = queue_name
293
+ INTO v_table, v_partition;
294
+
295
+ IF v_partition THEN
296
+ EXECUTE format('DROP TABLE IF EXISTS ${schema}.%I', v_table);
297
+ ELSE
298
+ EXECUTE format('DELETE FROM ${schema}.%I WHERE name = %L', v_table, queue_name);
299
+ END IF;
300
+
301
+ DELETE FROM ${schema}.queue WHERE name = queue_name;
302
+ END;
303
+ $$
304
+ LANGUAGE plpgsql;
305
+ `;
306
+ }
307
+ function createQueue(schema, name, options) {
308
+ const sql = `SELECT ${schema}.create_queue('${name}', '${JSON.stringify(options)}'::jsonb)`;
309
+ return locked(schema, sql, 'create-queue');
310
+ }
311
+ function deleteQueue(schema, name) {
312
+ const sql = `SELECT ${schema}.delete_queue('${name}')`;
313
+ return locked(schema, sql, 'delete-queue');
314
+ }
315
+ function createPrimaryKeyJob(schema) {
316
+ return `ALTER TABLE ${schema}.job ADD PRIMARY KEY (name, id)`;
317
+ }
318
+ function createQueueForeignKeyJob(schema) {
319
+ return `ALTER TABLE ${schema}.job ADD CONSTRAINT q_fkey FOREIGN KEY (name) REFERENCES ${schema}.queue (name) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED`;
320
+ }
321
+ function createQueueForeignKeyJobDeadLetter(schema) {
322
+ return `ALTER TABLE ${schema}.job ADD CONSTRAINT dlq_fkey FOREIGN KEY (dead_letter) REFERENCES ${schema}.queue (name) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED`;
323
+ }
324
+ function createIndexJobPolicyShort(schema) {
325
+ return `CREATE UNIQUE INDEX job_i1 ON ${schema}.job (name, COALESCE(singleton_key, '')) WHERE state = '${JOB_STATES.created}' AND policy = '${QUEUE_POLICIES.short}'`;
326
+ }
327
+ function createIndexJobPolicySingleton(schema) {
328
+ return `CREATE UNIQUE INDEX job_i2 ON ${schema}.job (name, COALESCE(singleton_key, '')) WHERE state = '${JOB_STATES.active}' AND policy = '${QUEUE_POLICIES.singleton}'`;
329
+ }
330
+ function createIndexJobPolicyStately(schema) {
331
+ return `CREATE UNIQUE INDEX job_i3 ON ${schema}.job (name, state, COALESCE(singleton_key, '')) WHERE state <= '${JOB_STATES.active}' AND policy = '${QUEUE_POLICIES.stately}'`;
332
+ }
333
+ function createIndexJobThrottle(schema) {
334
+ return `CREATE UNIQUE INDEX job_i4 ON ${schema}.job (name, singleton_on, COALESCE(singleton_key, '')) WHERE state <> '${JOB_STATES.cancelled}' AND singleton_on IS NOT NULL`;
335
+ }
336
+ function createIndexJobFetch(schema) {
337
+ return `CREATE INDEX job_i5 ON ${schema}.job (name, start_after) INCLUDE (priority, created_on, id) WHERE state < '${JOB_STATES.active}'`;
338
+ }
339
+ function createIndexJobPolicyExclusive(schema) {
340
+ return `CREATE UNIQUE INDEX job_i6 ON ${schema}.job (name, COALESCE(singleton_key, '')) WHERE state <= '${JOB_STATES.active}' AND policy = '${QUEUE_POLICIES.exclusive}'`;
341
+ }
342
+ function trySetQueueMonitorTime(schema, queues, seconds) {
343
+ return trySetQueueTimestamp(schema, queues, 'monitor_on', seconds);
344
+ }
345
+ function trySetQueueDeletionTime(schema, queues, seconds) {
346
+ return trySetQueueTimestamp(schema, queues, 'maintain_on', seconds);
347
+ }
348
+ function trySetCronTime(schema, seconds) {
349
+ return trySetTimestamp(schema, 'cron_on', seconds);
350
+ }
351
+ function trySetTimestamp(schema, column, seconds) {
352
+ return `
353
+ UPDATE ${schema}.version
354
+ SET ${column} = now()
355
+ WHERE EXTRACT( EPOCH FROM (now() - COALESCE(${column}, now() - interval '1 week') ) ) > ${seconds}
356
+ RETURNING true
357
+ `;
358
+ }
359
+ function trySetQueueTimestamp(schema, queues, column, seconds) {
360
+ return `
361
+ UPDATE ${schema}.queue
362
+ SET ${column} = now()
363
+ WHERE name IN(${getQueueInClause(queues)})
364
+ AND EXTRACT( EPOCH FROM (now() - COALESCE(${column}, now() - interval '1 week') ) ) > ${seconds}
365
+ RETURNING name
366
+ `;
367
+ }
368
+ function updateQueue(schema, { deadLetter } = {}) {
369
+ return `
370
+ WITH options as (SELECT $2::jsonb as data)
371
+ UPDATE ${schema}.queue SET
372
+ retry_limit = COALESCE((o.data->>'retryLimit')::int, retry_limit),
373
+ retry_delay = COALESCE((o.data->>'retryDelay')::int, retry_delay),
374
+ retry_backoff = COALESCE((o.data->>'retryBackoff')::bool, retry_backoff),
375
+ retry_delay_max = CASE WHEN o.data ? 'retryDelayMax'
376
+ THEN (o.data->>'retryDelayMax')::int
377
+ ELSE retry_delay_max END,
378
+ expire_seconds = COALESCE((o.data->>'expireInSeconds')::int, expire_seconds),
379
+ retention_seconds = COALESCE((o.data->>'retentionSeconds')::int, retention_seconds),
380
+ deletion_seconds = COALESCE((o.data->>'deleteAfterSeconds')::int, deletion_seconds),
381
+ warning_queued = COALESCE((o.data->>'warningQueueSize')::int, warning_queued),
382
+ ${deadLetter === undefined
383
+ ? ''
384
+ : `dead_letter = CASE WHEN '${deadLetter}' IS DISTINCT FROM dead_letter THEN '${deadLetter}' ELSE dead_letter END,`}
385
+ updated_on = now()
386
+ FROM options o
387
+ WHERE name = $1
388
+ `;
389
+ }
390
+ function getQueues(schema, names) {
391
+ return `
392
+ SELECT
393
+ q.name,
394
+ q.policy,
395
+ q.retry_limit as "retryLimit",
396
+ q.retry_delay as "retryDelay",
397
+ q.retry_backoff as "retryBackoff",
398
+ q.retry_delay_max as "retryDelayMax",
399
+ q.expire_seconds as "expireInSeconds",
400
+ q.retention_seconds as "retentionSeconds",
401
+ q.deletion_seconds as "deleteAfterSeconds",
402
+ q.partition,
403
+ q.dead_letter as "deadLetter",
404
+ q.deferred_count as "deferredCount",
405
+ q.warning_queued as "warningQueueSize",
406
+ q.queued_count as "queuedCount",
407
+ q.active_count as "activeCount",
408
+ q.total_count as "totalCount",
409
+ q.singletons_active as "singletonsActive",
410
+ q.table_name as "table",
411
+ q.created_on as "createdOn",
412
+ q.updated_on as "updatedOn"
413
+ FROM ${schema}.queue q
414
+ ${names ? `WHERE q.name IN (${names.map(i => `'${i}'`)})` : ''}
415
+ `;
416
+ }
417
+ function deleteJobsById(schema, table) {
418
+ return `
419
+ WITH results as (
420
+ DELETE FROM ${schema}.${table}
421
+ WHERE name = $1
422
+ AND id IN (SELECT UNNEST($2::uuid[]))
423
+ RETURNING 1
424
+ )
425
+ SELECT COUNT(*) from results
426
+ `;
427
+ }
428
+ function deleteQueuedJobs(schema, table) {
429
+ return `DELETE from ${schema}.${table} WHERE name = $1 and state < '${JOB_STATES.active}'`;
430
+ }
431
+ function deleteStoredJobs(schema, table) {
432
+ return `DELETE from ${schema}.${table} WHERE name = $1 and state > '${JOB_STATES.active}'`;
433
+ }
434
+ function truncateTable(schema, table) {
435
+ return `TRUNCATE ${schema}.${table}`;
436
+ }
437
+ function deleteAllJobs(schema, table) {
438
+ return `DELETE from ${schema}.${table} WHERE name = $1`;
439
+ }
440
+ function getSchedules(schema) {
441
+ return `SELECT * FROM ${schema}.schedule`;
442
+ }
443
+ function getSchedulesByQueue(schema) {
444
+ return `SELECT * FROM ${schema}.schedule WHERE name = $1 AND COALESCE(key, '') = $2`;
445
+ }
446
+ function schedule(schema) {
447
+ return `
448
+ INSERT INTO ${schema}.schedule (name, key, cron, timezone, data, options)
449
+ VALUES ($1, $2, $3, $4, $5, $6)
450
+ ON CONFLICT (name, key) DO UPDATE SET
451
+ cron = EXCLUDED.cron,
452
+ timezone = EXCLUDED.timezone,
453
+ data = EXCLUDED.data,
454
+ options = EXCLUDED.options,
455
+ updated_on = now()
456
+ `;
457
+ }
458
+ function unschedule(schema) {
459
+ return `
460
+ DELETE FROM ${schema}.schedule
461
+ WHERE name = $1
462
+ AND COALESCE(key, '') = $2
463
+ `;
464
+ }
465
+ function subscribe(schema) {
466
+ return `
467
+ INSERT INTO ${schema}.subscription (event, name)
468
+ VALUES ($1, $2)
469
+ ON CONFLICT (event, name) DO UPDATE SET
470
+ event = EXCLUDED.event,
471
+ name = EXCLUDED.name,
472
+ updated_on = now()
473
+ `;
474
+ }
475
+ function unsubscribe(schema) {
476
+ return `
477
+ DELETE FROM ${schema}.subscription
478
+ WHERE event = $1 and name = $2
479
+ `;
480
+ }
481
+ function getQueuesForEvent(schema) {
482
+ return `
483
+ SELECT name FROM ${schema}.subscription
484
+ WHERE event = $1
485
+ `;
486
+ }
487
+ function getTime() {
488
+ return "SELECT round(date_part('epoch', now()) * 1000) as time";
489
+ }
490
+ function getVersion(schema) {
491
+ return `SELECT version from ${schema}.version`;
492
+ }
493
+ function setVersion(schema, version) {
494
+ return `UPDATE ${schema}.version SET version = '${version}'`;
495
+ }
496
+ function versionTableExists(schema) {
497
+ return `SELECT to_regclass('${schema}.version') as name`;
498
+ }
499
+ function insertVersion(schema, version) {
500
+ return `INSERT INTO ${schema}.version(version) VALUES ('${version}')`;
501
+ }
502
+ function fetchNextJob({ schema, table, name, policy, limit, includeMetadata, priority = true, ignoreStartAfter = false, ignoreSingletons = null }) {
503
+ const singletonFetch = limit > 1 && (policy === QUEUE_POLICIES.singleton || policy === QUEUE_POLICIES.stately);
504
+ const cte = singletonFetch ? 'grouped' : 'next';
505
+ return `
506
+ WITH next as (
507
+ SELECT id ${singletonFetch ? ', singleton_key' : ''}
508
+ FROM ${schema}.${table}
509
+ WHERE name = '${name}'
510
+ AND state < '${JOB_STATES.active}'
511
+ ${ignoreStartAfter ? '' : 'AND start_after < now()'}
512
+ ${ignoreSingletons != null && ignoreSingletons?.length > 0 ? `AND singleton_key NOT IN (${ignoreSingletons.map(i => `'${i}'`).join()})` : ''}
513
+ ORDER BY ${priority ? 'priority desc, ' : ''}created_on, id
514
+ LIMIT ${limit}
515
+ FOR UPDATE SKIP LOCKED
516
+ )
517
+ ${singletonFetch ? ', grouped as ( SELECT id, row_number() OVER (PARTITION BY singleton_key) FROM next)' : ''}
518
+ UPDATE ${schema}.${table} j SET
519
+ state = '${JOB_STATES.active}',
520
+ started_on = now(),
521
+ retry_count = CASE WHEN started_on IS NOT NULL THEN retry_count + 1 ELSE retry_count END
522
+ FROM ${cte}
523
+ WHERE name = '${name}' AND j.id = ${cte}.id
524
+ ${singletonFetch ? ` AND ${cte}.row_number = 1` : ''}
525
+ RETURNING j.${includeMetadata ? JOB_COLUMNS_ALL : JOB_COLUMNS_MIN}
526
+ `;
527
+ }
528
+ function completeJobs(schema, table) {
529
+ return `
530
+ WITH results AS (
531
+ UPDATE ${schema}.${table}
532
+ SET completed_on = now(),
533
+ state = '${JOB_STATES.completed}',
534
+ output = $3::jsonb
535
+ WHERE name = $1
536
+ AND id IN (SELECT UNNEST($2::uuid[]))
537
+ AND state = '${JOB_STATES.active}'
538
+ RETURNING *
539
+ )
540
+ SELECT COUNT(*) FROM results
541
+ `;
542
+ }
543
+ function cancelJobs(schema, table) {
544
+ return `
545
+ WITH results as (
546
+ UPDATE ${schema}.${table}
547
+ SET completed_on = now(),
548
+ state = '${JOB_STATES.cancelled}'
549
+ WHERE name = $1
550
+ AND id IN (SELECT UNNEST($2::uuid[]))
551
+ AND state < '${JOB_STATES.completed}'
552
+ RETURNING 1
553
+ )
554
+ SELECT COUNT(*) from results
555
+ `;
556
+ }
557
+ function resumeJobs(schema, table) {
558
+ return `
559
+ WITH results as (
560
+ UPDATE ${schema}.${table}
561
+ SET completed_on = NULL,
562
+ state = '${JOB_STATES.created}'
563
+ WHERE name = $1
564
+ AND id IN (SELECT UNNEST($2::uuid[]))
565
+ AND state = '${JOB_STATES.cancelled}'
566
+ RETURNING 1
567
+ )
568
+ SELECT COUNT(*) from results
569
+ `;
570
+ }
571
+ function insertJobs(schema, { table, name, returnId = true }) {
572
+ const sql = `
573
+ INSERT INTO ${schema}.${table} (
574
+ id,
575
+ name,
576
+ data,
577
+ priority,
578
+ start_after,
579
+ singleton_key,
580
+ singleton_on,
581
+ expire_seconds,
582
+ deletion_seconds,
583
+ keep_until,
584
+ retry_limit,
585
+ retry_delay,
586
+ retry_backoff,
587
+ retry_delay_max,
588
+ policy,
589
+ dead_letter
590
+ )
591
+ SELECT
592
+ COALESCE(id, gen_random_uuid()) as id,
593
+ '${name}' as name,
594
+ data,
595
+ COALESCE(priority, 0) as priority,
596
+ j.start_after,
597
+ "singletonKey",
598
+ CASE
599
+ WHEN "singletonSeconds" IS NOT NULL THEN 'epoch'::timestamp + '1s'::interval * ("singletonSeconds" * floor(( date_part('epoch', now()) + COALESCE("singletonOffset",0)) / "singletonSeconds" ))
600
+ ELSE NULL
601
+ END as singleton_on,
602
+ COALESCE("expireInSeconds", q.expire_seconds) as expire_seconds,
603
+ COALESCE("deleteAfterSeconds", q.deletion_seconds) as deletion_seconds,
604
+ j.start_after + (COALESCE("retentionSeconds", q.retention_seconds) * interval '1s') as keep_until,
605
+ COALESCE("retryLimit", q.retry_limit) as retry_limit,
606
+ COALESCE("retryDelay", q.retry_delay) as retry_delay,
607
+ COALESCE("retryBackoff", q.retry_backoff, false) as retry_backoff,
608
+ COALESCE("retryDelayMax", q.retry_delay_max) as retry_delay_max,
609
+ q.policy,
610
+ q.dead_letter
611
+ FROM (
612
+ SELECT *,
613
+ CASE
614
+ WHEN right("startAfter", 1) = 'Z' THEN CAST("startAfter" as timestamp with time zone)
615
+ ELSE now() + CAST(COALESCE("startAfter",'0') as interval)
616
+ END as start_after
617
+ FROM json_to_recordset($1::json) as x (
618
+ id uuid,
619
+ priority integer,
620
+ data jsonb,
621
+ "startAfter" text,
622
+ "retryLimit" integer,
623
+ "retryDelay" integer,
624
+ "retryDelayMax" integer,
625
+ "retryBackoff" boolean,
626
+ "singletonKey" text,
627
+ "singletonSeconds" integer,
628
+ "singletonOffset" integer,
629
+ "expireInSeconds" integer,
630
+ "deleteAfterSeconds" integer,
631
+ "retentionSeconds" integer
632
+ )
633
+ ) j
634
+ JOIN ${schema}.queue q ON q.name = '${name}'
635
+ ON CONFLICT DO NOTHING
636
+ ${returnId ? 'RETURNING id' : ''}
637
+ `;
638
+ return sql;
639
+ }
640
+ function failJobsById(schema, table) {
641
+ const where = `name = $1 AND id IN (SELECT UNNEST($2::uuid[])) AND state < '${JOB_STATES.completed}'`;
642
+ const output = '$3::jsonb';
643
+ return failJobs(schema, table, where, output);
644
+ }
645
+ function failJobsByTimeout(schema, table, queues) {
646
+ const where = `state = '${JOB_STATES.active}'
647
+ AND (started_on + expire_seconds * interval '1s') < now()
648
+ AND name IN (${getQueueInClause(queues)})`;
649
+ const output = '\'{ "value": { "message": "job timed out" } }\'::jsonb';
650
+ return locked(schema, failJobs(schema, table, where, output), table + 'failJobsByTimeout');
651
+ }
652
+ function failJobs(schema, table, where, output) {
653
+ return `
654
+ WITH deleted_jobs AS (
655
+ DELETE FROM ${schema}.${table}
656
+ WHERE ${where}
657
+ RETURNING *
658
+ ),
659
+ retried_jobs AS (
660
+ INSERT INTO ${schema}.${table} (
661
+ id,
662
+ name,
663
+ priority,
664
+ data,
665
+ state,
666
+ retry_limit,
667
+ retry_count,
668
+ retry_delay,
669
+ retry_backoff,
670
+ retry_delay_max,
671
+ start_after,
672
+ started_on,
673
+ singleton_key,
674
+ singleton_on,
675
+ expire_seconds,
676
+ deletion_seconds,
677
+ created_on,
678
+ completed_on,
679
+ keep_until,
680
+ policy,
681
+ output,
682
+ dead_letter
683
+ )
684
+ SELECT
685
+ id,
686
+ name,
687
+ priority,
688
+ data,
689
+ CASE
690
+ WHEN retry_count < retry_limit THEN '${JOB_STATES.retry}'::${schema}.job_state
691
+ ELSE '${JOB_STATES.failed}'::${schema}.job_state
692
+ END as state,
693
+ retry_limit,
694
+ retry_count,
695
+ retry_delay,
696
+ retry_backoff,
697
+ retry_delay_max,
698
+ CASE WHEN retry_count = retry_limit THEN start_after
699
+ WHEN NOT retry_backoff THEN now() + retry_delay * interval '1'
700
+ ELSE now() + LEAST(
701
+ retry_delay_max,
702
+ retry_delay + (
703
+ 2 ^ LEAST(16, retry_count + 1) / 2 +
704
+ 2 ^ LEAST(16, retry_count + 1) / 2 * random()
705
+ )
706
+ ) * interval '1s'
707
+ END as start_after,
708
+ started_on,
709
+ singleton_key,
710
+ singleton_on,
711
+ expire_seconds,
712
+ deletion_seconds,
713
+ created_on,
714
+ CASE WHEN retry_count < retry_limit THEN NULL ELSE now() END as completed_on,
715
+ keep_until,
716
+ policy,
717
+ ${output},
718
+ dead_letter
719
+ FROM deleted_jobs
720
+ ON CONFLICT DO NOTHING
721
+ RETURNING *
722
+ ),
723
+ failed_jobs as (
724
+ INSERT INTO ${schema}.${table} (
725
+ id,
726
+ name,
727
+ priority,
728
+ data,
729
+ state,
730
+ retry_limit,
731
+ retry_count,
732
+ retry_delay,
733
+ retry_backoff,
734
+ retry_delay_max,
735
+ start_after,
736
+ started_on,
737
+ singleton_key,
738
+ singleton_on,
739
+ expire_seconds,
740
+ deletion_seconds,
741
+ created_on,
742
+ completed_on,
743
+ keep_until,
744
+ policy,
745
+ output,
746
+ dead_letter
747
+ )
748
+ SELECT
749
+ id,
750
+ name,
751
+ priority,
752
+ data,
753
+ '${JOB_STATES.failed}'::${schema}.job_state as state,
754
+ retry_limit,
755
+ retry_count,
756
+ retry_delay,
757
+ retry_backoff,
758
+ retry_delay_max,
759
+ start_after,
760
+ started_on,
761
+ singleton_key,
762
+ singleton_on,
763
+ expire_seconds,
764
+ deletion_seconds,
765
+ created_on,
766
+ now() as completed_on,
767
+ keep_until,
768
+ policy,
769
+ ${output},
770
+ dead_letter
771
+ FROM deleted_jobs
772
+ WHERE id NOT IN (SELECT id from retried_jobs)
773
+ RETURNING *
774
+ ),
775
+ results as (
776
+ SELECT * FROM retried_jobs
777
+ UNION ALL
778
+ SELECT * FROM failed_jobs
779
+ ),
780
+ dlq_jobs as (
781
+ INSERT INTO ${schema}.job (name, data, output, retry_limit, retry_backoff, retry_delay, keep_until, deletion_seconds)
782
+ SELECT
783
+ r.dead_letter,
784
+ data,
785
+ output,
786
+ q.retry_limit,
787
+ q.retry_backoff,
788
+ q.retry_delay,
789
+ now() + q.retention_seconds * interval '1s',
790
+ q.deletion_seconds
791
+ FROM results r
792
+ JOIN ${schema}.queue q ON q.name = r.dead_letter
793
+ WHERE state = '${JOB_STATES.failed}'
794
+ )
795
+ SELECT COUNT(*) FROM results
796
+ `;
797
+ }
798
+ function deletion(schema, table, queues) {
799
+ const sql = `
800
+ DELETE FROM ${schema}.${table}
801
+ WHERE name IN (${getQueueInClause(queues)})
802
+ AND
803
+ (
804
+ completed_on + deletion_seconds * interval '1s' < now()
805
+ OR
806
+ (state < '${JOB_STATES.active}' AND keep_until < now())
807
+ )
808
+ `;
809
+ return locked(schema, sql, table + 'deletion');
810
+ }
811
+ function retryJobs(schema, table) {
812
+ return `
813
+ WITH results as (
814
+ UPDATE ${schema}.job
815
+ SET state = '${JOB_STATES.retry}',
816
+ retry_limit = retry_limit + 1
817
+ WHERE name = $1
818
+ AND id IN (SELECT UNNEST($2::uuid[]))
819
+ AND state = '${JOB_STATES.failed}'
820
+ RETURNING 1
821
+ )
822
+ SELECT COUNT(*) from results
823
+ `;
824
+ }
825
+ function getQueueStats(schema, table, queues) {
826
+ return `
827
+ SELECT
828
+ name,
829
+ (count(*) FILTER (WHERE start_after > now()))::int as "deferredCount",
830
+ (count(*) FILTER (WHERE state < '${JOB_STATES.active}'))::int as "queuedCount",
831
+ (count(*) FILTER (WHERE state = '${JOB_STATES.active}'))::int as "activeCount",
832
+ count(*)::int as "totalCount",
833
+ array_agg(singleton_key) FILTER (WHERE policy IN ('${QUEUE_POLICIES.singleton}','${QUEUE_POLICIES.stately}') AND state = '${JOB_STATES.active}') as "singletonsActive"
834
+ FROM ${schema}.${table}
835
+ WHERE name IN (${getQueueInClause(queues)})
836
+ GROUP BY 1
837
+ `;
838
+ }
839
+ function cacheQueueStats(schema, table, queues) {
840
+ const sql = `
841
+ WITH stats AS (${getQueueStats(schema, table, queues)})
842
+ UPDATE ${schema}.queue SET
843
+ deferred_count = "deferredCount",
844
+ queued_count = "queuedCount",
845
+ active_count = "activeCount",
846
+ total_count = "totalCount",
847
+ singletons_active = "singletonsActive"
848
+ FROM stats
849
+ WHERE queue.name = stats.name
850
+ RETURNING
851
+ queue.name,
852
+ "queuedCount",
853
+ warning_queued as "warningQueueSize"
854
+ `;
855
+ return locked(schema, sql, 'queue-stats');
856
+ }
857
+ function locked(schema, query, key) {
858
+ if (Array.isArray(query)) {
859
+ query = query.join(';\n');
860
+ }
861
+ return `
862
+ BEGIN;
863
+ SET LOCAL lock_timeout = 30000;
864
+ SET LOCAL idle_in_transaction_session_timeout = 30000;
865
+ ${advisoryLock(schema, key)};
866
+ ${query};
867
+ COMMIT;
868
+ `;
869
+ }
870
+ function advisoryLock(schema, key) {
871
+ return `SELECT pg_advisory_xact_lock(
872
+ ('x' || encode(sha224((current_database() || '.pgboss.${schema}${key || ''}')::bytea), 'hex'))::bit(64)::bigint
873
+ )`;
874
+ }
875
+ function assertMigration(schema, version) {
876
+ // raises 'division by zero' if already on desired schema version
877
+ return `SELECT version::int/(version::int-${version}) from ${schema}.version`;
878
+ }
879
+ function getJobById(schema, table) {
880
+ return `SELECT ${JOB_COLUMNS_ALL} FROM ${schema}.${table} WHERE name = $1 AND id = $2`;
881
+ }
882
+ function getQueueInClause(queues) {
883
+ return queues.map(i => `'${i}'`).join(',');
884
+ }
885
+ export { create, insertVersion, getVersion, setVersion, versionTableExists, fetchNextJob, completeJobs, cancelJobs, resumeJobs, retryJobs, deleteJobsById, deleteAllJobs, deleteQueuedJobs, deleteStoredJobs, truncateTable, failJobsById, failJobsByTimeout, insertJobs, getTime, getSchedules, getSchedulesByQueue, schedule, unschedule, subscribe, unsubscribe, getQueuesForEvent, deletion, cacheQueueStats, updateQueue, createQueue, deleteQueue, getQueues, getQueueStats, trySetQueueMonitorTime, trySetQueueDeletionTime, trySetCronTime, locked, assertMigration, getJobById, QUEUE_POLICIES, JOB_STATES, MIGRATE_RACE_MESSAGE, CREATE_RACE_MESSAGE, DEFAULT_SCHEMA, };