a3s-flow 0.10.15

Durable workflow engine and Rust SDK for A3S
Documentation
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
use a3s_orm::Migration;

#[cfg(any(feature = "postgres", feature = "sqlite"))]
mod scheduled_wakeups;
#[cfg(feature = "postgres")]
use scheduled_wakeups::POSTGRES_SCHEDULED_WAKEUPS_SQL;
#[cfg(feature = "sqlite")]
use scheduled_wakeups::SQLITE_SCHEDULED_WAKEUPS_SQL;

const EVENTS_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS flow_events (
    run_id TEXT NOT NULL,
    sequence BIGINT NOT NULL CHECK (sequence >= 1),
    event_id TEXT NOT NULL,
    timestamp TEXT NOT NULL,
    event_json TEXT NOT NULL,
    PRIMARY KEY (run_id, sequence)
);

CREATE INDEX IF NOT EXISTS idx_flow_events_run_id_sequence
ON flow_events (run_id, sequence);
"#;

#[cfg(feature = "sqlite")]
const SQLITE_ACTIVE_HOOKS_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS flow_active_hooks (
    run_id TEXT NOT NULL,
    hook_id TEXT NOT NULL,
    token TEXT NOT NULL,
    metadata_json TEXT NOT NULL,
    created_sequence BIGINT NOT NULL CHECK (created_sequence >= 1),
    PRIMARY KEY (token),
    UNIQUE (run_id, hook_id)
);

INSERT INTO flow_active_hooks (
    run_id,
    hook_id,
    token,
    metadata_json,
    created_sequence
)
SELECT
    created.run_id,
    json_extract(created.event_json, '$.hook_id'),
    json_extract(created.event_json, '$.token'),
    json_quote(json_extract(created.event_json, '$.metadata')),
    created.sequence
FROM flow_events AS created
WHERE json_extract(created.event_json, '$.type') = 'hook_created'
  AND NOT EXISTS (
      SELECT 1
      FROM flow_events AS later
      WHERE later.run_id = created.run_id
        AND later.sequence > created.sequence
        AND (
            (
                json_extract(later.event_json, '$.type') IN (
                    'hook_received',
                    'hook_disposed'
                )
                AND json_extract(later.event_json, '$.hook_id') =
                    json_extract(created.event_json, '$.hook_id')
            )
            OR json_extract(later.event_json, '$.type') IN (
                'run_cancellation_requested',
                'run_completed',
                'run_failed',
                'run_cancelled',
                'run_timed_out',
                'run_retry_exhausted',
                'run_host_shutdown'
            )
        )
  )
ORDER BY created.run_id, created.sequence;

CREATE TRIGGER IF NOT EXISTS flow_active_hooks_after_hook_created
AFTER INSERT ON flow_events
WHEN json_extract(NEW.event_json, '$.type') = 'hook_created'
BEGIN
    SELECT RAISE(ABORT, 'flow active hook token conflict')
    WHERE EXISTS (
        SELECT 1
        FROM flow_active_hooks
        WHERE token = json_extract(NEW.event_json, '$.token')
          AND (
              run_id <> NEW.run_id
              OR hook_id <> json_extract(NEW.event_json, '$.hook_id')
          )
    );

    SELECT RAISE(ABORT, 'flow active hook identity conflict')
    WHERE EXISTS (
        SELECT 1
        FROM flow_active_hooks
        WHERE run_id = NEW.run_id
          AND hook_id = json_extract(NEW.event_json, '$.hook_id')
          AND token <> json_extract(NEW.event_json, '$.token')
    );

    INSERT OR IGNORE INTO flow_active_hooks (
        run_id,
        hook_id,
        token,
        metadata_json,
        created_sequence
    ) VALUES (
        NEW.run_id,
        json_extract(NEW.event_json, '$.hook_id'),
        json_extract(NEW.event_json, '$.token'),
        json_quote(json_extract(NEW.event_json, '$.metadata')),
        NEW.sequence
    );
END;

CREATE TRIGGER IF NOT EXISTS flow_active_hooks_after_hook_closed
AFTER INSERT ON flow_events
WHEN json_extract(NEW.event_json, '$.type') IN ('hook_received', 'hook_disposed')
BEGIN
    DELETE FROM flow_active_hooks
    WHERE run_id = NEW.run_id
      AND hook_id = json_extract(NEW.event_json, '$.hook_id');
END;

