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