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