@diffra-ai/durable 0.0.0-stage → 0.2.2
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.
- package/CHANGELOG.md +440 -0
- package/README.md +1153 -2
- package/dist/codemode/codemode.d.ts +174 -0
- package/dist/codemode/codemode.d.ts.map +1 -0
- package/dist/codemode/codemode.js +884 -0
- package/dist/codemode/codemode.js.map +1 -0
- package/dist/codemode/describe.d.ts +38 -0
- package/dist/codemode/describe.d.ts.map +1 -0
- package/dist/codemode/describe.js +127 -0
- package/dist/codemode/describe.js.map +1 -0
- package/dist/codemode/index.d.ts +3 -0
- package/dist/codemode/index.d.ts.map +1 -0
- package/dist/codemode/index.js +3 -0
- package/dist/codemode/index.js.map +1 -0
- package/dist/codemode/models.d.ts +29 -0
- package/dist/codemode/models.d.ts.map +1 -0
- package/dist/codemode/models.js +242 -0
- package/dist/codemode/models.js.map +1 -0
- package/dist/codemode/output.d.ts +43 -0
- package/dist/codemode/output.d.ts.map +1 -0
- package/dist/codemode/output.js +168 -0
- package/dist/codemode/output.js.map +1 -0
- package/dist/documents.d.ts +66 -0
- package/dist/documents.d.ts.map +1 -0
- package/dist/documents.js +98 -0
- package/dist/documents.js.map +1 -0
- package/dist/entries.d.ts +31 -0
- package/dist/entries.d.ts.map +1 -0
- package/dist/entries.js +31 -0
- package/dist/entries.js.map +1 -0
- package/dist/env/decode.d.ts +16 -0
- package/dist/env/decode.d.ts.map +1 -0
- package/dist/env/decode.js +28 -0
- package/dist/env/decode.js.map +1 -0
- package/dist/env/index.d.ts +308 -0
- package/dist/env/index.d.ts.map +1 -0
- package/dist/env/index.js +49 -0
- package/dist/env/index.js.map +1 -0
- package/dist/env/line-scan.d.ts +13 -0
- package/dist/env/line-scan.d.ts.map +1 -0
- package/dist/env/line-scan.js +147 -0
- package/dist/env/line-scan.js.map +1 -0
- package/dist/env/node-watch.d.ts +29 -0
- package/dist/env/node-watch.d.ts.map +1 -0
- package/dist/env/node-watch.js +487 -0
- package/dist/env/node-watch.js.map +1 -0
- package/dist/env/node.d.ts +56 -0
- package/dist/env/node.d.ts.map +1 -0
- package/dist/env/node.js +1185 -0
- package/dist/env/node.js.map +1 -0
- package/dist/errors.d.ts +48 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +76 -0
- package/dist/errors.js.map +1 -0
- package/dist/harness/agent.d.ts +46 -0
- package/dist/harness/agent.d.ts.map +1 -0
- package/dist/harness/agent.js +334 -0
- package/dist/harness/agent.js.map +1 -0
- package/dist/harness/compaction.d.ts +68 -0
- package/dist/harness/compaction.d.ts.map +1 -0
- package/dist/harness/compaction.js +431 -0
- package/dist/harness/compaction.js.map +1 -0
- package/dist/harness/context.d.ts +84 -0
- package/dist/harness/context.d.ts.map +1 -0
- package/dist/harness/context.js +301 -0
- package/dist/harness/context.js.map +1 -0
- package/dist/harness/define.d.ts +25 -0
- package/dist/harness/define.d.ts.map +1 -0
- package/dist/harness/define.js +32 -0
- package/dist/harness/define.js.map +1 -0
- package/dist/harness/generation.d.ts +117 -0
- package/dist/harness/generation.d.ts.map +1 -0
- package/dist/harness/generation.js +1098 -0
- package/dist/harness/generation.js.map +1 -0
- package/dist/harness/harness.d.ts +22 -0
- package/dist/harness/harness.d.ts.map +1 -0
- package/dist/harness/harness.js +438 -0
- package/dist/harness/harness.js.map +1 -0
- package/dist/harness/inbox.d.ts +84 -0
- package/dist/harness/inbox.d.ts.map +1 -0
- package/dist/harness/inbox.js +135 -0
- package/dist/harness/inbox.js.map +1 -0
- package/dist/harness/json.d.ts +26 -0
- package/dist/harness/json.d.ts.map +1 -0
- package/dist/harness/json.js +51 -0
- package/dist/harness/json.js.map +1 -0
- package/dist/harness/live.d.ts +285 -0
- package/dist/harness/live.d.ts.map +1 -0
- package/dist/harness/live.js +257 -0
- package/dist/harness/live.js.map +1 -0
- package/dist/harness/parks.d.ts +23 -0
- package/dist/harness/parks.d.ts.map +1 -0
- package/dist/harness/parks.js +52 -0
- package/dist/harness/parks.js.map +1 -0
- package/dist/harness/partial-changes.d.ts +54 -0
- package/dist/harness/partial-changes.d.ts.map +1 -0
- package/dist/harness/partial-changes.js +163 -0
- package/dist/harness/partial-changes.js.map +1 -0
- package/dist/harness/prompt.d.ts +27 -0
- package/dist/harness/prompt.d.ts.map +1 -0
- package/dist/harness/prompt.js +131 -0
- package/dist/harness/prompt.js.map +1 -0
- package/dist/harness/provider.d.ts +16 -0
- package/dist/harness/provider.d.ts.map +1 -0
- package/dist/harness/provider.js +33 -0
- package/dist/harness/provider.js.map +1 -0
- package/dist/harness/registry-reader.d.ts +11 -0
- package/dist/harness/registry-reader.d.ts.map +1 -0
- package/dist/harness/registry-reader.js +25 -0
- package/dist/harness/registry-reader.js.map +1 -0
- package/dist/harness/registry.d.ts +6 -0
- package/dist/harness/registry.d.ts.map +1 -0
- package/dist/harness/registry.js +101 -0
- package/dist/harness/registry.js.map +1 -0
- package/dist/harness/scheduler.d.ts +195 -0
- package/dist/harness/scheduler.d.ts.map +1 -0
- package/dist/harness/scheduler.js +3073 -0
- package/dist/harness/scheduler.js.map +1 -0
- package/dist/harness/submissions.d.ts +44 -0
- package/dist/harness/submissions.d.ts.map +1 -0
- package/dist/harness/submissions.js +265 -0
- package/dist/harness/submissions.js.map +1 -0
- package/dist/harness/task-graph.d.ts +75 -0
- package/dist/harness/task-graph.d.ts.map +1 -0
- package/dist/harness/task-graph.js +224 -0
- package/dist/harness/task-graph.js.map +1 -0
- package/dist/harness/telemetry.d.ts +307 -0
- package/dist/harness/telemetry.d.ts.map +1 -0
- package/dist/harness/telemetry.js +140 -0
- package/dist/harness/telemetry.js.map +1 -0
- package/dist/harness/tool.d.ts +106 -0
- package/dist/harness/tool.d.ts.map +1 -0
- package/dist/harness/tool.js +1182 -0
- package/dist/harness/tool.js.map +1 -0
- package/dist/harness/transcript.d.ts +72 -0
- package/dist/harness/transcript.d.ts.map +1 -0
- package/dist/harness/transcript.js +264 -0
- package/dist/harness/transcript.js.map +1 -0
- package/dist/harness/types.d.ts +1146 -0
- package/dist/harness/types.d.ts.map +1 -0
- package/dist/harness/types.js +2 -0
- package/dist/harness/types.js.map +1 -0
- package/dist/harness/usage.d.ts +19 -0
- package/dist/harness/usage.d.ts.map +1 -0
- package/dist/harness/usage.js +57 -0
- package/dist/harness/usage.js.map +1 -0
- package/dist/harness/util.d.ts +25 -0
- package/dist/harness/util.d.ts.map +1 -0
- package/dist/harness/util.js +76 -0
- package/dist/harness/util.js.map +1 -0
- package/dist/harness/view.d.ts +69 -0
- package/dist/harness/view.d.ts.map +1 -0
- package/dist/harness/view.js +265 -0
- package/dist/harness/view.js.map +1 -0
- package/dist/ids.d.ts +6 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +9 -0
- package/dist/ids.js.map +1 -0
- package/dist/images/cloudflare.d.ts +4 -0
- package/dist/images/cloudflare.d.ts.map +1 -0
- package/dist/images/cloudflare.js +9 -0
- package/dist/images/cloudflare.js.map +1 -0
- package/dist/images/exif.d.ts +3 -0
- package/dist/images/exif.d.ts.map +1 -0
- package/dist/images/exif.js +71 -0
- package/dist/images/exif.js.map +1 -0
- package/dist/images/fit.d.ts +41 -0
- package/dist/images/fit.d.ts.map +1 -0
- package/dist/images/fit.js +108 -0
- package/dist/images/fit.js.map +1 -0
- package/dist/images/index.d.ts +18 -0
- package/dist/images/index.d.ts.map +1 -0
- package/dist/images/index.js +125 -0
- package/dist/images/index.js.map +1 -0
- package/dist/images/node-worker.d.ts +19 -0
- package/dist/images/node-worker.d.ts.map +1 -0
- package/dist/images/node-worker.js +17 -0
- package/dist/images/node-worker.js.map +1 -0
- package/dist/images/node.d.ts +21 -0
- package/dist/images/node.d.ts.map +1 -0
- package/dist/images/node.js +121 -0
- package/dist/images/node.js.map +1 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/dist/search.d.ts +29 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +148 -0
- package/dist/search.js.map +1 -0
- package/dist/session/cached-storage.d.ts +72 -0
- package/dist/session/cached-storage.d.ts.map +1 -0
- package/dist/session/cached-storage.js +269 -0
- package/dist/session/cached-storage.js.map +1 -0
- package/dist/session/conversation-tails.d.ts +33 -0
- package/dist/session/conversation-tails.d.ts.map +1 -0
- package/dist/session/conversation-tails.js +101 -0
- package/dist/session/conversation-tails.js.map +1 -0
- package/dist/session/forks.d.ts +10 -0
- package/dist/session/forks.d.ts.map +1 -0
- package/dist/session/forks.js +42 -0
- package/dist/session/forks.js.map +1 -0
- package/dist/session/keys.d.ts +69 -0
- package/dist/session/keys.d.ts.map +1 -0
- package/dist/session/keys.js +161 -0
- package/dist/session/keys.js.map +1 -0
- package/dist/session/session.d.ts +287 -0
- package/dist/session/session.d.ts.map +1 -0
- package/dist/session/session.js +1701 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/transaction.d.ts +205 -0
- package/dist/session/transaction.d.ts.map +1 -0
- package/dist/session/transaction.js +1059 -0
- package/dist/session/transaction.js.map +1 -0
- package/dist/session/writer.d.ts +74 -0
- package/dist/session/writer.d.ts.map +1 -0
- package/dist/session/writer.js +294 -0
- package/dist/session/writer.js.map +1 -0
- package/dist/signals.d.ts +180 -0
- package/dist/signals.d.ts.map +1 -0
- package/dist/signals.js +236 -0
- package/dist/signals.js.map +1 -0
- package/dist/storage/indexeddb.d.ts +69 -0
- package/dist/storage/indexeddb.d.ts.map +1 -0
- package/dist/storage/indexeddb.js +883 -0
- package/dist/storage/indexeddb.js.map +1 -0
- package/dist/storage/jsonl/index.d.ts +2 -0
- package/dist/storage/jsonl/index.d.ts.map +1 -0
- package/dist/storage/jsonl/index.js +2 -0
- package/dist/storage/jsonl/index.js.map +1 -0
- package/dist/storage/jsonl/node.d.ts +6 -0
- package/dist/storage/jsonl/node.d.ts.map +1 -0
- package/dist/storage/jsonl/node.js +8 -0
- package/dist/storage/jsonl/node.js.map +1 -0
- package/dist/storage/jsonl/storage.d.ts +206 -0
- package/dist/storage/jsonl/storage.d.ts.map +1 -0
- package/dist/storage/jsonl/storage.js +799 -0
- package/dist/storage/jsonl/storage.js.map +1 -0
- package/dist/storage/memory.d.ts +68 -0
- package/dist/storage/memory.d.ts.map +1 -0
- package/dist/storage/memory.js +761 -0
- package/dist/storage/memory.js.map +1 -0
- package/dist/storage/scan.d.ts +18 -0
- package/dist/storage/scan.d.ts.map +1 -0
- package/dist/storage/scan.js +29 -0
- package/dist/storage/scan.js.map +1 -0
- package/dist/storage/sqlite/cloudflare.d.ts +9 -0
- package/dist/storage/sqlite/cloudflare.d.ts.map +1 -0
- package/dist/storage/sqlite/cloudflare.js +11 -0
- package/dist/storage/sqlite/cloudflare.js.map +1 -0
- package/dist/storage/sqlite/commit.d.ts +52 -0
- package/dist/storage/sqlite/commit.d.ts.map +1 -0
- package/dist/storage/sqlite/commit.js +371 -0
- package/dist/storage/sqlite/commit.js.map +1 -0
- package/dist/storage/sqlite/database.d.ts +2 -0
- package/dist/storage/sqlite/database.d.ts.map +1 -0
- package/dist/storage/sqlite/database.js +2 -0
- package/dist/storage/sqlite/database.js.map +1 -0
- package/dist/storage/sqlite/index.d.ts +4 -0
- package/dist/storage/sqlite/index.d.ts.map +1 -0
- package/dist/storage/sqlite/index.js +3 -0
- package/dist/storage/sqlite/index.js.map +1 -0
- package/dist/storage/sqlite/migrations.d.ts +12 -0
- package/dist/storage/sqlite/migrations.d.ts.map +1 -0
- package/dist/storage/sqlite/migrations.js +121 -0
- package/dist/storage/sqlite/migrations.js.map +1 -0
- package/dist/storage/sqlite/node.d.ts +8 -0
- package/dist/storage/sqlite/node.d.ts.map +1 -0
- package/dist/storage/sqlite/node.js +12 -0
- package/dist/storage/sqlite/node.js.map +1 -0
- package/dist/storage/sqlite/rows.d.ts +33 -0
- package/dist/storage/sqlite/rows.d.ts.map +1 -0
- package/dist/storage/sqlite/rows.js +53 -0
- package/dist/storage/sqlite/rows.js.map +1 -0
- package/dist/storage/sqlite/schema.d.ts +45 -0
- package/dist/storage/sqlite/schema.d.ts.map +1 -0
- package/dist/storage/sqlite/schema.js +50 -0
- package/dist/storage/sqlite/schema.js.map +1 -0
- package/dist/storage/sqlite/statements.d.ts +13 -0
- package/dist/storage/sqlite/statements.d.ts.map +1 -0
- package/dist/storage/sqlite/statements.js +88 -0
- package/dist/storage/sqlite/statements.js.map +1 -0
- package/dist/storage/sqlite/storage.d.ts +86 -0
- package/dist/storage/sqlite/storage.d.ts.map +1 -0
- package/dist/storage/sqlite/storage.js +534 -0
- package/dist/storage/sqlite/storage.js.map +1 -0
- package/dist/storage/store/commit.d.ts +33 -0
- package/dist/storage/store/commit.d.ts.map +1 -0
- package/dist/storage/store/commit.js +286 -0
- package/dist/storage/store/commit.js.map +1 -0
- package/dist/storage/store/documents.d.ts +43 -0
- package/dist/storage/store/documents.d.ts.map +1 -0
- package/dist/storage/store/documents.js +102 -0
- package/dist/storage/store/documents.js.map +1 -0
- package/dist/storage/store/index.d.ts +2 -0
- package/dist/storage/store/index.d.ts.map +1 -0
- package/dist/storage/store/index.js +2 -0
- package/dist/storage/store/index.js.map +1 -0
- package/dist/storage/store/queries.d.ts +49 -0
- package/dist/storage/store/queries.d.ts.map +1 -0
- package/dist/storage/store/queries.js +93 -0
- package/dist/storage/store/queries.js.map +1 -0
- package/dist/storage/store/storage.d.ts +60 -0
- package/dist/storage/store/storage.d.ts.map +1 -0
- package/dist/storage/store/storage.js +438 -0
- package/dist/storage/store/storage.js.map +1 -0
- package/dist/storage/store/tables.d.ts +54 -0
- package/dist/storage/store/tables.d.ts.map +1 -0
- package/dist/storage/store/tables.js +108 -0
- package/dist/storage/store/tables.js.map +1 -0
- package/dist/tasks.d.ts +6 -0
- package/dist/tasks.d.ts.map +1 -0
- package/dist/tasks.js +5 -0
- package/dist/tasks.js.map +1 -0
- package/dist/testing/assertions.d.ts +5 -0
- package/dist/testing/assertions.d.ts.map +1 -0
- package/dist/testing/assertions.js +25 -0
- package/dist/testing/assertions.js.map +1 -0
- package/dist/testing/commit-writes.d.ts +5 -0
- package/dist/testing/commit-writes.d.ts.map +1 -0
- package/dist/testing/commit-writes.js +12 -0
- package/dist/testing/commit-writes.js.map +1 -0
- package/dist/testing/env-conformance.d.ts +7 -0
- package/dist/testing/env-conformance.d.ts.map +1 -0
- package/dist/testing/env-conformance.js +531 -0
- package/dist/testing/env-conformance.js.map +1 -0
- package/dist/testing/index.d.ts +8 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +7 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/runner.d.ts +12 -0
- package/dist/testing/runner.d.ts.map +1 -0
- package/dist/testing/runner.js +23 -0
- package/dist/testing/runner.js.map +1 -0
- package/dist/testing/storage-benchmark.d.ts +41 -0
- package/dist/testing/storage-benchmark.d.ts.map +1 -0
- package/dist/testing/storage-benchmark.js +351 -0
- package/dist/testing/storage-benchmark.js.map +1 -0
- package/dist/testing/storage-conformance.d.ts +4 -0
- package/dist/testing/storage-conformance.d.ts.map +1 -0
- package/dist/testing/storage-conformance.js +1554 -0
- package/dist/testing/storage-conformance.js.map +1 -0
- package/dist/testing/types.d.ts +39 -0
- package/dist/testing/types.d.ts.map +1 -0
- package/dist/testing/types.js +2 -0
- package/dist/testing/types.js.map +1 -0
- package/dist/timers.d.ts +21 -0
- package/dist/timers.d.ts.map +1 -0
- package/dist/timers.js +72 -0
- package/dist/timers.js.map +1 -0
- package/dist/tool-search/index.d.ts +2 -0
- package/dist/tool-search/index.d.ts.map +1 -0
- package/dist/tool-search/index.js +2 -0
- package/dist/tool-search/index.js.map +1 -0
- package/dist/tool-search/tool-search.d.ts +17 -0
- package/dist/tool-search/tool-search.d.ts.map +1 -0
- package/dist/tool-search/tool-search.js +96 -0
- package/dist/tool-search/tool-search.js.map +1 -0
- package/dist/tools/bash.d.ts +55 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +139 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit-diff.d.ts +89 -0
- package/dist/tools/edit-diff.d.ts.map +1 -0
- package/dist/tools/edit-diff.js +386 -0
- package/dist/tools/edit-diff.js.map +1 -0
- package/dist/tools/edit.d.ts +18 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +117 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/env.d.ts +5 -0
- package/dist/tools/env.d.ts.map +1 -0
- package/dist/tools/env.js +7 -0
- package/dist/tools/env.js.map +1 -0
- package/dist/tools/file-mutation-queue.d.ts +9 -0
- package/dist/tools/file-mutation-queue.d.ts.map +1 -0
- package/dist/tools/file-mutation-queue.js +52 -0
- package/dist/tools/file-mutation-queue.js.map +1 -0
- package/dist/tools/image-processor.d.ts +57 -0
- package/dist/tools/image-processor.d.ts.map +1 -0
- package/dist/tools/image-processor.js +49 -0
- package/dist/tools/image-processor.js.map +1 -0
- package/dist/tools/image.d.ts +20 -0
- package/dist/tools/image.d.ts.map +1 -0
- package/dist/tools/image.js +178 -0
- package/dist/tools/image.js.map +1 -0
- package/dist/tools/index.d.ts +46 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +23 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/path-utils.d.ts +5 -0
- package/dist/tools/path-utils.d.ts.map +1 -0
- package/dist/tools/path-utils.js +26 -0
- package/dist/tools/path-utils.js.map +1 -0
- package/dist/tools/read.d.ts +30 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +239 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +31 -0
- package/dist/tools/write.js.map +1 -0
- package/dist/truncate.d.ts +65 -0
- package/dist/truncate.d.ts.map +1 -0
- package/dist/truncate.js +124 -0
- package/dist/truncate.js.map +1 -0
- package/dist/types.d.ts +1244 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +179 -5
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
import { apply } from "@diffra-ai/chord/delta";
|
|
2
|
+
import { StorageRequestError } from "../../errors.js";
|
|
3
|
+
import { idFromNumber, seqFromNumber } from "../../ids.js";
|
|
4
|
+
import { nextCursor, scanStart } from "../scan.js";
|
|
5
|
+
import { CommitState, claimOf, PendingWrites, prepareDocumentActions } from "./commit.js";
|
|
6
|
+
import { applySqliteMigrationsForSchema } from "./migrations.js";
|
|
7
|
+
import { addressParts, encodeIndexedString, isCurrentOnly, parseJson, scopeColumns } from "./rows.js";
|
|
8
|
+
import { createSqliteSchema } from "./schema.js";
|
|
9
|
+
const cursorId = (cursor) => {
|
|
10
|
+
const after = cursor?.after;
|
|
11
|
+
if (after === undefined)
|
|
12
|
+
return undefined;
|
|
13
|
+
if (typeof after !== "number" || !Number.isSafeInteger(after))
|
|
14
|
+
throw new StorageRequestError("Invalid storage cursor");
|
|
15
|
+
return idFromNumber(after);
|
|
16
|
+
};
|
|
17
|
+
const page = (values, limit, order = "ascending") => {
|
|
18
|
+
const items = values.slice(0, limit);
|
|
19
|
+
if (values.length <= limit)
|
|
20
|
+
return { items };
|
|
21
|
+
return { items, next: nextCursor(items.at(-1).id, order) };
|
|
22
|
+
};
|
|
23
|
+
/** The ID condition, its parameter, and the `ORDER BY` direction of a table scan. */
|
|
24
|
+
const scanSql = (start) => start.order === "ascending"
|
|
25
|
+
? { clause: "id > ?", param: start.after ?? -1, direction: "ASC" }
|
|
26
|
+
: { clause: "id < ?", param: start.after ?? Number.MAX_SAFE_INTEGER, direction: "DESC" };
|
|
27
|
+
const isAliveAt = (record, at) => {
|
|
28
|
+
if (at === "current")
|
|
29
|
+
return record.retiredAt === undefined;
|
|
30
|
+
return record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* `executor`, setting `calls.failed` when one of its calls throws, synchronously (a synchronous driver) or by
|
|
34
|
+
* rejecting, with any value: then a failing check is the database's, not one of Durable's own.
|
|
35
|
+
*/
|
|
36
|
+
function watchCalls(executor, calls) {
|
|
37
|
+
const watched = async (call) => {
|
|
38
|
+
try {
|
|
39
|
+
return await call();
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
calls.failed = true;
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
exec: (sql) => watched(() => executor.exec(sql)),
|
|
48
|
+
run: (sql, ...params) => watched(() => executor.run(sql, ...params)),
|
|
49
|
+
runCounted: (sql, ...params) => watched(() => executor.runCounted(sql, ...params)),
|
|
50
|
+
get: (sql, ...params) => watched(() => executor.get(sql, ...params)),
|
|
51
|
+
all: (sql, ...params) => watched(() => executor.all(sql, ...params)),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** Portable SQLite implementation of the Pico storage contract. */
|
|
55
|
+
export class SqliteStorage {
|
|
56
|
+
db;
|
|
57
|
+
schema;
|
|
58
|
+
nextId;
|
|
59
|
+
closed = false;
|
|
60
|
+
closing;
|
|
61
|
+
admittedReads = 0;
|
|
62
|
+
readsDrained;
|
|
63
|
+
constructor(db, schema, nextId) {
|
|
64
|
+
this.db = db;
|
|
65
|
+
this.schema = schema;
|
|
66
|
+
this.nextId = nextId;
|
|
67
|
+
}
|
|
68
|
+
/** Initialize storage over an owned SQLite database facade. */
|
|
69
|
+
static async open(db, options = {}) {
|
|
70
|
+
try {
|
|
71
|
+
const schema = createSqliteSchema(options.prefix);
|
|
72
|
+
await applySqliteMigrationsForSchema(db, schema);
|
|
73
|
+
const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`);
|
|
74
|
+
if (metadata === undefined)
|
|
75
|
+
throw new Error("Durable SQLite metadata is missing");
|
|
76
|
+
return new SqliteStorage(db, schema, Number(metadata.next_id));
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
try {
|
|
80
|
+
await db.close();
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// Preserve the initialization failure.
|
|
84
|
+
}
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Commit `batches` in one SQL transaction, each with its own seq. Each batch is checked before it writes anything,
|
|
90
|
+
* against the state the earlier ones left, and the first one refused ends the batch: the transaction commits the ones
|
|
91
|
+
* before it. No savepoints, which Durable Objects do not allow: the checks run before the writes instead. The checks
|
|
92
|
+
* read the stored state of all batches up front and run in memory, and the accepted batches are written per table in
|
|
93
|
+
* multi-row statements (`commit.ts`), so a call costs a few statements whatever its number of batches. A batch with a
|
|
94
|
+
* copy reads the copy's source from the database: the batches before it are written first, so a call of many fork
|
|
95
|
+
* batches costs a few statements per fork.
|
|
96
|
+
*/
|
|
97
|
+
async commit(batches, receive, _context) {
|
|
98
|
+
this.assertOpen();
|
|
99
|
+
const seqs = [];
|
|
100
|
+
let refused;
|
|
101
|
+
let candidateNextId = this.nextId;
|
|
102
|
+
await this.db.transaction(async (transaction) => {
|
|
103
|
+
const metadata = await this.readMetadata(transaction);
|
|
104
|
+
let next = metadata.next_seq;
|
|
105
|
+
// A failure of the database rejects the call and rolls back the batches before it with the transaction.
|
|
106
|
+
const state = await CommitState.read(transaction, this.schema.tables, batches);
|
|
107
|
+
const pending = new PendingWrites();
|
|
108
|
+
for (const writes of batches) {
|
|
109
|
+
const checked = await this.checkBatch(transaction, state, pending, writes);
|
|
110
|
+
if (checked.kind === "refused") {
|
|
111
|
+
refused = { error: checked.refused };
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
const seq = seqFromNumber(next++);
|
|
115
|
+
state.apply(writes, checked.actions, seq);
|
|
116
|
+
pending.add(writes, checked.actions, seq, state);
|
|
117
|
+
seqs.push(seq);
|
|
118
|
+
candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes));
|
|
119
|
+
}
|
|
120
|
+
await pending.flush(transaction, this.schema.tables);
|
|
121
|
+
if (seqs.length > 0) {
|
|
122
|
+
await this.writeMetadata(transaction, Math.max(Number(metadata.next_id), candidateNextId), next);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
this.nextId = Math.max(this.nextId, candidateNextId);
|
|
126
|
+
// `COMMIT` returned: the stored batches are durable.
|
|
127
|
+
for (const [index, seq] of seqs.entries())
|
|
128
|
+
receive(index, seq);
|
|
129
|
+
return refused === undefined
|
|
130
|
+
? { kind: "stored", stored: seqs.length }
|
|
131
|
+
: { kind: "refused", stored: seqs.length, refused: refused.error };
|
|
132
|
+
}
|
|
133
|
+
async readMetadata(executor) {
|
|
134
|
+
const metadata = await executor.get(`SELECT next_id, next_seq FROM ${this.schema.tables.durableMetadata} WHERE singleton = 1`);
|
|
135
|
+
if (metadata === undefined)
|
|
136
|
+
throw new Error("Durable SQLite metadata is missing");
|
|
137
|
+
return metadata;
|
|
138
|
+
}
|
|
139
|
+
async writeMetadata(executor, nextId, nextSeq) {
|
|
140
|
+
await executor.run(`UPDATE ${this.schema.tables.durableMetadata} SET next_id = ?, next_seq = ? WHERE singleton = 1`, String(nextId), nextSeq);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Durable's own checks of one batch, against what the batches before it left: its document actions, or its refusal.
|
|
144
|
+
* Only these checks refuse; a failure of a database call rejects. A copy reads its source from the database, so the
|
|
145
|
+
* batches before it are written first.
|
|
146
|
+
*/
|
|
147
|
+
async checkBatch(transaction, state, pending, writes) {
|
|
148
|
+
let actions;
|
|
149
|
+
try {
|
|
150
|
+
actions = prepareDocumentActions(writes);
|
|
151
|
+
state.check(writes, actions);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
return { kind: "refused", refused: error };
|
|
155
|
+
}
|
|
156
|
+
if (![...actions.values()].some((action) => action.copy !== undefined))
|
|
157
|
+
return { kind: "checked", actions };
|
|
158
|
+
await pending.flush(transaction, this.schema.tables);
|
|
159
|
+
const calls = { failed: false };
|
|
160
|
+
try {
|
|
161
|
+
await this.resolveCopies(watchCalls(transaction, calls), actions);
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (calls.failed)
|
|
165
|
+
throw error;
|
|
166
|
+
return { kind: "refused", refused: error };
|
|
167
|
+
}
|
|
168
|
+
return { kind: "checked", actions };
|
|
169
|
+
}
|
|
170
|
+
async mintId() {
|
|
171
|
+
this.assertOpen();
|
|
172
|
+
if (!Number.isSafeInteger(this.nextId))
|
|
173
|
+
throw new Error("ID space is exhausted");
|
|
174
|
+
return idFromNumber(this.nextId++);
|
|
175
|
+
}
|
|
176
|
+
async conversation(id, _context) {
|
|
177
|
+
this.assertOpen();
|
|
178
|
+
const row = await this.db.get(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);
|
|
179
|
+
return row === undefined ? undefined : parseJson(row.record);
|
|
180
|
+
}
|
|
181
|
+
async scanConversations(query, limit, cursor, _context) {
|
|
182
|
+
this.assertOpen();
|
|
183
|
+
const start = scanStart(query.order, cursor, "ascending");
|
|
184
|
+
const scan = scanSql(start);
|
|
185
|
+
const clauses = [scan.clause];
|
|
186
|
+
const params = [scan.param];
|
|
187
|
+
if (query.ownerConversationId !== undefined) {
|
|
188
|
+
clauses.push("owner_conversation_id = ?");
|
|
189
|
+
params.push(query.ownerConversationId);
|
|
190
|
+
}
|
|
191
|
+
if (query.ownerTaskId !== undefined) {
|
|
192
|
+
clauses.push("owner_task_id = ?");
|
|
193
|
+
params.push(query.ownerTaskId);
|
|
194
|
+
}
|
|
195
|
+
params.push(limit + 1);
|
|
196
|
+
const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.conversations} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} LIMIT ?`, ...params);
|
|
197
|
+
return page(rows.map((row) => parseJson(row.record)), limit, start.order);
|
|
198
|
+
}
|
|
199
|
+
entry(idOrConversationId, idOrContext, context) {
|
|
200
|
+
return this.admitRead(() => this.readEntry(idOrConversationId, idOrContext, context));
|
|
201
|
+
}
|
|
202
|
+
findLatestHeadMarker(conversationId, atOrBeforeEntryId, _context) {
|
|
203
|
+
return this.admitRead(() => this.readLatestHeadMarker(conversationId, atOrBeforeEntryId));
|
|
204
|
+
}
|
|
205
|
+
scanEntries(query, limit, cursor, _context) {
|
|
206
|
+
return this.admitRead(() => this.readEntries(query, limit, cursor));
|
|
207
|
+
}
|
|
208
|
+
async readEntry(idOrConversationId, idOrContext, context) {
|
|
209
|
+
const id = context === undefined
|
|
210
|
+
? idFromNumber(idOrConversationId)
|
|
211
|
+
: typeof idOrContext === "number"
|
|
212
|
+
? idFromNumber(idOrContext)
|
|
213
|
+
: undefined;
|
|
214
|
+
if (id === undefined)
|
|
215
|
+
throw new StorageRequestError("Storage.entry() requires an entry ID");
|
|
216
|
+
let conversation;
|
|
217
|
+
if (context !== undefined) {
|
|
218
|
+
const conversationId = idFromNumber(idOrConversationId);
|
|
219
|
+
conversation = await this.readConversation(conversationId);
|
|
220
|
+
if (conversation === undefined)
|
|
221
|
+
throw new StorageRequestError(`Unknown conversation: ${conversationId}`);
|
|
222
|
+
}
|
|
223
|
+
const row = await this.db.get(`SELECT record, commit_seq FROM ${this.schema.tables.entries} WHERE id = ?`, id);
|
|
224
|
+
if (row === undefined)
|
|
225
|
+
return undefined;
|
|
226
|
+
const entry = parseJson(row.record);
|
|
227
|
+
if (conversation !== undefined) {
|
|
228
|
+
let upperEntryId = Number.POSITIVE_INFINITY;
|
|
229
|
+
while (conversation.id !== entry.conversationId) {
|
|
230
|
+
if (conversation.parent === undefined)
|
|
231
|
+
return undefined;
|
|
232
|
+
upperEntryId = Math.min(upperEntryId, conversation.parent.at);
|
|
233
|
+
conversation = (await this.readConversation(conversation.parent.conversationId));
|
|
234
|
+
}
|
|
235
|
+
if (entry.id > upperEntryId)
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
return { entry, commitSeq: seqFromNumber(row.commit_seq) };
|
|
239
|
+
}
|
|
240
|
+
async readLatestHeadMarker(conversationId, atOrBeforeEntryId) {
|
|
241
|
+
let conversation = await this.readConversation(conversationId);
|
|
242
|
+
if (conversation === undefined)
|
|
243
|
+
throw new StorageRequestError(`Unknown conversation: ${conversationId}`);
|
|
244
|
+
let upper = atOrBeforeEntryId;
|
|
245
|
+
while (true) {
|
|
246
|
+
const row = upper === undefined
|
|
247
|
+
? await this.db.get(`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1`, conversation.id)
|
|
248
|
+
: await this.db.get(`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1`, conversation.id, upper);
|
|
249
|
+
if (row !== undefined)
|
|
250
|
+
return parseJson(row.record);
|
|
251
|
+
if (conversation.parent === undefined)
|
|
252
|
+
return undefined;
|
|
253
|
+
upper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);
|
|
254
|
+
conversation = (await this.readConversation(conversation.parent.conversationId));
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async readEntries(query, limit, cursor) {
|
|
258
|
+
const { order, after } = scanStart(query.order, cursor, "descending");
|
|
259
|
+
if (order === "ascending")
|
|
260
|
+
return this.readEntriesAscending(query, limit, after);
|
|
261
|
+
let conversation = await this.readConversation(query.conversationId);
|
|
262
|
+
if (conversation === undefined)
|
|
263
|
+
throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);
|
|
264
|
+
let upper = query.maxEntryId;
|
|
265
|
+
if (after !== undefined)
|
|
266
|
+
upper = Math.min(upper ?? Number.MAX_SAFE_INTEGER, after - 1);
|
|
267
|
+
const values = [];
|
|
268
|
+
while (true) {
|
|
269
|
+
const clauses = ["conversation_id = ?"];
|
|
270
|
+
const params = [conversation.id];
|
|
271
|
+
if (query.minEntryId !== undefined) {
|
|
272
|
+
clauses.push("id >= ?");
|
|
273
|
+
params.push(query.minEntryId);
|
|
274
|
+
}
|
|
275
|
+
if (upper !== undefined) {
|
|
276
|
+
clauses.push("id <= ?");
|
|
277
|
+
params.push(upper);
|
|
278
|
+
}
|
|
279
|
+
params.push(limit + 1 - values.length);
|
|
280
|
+
const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(" AND ")} ORDER BY id DESC LIMIT ?`, ...params);
|
|
281
|
+
values.push(...rows.map((row) => parseJson(row.record)));
|
|
282
|
+
if (values.length > limit || conversation.parent === undefined)
|
|
283
|
+
break;
|
|
284
|
+
upper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);
|
|
285
|
+
if (query.minEntryId !== undefined && upper < query.minEntryId)
|
|
286
|
+
break;
|
|
287
|
+
conversation = (await this.readConversation(conversation.parent.conversationId));
|
|
288
|
+
}
|
|
289
|
+
return page(values, limit, "descending");
|
|
290
|
+
}
|
|
291
|
+
/** Oldest first: the fork chain's segments from the root conversation forward, each up to its fork point. */
|
|
292
|
+
async readEntriesAscending(query, limit, after) {
|
|
293
|
+
const segments = [];
|
|
294
|
+
let conversation = await this.readConversation(query.conversationId);
|
|
295
|
+
if (conversation === undefined)
|
|
296
|
+
throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);
|
|
297
|
+
let upper = query.maxEntryId;
|
|
298
|
+
while (true) {
|
|
299
|
+
segments.push({ conversationId: conversation.id, upper });
|
|
300
|
+
if (conversation.parent === undefined)
|
|
301
|
+
break;
|
|
302
|
+
upper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);
|
|
303
|
+
if (query.minEntryId !== undefined && upper < query.minEntryId)
|
|
304
|
+
break;
|
|
305
|
+
conversation = (await this.readConversation(conversation.parent.conversationId));
|
|
306
|
+
}
|
|
307
|
+
let lower = query.minEntryId;
|
|
308
|
+
if (after !== undefined)
|
|
309
|
+
lower = Math.max(lower ?? after + 1, after + 1);
|
|
310
|
+
const values = [];
|
|
311
|
+
for (const segment of segments.reverse()) {
|
|
312
|
+
const clauses = ["conversation_id = ?"];
|
|
313
|
+
const params = [segment.conversationId];
|
|
314
|
+
if (lower !== undefined) {
|
|
315
|
+
clauses.push("id >= ?");
|
|
316
|
+
params.push(lower);
|
|
317
|
+
}
|
|
318
|
+
if (segment.upper !== undefined) {
|
|
319
|
+
clauses.push("id <= ?");
|
|
320
|
+
params.push(segment.upper);
|
|
321
|
+
}
|
|
322
|
+
params.push(limit + 1 - values.length);
|
|
323
|
+
const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(" AND ")} ORDER BY id ASC LIMIT ?`, ...params);
|
|
324
|
+
values.push(...rows.map((row) => parseJson(row.record)));
|
|
325
|
+
if (values.length > limit)
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
return page(values, limit, "ascending");
|
|
329
|
+
}
|
|
330
|
+
async task(id, _context) {
|
|
331
|
+
this.assertOpen();
|
|
332
|
+
const row = await this.db.get(`SELECT record FROM ${this.schema.tables.tasks} WHERE id = ?`, id);
|
|
333
|
+
return row === undefined ? undefined : parseJson(row.record);
|
|
334
|
+
}
|
|
335
|
+
async scanTasks(query, limit, cursor, _context) {
|
|
336
|
+
this.assertOpen();
|
|
337
|
+
const start = scanStart(query.order, cursor, "ascending");
|
|
338
|
+
const scan = scanSql(start);
|
|
339
|
+
const clauses = [scan.clause];
|
|
340
|
+
const params = [scan.param];
|
|
341
|
+
if (query.conversationId !== undefined) {
|
|
342
|
+
clauses.push("conversation_id = ?");
|
|
343
|
+
params.push(query.conversationId);
|
|
344
|
+
}
|
|
345
|
+
if (query.kind !== undefined) {
|
|
346
|
+
clauses.push("kind = ?");
|
|
347
|
+
params.push(encodeIndexedString(query.kind));
|
|
348
|
+
}
|
|
349
|
+
if (query.status !== undefined) {
|
|
350
|
+
clauses.push("status = ?");
|
|
351
|
+
params.push(query.status);
|
|
352
|
+
}
|
|
353
|
+
if (query.abortRequested !== undefined) {
|
|
354
|
+
clauses.push("abort_requested = ?");
|
|
355
|
+
params.push(query.abortRequested ? 1 : 0);
|
|
356
|
+
}
|
|
357
|
+
if (query.background !== undefined) {
|
|
358
|
+
clauses.push("background = ?");
|
|
359
|
+
params.push(query.background ? 1 : 0);
|
|
360
|
+
}
|
|
361
|
+
params.push(limit + 1);
|
|
362
|
+
const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.tasks} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} LIMIT ?`, ...params);
|
|
363
|
+
return page(rows.map((row) => parseJson(row.record)), limit, start.order);
|
|
364
|
+
}
|
|
365
|
+
async submission(id, _context) {
|
|
366
|
+
this.assertOpen();
|
|
367
|
+
const row = await this.db.get(`SELECT record FROM ${this.schema.tables.submissions} WHERE id = ?`, id);
|
|
368
|
+
return row === undefined ? undefined : parseJson(row.record);
|
|
369
|
+
}
|
|
370
|
+
async scanSubmissions(query, limit, cursor, _context) {
|
|
371
|
+
this.assertOpen();
|
|
372
|
+
const start = scanStart(query.order, cursor, "ascending");
|
|
373
|
+
const scan = scanSql(start);
|
|
374
|
+
const clauses = [scan.clause];
|
|
375
|
+
const params = [scan.param];
|
|
376
|
+
if (query.conversationId !== undefined) {
|
|
377
|
+
clauses.push("conversation_id = ?");
|
|
378
|
+
params.push(query.conversationId);
|
|
379
|
+
}
|
|
380
|
+
if (query.status !== undefined) {
|
|
381
|
+
clauses.push("status = ?");
|
|
382
|
+
params.push(query.status);
|
|
383
|
+
}
|
|
384
|
+
params.push(limit + 1);
|
|
385
|
+
const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.submissions} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} LIMIT ?`, ...params);
|
|
386
|
+
return page(rows.map((row) => parseJson(row.record)), limit, start.order);
|
|
387
|
+
}
|
|
388
|
+
async submissionByRequest(conversationId, requestId, _context) {
|
|
389
|
+
this.assertOpen();
|
|
390
|
+
const row = await this.db.get(`SELECT record FROM ${this.schema.tables.submissions} WHERE conversation_id = ? AND request_id = ?`, conversationId, encodeIndexedString(requestId));
|
|
391
|
+
return row === undefined ? undefined : parseJson(row.record);
|
|
392
|
+
}
|
|
393
|
+
async findDocument(address, at, _context) {
|
|
394
|
+
this.assertOpen();
|
|
395
|
+
const parts = addressParts(address);
|
|
396
|
+
const sql = at === "current"
|
|
397
|
+
? `SELECT record FROM ${this.schema.tables.documents}
|
|
398
|
+
WHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?
|
|
399
|
+
AND retired_at IS NULL ORDER BY created_at DESC LIMIT 1`
|
|
400
|
+
: `SELECT record FROM ${this.schema.tables.documents}
|
|
401
|
+
WHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?
|
|
402
|
+
AND created_at <= ? AND (retired_at IS NULL OR retired_at > ?)
|
|
403
|
+
ORDER BY created_at DESC LIMIT 1`;
|
|
404
|
+
const params = [parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue];
|
|
405
|
+
if (at !== "current")
|
|
406
|
+
params.push(at, at);
|
|
407
|
+
const row = await this.db.get(sql, ...params);
|
|
408
|
+
return row === undefined ? undefined : parseJson(row.record);
|
|
409
|
+
}
|
|
410
|
+
async document(id, at, _context) {
|
|
411
|
+
this.assertOpen();
|
|
412
|
+
// The record and revision queries must observe one committed state; a commit between them can replace the base.
|
|
413
|
+
return this.db.transaction((transaction) => this.materializeDocument(transaction, id, at));
|
|
414
|
+
}
|
|
415
|
+
async scanDocuments(query, limit, cursor, _context) {
|
|
416
|
+
this.assertOpen();
|
|
417
|
+
const scope = scopeColumns(query.scope);
|
|
418
|
+
const clauses = ["scope_kind = ?", "owner_id = ?", "id > ?"];
|
|
419
|
+
const params = [scope.scopeKind, scope.ownerId, cursorId(cursor) ?? -1];
|
|
420
|
+
if (query.kind !== undefined) {
|
|
421
|
+
clauses.push("kind = ?");
|
|
422
|
+
params.push(encodeIndexedString(query.kind));
|
|
423
|
+
}
|
|
424
|
+
if (query.at === "current") {
|
|
425
|
+
clauses.push("retired_at IS NULL");
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
clauses.push("created_at <= ?", "(retired_at IS NULL OR retired_at > ?)");
|
|
429
|
+
params.push(query.at, query.at);
|
|
430
|
+
}
|
|
431
|
+
params.push(limit + 1);
|
|
432
|
+
const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.documents} WHERE ${clauses.join(" AND ")} ORDER BY id LIMIT ?`, ...params);
|
|
433
|
+
return page(rows.map((row) => parseJson(row.record)), limit);
|
|
434
|
+
}
|
|
435
|
+
close(_context) {
|
|
436
|
+
if (this.closing === undefined) {
|
|
437
|
+
this.closed = true;
|
|
438
|
+
this.closing = this.closeDatabase();
|
|
439
|
+
}
|
|
440
|
+
return this.closing;
|
|
441
|
+
}
|
|
442
|
+
async closeDatabase() {
|
|
443
|
+
if (this.admittedReads > 0) {
|
|
444
|
+
await new Promise((resolve) => {
|
|
445
|
+
this.readsDrained = resolve;
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
await this.db.close();
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Run a read that issues several queries. Close waits for admitted reads, so their later queries never reach a
|
|
452
|
+
* closed database. Single-query reads and transactions are already ordered before close by the database.
|
|
453
|
+
*/
|
|
454
|
+
async admitRead(read) {
|
|
455
|
+
this.assertOpen();
|
|
456
|
+
this.admittedReads++;
|
|
457
|
+
try {
|
|
458
|
+
return await read();
|
|
459
|
+
}
|
|
460
|
+
finally {
|
|
461
|
+
if (--this.admittedReads === 0)
|
|
462
|
+
this.readsDrained?.();
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
async readConversation(id) {
|
|
466
|
+
const row = await this.db.get(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);
|
|
467
|
+
return row === undefined ? undefined : parseJson(row.record);
|
|
468
|
+
}
|
|
469
|
+
async materializeDocument(executor, id, at) {
|
|
470
|
+
const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id);
|
|
471
|
+
if (row === undefined)
|
|
472
|
+
return undefined;
|
|
473
|
+
const record = parseJson(row.record);
|
|
474
|
+
if (at !== "current" && isCurrentOnly(record)) {
|
|
475
|
+
throw new StorageRequestError(`Document ${id} does not retain historical content`);
|
|
476
|
+
}
|
|
477
|
+
if (!isAliveAt(record, at))
|
|
478
|
+
return undefined;
|
|
479
|
+
const upper = at === "current" ? Number.MAX_SAFE_INTEGER : at;
|
|
480
|
+
const base = await executor.get(`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}
|
|
481
|
+
WHERE document_id = ? AND kind = 'base' AND seq <= ? ORDER BY seq DESC LIMIT 1`, id, upper);
|
|
482
|
+
if (base === undefined)
|
|
483
|
+
throw new Error(`Document ${id} is missing a required base`);
|
|
484
|
+
let value = parseJson(base.content);
|
|
485
|
+
const tail = await executor.all(`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}
|
|
486
|
+
WHERE document_id = ? AND seq > ? AND seq <= ? ORDER BY seq`, id, base.seq, upper);
|
|
487
|
+
for (const revision of tail) {
|
|
488
|
+
if (revision.kind !== "delta" || revision.version !== base.version) {
|
|
489
|
+
throw new Error(`Document ${id} crosses a stored version boundary without a base`);
|
|
490
|
+
}
|
|
491
|
+
value = apply(value, parseJson(revision.content));
|
|
492
|
+
}
|
|
493
|
+
return { record, version: base.version, value, deltasSinceBase: tail.length };
|
|
494
|
+
}
|
|
495
|
+
candidateNextId(writes) {
|
|
496
|
+
let nextId = this.nextId;
|
|
497
|
+
for (const write of writes) {
|
|
498
|
+
const id = claimOf(write)?.id;
|
|
499
|
+
if (id !== undefined)
|
|
500
|
+
nextId = Math.max(nextId, id + 1);
|
|
501
|
+
}
|
|
502
|
+
return nextId;
|
|
503
|
+
}
|
|
504
|
+
/** Resolve each copy to a base of its source's state before this batch, which may not change the source. */
|
|
505
|
+
async resolveCopies(executor, actions) {
|
|
506
|
+
for (const [id, action] of actions) {
|
|
507
|
+
if (action.copy === undefined)
|
|
508
|
+
continue;
|
|
509
|
+
try {
|
|
510
|
+
const stored = await this.materializeDocument(executor, action.copy.id, action.copy.at);
|
|
511
|
+
if (stored === undefined)
|
|
512
|
+
throw new Error(`Fork source document ${action.copy.id} cannot be read`);
|
|
513
|
+
const create = action.create;
|
|
514
|
+
if (stored.record.scope.kind !== "conversation" ||
|
|
515
|
+
create.scope.kind !== "conversation" ||
|
|
516
|
+
stored.record.kind !== create.kind ||
|
|
517
|
+
stored.record.key !== create.key ||
|
|
518
|
+
stored.record.history !== create.history ||
|
|
519
|
+
stored.record.fork !== create.fork) {
|
|
520
|
+
throw new Error(`Fork source document ${action.copy.id} does not match the copied record`);
|
|
521
|
+
}
|
|
522
|
+
action.content = { kind: "base", version: stored.version, value: stored.value };
|
|
523
|
+
}
|
|
524
|
+
catch (error) {
|
|
525
|
+
throw new Error(`Document copy ${id} was rejected`, { cause: error });
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
assertOpen() {
|
|
530
|
+
if (this.closed)
|
|
531
|
+
throw new Error("SqliteStorage is closed");
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
//# sourceMappingURL=storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../../src/storage/sqlite/storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAW,MAAM,wBAAwB,CAAC;AAGxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AA+B3D,OAAO,EAAE,UAAU,EAAkB,SAAS,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAuB,aAAa,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC/G,OAAO,EAAE,8BAA8B,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,aAA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AC,CAAC;gBACnG,MAAM,MAAM,GAAG,MAAM,CAAC,MAAO,CAAC;gBAC9B,IACC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,cAAc;oBAC3C,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,cAAc;oBACpC,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI;oBAClC,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,MAAM,CAAC,GAAG;oBAChC,MAAM,CAAC,MAAM,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;oBACxC,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,EACjC,CAAC;oBACF,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,CAAC,IAAI,CAAC,EAAE,mCAAmC,CAAC,CAAC;gBAC5F,CAAC;gBACD,MAAM,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;YACjF,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,MAAM,IAAI,KAAK,CAAC,iBAAiB,EAAE,eAAe,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACvE,CAAC;QACF,CAAC;IACF,CAAC;IAEO,UAAU;QACjB,IAAI,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7D,CAAC;CACD","sourcesContent":["import type { Context } from \"@diffra-ai/chord/context\";\nimport { apply, type Op } from \"@diffra-ai/chord/delta\";\nimport type { JsonValue } from \"@diffra-ai/chord/json\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteValue } from \"@diffra-ai/chord/sqlite\";\nimport { StorageRequestError } from \"../../errors.ts\";\nimport { idFromNumber, seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tCommitResult,\n\tConversationId,\n\tConversationQuery,\n\tConversationRecord,\n\tCursor,\n\tDocumentAddress,\n\tDocumentContent,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentQuery,\n\tDocumentRecord,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tId,\n\tJsonObject,\n\tPage,\n\tScanOrder,\n\tSeq,\n\tStorage,\n\tStorageWrite,\n\tStoredDocument,\n\tSubmissionId,\n\tSubmissionQuery,\n\tSubmissionRecord,\n\tTaskId,\n\tTaskQuery,\n\tTaskRecord,\n} from \"../../types.ts\";\nimport { nextCursor, type ScanStart, scanStart } from \"../scan.ts\";\nimport { CommitState, claimOf, type DocumentAction, PendingWrites, prepareDocumentActions } from \"./commit.ts\";\nimport { applySqliteMigrationsForSchema } from \"./migrations.ts\";\nimport { addressParts, encodeIndexedString, isCurrentOnly, parseJson, scopeColumns } from \"./rows.ts\";\nimport { createSqliteSchema, type SqliteSchema } from \"./schema.ts\";\n\ntype StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype JsonRow = { readonly record: string };\ntype EntryJsonRow = { readonly record: string; readonly commit_seq: number };\ntype RevisionRow = {\n\treadonly seq: number;\n\treadonly kind: DocumentContent[\"kind\"];\n\treadonly version: number;\n\treadonly content: string;\n};\ntype MetadataRow = { readonly next_id: string; readonly next_seq: number };\n\nexport type SqliteStorageOptions = {\n\t/**\n\t * Prefix for every table and index in the durable schema. It must be a SQLite identifier and must not use\n\t * SQLite's reserved `sqlite_` prefix. Existing data is not migrated when this changes.\n\t */\n\treadonly prefix?: string;\n};\n\nconst cursorId = <I extends Id<string>>(cursor: Cursor | undefined): I | undefined => {\n\tconst after = cursor?.after;\n\tif (after === undefined) return undefined;\n\tif (typeof after !== \"number\" || !Number.isSafeInteger(after))\n\t\tthrow new StorageRequestError(\"Invalid storage cursor\");\n\treturn idFromNumber<I>(after);\n};\n\nconst page = <T extends { readonly id: Id<string> }>(\n\tvalues: readonly T[],\n\tlimit: number,\n\torder: ScanOrder = \"ascending\",\n): Page<T, Cursor> => {\n\tconst items = values.slice(0, limit);\n\tif (values.length <= limit) return { items };\n\treturn { items, next: nextCursor(items.at(-1)!.id, order) };\n};\n\n/** The ID condition, its parameter, and the `ORDER BY` direction of a table scan. */\nconst scanSql = (start: ScanStart): { readonly clause: string; readonly param: number; readonly direction: string } =>\n\tstart.order === \"ascending\"\n\t\t? { clause: \"id > ?\", param: start.after ?? -1, direction: \"ASC\" }\n\t\t: { clause: \"id < ?\", param: start.after ?? Number.MAX_SAFE_INTEGER, direction: \"DESC\" };\n\nconst isAliveAt = (record: DocumentRecord, at: DocumentPoint): boolean => {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n};\n\n/** Whether a database call of the checks failed, whatever it threw or rejected with. */\ntype CheckCalls = { failed: boolean };\n\n/**\n * `executor`, setting `calls.failed` when one of its calls throws, synchronously (a synchronous driver) or by\n * rejecting, with any value: then a failing check is the database's, not one of Durable's own.\n */\nfunction watchCalls(executor: SqliteExecutor, calls: CheckCalls): SqliteExecutor {\n\tconst watched = async <T>(call: () => Promise<T>): Promise<T> => {\n\t\ttry {\n\t\t\treturn await call();\n\t\t} catch (error) {\n\t\t\tcalls.failed = true;\n\t\t\tthrow error;\n\t\t}\n\t};\n\treturn {\n\t\texec: (sql) => watched(() => executor.exec(sql)),\n\t\trun: (sql, ...params) => watched(() => executor.run(sql, ...params)),\n\t\trunCounted: (sql, ...params) => watched(() => executor.runCounted(sql, ...params)),\n\t\tget: (sql, ...params) => watched(() => executor.get(sql, ...params)),\n\t\tall: (sql, ...params) => watched(() => executor.all(sql, ...params)),\n\t};\n}\n\n/** Portable SQLite implementation of the Pico storage contract. */\nexport class SqliteStorage implements Storage {\n\tprivate readonly db: SqliteDatabase;\n\tprivate readonly schema: SqliteSchema;\n\tprivate nextId: number;\n\tprivate closed = false;\n\tprivate closing: Promise<void> | undefined;\n\tprivate admittedReads = 0;\n\tprivate readsDrained: (() => void) | undefined;\n\n\tprivate constructor(db: SqliteDatabase, schema: SqliteSchema, nextId: number) {\n\t\tthis.db = db;\n\t\tthis.schema = schema;\n\t\tthis.nextId = nextId;\n\t}\n\n\t/** Initialize storage over an owned SQLite database facade. */\n\tstatic async open(db: SqliteDatabase, options: SqliteStorageOptions = {}): Promise<SqliteStorage> {\n\t\ttry {\n\t\t\tconst schema = createSqliteSchema(options.prefix);\n\t\t\tawait applySqliteMigrationsForSchema(db, schema);\n\t\t\tconst metadata = await db.get<MetadataRow>(\n\t\t\t\t`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`,\n\t\t\t);\n\t\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\t\treturn new SqliteStorage(db, schema, Number(metadata.next_id));\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait db.close();\n\t\t\t} catch {\n\t\t\t\t// Preserve the initialization failure.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Commit `batches` in one SQL transaction, each with its own seq. Each batch is checked before it writes anything,\n\t * against the state the earlier ones left, and the first one refused ends the batch: the transaction commits the ones\n\t * before it. No savepoints, which Durable Objects do not allow: the checks run before the writes instead. The checks\n\t * read the stored state of all batches up front and run in memory, and the accepted batches are written per table in\n\t * multi-row statements (`commit.ts`), so a call costs a few statements whatever its number of batches. A batch with a\n\t * copy reads the copy's source from the database: the batches before it are written first, so a call of many fork\n\t * batches costs a few statements per fork.\n\t */\n\tasync commit(\n\t\tbatches: readonly (readonly StorageWrite[])[],\n\t\treceive: (index: number, seq: Seq) => void,\n\t\t_context: Context,\n\t): Promise<CommitResult> {\n\t\tthis.assertOpen();\n\t\tconst seqs: Seq[] = [];\n\t\tlet refused: { readonly error: unknown } | undefined;\n\t\tlet candidateNextId = this.nextId;\n\t\tawait this.db.transaction(async (transaction) => {\n\t\t\tconst metadata = await this.readMetadata(transaction);\n\t\t\tlet next = metadata.next_seq;\n\t\t\t// A failure of the database rejects the call and rolls back the batches before it with the transaction.\n\t\t\tconst state = await CommitState.read(transaction, this.schema.tables, batches);\n\t\t\tconst pending = new PendingWrites();\n\t\t\tfor (const writes of batches) {\n\t\t\t\tconst checked = await this.checkBatch(transaction, state, pending, writes);\n\t\t\t\tif (checked.kind === \"refused\") {\n\t\t\t\t\trefused = { error: checked.refused };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst seq = seqFromNumber(next++);\n\t\t\t\tstate.apply(writes, checked.actions, seq);\n\t\t\t\tpending.add(writes, checked.actions, seq, state);\n\t\t\t\tseqs.push(seq);\n\t\t\t\tcandidateNextId = Math.max(candidateNextId, this.candidateNextId(writes));\n\t\t\t}\n\t\t\tawait pending.flush(transaction, this.schema.tables);\n\t\t\tif (seqs.length > 0) {\n\t\t\t\tawait this.writeMetadata(transaction, Math.max(Number(metadata.next_id), candidateNextId), next);\n\t\t\t}\n\t\t});\n\t\tthis.nextId = Math.max(this.nextId, candidateNextId);\n\t\t// `COMMIT` returned: the stored batches are durable.\n\t\tfor (const [index, seq] of seqs.entries()) receive(index, seq);\n\t\treturn refused === undefined\n\t\t\t? { kind: \"stored\", stored: seqs.length }\n\t\t\t: { kind: \"refused\", stored: seqs.length, refused: refused.error };\n\t}\n\n\tprivate async readMetadata(executor: SqliteExecutor): Promise<MetadataRow> {\n\t\tconst metadata = await executor.get<MetadataRow>(\n\t\t\t`SELECT next_id, next_seq FROM ${this.schema.tables.durableMetadata} WHERE singleton = 1`,\n\t\t);\n\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\treturn metadata;\n\t}\n\n\tprivate async writeMetadata(executor: SqliteExecutor, nextId: number, nextSeq: number): Promise<void> {\n\t\tawait executor.run(\n\t\t\t`UPDATE ${this.schema.tables.durableMetadata} SET next_id = ?, next_seq = ? WHERE singleton = 1`,\n\t\t\tString(nextId),\n\t\t\tnextSeq,\n\t\t);\n\t}\n\n\t/**\n\t * Durable's own checks of one batch, against what the batches before it left: its document actions, or its refusal.\n\t * Only these checks refuse; a failure of a database call rejects. A copy reads its source from the database, so the\n\t * batches before it are written first.\n\t */\n\tprivate async checkBatch(\n\t\ttransaction: SqliteExecutor,\n\t\tstate: CommitState,\n\t\tpending: PendingWrites,\n\t\twrites: readonly StorageWrite[],\n\t): Promise<\n\t\t| { readonly kind: \"checked\"; readonly actions: Map<DocumentId, DocumentAction> }\n\t\t| { readonly kind: \"refused\"; readonly refused: unknown }\n\t> {\n\t\tlet actions: Map<DocumentId, DocumentAction>;\n\t\ttry {\n\t\t\tactions = prepareDocumentActions(writes);\n\t\t\tstate.check(writes, actions);\n\t\t} catch (error) {\n\t\t\treturn { kind: \"refused\", refused: error };\n\t\t}\n\t\tif (![...actions.values()].some((action) => action.copy !== undefined)) return { kind: \"checked\", actions };\n\t\tawait pending.flush(transaction, this.schema.tables);\n\t\tconst calls: CheckCalls = { failed: false };\n\t\ttry {\n\t\t\tawait this.resolveCopies(watchCalls(transaction, calls), actions);\n\t\t} catch (error) {\n\t\t\tif (calls.failed) throw error;\n\t\t\treturn { kind: \"refused\", refused: error };\n\t\t}\n\t\treturn { kind: \"checked\", actions };\n\t}\n\n\tasync mintId<I extends Id<string>>(): Promise<I> {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(this.nextId)) throw new Error(\"ID space is exhausted\");\n\t\treturn idFromNumber<I>(this.nextId++);\n\t}\n\n\tasync conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tasync scanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<ConversationRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.ownerConversationId !== undefined) {\n\t\t\tclauses.push(\"owner_conversation_id = ?\");\n\t\t\tparams.push(query.ownerConversationId);\n\t\t}\n\t\tif (query.ownerTaskId !== undefined) {\n\t\t\tclauses.push(\"owner_task_id = ?\");\n\t\t\tparams.push(query.ownerTaskId);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.conversations} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<ConversationRecord>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tentry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tconversationId: ConversationId,\n\t\tid: EntryId,\n\t\tcontext: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\treturn this.admitRead(() => this.readEntry(idOrConversationId, idOrContext, context));\n\t}\n\n\tfindLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t\t_context: Context,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\treturn this.admitRead(() => this.readLatestHeadMarker(conversationId, atOrBeforeEntryId));\n\t}\n\n\tscanEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\treturn this.admitRead(() => this.readEntries(query, limit, cursor));\n\t}\n\n\tprivate async readEntry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\tconst id =\n\t\t\tcontext === undefined\n\t\t\t\t? idFromNumber<EntryId>(idOrConversationId)\n\t\t\t\t: typeof idOrContext === \"number\"\n\t\t\t\t\t? idFromNumber<EntryId>(idOrContext)\n\t\t\t\t\t: undefined;\n\t\tif (id === undefined) throw new StorageRequestError(\"Storage.entry() requires an entry ID\");\n\t\tlet conversation: ConversationRecord | undefined;\n\t\tif (context !== undefined) {\n\t\t\tconst conversationId = idFromNumber<ConversationId>(idOrConversationId);\n\t\t\tconversation = await this.readConversation(conversationId);\n\t\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tconst row = await this.db.get<EntryJsonRow>(\n\t\t\t`SELECT record, commit_seq FROM ${this.schema.tables.entries} WHERE id = ?`,\n\t\t\tid,\n\t\t);\n\t\tif (row === undefined) return undefined;\n\t\tconst entry = parseJson<EntryRecord>(row.record);\n\t\tif (conversation !== undefined) {\n\t\t\tlet upperEntryId = Number.POSITIVE_INFINITY;\n\t\t\twhile (conversation.id !== entry.conversationId) {\n\t\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t\t}\n\t\t\tif (entry.id > upperEntryId) return undefined;\n\t\t}\n\t\treturn { entry, commitSeq: seqFromNumber(row.commit_seq) };\n\t}\n\n\tprivate async readLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\tlet conversation = await this.readConversation(conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\tlet upper: number | undefined = atOrBeforeEntryId;\n\t\twhile (true) {\n\t\t\tconst row =\n\t\t\t\tupper === undefined\n\t\t\t\t\t? await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1`,\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t)\n\t\t\t\t\t: await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1`,\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t\tupper,\n\t\t\t\t\t\t);\n\t\t\tif (row !== undefined) return parseJson<EntryRecord & { readonly head: EntryId }>(row.record);\n\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t}\n\n\tprivate async readEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst { order, after } = scanStart(query.order, cursor, \"descending\");\n\t\tif (order === \"ascending\") return this.readEntriesAscending(query, limit, after);\n\t\tlet conversation = await this.readConversation(query.conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);\n\t\tlet upper: number | undefined = query.maxEntryId;\n\t\tif (after !== undefined) upper = Math.min(upper ?? Number.MAX_SAFE_INTEGER, after - 1);\n\t\tconst values: EntryRecord[] = [];\n\t\twhile (true) {\n\t\t\tconst clauses = [\"conversation_id = ?\"];\n\t\t\tconst params: SqliteValue[] = [conversation.id];\n\t\t\tif (query.minEntryId !== undefined) {\n\t\t\t\tclauses.push(\"id >= ?\");\n\t\t\t\tparams.push(query.minEntryId);\n\t\t\t}\n\t\t\tif (upper !== undefined) {\n\t\t\t\tclauses.push(\"id <= ?\");\n\t\t\t\tparams.push(upper);\n\t\t\t}\n\t\t\tparams.push(limit + 1 - values.length);\n\t\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(\" AND \")} ORDER BY id DESC LIMIT ?`,\n\t\t\t\t...params,\n\t\t\t);\n\t\t\tvalues.push(...rows.map((row) => parseJson<EntryRecord>(row.record)));\n\t\t\tif (values.length > limit || conversation.parent === undefined) break;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tif (query.minEntryId !== undefined && upper < query.minEntryId) break;\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t\treturn page(values, limit, \"descending\");\n\t}\n\n\t/** Oldest first: the fork chain's segments from the root conversation forward, each up to its fork point. */\n\tprivate async readEntriesAscending(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tafter: number | undefined,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst segments: { readonly conversationId: ConversationId; readonly upper: number | undefined }[] = [];\n\t\tlet conversation = await this.readConversation(query.conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);\n\t\tlet upper: number | undefined = query.maxEntryId;\n\t\twhile (true) {\n\t\t\tsegments.push({ conversationId: conversation.id, upper });\n\t\t\tif (conversation.parent === undefined) break;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tif (query.minEntryId !== undefined && upper < query.minEntryId) break;\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t\tlet lower: number | undefined = query.minEntryId;\n\t\tif (after !== undefined) lower = Math.max(lower ?? after + 1, after + 1);\n\t\tconst values: EntryRecord[] = [];\n\t\tfor (const segment of segments.reverse()) {\n\t\t\tconst clauses = [\"conversation_id = ?\"];\n\t\t\tconst params: SqliteValue[] = [segment.conversationId];\n\t\t\tif (lower !== undefined) {\n\t\t\t\tclauses.push(\"id >= ?\");\n\t\t\t\tparams.push(lower);\n\t\t\t}\n\t\t\tif (segment.upper !== undefined) {\n\t\t\t\tclauses.push(\"id <= ?\");\n\t\t\t\tparams.push(segment.upper);\n\t\t\t}\n\t\t\tparams.push(limit + 1 - values.length);\n\t\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(\" AND \")} ORDER BY id ASC LIMIT ?`,\n\t\t\t\t...params,\n\t\t\t);\n\t\t\tvalues.push(...rows.map((row) => parseJson<EntryRecord>(row.record)));\n\t\t\tif (values.length > limit) break;\n\t\t}\n\t\treturn page(values, limit, \"ascending\");\n\t}\n\n\tasync task(id: TaskId, _context: Context): Promise<StoredTask | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.tasks} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<StoredTask>(row.record);\n\t}\n\n\tasync scanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<StoredTask, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tif (query.abortRequested !== undefined) {\n\t\t\tclauses.push(\"abort_requested = ?\");\n\t\t\tparams.push(query.abortRequested ? 1 : 0);\n\t\t}\n\t\tif (query.background !== undefined) {\n\t\t\tclauses.push(\"background = ?\");\n\t\t\tparams.push(query.background ? 1 : 0);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.tasks} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<StoredTask>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tasync submission(id: SubmissionId, _context: Context): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.submissions} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync scanSubmissions(\n\t\tquery: SubmissionQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<SubmissionRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.submissions} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<SubmissionRecord>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tasync submissionByRequest(\n\t\tconversationId: ConversationId,\n\t\trequestId: string,\n\t\t_context: Context,\n\t): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.submissions} WHERE conversation_id = ? AND request_id = ?`,\n\t\t\tconversationId,\n\t\t\tencodeIndexedString(requestId),\n\t\t);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync findDocument(\n\t\taddress: DocumentAddress,\n\t\tat: DocumentPoint,\n\t\t_context: Context,\n\t): Promise<DocumentRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst parts = addressParts(address);\n\t\tconst sql =\n\t\t\tat === \"current\"\n\t\t\t\t? `SELECT record FROM ${this.schema.tables.documents}\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND retired_at IS NULL ORDER BY created_at DESC LIMIT 1`\n\t\t\t\t: `SELECT record FROM ${this.schema.tables.documents}\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND created_at <= ? AND (retired_at IS NULL OR retired_at > ?)\n\t\t\t\t\tORDER BY created_at DESC LIMIT 1`;\n\t\tconst params: SqliteValue[] = [parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue];\n\t\tif (at !== \"current\") params.push(at, at);\n\t\tconst row = await this.db.get<JsonRow>(sql, ...params);\n\t\treturn row === undefined ? undefined : parseJson<DocumentRecord>(row.record);\n\t}\n\n\tasync document(id: DocumentId, at: DocumentPoint, _context: Context): Promise<StoredDocument | undefined> {\n\t\tthis.assertOpen();\n\t\t// The record and revision queries must observe one committed state; a commit between them can replace the base.\n\t\treturn this.db.transaction((transaction) => this.materializeDocument(transaction, id, at));\n\t}\n\n\tasync scanDocuments(\n\t\tquery: DocumentQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<DocumentRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst scope = scopeColumns(query.scope);\n\t\tconst clauses = [\"scope_kind = ?\", \"owner_id = ?\", \"id > ?\"];\n\t\tconst params: SqliteValue[] = [scope.scopeKind, scope.ownerId, cursorId(cursor) ?? -1];\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.at === \"current\") {\n\t\t\tclauses.push(\"retired_at IS NULL\");\n\t\t} else {\n\t\t\tclauses.push(\"created_at <= ?\", \"(retired_at IS NULL OR retired_at > ?)\");\n\t\t\tparams.push(query.at, query.at);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.documents} WHERE ${clauses.join(\" AND \")} ORDER BY id LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<DocumentRecord>(row.record)),\n\t\t\tlimit,\n\t\t);\n\t}\n\n\tclose(_context: Context): Promise<void> {\n\t\tif (this.closing === undefined) {\n\t\t\tthis.closed = true;\n\t\t\tthis.closing = this.closeDatabase();\n\t\t}\n\t\treturn this.closing;\n\t}\n\n\tprivate async closeDatabase(): Promise<void> {\n\t\tif (this.admittedReads > 0) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tthis.readsDrained = resolve;\n\t\t\t});\n\t\t}\n\t\tawait this.db.close();\n\t}\n\n\t/**\n\t * Run a read that issues several queries. Close waits for admitted reads, so their later queries never reach a\n\t * closed database. Single-query reads and transactions are already ordered before close by the database.\n\t */\n\tprivate async admitRead<T>(read: () => Promise<T>): Promise<T> {\n\t\tthis.assertOpen();\n\t\tthis.admittedReads++;\n\t\ttry {\n\t\t\treturn await read();\n\t\t} finally {\n\t\t\tif (--this.admittedReads === 0) this.readsDrained?.();\n\t\t}\n\t}\n\n\tprivate async readConversation(id: ConversationId): Promise<ConversationRecord | undefined> {\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tprivate async materializeDocument(\n\t\texecutor: SqliteExecutor,\n\t\tid: DocumentId,\n\t\tat: DocumentPoint,\n\t): Promise<StoredDocument | undefined> {\n\t\tconst row = await executor.get<JsonRow>(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id);\n\t\tif (row === undefined) return undefined;\n\t\tconst record = parseJson<DocumentRecord>(row.record);\n\t\tif (at !== \"current\" && isCurrentOnly(record)) {\n\t\t\tthrow new StorageRequestError(`Document ${id} does not retain historical content`);\n\t\t}\n\t\tif (!isAliveAt(record, at)) return undefined;\n\t\tconst upper = at === \"current\" ? Number.MAX_SAFE_INTEGER : at;\n\t\tconst base = await executor.get<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}\n\t\t\t\tWHERE document_id = ? AND kind = 'base' AND seq <= ? ORDER BY seq DESC LIMIT 1`,\n\t\t\tid,\n\t\t\tupper,\n\t\t);\n\t\tif (base === undefined) throw new Error(`Document ${id} is missing a required base`);\n\t\tlet value = parseJson<JsonObject>(base.content);\n\t\tconst tail = await executor.all<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}\n\t\t\t\tWHERE document_id = ? AND seq > ? AND seq <= ? ORDER BY seq`,\n\t\t\tid,\n\t\t\tbase.seq,\n\t\t\tupper,\n\t\t);\n\t\tfor (const revision of tail) {\n\t\t\tif (revision.kind !== \"delta\" || revision.version !== base.version) {\n\t\t\t\tthrow new Error(`Document ${id} crosses a stored version boundary without a base`);\n\t\t\t}\n\t\t\tvalue = apply(value, parseJson<readonly Op[]>(revision.content)) as JsonObject;\n\t\t}\n\t\treturn { record, version: base.version, value, deltasSinceBase: tail.length };\n\t}\n\n\tprivate candidateNextId(writes: readonly StorageWrite[]): number {\n\t\tlet nextId = this.nextId;\n\t\tfor (const write of writes) {\n\t\t\tconst id = claimOf(write)?.id;\n\t\t\tif (id !== undefined) nextId = Math.max(nextId, id + 1);\n\t\t}\n\t\treturn nextId;\n\t}\n\n\t/** Resolve each copy to a base of its source's state before this batch, which may not change the source. */\n\tprivate async resolveCopies(executor: SqliteExecutor, actions: Map<DocumentId, DocumentAction>): Promise<void> {\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.copy === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst stored = await this.materializeDocument(executor, action.copy.id, action.copy.at);\n\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${action.copy.id} cannot be read`);\n\t\t\t\tconst create = action.create!;\n\t\t\t\tif (\n\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\tcreate.scope.kind !== \"conversation\" ||\n\t\t\t\t\tstored.record.kind !== create.kind ||\n\t\t\t\t\tstored.record.key !== create.key ||\n\t\t\t\t\tstored.record.history !== create.history ||\n\t\t\t\t\tstored.record.fork !== create.fork\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Fork source document ${action.copy.id} does not match the copied record`);\n\t\t\t\t}\n\t\t\t\taction.content = { kind: \"base\", version: stored.version, value: stored.value };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Document copy ${id} was rejected`, { cause: error });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this.closed) throw new Error(\"SqliteStorage is closed\");\n\t}\n}\n"]}
|