@gencow/core 0.1.22 → 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.
Files changed (44) hide show
  1. package/dist/crud.js +1 -1
  2. package/dist/index.d.ts +6 -1
  3. package/dist/index.js +3 -0
  4. package/dist/reactive.js +6 -0
  5. package/dist/rls-db.d.ts +43 -4
  6. package/dist/rls-db.js +212 -7
  7. package/dist/rls.d.ts +1 -1
  8. package/dist/rls.js +1 -1
  9. package/dist/scheduler.d.ts +35 -5
  10. package/dist/scheduler.js +83 -42
  11. package/dist/workflow-types.d.ts +81 -0
  12. package/dist/workflow-types.js +12 -0
  13. package/dist/workflow.d.ts +30 -0
  14. package/dist/workflow.js +157 -0
  15. package/dist/workflows-api.d.ts +13 -0
  16. package/dist/workflows-api.js +328 -0
  17. package/package.json +1 -1
  18. package/src/__tests__/crud-owner-rls.test.ts +6 -6
  19. package/src/__tests__/dist-exports.test.ts +6 -0
  20. package/src/__tests__/fixtures/basic/migrations/{0000_faithful_silver_sable.sql → 0000_last_warstar.sql} +9 -0
  21. package/src/__tests__/fixtures/basic/migrations/meta/0000_snapshot.json +60 -1
  22. package/src/__tests__/fixtures/basic/migrations/meta/_journal.json +2 -2
  23. package/src/__tests__/fixtures/basic/schema.ts +19 -3
  24. package/src/__tests__/helpers/basic-rls-fixture.ts +133 -0
  25. package/src/__tests__/helpers/test-gencow-ctx-rls.ts +1 -1
  26. package/src/__tests__/reactive.test.ts +161 -0
  27. package/src/__tests__/rls-crud-basic.test.ts +120 -161
  28. package/src/__tests__/rls-crud-no-owner-rls-pglite.test.ts +117 -0
  29. package/src/__tests__/rls-custom-mutation-handlers.test.ts +189 -0
  30. package/src/__tests__/rls-custom-query-handlers.test.ts +128 -0
  31. package/src/__tests__/rls-db-leased-connection.test.ts +122 -0
  32. package/src/__tests__/rls-session-and-policies.test.ts +246 -0
  33. package/src/__tests__/scheduler-durable-v2.test.ts +270 -0
  34. package/src/__tests__/scheduler-durable.test.ts +173 -0
  35. package/src/__tests__/workflow.test.ts +583 -0
  36. package/src/crud.ts +1 -1
  37. package/src/index.ts +6 -4
  38. package/src/reactive.ts +8 -0
  39. package/src/rls-db.ts +277 -10
  40. package/src/rls.ts +1 -1
  41. package/src/scheduler.ts +124 -46
  42. package/src/workflow-types.ts +111 -0
  43. package/src/workflow.ts +205 -0
  44. package/src/workflows-api.ts +425 -0