CREATE TRIGGER IF NOT EXISTS flow_active_hooks_after_run_closed
AFTER INSERT ON flow_events
WHEN json_extract(NEW.event_json, '$.type') IN (
    'run_cancellation_requested',
    'run_completed',
    'run_failed',
    'run_cancelled',
    'run_timed_out',
    'run_retry_exhausted',
    'run_host_shutdown'
)
BEGIN
    DELETE FROM flow_active_hooks WHERE run_id = NEW.run_id;
END;
"#;

#[cfg(feature = "postgres")]
const POSTGRES_ACTIVE_HOOKS_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS flow_active_hooks (
    run_id TEXT NOT NULL,
    hook_id TEXT NOT NULL,
    token TEXT NOT NULL,
    metadata_json TEXT NOT NULL,
    created_sequence BIGINT NOT NULL CHECK (created_sequence >= 1),
    PRIMARY KEY (run_id, hook_id)
);

CREATE INDEX IF NOT EXISTS idx_flow_active_hooks_token
ON flow_active_hooks USING HASH (token);

INSERT INTO flow_active_hooks (
    run_id,
    hook_id,
    token,
    metadata_json,
    created_sequence
)
SELECT
    created.run_id,
    created.event_json::jsonb ->> 'hook_id',
    created.event_json::jsonb ->> 'token',
    (created.event_json::jsonb -> 'metadata')::text,
    created.sequence
FROM flow_events AS created
WHERE created.event_json::jsonb ->> 'type' = 'hook_created'
  AND NOT EXISTS (
      SELECT 1
      FROM flow_events AS later
      WHERE later.run_id = created.run_id
        AND later.sequence > created.sequence
        AND (
            (
                later.event_json::jsonb ->> 'type' IN (
                    'hook_received',
                    'hook_disposed'
                )
                AND later.event_json::jsonb ->> 'hook_id' =
                    created.event_json::jsonb ->> 'hook_id'
            )
            OR later.event_json::jsonb ->> 'type' IN (
                'run_cancellation_requested',
                'run_completed',
                'run_failed',
                'run_cancelled',
                'run_timed_out',
                'run_retry_exhausted',
                'run_host_shutdown'
            )
        )
  )
ORDER BY created.run_id, created.sequence;

DO $$
BEGIN
    IF EXISTS (
        SELECT token
        FROM flow_active_hooks
        GROUP BY token
        HAVING COUNT(*) > 1
    ) THEN
        RAISE EXCEPTION 'existing Flow history contains duplicate active hook tokens'
            USING ERRCODE = '23505';
    END IF;
END;
$$;

CREATE OR REPLACE FUNCTION a3s_flow_project_active_hook()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
    event_type TEXT := NEW.event_json::jsonb ->> 'type';
    event_hook_id TEXT;
    event_token TEXT;
    existing_run_id TEXT;
    existing_hook_id TEXT;
BEGIN
    IF event_type = 'hook_created' THEN
        event_hook_id := NEW.event_json::jsonb ->> 'hook_id';
        event_token := NEW.event_json::jsonb ->> 'token';

        PERFORM pg_advisory_xact_lock(hashtext(event_token), 2);

        SELECT run_id, hook_id
        INTO existing_run_id, existing_hook_id
        FROM flow_active_hooks
        WHERE token = event_token
        ORDER BY run_id, hook_id
        LIMIT 1;

        IF FOUND AND (
            existing_run_id <> NEW.run_id
            OR existing_hook_id <> event_hook_id
        ) THEN
            RAISE EXCEPTION 'flow active hook token conflict'
                USING ERRCODE = '23505';
        END IF;

        INSERT INTO flow_active_hooks (
            run_id,
            hook_id,
            token,
            metadata_json,
            created_sequence
        ) VALUES (
            NEW.run_id,
            event_hook_id,
            event_token,
            (NEW.event_json::jsonb -> 'metadata')::text,
            NEW.sequence
        ) ON CONFLICT (run_id, hook_id) DO UPDATE
          SET token = EXCLUDED.token
        WHERE flow_active_hooks.token = EXCLUDED.token
        RETURNING flow_active_hooks.run_id INTO existing_run_id;

        IF NOT FOUND THEN
            RAISE EXCEPTION 'flow active hook identity conflict'
                USING ERRCODE = '23505';
        END IF;
    ELSIF event_type IN ('hook_received', 'hook_disposed') THEN
        DELETE FROM flow_active_hooks
        WHERE run_id = NEW.run_id
          AND hook_id = NEW.event_json::jsonb ->> 'hook_id';
    ELSIF event_type IN (
        'run_cancellation_requested',
        'run_completed',
        'run_failed',
        'run_cancelled',
        'run_timed_out',
        'run_retry_exhausted',
        'run_host_shutdown'
    ) THEN
        DELETE FROM flow_active_hooks WHERE run_id = NEW.run_id;
    END IF;

    RETURN NEW;
