@pgflow/core 0.0.19 → 0.0.20

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,56 @@
1
+ /**
2
+ * Implementation of IPgflowClient that uses direct SQL calls to pgflow functions
3
+ */
4
+ export class PgflowSqlClient {
5
+ sql;
6
+ constructor(sql) {
7
+ this.sql = sql;
8
+ }
9
+ async pollForTasks(queueName, batchSize = 20, visibilityTimeout = 2, maxPollSeconds = 5, pollIntervalMs = 200) {
10
+ return await this.sql `
11
+ SELECT *
12
+ FROM pgflow.poll_for_tasks(
13
+ queue_name => ${queueName},
14
+ vt => ${visibilityTimeout},
15
+ qty => ${batchSize},
16
+ max_poll_seconds => ${maxPollSeconds},
17
+ poll_interval_ms => ${pollIntervalMs}
18
+ );
19
+ `;
20
+ }
21
+ async completeTask(stepTask, output) {
22
+ await this.sql `
23
+ SELECT pgflow.complete_task(
24
+ run_id => ${stepTask.run_id}::uuid,
25
+ step_slug => ${stepTask.step_slug}::text,
26
+ task_index => ${0}::int,
27
+ output => ${this.sql.json(output || null)}::jsonb
28
+ );
29
+ `;
30
+ }
31
+ async failTask(stepTask, error) {
32
+ const errorString = typeof error === 'string'
33
+ ? error
34
+ : error instanceof Error
35
+ ? error.message
36
+ : JSON.stringify(error);
37
+ await this.sql `
38
+ SELECT pgflow.fail_task(
39
+ run_id => ${stepTask.run_id}::uuid,
40
+ step_slug => ${stepTask.step_slug}::text,
41
+ task_index => ${0}::int,
42
+ error_message => ${errorString}::text
43
+ );
44
+ `;
45
+ }
46
+ async startFlow(flow, input) {
47
+ const results = await this.sql `
48
+ SELECT * FROM pgflow.start_flow(${flow.slug}::text, ${this.sql.json(input)}::jsonb);
49
+ `;
50
+ if (results.length === 0) {
51
+ throw new Error(`Failed to start flow ${flow.slug}`);
52
+ }
53
+ const [flowRun] = results;
54
+ return flowRun;
55
+ }
56
+ }
package/dist/README.md ADDED
@@ -0,0 +1,373 @@
1
+ # pgflow SQL Core
2
+
3
+ PostgreSQL-native workflow engine for defining, managing, and tracking DAG-based workflows directly in your database.
4
+
5
+ > [!NOTE]
6
+ > This project is licensed under [AGPL v3](./LICENSE.md) license and is part of **pgflow** stack.
7
+ > See [LICENSING_OVERVIEW.md](../../LICENSING_OVERVIEW.md) in root of this monorepo for more details.
8
+
9
+ ## Table of Contents
10
+
11
+ - [Overview](#overview)
12
+ - [Key Features](#key-features)
13
+ - [Architecture](#architecture)
14
+ - [Schema Design](#schema-design)
15
+ - [Execution Model](#execution-model)
16
+ - [Example Flow and its life](#example-flow-and-its-life)
17
+ - [Defining a Workflow](#defining-a-workflow)
18
+ - [Starting a Workflow Run](#starting-a-workflow-run)
19
+ - [Workflow Execution](#workflow-execution)
20
+ - [Task Polling](#task-polling)
21
+ - [Task Completion](#task-completion)
22
+ - [Error Handling](#error-handling)
23
+ - [Retries and Timeouts](#retries-and-timeouts)
24
+ - [TypeScript Flow DSL](#typescript-flow-dsl)
25
+ - [Overview](#overview-1)
26
+ - [Type Inference System](#type-inference-system)
27
+ - [Basic Example](#basic-example)
28
+ - [How Payload Types Are Built](#how-payload-types-are-built)
29
+ - [Benefits of Automatic Type Inference](#benefits-of-automatic-type-inference)
30
+ - [Data Flow](#data-flow)
31
+ - [Input and Output Handling](#input-and-output-handling)
32
+ - [Run Completion](#run-completion)
33
+
34
+ ## Overview
35
+
36
+ The pgflow SQL Core provides the data model, state machine, and transactional functions for workflow management. It treats workflows as Directed Acyclic Graphs (DAGs) of steps, each step being a simple state machine.
37
+
38
+ This package focuses on:
39
+
40
+ - Defining and storing workflow shapes
41
+ - Managing workflow state transitions
42
+ - Exposing transactional functions for workflow operations
43
+ - Providing APIs for task polling and status updates
44
+
45
+ The actual execution of workflow tasks is handled by the [Edge Worker](../edge-worker/README.md), which calls back to the SQL Core to acknowledge task completion or failure.
46
+
47
+ ## Key Features
48
+
49
+ - **Declarative Workflows**: Define flows and steps via SQL tables
50
+ - **Dependency Management**: Explicit step dependencies with atomic transitions
51
+ - **Configurable Behavior**: Per-flow and per-step options for timeouts, retries, and delays
52
+ - **Queue Integration**: Built on pgmq for reliable task processing
53
+ - **Transactional Guarantees**: All state transitions are ACID-compliant
54
+
55
+ ## Architecture
56
+
57
+ ### Schema Design
58
+
59
+ [Schema ERD Diagram (click to enlarge)](./schema.svg)
60
+
61
+ <a href="./schema.svg">
62
+ <img src="./schema.svg" alt="Schema ERD Diagram" width="25%" height="25%">
63
+ </a>
64
+
65
+ ---
66
+
67
+ The schema consists of two main categories of tables:
68
+
69
+ #### Static definition tables
70
+
71
+ - `flows` (just an identity for the workflow with some global options)
72
+ - `steps` (DAG nodes belonging to particular `flows`, with option overrides)
73
+ - `deps` (DAG edges between `steps`)
74
+
75
+ #### Runtime state tables
76
+
77
+ - `runs` (execution instances of `flows`)
78
+ - `step_states` (states of individual `steps` within a `run`)
79
+ - `step_tasks` (units of work for individual `steps` within a `run`, so we can have fanouts)
80
+
81
+ ### Execution Model
82
+
83
+ The SQL Core handles the workflow lifecycle through these key operations:
84
+
85
+ 1. **Definition**: Workflows are defined using `create_flow` and `add_step`
86
+ 2. **Instantiation**: Workflow instances are started with `start_flow`, creating a new run
87
+ 3. **Task Management**: The [Edge Worker](../edge-worker/README.md) polls for available tasks using `poll_for_tasks`
88
+ 4. **State Transitions**: When the Edge Worker reports back using `complete_task` or `fail_task`, the SQL Core handles state transitions and schedules dependent steps
89
+
90
+ [Flow lifecycle diagram (click to enlarge)](./flow-lifecycle.svg)
91
+
92
+ <a href="./flow-lifecycle.svg"><img src="./flow-lifecycle.svg" alt="Flow Lifecycle" width="25%" height="25%"></a>
93
+
94
+ ## Example flow and its life
95
+
96
+ Let's walk through creating and running a workflow that fetches a website,
97
+ does summarization and sentiment analysis in parallel steps
98
+ and saves the results to a database.
99
+
100
+ ![example flow graph](./example-flow.svg)
101
+
102
+ ### Defining a Workflow
103
+
104
+ Workflows are defined using two SQL functions: `create_flow` and `add_step`.
105
+
106
+ In this example, we'll create a workflow with:
107
+ - `website` as the entry point ("root step")
108
+ - `sentiment` and `summary` as parallel steps that depend on `website`
109
+ - `saveToDb` as the final step, depending on both parallel steps
110
+
111
+ ```sql
112
+ -- Define workflow with parallel steps
113
+ SELECT pgflow.create_flow('analyze_website');
114
+ SELECT pgflow.add_step('analyze_website', 'website');
115
+ SELECT pgflow.add_step('analyze_website', 'sentiment', deps_slugs => ARRAY['website']);
116
+ SELECT pgflow.add_step('analyze_website', 'summary', deps_slugs => ARRAY['website']);
117
+ SELECT pgflow.add_step('analyze_website', 'saveToDb', deps_slugs => ARRAY['sentiment', 'summary']);
118
+ ```
119
+
120
+ > [!WARNING]
121
+ > You need to call `add_step` in topological order, which is enforced by foreign key constraints.
122
+
123
+ > [!NOTE]
124
+ > You can have multiple "root steps" in a workflow. You can even create a root-steps-only workflow
125
+ > to process a single input in parallel, because at the end, all of the outputs from steps
126
+ > that does not have dependents ("final steps") are aggregated and saved as run's `output`.
127
+
128
+ ### Starting a Workflow Run
129
+
130
+ To start a workflow, call `start_flow` with a flow slug and input arguments:
131
+
132
+ ```sql
133
+ SELECT * FROM pgflow.start_flow(
134
+ flow_slug => 'analyze_website',
135
+ input => '{"url": "https://example.com"}'::jsonb
136
+ );
137
+
138
+ -- run_id | flow_slug | status | input | output | remaining_steps
139
+ -- ------------+-----------------+---------+--------------------------------+--------+-----------------
140
+ -- <run uuid> | analyze_website | started | {"url": "https://example.com"} | [NULL] | 4
141
+ ```
142
+
143
+ When a workflow starts:
144
+ - A new `run` record is created
145
+ - Initial states for all steps are created
146
+ - Root steps are marked as `started`
147
+ - Tasks are created for root steps
148
+ - Messages are enqueued on PGMQ for worker processing
149
+
150
+ > [!NOTE]
151
+ > The `input` argument must be a valid JSONB object: string, number, boolean, array, object or null.
152
+
153
+ ### Workflow Execution
154
+
155
+ #### Task Polling
156
+
157
+ The Edge Worker continuously polls for available tasks using the `poll_for_tasks` function:
158
+
159
+ ```sql
160
+ SELECT * FROM pgflow.poll_for_tasks(
161
+ queue_name => 'analyze_website',
162
+ vt => 60, -- visibility timeout in seconds
163
+ qty => 5 -- maximum number of tasks to fetch
164
+ );
165
+ ```
166
+
167
+ When a task is polled:
168
+
169
+ 1. The message is hidden from other workers for the specified timeout period
170
+ 2. The task's attempts counter is incremented for retry tracking
171
+ 3. An input object is built by combining the run input with outputs from completed dependency steps
172
+ 4. Task metadata and input are returned to the worker
173
+
174
+ This process happens in a single transaction to ensure reliability. The worker then executes the appropriate handler function based on the task metadata.
175
+
176
+ #### Task Completion
177
+
178
+ After successful processing, the worker acknowledges completion:
179
+
180
+ ```sql
181
+ SELECT pgflow.complete_task(
182
+ run_id => '<run_uuid>',
183
+ step_slug => 'website',
184
+ task_index => 0, -- we will have multiple tasks for a step in the future
185
+ output => '{"content": "HTML content", "status": 200}'::jsonb
186
+ );
187
+ ```
188
+
189
+ When a task completes:
190
+ 1. The task status is updated to 'completed' and the output is saved
191
+ 2. The message is archived in PGMQ
192
+ 3. The step state is updated to 'completed'
193
+ 4. Dependent steps with all dependencies completed are automatically started
194
+ 5. The run's remaining_steps counter is decremented
195
+ 6. If all steps are completed, the run is marked as completed with aggregated outputs
196
+
197
+ #### Error Handling
198
+
199
+ If a task fails, the worker acknowledges this using `fail_task`:
200
+
201
+ ```sql
202
+ SELECT pgflow.fail_task(
203
+ run_id => '<run_uuid>',
204
+ step_slug => 'website',
205
+ task_index => 0,
206
+ error_message => 'Connection timeout when fetching URL'::text
207
+ );
208
+ ```
209
+
210
+ The system handles failures by:
211
+
212
+ 1. Checking if retry attempts are available
213
+ 2. For available retries:
214
+ - Keeping the task in 'queued' status
215
+ - Applying exponential backoff for visibility
216
+ - Preventing processing until the visibility timeout expires
217
+ 3. When retries are exhausted:
218
+ - Marking the task as 'failed'
219
+ - Marking the step as 'failed'
220
+ - Marking the run as 'failed'
221
+ - Archiving the message in PGMQ
222
+ - Notifying workers to abort pending tasks (future feature)
223
+
224
+ #### Retries and Timeouts
225
+
226
+ Retry behavior can be configured at both the flow and step level:
227
+
228
+ ```sql
229
+ -- Flow-level defaults
230
+ SELECT pgflow.create_flow(
231
+ flow_slug => 'analyze_website',
232
+ max_attempts => 3, -- Maximum retry attempts (including first attempt)
233
+ base_delay => 5, -- Base delay in seconds for exponential backoff
234
+ timeout => 60 -- Task timeout in seconds
235
+ );
236
+
237
+ -- Step-level overrides
238
+ SELECT pgflow.add_step(
239
+ flow_slug => 'analyze_website',
240
+ step_slug => 'sentiment',
241
+ deps_slugs => ARRAY['website']::text[],
242
+ max_attempts => 5, -- Override max attempts for this step
243
+ base_delay => 2, -- Override base delay for exponential backoff
244
+ timeout => 30 -- Override timeout for this step
245
+ );
246
+ ```
247
+
248
+ The system applies exponential backoff for retries using the formula:
249
+ ```
250
+ delay = base_delay * (2 ^ attempts_count)
251
+ ```
252
+
253
+ Timeouts are enforced by setting the message visibility timeout to the step's timeout value plus a small buffer. If a worker doesn't acknowledge completion or failure within this period, the task becomes visible again and can be retried.
254
+
255
+ ## TypeScript Flow DSL
256
+
257
+ > [!NOTE]
258
+ > TypeScript Flow DSL is a Work In Progress and is not ready yet!
259
+
260
+ ### Overview
261
+
262
+ While the SQL Core engine handles workflow definitions and state management, the primary way to define and work with your workflow logic is via the Flow DSL in TypeScript. This DSL offers a fluent API that makes it straightforward to outline the steps in your flow with full type safety.
263
+
264
+ ### Type Inference System
265
+
266
+ The most powerful feature of the Flow DSL is its **automatic type inference system**:
267
+
268
+ 1. You only need to annotate the initial Flow input type
269
+ 2. The return type of each step is automatically inferred from your handler function
270
+ 3. These return types become available in the payload of dependent steps
271
+ 4. The TypeScript compiler builds a complete type graph matching your workflow DAG
272
+
273
+ This means you get full IDE autocompletion and type checking throughout your workflow without manual type annotations.
274
+
275
+ ### Basic Example
276
+
277
+ Here's an example that matches our website analysis workflow:
278
+
279
+ ```ts
280
+ // Provide a type for the input of the Flow
281
+ type Input = {
282
+ url: string;
283
+ };
284
+
285
+ const AnalyzeWebsite = new Flow<Input>({
286
+ slug: "analyze_website",
287
+ maxAttempts: 3,
288
+ baseDelay: 5,
289
+ timeout: 10,
290
+ })
291
+ .step({ slug: "website" }, async (input) => await scrapeWebsite(input.run.url))
292
+ .step(
293
+ { slug: "sentiment", dependsOn: ["website"], timeout: 30, maxAttempts: 5 },
294
+ async (input) => await analyzeSentiment(input.website.content)
295
+ )
296
+ .step(
297
+ { slug: "summary", dependsOn: ["website"] },
298
+ async (input) => await summarizeWithAI(input.website.content)
299
+ )
300
+ .step(
301
+ { slug: "saveToDb", dependsOn: ["sentiment", "summary"] },
302
+ async (input) =>
303
+ await saveToDb({
304
+ websiteUrl: input.run.url,
305
+ sentiment: input.sentiment.score,
306
+ summary: input.summary,
307
+ }).status
308
+ );
309
+ ```
310
+
311
+ ### How Payload Types Are Built
312
+
313
+ The payload object for each step is constructed dynamically based on:
314
+
315
+ 1. **The `run` property**: Always contains the original workflow input
316
+ 2. **Dependency outputs**: Each dependency's output is available under a key matching the dependency's ID
317
+ 3. **DAG structure**: Only outputs from direct dependencies are included in the payload
318
+
319
+ This means your step handlers receive exactly the data they need, properly typed, without any manual type declarations beyond the initial Flow input type.
320
+
321
+ ### Benefits of Automatic Type Inference
322
+
323
+ - **Refactoring safety**: Change a step's output, and TypeScript will flag all dependent steps that need updates
324
+ - **Discoverability**: IDE autocompletion shows exactly what data is available in each step
325
+ - **Error prevention**: Catch typos and type mismatches at compile time, not runtime
326
+ - **Documentation**: The types themselves serve as living documentation of your workflow's data flow
327
+
328
+ ## Data Flow
329
+
330
+ ### Input and Output Handling
331
+
332
+ Handlers in pgflow **must return** JSON-serializable values that are captured and saved when `complete_task` is called. These outputs become available as inputs to dependent steps, allowing data to flow through your workflow pipeline.
333
+
334
+ When a step is executed, it receives an input object where:
335
+ - Each key is a step_slug of a completed dependency
336
+ - Each value is that step's output
337
+ - A special "run" key contains the original workflow input
338
+
339
+ #### Example: `sentiment`
340
+
341
+ When the `sentiment` step runs, it receives:
342
+
343
+ ```json
344
+ {
345
+ "run": {"url": "https://example.com"},
346
+ "website": {"content": "HTML content", "status": 200}
347
+ }
348
+ ```
349
+
350
+ #### Example: `saveToDb`
351
+
352
+ The `saveToDb` step depends on both `sentiment` and `summary`:
353
+
354
+ ```json
355
+ {
356
+ "run": {"url": "https://example.com"},
357
+ "sentiment": {"score": 0.85, "label": "positive"},
358
+ "summary": "This website discusses various topics related to technology and innovation."
359
+ }
360
+ ```
361
+
362
+ ### Run Completion
363
+
364
+ When all steps in a run are completed, the run status is automatically updated to 'completed' and its output is set. The output is an aggregation of all the outputs from final steps (steps that have no dependents):
365
+
366
+ ```sql
367
+ -- Example of a completed run with output
368
+ SELECT run_id, status, output FROM pgflow.runs WHERE run_id = '<run_uuid>';
369
+
370
+ -- run_id | status | output
371
+ -- ------------+-----------+-----------------------------------------------------
372
+ -- <run uuid> | completed | {"saveToDb": {"status": "success"}}
373
+ ```