@@ -0,0 +1,583 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from "bun:test";
2
+ import { PGlite } from "@electric-sql/pglite";
3
+ import { drizzle } from "drizzle-orm/pglite";
4
+ import { sql } from "drizzle-orm";
5
+ import { getWorkflowResumeActionName, workflow } from "../workflow.js";
6
+ import { getQueryDef, getRegisteredMutations } from "../reactive.js";
7
+ import { v } from "../v.js";
8
+ import { registerWorkflowsApi } from "../workflows-api.js";
9
+
10
+ const WORKFLOW_TABLE_SETUP = [
11
+ `CREATE TABLE IF NOT EXISTS _gencow_workflows (
12
+ id TEXT PRIMARY KEY,
13
+ name TEXT NOT NULL,
14
+ args JSONB NOT NULL DEFAULT '{}'::jsonb,
15
+ status TEXT NOT NULL DEFAULT 'pending',
16
+ current_step TEXT,
17
+ result JSONB,
18
+ error TEXT,
19
+ realtime_token TEXT NOT NULL DEFAULT '',
20
+ retry_count INTEGER NOT NULL DEFAULT 0,
21
+ max_retries INTEGER NOT NULL DEFAULT 3,
22
+ max_duration_ms BIGINT NOT NULL DEFAULT 1800000,
23
+ started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
24
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
25
+ completed_at TIMESTAMPTZ,
26
+ user_id TEXT
27
+ )`,
28
+ `CREATE TABLE IF NOT EXISTS _gencow_workflow_steps (
29
+ id SERIAL PRIMARY KEY,
30
+ workflow_id TEXT NOT NULL REFERENCES _gencow_workflows(id) ON DELETE CASCADE,
31
+ step_name TEXT NOT NULL,
32
+ status TEXT NOT NULL DEFAULT 'pending',
33
+ output JSONB,
34
+ error TEXT,
35
+ started_at TIMESTAMPTZ,
36
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
37
+ completed_at TIMESTAMPTZ,
38
+ UNIQUE(workflow_id, step_name)
39
+ )`,
40
+ `CREATE TABLE IF NOT EXISTS _gencow_workflow_events (
41
+ id TEXT PRIMARY KEY,
42
+ workflow_id TEXT NOT NULL REFERENCES _gencow_workflows(id) ON DELETE CASCADE,
43
+ event_name TEXT NOT NULL,
44
+ payload JSONB,
45
+ received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
46
+ consumed_at TIMESTAMPTZ
47
+ )`,
48
+ ] as const;
49
+
50
+ describe("workflow()", () => {
51
+ let client: PGlite;
52
+ let db: ReturnType<typeof drizzle>;
53
+
54
+ function buildCtx(userId: string | null) {
55
+ return {
56
+ db,
57
+ unsafeDb: db,
58
+ auth: {
59
+ getUserIdentity: () => (
60
+ userId
61
+ ? { id: userId, email: `${userId}@workflow.test` }
62
+ : null
63
+ ),
64
+ requireAuth: () => {
65
+ if (!userId) throw new Error("Authentication required");
66
+ return { id: userId, email: `${userId}@workflow.test` };
67
+ },
68
+ },
69
+ storage: {} as any,
70
+ scheduler: {
71
+ runAfter: () => "unused",
72
+ runAt: () => "unused",
73
+ cancel: () => false,
74
+ cron: () => {},
75
+ registerAction: () => {},
76
+ executeAction: async () => {},
77
+ },
78
+ realtime: { emit: () => {}, refresh: () => {} },
79
+ retry: async (fn: () => Promise<unknown>) => fn(),
80
+ };
81
+ }
82
+
83
+ beforeAll(async () => {
84
+ client = new PGlite();
85
+ db = drizzle(client);
86
+ for (const stmt of WORKFLOW_TABLE_SETUP) {
87
+ await client.exec(stmt);
88
+ }
89
+ registerWorkflowsApi();
90
+ });
91
+
92
+ afterAll(async () => {
93
+ await client.close();
94
+ });
95
+
96
+ it("start mutation inserts workflow row and schedules resume action", async () => {
97
+ const name = `agents.workflowStart${Date.now()}`;
98
+ const start = workflow(name, {
99
+ args: { topic: v.string() },
100
+ handler: async () => ({ ok: true }),
101
+ });
102
+
103
+ const scheduled: Array<{ delayMs: number; action: string; args: unknown }> = [];
104
+ const result = await start.handler({
105
+ db,
106
+ unsafeDb: db,
107
+ auth: {
108
+ getUserIdentity: () => ({ id: "user_workflow_start", email: "owner@test.dev" }),
109
+ requireAuth: () => ({ id: "user_workflow_start", email: "owner@test.dev" }),
110
+ },
111
+ storage: {} as any,
112
+ scheduler: {
113
+ runAfter: (delayMs, action, args) => {
114
+ scheduled.push({ delayMs, action, args });
115
+ return "job-start-1";
116
+ },
117
+ runAt: () => "unused",
118
+ cancel: () => false,
119
+ cron: () => {},
120
+ registerAction: () => {},
121
+ executeAction: async () => {},
122
+ },
123
+ realtime: { emit: () => {}, refresh: () => {} },
124
+ retry: async (fn) => fn(),
125
+ }, { topic: "durable execution" });
126
+
127
+ expect(result.status).toBe("pending");
128
+ expect(result.name).toBe(name);
129
+ expect(result.scheduledJobId).toBe("job-start-1");
130
+ expect(scheduled).toEqual([
131
+ {
132
+ delayMs: 0,
133
+ action: getWorkflowResumeActionName(name),
134
+ args: { workflowId: result.id },
135
+ },
136
+ ]);
137
+
138
+ const rowResult = await db.execute(sql`
139
+ SELECT id, name, status, max_retries, user_id, args, realtime_token
140
+ FROM _gencow_workflows
141
+ WHERE id = ${result.id}
142
+ `);
143
+ const row = (rowResult as { rows: Array<{ id: string; name: string; status: string; max_retries: number; user_id: string | null; args: unknown; realtime_token: string }> }).rows[0];
144
+
145
+ expect(row.id).toBe(result.id);
146
+ expect(row.name).toBe(name);
147
+ expect(row.status).toBe("pending");
148
+ expect(row.max_retries).toBe(3);
149
+ expect(row.user_id).toBe("user_workflow_start");
150
+ expect(row.args).toEqual({ value: { topic: "durable execution" } });
151
+ expect(row.realtime_token.length).toBeGreaterThan(10);
152
+ });
153
+
154
+ it("scheduler enqueue failure rolls back the workflow row", async () => {
155
+ const name = `agents.workflowRollback${Date.now()}`;
156
+ const start = workflow(name, {
157
+ args: { topic: v.string() },
158
+ handler: async () => ({ ok: true }),
159
+ });
160
+
161
+ await expect(start.handler({
162
+ db,
163
+ unsafeDb: db,
164
+ auth: {
165
+ getUserIdentity: () => null,
166
+ requireAuth: () => {
167
+ throw new Error("not used");
168
+ },
169
+ },
170
+ storage: {} as any,
171
+ scheduler: {
172
+ runAfter: () => {
173
+ throw new Error("scheduler unavailable");
174
+ },
175
+ runAt: () => "unused",
176
+ cancel: () => false,
177
+ cron: () => {},
178
+ registerAction: () => {},
179
+ executeAction: async () => {},
180
+ },
181
+ realtime: { emit: () => {}, refresh: () => {} },
182
+ retry: async (fn) => fn(),
183
+ }, { topic: "should rollback" })).rejects.toThrow("scheduler unavailable");
184
+
185
+ const countResult = await db.execute(sql`
186
+ SELECT count(*)::int AS c
187
+ FROM _gencow_workflows
188
+ WHERE name = ${name}
189
+ `);
190
+ const count = (countResult as { rows: Array<{ c: number }> }).rows[0]?.c ?? 0;
191
+ expect(count).toBe(0);
192
+ });
193
+
194
+ it("workflows.get returns full snapshot for the owner and hides private workflows from others", async () => {
195
+ const getWorkflow = getQueryDef("workflows.get");
196
+ expect(getWorkflow).toBeDefined();
197
+
198
+ const workflowId = `wf_owned_${Date.now()}`;
199
+ await db.execute(sql`
200
+ INSERT INTO _gencow_workflows (
201
+ id,
202
+ name,
203
+ args,
204
+ status,
205
+ current_step,
206
+ result,
207
+ error,
208
+ retry_count,
209
+ max_retries,
210
+ max_duration_ms,
211
+ started_at,
212
+ updated_at,
213
+ completed_at,
214
+ user_id
215
+ )
216
+ VALUES (
217
+ ${workflowId},
218
+ 'agents.report',
219
+ '{"value":{"topic":"market map"}}'::jsonb,
220
+ 'running',
221
+ 'analyze',
222
+ NULL,
223
+ NULL,
224
+ 1,
225
+ 3,
226
+ 1800000,
227
+ NOW() - INTERVAL '2 minutes',
228
+ NOW() - INTERVAL '5 seconds',
229
+ NULL,
230
+ 'owner_workflow'
231
+ )
232
+ `);
233
+ await db.execute(sql`
234
+ INSERT INTO _gencow_workflow_steps (
235
+ workflow_id,
236
+ step_name,
237
+ status,
238
+ output,
239
+ error,
240
+ started_at,
241
+ updated_at,
242
+ completed_at
243
+ )
244
+ VALUES
245
+ (
246
+ ${workflowId},
247
+ 'search',
248
+ 'completed',
249
+ '{"value":{"hits":2}}'::jsonb,
250
+ NULL,
251
+ NOW() - INTERVAL '90 seconds',
252
+ NOW() - INTERVAL '80 seconds',
253
+ NOW() - INTERVAL '80 seconds'
254
+ ),
255
+ (
256
+ ${workflowId},
257
+ 'analyze',
258
+ 'running',
259
+ NULL,
260
+ NULL,
261
+ NOW() - INTERVAL '10 seconds',
262
+ NOW() - INTERVAL '5 seconds',
263
+ NULL
264
+ )
265
+ `);
266
+
267
+ const ownerSnapshot = await getWorkflow!.handler(buildCtx("owner_workflow") as any, { id: workflowId });
268
+ expect(ownerSnapshot).toMatchObject({
269
+ id: workflowId,
270
+ name: "agents.report",
271
+ status: "running",
272
+ derivedStatus: "running",
273
+ currentStep: "analyze",
274
+ args: { topic: "market map" },
275
+ result: null,
276
+ retryCount: 1,
277
+ maxRetries: 3,
278
+ });
279
+ expect(ownerSnapshot?.realtimeKey).toMatch(new RegExp(`^__gencow\\.workflow\\.state\\.${workflowId}\\.`));
280
+ expect(ownerSnapshot?.steps).toHaveLength(2);
281
+ expect(ownerSnapshot?.steps[0]).toMatchObject({
282
+ name: "search",
283
+ status: "completed",
284
+ output: { hits: 2 },
285
+ });
286
+ expect(ownerSnapshot?.steps[1]).toMatchObject({
287
+ name: "analyze",
288
+ status: "running",
289
+ output: null,
290
+ });
291
+
292
+ const strangerSnapshot = await getWorkflow!.handler(buildCtx("stranger_workflow") as any, { id: workflowId });
293
+ expect(strangerSnapshot).toBeNull();
294
+ });
295
+
296
+ it("workflows.get allows ownerless public workflows to be polled without auth", async () => {
297
+ const getWorkflow = getQueryDef("workflows.get");
298
+ expect(getWorkflow).toBeDefined();
299
+
300
+ const workflowId = `wf_public_${Date.now()}`;
301
+ await db.execute(sql`
302
+ INSERT INTO _gencow_workflows (
303
+ id,
304
+ name,
305
+ args,
306
+ status,
307
+ current_step,
308
+ result,
309
+ error,
310
+ retry_count,
311
+ max_retries,
312
+ max_duration_ms,
313
+ started_at,
314
+ updated_at,
315
+ completed_at,
316
+ user_id
317
+ )
318
+ VALUES (
319
+ ${workflowId},
320
+ 'agents.public',
321
+ '{"value":{"topic":"public"}}'::jsonb,
322
+ 'completed',
323
+ NULL,
324
+ '{"value":{"report":"done"}}'::jsonb,
325
+ NULL,
326
+ 0,
327
+ 3,
328
+ 1800000,
329
+ NOW() - INTERVAL '1 minute',
330
+ NOW() - INTERVAL '5 seconds',
331
+ NOW() - INTERVAL '5 seconds',
332
+ NULL
333
+ )
334
+ `);
335
+
336
+ const snapshot = await getWorkflow!.handler(buildCtx(null) as any, { id: workflowId });
337
+ expect(snapshot).toMatchObject({
338
+ id: workflowId,
339
+ status: "completed",
340
+ derivedStatus: "completed",
341
+ result: { report: "done" },
342
+ steps: [],
343
+ });
344
+ expect(snapshot?.realtimeKey).toMatch(new RegExp(`^__gencow\\.workflow\\.state\\.${workflowId}\\.`));
345
+ });
346
+
347
+ it("workflows.signal persists an event and wakes waiting workflows for the owner only", async () => {
348
+ const signalWorkflow = getRegisteredMutations().find((item) => item.name === "workflows.signal");
349
+ expect(signalWorkflow).toBeDefined();
350
+
351
+ const workflowId = `wf_signal_${Date.now()}`;
352
+ await db.execute(sql`
353
+ INSERT INTO _gencow_workflows (
354
+ id,
355
+ name,
356
+ args,
357
+ status,
358
+ current_step,
359
+ result,
360
+ error,
361
+ retry_count,
362
+ max_retries,
363
+ max_duration_ms,
364
+ started_at,
365
+ updated_at,
366
+ completed_at,
367
+ user_id
368
+ )
369
+ VALUES (
370
+ ${workflowId},
371
+ 'agents.waiting',
372
+ '{}'::jsonb,
373
+ 'pending',
374
+ 'wait:approval#1',
375
+ NULL,
376
+ NULL,
377
+ 0,
378
+ 3,
379
+ 1800000,
380
+ NOW() - INTERVAL '20 seconds',
381
+ NOW() - INTERVAL '5 seconds',
382
+ NULL,
383
+ 'signal_owner'
384
+ )
385
+ `);
386
+
387
+ const scheduled: Array<{ delayMs: number; action: string; args: unknown }> = [];
388
+ const accepted = await signalWorkflow!.handler({
389
+ ...buildCtx("signal_owner"),
390
+ scheduler: {
391
+ runAfter: (delayMs, action, args) => {
392
+ scheduled.push({ delayMs, action, args });
393
+ return "job-signal-1";
394
+ },
395
+ runAt: () => "unused",
396
+ cancel: () => false,
397
+ cron: () => {},
398
+ registerAction: () => {},
399
+ executeAction: async () => {},
400
+ },
401
+ } as any, {
402
+ id: workflowId,
403
+ event: "approval",
404
+ payload: { approved: true },
405
+ });
406
+
407
+ expect(accepted).toEqual({
408
+ ok: true,
409
+ workflowId,
410
+ event: "approval",
411
+ scheduledJobId: "job-signal-1",
412
+ });
413
+ expect(scheduled).toEqual([
414
+ {
415
+ delayMs: 0,
416
+ action: getWorkflowResumeActionName("agents.waiting"),
417
+ args: { workflowId },
418
+ },
419
+ ]);
420
+
421
+ const eventResult = await db.execute(sql`
422
+ SELECT workflow_id, event_name, payload, consumed_at IS NULL AS is_unconsumed
423
+ FROM _gencow_workflow_events
424
+ WHERE workflow_id = ${workflowId}
425
+ `);
426
+ const eventRow = (eventResult as {
427
+ rows: Array<{
428
+ workflow_id: string;
429
+ event_name: string;
430
+ payload: unknown;
431
+ is_unconsumed: boolean;
432
+ }>;
433
+ }).rows[0];
434
+ expect(eventRow).toEqual({
435
+ workflow_id: workflowId,
436
+ event_name: "approval",
437
+ payload: { value: { approved: true } },
438
+ is_unconsumed: true,
439
+ });
440
+
441
+ const denied = await signalWorkflow!.handler(buildCtx("someone_else") as any, {
442
+ id: workflowId,
443
+ event: "approval",
444
+ payload: { approved: false },
445
+ });
446
+ expect(denied).toEqual({
447
+ ok: false,
448
+ workflowId,
449
+ event: "approval",
450
+ scheduledJobId: null,
451
+ });
452
+ });
453
+
454
+ it("workflows.list requires auth and filters to the current owner", async () => {
455
+ const listWorkflows = getQueryDef("workflows.list");
456
+ expect(listWorkflows).toBeDefined();
457
+
458
+ const userACompleted = `wf_user_a_completed_${Date.now()}`;
459
+ const userAWaiting = `wf_user_a_waiting_${Date.now()}`;
460
+ const userASleeping = `wf_user_a_sleeping_${Date.now()}`;
461
+ const userBRunning = `wf_user_b_running_${Date.now()}`;
462
+
463
+ await db.execute(sql`
464
+ INSERT INTO _gencow_workflows (
465
+ id,
466
+ name,
467
+ args,
468
+ status,
469
+ current_step,
470
+ result,
471
+ error,
472
+ retry_count,
473
+ max_retries,
474
+ max_duration_ms,
475
+ started_at,
476
+ updated_at,
477
+ completed_at,
478
+ user_id
479
+ )
480
+ VALUES
481
+ (
482
+ ${userACompleted},
483
+ 'agents.sync',
484
+ '{}'::jsonb,
485
+ 'completed',
486
+ NULL,
487
+ NULL,
488
+ NULL,
489
+ 0,
490
+ 3,
491
+ 1800000,
492
+ NOW() - INTERVAL '30 seconds',
493
+ NOW() - INTERVAL '20 seconds',
494
+ NOW() - INTERVAL '20 seconds',
495
+ 'workflow_user_a'
496
+ ),
497
+ (
498
+ ${userAWaiting},
499
+ 'agents.sync',
500
+ '{}'::jsonb,
501
+ 'pending',
502
+ 'wait:approval#1',
503
+ NULL,
504
+ NULL,
505
+ 0,
506
+ 3,
507
+ 1800000,
508
+ NOW() - INTERVAL '10 seconds',
509
+ NOW() - INTERVAL '10 seconds',
510
+ NULL,
511
+ 'workflow_user_a'
512
+ ),
513
+ (
514
+ ${userASleeping},
515
+ 'agents.sync',
516
+ '{}'::jsonb,
517
+ 'pending',
518
+ 'sleep#1',
519
+ NULL,
520
+ NULL,
521
+ 0,
522
+ 3,
523
+ 1800000,
524
+ NOW() - INTERVAL '15 seconds',
525
+ NOW() - INTERVAL '12 seconds',
526
+ NULL,
527
+ 'workflow_user_a'
528
+ ),
529
+ (
530
+ ${userBRunning},
531
+ 'agents.sync',
532
+ '{}'::jsonb,
533
+ 'running',
534
+ 'analyze',
535
+ NULL,
536
+ NULL,
537
+ 0,
538
+ 3,
539
+ 1800000,
540
+ NOW() - INTERVAL '5 seconds',
541
+ NOW() - INTERVAL '5 seconds',
542
+ NULL,
543
+ 'workflow_user_b'
544
+ )
545
+ `);
546
+
547
+ const ownWorkflows = await listWorkflows!.handler(buildCtx("workflow_user_a") as any, { limit: 10 });
548
+ expect(ownWorkflows.map((item: any) => item.id)).toEqual([userAWaiting, userASleeping, userACompleted]);
549
+ expect(ownWorkflows.every((item: any) => item.name === "agents.sync")).toBe(true);
550
+ expect(ownWorkflows.some((item: any) => item.id === userBRunning)).toBe(false);
551
+ expect(ownWorkflows.find((item: any) => item.id === userAWaiting)?.derivedStatus).toBe("waiting");
552
+ expect(ownWorkflows.find((item: any) => item.id === userASleeping)?.derivedStatus).toBe("sleeping");
553
+
554
+ const completedOnly = await listWorkflows!.handler(
555
+ buildCtx("workflow_user_a") as any,
556
+ { limit: 10, status: "completed" }
557
+ );
558
+ expect(completedOnly).toHaveLength(1);
559
+ expect(completedOnly[0]?.id).toBe(userACompleted);
560
+
561
+ const waitingOnly = await listWorkflows!.handler(
562
+ buildCtx("workflow_user_a") as any,
563
+ { limit: 10, status: "waiting" }
564
+ );
565
+ expect(waitingOnly).toHaveLength(1);
566
+ expect(waitingOnly[0]?.id).toBe(userAWaiting);
567
+
568
+ const sleepingOnly = await listWorkflows!.handler(
569
+ buildCtx("workflow_user_a") as any,
570
+ { limit: 10, status: "sleeping" }
571
+ );
572
+ expect(sleepingOnly).toHaveLength(1);
573
+ expect(sleepingOnly[0]?.id).toBe(userASleeping);
574
+
575
+ await expect(
576
+ listWorkflows!.handler(buildCtx(null) as any, { limit: 10 })
577
+ ).rejects.toThrow("Authentication required");
578
+
579
+ await expect(
580
+ listWorkflows!.handler(buildCtx("workflow_user_a") as any, { limit: 10, status: "mystery" })
581
+ ).rejects.toThrow('Argument "status": expected one of pending, running, completed, failed');
582
+ });
583
+ });
package/src/crud.ts CHANGED
@@ -412,7 +412,7 @@ export function crud<T extends PgTable>(table: T, options?: CrudOptions<T>) {
412
412
  }