END;
$$;

DROP TRIGGER IF EXISTS flow_active_hooks_after_event ON flow_events;

CREATE TRIGGER flow_active_hooks_after_event
AFTER INSERT ON flow_events
FOR EACH ROW
EXECUTE FUNCTION a3s_flow_project_active_hook();
"#;

#[cfg(feature = "postgres")]
const POSTGRES_TASKS_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS flow_tasks (
    queue_name TEXT NOT NULL,
    task_id TEXT NOT NULL,
    task_json TEXT NOT NULL,
    status TEXT NOT NULL CHECK (status IN ('pending', 'inflight')),
    enqueued_at_nanos BIGINT NOT NULL,
    leased_at_nanos BIGINT,
    lease_id TEXT,
    updated_at_nanos BIGINT NOT NULL,
    PRIMARY KEY (queue_name, task_id)
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_flow_tasks_queue_lease
ON flow_tasks (queue_name, lease_id)
WHERE lease_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_flow_tasks_pending_order
ON flow_tasks (queue_name, status, enqueued_at_nanos, task_id);

CREATE TABLE IF NOT EXISTS flow_task_dead_letters (
    queue_name TEXT NOT NULL,
    dead_letter_id TEXT NOT NULL,
    lease_id TEXT NOT NULL,
    task_json TEXT NOT NULL,
    reason TEXT NOT NULL,
    dead_lettered_at_nanos BIGINT NOT NULL,
    leased_at_nanos BIGINT,
    PRIMARY KEY (queue_name, dead_letter_id)
);

CREATE INDEX IF NOT EXISTS idx_flow_task_dead_letters_queue_time
ON flow_task_dead_letters (queue_name, dead_lettered_at_nanos, dead_letter_id);
"#;

#[cfg(any(feature = "postgres", feature = "sqlite"))]
const RETENTION_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS flow_history_holds (
    run_id TEXT NOT NULL,
    hold_id TEXT NOT NULL,
    reason TEXT NOT NULL,
    created_at TEXT NOT NULL,
    PRIMARY KEY (run_id, hold_id)
);

CREATE TABLE IF NOT EXISTS flow_history_tombstones (
    run_id TEXT PRIMARY KEY,
    deleted_at TEXT NOT NULL,
    terminal_sequence BIGINT NOT NULL CHECK (terminal_sequence >= 1),
    terminal_event_id TEXT NOT NULL,
    terminal_event_key TEXT NOT NULL,
    history_sha256 TEXT NOT NULL
);
"#;

#[cfg(feature = "sqlite")]
pub(crate) fn sqlite_migrations() -> Vec<Migration> {
    vec![
        Migration::new(
            "a3s-flow-0001-events",
            "create Flow event history",
            EVENTS_SQL,
        ),
        Migration::new(
            "a3s-flow-0002-retention",
            "create Flow history retention guards and tombstones",
            RETENTION_SQL,
        ),
        Migration::new(
            "a3s-flow-0003-active-hooks",
            "create the indexed active hook projection",
            SQLITE_ACTIVE_HOOKS_SQL,
        ),
        Migration::new(
            "a3s-flow-0004-scheduled-wakeups",
            "create the indexed scheduled wakeup projection",
            SQLITE_SCHEDULED_WAKEUPS_SQL,
        ),
    ]
}

#[cfg(feature = "postgres")]
pub(crate) fn postgres_migrations() -> Vec<Migration> {
    vec![
        Migration::new(
            "a3s-flow-0001-events",
            "create Flow event history",
            EVENTS_SQL,
        ),
        Migration::new(
            "a3s-flow-0002-tasks",
            "create Flow task dispatch tables",
            POSTGRES_TASKS_SQL,
        ),
        Migration::new(
            "a3s-flow-0003-retention",
            "create Flow history retention guards and tombstones",
            RETENTION_SQL,
        ),
        Migration::new(
            "a3s-flow-0004-active-hooks",
            "create the indexed active hook projection",
            POSTGRES_ACTIVE_HOOKS_SQL,
        ),
        Migration::new(
            "a3s-flow-0005-scheduled-wakeups",
            "reconcile active hooks and create the scheduled wakeup projection",
            POSTGRES_SCHEDULED_WAKEUPS_SQL,
        ),
    ]
}