forked from earendil-works/absurd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabsurd.sql
More file actions
3086 lines (2792 loc) · 88.7 KB
/
absurd.sql
File metadata and controls
3086 lines (2792 loc) · 88.7 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
-- Absurd installs a Postgres-native durable workflow system that can be dropped
-- into an existing database.
--
-- It bootstraps the `absurd` 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
-- * `i_` for idempotency keys (partitioned queues only)
--
-- `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`, `schedule_run`, 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 use first-write-wins
-- semantics: the first emission per name is cached, later emits are ignored.
create extension if not exists "uuid-ossp";
create schema if not exists absurd;
-- Returns either the actual current timestamp or a fake one if
-- the session sets `absurd.fake_now`. This lets tests control time.
create function absurd.current_time ()
returns timestamptz
language plpgsql
volatile
as $$
declare
v_fake text;
begin
v_fake := current_setting('absurd.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 absurd.queues (
queue_name text primary key,
created_at timestamptz not null default absurd.current_time(),
storage_mode text not null default 'unpartitioned'
check (storage_mode in ('unpartitioned', 'partitioned')),
default_partition text not null default 'enabled'
check (default_partition in ('enabled', 'disabled')),
partition_lookahead interval not null default interval '28 days'
check (partition_lookahead >= interval '0 seconds'),
partition_lookback interval not null default interval '1 day'
check (partition_lookback >= interval '0 seconds'),
cleanup_ttl interval not null default interval '30 days'
check (cleanup_ttl >= interval '0 seconds'),
cleanup_limit integer not null default 1000
check (cleanup_limit >= 1),
detach_mode text not null default 'none'
check (detach_mode in ('none', 'empty')),
detach_min_age interval not null default interval '30 days'
check (detach_min_age >= interval '0 seconds')
);
-- Returns the Absurd schema release version baked into this SQL file.
-- During development this is usually "main" and release automation replaces
-- it with the actual tag version.
create or replace function absurd.get_schema_version ()
returns text
language sql
as $$
select 'main'::text;
$$;
-- Queue names are used in generated table/index identifiers.
-- We intentionally cap UTF-8 byte length so generated explicit index names
-- (for instance r_<queue>_sai) stay within PostgreSQL's 63-byte identifier
-- limit. Character set is otherwise delegated to PostgreSQL quoted-ident rules.
create function absurd.validate_queue_name (p_queue_name text)
returns text
language plpgsql
as $$
begin
if p_queue_name is null or p_queue_name = '' then
raise exception 'Queue name must be provided';
end if;
if octet_length(p_queue_name) > 57 then
raise exception 'Queue name "%" is too long (max 57 bytes).', p_queue_name;
end if;
return p_queue_name;
end;
$$;
create function absurd.ensure_queue_tables (p_queue_name text)
returns void
language plpgsql
as $$
declare
v_storage_mode text := 'unpartitioned';
v_t_suffix text;
v_r_suffix text;
v_c_suffix text;
v_w_suffix text;
v_t_idempotency_def text;
begin
perform absurd.validate_queue_name(p_queue_name);
select storage_mode into v_storage_mode
from absurd.queues
where queue_name = p_queue_name;
v_storage_mode := coalesce(v_storage_mode, 'unpartitioned');
if v_storage_mode not in ('unpartitioned', 'partitioned') then
raise exception 'Unsupported queue storage mode "%"', v_storage_mode;
end if;
if v_storage_mode = 'partitioned' then
v_t_suffix := 'partition by range (task_id)';
v_r_suffix := 'partition by range (run_id)';
v_c_suffix := 'partition by range (task_id)';
v_w_suffix := 'partition by range (run_id)';
v_t_idempotency_def := 'idempotency_key text';
else
v_t_suffix := 'with (fillfactor=70)';
v_r_suffix := 'with (fillfactor=70)';
v_c_suffix := 'with (fillfactor=70)';
v_w_suffix := '';
v_t_idempotency_def := 'idempotency_key text unique';
end if;
execute format(
'create table if not exists absurd.%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,
enqueue_at timestamptz not null default absurd.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,
%s
) %s',
't_' || p_queue_name,
v_t_idempotency_def,
v_t_suffix
);
execute format(
'create table if not exists absurd.%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 absurd.current_time()
) %s',
'r_' || p_queue_name,
v_r_suffix
);
execute format(
'create table if not exists absurd.%I (
task_id uuid not null,
checkpoint_name text not null,
state jsonb,
status text not null default ''committed'',
owner_run_id uuid,
updated_at timestamptz not null default absurd.current_time(),
primary key (task_id, checkpoint_name)
) %s',
'c_' || p_queue_name,
v_c_suffix
);
execute format(
'create table if not exists absurd.%I (
event_name text primary key,
payload jsonb,
emitted_at timestamptz not null default absurd.current_time()
)',
'e_' || p_queue_name
);
execute format(
'create table if not exists absurd.%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 absurd.current_time(),
primary key (run_id, step_name)
) %s',
'w_' || p_queue_name,
v_w_suffix
);
if v_storage_mode = 'partitioned' then
execute format(
'create table if not exists absurd.%I (
idempotency_key text primary key,
task_id uuid not null
)',
'i_' || p_queue_name
);
end if;
execute format(
'create index if not exists %I on absurd.%I (state, available_at)',
('r_' || p_queue_name) || '_sai',
'r_' || p_queue_name
);
execute format(
'create index if not exists %I on absurd.%I (task_id)',
('r_' || p_queue_name) || '_ti',
'r_' || p_queue_name
);
execute format(
'create index if not exists %I on absurd.%I (claim_expires_at)
where state = ''running''
and claim_expires_at is not null',
('r_' || p_queue_name) || '_cei',
'r_' || p_queue_name
);
execute format(
'create index if not exists %I on absurd.%I (event_name)',
('w_' || p_queue_name) || '_eni',
'w_' || p_queue_name
);
execute format(
'create index if not exists %I on absurd.%I (task_id)',
('w_' || p_queue_name) || '_ti',
'w_' || p_queue_name
);
execute format(
'create index if not exists %I on absurd.%I (emitted_at)',
('e_' || p_queue_name) || '_eai',
'e_' || p_queue_name
);
if v_storage_mode = 'partitioned' then
execute format(
'create index if not exists %I on absurd.%I (task_id)',
('i_' || p_queue_name) || '_ti',
'i_' || p_queue_name
);
perform absurd.ensure_partitions(p_queue_name);
end if;
end;
$$;
-- Creates the queue with the given name and storage mode.
--
-- Existing queues are idempotent as long as the requested mode matches.
create function absurd.create_queue (
p_queue_name text,
p_storage_mode text
)
returns void
language plpgsql
as $$
declare
v_storage_mode text;
v_existing_mode text;
begin
p_queue_name := absurd.validate_queue_name(p_queue_name);
v_storage_mode := lower(trim(coalesce(p_storage_mode, '')));
if v_storage_mode not in ('unpartitioned', 'partitioned') then
raise exception 'Unsupported queue storage mode "%"', p_storage_mode;
end if;
insert into absurd.queues (queue_name, storage_mode)
values (p_queue_name, v_storage_mode)
on conflict (queue_name) do nothing;
select storage_mode into v_existing_mode
from absurd.queues
where queue_name = p_queue_name;
if v_existing_mode is null then
raise exception 'Queue "%" was not found after create attempt', p_queue_name;
end if;
if v_existing_mode <> v_storage_mode then
raise exception 'Queue "%" already exists with storage mode "%"', p_queue_name, v_existing_mode;
end if;
perform absurd.ensure_queue_tables(p_queue_name);
end;
$$;
-- Creates an unpartitioned queue (backward-compatible API).
create or replace function absurd.create_queue (p_queue_name text)
returns void
language plpgsql
as $$
begin
perform absurd.create_queue(p_queue_name, 'unpartitioned');
end;
$$;
-- Drop a queue if it exists.
-- We intentionally don't validate the provided name here so legacy queues
-- created under older naming rules can still be removed.
create function absurd.drop_queue (p_queue_name text)
returns void
language plpgsql
as $$
declare
v_existing_queue text;
begin
select queue_name into v_existing_queue
from absurd.queues
where queue_name = p_queue_name;
if v_existing_queue is null then
return;
end if;
-- Remove queue-scoped maintenance jobs only when pg_cron is available.
if to_regclass('cron.job') is not null and exists (
select 1
from pg_proc p
join pg_namespace n on n.oid = p.pronamespace
where n.nspname = 'cron'
and p.proname = 'unschedule'
) then
perform absurd.disable_cron(p_queue_name);
end if;
execute format('drop table if exists absurd.%I cascade', 'i_' || p_queue_name);
execute format('drop table if exists absurd.%I cascade', 'w_' || p_queue_name);
execute format('drop table if exists absurd.%I cascade', 'e_' || p_queue_name);
execute format('drop table if exists absurd.%I cascade', 'c_' || p_queue_name);
execute format('drop table if exists absurd.%I cascade', 'r_' || p_queue_name);
execute format('drop table if exists absurd.%I cascade', 't_' || p_queue_name);
delete from absurd.queues where queue_name = p_queue_name;
end;
$$;
-- Lists all queues that currently exist.
create function absurd.list_queues ()
returns table (queue_name text)
language sql
as $$
select queue_name from absurd.queues order by queue_name;
$$;
-- Returns queue maintenance policy metadata.
create function absurd.get_queue_policy (
p_queue_name text
)
returns table (
queue_name text,
storage_mode text,
default_partition text,
partition_lookahead interval,
partition_lookback interval,
cleanup_ttl interval,
cleanup_limit integer,
detach_mode text,
detach_min_age interval
)
language sql
as $$
select
q.queue_name,
q.storage_mode,
q.default_partition,
q.partition_lookahead,
q.partition_lookback,
q.cleanup_ttl,
q.cleanup_limit,
q.detach_mode,
q.detach_min_age
from absurd.queues q
where q.queue_name = p_queue_name;
$$;
-- Updates queue maintenance policy metadata.
--
-- p_policy accepts optional keys:
-- * partition_lookahead (interval text)
-- * partition_lookback (interval text)
-- * cleanup_ttl (interval text, >= 0)
-- * cleanup_limit (integer >= 1)
-- * detach_mode ('none' | 'empty')
-- * detach_min_age (interval text)
-- * default_partition ('enabled' | 'disabled')
create function absurd.set_queue_policy (
p_queue_name text,
p_policy jsonb
)
returns void
language plpgsql
as $$
declare
v_policy jsonb := coalesce(p_policy, '{}'::jsonb);
v_unknown_key text;
v_exists boolean := false;
v_storage_mode text;
v_default_partition text;
v_previous_default_partition text;
v_parent_prefix text;
v_parent_table text;
v_default_table text;
v_default_attached boolean;
v_default_has_rows boolean;
v_partition_lookahead interval;
v_partition_lookback interval;
v_cleanup_ttl interval;
v_cleanup_limit integer;
v_detach_mode text;
v_detach_min_age interval;
begin
p_queue_name := absurd.validate_queue_name(p_queue_name);
if jsonb_typeof(v_policy) <> 'object' then
raise exception 'Queue policy must be a JSON object';
end if;
select k.key
into v_unknown_key
from jsonb_object_keys(v_policy) as k(key)
where k.key not in (
'partition_lookahead',
'partition_lookback',
'cleanup_ttl',
'cleanup_limit',
'detach_mode',
'detach_min_age',
'default_partition'
)
limit 1;
if v_unknown_key is not null then
raise exception 'Unsupported queue policy key "%"', v_unknown_key;
end if;
select exists (
select 1
from absurd.queues
where queue_name = p_queue_name
)
into v_exists;
if not v_exists then
raise exception 'Queue "%" does not exist', p_queue_name;
end if;
select
storage_mode,
default_partition,
partition_lookahead,
partition_lookback,
cleanup_ttl,
cleanup_limit,
detach_mode,
detach_min_age
into
v_storage_mode,
v_default_partition,
v_partition_lookahead,
v_partition_lookback,
v_cleanup_ttl,
v_cleanup_limit,
v_detach_mode,
v_detach_min_age
from absurd.queues
where queue_name = p_queue_name
for update;
if v_policy ? 'partition_lookahead' then
v_partition_lookahead := (v_policy->>'partition_lookahead')::interval;
end if;
if v_policy ? 'partition_lookback' then
v_partition_lookback := (v_policy->>'partition_lookback')::interval;
end if;
if v_policy ? 'cleanup_ttl' then
v_cleanup_ttl := (v_policy->>'cleanup_ttl')::interval;
end if;
if v_policy ? 'cleanup_limit' then
v_cleanup_limit := (v_policy->>'cleanup_limit')::integer;
end if;
if v_policy ? 'detach_mode' then
v_detach_mode := lower(trim(coalesce(v_policy->>'detach_mode', '')));
end if;
if v_policy ? 'detach_min_age' then
v_detach_min_age := (v_policy->>'detach_min_age')::interval;
end if;
v_previous_default_partition := v_default_partition;
if v_policy ? 'default_partition' then
v_default_partition := lower(trim(coalesce(v_policy->>'default_partition', '')));
end if;
if v_partition_lookahead < interval '0 seconds' then
raise exception 'partition_lookahead must be non-negative';
end if;
if v_partition_lookback < interval '0 seconds' then
raise exception 'partition_lookback must be non-negative';
end if;
if v_cleanup_ttl < interval '0 seconds' then
raise exception 'cleanup_ttl must be non-negative';
end if;
if v_cleanup_limit < 1 then
raise exception 'cleanup_limit must be at least 1';
end if;
if v_detach_mode not in ('none', 'empty') then
raise exception 'Unsupported detach mode "%"', v_detach_mode;
end if;
if v_detach_min_age < interval '0 seconds' then
raise exception 'detach_min_age must be non-negative';
end if;
if v_default_partition not in ('enabled', 'disabled') then
raise exception 'Unsupported default_partition mode "%"', v_default_partition;
end if;
if v_storage_mode <> 'partitioned' and v_policy ? 'default_partition' then
raise exception 'default_partition policy is only supported for partitioned queues';
end if;
update absurd.queues
set default_partition = v_default_partition,
partition_lookahead = v_partition_lookahead,
partition_lookback = v_partition_lookback,
cleanup_ttl = v_cleanup_ttl,
cleanup_limit = v_cleanup_limit,
detach_mode = v_detach_mode,
detach_min_age = v_detach_min_age
where queue_name = p_queue_name;
if v_storage_mode = 'partitioned'
and v_previous_default_partition <> v_default_partition then
if v_default_partition = 'enabled' then
perform absurd.ensure_partitions(p_queue_name);
else
foreach v_parent_prefix in array array['t', 'r', 'c', 'w'] loop
v_parent_table := v_parent_prefix || '_' || p_queue_name;
v_default_table := v_parent_table || '_d';
select exists (
select 1
from pg_inherits inh
join pg_class parent on parent.oid = inh.inhparent
join pg_class child on child.oid = inh.inhrelid
join pg_namespace n on n.oid = parent.relnamespace
where n.nspname = 'absurd'
and parent.relname = v_parent_table
and child.relname = v_default_table
)
into v_default_attached;
if not coalesce(v_default_attached, false) then
continue;
end if;
-- Block out-of-window writes into the default partition while we
-- validate emptiness and detach/drop it.
execute format(
'lock table absurd.%I in access exclusive mode',
v_default_table
);
execute format(
'select exists (select 1 from absurd.%I limit 1)',
v_default_table
)
into v_default_has_rows;
if coalesce(v_default_has_rows, false) then
raise exception
'Cannot disable default_partition for queue "%": default partition "%" is not empty',
p_queue_name,
v_default_table;
end if;
execute format(
'alter table absurd.%I detach partition absurd.%I',
v_parent_table,
v_default_table
);
execute format('drop table if exists absurd.%I', v_default_table);
end loop;
end if;
end if;
end;
$$;
-- Returns the current state and terminal payload (if any) for a task.
--
-- Non-terminal states (pending/running/sleeping) return result/failure_reason
-- as NULL. Completed tasks expose completed_payload as result. Failed tasks
-- expose the last run failure_reason.
create function absurd.get_task_result (
p_queue_name text,
p_task_id uuid
)
returns table (
task_id uuid,
state text,
result jsonb,
failure_reason jsonb
)
language plpgsql
as $$
begin
p_queue_name := absurd.validate_queue_name(p_queue_name);
return query execute format(
'select t.task_id,
t.state,
case when t.state = ''completed'' then t.completed_payload else null end as result,
case when t.state = ''failed'' then r.failure_reason else null end as failure_reason
from absurd.%I t
left join absurd.%I r on r.run_id = t.last_attempt_run
where t.task_id = $1',
't_' || p_queue_name,
'r_' || p_queue_name
) using p_task_id;
end;
$$;
-- Spawns a given task in a queue.
--
-- If an idempotency_key is provided in p_options, the function will check if a task
-- with that key already exists. If so, it returns the existing task_id with run_id
-- and attempt set to NULL to signal "already exists". This is race-safe via
-- INSERT ... ON CONFLICT DO NOTHING.
create function absurd.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,
created boolean
)
language plpgsql
as $$
declare
v_task_id uuid := absurd.portable_uuidv7();
v_run_id uuid := absurd.portable_uuidv7();
v_attempt integer := 1;
v_headers jsonb;
v_retry_strategy jsonb;
v_max_attempts integer;
v_cancellation jsonb;
v_idempotency_key text;
v_existing_task_id uuid;
v_existing_run_id uuid;
v_existing_attempt integer;
v_row_count integer;
v_storage_mode text := 'unpartitioned';
v_task_inserted boolean := false;
v_now timestamptz := absurd.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';
v_idempotency_key := p_options->>'idempotency_key';
end if;
if v_idempotency_key is not null then
select storage_mode into v_storage_mode
from absurd.queues
where queue_name = p_queue_name;
v_storage_mode := coalesce(v_storage_mode, 'unpartitioned');
if v_storage_mode not in ('unpartitioned', 'partitioned') then
raise exception 'Unsupported queue storage mode "%"', v_storage_mode;
end if;
if v_storage_mode = 'partitioned' then
-- Reserve idempotency key via dedicated side table.
execute format(
'insert into absurd.%I (idempotency_key, task_id)
values ($1, $2)
on conflict (idempotency_key) do nothing',
'i_' || p_queue_name
)
using v_idempotency_key, v_task_id;
get diagnostics v_row_count = row_count;
if v_row_count = 0 then
execute format(
'select i.task_id, t.last_attempt_run, t.attempts
from absurd.%I i
join absurd.%I t on t.task_id = i.task_id
where i.idempotency_key = $1
for key share of i',
'i_' || p_queue_name,
't_' || p_queue_name
)
into v_existing_task_id, v_existing_run_id, v_existing_attempt
using v_idempotency_key;
if v_existing_task_id is null then
raise exception 'Idempotency key "%" in queue "%" was concurrently cleaned up', v_idempotency_key, p_queue_name
using errcode = '40001',
hint = 'Retry spawn_task with the same idempotency key.';
end if;
if v_existing_run_id is null then
raise exception 'Idempotency key "%" in queue "%" resolved to task "%" without a run', v_idempotency_key, p_queue_name, v_existing_task_id;
end if;
return query select v_existing_task_id, v_existing_run_id, v_existing_attempt, false;
return;
end if;
else
-- Unpartitioned queues keep the original unique(idempotency_key)
-- behavior directly on t_<queue>.
execute format(
'insert into absurd.%I (task_id, task_name, params, headers, retry_strategy, max_attempts, cancellation, enqueue_at, first_started_at, state, attempts, last_attempt_run, completed_payload, cancelled_at, idempotency_key)
values ($1, $2, $3, $4, $5, $6, $7, $8, null, ''pending'', $9, $10, null, null, $11)
on conflict (idempotency_key) do nothing',
't_' || p_queue_name
)
using v_task_id, p_task_name, v_params, v_headers, v_retry_strategy, v_max_attempts, v_cancellation, v_now, v_attempt, v_run_id, v_idempotency_key;
get diagnostics v_row_count = row_count;
if v_row_count = 0 then
execute format(
'select task_id, last_attempt_run, attempts
from absurd.%I
where idempotency_key = $1',
't_' || p_queue_name
)
into v_existing_task_id, v_existing_run_id, v_existing_attempt
using v_idempotency_key;
return query select v_existing_task_id, v_existing_run_id, v_existing_attempt, false;
return;
end if;
v_task_inserted := true;
end if;
end if;
if not v_task_inserted then
execute format(
'insert into absurd.%I (task_id, task_name, params, headers, retry_strategy, max_attempts, cancellation, enqueue_at, first_started_at, state, attempts, last_attempt_run, completed_payload, cancelled_at, idempotency_key)
values ($1, $2, $3, $4, $5, $6, $7, $8, null, ''pending'', $9, $10, null, null, $11)',
't_' || p_queue_name
)
using v_task_id, p_task_name, v_params, v_headers, v_retry_strategy, v_max_attempts, v_cancellation, v_now, v_attempt, v_run_id, v_idempotency_key;
end if;
execute format(
'insert into absurd.%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, true;
end;
$$;
-- Workers call this to reserve a task from a given queue
-- for a given reservation period in seconds.
create function absurd.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 := absurd.current_time();
v_claim_timeout integer := greatest(coalesce(p_claim_timeout, 30), 0);
v_worker_id text := coalesce(nullif(p_worker_id, ''), 'worker');
v_qty integer := greatest(coalesce(p_qty, 1), 1);
v_claim_until timestamptz := null;
v_sql text;
v_expired_run record;
v_cancel_candidate record;
v_expired_sweep_limit integer;
begin
if v_claim_timeout > 0 then
v_claim_until := v_now + make_interval(secs => v_claim_timeout);
end if;
-- Keep claim polling work bounded: process at most v_qty expired leases
-- per claim call.
v_expired_sweep_limit := greatest(v_qty, 1);
-- Apply cancellation rules before claiming.
--
-- Use cancel_task() so lock order stays consistent (runs first, task second)
-- with complete_run()/fail_run().
for v_cancel_candidate in
execute format(
'select task_id
from absurd.%I
where state in (''pending'', ''sleeping'', ''running'')
and (
(
(cancellation->>''max_delay'')::bigint is not null
and first_started_at is null
and extract(epoch from ($1 - enqueue_at)) >= (cancellation->>''max_delay'')::bigint
)
or
(
(cancellation->>''max_duration'')::bigint is not null
and first_started_at is not null
and extract(epoch from ($1 - first_started_at)) >= (cancellation->>''max_duration'')::bigint
)
)
order by task_id',
't_' || p_queue_name
)
using v_now
loop
perform absurd.cancel_task(p_queue_name, v_cancel_candidate.task_id);
end loop;
for v_expired_run in
execute format(
'select run_id,
claimed_by,
claim_expires_at,
attempt
from absurd.%I
where state = ''running''
and claim_expires_at is not null
and claim_expires_at <= $1
order by claim_expires_at, run_id
limit $2
for update skip locked',
'r_' || p_queue_name
)
using v_now, v_expired_sweep_limit
loop
perform absurd.fail_run(
p_queue_name,
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;
v_sql := format(
'with candidate as (
select r.run_id
from absurd.%1$I r
join absurd.%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
),
updated as (
update absurd.%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
),
task_upd as (
update absurd.%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
),
wait_cleanup as (
delete from absurd.%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 absurd.%1$I r on r.run_id = u.run_id
join absurd.%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;
$$;
-- Markes a run as completed
create function absurd.complete_run (
p_queue_name text,
p_run_id uuid,
p_state jsonb default null