413
413
 
414
414
  // ── 내부 헬퍼: list+count 데이터 가져오기 (realtime push용 재사용) ──
415
- // Runs inside db.transaction so createRlsDb() can SET LOCAL app.current_user_id for RLS.
415
+ // Runs inside db.transaction so createRlsDb() RLS session vars apply for RLS.
416
416
  // ⚠️ limit/offset 없이 전체 SELECT — 대량 데이터 시 성능 저하 주의
417
417
  // TODO(P2): realtime emit 시 invalidation 메시지만 전송하고 클라이언트가 re-fetch하는 패턴 검토
418
418
  async function fetchListWithTotal(db: any, whereClause?: SQL, userId?: string) {
package/src/index.ts CHANGED
@@ -9,7 +9,11 @@ export type { GencowCtx, AuthCtx, UserIdentity, QueryDef, MutationDef, RealtimeC
9
9
  export { query, mutation, httpAction, buildRealtimeCtx, subscribe, unsubscribe, registerClient, deregisterClient, handleWsMessage, getQueryHandler, getQueryDef, getRegisteredQueries, getRegisteredMutations, getRegisteredHttpActions } from "./reactive.js";
10
10
  export type { Storage } from "./storage.js";
11
11
  export { createScheduler, getSchedulerInfo } from "./scheduler.js";
12
- export type { Scheduler, ScheduleOptions, FailedJob } from "./scheduler.js";
12
+ export type { Scheduler, ScheduleOptions, FailedJob, CreateSchedulerOptions, ScheduledJobRecord } from "./scheduler.js";
13
+ export { workflow, getWorkflowDef, getRegisteredWorkflows, getWorkflowResumeActionName, getWorkflowRealtimeKey, createWorkflowRealtimeToken, serializeWorkflowValue, deserializeWorkflowValue, parseWorkflowDurationMs, DEFAULT_WORKFLOW_MAX_DURATION_MS, DEFAULT_WORKFLOW_MAX_RETRIES, WORKFLOW_RESUME_ACTION_PREFIX, WORKFLOW_REALTIME_KEY_PREFIX } from "./workflow.js";
14
+ export { deriveWorkflowStatus } from "./workflow-types.js";
15
+ export type { WorkflowCtx, WorkflowHandler, WorkflowOptions, WorkflowDef, WorkflowResumePayload, WorkflowStartResult, WorkflowSignalResult, WorkflowStatus, WorkflowDerivedStatus, WorkflowSummary, WorkflowSnapshot, WorkflowStepSnapshot, WorkflowListArgs, WorkflowDuration } from "./workflow-types.js";
16
+ export { loadWorkflowSnapshot } from "./workflows-api.js";
13
17
  export { v, parseArgs, GencowValidationError } from "./v.js";
14
18
  export type { Validator, Infer, InferArgs } from "./v.js";
15
19
  export { withRetry } from "./retry.js";
@@ -23,10 +27,8 @@ export type { GencowAuthConfig, AuthEmailVerification } from "./auth-config.js";
23
27
  export { ownerRls, getOwnerRlsMeta, registerOwnerRls } from "./rls.js";
24
28
  export type { OwnerRlsMeta } from "./rls.js";
25
29
  export { createRlsDb } from "./rls-db.js";
30
+ export type { RlsSessionContext } from "./rls-db.js";
26
31
  export { crud, parseFilterNode, applyFilterOp, getOwnerRlsTables } from "./crud.js";
27
32
 
28
33
  // Deprecated alias — 하위호환용, 향후 메이저 버전에서 제거 예정
29
34
  export { crud as gencowCrud } from "./crud.js";
30
-
31
-
32
-
package/src/reactive.ts CHANGED
@@ -477,6 +477,14 @@ export function buildRealtimeCtx(options?: {
477
477
  }
478
478
  try {
479
479
  // refresh용 ctx 생성 (mutation ctx와 동일한 DB/auth 스코프)
480
+ if (!options?.buildCtxForRefresh) {
481
+ console.warn(
482
+ `[gencow] ⚠️ refresh("${key}"): buildCtxForRefresh not provided. ` +
483
+ `Query handler will receive an empty ctx — ctx.db will be undefined. ` +
484
+ `This is a framework configuration error. ` +
485
+ `💡 Ensure buildRealtimeCtx() receives a buildCtxForRefresh callback.`
486
+ );
487
+ }
480
488
  const refreshCtx = options?.buildCtxForRefresh?.() ?? ({} as GencowCtx);
481
489
  const result = await queryDef.handler(refreshCtx, {});
482
490