-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.sql
More file actions
1888 lines (1730 loc) · 58.3 KB
/
schema.sql
File metadata and controls
1888 lines (1730 loc) · 58.3 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
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Note: this is taken from `absurd` (https://github.com/earendil-works/absurd)
-- durable installs a Postgres-native durable workflow system that can be dropped
-- into an existing database.
--
-- It bootstraps the `durable` schema and required extensions so that jobs, runs,
-- checkpoints, and workflow events all live alongside application data without
-- external services.
--
-- Each queue is materialized as its own set of tables that share a prefix:
-- * `t_` for tasks (what is to be run)
-- * `r_` for runs (attempts to run a task)
-- * `c_` for checkpoints (saved states)
-- * `e_` for emitted events
-- * `w_` for wait registrations
--
-- `create_queue`, `drop_queue`, and `list_queues` provide the management
-- surface for provisioning queues safely.
--
-- Task execution flows through `spawn_task`, which records the logical task and
-- its first run, and `claim_task`, which hands work to workers with leasing
-- semantics, state transitions, and cancellation checks. Runtime routines
-- such as `complete_run`, `sleep_for`, and `fail_run` advance or retry work,
-- enforce attempt accounting, and keep the task and run tables synchronized.
--
-- Long-running or event-driven workflows rely on lightweight persistence
-- primitives. Checkpoint helpers (`set_task_checkpoint_state`,
-- `get_task_checkpoint_state`, `get_task_checkpoint_states`) write arbitrary
-- JSON payloads keyed by task and step, while `await_event` and `emit_event`
-- coordinate sleepers and external signals so that tasks can suspend and resume
-- without losing context. Events are uniquely indexed and can only be fired
-- once per name.
create extension if not exists "uuid-ossp";
create schema if not exists durable;
-- Returns either the actual current timestamp or a fake one if
-- the session sets `durable.fake_now`. This lets tests control time.
create function durable.current_time ()
returns timestamptz
language plpgsql
volatile
as $$
declare
v_fake text;
begin
v_fake := current_setting('durable.fake_now', true);
if v_fake is not null and length(trim(v_fake)) > 0 then
return v_fake::timestamptz;
end if;
return clock_timestamp();
end;
$$;
create table if not exists durable.queues (
queue_name text primary key,
created_at timestamptz not null default durable.current_time()
);
create table if not exists durable.cron_schedules (
schedule_name text not null,
queue_name text not null,
task_name text not null,
cron_expression text not null,
params jsonb not null default '{}'::jsonb,
spawn_options jsonb not null default '{}'::jsonb,
metadata jsonb not null default '{}'::jsonb,
pgcron_job_name text not null,
created_at timestamptz not null default durable.current_time(),
updated_at timestamptz not null default durable.current_time(),
primary key (queue_name, schedule_name)
);
create index if not exists idx_cron_schedules_metadata
on durable.cron_schedules using gin (metadata);
create index if not exists idx_cron_schedules_task_name
on durable.cron_schedules (queue_name, task_name);
create function durable.ensure_queue_tables (p_queue_name text)
returns void
language plpgsql
as $$
begin
execute format(
'create table if not exists durable.%I (
task_id uuid primary key,
task_name text not null,
params jsonb not null,
headers jsonb,
retry_strategy jsonb,
max_attempts integer,
cancellation jsonb,
parent_task_id uuid,
enqueue_at timestamptz not null default durable.current_time(),
first_started_at timestamptz,
state text not null check (state in (''pending'', ''running'', ''sleeping'', ''completed'', ''failed'', ''cancelled'')),
attempts integer not null default 0,
last_attempt_run uuid,
completed_payload jsonb,
cancelled_at timestamptz
) with (fillfactor=70)',
't_' || p_queue_name
);
execute format('comment on column durable.%I.params is %L', 't_' || p_queue_name, 'User-defined. Task input parameters. Schema depends on Task::Params type.');
execute format('comment on column durable.%I.headers is %L', 't_' || p_queue_name, 'User-defined. Optional key-value metadata as {"key": <any JSON value>}.');
execute format('comment on column durable.%I.retry_strategy is %L', 't_' || p_queue_name, '{"kind": "none"} | {"kind": "fixed", "base_seconds": <u64>} | {"kind": "exponential", "base_seconds": <u64>, "factor": <f64>, "max_seconds": <u64>}');
execute format('comment on column durable.%I.cancellation is %L', 't_' || p_queue_name, '{"max_delay": <seconds>, "max_duration": <seconds>} - both optional. max_delay: cancel if not started within N seconds of enqueue. max_duration: cancel if not completed within N seconds of first start.');
execute format('comment on column durable.%I.completed_payload is %L', 't_' || p_queue_name, 'User-defined. Task return value. Schema depends on Task::Output type.');
execute format(
'create table if not exists durable.%I (
run_id uuid primary key,
task_id uuid not null,
attempt integer not null,
state text not null check (state in (''pending'', ''running'', ''sleeping'', ''completed'', ''failed'', ''cancelled'')),
claimed_by text,
claim_expires_at timestamptz,
available_at timestamptz not null,
wake_event text,
event_payload jsonb,
started_at timestamptz,
completed_at timestamptz,
failed_at timestamptz,
result jsonb,
failure_reason jsonb,
created_at timestamptz not null default durable.current_time()
) with (fillfactor=70)',
'r_' || p_queue_name
);
execute format('comment on column durable.%I.wake_event is %L', 'r_' || p_queue_name, 'Event name this run is waiting for while sleeping. Set by await_event when suspending, cleared when the event fires or timeout expires.');
execute format('comment on column durable.%I.event_payload is %L', 'r_' || p_queue_name, 'Payload delivered by emit_event when waking this run. Consumed by await_event on the next claim to return the value to the caller.');
execute format('comment on column durable.%I.result is %L', 'r_' || p_queue_name, 'User-defined. Serialized task output. Schema depends on Task::Output type.');
execute format('comment on column durable.%I.failure_reason is %L', 'r_' || p_queue_name, '{"name": "<error type>", "message": "<string>", "backtrace": "<string>"}');
execute format(
'create table if not exists durable.%I (
task_id uuid not null,
checkpoint_name text not null,
state jsonb,
owner_run_id uuid,
updated_at timestamptz not null default durable.current_time(),
primary key (task_id, checkpoint_name)
) with (fillfactor=70)',
'c_' || p_queue_name
);
execute format('comment on column durable.%I.state is %L', 'c_' || p_queue_name, 'User-defined. Checkpoint value from ctx.step(). Any JSON-serializable value.');
execute format(
'create table if not exists durable.%I (
event_name text primary key,
payload jsonb,
emitted_at timestamptz not null default durable.current_time()
)',
'e_' || p_queue_name
);
execute format('comment on column durable.%I.payload is %L', 'e_' || p_queue_name, 'User-defined. Event payload. Internal child events use: {"status": "completed"|"failed"|"cancelled", "result"?: <json>, "error"?: <json>}');
execute format(
'create table if not exists durable.%I (
task_id uuid not null,
run_id uuid not null,
step_name text not null,
event_name text not null,
timeout_at timestamptz,
created_at timestamptz not null default durable.current_time(),
primary key (run_id, step_name)
)',
'w_' || p_queue_name
);
execute format(
'create index if not exists %I on durable.%I (state, available_at)',
('r_' || p_queue_name) || '_sai',
'r_' || p_queue_name
);
-- Partial index for claim candidate ORDER BY (available_at, run_id).
-- Matches the exact ordering used in the claim query for ready runs.
execute format(
'create index if not exists %I on durable.%I (available_at, run_id) include (task_id)
where state in (''pending'', ''sleeping'')',
('r_' || p_queue_name) || '_ready',
'r_' || p_queue_name
);
execute format(
'create index if not exists %I on durable.%I (task_id)',
('r_' || p_queue_name) || '_ti',
'r_' || p_queue_name
);
execute format(
'create index if not exists %I on durable.%I (event_name)',
('w_' || p_queue_name) || '_eni',
'w_' || p_queue_name
);
-- Speed up cleanup_task_terminal wait deletion by task_id.
execute format(
'create index if not exists %I on durable.%I (task_id)',
('w_' || p_queue_name) || '_ti',
'w_' || p_queue_name
);
-- Index for finding children of a parent task (for cascade cancellation)
execute format(
'create index if not exists %I on durable.%I (parent_task_id) where parent_task_id is not null',
('t_' || p_queue_name) || '_pti',
't_' || p_queue_name
);
-- Speed up claim timeout scans.
execute format(
'create index if not exists %I on durable.%I (claim_expires_at)
where state = ''running'' and claim_expires_at is not null',
('r_' || p_queue_name) || '_cei',
'r_' || p_queue_name
);
-- Speed up cancellation sweep: only index tasks that have cancellation policies.
execute format(
'create index if not exists %I on durable.%I (task_id)
where state in (''pending'', ''sleeping'', ''running'')
and cancellation is not null
and (cancellation ? ''max_delay'' or cancellation ? ''max_duration'')',
('t_' || p_queue_name) || '_cxlpol',
't_' || p_queue_name
);
-- Composite index for active task state lookups.
-- Enables Index Only Scans for claim_task join, emit_event, and cancel propagation.
execute format(
'create index if not exists %I on durable.%I (state, task_id)
where state in (''pending'', ''sleeping'', ''running'', ''cancelled'')',
('t_' || p_queue_name) || '_state_tid',
't_' || p_queue_name
);
end;
$$;
-- Creates the queue with the given name.
--
-- If the table already exists, the function returns silently.
create function durable.create_queue (p_queue_name text)
returns void
language plpgsql
as $$
begin
if p_queue_name is null or length(trim(p_queue_name)) = 0 then
raise exception 'Queue name must be provided';
end if;
if length(p_queue_name) + 2 > 50 then
raise exception 'Queue name "%" is too long', p_queue_name;
end if;
begin
insert into durable.queues (queue_name)
values (p_queue_name);
exception when unique_violation then
return;
end;
perform durable.ensure_queue_tables(p_queue_name);
end;
$$;
-- Drop a queue if it exists.
-- Also cleans up any cron schedules and their pg_cron jobs for the queue.
create function durable.drop_queue (p_queue_name text)
returns void
language plpgsql
as $$
declare
v_existing_queue text;
v_rec record;
v_jobid bigint;
begin
select queue_name into v_existing_queue
from durable.queues
where queue_name = p_queue_name;
if v_existing_queue is null then
return;
end if;
-- Clean up any cron schedules associated with this queue
for v_rec in
select pgcron_job_name
from durable.cron_schedules
where queue_name = p_queue_name
loop
begin
select jobid into v_jobid
from cron.job
where jobname = v_rec.pgcron_job_name;
if v_jobid is not null then
perform cron.unschedule(v_jobid);
end if;
exception when others then
-- pg_cron may not be installed; ignore errors
null;
end;
end loop;
delete from durable.cron_schedules where queue_name = p_queue_name;
execute format('drop table if exists durable.%I cascade', 'w_' || p_queue_name);
execute format('drop table if exists durable.%I cascade', 'e_' || p_queue_name);
execute format('drop table if exists durable.%I cascade', 'c_' || p_queue_name);
execute format('drop table if exists durable.%I cascade', 'r_' || p_queue_name);
execute format('drop table if exists durable.%I cascade', 't_' || p_queue_name);
delete from durable.queues where queue_name = p_queue_name;
end;
$$;
-- Lists all queues that currently exist.
create function durable.list_queues ()
returns table (queue_name text)
language sql
as $$
select queue_name from durable.queues order by queue_name;
$$;
-- Spawns a given task in a queue.
create function durable.spawn_task (
p_queue_name text,
p_task_name text,
p_params jsonb,
p_options jsonb default '{}'::jsonb
)
returns table (
task_id uuid,
run_id uuid,
attempt integer
)
language plpgsql
as $$
declare
v_task_id uuid := durable.portable_uuidv7();
v_run_id uuid := durable.portable_uuidv7();
v_attempt integer := 1;
v_headers jsonb;
v_retry_strategy jsonb;
v_max_attempts integer;
v_cancellation jsonb;
v_parent_task_id uuid;
v_now timestamptz := durable.current_time();
v_params jsonb := coalesce(p_params, 'null'::jsonb);
begin
if p_task_name is null or length(trim(p_task_name)) = 0 then
raise exception 'task_name must be provided';
end if;
if p_options is not null then
v_headers := p_options->'headers';
v_retry_strategy := p_options->'retry_strategy';
if p_options ? 'max_attempts' then
v_max_attempts := (p_options->>'max_attempts')::int;
if v_max_attempts is not null and v_max_attempts < 1 then
raise exception 'max_attempts must be >= 1';
end if;
end if;
v_cancellation := p_options->'cancellation';
-- Extract parent_task_id for subtask tracking
v_parent_task_id := (p_options->>'parent_task_id')::uuid;
end if;
execute format(
'insert into durable.%I (task_id, task_name, params, headers, retry_strategy, max_attempts, cancellation, parent_task_id, enqueue_at, first_started_at, state, attempts, last_attempt_run, completed_payload, cancelled_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, null, ''pending'', $10, $11, null, null)',
't_' || p_queue_name
)
using v_task_id, p_task_name, v_params, v_headers, v_retry_strategy, v_max_attempts, v_cancellation, v_parent_task_id, v_now, v_attempt, v_run_id;
execute format(
'insert into durable.%I (run_id, task_id, attempt, state, available_at, wake_event, event_payload, result, failure_reason)
values ($1, $2, $3, ''pending'', $4, null, null, null, null)',
'r_' || p_queue_name
)
using v_run_id, v_task_id, v_attempt, v_now;
return query select v_task_id, v_run_id, v_attempt;
end;
$$;
-- Workers call this to reserve a task from a given queue
-- for a given reservation period in seconds.
create function durable.claim_task (
p_queue_name text,
p_worker_id text,
p_claim_timeout integer default 30,
p_qty integer default 1
)
returns table (
run_id uuid,
task_id uuid,
attempt integer,
task_name text,
params jsonb,
retry_strategy jsonb,
max_attempts integer,
headers jsonb,
wake_event text,
event_payload jsonb
)
language plpgsql
as $$
declare
v_now timestamptz := durable.current_time();
v_claim_timeout integer := coalesce(p_claim_timeout, 30);
v_worker_id text := coalesce(nullif(p_worker_id, ''), 'worker');
v_qty integer := greatest(coalesce(p_qty, 1), 1);
v_claim_until timestamptz;
v_sql text;
v_expired_run record;
v_cancelled_task uuid;
begin
if v_claim_timeout <= 0 then
raise exception 'claim_timeout must be greater than zero';
end if;
v_claim_until := v_now + make_interval(secs => v_claim_timeout);
-- Apply cancellation rules before claiming.
-- These are max_delay (delay before starting) and
-- max_duration (duration from created to finished)
-- Use a loop so we can cleanup each cancelled task properly.
-- Only scan tasks that actually have cancellation policies set.
for v_cancelled_task in
execute format(
'with limits as (
select task_id,
(cancellation->>''max_delay'')::bigint as max_delay,
(cancellation->>''max_duration'')::bigint as max_duration,
enqueue_at,
first_started_at,
state
from durable.%I
where state in (''pending'', ''sleeping'', ''running'')
and cancellation is not null
and (cancellation ? ''max_delay'' or cancellation ? ''max_duration'')
),
to_cancel as (
select task_id
from limits
where
(
max_delay is not null
and first_started_at is null
and extract(epoch from ($1 - enqueue_at)) >= max_delay
)
or
(
max_duration is not null
and first_started_at is not null
and extract(epoch from ($1 - first_started_at)) >= max_duration
)
)
update durable.%I t
set state = ''cancelled'',
cancelled_at = coalesce(t.cancelled_at, $1)
where t.task_id in (select task_id from to_cancel)
returning t.task_id',
't_' || p_queue_name,
't_' || p_queue_name
) using v_now
loop
-- Cancel all runs for this task
execute format(
'update durable.%I
set state = ''cancelled'',
claimed_by = null,
claim_expires_at = null
where task_id = $1
and state not in (''completed'', ''failed'', ''cancelled'')',
'r_' || p_queue_name
) using v_cancelled_task;
-- Cleanup: delete waiters, emit event, cascade cancel children
perform durable.cleanup_task_terminal(p_queue_name, v_cancelled_task, 'cancelled', null, true);
end loop;
-- Fail any run claims that have timed out.
-- Lock tasks first to keep a consistent task -> run lock order.
for v_expired_run in
execute format(
'select r.run_id,
r.task_id,
r.claimed_by,
r.claim_expires_at,
r.attempt
from durable.%I r
join durable.%I t on t.task_id = r.task_id
where r.state = ''running''
and r.claim_expires_at is not null
and r.claim_expires_at <= $1
for update of t skip locked',
'r_' || p_queue_name,
't_' || p_queue_name
)
using v_now
loop
perform durable.fail_run(
p_queue_name,
v_expired_run.task_id,
v_expired_run.run_id,
jsonb_strip_nulls(jsonb_build_object(
'name', '$ClaimTimeout',
'message', 'worker did not finish task within claim interval',
'workerId', v_expired_run.claimed_by,
'claimExpiredAt', v_expired_run.claim_expires_at,
'attempt', v_expired_run.attempt
)),
null
);
end loop;
-- Find all tasks where state is cancelled,
-- then update all the runs to be cancelled as well.
execute format(
'update durable.%I r
set state = ''cancelled'',
claimed_by = null,
claim_expires_at = null,
available_at = $1,
wake_event = null
where task_id in (select task_id from durable.%I where state = ''cancelled'')
and r.state <> ''cancelled''',
'r_' || p_queue_name,
't_' || p_queue_name
) using v_now;
-- Actually claim tasks
v_sql := format(
-- Grab unique pending / sleeping runs that are available now
'with candidate as (
select r.run_id
from durable.%1$I r
join durable.%2$I t on t.task_id = r.task_id
where r.state in (''pending'', ''sleeping'')
and t.state in (''pending'', ''sleeping'', ''running'')
and r.available_at <= $1
order by r.available_at, r.run_id
limit $2
for update skip locked
),
-- update the runs to be running and set claim info
updated as (
update durable.%1$I r
set state = ''running'',
claimed_by = $3,
claim_expires_at = $4,
started_at = $1,
available_at = $1
where run_id in (select run_id from candidate)
returning r.run_id, r.task_id, r.attempt
),
-- update the task to also be running and handle attempt / time bookkeeping
task_upd as (
update durable.%2$I t
set state = ''running'',
attempts = greatest(t.attempts, u.attempt),
first_started_at = coalesce(t.first_started_at, $1),
last_attempt_run = u.run_id
from updated u
where t.task_id = u.task_id
returning t.task_id
),
-- clean up any wait registrations that timed out
-- that are subsumed by the claim
-- e.g. a wait times out so the run becomes available and now
-- it is claimed but we do not want this wait to linger in DB
wait_cleanup as (
delete from durable.%3$I w
using updated u
where w.run_id = u.run_id
and w.timeout_at is not null
and w.timeout_at <= $1
returning w.run_id
)
select
u.run_id,
u.task_id,
u.attempt,
t.task_name,
t.params,
t.retry_strategy,
t.max_attempts,
t.headers,
r.wake_event,
r.event_payload
from updated u
join durable.%1$I r on r.run_id = u.run_id
join durable.%2$I t on t.task_id = u.task_id
order by r.available_at, u.run_id',
'r_' || p_queue_name,
't_' || p_queue_name,
'w_' || p_queue_name
);
return query execute v_sql using v_now, v_qty, v_worker_id, v_claim_until;
end;
$$;
-- Counts unclaimed runs that are ready to be claimed.
-- Uses the same candidate logic as claim_task but without locking or updating.
create function durable.count_unclaimed_ready_tasks (
p_queue_name text
)
returns bigint
language plpgsql
as $$
declare
v_now timestamptz := durable.current_time();
v_count bigint;
begin
execute format(
'select count(*)
from durable.%1$I r
join durable.%2$I t on t.task_id = r.task_id
where r.state in (''pending'', ''sleeping'')
and t.state in (''pending'', ''sleeping'', ''running'')
and r.available_at <= $1',
'r_' || p_queue_name,
't_' || p_queue_name
) into v_count using v_now;
return v_count;
end;
$$;
-- Marks a run as completed
create function durable.complete_run (
p_queue_name text,
p_task_id uuid,
p_run_id uuid,
p_state jsonb default null
)
returns void
language plpgsql
as $$
declare
v_task_id_locked uuid;
v_run_task_id uuid;
v_state text;
v_now timestamptz := durable.current_time();
begin
-- Lock task first to keep a consistent task -> run lock order.
execute format(
'select task_id
from durable.%I
where task_id = $1
for update',
't_' || p_queue_name
)
into v_task_id_locked
using p_task_id;
if v_task_id_locked is null then
raise exception 'Task "%" not found in queue "%"', p_task_id, p_queue_name;
end if;
-- Lock the run after the task lock
execute format(
'select task_id, state
from durable.%I
where run_id = $1
for update',
'r_' || p_queue_name
)
into v_run_task_id, v_state
using p_run_id;
if v_run_task_id is null then
raise exception 'Run "%" not found in queue "%"', p_run_id, p_queue_name;
end if;
if v_run_task_id <> p_task_id then
raise exception 'Run "%" does not belong to task "%"', p_run_id, p_task_id;
end if;
if v_state <> 'running' then
raise exception 'Run "%" is not currently running in queue "%"', p_run_id, p_queue_name;
end if;
-- Update run to completed
execute format(
'update durable.%I
set state = ''completed'',
completed_at = $2,
result = $3
where run_id = $1',
'r_' || p_queue_name
) using p_run_id, v_now, p_state;
-- Update task to completed
execute format(
'update durable.%I
set state = ''completed'',
completed_payload = $2,
last_attempt_run = $3
where task_id = $1',
't_' || p_queue_name
) using p_task_id, p_state, p_run_id;
-- Cleanup: delete waiters and emit completion event for parent
perform durable.cleanup_task_terminal(
p_queue_name,
p_task_id,
'completed',
jsonb_build_object('result', p_state),
false -- don't cascade cancel children for completed tasks
);
end;
$$;
create function durable.sleep_for(
p_queue_name text,
p_task_id uuid,
p_run_id uuid,
p_checkpoint_name text,
p_duration_ms bigint
)
returns boolean -- true = suspended, false = wake time already passed
language plpgsql
as $$
declare
v_wake_at timestamptz;
v_existing_state jsonb;
v_now timestamptz := durable.current_time();
v_run_task_id uuid;
v_run_state text;
v_task_state text;
begin
-- Lock task first to keep a consistent task -> run lock order.
execute format(
'select state from durable.%I where task_id = $1 for update',
't_' || p_queue_name
) into v_task_state using p_task_id;
if v_task_state is null then
raise exception 'Task "%" not found in queue "%"', p_task_id, p_queue_name;
end if;
if v_task_state = 'cancelled' then
raise exception sqlstate 'AB001' using message = 'Task has been cancelled';
end if;
-- Lock run after task
execute format(
'select task_id, state from durable.%I where run_id = $1 for update',
'r_' || p_queue_name
) into v_run_task_id, v_run_state using p_run_id;
if v_run_task_id is null then
raise exception 'Run "%" not found in queue "%"', p_run_id, p_queue_name;
end if;
if v_run_task_id <> p_task_id then
raise exception 'Run "%" does not belong to task "%"', p_run_id, p_task_id;
end if;
if v_run_state <> 'running' then
raise exception 'Run "%" is not currently running in queue "%"', p_run_id, p_queue_name;
end if;
-- Check for existing checkpoint
execute format(
'select state from durable.%I where task_id = $1 and checkpoint_name = $2',
'c_' || p_queue_name
) into v_existing_state using p_task_id, p_checkpoint_name;
if v_existing_state is not null then
v_wake_at := (v_existing_state #>> '{}')::timestamptz;
else
-- Compute wake time and store checkpoint (first-writer-wins)
v_wake_at := v_now + (p_duration_ms || ' milliseconds')::interval;
execute format(
'insert into durable.%I (task_id, checkpoint_name, state, owner_run_id, updated_at)
values ($1, $2, $3, $4, $5)
on conflict (task_id, checkpoint_name) do nothing',
'c_' || p_queue_name
) using p_task_id, p_checkpoint_name, to_jsonb(v_wake_at::text), p_run_id, v_now;
-- Re-read in case we lost the race (first-writer-wins)
execute format(
'select state from durable.%I where task_id = $1 and checkpoint_name = $2',
'c_' || p_queue_name
) into v_existing_state using p_task_id, p_checkpoint_name;
v_wake_at := (v_existing_state #>> '{}')::timestamptz;
end if;
-- If wake time passed, return false (no suspend needed)
if v_now >= v_wake_at then
return false;
end if;
-- Schedule the run to wake at v_wake_at
execute format(
'update durable.%I
set state = ''sleeping'',
claimed_by = null,
claim_expires_at = null,
available_at = $2,
wake_event = null
where run_id = $1',
'r_' || p_queue_name
) using p_run_id, v_wake_at;
execute format(
'update durable.%I
set state = ''sleeping''
where task_id = $1',
't_' || p_queue_name
) using p_task_id;
return true;
end;
$$;
-- Consolidates cleanup logic for a task that has reached a terminal state.
-- This function:
-- 1. Deletes wait registrations for the task
-- 2. Emits a completion event for the parent (if this is a subtask)
-- 3. Optionally cascades cancellation to children
--
-- Called by: complete_run, fail_run, cancel_task, cascade_cancel_children, claim_task
create function durable.cleanup_task_terminal (
p_queue_name text,
p_task_id uuid,
p_status text, -- 'completed', 'failed', 'cancelled'
p_payload jsonb default null,
p_cascade_children boolean default false
)
returns void
language plpgsql
as $$
declare
v_parent_task_id uuid;
begin
-- Get parent_task_id for event emission
execute format(
'select parent_task_id from durable.%I where task_id = $1',
't_' || p_queue_name
) into v_parent_task_id using p_task_id;
-- Delete wait registrations for this task
execute format(
'delete from durable.%I where task_id = $1',
'w_' || p_queue_name
) using p_task_id;
-- Emit completion event for parent (if subtask)
if v_parent_task_id is not null then
perform durable.emit_event(
p_queue_name,
'$child:' || p_task_id::text,
jsonb_build_object(
'inner', jsonb_build_object('status', p_status) || coalesce(p_payload, '{}'::jsonb),
'metadata', '{}'::jsonb
)
);
end if;
-- Cascade cancel children if requested
if p_cascade_children then
perform durable.cascade_cancel_children(p_queue_name, p_task_id);
end if;
end;
$$;
-- Recursively cancels all children of a parent task.
-- Used when a parent task fails or is cancelled to cascade the cancellation.
create function durable.cascade_cancel_children (
p_queue_name text,
p_parent_task_id uuid
)
returns void
language plpgsql
as $$
declare
v_child_id uuid;
v_now timestamptz := durable.current_time();
begin
-- Find all children of this parent that are not in terminal state
for v_child_id in
execute format(
'select task_id
from durable.%I
where parent_task_id = $1
and state not in (''completed'', ''failed'', ''cancelled'')
for update',
't_' || p_queue_name
)
using p_parent_task_id
loop
-- Cancel the child task
execute format(
'update durable.%I
set state = ''cancelled'',
cancelled_at = coalesce(cancelled_at, $2)
where task_id = $1',
't_' || p_queue_name
) using v_child_id, v_now;
-- Cancel all runs of this child
execute format(
'update durable.%I
set state = ''cancelled'',
claimed_by = null,
claim_expires_at = null
where task_id = $1
and state not in (''completed'', ''failed'', ''cancelled'')',
'r_' || p_queue_name
) using v_child_id;
-- Cleanup: delete waiters, emit event, and recursively cascade to grandchildren
perform durable.cleanup_task_terminal(p_queue_name, v_child_id, 'cancelled', null, true);
end loop;
end;
$$;
--- Marks a run as failed.
--- If p_force_fail is true, then the retry policy and `p_retry_at` are ignored,
--- and the task is immediately failed (as though it had reached the max retries)
create function durable.fail_run (
p_queue_name text,
p_task_id uuid,
p_run_id uuid,
p_reason jsonb,
p_retry_at timestamptz default null,
p_force_fail boolean default false
)
returns void
language plpgsql
as $$
declare
v_run_task_id uuid;
v_attempt integer;
v_retry_strategy jsonb;
v_max_attempts integer;
v_now timestamptz := durable.current_time();
v_next_attempt integer;
v_delay_seconds double precision := 0;
v_next_available timestamptz;
v_retry_kind text;
v_base double precision;
v_factor double precision;
v_max_seconds double precision;
v_first_started timestamptz;
v_cancellation jsonb;
v_max_duration bigint;
v_task_state text;
v_task_cancel boolean := false;
v_new_run_id uuid;
v_task_state_after text;
v_recorded_attempt integer;
v_last_attempt_run uuid := p_run_id;
v_cancelled_at timestamptz := null;
begin
-- Lock task first to keep a consistent task -> run lock order.
execute format(
'select retry_strategy, max_attempts, first_started_at, cancellation, state
from durable.%I
where task_id = $1
for update',
't_' || p_queue_name
)
into v_retry_strategy, v_max_attempts, v_first_started, v_cancellation, v_task_state
using p_task_id;
if v_task_state is null then
raise exception 'Task "%" not found in queue "%"', p_task_id, p_queue_name;
end if;
-- Lock run after task and ensure it's still eligible
execute format(
'select task_id, attempt
from durable.%I
where run_id = $1
and state in (''running'', ''sleeping'')
for update',
'r_' || p_queue_name
)
into v_run_task_id, v_attempt
using p_run_id;
if v_run_task_id is null then
raise exception 'Run "%" cannot be failed in queue "%"', p_run_id, p_queue_name;
end if;