/
plans.js
713 lines (650 loc) · 19.3 KB
/
plans.js
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
const assert = require('assert')
const states = {
created: 'created',
retry: 'retry',
active: 'active',
completed: 'completed',
expired: 'expired',
cancelled: 'cancelled',
failed: 'failed'
}
const DEFAULT_SCHEMA = 'pgboss'
const COMPLETION_JOB_PREFIX = `__state__${states.completed}__`
const SINGLETON_QUEUE_KEY = '__pgboss__singleton_queue'
const SINGLETON_QUEUE_KEY_ESCAPED = SINGLETON_QUEUE_KEY.replace(/_/g, '\\_')
const MIGRATE_RACE_MESSAGE = 'division by zero'
const CREATE_RACE_MESSAGE = 'already exists'
module.exports = {
create,
insertVersion,
getVersion,
setVersion,
versionTableExists,
fetchNextJob,
completeJobs,
cancelJobs,
resumeJobs,
failJobs,
insertJob,
insertJobs,
getTime,
getSchedules,
schedule,
unschedule,
subscribe,
unsubscribe,
getQueuesForEvent,
expire,
archive,
purge,
countStates,
deleteQueue,
deleteAllQueues,
clearStorage,
getQueueSize,
getMaintenanceTime,
setMaintenanceTime,
getCronTime,
setCronTime,
locked,
assertMigration,
getArchivedJobById,
getJobById,
states: { ...states },
COMPLETION_JOB_PREFIX,
SINGLETON_QUEUE_KEY,
MIGRATE_RACE_MESSAGE,
CREATE_RACE_MESSAGE,
DEFAULT_SCHEMA
}
function locked (schema, query) {
if (Array.isArray(query)) {
query = query.join(';\n')
}
return `
BEGIN;
SET LOCAL statement_timeout = '30s';
${advisoryLock(schema)};
${query};
COMMIT;
`
}
function create (schema, version) {
const commands = [
createSchema(schema),
createVersionTable(schema),
createJobStateEnum(schema),
createJobTable(schema),
cloneJobTableForArchive(schema),
createScheduleTable(schema),
createSubscriptionTable(schema),
addIdIndexToArchive(schema),
addArchivedOnToArchive(schema),
addArchivedOnIndexToArchive(schema),
createIndexJobName(schema),
createIndexJobFetch(schema),
createIndexSingletonOn(schema),
createIndexSingletonKeyOn(schema),
createIndexSingletonKey(schema),
createIndexSingletonQueue(schema),
insertVersion(schema, version)
]
return locked(schema, commands)
}
function createSchema (schema) {
return `
CREATE SCHEMA IF NOT EXISTS ${schema}
`
}
function createVersionTable (schema) {
return `
CREATE TABLE ${schema}.version (
version int primary key,
maintained_on timestamp with time zone,
cron_on timestamp with time zone
)
`
}
function createJobStateEnum (schema) {
// ENUM definition order is important
// base type is numeric and first values are less than last values
return `
CREATE TYPE ${schema}.job_state AS ENUM (
'${states.created}',
'${states.retry}',
'${states.active}',
'${states.completed}',
'${states.expired}',
'${states.cancelled}',
'${states.failed}'
)
`
}
function createJobTable (schema) {
return `
CREATE TABLE ${schema}.job (
id uuid primary key not null default gen_random_uuid(),
name text not null,
priority integer not null default(0),
data jsonb,
state ${schema}.job_state not null default('${states.created}'),
retryLimit integer not null default(0),
retryCount integer not null default(0),
retryDelay integer not null default(0),
retryBackoff boolean not null default false,
startAfter timestamp with time zone not null default now(),
startedOn timestamp with time zone,
singletonKey text,
singletonOn timestamp without time zone,
expireIn interval not null default interval '15 minutes',
createdOn timestamp with time zone not null default now(),
completedOn timestamp with time zone,
keepUntil timestamp with time zone NOT NULL default now() + interval '14 days',
on_complete boolean not null default false,
output jsonb
)
`
}
function cloneJobTableForArchive (schema) {
return `CREATE TABLE ${schema}.archive (LIKE ${schema}.job)`
}
function addArchivedOnToArchive (schema) {
return `ALTER TABLE ${schema}.archive ADD archivedOn timestamptz NOT NULL DEFAULT now()`
}
function addArchivedOnIndexToArchive (schema) {
return `CREATE INDEX archive_archivedon_idx ON ${schema}.archive(archivedon)`
}
function addIdIndexToArchive (schema) {
return `CREATE INDEX archive_id_idx ON ${schema}.archive(id)`
}
function setMaintenanceTime (schema) {
return `UPDATE ${schema}.version SET maintained_on = now()`
}
function getMaintenanceTime (schema) {
return `SELECT maintained_on, EXTRACT( EPOCH FROM (now() - maintained_on) ) seconds_ago FROM ${schema}.version`
}
function setCronTime (schema, time) {
time = time || 'now()'
return `UPDATE ${schema}.version SET cron_on = ${time}`
}
function getCronTime (schema) {
return `SELECT cron_on, EXTRACT( EPOCH FROM (now() - cron_on) ) seconds_ago FROM ${schema}.version`
}
function deleteQueue (schema, options = {}) {
options.before = options.before || states.active
assert(options.before in states, `${options.before} is not a valid state`)
return `DELETE FROM ${schema}.job WHERE name = $1 and state < '${options.before}'`
}
function deleteAllQueues (schema, options = {}) {
options.before = options.before || states.active
assert(options.before in states, `${options.before} is not a valid state`)
return `DELETE FROM ${schema}.job WHERE state < '${options.before}'`
}
function clearStorage (schema) {
return `TRUNCATE ${schema}.job, ${schema}.archive`
}
function getQueueSize (schema, options = {}) {
options.before = options.before || states.active
assert(options.before in states, `${options.before} is not a valid state`)
return `SELECT count(*) as count FROM ${schema}.job WHERE name = $1 AND state < '${options.before}'`
}
function createIndexSingletonKey (schema) {
// anything with singletonKey means "only 1 job can be queued or active at a time"
return `
CREATE UNIQUE INDEX job_singletonKey ON ${schema}.job (name, singletonKey) WHERE state < '${states.completed}' AND singletonOn IS NULL AND NOT singletonKey LIKE '${SINGLETON_QUEUE_KEY_ESCAPED}%'
`
}
function createIndexSingletonQueue (schema) {
// "singleton queue" means "only 1 job can be queued at a time"
return `
CREATE UNIQUE INDEX job_singleton_queue ON ${schema}.job (name, singletonKey) WHERE state < '${states.active}' AND singletonOn IS NULL AND singletonKey LIKE '${SINGLETON_QUEUE_KEY_ESCAPED}%'
`
}
function createIndexSingletonOn (schema) {
// anything with singletonOn means "only 1 job within this time period, queued, active or completed"
return `
CREATE UNIQUE INDEX job_singletonOn ON ${schema}.job (name, singletonOn) WHERE state < '${states.expired}' AND singletonKey IS NULL
`
}
function createIndexSingletonKeyOn (schema) {
// anything with both singletonOn and singletonKey means "only 1 job within this time period with this key, queued, active or completed"
return `
CREATE UNIQUE INDEX job_singletonKeyOn ON ${schema}.job (name, singletonOn, singletonKey) WHERE state < '${states.expired}'
`
}
function createIndexJobName (schema) {
return `
CREATE INDEX job_name ON ${schema}.job (name text_pattern_ops)
`
}
function createIndexJobFetch (schema) {
return `
CREATE INDEX job_fetch ON ${schema}.job (name text_pattern_ops, startAfter) WHERE state < '${states.active}'
`
}
function createScheduleTable (schema) {
return `
CREATE TABLE ${schema}.schedule (
name text primary key,
cron text not null,
timezone text,
data jsonb,
options jsonb,
created_on timestamp with time zone not null default now(),
updated_on timestamp with time zone not null default now()
)
`
}
function createSubscriptionTable (schema) {
return `
CREATE TABLE ${schema}.subscription (
event text not null,
name text not null,
created_on timestamp with time zone not null default now(),
updated_on timestamp with time zone not null default now(),
PRIMARY KEY(event, name)
)
`
}
function getSchedules (schema) {
return `
SELECT * FROM ${schema}.schedule
`
}
function schedule (schema) {
return `
INSERT INTO ${schema}.schedule (name, cron, timezone, data, options)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (name) DO UPDATE SET
cron = EXCLUDED.cron,
timezone = EXCLUDED.timezone,
data = EXCLUDED.data,
options = EXCLUDED.options,
updated_on = now()
`
}
function unschedule (schema) {
return `
DELETE FROM ${schema}.schedule
WHERE name = $1
`
}
function subscribe (schema) {
return `
INSERT INTO ${schema}.subscription (event, name)
VALUES ($1, $2)
ON CONFLICT (event, name) DO UPDATE SET
event = EXCLUDED.event,
name = EXCLUDED.name,
updated_on = now()
`
}
function unsubscribe (schema) {
return `
DELETE FROM ${schema}.subscription
WHERE event = $1 and name = $2
`
}
function getQueuesForEvent (schema) {
return `
SELECT name FROM ${schema}.subscription
WHERE event = $1
`
}
function getTime () {
return "SELECT round(date_part('epoch', now()) * 1000) as time"
}
function getVersion (schema) {
return `SELECT version from ${schema}.version`
}
function setVersion (schema, version) {
return `UPDATE ${schema}.version SET version = '${version}'`
}
function versionTableExists (schema) {
return `SELECT to_regclass('${schema}.version') as name`
}
function insertVersion (schema, version) {
return `INSERT INTO ${schema}.version(version) VALUES ('${version}')`
}
function fetchNextJob (schema) {
return (includeMetadata, enforceSingletonQueueActiveLimit) => `
WITH nextJob as (
SELECT id
FROM ${schema}.job j
WHERE state < '${states.active}'
AND name LIKE $1
AND startAfter < now()
${enforceSingletonQueueActiveLimit
? `AND (
CASE
WHEN singletonKey IS NOT NULL
AND singletonKey LIKE '${SINGLETON_QUEUE_KEY_ESCAPED}%'
THEN NOT EXISTS (
SELECT 1
FROM ${schema}.job active_job
WHERE active_job.state = '${states.active}'
AND active_job.name = j.name
AND active_job.singletonKey = j.singletonKey
LIMIT 1
)
ELSE
true
END
)`
: ''}
ORDER BY priority desc, createdOn, id
LIMIT $2
FOR UPDATE SKIP LOCKED
)
UPDATE ${schema}.job j SET
state = '${states.active}',
startedOn = now(),
retryCount = CASE WHEN state = '${states.retry}' THEN retryCount + 1 ELSE retryCount END
FROM nextJob
WHERE j.id = nextJob.id
RETURNING ${includeMetadata ? 'j.*' : 'j.id, name, data'}, EXTRACT(epoch FROM expireIn) as expire_in_seconds
`
}
function buildJsonCompletionObject (withResponse) {
// job completion contract
return `jsonb_build_object(
'request', jsonb_build_object('id', id, 'name', name, 'data', data),
'response', ${withResponse ? '$2::jsonb' : 'null'},
'state', state,
'retryCount', retryCount,
'createdOn', createdOn,
'startedOn', startedOn,
'completedOn', completedOn,
'failed', CASE WHEN state = '${states.completed}' THEN false ELSE true END
)`
}
const retryCompletedOnCase = `CASE
WHEN retryCount < retryLimit
THEN NULL
ELSE now()
END`
const retryStartAfterCase = `CASE
WHEN retryCount = retryLimit THEN startAfter
WHEN NOT retryBackoff THEN now() + retryDelay * interval '1'
ELSE now() +
(
retryDelay * 2 ^ LEAST(16, retryCount + 1) / 2
+
retryDelay * 2 ^ LEAST(16, retryCount + 1) / 2 * random()
)
* interval '1'
END`
const keepUntilInheritance = 'keepUntil + (keepUntil - startAfter)'
function completeJobs (schema) {
return `
WITH results AS (
UPDATE ${schema}.job
SET completedOn = now(),
state = '${states.completed}',
output = $2::jsonb
WHERE id IN (SELECT UNNEST($1::uuid[]))
AND state = '${states.active}'
RETURNING *
), completion_jobs as (
INSERT INTO ${schema}.job (name, data, keepUntil)
SELECT
'${COMPLETION_JOB_PREFIX}' || name,
${buildJsonCompletionObject(true)},
${keepUntilInheritance}
FROM results
WHERE NOT name LIKE '${COMPLETION_JOB_PREFIX}%'
AND on_complete
)
SELECT COUNT(*) FROM results
`
}
function failJobs (schema) {
return `
WITH results AS (
UPDATE ${schema}.job
SET state = CASE
WHEN retryCount < retryLimit
THEN '${states.retry}'::${schema}.job_state
ELSE '${states.failed}'::${schema}.job_state
END,
completedOn = ${retryCompletedOnCase},
startAfter = ${retryStartAfterCase},
output = $2::jsonb
WHERE id IN (SELECT UNNEST($1::uuid[]))
AND state < '${states.completed}'
RETURNING *
), completion_jobs as (
INSERT INTO ${schema}.job (name, data, keepUntil)
SELECT
'${COMPLETION_JOB_PREFIX}' || name,
${buildJsonCompletionObject(true)},
${keepUntilInheritance}
FROM results
WHERE state = '${states.failed}'
AND NOT name LIKE '${COMPLETION_JOB_PREFIX}%'
AND on_complete
)
SELECT COUNT(*) FROM results
`
}
function expire (schema) {
return `
WITH results AS (
UPDATE ${schema}.job
SET state = CASE
WHEN retryCount < retryLimit THEN '${states.retry}'::${schema}.job_state
ELSE '${states.expired}'::${schema}.job_state
END,
completedOn = ${retryCompletedOnCase},
startAfter = ${retryStartAfterCase}
WHERE state = '${states.active}'
AND (startedOn + expireIn) < now()
RETURNING *
)
INSERT INTO ${schema}.job (name, data, keepUntil)
SELECT
'${COMPLETION_JOB_PREFIX}' || name,
${buildJsonCompletionObject()},
${keepUntilInheritance}
FROM results
WHERE state = '${states.expired}'
AND NOT name LIKE '${COMPLETION_JOB_PREFIX}%'
AND on_complete
`
}
function cancelJobs (schema) {
return `
with results as (
UPDATE ${schema}.job
SET completedOn = now(),
state = '${states.cancelled}'
WHERE id IN (SELECT UNNEST($1::uuid[]))
AND state < '${states.completed}'
RETURNING 1
)
SELECT COUNT(*) from results
`
}
function resumeJobs (schema) {
return `
with results as (
UPDATE ${schema}.job
SET completedOn = NULL,
state = '${states.created}'
WHERE id IN (SELECT UNNEST($1::uuid[]))
RETURNING 1
)
SELECT COUNT(*) from results
`
}
function insertJob (schema) {
return `
INSERT INTO ${schema}.job (
id,
name,
priority,
state,
retryLimit,
startAfter,
expireIn,
data,
singletonKey,
singletonOn,
retryDelay,
retryBackoff,
keepUntil,
on_complete
)
SELECT
id,
name,
priority,
state,
retryLimit,
startAfter,
expireIn,
data,
singletonKey,
singletonOn,
retryDelay,
retryBackoff,
keepUntil,
on_complete
FROM
( SELECT *,
CASE
WHEN right(keepUntilValue, 1) = 'Z' THEN CAST(keepUntilValue as timestamp with time zone)
ELSE startAfter + CAST(COALESCE(keepUntilValue,'0') as interval)
END as keepUntil
FROM
( SELECT *,
CASE
WHEN right(startAfterValue, 1) = 'Z' THEN CAST(startAfterValue as timestamp with time zone)
ELSE now() + CAST(COALESCE(startAfterValue,'0') as interval)
END as startAfter
FROM
( SELECT
$1::uuid as id,
$2::text as name,
$3::int as priority,
'${states.created}'::${schema}.job_state as state,
$4::int as retryLimit,
$5::text as startAfterValue,
CAST($6 as interval) as expireIn,
$7::jsonb as data,
$8::text as singletonKey,
CASE
WHEN $9::integer IS NOT NULL THEN 'epoch'::timestamp + '1 second'::interval * ($9 * floor((date_part('epoch', now()) + $10) / $9))
ELSE NULL
END as singletonOn,
$11::int as retryDelay,
$12::bool as retryBackoff,
$13::text as keepUntilValue,
$14::boolean as on_complete
) j1
) j2
) j3
ON CONFLICT DO NOTHING
RETURNING id
`
}
function insertJobs (schema) {
return `
INSERT INTO ${schema}.job (
id,
name,
data,
priority,
startAfter,
expireIn,
retryLimit,
retryDelay,
retryBackoff,
singletonKey,
keepUntil,
on_complete
)
SELECT
COALESCE(id, gen_random_uuid()) as id,
name,
data,
COALESCE(priority, 0) as priority,
COALESCE("startAfter", now()) as startAfter,
COALESCE("expireInSeconds", 15 * 60) * interval '1s' as expireIn,
COALESCE("retryLimit", 0) as retryLimit,
COALESCE("retryDelay", 0) as retryDelay,
COALESCE("retryBackoff", false) as retryBackoff,
"singletonKey",
COALESCE("keepUntil", now() + interval '14 days') as keepUntil,
COALESCE("onComplete", false) as onComplete
FROM json_to_recordset($1) as x(
id uuid,
name text,
priority integer,
data jsonb,
"retryLimit" integer,
"retryDelay" integer,
"retryBackoff" boolean,
"startAfter" timestamp with time zone,
"singletonKey" text,
"expireInSeconds" integer,
"keepUntil" timestamp with time zone,
"onComplete" boolean
)
ON CONFLICT DO NOTHING
`
}
function purge (schema, interval) {
return `
DELETE FROM ${schema}.archive
WHERE archivedOn < (now() - interval '${interval}')
`
}
function archive (schema, completedInterval, failedInterval = completedInterval) {
return `
WITH archived_rows AS (
DELETE FROM ${schema}.job
WHERE (
state <> '${states.failed}' AND completedOn < (now() - interval '${completedInterval}')
)
OR (
state = '${states.failed}' AND completedOn < (now() - interval '${failedInterval}')
)
OR (
state < '${states.active}' AND keepUntil < now()
)
RETURNING *
)
INSERT INTO ${schema}.archive (
id, name, priority, data, state, retryLimit, retryCount, retryDelay, retryBackoff, startAfter, startedOn, singletonKey, singletonOn, expireIn, createdOn, completedOn, keepUntil, on_complete, output
)
SELECT
id, name, priority, data, state, retryLimit, retryCount, retryDelay, retryBackoff, startAfter, startedOn, singletonKey, singletonOn, expireIn, createdOn, completedOn, keepUntil, on_complete, output
FROM archived_rows
`
}
function countStates (schema) {
return `
SELECT name, state, count(*) size
FROM ${schema}.job
GROUP BY rollup(name), rollup(state)
`
}
function advisoryLock (schema) {
return `SELECT pg_advisory_xact_lock(
('x' || md5(current_database() || '.pgboss.${schema}'))::bit(64)::bigint
)`
}
function assertMigration (schema, version) {
// raises 'division by zero' if already on desired schema version
return `SELECT version::int/(version::int-${version}) from ${schema}.version`
}
function getJobById (schema) {
return getJobByTableAndId(schema, 'job')
}
function getArchivedJobById (schema) {
return getJobByTableAndId(schema, 'archive')
}
function getJobByTableAndId (schema, table) {
return `SELECT * From ${schema}.${table} WHERE id = $1`
}