pg-workflows 0.7.1 → 0.8.0

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,753 @@
1
+ // src/error.ts
2
+ class WorkflowEngineError extends Error {
3
+ workflowId;
4
+ runId;
5
+ cause;
6
+ issues;
7
+ constructor(message, workflowId, runId, cause = undefined, issues) {
8
+ super(message);
9
+ this.workflowId = workflowId;
10
+ this.runId = runId;
11
+ this.cause = cause;
12
+ this.issues = issues;
13
+ this.name = "WorkflowEngineError";
14
+ if (Error.captureStackTrace) {
15
+ Error.captureStackTrace(this, WorkflowEngineError);
16
+ }
17
+ }
18
+ }
19
+
20
+ class WorkflowRunNotFoundError extends WorkflowEngineError {
21
+ constructor(runId, workflowId) {
22
+ super("Workflow run not found", workflowId, runId);
23
+ this.name = "WorkflowRunNotFoundError";
24
+ }
25
+ }
26
+
27
+ // src/types.ts
28
+ var WorkflowStatus;
29
+ ((WorkflowStatus2) => {
30
+ WorkflowStatus2["PENDING"] = "pending";
31
+ WorkflowStatus2["RUNNING"] = "running";
32
+ WorkflowStatus2["PAUSED"] = "paused";
33
+ WorkflowStatus2["COMPLETED"] = "completed";
34
+ WorkflowStatus2["FAILED"] = "failed";
35
+ WorkflowStatus2["CANCELLED"] = "cancelled";
36
+ })(WorkflowStatus ||= {});
37
+ var StepType;
38
+ ((StepType2) => {
39
+ StepType2["PAUSE"] = "pause";
40
+ StepType2["RUN"] = "run";
41
+ StepType2["WAIT_FOR"] = "waitFor";
42
+ StepType2["WAIT_UNTIL"] = "waitUntil";
43
+ StepType2["DELAY"] = "delay";
44
+ StepType2["POLL"] = "poll";
45
+ })(StepType ||= {});
46
+
47
+ // src/client.ts
48
+ import { merge } from "es-toolkit";
49
+ import pg from "pg";
50
+ import { PgBoss } from "pg-boss";
51
+
52
+ // src/constants.ts
53
+ var PAUSE_EVENT_NAME = "__internal_pause";
54
+ var WORKFLOW_RUN_QUEUE_NAME = "workflow-run";
55
+ var DEFAULT_PGBOSS_SCHEMA = "pgboss_v12_pgworkflow";
56
+
57
+ // src/db/migration.ts
58
+ var MIGRATION_LOCK_ID = 738291645;
59
+ var CURRENT_SCHEMA_VERSION = 2;
60
+ async function runMigrations(db) {
61
+ if (await isSchemaUpToDate(db)) {
62
+ return;
63
+ }
64
+ const currentVersion = await getCurrentVersion(db);
65
+ const commands = [];
66
+ if (currentVersion < 1) {
67
+ commands.push(`
68
+ CREATE TABLE IF NOT EXISTS workflow_runs (
69
+ id varchar(32) PRIMARY KEY NOT NULL,
70
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
71
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
72
+ resource_id varchar(32),
73
+ workflow_id varchar(32) NOT NULL,
74
+ status text DEFAULT 'pending' NOT NULL,
75
+ input jsonb NOT NULL,
76
+ output jsonb,
77
+ error text,
78
+ current_step_id varchar(256) NOT NULL,
79
+ timeline jsonb DEFAULT '{}'::jsonb NOT NULL,
80
+ paused_at timestamp with time zone,
81
+ resumed_at timestamp with time zone,
82
+ completed_at timestamp with time zone,
83
+ timeout_at timestamp with time zone,
84
+ retry_count integer DEFAULT 0 NOT NULL,
85
+ max_retries integer DEFAULT 0 NOT NULL,
86
+ job_id varchar(256)
87
+ )
88
+ `);
89
+ commands.push(`
90
+ CREATE INDEX IF NOT EXISTS workflow_runs_created_at_idx ON workflow_runs USING btree (created_at)
91
+ `);
92
+ commands.push(`
93
+ CREATE INDEX IF NOT EXISTS workflow_runs_resource_id_created_at_idx ON workflow_runs USING btree (resource_id, created_at DESC)
94
+ `);
95
+ commands.push(`
96
+ CREATE INDEX IF NOT EXISTS workflow_runs_status_created_at_idx ON workflow_runs USING btree (status, created_at DESC)
97
+ `);
98
+ commands.push(`
99
+ CREATE INDEX IF NOT EXISTS workflow_runs_workflow_id_created_at_idx ON workflow_runs USING btree (workflow_id, created_at DESC)
100
+ `);
101
+ commands.push(`
102
+ CREATE INDEX IF NOT EXISTS workflow_runs_resource_id_workflow_id_created_at_idx ON workflow_runs USING btree (resource_id, workflow_id, created_at DESC)
103
+ `);
104
+ }
105
+ if (currentVersion < 2) {
106
+ commands.push("DROP INDEX IF EXISTS workflow_runs_workflow_id_idx");
107
+ commands.push("DROP INDEX IF EXISTS workflow_runs_resource_id_idx");
108
+ commands.push("ALTER TABLE workflow_runs ADD COLUMN IF NOT EXISTS idempotency_key varchar(256)");
109
+ commands.push(`
110
+ CREATE UNIQUE INDEX IF NOT EXISTS workflow_runs_idempotency_key_idx ON workflow_runs (idempotency_key) WHERE idempotency_key IS NOT NULL
111
+ `);
112
+ }
113
+ if (currentVersion === 0) {
114
+ commands.push(`INSERT INTO workflow_schema_version (version) VALUES (${CURRENT_SCHEMA_VERSION})`);
115
+ } else {
116
+ commands.push(`UPDATE workflow_schema_version SET version = ${CURRENT_SCHEMA_VERSION}`);
117
+ }
118
+ if (commands.length === 0) {
119
+ return;
120
+ }
121
+ const sql = [
122
+ "BEGIN",
123
+ "SET LOCAL lock_timeout = '30s'",
124
+ "SET LOCAL idle_in_transaction_session_timeout = '30s'",
125
+ `SELECT pg_advisory_xact_lock(${MIGRATION_LOCK_ID})`,
126
+ "CREATE TABLE IF NOT EXISTS workflow_schema_version (version integer NOT NULL)",
127
+ ...commands,
128
+ "COMMIT"
129
+ ].join(`;
130
+ `);
131
+ await db.executeSql(sql, []);
132
+ }
133
+ async function isSchemaUpToDate(db) {
134
+ try {
135
+ const result = await db.executeSql("SELECT version FROM workflow_schema_version LIMIT 1", []);
136
+ return (result.rows[0]?.version ?? 0) >= CURRENT_SCHEMA_VERSION;
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+ async function getCurrentVersion(db) {
142
+ try {
143
+ const result = await db.executeSql("SELECT version FROM workflow_schema_version LIMIT 1", []);
144
+ return result.rows[0]?.version ?? 0;
145
+ } catch {
146
+ return 0;
147
+ }
148
+ }
149
+
150
+ // src/db/queries.ts
151
+ import ksuid from "ksuid";
152
+ function generateKSUID(prefix) {
153
+ return `${prefix ? `${prefix}_` : ""}${ksuid.randomSync().string}`;
154
+ }
155
+ function mapRowToWorkflowRun(row) {
156
+ return {
157
+ id: row.id,
158
+ createdAt: new Date(row.created_at),
159
+ updatedAt: new Date(row.updated_at),
160
+ resourceId: row.resource_id,
161
+ workflowId: row.workflow_id,
162
+ status: row.status,
163
+ input: typeof row.input === "string" ? JSON.parse(row.input) : row.input,
164
+ output: typeof row.output === "string" ? row.output.trim().startsWith("{") || row.output.trim().startsWith("[") ? JSON.parse(row.output) : row.output : row.output ?? null,
165
+ error: row.error,
166
+ currentStepId: row.current_step_id,
167
+ timeline: typeof row.timeline === "string" ? JSON.parse(row.timeline) : row.timeline,
168
+ pausedAt: row.paused_at ? new Date(row.paused_at) : null,
169
+ resumedAt: row.resumed_at ? new Date(row.resumed_at) : null,
170
+ completedAt: row.completed_at ? new Date(row.completed_at) : null,
171
+ timeoutAt: row.timeout_at ? new Date(row.timeout_at) : null,
172
+ retryCount: row.retry_count,
173
+ maxRetries: row.max_retries,
174
+ jobId: row.job_id,
175
+ idempotencyKey: row.idempotency_key
176
+ };
177
+ }
178
+ async function insertWorkflowRun({
179
+ resourceId,
180
+ workflowId,
181
+ currentStepId,
182
+ status,
183
+ input,
184
+ maxRetries,
185
+ timeoutAt,
186
+ idempotencyKey
187
+ }, db) {
188
+ const runId = generateKSUID("run");
189
+ const now = new Date;
190
+ const result = await db.executeSql(`INSERT INTO workflow_runs (
191
+ id,
192
+ resource_id,
193
+ workflow_id,
194
+ current_step_id,
195
+ status,
196
+ input,
197
+ max_retries,
198
+ timeout_at,
199
+ created_at,
200
+ updated_at,
201
+ timeline,
202
+ retry_count,
203
+ idempotency_key
204
+ )
205
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
206
+ ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
207
+ RETURNING *`, [
208
+ runId,
209
+ resourceId ?? null,
210
+ workflowId,
211
+ currentStepId,
212
+ status,
213
+ JSON.stringify(input),
214
+ maxRetries,
215
+ timeoutAt,
216
+ now,
217
+ now,
218
+ "{}",
219
+ 0,
220
+ idempotencyKey ?? null
221
+ ]);
222
+ if (result.rows[0]) {
223
+ return { run: mapRowToWorkflowRun(result.rows[0]), created: true };
224
+ }
225
+ const existing = await db.executeSql("SELECT * FROM workflow_runs WHERE idempotency_key = $1", [
226
+ idempotencyKey
227
+ ]);
228
+ if (!existing.rows[0]) {
229
+ throw new Error(`Idempotency conflict: existing run not found for key "${idempotencyKey}"`);
230
+ }
231
+ return { run: mapRowToWorkflowRun(existing.rows[0]), created: false };
232
+ }
233
+ async function getWorkflowRun({
234
+ runId,
235
+ resourceId
236
+ }, { exclusiveLock = false, db }) {
237
+ const lockSuffix = exclusiveLock ? "FOR UPDATE" : "";
238
+ const result = resourceId ? await db.executeSql(`SELECT * FROM workflow_runs
239
+ WHERE id = $1 AND resource_id = $2
240
+ ${lockSuffix}`, [runId, resourceId]) : await db.executeSql(`SELECT * FROM workflow_runs
241
+ WHERE id = $1
242
+ ${lockSuffix}`, [runId]);
243
+ const run = result.rows[0];
244
+ if (!run) {
245
+ return null;
246
+ }
247
+ return mapRowToWorkflowRun(run);
248
+ }
249
+ async function updateWorkflowRun({
250
+ runId,
251
+ resourceId,
252
+ data,
253
+ expectedStatuses
254
+ }, db) {
255
+ const now = new Date;
256
+ const updates = ["updated_at = $1"];
257
+ const values = [now];
258
+ let paramIndex = 2;
259
+ if (data.status !== undefined) {
260
+ updates.push(`status = $${paramIndex}`);
261
+ values.push(data.status);
262
+ paramIndex++;
263
+ }
264
+ if (data.currentStepId !== undefined) {
265
+ updates.push(`current_step_id = $${paramIndex}`);
266
+ values.push(data.currentStepId);
267
+ paramIndex++;
268
+ }
269
+ if (data.timeline !== undefined) {
270
+ updates.push(`timeline = $${paramIndex}`);
271
+ values.push(JSON.stringify(data.timeline));
272
+ paramIndex++;
273
+ }
274
+ if (data.pausedAt !== undefined) {
275
+ updates.push(`paused_at = $${paramIndex}`);
276
+ values.push(data.pausedAt);
277
+ paramIndex++;
278
+ }
279
+ if (data.resumedAt !== undefined) {
280
+ updates.push(`resumed_at = $${paramIndex}`);
281
+ values.push(data.resumedAt);
282
+ paramIndex++;
283
+ }
284
+ if (data.completedAt !== undefined) {
285
+ updates.push(`completed_at = $${paramIndex}`);
286
+ values.push(data.completedAt);
287
+ paramIndex++;
288
+ }
289
+ if (data.output !== undefined) {
290
+ updates.push(`output = $${paramIndex}`);
291
+ values.push(JSON.stringify(data.output));
292
+ paramIndex++;
293
+ }
294
+ if (data.error !== undefined) {
295
+ updates.push(`error = $${paramIndex}`);
296
+ values.push(data.error);
297
+ paramIndex++;
298
+ }
299
+ if (data.retryCount !== undefined) {
300
+ updates.push(`retry_count = $${paramIndex}`);
301
+ values.push(data.retryCount);
302
+ paramIndex++;
303
+ }
304
+ if (data.jobId !== undefined) {
305
+ updates.push(`job_id = $${paramIndex}`);
306
+ values.push(data.jobId);
307
+ paramIndex++;
308
+ }
309
+ values.push(runId);
310
+ const idParam = paramIndex;
311
+ paramIndex++;
312
+ if (resourceId) {
313
+ values.push(resourceId);
314
+ paramIndex++;
315
+ }
316
+ if (expectedStatuses && expectedStatuses.length > 0) {
317
+ values.push(expectedStatuses);
318
+ paramIndex++;
319
+ }
320
+ let whereClause = resourceId ? `WHERE id = $${idParam} AND resource_id = $${idParam + 1}` : `WHERE id = $${idParam}`;
321
+ if (expectedStatuses && expectedStatuses.length > 0) {
322
+ whereClause += ` AND status = ANY($${paramIndex - 1})`;
323
+ }
324
+ const query = `
325
+ UPDATE workflow_runs
326
+ SET ${updates.join(", ")}
327
+ ${whereClause}
328
+ RETURNING *
329
+ `;
330
+ const result = await db.executeSql(query, values);
331
+ const run = result.rows[0];
332
+ if (!run) {
333
+ return null;
334
+ }
335
+ return mapRowToWorkflowRun(run);
336
+ }
337
+ async function getWorkflowRuns({
338
+ resourceId,
339
+ startingAfter,
340
+ endingBefore,
341
+ limit = 20,
342
+ statuses,
343
+ workflowId
344
+ }, db) {
345
+ const conditions = [];
346
+ const values = [];
347
+ let paramIndex = 1;
348
+ if (resourceId) {
349
+ conditions.push(`resource_id = $${paramIndex}`);
350
+ values.push(resourceId);
351
+ paramIndex++;
352
+ }
353
+ if (statuses && statuses.length > 0) {
354
+ conditions.push(`status = ANY($${paramIndex})`);
355
+ values.push(statuses);
356
+ paramIndex++;
357
+ }
358
+ if (workflowId) {
359
+ conditions.push(`workflow_id = $${paramIndex}`);
360
+ values.push(workflowId);
361
+ paramIndex++;
362
+ }
363
+ const cursorIds = [startingAfter, endingBefore].filter(Boolean);
364
+ if (cursorIds.length > 0) {
365
+ const cursorResult = await db.executeSql("SELECT id, created_at FROM workflow_runs WHERE id = ANY($1)", [cursorIds]);
366
+ const cursorMap = new Map;
367
+ for (const row of cursorResult.rows) {
368
+ cursorMap.set(row.id, typeof row.created_at === "string" ? new Date(row.created_at) : row.created_at);
369
+ }
370
+ if (startingAfter) {
371
+ const cursor = cursorMap.get(startingAfter);
372
+ if (cursor) {
373
+ conditions.push(`created_at < $${paramIndex}`);
374
+ values.push(cursor);
375
+ paramIndex++;
376
+ }
377
+ }
378
+ if (endingBefore) {
379
+ const cursor = cursorMap.get(endingBefore);
380
+ if (cursor) {
381
+ conditions.push(`created_at > $${paramIndex}`);
382
+ values.push(cursor);
383
+ paramIndex++;
384
+ }
385
+ }
386
+ }
387
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
388
+ const actualLimit = Math.min(Math.max(limit, 1), 100) + 1;
389
+ const isBackward = !!endingBefore && !startingAfter;
390
+ const query = `
391
+ SELECT * FROM workflow_runs
392
+ ${whereClause}
393
+ ORDER BY created_at ${isBackward ? "ASC" : "DESC"}
394
+ LIMIT $${paramIndex}
395
+ `;
396
+ values.push(actualLimit);
397
+ const result = await db.executeSql(query, values);
398
+ const rows = result.rows;
399
+ const hasExtraRow = rows.length > (limit ?? 20);
400
+ const rawItems = hasExtraRow ? rows.slice(0, limit) : rows;
401
+ if (isBackward) {
402
+ rawItems.reverse();
403
+ }
404
+ const items = rawItems.map((row) => mapRowToWorkflowRun(row));
405
+ const hasMore = isBackward ? items.length > 0 : hasExtraRow;
406
+ const hasPrev = isBackward ? hasExtraRow : !!startingAfter && items.length > 0;
407
+ const nextCursor = hasMore && items.length > 0 ? items[items.length - 1]?.id ?? null : null;
408
+ const prevCursor = hasPrev && items.length > 0 ? items[0]?.id ?? null : null;
409
+ return { items, nextCursor, prevCursor, hasMore, hasPrev };
410
+ }
411
+ async function withPostgresTransaction(db, callback, pool) {
412
+ let txDb;
413
+ let release;
414
+ if (pool) {
415
+ const client = await pool.connect();
416
+ txDb = {
417
+ executeSql: (text, values) => client.query(text, values)
418
+ };
419
+ release = () => client.release();
420
+ } else {
421
+ txDb = db;
422
+ }
423
+ try {
424
+ await txDb.executeSql("BEGIN", []);
425
+ const result = await callback(txDb);
426
+ await txDb.executeSql("COMMIT", []);
427
+ return result;
428
+ } catch (error) {
429
+ await txDb.executeSql("ROLLBACK", []);
430
+ throw error;
431
+ } finally {
432
+ release?.();
433
+ }
434
+ }
435
+
436
+ // src/client.ts
437
+ var LOG_PREFIX = "[WorkflowClient]";
438
+ var defaultLogger = {
439
+ log: (_message) => console.warn(_message),
440
+ error: (message, error) => console.error(message, error)
441
+ };
442
+ var defaultExpireInSeconds = process.env.WORKFLOW_RUN_EXPIRE_IN_SECONDS ? Number.parseInt(process.env.WORKFLOW_RUN_EXPIRE_IN_SECONDS, 10) : 5 * 60;
443
+
444
+ class WorkflowClient {
445
+ boss;
446
+ db;
447
+ pool;
448
+ _ownsPool = false;
449
+ _started = false;
450
+ logger;
451
+ constructor({ logger, ...connectionOptions }) {
452
+ this.logger = logger ?? defaultLogger;
453
+ if ("pool" in connectionOptions && connectionOptions.pool) {
454
+ this.pool = connectionOptions.pool;
455
+ } else if ("connectionString" in connectionOptions && connectionOptions.connectionString) {
456
+ this.pool = new pg.Pool({ connectionString: connectionOptions.connectionString });
457
+ this._ownsPool = true;
458
+ } else {
459
+ throw new WorkflowEngineError("Either pool or connectionString must be provided");
460
+ }
461
+ const db = {
462
+ executeSql: (text, values) => this.pool.query(text, values)
463
+ };
464
+ this.boss = new PgBoss({ db, schema: DEFAULT_PGBOSS_SCHEMA });
465
+ this.db = db;
466
+ }
467
+ async start() {
468
+ if (this._started) {
469
+ return;
470
+ }
471
+ await this.boss.start();
472
+ this.db = this.boss.getDb();
473
+ await runMigrations(this.db);
474
+ await this.boss.createQueue(WORKFLOW_RUN_QUEUE_NAME);
475
+ this._started = true;
476
+ this.logger.log(`${LOG_PREFIX} Client started`);
477
+ }
478
+ async stop() {
479
+ await this.boss.stop();
480
+ if (this._ownsPool) {
481
+ await this.pool.end();
482
+ }
483
+ this._started = false;
484
+ this.logger.log(`${LOG_PREFIX} Client stopped`);
485
+ }
486
+ async startWorkflow(refOrParams, inputArg, optionsArg) {
487
+ await this.ensureStarted();
488
+ let workflowId;
489
+ let input;
490
+ let resourceId;
491
+ let options;
492
+ if (typeof refOrParams === "function" && "id" in refOrParams) {
493
+ const ref = refOrParams;
494
+ workflowId = ref.id;
495
+ input = inputArg;
496
+ options = optionsArg;
497
+ resourceId = optionsArg?.resourceId;
498
+ if (ref.inputSchema) {
499
+ const result = await ref.inputSchema["~standard"].validate(input);
500
+ if (result.issues) {
501
+ throw new WorkflowEngineError(JSON.stringify(result.issues), workflowId, undefined, undefined, result.issues);
502
+ }
503
+ }
504
+ } else {
505
+ const params = refOrParams;
506
+ workflowId = params.workflowId;
507
+ input = params.input;
508
+ resourceId = params.resourceId;
509
+ options = params.options;
510
+ }
511
+ const run = await withPostgresTransaction(this.db, async (_db) => {
512
+ const timeoutAt = options?.timeout ? new Date(Date.now() + options.timeout) : null;
513
+ const { run: insertedRun, created } = await insertWorkflowRun({
514
+ resourceId,
515
+ workflowId,
516
+ currentStepId: "__start__",
517
+ status: "running" /* RUNNING */,
518
+ input,
519
+ maxRetries: options?.retries ?? 0,
520
+ timeoutAt
521
+ }, _db);
522
+ if (created) {
523
+ const job = {
524
+ runId: insertedRun.id,
525
+ resourceId,
526
+ workflowId,
527
+ input
528
+ };
529
+ await this.boss.send(WORKFLOW_RUN_QUEUE_NAME, job, {
530
+ startAfter: new Date,
531
+ expireInSeconds: options?.expireInSeconds ?? defaultExpireInSeconds
532
+ });
533
+ }
534
+ return insertedRun;
535
+ }, this.pool);
536
+ this.logger.log(`${LOG_PREFIX} Started workflow run ${run.id} for ${workflowId}`);
537
+ return run;
538
+ }
539
+ async triggerEvent({
540
+ runId,
541
+ resourceId,
542
+ eventName,
543
+ data,
544
+ options
545
+ }) {
546
+ await this.ensureStarted();
547
+ const run = await this.getRun({ runId, resourceId });
548
+ const job = {
549
+ runId: run.id,
550
+ resourceId: resourceId ?? run.resourceId ?? undefined,
551
+ workflowId: run.workflowId,
552
+ input: run.input,
553
+ event: {
554
+ name: eventName,
555
+ data
556
+ }
557
+ };
558
+ await this.boss.send(WORKFLOW_RUN_QUEUE_NAME, job, {
559
+ expireInSeconds: options?.expireInSeconds ?? defaultExpireInSeconds
560
+ });
561
+ this.logger.log(`${LOG_PREFIX} Event ${eventName} sent for workflow run ${runId}`);
562
+ return run;
563
+ }
564
+ async pauseWorkflow({
565
+ runId,
566
+ resourceId
567
+ }) {
568
+ await this.ensureStarted();
569
+ const run = await updateWorkflowRun({
570
+ runId,
571
+ resourceId,
572
+ data: {
573
+ status: "paused" /* PAUSED */,
574
+ pausedAt: new Date
575
+ },
576
+ expectedStatuses: ["running" /* RUNNING */, "pending" /* PENDING */]
577
+ }, this.db);
578
+ if (!run) {
579
+ throw new WorkflowRunNotFoundError(runId);
580
+ }
581
+ this.logger.log(`${LOG_PREFIX} Paused workflow run ${runId}`);
582
+ return run;
583
+ }
584
+ async resumeWorkflow({
585
+ runId,
586
+ resourceId,
587
+ options
588
+ }) {
589
+ await this.ensureStarted();
590
+ const current = await this.getRun({ runId, resourceId });
591
+ if (current.status !== "paused" /* PAUSED */) {
592
+ throw new WorkflowEngineError(`Cannot resume workflow run in '${current.status}' status, must be 'paused'`, current.workflowId, runId);
593
+ }
594
+ return this.triggerEvent({
595
+ runId,
596
+ resourceId,
597
+ eventName: PAUSE_EVENT_NAME,
598
+ data: {},
599
+ options
600
+ });
601
+ }
602
+ async fastForwardWorkflow({
603
+ runId,
604
+ resourceId,
605
+ data
606
+ }) {
607
+ await this.ensureStarted();
608
+ const run = await this.getRun({ runId, resourceId });
609
+ if (run.status !== "paused" /* PAUSED */) {
610
+ return run;
611
+ }
612
+ const stepId = run.currentStepId;
613
+ const waitForEntry = run.timeline[`${stepId}-wait-for`];
614
+ if (!waitForEntry || typeof waitForEntry !== "object" || !("waitFor" in waitForEntry)) {
615
+ return run;
616
+ }
617
+ const { eventName, timeoutEvent, skipOutput } = waitForEntry.waitFor;
618
+ if (eventName === PAUSE_EVENT_NAME) {
619
+ return this.resumeWorkflow({ runId, resourceId });
620
+ }
621
+ if (skipOutput && timeoutEvent) {
622
+ await withPostgresTransaction(this.db, async (db) => {
623
+ const freshRun = await getWorkflowRun({ runId, resourceId }, { exclusiveLock: true, db });
624
+ if (!freshRun)
625
+ throw new WorkflowRunNotFoundError(runId);
626
+ return updateWorkflowRun({
627
+ runId,
628
+ resourceId,
629
+ data: {
630
+ timeline: merge(freshRun.timeline, {
631
+ [stepId]: {
632
+ output: data ?? {},
633
+ timestamp: new Date
634
+ }
635
+ })
636
+ }
637
+ }, db);
638
+ }, this.pool);
639
+ return this.triggerEvent({ runId, resourceId, eventName: timeoutEvent });
640
+ }
641
+ if (eventName) {
642
+ return this.triggerEvent({ runId, resourceId, eventName, data: data ?? {} });
643
+ }
644
+ if (timeoutEvent) {
645
+ return this.triggerEvent({ runId, resourceId, eventName: timeoutEvent, data: data ?? {} });
646
+ }
647
+ return run;
648
+ }
649
+ async cancelWorkflow({
650
+ runId,
651
+ resourceId
652
+ }) {
653
+ await this.ensureStarted();
654
+ const run = await updateWorkflowRun({
655
+ runId,
656
+ resourceId,
657
+ data: {
658
+ status: "cancelled" /* CANCELLED */
659
+ },
660
+ expectedStatuses: ["pending" /* PENDING */, "running" /* RUNNING */, "paused" /* PAUSED */]
661
+ }, this.db);
662
+ if (!run) {
663
+ throw new WorkflowRunNotFoundError(runId);
664
+ }
665
+ this.logger.log(`${LOG_PREFIX} Cancelled workflow run ${runId}`);
666
+ return run;
667
+ }
668
+ async getRun({
669
+ runId,
670
+ resourceId
671
+ }) {
672
+ await this.ensureStarted();
673
+ const run = await getWorkflowRun({ runId, resourceId }, { db: this.db });
674
+ if (!run) {
675
+ throw new WorkflowRunNotFoundError(runId);
676
+ }
677
+ return run;
678
+ }
679
+ async checkProgress({
680
+ runId,
681
+ resourceId
682
+ }) {
683
+ const run = await this.getRun({ runId, resourceId });
684
+ const completedSteps = Object.values(run.timeline).filter((entry) => typeof entry === "object" && entry !== null && ("output" in entry) && entry.output !== undefined).length;
685
+ const totalSteps = run.status === "completed" /* COMPLETED */ ? completedSteps : 0;
686
+ const completionPercentage = run.status === "completed" /* COMPLETED */ ? 100 : run.status === "failed" /* FAILED */ || run.status === "cancelled" /* CANCELLED */ ? 0 : 0;
687
+ return {
688
+ ...run,
689
+ completedSteps,
690
+ completionPercentage,
691
+ totalSteps
692
+ };
693
+ }
694
+ async getRuns({
695
+ resourceId,
696
+ startingAfter,
697
+ endingBefore,
698
+ limit = 20,
699
+ statuses,
700
+ workflowId
701
+ }) {
702
+ await this.ensureStarted();
703
+ return getWorkflowRuns({
704
+ resourceId,
705
+ startingAfter,
706
+ endingBefore,
707
+ limit,
708
+ statuses,
709
+ workflowId
710
+ }, this.db);
711
+ }
712
+ async ensureStarted() {
713
+ if (!this._started) {
714
+ await this.start();
715
+ }
716
+ }
717
+ }
718
+
719
+ // src/definition.ts
720
+ function createWorkflowRef(id, options) {
721
+ const ref = (handler, defineOptions) => ({
722
+ id,
723
+ handler,
724
+ inputSchema: options?.inputSchema,
725
+ timeout: defineOptions?.timeout,
726
+ retries: defineOptions?.retries
727
+ });
728
+ Object.defineProperty(ref, "id", { value: id, enumerable: true });
729
+ Object.defineProperty(ref, "inputSchema", { value: options?.inputSchema, enumerable: true });
730
+ return ref;
731
+ }
732
+ function createWorkflowFactory(plugins = []) {
733
+ const factory = (id, handler, { inputSchema, timeout, retries } = {}) => ({
734
+ id,
735
+ handler,
736
+ inputSchema,
737
+ timeout,
738
+ retries,
739
+ plugins: plugins.length > 0 ? plugins : undefined
740
+ });
741
+ factory.use = (plugin) => createWorkflowFactory([
742
+ ...plugins,
743
+ plugin
744
+ ]);
745
+ factory.ref = createWorkflowRef;
746
+ return factory;
747
+ }
748
+ var workflow = createWorkflowFactory();
749
+
750
+ export { PAUSE_EVENT_NAME, WORKFLOW_RUN_QUEUE_NAME, DEFAULT_PGBOSS_SCHEMA, runMigrations, insertWorkflowRun, getWorkflowRun, updateWorkflowRun, getWorkflowRuns, withPostgresTransaction, WorkflowEngineError, WorkflowRunNotFoundError, WorkflowStatus, StepType, WorkflowClient, createWorkflowRef, workflow };
751
+
752
+ //# debugId=195A7297AA34528664756E2164756E21
753
+ //# sourceMappingURL=chunk-8n9chg7z.js.map