@yieldstar/sqlite-runtime 0.5.0 → 0.6.1

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 (83) hide show
  1. package/dist/bun.js +15 -17
  2. package/dist/dao/effect-waiters-dao.d.ts +19 -0
  3. package/dist/dao/effect-waiters-dao.d.ts.map +1 -0
  4. package/dist/dao/effects-dao.d.ts +17 -0
  5. package/dist/dao/effects-dao.d.ts.map +1 -0
  6. package/dist/dao/executions-dao.d.ts +24 -0
  7. package/dist/dao/executions-dao.d.ts.map +1 -0
  8. package/dist/dao/start-requests-dao.d.ts +15 -0
  9. package/dist/dao/start-requests-dao.d.ts.map +1 -0
  10. package/dist/dao/step-response-dao.d.ts +1 -0
  11. package/dist/dao/step-response-dao.d.ts.map +1 -1
  12. package/dist/dao/store-waiters-dao.d.ts +26 -0
  13. package/dist/dao/store-waiters-dao.d.ts.map +1 -0
  14. package/dist/index-083bmj5k.js +800 -0
  15. package/dist/index-4kybaxga.js +798 -0
  16. package/dist/index-a8thbaee.js +718 -0
  17. package/dist/index-ag93sv33.js +664 -0
  18. package/dist/index-eabcgmaa.js +996 -0
  19. package/dist/index-ekggxe8v.js +987 -0
  20. package/dist/index-gjfs8rn6.js +997 -0
  21. package/dist/index-h3h7r4b6.js +981 -0
  22. package/dist/index-ma984fze.js +718 -0
  23. package/dist/index-ne28djfn.js +718 -0
  24. package/dist/index-t60e4kvz.js +988 -0
  25. package/dist/index-v6rn0pr6.js +664 -0
  26. package/dist/index-wx6vk994.js +669 -0
  27. package/dist/index.d.ts +3 -4
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +11 -13
  30. package/dist/node.js +15 -17
  31. package/dist/sqlite-effect.d.ts +30 -0
  32. package/dist/sqlite-effect.d.ts.map +1 -0
  33. package/dist/sqlite-execution.d.ts +55 -0
  34. package/dist/sqlite-execution.d.ts.map +1 -0
  35. package/dist/sqlite-heap.d.ts +12 -4
  36. package/dist/sqlite-heap.d.ts.map +1 -1
  37. package/dist/sqlite-runtime.d.ts +22 -0
  38. package/dist/sqlite-runtime.d.ts.map +1 -0
  39. package/dist/sqlite-store.d.ts +31 -25
  40. package/dist/sqlite-store.d.ts.map +1 -1
  41. package/dist/sqlite-transaction.d.ts +9 -0
  42. package/dist/sqlite-transaction.d.ts.map +1 -0
  43. package/package.json +2 -2
  44. package/src/dao/effect-waiters-dao.ts +63 -0
  45. package/src/dao/effects-dao.ts +123 -0
  46. package/src/dao/executions-dao.ts +199 -0
  47. package/src/dao/start-requests-dao.ts +72 -0
  48. package/src/dao/step-response-dao.ts +16 -1
  49. package/src/dao/store-waiters-dao.ts +92 -0
  50. package/src/index.ts +6 -4
  51. package/src/sqlite-effect.ts +99 -0
  52. package/src/sqlite-execution.ts +242 -0
  53. package/src/sqlite-heap.ts +64 -12
  54. package/src/sqlite-runtime.ts +36 -0
  55. package/src/sqlite-store.ts +184 -520
  56. package/src/sqlite-transaction.ts +19 -0
  57. package/dist/dao/task-queue-dao.d.ts +0 -21
  58. package/dist/dao/task-queue-dao.d.ts.map +0 -1
  59. package/dist/dao/timers-dao.d.ts +0 -22
  60. package/dist/dao/timers-dao.d.ts.map +0 -1
  61. package/dist/index-4vq70w0r.js +0 -796
  62. package/dist/index-s8wqgfwt.js +0 -19
  63. package/dist/index-x891hxwg.js +0 -796
  64. package/dist/node-driver.d.ts +0 -10
  65. package/dist/node-driver.d.ts.map +0 -1
  66. package/dist/sqlite-event-loop.d.ts +0 -18
  67. package/dist/sqlite-event-loop.d.ts.map +0 -1
  68. package/dist/sqlite-scheduler.d.ts +0 -13
  69. package/dist/sqlite-scheduler.d.ts.map +0 -1
  70. package/dist/sqlite-store.test.d.ts +0 -2
  71. package/dist/sqlite-store.test.d.ts.map +0 -1
  72. package/dist/sqlite-task-queue.d.ts +0 -26
  73. package/dist/sqlite-task-queue.d.ts.map +0 -1
  74. package/dist/sqlite-timers.d.ts +0 -18
  75. package/dist/sqlite-timers.d.ts.map +0 -1
  76. package/src/dao/task-queue-dao.ts +0 -79
  77. package/src/dao/timers-dao.ts +0 -81
  78. package/src/sqlite-event-loop.ts +0 -41
  79. package/src/sqlite-scheduler.ts +0 -24
  80. package/src/sqlite-task-queue.ts +0 -64
  81. package/src/sqlite-timers.ts +0 -40
  82. package/tsconfig.tsbuildinfo +0 -1
  83. /package/dist/{index-h7bm9xg4.js → index-dapqh99v.js} +0 -0
