@pgflow/core 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ -- drop function if exists pgflow.complete_task(uuid, text, int, jsonb);
2
+ create or replace function pgflow.complete_task(
3
+ run_id uuid,
4
+ step_slug text,
5
+ task_index int,
6
+ output jsonb
7
+ )
8
+ returns setof pgflow.step_tasks
9
+ language plpgsql
10
+ volatile
11
+ set search_path to ''
12
+ as $$
13
+ begin
14
+
15
+ WITH run_lock AS (
16
+ SELECT * FROM pgflow.runs
17
+ WHERE pgflow.runs.run_id = complete_task.run_id
18
+ FOR UPDATE
19
+ ),
20
+ step_lock AS (
21
+ SELECT * FROM pgflow.step_states
22
+ WHERE pgflow.step_states.run_id = complete_task.run_id
23
+ AND pgflow.step_states.step_slug = complete_task.step_slug
24
+ FOR UPDATE
25
+ ),
26
+ task AS (
27
+ UPDATE pgflow.step_tasks
28
+ SET
29
+ status = 'completed',
30
+ output = complete_task.output
31
+ WHERE pgflow.step_tasks.run_id = complete_task.run_id
32
+ AND pgflow.step_tasks.step_slug = complete_task.step_slug
33
+ AND pgflow.step_tasks.task_index = complete_task.task_index
34
+ RETURNING *
35
+ ),
36
+ step_state AS (
37
+ UPDATE pgflow.step_states
38
+ SET
39
+ status = CASE
40
+ WHEN pgflow.step_states.remaining_tasks = 1 THEN 'completed' -- Will be 0 after decrement
41
+ ELSE 'started'
42
+ END,
43
+ remaining_tasks = pgflow.step_states.remaining_tasks - 1
44
+ FROM task
45
+ WHERE pgflow.step_states.run_id = complete_task.run_id
46
+ AND pgflow.step_states.step_slug = complete_task.step_slug
47
+ RETURNING pgflow.step_states.*
48
+ ),
49
+ -- Find all dependent steps if the current step was completed
50
+ dependent_steps AS (
51
+ SELECT d.step_slug AS dependent_step_slug
52
+ FROM pgflow.deps d
53
+ JOIN step_state s ON s.status = 'completed' AND d.flow_slug = s.flow_slug
54
+ WHERE d.dep_slug = complete_task.step_slug
55
+ ORDER BY d.step_slug -- Ensure consistent ordering
56
+ ),
57
+ -- Lock dependent steps before updating
58
+ dependent_steps_lock AS (
59
+ SELECT * FROM pgflow.step_states
60
+ WHERE pgflow.step_states.run_id = complete_task.run_id
61
+ AND pgflow.step_states.step_slug IN (SELECT dependent_step_slug FROM dependent_steps)
62
+ FOR UPDATE
63
+ ),
64
+ -- Update all dependent steps
65
+ dependent_steps_update AS (
66
+ UPDATE pgflow.step_states
67
+ SET remaining_deps = pgflow.step_states.remaining_deps - 1
68
+ FROM dependent_steps
69
+ WHERE pgflow.step_states.run_id = complete_task.run_id
70
+ AND pgflow.step_states.step_slug = dependent_steps.dependent_step_slug
71
+ )
72
+ -- Only decrement remaining_steps, don't update status
73
+ UPDATE pgflow.runs
74
+ SET remaining_steps = pgflow.runs.remaining_steps - 1
75
+ FROM step_state
76
+ WHERE pgflow.runs.run_id = complete_task.run_id
77
+ AND step_state.status = 'completed';
78
+
79
+ PERFORM pgmq.archive(
80
+ queue_name => (SELECT run.flow_slug FROM pgflow.runs AS run WHERE run.run_id = complete_task.run_id),
81
+ msg_id => (SELECT message_id FROM pgflow.step_tasks AS step_task
82
+ WHERE step_task.run_id = complete_task.run_id
83
+ AND step_task.step_slug = complete_task.step_slug
84
+ AND step_task.task_index = complete_task.task_index)
85
+ );
86
+
87
+ PERFORM pgflow.start_ready_steps(complete_task.run_id);
88
+
89
+ PERFORM pgflow.maybe_complete_run(complete_task.run_id);
90
+
91
+ RETURN QUERY SELECT *
92
+ FROM pgflow.step_tasks AS step_task
93
+ WHERE step_task.run_id = complete_task.run_id
94
+ AND step_task.step_slug = complete_task.step_slug
95
+ AND step_task.task_index = complete_task.task_index;
96
+
97
+ end;
98
+ $$;
@@ -0,0 +1,11 @@
1
+ create or replace function pgflow.calculate_retry_delay(
2
+ base_delay numeric,
3
+ attempts_count int
4
+ )
5
+ returns int
6
+ language sql
7
+ immutable
8
+ parallel safe
9
+ as $$
10
+ select floor(base_delay * power(2, attempts_count))::int
11
+ $$;
@@ -0,0 +1,124 @@
1
+ create or replace function pgflow.fail_task(
2
+ run_id uuid,
3
+ step_slug text,
4
+ task_index int,
5
+ error_message text
6
+ )
7
+ returns setof pgflow.step_tasks
8
+ language plpgsql
9
+ volatile
10
+ set search_path to ''
11
+ as $$
12
+ begin
13
+
14
+ WITH run_lock AS (
15
+ SELECT * FROM pgflow.runs
16
+ WHERE pgflow.runs.run_id = fail_task.run_id
17
+ FOR UPDATE
18
+ ),
19
+ step_lock AS (
20
+ SELECT * FROM pgflow.step_states
21
+ WHERE pgflow.step_states.run_id = fail_task.run_id
22
+ AND pgflow.step_states.step_slug = fail_task.step_slug
23
+ FOR UPDATE
24
+ ),
25
+ flow_info AS (
26
+ SELECT r.flow_slug
27
+ FROM pgflow.runs r
28
+ WHERE r.run_id = fail_task.run_id
29
+ ),
30
+ config AS (
31
+ SELECT
32
+ COALESCE(s.opt_max_attempts, f.opt_max_attempts) AS opt_max_attempts,
33
+ COALESCE(s.opt_base_delay, f.opt_base_delay) AS opt_base_delay
34
+ FROM pgflow.steps s
35
+ JOIN pgflow.flows f ON f.flow_slug = s.flow_slug
36
+ JOIN flow_info fi ON fi.flow_slug = s.flow_slug
37
+ WHERE s.flow_slug = fi.flow_slug AND s.step_slug = fail_task.step_slug
38
+ ),
39
+
40
+ fail_or_retry_task as (
41
+ UPDATE pgflow.step_tasks as task
42
+ SET
43
+ status = CASE
44
+ WHEN task.attempts_count < (SELECT opt_max_attempts FROM config) THEN 'queued'
45
+ ELSE 'failed'
46
+ END,
47
+ error_message = fail_task.error_message
48
+ WHERE task.run_id = fail_task.run_id
49
+ AND task.step_slug = fail_task.step_slug
50
+ AND task.task_index = fail_task.task_index
51
+ AND task.status = 'queued'
52
+ RETURNING *
53
+ ),
54
+ maybe_fail_step AS (
55
+ UPDATE pgflow.step_states
56
+ SET
57
+ status = CASE
58
+ WHEN (select fail_or_retry_task.status from fail_or_retry_task) = 'failed' THEN 'failed'
59
+ ELSE pgflow.step_states.status
60
+ END
61
+ FROM fail_or_retry_task
62
+ WHERE pgflow.step_states.run_id = fail_task.run_id
63
+ AND pgflow.step_states.step_slug = fail_task.step_slug
64
+ RETURNING pgflow.step_states.*
65
+ )
66
+ UPDATE pgflow.runs
67
+ SET status = CASE
68
+ WHEN (select status from maybe_fail_step) = 'failed' THEN 'failed'
69
+ ELSE status
70
+ END
71
+ WHERE pgflow.runs.run_id = fail_task.run_id;
72
+
73
+ -- For queued tasks: delay the message for retry with exponential backoff
74
+ PERFORM (
75
+ WITH retry_config AS (
76
+ SELECT
77
+ COALESCE(s.opt_base_delay, f.opt_base_delay) AS base_delay
78
+ FROM pgflow.steps s
79
+ JOIN pgflow.flows f ON f.flow_slug = s.flow_slug
80
+ JOIN pgflow.runs r ON r.flow_slug = f.flow_slug
81
+ WHERE r.run_id = fail_task.run_id
82
+ AND s.step_slug = fail_task.step_slug
83
+ ),
84
+ queued_tasks AS (
85
+ SELECT
86
+ r.flow_slug,
87
+ st.message_id,
88
+ pgflow.calculate_retry_delay((SELECT base_delay FROM retry_config), st.attempts_count) AS calculated_delay
89
+ FROM pgflow.step_tasks st
90
+ JOIN pgflow.runs r ON st.run_id = r.run_id
91
+ WHERE st.run_id = fail_task.run_id
92
+ AND st.step_slug = fail_task.step_slug
93
+ AND st.task_index = fail_task.task_index
94
+ AND st.status = 'queued'
95
+ )
96
+ SELECT pgmq.set_vt(qt.flow_slug, qt.message_id, qt.calculated_delay)
97
+ FROM queued_tasks qt
98
+ WHERE EXISTS (SELECT 1 FROM queued_tasks)
99
+ );
100
+
101
+ -- For failed tasks: archive the message
102
+ PERFORM (
103
+ WITH failed_tasks AS (
104
+ SELECT r.flow_slug, st.message_id
105
+ FROM pgflow.step_tasks st
106
+ JOIN pgflow.runs r ON st.run_id = r.run_id
107
+ WHERE st.run_id = fail_task.run_id
108
+ AND st.step_slug = fail_task.step_slug
109
+ AND st.task_index = fail_task.task_index
110
+ AND st.status = 'failed'
111
+ )
112
+ SELECT pgmq.archive(ft.flow_slug, ft.message_id)
113
+ FROM failed_tasks ft
114
+ WHERE EXISTS (SELECT 1 FROM failed_tasks)
115
+ );
116
+
117
+ return query select *
118
+ from pgflow.step_tasks st
119
+ where st.run_id = fail_task.run_id
120
+ and st.step_slug = fail_task.step_slug
121
+ and st.task_index = fail_task.task_index;
122
+
123
+ end;
124
+ $$;
@@ -0,0 +1,86 @@
1
+ create extension if not exists pgmq version '1.4.4';
2
+
3
+ create schema if not exists edge_worker;
4
+
5
+ -------------------------------------------------------------------------------
6
+ -- Workers Table --------------------------------------------------------------
7
+ -------------------------------------------------------------------------------
8
+ create table if not exists edge_worker.workers (
9
+ worker_id uuid not null primary key,
10
+ queue_name text not null,
11
+ function_name text not null,
12
+ started_at timestamptz not null default now(),
13
+ stopped_at timestamptz,
14
+ last_heartbeat_at timestamptz not null default now()
15
+ );
16
+
17
+ --------------------------------------------------------------------------------
18
+ -- Read With Poll --------------------------------------------------------------
19
+ -- --
20
+ -- This is a backport of the pgmq.read_with_poll function from version 1.5.0 --
21
+ -- It is required because it fixes a bug with high CPU usage and Supabase --
22
+ -- is still using version 1.4.4. --
23
+ -- --
24
+ -- It is slightly modified (removed headers which are not available in 1.4.1) --
25
+ -- --
26
+ -- This will be removed once Supabase upgrades to 1.5.0 or higher. --
27
+ --------------------------------------------------------------------------------
28
+ create function edge_worker.read_with_poll(
29
+ queue_name text,
30
+ vt integer,
31
+ qty integer,
32
+ max_poll_seconds integer default 5,
33
+ poll_interval_ms integer default 100,
34
+ conditional jsonb default '{}'
35
+ )
36
+ returns setof pgmq.message_record as $$
37
+ DECLARE
38
+ r pgmq.message_record;
39
+ stop_at timestamp;
40
+ sql text;
41
+ qtable text := pgmq.format_table_name(queue_name, 'q');
42
+ BEGIN
43
+ stop_at := clock_timestamp() + make_interval(secs => max_poll_seconds);
44
+ LOOP
45
+ IF (SELECT clock_timestamp() >= stop_at) THEN
46
+ RETURN;
47
+ END IF;
48
+
49
+ sql := FORMAT(
50
+ $QUERY$
51
+ WITH cte AS
52
+ (
53
+ SELECT msg_id
54
+ FROM pgmq.%I
55
+ WHERE vt <= clock_timestamp() AND CASE
56
+ WHEN %L != '{}'::jsonb THEN (message @> %2$L)::integer
57
+ ELSE 1
58
+ END = 1
59
+ ORDER BY msg_id ASC
60
+ LIMIT $1
61
+ FOR UPDATE SKIP LOCKED
62
+ )
63
+ UPDATE pgmq.%I m
64
+ SET
65
+ vt = clock_timestamp() + %L,
66
+ read_ct = read_ct + 1
67
+ FROM cte
68
+ WHERE m.msg_id = cte.msg_id
69
+ RETURNING m.msg_id, m.read_ct, m.enqueued_at, m.vt, m.message;
70
+ $QUERY$,
71
+ qtable, conditional, qtable, make_interval(secs => vt)
72
+ );
73
+
74
+ FOR r IN
75
+ EXECUTE sql USING qty
76
+ LOOP
77
+ RETURN NEXT r;
78
+ END LOOP;
79
+ IF FOUND THEN
80
+ RETURN;
81
+ ELSE
82
+ PERFORM pg_sleep(poll_interval_ms::numeric / 1000);
83
+ END IF;
84
+ END LOOP;
85
+ END;
86
+ $$ language plpgsql;
@@ -0,0 +1 @@
1
+ {"version":"5.6.3"}
@@ -0,0 +1,77 @@
1
+ import type { ExtractFlowSteps, StepInput, Simplify, AnyFlow } from '@pgflow/dsl';
2
+ import type { Database } from './database-types.js';
3
+ export type Json = string | number | boolean | null | {
4
+ [key: string]: Json | undefined;
5
+ } | Json[];
6
+ /**
7
+ * Record representing a task from pgflow.poll_for_tasks
8
+ *
9
+ * Same as pgflow.step_task_record type, but with not-null fields and type argument for payload.
10
+ * The input type is automatically inferred based on the step_slug using a discriminated union.
11
+ * This ensures that each step only receives inputs from its declared dependencies and the flow's run input.
12
+ */
13
+ export type StepTaskRecord<TFlow extends AnyFlow> = {
14
+ [StepSlug in Extract<keyof ExtractFlowSteps<TFlow>, string>]: {
15
+ flow_slug: string;
16
+ run_id: string;
17
+ step_slug: StepSlug;
18
+ input: Simplify<StepInput<TFlow, StepSlug>>;
19
+ msg_id: number;
20
+ };
21
+ }[Extract<keyof ExtractFlowSteps<TFlow>, string>];
22
+ /**
23
+ * Composite key that is enough to find a particular step task
24
+ * Contains only the minimum fields needed to identify a task
25
+ */
26
+ export type StepTaskKey = Pick<StepTaskRecord<any>, 'run_id' | 'step_slug'>;
27
+ /**
28
+ * Interface for interacting with pgflow database functions
29
+ */
30
+ export interface IPgflowClient<TFlow extends AnyFlow = AnyFlow> {
31
+ /**
32
+ * Fetches tasks from pgflow
33
+ * @param queueName - Name
34
+ * @param batchSize - Number of tasks to fetch
35
+ * @param visibilityTimeout - Visibility timeout for tasks
36
+ * @param maxPollSeconds - Maximum time to poll for tasks
37
+ * @param pollIntervalMs - Poll interval in milliseconds
38
+ */
39
+ pollForTasks(queueName: string, batchSize?: number, visibilityTimeout?: number, maxPollSeconds?: number, pollIntervalMs?: number): Promise<StepTaskRecord<TFlow>[]>;
40
+ /**
41
+ * Marks a task as completed
42
+ * @param stepTask - Step task key containing run_id and step_slug
43
+ * @param output - Output payload for the task
44
+ */
45
+ completeTask(stepTask: StepTaskKey, output?: Json): Promise<void>;
46
+ /**
47
+ * Marks a task as failed
48
+ * @param stepTask - Step task key containing run_id and step_slug
49
+ * @param error - Error to fail task with
50
+ */
51
+ failTask(stepTask: StepTaskKey, error: unknown): Promise<void>;
52
+ }
53
+ /**
54
+ * Record representing a flow from pgflow.flows
55
+ */
56
+ export type FlowRow = Database['pgflow']['Tables']['flows']['Row'];
57
+ /**
58
+ * Record representing a step from pgflow.steps
59
+ */
60
+ export type StepRow = Database['pgflow']['Tables']['steps']['Row'];
61
+ /**
62
+ * Record representing a step from pgflow.deps
63
+ */
64
+ export type DepRow = Database['pgflow']['Tables']['deps']['Row'];
65
+ /**
66
+ * Record representing a step from pgflow.queues
67
+ */
68
+ export type RunRow = Database['pgflow']['Tables']['runs']['Row'];
69
+ /**
70
+ * Record representing a step from pgflow.step_states
71
+ */
72
+ export type StepStateRow = Database['pgflow']['Tables']['step_states']['Row'];
73
+ /**
74
+ * Record representing a step from pgflow.step_tasks
75
+ */
76
+ export type StepTaskRow = Database['pgflow']['Tables']['step_tasks']['Row'];
77
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,SAAS,EACT,QAAQ,EACR,OAAO,EACR,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,MAAM,IAAI,GACZ,MAAM,GACN,MAAM,GACN,OAAO,GACP,IAAI,GACJ;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;CAAE,GACnC,IAAI,EAAE,CAAC;AAEX;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,CAAC,KAAK,SAAS,OAAO,IAAI;KACjD,QAAQ,IAAI,OAAO,CAAC,MAAM,gBAAgB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,GAAG;QAC5D,SAAS,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,QAAQ,CAAC;QACpB,KAAK,EAAE,QAAQ,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC;QAC5C,MAAM,EAAE,MAAM,CAAC;KAChB;CACF,CAAC,OAAO,CAAC,MAAM,gBAAgB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;AAElD;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,QAAQ,GAAG,WAAW,CAAC,CAAC;AAE5E;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,KAAK,SAAS,OAAO,GAAG,OAAO;IAC5D;;;;;;;OAOG;IACH,YAAY,CACV,SAAS,EAAE,MAAM,EACjB,SAAS,CAAC,EAAE,MAAM,EACl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@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgflow/core",
3
- "version": "0.0.21",
3
+ "version": "0.0.22",
4
4
  "license": "AGPL-3.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "postgres": "^3.4.5",
27
- "@pgflow/dsl": "0.0.21"
27
+ "@pgflow/dsl": "0.0.22"
28
28
  },
29
29
  "publishConfig": {
30
30
  "access": "public",