@gencow/core 0.1.23 → 0.1.24

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,111 @@
1
+ import type { GencowCtx } from "./reactive.js";
2
+ import type { InferArgs } from "./v.js";
3
+
4
+ export type WorkflowStatus = "pending" | "running" | "completed" | "failed";
5
+ export type WorkflowDuration = number | string;
6
+ export type WorkflowDerivedStatus = WorkflowStatus | "queued" | "waiting" | "sleeping";
7
+
8
+ export function deriveWorkflowStatus(
9
+ status: WorkflowStatus,
10
+ currentStep: string | null | undefined
11
+ ): WorkflowDerivedStatus {
12
+ if (status !== "pending") {
13
+ return status;
14
+ }
15
+ if (currentStep?.startsWith("sleep#")) {
16
+ return "sleeping";
17
+ }
18
+ if (currentStep?.startsWith("wait:")) {
19
+ return "waiting";
20
+ }
21
+ return "queued";
22
+ }
23
+
24
+ export interface WorkflowSummary {
25
+ id: string;
26
+ name: string;
27
+ status: WorkflowStatus;
28
+ derivedStatus: WorkflowDerivedStatus;
29
+ currentStep: string | null;
30
+ error: string | null;
31
+ retryCount: number;
32
+ maxRetries: number;
33
+ maxDurationMs: number;
34
+ startedAt: string;
35
+ updatedAt: string;
36
+ completedAt: string | null;
37
+ }
38
+
39
+ export interface WorkflowStepSnapshot {
40
+ name: string;
41
+ status: WorkflowStatus;
42
+ output: unknown;
43
+ error: string | null;
44
+ startedAt: string | null;
45
+ updatedAt: string;
46
+ completedAt: string | null;
47
+ }
48
+
49
+ export interface WorkflowSnapshot extends WorkflowSummary {
50
+ args: unknown;
51
+ result: unknown;
52
+ steps: WorkflowStepSnapshot[];
53
+ /** Opaque realtime channel for exact-id workflow updates. */
54
+ realtimeKey: string;
55
+ }
56
+
57
+ export interface WorkflowListArgs {
58
+ limit?: number;
59
+ status?: WorkflowDerivedStatus;
60
+ }
61
+
62
+ export interface WorkflowStartResult {
63
+ id: string;
64
+ name: string;
65
+ status: "pending";
66
+ scheduledJobId: string;
67
+ }
68
+
69
+ export interface WorkflowSignalResult {
70
+ ok: boolean;
71
+ workflowId: string;
72
+ event: string;
73
+ scheduledJobId: string | null;
74
+ }
75
+
76
+ export interface WorkflowResumePayload {
77
+ workflowId: string;
78
+ }
79
+
80
+ export interface WorkflowCtx extends GencowCtx {
81
+ workflowId: string;
82
+ workflowName: string;
83
+ step<TResult>(name: string, run: () => Promise<TResult>): Promise<TResult>;
84
+ sleep(duration: WorkflowDuration): Promise<void>;
85
+ waitForEvent<TPayload = unknown>(name: string, timeout?: WorkflowDuration): Promise<TPayload>;
86
+ parallel<TTasks extends ReadonlyArray<() => Promise<any>>>(
87
+ tasks: TTasks
88
+ ): Promise<{ [K in keyof TTasks]: Awaited<ReturnType<TTasks[K]>> }>;
89
+ }
90
+
91
+ export type WorkflowHandler<TArgs, TReturn> = (
92
+ wf: WorkflowCtx,
93
+ args: TArgs
94
+ ) => Promise<TReturn>;
95
+
96
+ export interface WorkflowOptions<TSchema = any, TReturn = any> {
97
+ args?: TSchema;
98
+ public?: boolean;
99
+ maxDuration?: WorkflowDuration;
100
+ retries?: number;
101
+ handler: WorkflowHandler<InferArgs<TSchema>, TReturn>;
102
+ }
103
+
104
+ export interface WorkflowDef<TSchema = any, TReturn = any> {
105
+ name: string;
106
+ argsSchema?: TSchema;
107
+ isPublic: boolean;
108
+ maxDurationMs: number;
109
+ maxRetries: number;
110
+ handler: WorkflowHandler<InferArgs<TSchema>, TReturn>;
111
+ }
@@ -0,0 +1,205 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { mutation } from "./reactive.js";
3
+ import type { MutationDef } from "./reactive.js";
4
+ import type {
5
+ WorkflowDef,
6
+ WorkflowDuration,
7
+ WorkflowOptions,
8
+ WorkflowStartResult,
9
+ } from "./workflow-types.js";
10
+ import { registerWorkflowsApi } from "./workflows-api.js";
11
+
12
+ declare global {
13
+ // eslint-disable-next-line no-var
14
+ var __gencow_workflowRegistry: Map<string, WorkflowDef<any, any>>;
15
+ }
16
+
17
+ const workflowRegistry =
18
+ globalThis.__gencow_workflowRegistry ??= new Map<string, WorkflowDef<any, any>>();
19
+
20
+ export const DEFAULT_WORKFLOW_MAX_DURATION_MS = 30 * 60 * 1000;
21
+ export const DEFAULT_WORKFLOW_MAX_RETRIES = 3;
22
+ export const WORKFLOW_RESUME_ACTION_PREFIX = "__gencow.workflow.resume";
23
+ export const WORKFLOW_REALTIME_KEY_PREFIX = "__gencow.workflow.state";
24
+
25
+ type SerializedWorkflowValue =
26
+ | { __gencowUndefined: true }
27
+ | { value: unknown };
28
+
29
+ function isSerializedWorkflowValue(value: unknown): value is SerializedWorkflowValue {
30
+ return !!value && typeof value === "object" && (
31
+ "__gencowUndefined" in value ||
32
+ "value" in value
33
+ );
34
+ }
35
+
36
+ export function serializeWorkflowValue(value: unknown): SerializedWorkflowValue {
37
+ const payload = value === undefined
38
+ ? { __gencowUndefined: true as const }
39
+ : { value };
40
+
41
+ try {
42
+ return JSON.parse(JSON.stringify(payload)) as SerializedWorkflowValue;
43
+ } catch (error) {
44
+ const reason = error instanceof Error ? error.message : String(error);
45
+ throw new Error(
46
+ `workflow() only persists JSON-serializable values. Failed to serialize workflow payload: ${reason}`
47
+ );
48
+ }
49
+ }
50
+
51
+ export function deserializeWorkflowValue(value: unknown): unknown {
52
+ if (!isSerializedWorkflowValue(value)) return value;
53
+ if ("__gencowUndefined" in value) return undefined;
54
+ return value.value;
55
+ }
56
+
57
+ function clampRetries(retries: number | undefined): number {
58
+ if (retries == null) return DEFAULT_WORKFLOW_MAX_RETRIES;
59
+ if (!Number.isFinite(retries) || retries < 0) {
60
+ throw new Error(`workflow() retries must be a non-negative finite number, got "${retries}"`);
61
+ }
62
+ return Math.floor(retries);
63
+ }
64
+
65
+ function parseDurationString(raw: string, label: string): number {
66
+ const normalized = raw.trim().toLowerCase();
67
+ const match = normalized.match(/^(\d+)(ms|s|m|h|d)$/);
68
+ if (!match) {
69
+ throw new Error(
70
+ `${label} must be a number of ms or a string like "30m", "90s", "1h" — got "${raw}"`
71
+ );
72
+ }
73
+ const value = Number(match[1]);
74
+ const unit = match[2];
75
+ const unitMs =
76
+ unit === "ms" ? 1 :
77
+ unit === "s" ? 1_000 :
78
+ unit === "m" ? 60_000 :
79
+ unit === "h" ? 3_600_000 :
80
+ 86_400_000;
81
+ return value * unitMs;
82
+ }
83
+
84
+ export function parseWorkflowDurationMs(
85
+ raw: WorkflowDuration,
86
+ label = "workflow duration"
87
+ ): number {
88
+ if (typeof raw === "number") {
89
+ if (!Number.isFinite(raw) || raw <= 0) {
90
+ throw new Error(`${label} must be a positive finite number, got "${raw}"`);
91
+ }
92
+ return Math.floor(raw);
93
+ }
94
+ if (typeof raw !== "string") {
95
+ throw new Error(
96
+ `${label} must be a positive finite number or a string like "30m", "90s", "1h" — got "${String(raw)}"`
97
+ );
98
+ }
99
+ return parseDurationString(raw, label);
100
+ }
101
+
102
+ function normalizeMaxDurationMs(maxDuration: WorkflowDuration | undefined): number {
103
+ if (maxDuration == null) return DEFAULT_WORKFLOW_MAX_DURATION_MS;
104
+ return parseWorkflowDurationMs(maxDuration, "workflow() maxDuration");
105
+ }
106
+
107
+ export function getWorkflowResumeActionName(name: string): string {
108
+ return `${WORKFLOW_RESUME_ACTION_PREFIX}.${name}`;
109
+ }
110
+
111
+ export function createWorkflowRealtimeToken(): string {
112
+ return crypto.randomUUID().replace(/-/g, "");
113
+ }
114
+
115
+ export function getWorkflowRealtimeKey(workflowId: string, realtimeToken: string): string {
116
+ return `${WORKFLOW_REALTIME_KEY_PREFIX}.${workflowId}.${realtimeToken}`;
117
+ }
118
+
119
+ export function getWorkflowDef(name: string): WorkflowDef | undefined {
120
+ return workflowRegistry.get(name);
121
+ }
122
+
123
+ export function getRegisteredWorkflows(): WorkflowDef[] {
124
+ return Array.from(workflowRegistry.values());
125
+ }
126
+
127
+ /**
128
+ * workflow() — durable multi-step execution with step memoization.
129
+ *
130
+ * The returned value is still a mutation definition, so existing API codegen and
131
+ * frontend hooks keep working without extra workflow-specific tooling.
132
+ */
133
+ export function workflow<TSchema = any, TReturn = any>(
134
+ name: string,
135
+ options: WorkflowOptions<TSchema, TReturn>
136
+ ): MutationDef<TSchema, WorkflowStartResult> {
137
+ registerWorkflowsApi();
138
+
139
+ const maxDurationMs = normalizeMaxDurationMs(options.maxDuration);
140
+ const maxRetries = clampRetries(options.retries);
141
+
142
+ const def: WorkflowDef<TSchema, TReturn> = {
143
+ name,
144
+ argsSchema: options.args,
145
+ isPublic: options.public === true,
146
+ maxDurationMs,
147
+ maxRetries,
148
+ handler: options.handler,
149
+ };
150
+
151
+ workflowRegistry.set(name, def);
152
+
153
+ return mutation<TSchema, WorkflowStartResult>(name, {
154
+ args: options.args,
155
+ public: options.public,
156
+ handler: async (ctx, args) => {
157
+ const workflowId = crypto.randomUUID();
158
+ const resumeAction = getWorkflowResumeActionName(name);
159
+ const ownerId = ctx.auth.getUserIdentity()?.id ?? null;
160
+ const persistedArgs = serializeWorkflowValue(args ?? {});
161
+ const realtimeToken = createWorkflowRealtimeToken();
162
+
163
+ await ctx.unsafeDb.execute(sql`
164
+ INSERT INTO _gencow_workflows (
165
+ id,
166
+ name,
167
+ args,
168
+ realtime_token,
169
+ status,
170
+ retry_count,
171
+ max_retries,
172
+ max_duration_ms,
173
+ user_id
174
+ )
175
+ VALUES (
176
+ ${workflowId},
177
+ ${name},
178
+ ${JSON.stringify(persistedArgs)}::jsonb,
179
+ ${realtimeToken},
180
+ 'pending',
181
+ 0,
182
+ ${maxRetries},
183
+ ${maxDurationMs},
184
+ ${ownerId}
185
+ )
186
+ `);
187
+
188
+ try {
189
+ const scheduledJobId = ctx.scheduler.runAfter(0, resumeAction, { workflowId });
190
+ return {
191
+ id: workflowId,
192
+ name,
193
+ status: "pending",
194
+ scheduledJobId,
195
+ };
196
+ } catch (error) {
197
+ await ctx.unsafeDb.execute(sql`
198
+ DELETE FROM _gencow_workflows
199
+ WHERE id = ${workflowId}
200
+ `);
201
+ throw error;
202
+ }
203
+ },
204
+ });
205
+ }