@@ -0,0 +1,997 @@
1
+ // src/sqlite-runtime.ts
2
+ import { Runtime } from "@yieldstar/core";
3
+
4
+ // src/sqlite-effect.ts
5
+ import {
6
+ createEffectState,
7
+ effectNotFound,
8
+ matchEffectBegin,
9
+ prepareEffectBegin,
10
+ prepareEffectSettle,
11
+ prepareEffectWatch,
12
+ settleEffect,
13
+ toEffectRecord
14
+ } from "@yieldstar/core";
15
+
16
+ // src/dao/effect-waiters-dao.ts
17
+ class EffectWaitersDao {
18
+ db;
19
+ constructor(db) {
20
+ this.db = db;
21
+ this.setupDb();
22
+ }
23
+ setupDb() {
24
+ this.db.run(`
25
+ CREATE TABLE IF NOT EXISTS effect_waiters (
26
+ effect_id TEXT NOT NULL,
27
+ execution_id TEXT NOT NULL,
28
+ step_key TEXT NOT NULL,
29
+ PRIMARY KEY (effect_id, execution_id, step_key)
30
+ );
31
+ CREATE INDEX IF NOT EXISTS idx_effect_waiters_step
32
+ ON effect_waiters(execution_id, step_key);
33
+ `);
34
+ }
35
+ upsertWaiter(waiter) {
36
+ this.db.query(`INSERT INTO effect_waiters (effect_id, execution_id, step_key)
37
+ VALUES ($effectId, $executionId, $stepKey)
38
+ ON CONFLICT(effect_id, execution_id, step_key) DO NOTHING`).run({
39
+ $effectId: waiter.effectId,
40
+ $executionId: waiter.executionId,
41
+ $stepKey: waiter.stepKey
42
+ });
43
+ }
44
+ getWaitingExecutionIds(effectId) {
45
+ return this.db.query(`SELECT DISTINCT execution_id FROM effect_waiters WHERE effect_id = $effectId`).all({ $effectId: effectId }).map((row) => row.execution_id);
46
+ }
47
+ deleteStepWaiters(executionId, stepKey) {
48
+ this.db.query(`DELETE FROM effect_waiters WHERE execution_id = $executionId AND step_key = $stepKey`).run({ $executionId: executionId, $stepKey: stepKey });
49
+ }
50
+ }
51
+
52
+ // src/dao/effects-dao.ts
53
+ class EffectsDao {
54
+ db;
55
+ constructor(db) {
56
+ this.db = db;
57
+ this.setupDb();
58
+ }
59
+ setupDb() {
60
+ this.db.run(`
61
+ CREATE TABLE IF NOT EXISTS effects (
62
+ effect_id TEXT PRIMARY KEY,
63
+ operation TEXT NOT NULL,
64
+ input TEXT NOT NULL,
65
+ status TEXT NOT NULL,
66
+ result TEXT
67
+ );
68
+ CREATE TABLE IF NOT EXISTS effect_conflicts (
69
+ effect_id TEXT NOT NULL,
70
+ result TEXT NOT NULL,
71
+ conflicting_result TEXT NOT NULL,
72
+ reported_at INTEGER NOT NULL,
73
+ PRIMARY KEY (effect_id, conflicting_result)
74
+ );
75
+ `);
76
+ }
77
+ getState(effectId) {
78
+ const row = this.db.query(`SELECT * FROM effects WHERE effect_id = $effectId`).get({ $effectId: effectId });
79
+ if (!row)
80
+ return;
81
+ const conflicts = this.db.query(`SELECT result, conflicting_result, reported_at FROM effect_conflicts
82
+ WHERE effect_id = $effectId
83
+ ORDER BY reported_at, rowid`).all({ $effectId: effectId });
84
+ const state = {
85
+ effectId: row.effect_id,
86
+ operation: row.operation,
87
+ input: row.input,
88
+ status: row.status,
89
+ conflicts: conflicts.map((conflict) => ({
90
+ result: conflict.result,
91
+ conflictingResult: conflict.conflicting_result,
92
+ reportedAt: conflict.reported_at
93
+ }))
94
+ };
95
+ if (row.result !== null)
96
+ state.result = row.result;
97
+ return state;
98
+ }
99
+ insertState(state) {
100
+ this.db.query(`INSERT INTO effects (effect_id, operation, input, status, result)
101
+ VALUES ($effectId, $operation, $input, $status, $result)`).run({
102
+ $effectId: state.effectId,
103
+ $operation: state.operation,
104
+ $input: state.input,
105
+ $status: state.status,
106
+ $result: state.result ?? null
107
+ });
108
+ }
109
+ updateState(before, after) {
110
+ if (before.status !== after.status || before.result !== after.result) {
111
+ this.db.query(`UPDATE effects SET status = $status, result = $result
112
+ WHERE effect_id = $effectId`).run({
113
+ $effectId: after.effectId,
114
+ $status: after.status,
115
+ $result: after.result ?? null
116
+ });
117
+ }
118
+ for (const conflict of after.conflicts.slice(before.conflicts.length)) {
119
+ this.insertConflict(after.effectId, conflict);
120
+ }
121
+ }
122
+ insertConflict(effectId, conflict) {
123
+ this.db.query(`INSERT INTO effect_conflicts (effect_id, result, conflicting_result, reported_at)
124
+ VALUES ($effectId, $result, $conflictingResult, $reportedAt)`).run({
125
+ $effectId: effectId,
126
+ $result: conflict.result,
127
+ $conflictingResult: conflict.conflictingResult,
128
+ $reportedAt: conflict.reportedAt
129
+ });
130
+ }
131
+ }
132
+
133
+ // src/sqlite-execution.ts
134
+ import {
135
+ acknowledgeExecution,
136
+ claimExecution,
137
+ createExecutionState,
138
+ createStartedExecution,
139
+ executionIdConflict,
140
+ executionNotFound,
141
+ isExecutionClaimable,
142
+ matchStartRequest,
143
+ prepareExecutionAdmission,
144
+ prepareExecutionStart,
145
+ releaseExecutionLease,
146
+ renewExecutionLease,
147
+ requestExecutionWake,
148
+ toExecutionRecord
149
+ } from "@yieldstar/core";
150
+
151
+ // src/dao/executions-dao.ts
152
+ import { nextClaimAt } from "@yieldstar/core";
153
+ class ExecutionsDao {
154
+ db;
155
+ constructor(db) {
156
+ this.db = db;
157
+ this.setupDb();
158
+ }
159
+ setupDb() {
160
+ this.db.run(`
161
+ CREATE TABLE IF NOT EXISTS executions (
162
+ execution_id TEXT PRIMARY KEY,
163
+ workflow_id TEXT NOT NULL,
164
+ params TEXT NOT NULL,
165
+ context TEXT NOT NULL,
166
+ status TEXT NOT NULL,
167
+ outcome TEXT,
168
+ admitted_at INTEGER NOT NULL,
169
+ updated_at INTEGER NOT NULL,
170
+ due_at INTEGER,
171
+ claimed_due_at INTEGER,
172
+ lease_token INTEGER NOT NULL DEFAULT 0,
173
+ lease_expires_at INTEGER,
174
+ unacknowledged_delivery_count INTEGER NOT NULL DEFAULT 0,
175
+ redeliver_at INTEGER,
176
+ next_claim_at INTEGER,
177
+ parent_execution_id TEXT,
178
+ parent_step_key TEXT
179
+ );
180
+ CREATE INDEX IF NOT EXISTS idx_executions_next_claim_at
181
+ ON executions(next_claim_at) WHERE next_claim_at IS NOT NULL;
182
+ `);
183
+ }
184
+ getState(executionId) {
185
+ const row = this.db.query(`SELECT * FROM executions WHERE execution_id = $executionId`).get({ $executionId: executionId });
186
+ return row ? toState(row) : undefined;
187
+ }
188
+ getClaimableIds(now, limit) {
189
+ return this.db.query(`SELECT execution_id FROM executions
190
+ WHERE next_claim_at IS NOT NULL AND next_claim_at <= $now
191
+ ORDER BY next_claim_at, execution_id
192
+ LIMIT $limit`).all({ $now: now, $limit: limit }).map((row) => row.execution_id);
193
+ }
194
+ insertState(state) {
195
+ const result = this.db.query(`INSERT INTO executions (
196
+ execution_id, workflow_id, params, context, status, outcome,
197
+ admitted_at, updated_at, due_at, claimed_due_at, lease_token,
198
+ lease_expires_at, unacknowledged_delivery_count, redeliver_at,
199
+ next_claim_at, parent_execution_id, parent_step_key
200
+ ) VALUES (
201
+ $executionId, $workflowId, $params, $context, $status, $outcome,
202
+ $admittedAt, $updatedAt, $dueAt, $claimedDueAt, $leaseToken,
203
+ $leaseExpiresAt, $unacknowledgedDeliveryCount, $redeliverAt,
204
+ $nextClaimAt, $parentExecutionId, $parentStepKey
205
+ )
206
+ ON CONFLICT(execution_id) DO NOTHING`).run({
207
+ ...toBindings(state),
208
+ $parentExecutionId: state.parent?.executionId ?? null,
209
+ $parentStepKey: state.parent?.stepKey ?? null
210
+ });
211
+ return Number(result.changes) === 1;
212
+ }
213
+ updateState(state) {
214
+ this.db.query(`UPDATE executions SET
215
+ workflow_id = $workflowId,
216
+ params = $params,
217
+ context = $context,
218
+ status = $status,
219
+ outcome = $outcome,
220
+ admitted_at = $admittedAt,
221
+ updated_at = $updatedAt,
222
+ due_at = $dueAt,
223
+ claimed_due_at = $claimedDueAt,
224
+ lease_token = $leaseToken,
225
+ lease_expires_at = $leaseExpiresAt,
226
+ unacknowledged_delivery_count = $unacknowledgedDeliveryCount,
227
+ redeliver_at = $redeliverAt,
228
+ next_claim_at = $nextClaimAt
229
+ WHERE execution_id = $executionId`).run(toBindings(state));
230
+ }
231
+ }
232
+ function toState(row) {
233
+ return {
234
+ executionId: row.execution_id,
235
+ workflowId: row.workflow_id,
236
+ params: row.params,
237
+ context: row.context,
238
+ status: row.status,
239
+ outcome: row.outcome,
240
+ admittedAt: Number(row.admitted_at),
241
+ updatedAt: Number(row.updated_at),
242
+ dueAt: toNumberOrNull(row.due_at),
243
+ claimedDueAt: toNumberOrNull(row.claimed_due_at),
244
+ leaseToken: Number(row.lease_token),
245
+ leaseExpiresAt: toNumberOrNull(row.lease_expires_at),
246
+ unacknowledgedDeliveryCount: Number(row.unacknowledged_delivery_count),
247
+ redeliverAt: toNumberOrNull(row.redeliver_at),
248
+ parent: row.parent_execution_id !== null && row.parent_step_key !== null ? { executionId: row.parent_execution_id, stepKey: row.parent_step_key } : null
249
+ };
250
+ }
251
+ function toBindings(state) {
252
+ return {
253
+ $executionId: state.executionId,
254
+ $workflowId: state.workflowId,
255
+ $params: state.params,
256
+ $context: state.context,
257
+ $status: state.status,
258
+ $outcome: state.outcome,
259
+ $admittedAt: state.admittedAt,
260
+ $updatedAt: state.updatedAt,
261
+ $dueAt: state.dueAt,
262
+ $claimedDueAt: state.claimedDueAt,
263
+ $leaseToken: state.leaseToken,
264
+ $leaseExpiresAt: state.leaseExpiresAt,
265
+ $unacknowledgedDeliveryCount: state.unacknowledgedDeliveryCount,
266
+ $redeliverAt: state.redeliverAt,
267
+ $nextClaimAt: nextClaimAt(state)
268
+ };
269
+ }
270
+ function toNumberOrNull(value) {
271
+ return value === null ? null : Number(value);
272
+ }
273
+
274
+ // src/dao/start-requests-dao.ts
275
+ class StartRequestsDao {
276
+ db;
277
+ constructor(db) {
278
+ this.db = db;
279
+ this.setupDb();
280
+ }
281
+ setupDb() {
282
+ this.db.run(`
283
+ CREATE TABLE IF NOT EXISTS start_requests (
284
+ caller_execution_id TEXT NOT NULL,
285
+ step_key TEXT NOT NULL,
286
+ workflow_id TEXT NOT NULL,
287
+ params TEXT,
288
+ execution_id TEXT NOT NULL,
289
+ PRIMARY KEY (caller_execution_id, step_key)
290
+ );
291
+ `);
292
+ }
293
+ get(callerExecutionId, stepKey) {
294
+ const row = this.db.query(`SELECT * FROM start_requests
295
+ WHERE caller_execution_id = $callerExecutionId AND step_key = $stepKey`).get({ $callerExecutionId: callerExecutionId, $stepKey: stepKey });
296
+ return row ? {
297
+ callerExecutionId: row.caller_execution_id,
298
+ stepKey: row.step_key,
299
+ workflowId: row.workflow_id,
300
+ params: row.params,
301
+ executionId: row.execution_id
302
+ } : undefined;
303
+ }
304
+ insert(request) {
305
+ this.db.query(`INSERT INTO start_requests
306
+ (caller_execution_id, step_key, workflow_id, params, execution_id)
307
+ VALUES
308
+ ($callerExecutionId, $stepKey, $workflowId, $params, $executionId)`).run({
309
+ $callerExecutionId: request.callerExecutionId,
310
+ $stepKey: request.stepKey,
311
+ $workflowId: request.workflowId,
312
+ $params: request.params,
313
+ $executionId: request.executionId
314
+ });
315
+ }
316
+ }
317
+
318
+ // src/sqlite-transaction.ts
319
+ function runTransaction(db, fn) {
320
+ db.run("BEGIN IMMEDIATE");
321
+ try {
322
+ const result = fn();
323
+ db.run("COMMIT");
324
+ return result;
325
+ } catch (err) {
326
+ db.run("ROLLBACK");
327
+ throw err;
328
+ }
329
+ }
330
+
331
+ // src/sqlite-execution.ts
332
+ class SqliteExecutionClient2 {
333
+ db;
334
+ executionsDao;
335
+ startRequestsDao;
336
+ clock;
337
+ constructor(db, options = {}) {
338
+ this.db = db;
339
+ this.executionsDao = new ExecutionsDao(db);
340
+ this.startRequestsDao = new StartRequestsDao(db);
341
+ this.clock = options.clock ?? (() => Date.now());
342
+ }
343
+ async admit(request) {
344
+ const prepared = prepareExecutionAdmission(request);
345
+ if (!prepared.ok) {
346
+ return {
347
+ status: "rejected",
348
+ code: prepared.code,
349
+ message: prepared.message
350
+ };
351
+ }
352
+ return runTransaction(this.db, () => {
353
+ const state = createExecutionState({
354
+ executionId: prepared.executionId,
355
+ workflowId: request.workflowId,
356
+ encoded: prepared.encoded,
357
+ now: this.clock()
358
+ });
359
+ if (!this.executionsDao.insertState(state)) {
360
+ return executionIdConflict(prepared.executionId);
361
+ }
362
+ return { status: "accepted", executionId: prepared.executionId };
363
+ });
364
+ }
365
+ async start(request) {
366
+ const prepared = prepareExecutionStart(request);
367
+ if (!prepared.ok)
368
+ return prepared.result;
369
+ const { start } = prepared;
370
+ return runTransaction(this.db, () => {
371
+ const recorded = this.startRequestsDao.get(start.callerExecutionId, start.stepKey);
372
+ if (recorded)
373
+ return matchStartRequest(recorded, start);
374
+ const caller = this.executionsDao.getState(start.callerExecutionId);
375
+ if (!caller) {
376
+ throw new Error(`Cannot start a workflow from execution "${start.callerExecutionId}": it does not exist`);
377
+ }
378
+ let created = createStartedExecution({ start, caller, now: this.clock() });
379
+ while (!this.executionsDao.insertState(created.target)) {
380
+ created = createStartedExecution({ start, caller, now: this.clock() });
381
+ }
382
+ this.startRequestsDao.insert(created.startRequest);
383
+ return {
384
+ status: "accepted",
385
+ executionId: created.target.executionId
386
+ };
387
+ });
388
+ }
389
+ async get(executionId) {
390
+ const state = this.executionsDao.getState(executionId);
391
+ return state ? toExecutionRecord(state, this.clock()) : undefined;
392
+ }
393
+ async requestWake(request) {
394
+ return runTransaction(this.db, () => {
395
+ const state = this.executionsDao.getState(request.executionId);
396
+ if (!state)
397
+ return executionNotFound(request.executionId);
398
+ const next = requestExecutionWake(state, request.wakeAt, this.clock());
399
+ if (!next)
400
+ return { status: "ignored" };
401
+ this.executionsDao.updateState(next);
402
+ return { status: "requested" };
403
+ });
404
+ }
405
+ async claimDue(request) {
406
+ if (request.limit <= 0)
407
+ return [];
408
+ return runTransaction(this.db, () => {
409
+ const now = this.clock();
410
+ const leases = [];
411
+ for (const executionId of this.executionsDao.getClaimableIds(now, request.limit)) {
412
+ const state = this.executionsDao.getState(executionId);
413
+ if (!state || !isExecutionClaimable(state, now))
414
+ continue;
415
+ const claimed = claimExecution(state, {
416
+ now,
417
+ duration: request.duration
418
+ });
419
+ this.executionsDao.updateState(claimed.state);
420
+ leases.push(claimed.lease);
421
+ }
422
+ return leases;
423
+ });
424
+ }
425
+ async renew(request) {
426
+ return this.transition(request.lease, (state) => renewExecutionLease(state, {
427
+ lease: request.lease,
428
+ duration: request.duration,
429
+ now: this.clock()
430
+ }));
431
+ }
432
+ async release(request) {
433
+ return this.transition(request.lease, (state) => releaseExecutionLease(state, { lease: request.lease, now: this.clock() }));
434
+ }
435
+ async acknowledge(request) {
436
+ return this.transition(request.lease, (state) => acknowledgeExecution(state, {
437
+ lease: request.lease,
438
+ outcome: request.outcome,
439
+ now: this.clock()
440
+ }));
441
+ }
442
+ transition(lease, fn) {
443
+ return Promise.resolve(runTransaction(this.db, () => {
444
+ const state = this.executionsDao.getState(lease.executionId);
445
+ if (!state)
446
+ return { status: "lost" };
447
+ const next = fn(state);
448
+ if (next.state !== state)
449
+ this.executionsDao.updateState(next.state);
450
+ return next.result;
451
+ }));
452
+ }
453
+ wakeInTransaction(executionId, wakeAt = this.clock()) {
454
+ const state = this.executionsDao.getState(executionId);
455
+ if (!state)
456
+ return;
457
+ const next = requestExecutionWake(state, wakeAt, this.clock());
458
+ if (next)
459
+ this.executionsDao.updateState(next);
460
+ }
461
+ }
462
+
463
+ // src/sqlite-effect.ts
464
+ class SqliteEffectClient2 {
465
+ db;
466
+ executions;
467
+ effectsDao;
468
+ effectWaitersDao;
469
+ clock;
470
+ constructor(params) {
471
+ this.db = params.db;
472
+ this.clock = params.clock ?? (() => Date.now());
473
+ this.executions = params.executions ?? new SqliteExecutionClient2(params.db, { clock: this.clock });
474
+ this.effectsDao = new EffectsDao(params.db);
475
+ this.effectWaitersDao = new EffectWaitersDao(params.db);
476
+ }
477
+ async begin(request) {
478
+ const begin = prepareEffectBegin(request);
479
+ return runTransaction(this.db, () => {
480
+ const state = this.effectsDao.getState(begin.effectId);
481
+ if (state)
482
+ return matchEffectBegin(state, begin);
483
+ this.effectsDao.insertState(createEffectState(begin));
484
+ return { status: "new" };
485
+ });
486
+ }
487
+ async settle(request) {
488
+ const settle = prepareEffectSettle(request);
489
+ return runTransaction(this.db, () => {
490
+ const state = this.effectsDao.getState(settle.effectId);
491
+ if (!state)
492
+ throw effectNotFound(settle.effectId);
493
+ const settled = settleEffect(state, settle, this.clock());
494
+ if (settled.state !== state)
495
+ this.effectsDao.updateState(state, settled.state);
496
+ if (settled.wake) {
497
+ for (const executionId of this.effectWaitersDao.getWaitingExecutionIds(settle.effectId)) {
498
+ this.executions.wakeInTransaction(executionId);
499
+ }
500
+ }
501
+ return settled.result;
502
+ });
503
+ }
504
+ async watch(request) {
505
+ const watch = prepareEffectWatch(request);
506
+ runTransaction(this.db, () => {
507
+ const state = this.effectsDao.getState(watch.effectId);
508
+ if (!state)
509
+ throw effectNotFound(watch.effectId);
510
+ this.effectWaitersDao.upsertWaiter(watch);
511
+ if (state.status === "settled") {
512
+ this.executions.wakeInTransaction(watch.executionId);
513
+ }
514
+ });
515
+ }
516
+ async getEffect(effectId) {
517
+ const state = this.effectsDao.getState(effectId);
518
+ return state ? toEffectRecord(state) : undefined;
519
+ }
520
+ }
521
+
522
+ // src/sqlite-heap.ts
523
+ import {
524
+ isLeaseCurrent
525
+ } from "@yieldstar/core";
526
+
527
+ // src/dao/step-response-dao.ts
528
+ class StepResponsesDao {
529
+ db;
530
+ constructor(db) {
531
+ this.db = db;
532
+ this.setupDb();
533
+ }
534
+ setupDb() {
535
+ this.db.run(`
536
+ CREATE TABLE IF NOT EXISTS step_responses (
537
+ execution_id TEXT NOT NULL,
538
+ step_key TEXT NOT NULL,
539
+ step_attempt INTEGER NOT NULL,
540
+ step_done BOOL NOT NULL,
541
+ step_response TEXT NOT NULL,
542
+ PRIMARY KEY (execution_id, step_key, step_attempt)
543
+ );
544
+ CREATE INDEX IF NOT EXISTS idx_execution_step_attempt
545
+ ON step_responses(execution_id, step_key, step_attempt DESC);
546
+ `);
547
+ }
548
+ getAllSteps() {
549
+ const query = this.db.query(`SELECT * FROM step_responses`);
550
+ return query.all();
551
+ }
552
+ deleteAll() {
553
+ const query = this.db.query(`DELETE FROM step_responses`);
554
+ query.run();
555
+ }
556
+ getLatestStepResponse(executionId, stepKey) {
557
+ const query = this.db.query(`SELECT * FROM step_responses
558
+ WHERE execution_id = $executionId
559
+ AND step_key = $stepKey
560
+ ORDER BY step_attempt DESC LIMIT 1`);
561
+ const result = query.get({
562
+ $executionId: executionId,
563
+ $stepKey: stepKey
564
+ });
565
+ return result;
566
+ }
567
+ getStepResponse(executionId, stepKey, stepAttempt) {
568
+ return this.db.query(`SELECT * FROM step_responses
569
+ WHERE execution_id = $executionId
570
+ AND step_key = $stepKey
571
+ AND step_attempt = $stepAttempt`).get({
572
+ $executionId: executionId,
573
+ $stepKey: stepKey,
574
+ $stepAttempt: stepAttempt
575
+ });
576
+ }
577
+ insertStepResponse(executionId, stepKey, stepAttempt, stepDone, stepResponseJson) {
578
+ const query = this.db.query(`INSERT INTO step_responses (execution_id, step_key, step_attempt, step_done, step_response)
579
+ VALUES ($executionId, $stepKey, $stepAttempt, $stepDone, $stepResponse)`);
580
+ query.run({
581
+ $executionId: executionId,
582
+ $stepKey: stepKey,
583
+ $stepAttempt: stepAttempt,
584
+ $stepDone: stepDone,
585
+ $stepResponse: stepResponseJson
586
+ });
587
+ }
588
+ }
589
+
590
+ // src/dao/store-waiters-dao.ts
591
+ class StoreWaitersDao {
592
+ db;
593
+ constructor(db) {
594
+ this.db = db;
595
+ this.setupDb();
596
+ }
597
+ setupDb() {
598
+ this.db.run(`
599
+ CREATE TABLE IF NOT EXISTS store_waiters (
600
+ workflow_id TEXT NOT NULL,
601
+ execution_id TEXT NOT NULL,
602
+ step_key TEXT NOT NULL,
603
+ store_name TEXT NOT NULL,
604
+ store_id TEXT NOT NULL,
605
+ since_version INTEGER NOT NULL,
606
+ read_paths TEXT NOT NULL,
607
+ PRIMARY KEY (store_name, store_id, execution_id, step_key)
608
+ );
609
+ CREATE INDEX IF NOT EXISTS idx_store_waiters_step
610
+ ON store_waiters(execution_id, step_key);
611
+ `);
612
+ }
613
+ upsertWaiter(waiter) {
614
+ this.db.query(`INSERT INTO store_waiters
615
+ (workflow_id, execution_id, step_key, store_name, store_id, since_version, read_paths)
616
+ VALUES
617
+ ($workflowId, $executionId, $stepKey, $storeName, $storeId, $sinceVersion, $readPaths)
618
+ ON CONFLICT(store_name, store_id, execution_id, step_key)
619
+ DO UPDATE SET
620
+ workflow_id = excluded.workflow_id,
621
+ since_version = excluded.since_version,
622
+ read_paths = excluded.read_paths`).run({
623
+ $workflowId: waiter.workflowId,
624
+ $executionId: waiter.executionId,
625
+ $stepKey: waiter.stepKey,
626
+ $storeName: waiter.storeName,
627
+ $storeId: waiter.storeId,
628
+ $sinceVersion: waiter.sinceVersion,
629
+ $readPaths: JSON.stringify(waiter.readPaths)
630
+ });
631
+ }
632
+ getStoreWaiters(storeName, storeId) {
633
+ return this.db.query(`SELECT * FROM store_waiters
634
+ WHERE store_name = $storeName AND store_id = $storeId`).all({ $storeName: storeName, $storeId: storeId });
635
+ }
636
+ deleteStoreWaiters(storeName, storeId) {
637
+ this.db.query(`DELETE FROM store_waiters WHERE store_name = $storeName AND store_id = $storeId`).run({ $storeName: storeName, $storeId: storeId });
638
+ }
639
+ deleteStepWaiters(executionId, stepKey) {
640
+ this.db.query(`DELETE FROM store_waiters WHERE execution_id = $executionId AND step_key = $stepKey`).run({ $executionId: executionId, $stepKey: stepKey });
641
+ }
642
+ }
643
+
644
+ // src/sqlite-heap.ts
645
+ class SqliteHeapClient2 {
646
+ db;
647
+ executionsDao;
648
+ stepResponsesDao;
649
+ storeWaitersDao;
650
+ effectWaitersDao;
651
+ constructor(db) {
652
+ this.db = db;
653
+ this.executionsDao = new ExecutionsDao(db);
654
+ this.stepResponsesDao = new StepResponsesDao(db);
655
+ this.storeWaitersDao = new StoreWaitersDao(db);
656
+ this.effectWaitersDao = new EffectWaitersDao(db);
657
+ }
658
+ async getAllSteps() {
659
+ return this.stepResponsesDao.getAllSteps();
660
+ }
661
+ async deleteAll() {
662
+ this.stepResponsesDao.deleteAll();
663
+ }
664
+ async readStep(params) {
665
+ const result = this.stepResponsesDao.getLatestStepResponse(params.executionId, params.stepKey);
666
+ if (!result) {
667
+ return null;
668
+ }
669
+ return {
670
+ stepResponseJson: result.step_response,
671
+ meta: {
672
+ attempt: result.step_attempt,
673
+ done: Boolean(result.step_done)
674
+ }
675
+ };
676
+ }
677
+ async writeStep(params) {
678
+ const { lease, stepKey, stepAttempt, done, stepResponseJson } = params;
679
+ const { executionId } = lease;
680
+ return runTransaction(this.db, () => {
681
+ const state = this.executionsDao.getState(executionId);
682
+ if (!state || !isLeaseCurrent(state, lease)) {
683
+ return { status: "lost" };
684
+ }
685
+ const existing = this.stepResponsesDao.getStepResponse(executionId, stepKey, stepAttempt);
686
+ if (existing) {
687
+ return {
688
+ stepResponseJson: existing.step_response,
689
+ meta: { attempt: existing.step_attempt, done: Boolean(existing.step_done) }
690
+ };
691
+ }
692
+ this.stepResponsesDao.insertStepResponse(executionId, stepKey, stepAttempt, done, stepResponseJson);
693
+ if (done) {
694
+ this.storeWaitersDao.deleteStepWaiters(executionId, stepKey);
695
+ this.effectWaitersDao.deleteStepWaiters(executionId, stepKey);
696
+ }
697
+ return { stepResponseJson, meta: { attempt: stepAttempt, done } };
698
+ });
699
+ }
700
+ }
701
+
702
+ // src/sqlite-store.ts
703
+ import { v7 as uuidv7 } from "uuid";
704
+ import {
705
+ cloneStoreState,
706
+ CasStoreClient,
707
+ decodeStoreValue,
708
+ encodeStoreValue,
709
+ StoreNotFoundError,
710
+ storePathsIntersect,
711
+ validateStoreState
712
+ } from "@yieldstar/core";
713
+ class SqliteStoreClient2 extends CasStoreClient {
714
+ db;
715
+ executions;
716
+ storeWaitersDao;
717
+ constructor(params) {
718
+ super();
719
+ this.db = params.db;
720
+ this.executions = params.executions ?? new SqliteExecutionClient2(params.db);
721
+ this.setupDb();
722
+ this.storeWaitersDao = new StoreWaitersDao(params.db);
723
+ }
724
+ async getOrCreateStore(params) {
725
+ const existing = this.getStoreRow(params.definition.name, params.id);
726
+ if (existing) {
727
+ return toSnapshot(existing);
728
+ }
729
+ if (!params.initial) {
730
+ throw new StoreNotFoundError(params.definition.name, params.id);
731
+ }
732
+ const initialValue = params.initial;
733
+ const initial = typeof initialValue === "function" ? await initialValue() : initialValue;
734
+ const state = await validateStoreState(params.definition, initial);
735
+ return runTransaction(this.db, () => {
736
+ const existingTx = this.getStoreRow(params.definition.name, params.id);
737
+ if (existingTx) {
738
+ return toSnapshot(existingTx);
739
+ }
740
+ const instanceId = uuidv7();
741
+ this.db.query(`INSERT INTO stores (instance_id, store_name, store_id, version, state)
742
+ VALUES ($instanceId, $storeName, $storeId, 0, $state)`).run({
743
+ $instanceId: instanceId,
744
+ $storeName: params.definition.name,
745
+ $storeId: params.id,
746
+ $state: encodeStoreValue(state)
747
+ });
748
+ return {
749
+ state: cloneStoreState(state),
750
+ instanceId,
751
+ version: 0
752
+ };
753
+ });
754
+ }
755
+ async getStore(params) {
756
+ const row = this.getStoreRow(params.definition.name, params.id);
757
+ if (!row) {
758
+ throw new StoreNotFoundError(params.definition.name, params.id);
759
+ }
760
+ return toSnapshot(row);
761
+ }
762
+ async getAppliedStoreStep(params) {
763
+ const row = this.getAppliedStepRow({
764
+ storeName: params.definition.name,
765
+ storeId: params.id,
766
+ stepId: params.stepId
767
+ });
768
+ return row ? { result: decodeStoreValue(row.result) } : undefined;
769
+ }
770
+ async commitStoreMutation(mutation) {
771
+ return runTransaction(this.db, () => {
772
+ if (mutation.stepId) {
773
+ const applied = this.getAppliedStepRow({
774
+ storeName: mutation.definition.name,
775
+ storeId: mutation.id,
776
+ stepId: mutation.stepId
777
+ });
778
+ if (applied) {
779
+ return {
780
+ status: "already-applied",
781
+ result: decodeStoreValue(applied.result)
782
+ };
783
+ }
784
+ }
785
+ const row = this.getStoreRow(mutation.definition.name, mutation.id);
786
+ if (!row) {
787
+ throw new StoreNotFoundError(mutation.definition.name, mutation.id);
788
+ }
789
+ if (row.instance_id !== mutation.expected.instanceId || row.version !== mutation.expected.version) {
790
+ return { status: "conflict", snapshot: toSnapshot(row) };
791
+ }
792
+ const version = mutation.expected.version + 1;
793
+ const changed = this.db.query(`UPDATE stores
794
+ SET version = $version, state = $state
795
+ WHERE instance_id = $instanceId AND version = $expectedVersion`).run({
796
+ $instanceId: mutation.expected.instanceId,
797
+ $expectedVersion: mutation.expected.version,
798
+ $version: version,
799
+ $state: encodeStoreValue(mutation.nextState)
800
+ });
801
+ if (Number(changed.changes) !== 1) {
802
+ throw new Error("Store changed during its mutation transaction");
803
+ }
804
+ if (mutation.stepId) {
805
+ this.insertAppliedStepRow({
806
+ storeName: mutation.definition.name,
807
+ storeId: mutation.id,
808
+ stepId: mutation.stepId,
809
+ result: encodeStoreValue(mutation.result)
810
+ });
811
+ }
812
+ const executionIds = this.selectMatchingExecutionIds({
813
+ storeName: mutation.definition.name,
814
+ storeId: mutation.id,
815
+ version,
816
+ changedPaths: mutation.changedPaths
817
+ });
818
+ for (const executionId of executionIds) {
819
+ this.executions.wakeInTransaction(executionId);
820
+ }
821
+ return { status: "committed" };
822
+ });
823
+ }
824
+ async listStores(definition) {
825
+ const rows = this.db.query(`SELECT store_id FROM stores
826
+ WHERE store_name = $storeName
827
+ ORDER BY store_id ASC`).all({ $storeName: definition.name });
828
+ return rows.map((row) => row.store_id);
829
+ }
830
+ async deleteStore(params) {
831
+ runTransaction(this.db, () => {
832
+ this.db.query(`DELETE FROM stores WHERE store_name = $storeName AND store_id = $storeId`).run({
833
+ $storeName: params.definition.name,
834
+ $storeId: params.id
835
+ });
836
+ this.storeWaitersDao.deleteStoreWaiters(params.definition.name, params.id);
837
+ });
838
+ }
839
+ async deleteStoreFrom(params) {
840
+ return runTransaction(this.db, () => {
841
+ if (params.stepId) {
842
+ const applied = this.getAppliedStepRow({
843
+ storeName: params.definition.name,
844
+ storeId: params.id,
845
+ stepId: params.stepId
846
+ });
847
+ if (applied) {
848
+ return decodeStoreValue(applied.result);
849
+ }
850
+ }
851
+ this.assertSnapshotHasInstanceId(params.snapshot);
852
+ const row = this.getStoreRow(params.definition.name, params.id);
853
+ if (!row) {
854
+ return {
855
+ deleted: false,
856
+ reason: "not-found",
857
+ expectedInstanceId: params.snapshot.instanceId,
858
+ expectedVersion: params.snapshot.version
859
+ };
860
+ }
861
+ if (row.instance_id !== params.snapshot.instanceId || row.version !== params.snapshot.version) {
862
+ return {
863
+ deleted: false,
864
+ reason: "conflict",
865
+ expectedInstanceId: params.snapshot.instanceId,
866
+ actualInstanceId: row.instance_id,
867
+ expectedVersion: params.snapshot.version,
868
+ actualVersion: row.version
869
+ };
870
+ }
871
+ this.storeWaitersDao.deleteStoreWaiters(params.definition.name, params.id);
872
+ this.db.query(`DELETE FROM stores WHERE instance_id = $instanceId`).run({ $instanceId: row.instance_id });
873
+ const result = { deleted: true };
874
+ if (params.stepId) {
875
+ this.insertAppliedStepRow({
876
+ storeName: params.definition.name,
877
+ storeId: params.id,
878
+ stepId: params.stepId,
879
+ result: encodeStoreValue(result)
880
+ });
881
+ }
882
+ return result;
883
+ });
884
+ }
885
+ async registerWaiter(waiter) {
886
+ runTransaction(this.db, () => {
887
+ this.storeWaitersDao.upsertWaiter(waiter);
888
+ const row = this.getStoreRow(waiter.storeName, waiter.storeId);
889
+ if (!row || row.instance_id !== waiter.instanceId || row.version > waiter.sinceVersion) {
890
+ this.executions.wakeInTransaction(waiter.executionId);
891
+ }
892
+ });
893
+ }
894
+ setupDb() {
895
+ this.createStoresTable();
896
+ this.db.run(`
897
+ CREATE TABLE IF NOT EXISTS store_applied_steps (
898
+ store_name TEXT NOT NULL,
899
+ store_id TEXT NOT NULL,
900
+ execution_id TEXT NOT NULL,
901
+ step_key TEXT NOT NULL,
902
+ result TEXT NOT NULL,
903
+ PRIMARY KEY (store_name, store_id, execution_id, step_key)
904
+ );
905
+ `);
906
+ }
907
+ createStoresTable() {
908
+ this.db.run(`
909
+ CREATE TABLE IF NOT EXISTS stores (
910
+ instance_id TEXT PRIMARY KEY,
911
+ store_name TEXT NOT NULL,
912
+ store_id TEXT NOT NULL,
913
+ version INTEGER NOT NULL,
914
+ state TEXT NOT NULL,
915
+ UNIQUE (store_name, store_id)
916
+ )
917
+ `);
918
+ }
919
+ getAppliedStepRow(params) {
920
+ return this.db.query(`SELECT result FROM store_applied_steps
921
+ WHERE store_name = $storeName
922
+ AND store_id = $storeId
923
+ AND execution_id = $executionId
924
+ AND step_key = $stepKey`).get({
925
+ $storeName: params.storeName,
926
+ $storeId: params.storeId,
927
+ $executionId: params.stepId.executionId,
928
+ $stepKey: params.stepId.stepKey
929
+ });
930
+ }
931
+ insertAppliedStepRow(params) {
932
+ this.db.query(`INSERT INTO store_applied_steps
933
+ (store_name, store_id, execution_id, step_key, result)
934
+ VALUES
935
+ ($storeName, $storeId, $executionId, $stepKey, $result)`).run({
936
+ $storeName: params.storeName,
937
+ $storeId: params.storeId,
938
+ $executionId: params.stepId.executionId,
939
+ $stepKey: params.stepId.stepKey,
940
+ $result: params.result
941
+ });
942
+ }
943
+ getStoreRow(storeName, storeId) {
944
+ return this.db.query(`SELECT instance_id, state, version FROM stores
945
+ WHERE store_name = $storeName AND store_id = $storeId`).get({
946
+ $storeName: storeName,
947
+ $storeId: storeId
948
+ });
949
+ }
950
+ selectMatchingExecutionIds(params) {
951
+ const executionIds = new Set;
952
+ const rows = this.storeWaitersDao.getStoreWaiters(params.storeName, params.storeId);
953
+ for (const row of rows) {
954
+ if (row.since_version >= params.version)
955
+ continue;
956
+ const readPaths = JSON.parse(row.read_paths);
957
+ if (!storePathsIntersect(readPaths, params.changedPaths))
958
+ continue;
959
+ executionIds.add(row.execution_id);
960
+ }
961
+ return executionIds;
962
+ }
963
+ assertSnapshotHasInstanceId(snapshot) {
964
+ if (!snapshot.instanceId) {
965
+ throw new Error("Store snapshot is missing instanceId; read a fresh snapshot");
966
+ }
967
+ }
968
+ }
969
+ function toSnapshot(row) {
970
+ return {
971
+ state: decodeStoreValue(row.state),
972
+ instanceId: row.instance_id,
973
+ version: row.version
974
+ };
975
+ }
976
+
977
+ // src/sqlite-runtime.ts
978
+ class SqliteRuntime2 extends Runtime {
979
+ clock;
980
+ executions;
981
+ effects;
982
+ heap;
983
+ stores;
984
+ constructor(db, options = {}) {
985
+ super();
986
+ this.clock = options.clock ?? (() => Date.now());
987
+ this.executions = new SqliteExecutionClient2(db, { clock: this.clock });
988
+ this.heap = new SqliteHeapClient2(db);
989
+ this.stores = new SqliteStoreClient2({ db, executions: this.executions });
990
+ this.effects = new SqliteEffectClient2({
991
+ db,
992
+ executions: this.executions,
993
+ clock: this.clock
994
+ });
995
+ }
996
+ }
997
+ export { SqliteExecutionClient2, SqliteEffectClient2, SqliteHeapClient2, SqliteStoreClient2, SqliteRuntime2 };