@draht/durable 2026.11.27 → 2026.12.3

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 (119) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/codemode/codemode.d.ts.map +1 -1
  3. package/dist/codemode/codemode.js +39 -0
  4. package/dist/codemode/codemode.js.map +1 -1
  5. package/dist/documents.d.ts.map +1 -1
  6. package/dist/documents.js +7 -2
  7. package/dist/documents.js.map +1 -1
  8. package/dist/env/index.d.ts +11 -0
  9. package/dist/env/index.d.ts.map +1 -1
  10. package/dist/env/index.js.map +1 -1
  11. package/dist/env/node.d.ts +1 -0
  12. package/dist/env/node.d.ts.map +1 -1
  13. package/dist/env/node.js +114 -34
  14. package/dist/env/node.js.map +1 -1
  15. package/dist/harness/task-graph.d.ts.map +1 -1
  16. package/dist/harness/task-graph.js +26 -13
  17. package/dist/harness/task-graph.js.map +1 -1
  18. package/dist/harness/usage.d.ts.map +1 -1
  19. package/dist/harness/usage.js +2 -0
  20. package/dist/harness/usage.js.map +1 -1
  21. package/dist/harness/view.d.ts +5 -1
  22. package/dist/harness/view.d.ts.map +1 -1
  23. package/dist/harness/view.js +36 -24
  24. package/dist/harness/view.js.map +1 -1
  25. package/dist/ids.d.ts +10 -0
  26. package/dist/ids.d.ts.map +1 -1
  27. package/dist/ids.js +21 -0
  28. package/dist/ids.js.map +1 -1
  29. package/dist/images/encode.d.ts +33 -0
  30. package/dist/images/encode.d.ts.map +1 -0
  31. package/dist/images/encode.js +69 -0
  32. package/dist/images/encode.js.map +1 -0
  33. package/dist/images/index.d.ts +4 -4
  34. package/dist/images/index.d.ts.map +1 -1
  35. package/dist/images/index.js +41 -58
  36. package/dist/images/index.js.map +1 -1
  37. package/dist/images/node-worker.d.ts +1 -18
  38. package/dist/images/node-worker.d.ts.map +1 -1
  39. package/dist/images/node-worker.js +2 -12
  40. package/dist/images/node-worker.js.map +1 -1
  41. package/dist/images/node.d.ts.map +1 -1
  42. package/dist/images/node.js +4 -103
  43. package/dist/images/node.js.map +1 -1
  44. package/dist/images/pi-images/cloudflare.d.ts +8 -0
  45. package/dist/images/pi-images/cloudflare.d.ts.map +1 -0
  46. package/dist/images/pi-images/cloudflare.js +14 -0
  47. package/dist/images/pi-images/cloudflare.js.map +1 -0
  48. package/dist/images/pi-images/index.d.ts +37 -0
  49. package/dist/images/pi-images/index.d.ts.map +1 -0
  50. package/dist/images/pi-images/index.js +22 -0
  51. package/dist/images/pi-images/index.js.map +1 -0
  52. package/dist/images/pi-images/installed.d.ts +8 -0
  53. package/dist/images/pi-images/installed.d.ts.map +1 -0
  54. package/dist/images/pi-images/installed.js +24 -0
  55. package/dist/images/pi-images/installed.js.map +1 -0
  56. package/dist/images/pi-images/node-worker.d.ts +2 -0
  57. package/dist/images/pi-images/node-worker.d.ts.map +1 -0
  58. package/dist/images/pi-images/node-worker.js +7 -0
  59. package/dist/images/pi-images/node-worker.js.map +1 -0
  60. package/dist/images/pi-images/node.d.ts +24 -0
  61. package/dist/images/pi-images/node.d.ts.map +1 -0
  62. package/dist/images/pi-images/node.js +18 -0
  63. package/dist/images/pi-images/node.js.map +1 -0
  64. package/dist/images/pi-images/processor.d.ts +21 -0
  65. package/dist/images/pi-images/processor.d.ts.map +1 -0
  66. package/dist/images/pi-images/processor.js +117 -0
  67. package/dist/images/pi-images/processor.js.map +1 -0
  68. package/dist/images/thread.d.ts +27 -0
  69. package/dist/images/thread.d.ts.map +1 -0
  70. package/dist/images/thread.js +131 -0
  71. package/dist/images/thread.js.map +1 -0
  72. package/dist/session/session.js +32 -6
  73. package/dist/session/session.js.map +1 -1
  74. package/dist/session/transaction.d.ts.map +1 -1
  75. package/dist/session/transaction.js +3 -0
  76. package/dist/session/transaction.js.map +1 -1
  77. package/dist/storage/jsonl/storage.d.ts +6 -0
  78. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  79. package/dist/storage/jsonl/storage.js +65 -0
  80. package/dist/storage/jsonl/storage.js.map +1 -1
  81. package/dist/storage/sqlite/commit.d.ts.map +1 -1
  82. package/dist/storage/sqlite/commit.js +3 -3
  83. package/dist/storage/sqlite/commit.js.map +1 -1
  84. package/dist/storage/sqlite/migrations.d.ts.map +1 -1
  85. package/dist/storage/sqlite/migrations.js +20 -0
  86. package/dist/storage/sqlite/migrations.js.map +1 -1
  87. package/dist/storage/sqlite/rows.d.ts +0 -2
  88. package/dist/storage/sqlite/rows.d.ts.map +1 -1
  89. package/dist/storage/sqlite/rows.js +3 -5
  90. package/dist/storage/sqlite/rows.js.map +1 -1
  91. package/dist/storage/sqlite/storage.d.ts +1 -1
  92. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  93. package/dist/storage/sqlite/storage.js +11 -10
  94. package/dist/storage/sqlite/storage.js.map +1 -1
  95. package/dist/storage/store/documents.d.ts.map +1 -1
  96. package/dist/storage/store/documents.js +4 -6
  97. package/dist/storage/store/documents.js.map +1 -1
  98. package/dist/storage/store/migrations.d.ts +10 -0
  99. package/dist/storage/store/migrations.d.ts.map +1 -0
  100. package/dist/storage/store/migrations.js +44 -0
  101. package/dist/storage/store/migrations.js.map +1 -0
  102. package/dist/storage/store/storage.d.ts +3 -2
  103. package/dist/storage/store/storage.d.ts.map +1 -1
  104. package/dist/storage/store/storage.js +9 -6
  105. package/dist/storage/store/storage.js.map +1 -1
  106. package/dist/storage/store/tables.d.ts +21 -3
  107. package/dist/storage/store/tables.d.ts.map +1 -1
  108. package/dist/storage/store/tables.js +14 -10
  109. package/dist/storage/store/tables.js.map +1 -1
  110. package/dist/tasks.d.ts.map +1 -1
  111. package/dist/tasks.js +2 -0
  112. package/dist/tasks.js.map +1 -1
  113. package/dist/testing/storage-conformance.d.ts.map +1 -1
  114. package/dist/testing/storage-conformance.js +0 -74
  115. package/dist/testing/storage-conformance.js.map +1 -1
  116. package/dist/types.d.ts +4 -1
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/package.json +26 -6
@@ -1 +1 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AC;QACpB,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;QAC1B,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;CACD","sourcesContent":["// One `SqliteStorage.commit()` call in a few statements whatever its number of batches: the check state of all its\n// batches read up front (`CommitState`), each batch checked in memory against what the batches before it left, and the\n// accepted batches written per table (`PendingWrites`, through `statements.ts`). Over a remote SQLite every statement\n// is a round trip while the write lock is held; a group of commits must not cost one round trip per write.\n\nimport type { SqliteExecutor } from \"@draht/chord/sqlite\";\nimport type {\n\tDocumentContent,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentRecord,\n\tId,\n\tSeq,\n\tStorageWrite,\n} from \"../../types.ts\";\nimport {\n\taddressColumnsKey,\n\taddressKey,\n\taddressParts,\n\ttype Cell,\n\tdocumentRow,\n\tencodeIndexedString,\n\tencodeJson,\n\tisCurrentOnly,\n\tparseJson,\n} from \"./rows.ts\";\nimport type { SqliteSchema } from \"./schema.ts\";\nimport { insertRows, readRows, runForEach } from \"./statements.ts\";\n\n/** The table a record ID belongs to, as `record_ids` stores it. */\nexport type TableName = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\n\n/** What one batch does to one document: its creation or copy, its new content, its retirement. */\nexport type DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcopy?: Extract<StorageWrite, { readonly type: \"document.copy\" }>[\"source\"];\n\tcontent?: DocumentContent;\n\tretire: boolean;\n};\n\ntype Tables = SqliteSchema[\"tables\"];\n\n/** The record ID a write claims and its table, if it claims one. */\nexport const claimOf = (write: StorageWrite): { readonly id: Id<string>; readonly table: TableName } | undefined => {\n\tswitch (write.type) {\n\t\tcase \"conversation\":\n\t\tcase \"entry\":\n\t\tcase \"task\":\n\t\tcase \"submission\":\n\t\t\treturn { id: write.value.id, table: write.type };\n\t\tcase \"document.create\":\n\t\tcase \"document.copy\":\n\t\t\treturn { id: write.record.id, table: \"document\" };\n\t\tcase \"document.change\":\n\t\tcase \"document.retire\":\n\t\t\treturn undefined;\n\t}\n};\n\n/** One batch's writes per document; throws when a document gets two content commands or two retirements. */\nexport function prepareDocumentActions(writes: readonly StorageWrite[]): Map<DocumentId, DocumentAction> {\n\tconst actions = new Map<DocumentId, DocumentAction>();\n\tfor (const write of writes) {\n\t\tif (\n\t\t\twrite.type !== \"document.create\" &&\n\t\t\twrite.type !== \"document.copy\" &&\n\t\t\twrite.type !== \"document.change\" &&\n\t\t\twrite.type !== \"document.retire\"\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = write.type === \"document.create\" || write.type === \"document.copy\" ? write.record.id : write.id;\n\t\tlet action = actions.get(id);\n\t\tif (action === undefined) {\n\t\t\taction = { retire: false };\n\t\t\tactions.set(id, action);\n\t\t}\n\t\tswitch (write.type) {\n\t\t\tcase \"document.create\":\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.create = write.record;\n\t\t\t\taction.content = write.content;\n\t\t\t\tbreak;\n\t\t\tcase \"document.copy\":\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.create = write.record;\n\t\t\t\taction.copy = write.source;\n\t\t\t\tbreak;\n\t\t\tcase \"document.change\":\n\t\t\t\tif (action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.content = write.content;\n\t\t\t\tbreak;\n\t\t\tcase \"document.retire\":\n\t\t\t\tif (action.retire) throw new Error(`Document ${id} is retired more than once`);\n\t\t\t\taction.retire = true;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn actions;\n}\n\ntype RecordIdRow = { readonly id: number; readonly record_type: TableName };\ntype DocumentRow = { readonly record: string };\ntype VersionRow = { readonly document_id: number; readonly version: number | null };\ntype AddressRow = {\n\treadonly id: number;\n\treadonly kind: string;\n\treadonly scope_kind: string;\n\treadonly owner_id: number;\n\treadonly family: number;\n\treadonly key_value: string;\n};\n\n/**\n * What the checks of one call's batches read: the stored state of every ID, document and address the batches touch,\n * read in a few statements when the call starts, then advanced in memory by each accepted batch.\n */\nexport class CommitState {\n\t/** The table of each claimed ID; absent: unclaimed. */\n\treadonly #recordIds: Map<number, TableName>;\n\t/** Each touched document's record; absent: no such document. */\n\treadonly #documents: Map<number, DocumentRecord>;\n\t/** The version of each delta-changed document's latest revision; absent: no revision. */\n\treadonly #versions: Map<number, number>;\n\t/** The current incarnation of each created address (`addressKey`); `undefined`: none. */\n\treadonly #current: Map<string, DocumentId | undefined>;\n\n\tprivate constructor(\n\t\trecordIds: Map<number, TableName>,\n\t\tdocuments: Map<number, DocumentRecord>,\n\t\tversions: Map<number, number>,\n\t\tcurrent: Map<string, DocumentId | undefined>,\n\t) {\n\t\tthis.#recordIds = recordIds;\n\t\tthis.#documents = documents;\n\t\tthis.#versions = versions;\n\t\tthis.#current = current;\n\t}\n\n\t/** Reads the stored state the checks of `batches` need: one statement per kind of state (split only by size). */\n\tstatic async read(\n\t\texecutor: SqliteExecutor,\n\t\ttables: Tables,\n\t\tbatches: readonly (readonly StorageWrite[])[],\n\t): Promise<CommitState> {\n\t\tconst ids = new Set<number>();\n\t\tconst documentIds = new Set<number>();\n\t\tconst deltaIds = new Set<number>();\n\t\tconst addresses = new Map<string, ReturnType<typeof addressParts>>();\n\t\tfor (const writes of batches) {\n\t\t\tfor (const write of writes) {\n\t\t\t\tconst claim = claimOf(write);\n\t\t\t\tif (claim !== undefined) ids.add(claim.id);\n\t\t\t\tswitch (write.type) {\n\t\t\t\t\tcase \"document.create\":\n\t\t\t\t\tcase \"document.copy\":\n\t\t\t\t\t\tdocumentIds.add(write.record.id);\n\t\t\t\t\t\taddresses.set(addressKey(write.record), addressParts(write.record));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"document.change\":\n\t\t\t\t\t\tdocumentIds.add(write.id);\n\t\t\t\t\t\tif (write.content.kind === \"delta\") deltaIds.add(write.id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"document.retire\":\n\t\t\t\t\t\tdocumentIds.add(write.id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst recordIds = new Map<number, TableName>();\n\t\tfor (const row of await readRows<RecordIdRow>(\n\t\t\texecutor,\n\t\t\t`SELECT id, record_type FROM ${tables.recordIds} WHERE id IN (SELECT value FROM json_each(?))`,\n\t\t\t[...ids],\n\t\t)) {\n\t\t\trecordIds.set(row.id, row.record_type);\n\t\t}\n\t\tconst documents = new Map<number, DocumentRecord>();\n\t\tfor (const row of await readRows<DocumentRow>(\n\t\t\texecutor,\n\t\t\t`SELECT record FROM ${tables.documents} WHERE id IN (SELECT value FROM json_each(?))`,\n\t\t\t[...documentIds],\n\t\t)) {\n\t\t\tconst record = parseJson<DocumentRecord>(row.record);\n\t\t\tdocuments.set(record.id, record);\n\t\t}\n\t\tconst versions = new Map<number, number>();\n\t\t// Driven by the requested IDs: each latest revision is one descending probe of the primary key.\n\t\tfor (const row of await readRows<VersionRow>(\n\t\t\texecutor,\n\t\t\t`SELECT requested.value AS document_id, (\n\t\t\t\tSELECT version FROM ${tables.documentRevisions} WHERE document_id = requested.value ORDER BY seq DESC LIMIT 1\n\t\t\t) AS version FROM json_each(?) AS requested`,\n\t\t\t[...deltaIds],\n\t\t)) {\n\t\t\tif (row.version !== null) versions.set(row.document_id, row.version);\n\t\t}\n\t\treturn new CommitState(recordIds, documents, versions, await readCurrent(executor, tables, addresses));\n\t}\n\n\t/** Durable's own checks of one batch that need no copy source: throws the refusal. */\n\tcheck(writes: readonly StorageWrite[], actions: ReadonlyMap<DocumentId, DocumentAction>): void {\n\t\tthis.#checkIds(writes);\n\t\tthis.#checkDocuments(actions);\n\t}\n\n\t/** Advances the state past an accepted batch stored at `seq`, its copies resolved to their content. */\n\tapply(writes: readonly StorageWrite[], actions: ReadonlyMap<DocumentId, DocumentAction>, seq: Seq): void {\n\t\tfor (const write of writes) {\n\t\t\t// An accepted batch claims an ID only for its stored table, if it has one (`#checkIds`).\n\t\t\tconst claim = claimOf(write);\n\t\t\tif (claim !== undefined) this.#recordIds.set(claim.id, claim.table);\n\t\t}\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.create !== undefined) {\n\t\t\t\tconst record = { ...action.create, createdAt: seq, ...(action.retire ? { retiredAt: seq } : {}) };\n\t\t\t\tthis.#documents.set(id, record);\n\t\t\t\tif (!action.retire) this.#current.set(addressKey(record), id);\n\t\t\t} else if (action.retire) {\n\t\t\t\tconst record = { ...this.#documents.get(id)!, retiredAt: seq };\n\t\t\t\tthis.#documents.set(id, record);\n\t\t\t\t// The batch may have created the address's next incarnation already: only this one leaves.\n\t\t\t\tconst key = addressKey(record);\n\t\t\t\tif (this.#current.get(key) === id) this.#current.set(key, undefined);\n\t\t\t}\n\t\t\t// A retired document's versions are never read again: every later action on it is refused first.\n\t\t\tif (action.content !== undefined) this.#versions.set(id, action.content.version);\n\t\t}\n\t}\n\n\t/** A document's record as the accepted batches left it. */\n\tdocument(id: DocumentId): DocumentRecord | undefined {\n\t\treturn this.#documents.get(id);\n\t}\n\n\t#checkIds(writes: readonly StorageWrite[]): void {\n\t\tconst claimed = new Map<Id<string>, TableName>();\n\t\tfor (const write of writes) {\n\t\t\tconst claim = claimOf(write);\n\t\t\tif (claim === undefined) continue;\n\t\t\tconst { id, table } = claim;\n\t\t\tconst existing = this.#recordIds.get(id);\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (table === \"conversation\" || table === \"entry\" || table === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== table)\n\t\t\t\t\tthrow new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined && earlier !== table) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, table);\n\t\t}\n\t}\n\n\t#checkDocuments(actions: ReadonlyMap<DocumentId, DocumentAction>): void {\n\t\tconst liveCounts = new Map<string, number>();\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.copy !== undefined && actions.has(action.copy.id)) {\n\t\t\t\tthrow new Error(`Document copy ${id} source is changed in the copy batch`);\n\t\t\t}\n\t\t\tconst existing = this.#documents.get(id);\n\t\t\tif (action.create === undefined && existing === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (action.create !== undefined && existing !== undefined) throw new Error(`Document ${id} already exists`);\n\t\t\tif (existing?.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tif (action.content?.kind === \"delta\") {\n\t\t\t\tconst previous = this.#versions.get(id);\n\t\t\t\tif (previous === undefined) throw new Error(`Document ${id} delta has no base`);\n\t\t\t\tif (previous !== action.content.version)\n\t\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t}\n\t\t\t// A plain change keeps its address's live count: only creations and retirements are counted.\n\t\t\tif (action.create === undefined && !action.retire) continue;\n\t\t\tconst key = addressKey(action.create ?? existing!);\n\t\t\tlet live = liveCounts.get(key);\n\t\t\t// Only created addresses were read: an address no batch creates only loses incarnations, never exceeds one.\n\t\t\tif (live === undefined) live = this.#current.get(key) === undefined ? 0 : 1;\n\t\t\tif (action.retire && existing !== undefined) live--;\n\t\t\tif (action.create !== undefined && !action.retire) live++;\n\t\t\tliveCounts.set(key, live);\n\t\t}\n\t\tfor (const live of liveCounts.values()) {\n\t\t\tif (live > 1) throw new Error(\"Document address already has a current incarnation\");\n\t\t}\n\t}\n}\n\n/** The current incarnation of each of `addresses`, `undefined` for one without. */\nasync function readCurrent(\n\texecutor: SqliteExecutor,\n\ttables: Tables,\n\taddresses: ReadonlyMap<string, ReturnType<typeof addressParts>>,\n): Promise<Map<string, DocumentId | undefined>> {\n\tconst current = new Map<string, DocumentId | undefined>();\n\tfor (const key of addresses.keys()) current.set(key, undefined);\n\tconst rows = await readRows<AddressRow>(\n\t\texecutor,\n\t\t`SELECT document.id, document.kind, document.scope_kind, document.owner_id, document.family, document.key_value\n\t\t\tFROM json_each(?) AS address JOIN ${tables.documents} AS document\n\t\t\tON document.kind = json_extract(address.value, '$[0]') AND document.scope_kind = json_extract(address.value, '$[1]')\n\t\t\tAND document.owner_id = json_extract(address.value, '$[2]') AND document.family = json_extract(address.value, '$[3]')\n\t\t\tAND document.key_value = json_extract(address.value, '$[4]')\n\t\t\tWHERE document.retired_at IS NULL`,\n\t\t[...addresses.values()].map((part) => [part.kind, part.scopeKind, part.ownerId, part.family, part.keyValue]),\n\t);\n\tfor (const row of rows) {\n\t\tcurrent.set(\n\t\t\taddressColumnsKey(row.kind, row.scope_kind, row.owner_id, row.family, row.key_value),\n\t\t\trow.id as DocumentId,\n\t\t);\n\t}\n\treturn current;\n}\n\n/**\n * The writes of the accepted batches not yet written, per table, as their net effect: a task or submission written\n * twice is written once, as last written; a current-only document's revisions before its latest base or retirement\n * are dropped (and its stored ones deleted).\n */\nexport class PendingWrites {\n\treadonly #recordIds = new Map<number, TableName>();\n\treadonly #conversations: Cell[][] = [];\n\treadonly #entries: Cell[][] = [];\n\treadonly #tasks = new Map<number, Cell[]>();\n\treadonly #submissions = new Map<number, Cell[]>();\n\t/** Each created or retired document's record. */\n\treadonly #documents = new Map<number, DocumentRecord>();\n\t/** The documents whose stored revisions go. */\n\treadonly #cleared = new Set<number>();\n\t/** Each document's new revisions, in seq order. */\n\treadonly #revisions = new Map<number, Cell[][]>();\n\n\t/** Adds a batch stored at `seq`, after `state` applied it. */\n\tadd(\n\t\twrites: readonly StorageWrite[],\n\t\tactions: ReadonlyMap<DocumentId, DocumentAction>,\n\t\tseq: Seq,\n\t\tstate: CommitState,\n\t): void {\n\t\tfor (const write of writes) this.#addWrite(write, seq);\n\t\tfor (const [id, action] of actions) this.#addDocument(id, action, seq, state.document(id)!);\n\t}\n\n\t#addWrite(write: StorageWrite, seq: Seq): void {\n\t\tconst claim = claimOf(write);\n\t\tif (claim !== undefined) this.#recordIds.set(claim.id, claim.table);\n\t\tswitch (write.type) {\n\t\t\tcase \"conversation\":\n\t\t\t\tthis.#conversations.push([\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.owner?.conversationId ?? null,\n\t\t\t\t\twrite.value.owner?.taskId ?? null,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"entry\":\n\t\t\t\tthis.#entries.push([\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.head ?? null,\n\t\t\t\t\tseq,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"task\":\n\t\t\t\tthis.#tasks.set(write.value.id, [\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\tencodeIndexedString(write.value.kind),\n\t\t\t\t\twrite.value.state.status,\n\t\t\t\t\twrite.value.abortRequested ? 1 : 0,\n\t\t\t\t\twrite.value.background ? 1 : 0,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"submission\":\n\t\t\t\tthis.#submissions.set(write.value.id, [\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.requestId === undefined ? null : encodeIndexedString(write.value.requestId),\n\t\t\t\t\twrite.value.status,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t#addDocument(id: DocumentId, action: DocumentAction, seq: Seq, record: DocumentRecord): void {\n\t\tif (action.create !== undefined || action.retire) this.#documents.set(id, record);\n\t\tconst content = action.content;\n\t\tif (content !== undefined) {\n\t\t\tif (content.kind === \"base\" && isCurrentOnly(record)) this.#clear(id);\n\t\t\tconst encoded = content.kind === \"base\" ? encodeJson(content.value) : encodeJson(content.ops);\n\t\t\tlet revisions = this.#revisions.get(id);\n\t\t\tif (revisions === undefined) {\n\t\t\t\trevisions = [];\n\t\t\t\tthis.#revisions.set(id, revisions);\n\t\t\t}\n\t\t\trevisions.push([id, seq, content.kind, content.version, encoded]);\n\t\t}\n\t\tif (action.retire && isCurrentOnly(record)) this.#clear(id);\n\t}\n\n\t/** Drops a document's revisions: the pending ones, and the stored ones when written. */\n\t#clear(id: number): void {\n\t\tthis.#cleared.add(id);\n\t\tthis.#revisions.delete(id);\n\t}\n\n\t/** Writes everything pending, a few statements per table (`insertRows`), and forgets it. */\n\tasync flush(executor: SqliteExecutor, tables: Tables): Promise<void> {\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.recordIds,\n\t\t\t[\"id\", \"record_type\"],\n\t\t\t[...this.#recordIds].map(([id, table]) => [id, table]),\n\t\t\t\"ON CONFLICT(id) DO NOTHING\",\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.conversations,\n\t\t\t[\"id\", \"owner_conversation_id\", \"owner_task_id\", \"record\"],\n\t\t\tthis.#conversations,\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.entries,\n\t\t\t[\"id\", \"conversation_id\", \"head\", \"commit_seq\", \"record\"],\n\t\t\tthis.#entries,\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.tasks,\n\t\t\t[\"id\", \"conversation_id\", \"kind\", \"status\", \"abort_requested\", \"background\", \"record\"],\n\t\t\t[...this.#tasks.values()],\n\t\t\t`ON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id, kind = excluded.kind,\n\t\t\t\tstatus = excluded.status, abort_requested = excluded.abort_requested,\n\t\t\t\tbackground = excluded.background, record = excluded.record`,\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.submissions,\n\t\t\t[\"id\", \"conversation_id\", \"request_id\", \"status\", \"record\"],\n\t\t\t[...this.#submissions.values()],\n\t\t\t`ON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id,\n\t\t\t\trequest_id = excluded.request_id, status = excluded.status, record = excluded.record`,\n\t\t);\n\t\t// A created document is inserted, a stored one retired: one upsert writes both.\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.documents,\n\t\t\t[\"id\", \"kind\", \"family\", \"key_value\", \"scope_kind\", \"owner_id\", \"created_at\", \"retired_at\", \"record\"],\n\t\t\t[...this.#documents.values()].map(documentRow),\n\t\t\t\"ON CONFLICT(id) DO UPDATE SET retired_at = excluded.retired_at, record = excluded.record\",\n\t\t);\n\t\tawait runForEach(\n\t\t\texecutor,\n\t\t\t`DELETE FROM ${tables.documentRevisions} WHERE document_id IN (SELECT value FROM json_each(?))`,\n\t\t\t[...this.#cleared],\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.documentRevisions,\n\t\t\t[\"document_id\", \"seq\", \"kind\", \"version\", \"content\"],\n\t\t\t[...this.#revisions.values()].flat(),\n\t\t);\n\t\tthis.#recordIds.clear();\n\t\tthis.#conversations.length = 0;\n\t\tthis.#entries.length = 0;\n\t\tthis.#tasks.clear();\n\t\tthis.#submissions.clear();\n\t\tthis.#documents.clear();\n\t\tthis.#cleared.clear();\n\t\tthis.#revisions.clear();\n\t}\n}\n"]}
1
+ {"version":3,"file":"commit.js","sourceRoot":"","sources":["../../../src/storage/sqlite/commit.ts"],"names":[],"mappings":"AAAA,mHAAmH;AACnH,uHAAuH;AACvH,sH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` call in a few statements whatever its number of batches: the check state of all its\n// batches read up front (`CommitState`), each batch checked in memory against what the batches before it left, and the\n// accepted batches written per table (`PendingWrites`, through `statements.ts`). Over a remote SQLite every statement\n// is a round trip while the write lock is held; a group of commits must not cost one round trip per write.\n\nimport type { SqliteExecutor } from \"@draht/chord/sqlite\";\nimport type {\n\tDocumentContent,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentRecord,\n\tId,\n\tSeq,\n\tStorageWrite,\n} from \"../../types.ts\";\nimport {\n\taddressColumnsKey,\n\taddressKey,\n\taddressParts,\n\ttype Cell,\n\tdocumentRow,\n\tencodeJson,\n\tisCurrentOnly,\n\tparseJson,\n} from \"./rows.ts\";\nimport type { SqliteSchema } from \"./schema.ts\";\nimport { insertRows, readRows, runForEach } from \"./statements.ts\";\n\n/** The table a record ID belongs to, as `record_ids` stores it. */\nexport type TableName = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\n\n/** What one batch does to one document: its creation or copy, its new content, its retirement. */\nexport type DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcopy?: Extract<StorageWrite, { readonly type: \"document.copy\" }>[\"source\"];\n\tcontent?: DocumentContent;\n\tretire: boolean;\n};\n\ntype Tables = SqliteSchema[\"tables\"];\n\n/** The record ID a write claims and its table, if it claims one. */\nexport const claimOf = (write: StorageWrite): { readonly id: Id<string>; readonly table: TableName } | undefined => {\n\tswitch (write.type) {\n\t\tcase \"conversation\":\n\t\tcase \"entry\":\n\t\tcase \"task\":\n\t\tcase \"submission\":\n\t\t\treturn { id: write.value.id, table: write.type };\n\t\tcase \"document.create\":\n\t\tcase \"document.copy\":\n\t\t\treturn { id: write.record.id, table: \"document\" };\n\t\tcase \"document.change\":\n\t\tcase \"document.retire\":\n\t\t\treturn undefined;\n\t}\n};\n\n/** One batch's writes per document; throws when a document gets two content commands or two retirements. */\nexport function prepareDocumentActions(writes: readonly StorageWrite[]): Map<DocumentId, DocumentAction> {\n\tconst actions = new Map<DocumentId, DocumentAction>();\n\tfor (const write of writes) {\n\t\tif (\n\t\t\twrite.type !== \"document.create\" &&\n\t\t\twrite.type !== \"document.copy\" &&\n\t\t\twrite.type !== \"document.change\" &&\n\t\t\twrite.type !== \"document.retire\"\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = write.type === \"document.create\" || write.type === \"document.copy\" ? write.record.id : write.id;\n\t\tlet action = actions.get(id);\n\t\tif (action === undefined) {\n\t\t\taction = { retire: false };\n\t\t\tactions.set(id, action);\n\t\t}\n\t\tswitch (write.type) {\n\t\t\tcase \"document.create\":\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.create = write.record;\n\t\t\t\taction.content = write.content;\n\t\t\t\tbreak;\n\t\t\tcase \"document.copy\":\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.create = write.record;\n\t\t\t\taction.copy = write.source;\n\t\t\t\tbreak;\n\t\t\tcase \"document.change\":\n\t\t\t\tif (action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.content = write.content;\n\t\t\t\tbreak;\n\t\t\tcase \"document.retire\":\n\t\t\t\tif (action.retire) throw new Error(`Document ${id} is retired more than once`);\n\t\t\t\taction.retire = true;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn actions;\n}\n\ntype RecordIdRow = { readonly id: number; readonly record_type: TableName };\ntype DocumentRow = { readonly record: string };\ntype VersionRow = { readonly document_id: number; readonly version: number | null };\ntype AddressRow = {\n\treadonly id: number;\n\treadonly kind: string;\n\treadonly scope_kind: string;\n\treadonly owner_id: number;\n\treadonly family: number;\n\treadonly key_value: string;\n};\n\n/**\n * What the checks of one call's batches read: the stored state of every ID, document and address the batches touch,\n * read in a few statements when the call starts, then advanced in memory by each accepted batch.\n */\nexport class CommitState {\n\t/** The table of each claimed ID; absent: unclaimed. */\n\treadonly #recordIds: Map<number, TableName>;\n\t/** Each touched document's record; absent: no such document. */\n\treadonly #documents: Map<number, DocumentRecord>;\n\t/** The version of each delta-changed document's latest revision; absent: no revision. */\n\treadonly #versions: Map<number, number>;\n\t/** The current incarnation of each created address (`addressKey`); `undefined`: none. */\n\treadonly #current: Map<string, DocumentId | undefined>;\n\n\tprivate constructor(\n\t\trecordIds: Map<number, TableName>,\n\t\tdocuments: Map<number, DocumentRecord>,\n\t\tversions: Map<number, number>,\n\t\tcurrent: Map<string, DocumentId | undefined>,\n\t) {\n\t\tthis.#recordIds = recordIds;\n\t\tthis.#documents = documents;\n\t\tthis.#versions = versions;\n\t\tthis.#current = current;\n\t}\n\n\t/** Reads the stored state the checks of `batches` need: one statement per kind of state (split only by size). */\n\tstatic async read(\n\t\texecutor: SqliteExecutor,\n\t\ttables: Tables,\n\t\tbatches: readonly (readonly StorageWrite[])[],\n\t): Promise<CommitState> {\n\t\tconst ids = new Set<number>();\n\t\tconst documentIds = new Set<number>();\n\t\tconst deltaIds = new Set<number>();\n\t\tconst addresses = new Map<string, ReturnType<typeof addressParts>>();\n\t\tfor (const writes of batches) {\n\t\t\tfor (const write of writes) {\n\t\t\t\tconst claim = claimOf(write);\n\t\t\t\tif (claim !== undefined) ids.add(claim.id);\n\t\t\t\tswitch (write.type) {\n\t\t\t\t\tcase \"document.create\":\n\t\t\t\t\tcase \"document.copy\":\n\t\t\t\t\t\tdocumentIds.add(write.record.id);\n\t\t\t\t\t\taddresses.set(addressKey(write.record), addressParts(write.record));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"document.change\":\n\t\t\t\t\t\tdocumentIds.add(write.id);\n\t\t\t\t\t\tif (write.content.kind === \"delta\") deltaIds.add(write.id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"document.retire\":\n\t\t\t\t\t\tdocumentIds.add(write.id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst recordIds = new Map<number, TableName>();\n\t\tfor (const row of await readRows<RecordIdRow>(\n\t\t\texecutor,\n\t\t\t`SELECT id, record_type FROM ${tables.recordIds} WHERE id IN (SELECT value FROM json_each(?))`,\n\t\t\t[...ids],\n\t\t)) {\n\t\t\trecordIds.set(row.id, row.record_type);\n\t\t}\n\t\tconst documents = new Map<number, DocumentRecord>();\n\t\tfor (const row of await readRows<DocumentRow>(\n\t\t\texecutor,\n\t\t\t`SELECT record FROM ${tables.documents} WHERE id IN (SELECT value FROM json_each(?))`,\n\t\t\t[...documentIds],\n\t\t)) {\n\t\t\tconst record = parseJson<DocumentRecord>(row.record);\n\t\t\tdocuments.set(record.id, record);\n\t\t}\n\t\tconst versions = new Map<number, number>();\n\t\t// Driven by the requested IDs: each latest revision is one descending probe of the primary key.\n\t\tfor (const row of await readRows<VersionRow>(\n\t\t\texecutor,\n\t\t\t`SELECT requested.value AS document_id, (\n\t\t\t\tSELECT version FROM ${tables.documentRevisions} WHERE document_id = requested.value ORDER BY seq DESC LIMIT 1\n\t\t\t) AS version FROM json_each(?) AS requested`,\n\t\t\t[...deltaIds],\n\t\t)) {\n\t\t\tif (row.version !== null) versions.set(row.document_id, row.version);\n\t\t}\n\t\treturn new CommitState(recordIds, documents, versions, await readCurrent(executor, tables, addresses));\n\t}\n\n\t/** Durable's own checks of one batch that need no copy source: throws the refusal. */\n\tcheck(writes: readonly StorageWrite[], actions: ReadonlyMap<DocumentId, DocumentAction>): void {\n\t\tthis.#checkIds(writes);\n\t\tthis.#checkDocuments(actions);\n\t}\n\n\t/** Advances the state past an accepted batch stored at `seq`, its copies resolved to their content. */\n\tapply(writes: readonly StorageWrite[], actions: ReadonlyMap<DocumentId, DocumentAction>, seq: Seq): void {\n\t\tfor (const write of writes) {\n\t\t\t// An accepted batch claims an ID only for its stored table, if it has one (`#checkIds`).\n\t\t\tconst claim = claimOf(write);\n\t\t\tif (claim !== undefined) this.#recordIds.set(claim.id, claim.table);\n\t\t}\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.create !== undefined) {\n\t\t\t\tconst record = { ...action.create, createdAt: seq, ...(action.retire ? { retiredAt: seq } : {}) };\n\t\t\t\tthis.#documents.set(id, record);\n\t\t\t\tif (!action.retire) this.#current.set(addressKey(record), id);\n\t\t\t} else if (action.retire) {\n\t\t\t\tconst record = { ...this.#documents.get(id)!, retiredAt: seq };\n\t\t\t\tthis.#documents.set(id, record);\n\t\t\t\t// The batch may have created the address's next incarnation already: only this one leaves.\n\t\t\t\tconst key = addressKey(record);\n\t\t\t\tif (this.#current.get(key) === id) this.#current.set(key, undefined);\n\t\t\t}\n\t\t\t// A retired document's versions are never read again: every later action on it is refused first.\n\t\t\tif (action.content !== undefined) this.#versions.set(id, action.content.version);\n\t\t}\n\t}\n\n\t/** A document's record as the accepted batches left it. */\n\tdocument(id: DocumentId): DocumentRecord | undefined {\n\t\treturn this.#documents.get(id);\n\t}\n\n\t#checkIds(writes: readonly StorageWrite[]): void {\n\t\tconst claimed = new Map<Id<string>, TableName>();\n\t\tfor (const write of writes) {\n\t\t\tconst claim = claimOf(write);\n\t\t\tif (claim === undefined) continue;\n\t\t\tconst { id, table } = claim;\n\t\t\tconst existing = this.#recordIds.get(id);\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (table === \"conversation\" || table === \"entry\" || table === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== table)\n\t\t\t\t\tthrow new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined && earlier !== table) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, table);\n\t\t}\n\t}\n\n\t#checkDocuments(actions: ReadonlyMap<DocumentId, DocumentAction>): void {\n\t\tconst liveCounts = new Map<string, number>();\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.copy !== undefined && actions.has(action.copy.id)) {\n\t\t\t\tthrow new Error(`Document copy ${id} source is changed in the copy batch`);\n\t\t\t}\n\t\t\tconst existing = this.#documents.get(id);\n\t\t\tif (action.create === undefined && existing === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (action.create !== undefined && existing !== undefined) throw new Error(`Document ${id} already exists`);\n\t\t\tif (existing?.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tif (action.content?.kind === \"delta\") {\n\t\t\t\tconst previous = this.#versions.get(id);\n\t\t\t\tif (previous === undefined) throw new Error(`Document ${id} delta has no base`);\n\t\t\t\tif (previous !== action.content.version)\n\t\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t}\n\t\t\t// A plain change keeps its address's live count: only creations and retirements are counted.\n\t\t\tif (action.create === undefined && !action.retire) continue;\n\t\t\tconst key = addressKey(action.create ?? existing!);\n\t\t\tlet live = liveCounts.get(key);\n\t\t\t// Only created addresses were read: an address no batch creates only loses incarnations, never exceeds one.\n\t\t\tif (live === undefined) live = this.#current.get(key) === undefined ? 0 : 1;\n\t\t\tif (action.retire && existing !== undefined) live--;\n\t\t\tif (action.create !== undefined && !action.retire) live++;\n\t\t\tliveCounts.set(key, live);\n\t\t}\n\t\tfor (const live of liveCounts.values()) {\n\t\t\tif (live > 1) throw new Error(\"Document address already has a current incarnation\");\n\t\t}\n\t}\n}\n\n/** The current incarnation of each of `addresses`, `undefined` for one without. */\nasync function readCurrent(\n\texecutor: SqliteExecutor,\n\ttables: Tables,\n\taddresses: ReadonlyMap<string, ReturnType<typeof addressParts>>,\n): Promise<Map<string, DocumentId | undefined>> {\n\tconst current = new Map<string, DocumentId | undefined>();\n\tfor (const key of addresses.keys()) current.set(key, undefined);\n\tconst rows = await readRows<AddressRow>(\n\t\texecutor,\n\t\t`SELECT document.id, document.kind, document.scope_kind, document.owner_id, document.family, document.key_value\n\t\t\tFROM json_each(?) AS address JOIN ${tables.documents} AS document\n\t\t\tON document.kind = json_extract(address.value, '$[0]') AND document.scope_kind = json_extract(address.value, '$[1]')\n\t\t\tAND document.owner_id = json_extract(address.value, '$[2]') AND document.family = json_extract(address.value, '$[3]')\n\t\t\tAND document.key_value = json_extract(address.value, '$[4]')\n\t\t\tWHERE document.retired_at IS NULL`,\n\t\t[...addresses.values()].map((part) => [part.kind, part.scopeKind, part.ownerId, part.family, part.keyValue]),\n\t);\n\tfor (const row of rows) {\n\t\tcurrent.set(\n\t\t\taddressColumnsKey(row.kind, row.scope_kind, row.owner_id, row.family, row.key_value),\n\t\t\trow.id as DocumentId,\n\t\t);\n\t}\n\treturn current;\n}\n\n/**\n * The writes of the accepted batches not yet written, per table, as their net effect: a task or submission written\n * twice is written once, as last written; a current-only document's revisions before its latest base or retirement\n * are dropped (and its stored ones deleted).\n */\nexport class PendingWrites {\n\treadonly #recordIds = new Map<number, TableName>();\n\treadonly #conversations: Cell[][] = [];\n\treadonly #entries: Cell[][] = [];\n\treadonly #tasks = new Map<number, Cell[]>();\n\treadonly #submissions = new Map<number, Cell[]>();\n\t/** Each created or retired document's record. */\n\treadonly #documents = new Map<number, DocumentRecord>();\n\t/** The documents whose stored revisions go. */\n\treadonly #cleared = new Set<number>();\n\t/** Each document's new revisions, in seq order. */\n\treadonly #revisions = new Map<number, Cell[][]>();\n\n\t/** Adds a batch stored at `seq`, after `state` applied it. */\n\tadd(\n\t\twrites: readonly StorageWrite[],\n\t\tactions: ReadonlyMap<DocumentId, DocumentAction>,\n\t\tseq: Seq,\n\t\tstate: CommitState,\n\t): void {\n\t\tfor (const write of writes) this.#addWrite(write, seq);\n\t\tfor (const [id, action] of actions) this.#addDocument(id, action, seq, state.document(id)!);\n\t}\n\n\t#addWrite(write: StorageWrite, seq: Seq): void {\n\t\tconst claim = claimOf(write);\n\t\tif (claim !== undefined) this.#recordIds.set(claim.id, claim.table);\n\t\tswitch (write.type) {\n\t\t\tcase \"conversation\":\n\t\t\t\tthis.#conversations.push([\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.owner?.conversationId ?? null,\n\t\t\t\t\twrite.value.owner?.taskId ?? null,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"entry\":\n\t\t\t\tthis.#entries.push([\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.head ?? null,\n\t\t\t\t\tseq,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"task\":\n\t\t\t\tthis.#tasks.set(write.value.id, [\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.kind,\n\t\t\t\t\twrite.value.state.status,\n\t\t\t\t\twrite.value.abortRequested ? 1 : 0,\n\t\t\t\t\twrite.value.background ? 1 : 0,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"submission\":\n\t\t\t\tthis.#submissions.set(write.value.id, [\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.requestId ?? null,\n\t\t\t\t\twrite.value.status,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t#addDocument(id: DocumentId, action: DocumentAction, seq: Seq, record: DocumentRecord): void {\n\t\tif (action.create !== undefined || action.retire) this.#documents.set(id, record);\n\t\tconst content = action.content;\n\t\tif (content !== undefined) {\n\t\t\tif (content.kind === \"base\" && isCurrentOnly(record)) this.#clear(id);\n\t\t\tconst encoded = content.kind === \"base\" ? encodeJson(content.value) : encodeJson(content.ops);\n\t\t\tlet revisions = this.#revisions.get(id);\n\t\t\tif (revisions === undefined) {\n\t\t\t\trevisions = [];\n\t\t\t\tthis.#revisions.set(id, revisions);\n\t\t\t}\n\t\t\trevisions.push([id, seq, content.kind, content.version, encoded]);\n\t\t}\n\t\tif (action.retire && isCurrentOnly(record)) this.#clear(id);\n\t}\n\n\t/** Drops a document's revisions: the pending ones, and the stored ones when written. */\n\t#clear(id: number): void {\n\t\tthis.#cleared.add(id);\n\t\tthis.#revisions.delete(id);\n\t}\n\n\t/** Writes everything pending, a few statements per table (`insertRows`), and forgets it. */\n\tasync flush(executor: SqliteExecutor, tables: Tables): Promise<void> {\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.recordIds,\n\t\t\t[\"id\", \"record_type\"],\n\t\t\t[...this.#recordIds].map(([id, table]) => [id, table]),\n\t\t\t\"ON CONFLICT(id) DO NOTHING\",\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.conversations,\n\t\t\t[\"id\", \"owner_conversation_id\", \"owner_task_id\", \"record\"],\n\t\t\tthis.#conversations,\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.entries,\n\t\t\t[\"id\", \"conversation_id\", \"head\", \"commit_seq\", \"record\"],\n\t\t\tthis.#entries,\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.tasks,\n\t\t\t[\"id\", \"conversation_id\", \"kind\", \"status\", \"abort_requested\", \"background\", \"record\"],\n\t\t\t[...this.#tasks.values()],\n\t\t\t`ON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id, kind = excluded.kind,\n\t\t\t\tstatus = excluded.status, abort_requested = excluded.abort_requested,\n\t\t\t\tbackground = excluded.background, record = excluded.record`,\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.submissions,\n\t\t\t[\"id\", \"conversation_id\", \"request_id\", \"status\", \"record\"],\n\t\t\t[...this.#submissions.values()],\n\t\t\t`ON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id,\n\t\t\t\trequest_id = excluded.request_id, status = excluded.status, record = excluded.record`,\n\t\t);\n\t\t// A created document is inserted, a stored one retired: one upsert writes both.\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.documents,\n\t\t\t[\"id\", \"kind\", \"family\", \"key_value\", \"scope_kind\", \"owner_id\", \"created_at\", \"retired_at\", \"record\"],\n\t\t\t[...this.#documents.values()].map(documentRow),\n\t\t\t\"ON CONFLICT(id) DO UPDATE SET retired_at = excluded.retired_at, record = excluded.record\",\n\t\t);\n\t\tawait runForEach(\n\t\t\texecutor,\n\t\t\t`DELETE FROM ${tables.documentRevisions} WHERE document_id IN (SELECT value FROM json_each(?))`,\n\t\t\t[...this.#cleared],\n\t\t);\n\t\tawait insertRows(\n\t\t\texecutor,\n\t\t\ttables.documentRevisions,\n\t\t\t[\"document_id\", \"seq\", \"kind\", \"version\", \"content\"],\n\t\t\t[...this.#revisions.values()].flat(),\n\t\t);\n\t\tthis.#recordIds.clear();\n\t\tthis.#conversations.length = 0;\n\t\tthis.#entries.length = 0;\n\t\tthis.#tasks.clear();\n\t\tthis.#submissions.clear();\n\t\tthis.#documents.clear();\n\t\tthis.#cleared.clear();\n\t\tthis.#revisions.clear();\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../../../src/storage/sqlite/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAyB,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAEvE,YAAY,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,+EAA+E;AAC/E,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,eAAe,EAAE,CA0GvF;AAED,eAAO,MAAM,iBAAiB,EAAE,SAAS,eAAe,EAAkD,CAAC;AAE3G,eAAO,MAAM,6BAA6B,QAAyC,CAAC;AAEpF,sDAAsD;AACtD,wBAAsB,qBAAqB,CAC1C,QAAQ,EAAE,cAAc,EACxB,UAAU,GAAE,SAAS,eAAe,EAAsB,GACxD,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,yDAAyD;AACzD,wBAAsB,8BAA8B,CACnD,QAAQ,EAAE,cAAc,EACxB,MAAM,EAAE,YAAY,EACpB,UAAU,GAAE,SAAS,eAAe,EAAmC,GACrE,OAAO,CAAC,IAAI,CAAC,CAEf"}
1
+ {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../../../src/storage/sqlite/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAyB,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAEvE,YAAY,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,+EAA+E;AAC/E,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,eAAe,EAAE,CA8HvF;AAED,eAAO,MAAM,iBAAiB,EAAE,SAAS,eAAe,EAAkD,CAAC;AAE3G,eAAO,MAAM,6BAA6B,QAAyC,CAAC;AAEpF,sDAAsD;AACtD,wBAAsB,qBAAqB,CAC1C,QAAQ,EAAE,cAAc,EACxB,UAAU,GAAE,SAAS,eAAe,EAAsB,GACxD,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,yDAAyD;AACzD,wBAAsB,8BAA8B,CACnD,QAAQ,EAAE,cAAc,EACxB,MAAM,EAAE,YAAY,EACpB,UAAU,GAAE,SAAS,eAAe,EAAmC,GACrE,OAAO,CAAC,IAAI,CAAC,CAEf"}
@@ -103,9 +103,29 @@ export function createSqliteMigrations(schema) {
103
103
  `CREATE INDEX ${indexes.tasksByAbortRequested} ON ${tables.tasks} (abort_requested, id)`,
104
104
  `CREATE INDEX ${indexes.tasksByBackground} ON ${tables.tasks} (background, id)`,
105
105
  ];
106
+ // Version 3 stores indexed strings as plain text instead of JSON string literals. An escaped lone surrogate or NUL
107
+ // (which `json_extract` would corrupt) refuses it first; the CHECK's name is the error. Without `\\`, `\u` is an escape.
108
+ const escapes = (column) => {
109
+ const unescaped = `replace(${column}, '\\\\', '')`;
110
+ return `(${unescaped} GLOB '*\\ud[89a-f]*' OR ${unescaped} GLOB '*\\u0000*')`;
111
+ };
112
+ const check = `${tables.durableSchema}_v3_check`;
113
+ const plainIndexedStrings = [
114
+ `CREATE TABLE ${check} (refused INTEGER
115
+ CONSTRAINT "an indexed string holds a lone surrogate or NUL, which plain text cannot keep" CHECK (refused = 0))`,
116
+ `INSERT INTO ${check} SELECT
117
+ (SELECT count(*) FROM ${tables.tasks} WHERE ${escapes("kind")})
118
+ + (SELECT count(*) FROM ${tables.submissions} WHERE request_id IS NOT NULL AND ${escapes("request_id")})
119
+ + (SELECT count(*) FROM ${tables.documents} WHERE ${escapes("kind")} OR ${escapes("key_value")})`,
120
+ `DROP TABLE ${check}`,
121
+ `UPDATE ${tables.tasks} SET kind = json_extract(kind, '$')`,
122
+ `UPDATE ${tables.submissions} SET request_id = json_extract(request_id, '$') WHERE request_id IS NOT NULL`,
123
+ `UPDATE ${tables.documents} SET kind = json_extract(kind, '$'), key_value = json_extract(key_value, '$')`,
124
+ ];
106
125
  return [
107
126
  { version: 1, statements: initialSchema },
108
127
  { version: 2, statements: sleepingStatus },
128
+ { version: 3, statements: plainIndexedStrings },
109
129
  ];
110
130
  }
111
131
  export const SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA);
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/storage/sqlite/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,qBAAqB,IAAI,eAAe,GAGxC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,qBAAqB,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AA+B,sBAAsB,CAAC,qBAAqB,CAAC,CAAC;AAE3G,MAAM,CAAC,MAAM,6BAA6B,GAAG,iBAAiB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,CAAC;AAEpF,sDAAsD;AACtD,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAC1C,QAAwB,EACxB,UAAU,GAA+B,iBAAiB;IAE1D,MAAM,8BAA8B,CAAC,QAAQ,EAAE,qBAAqB,EAAE,UAAU,CAAC,CAAC;AACnF,CAAC;AAED,yDAAyD;AACzD,MAAM,CAAC,KAAK,UAAU,8BAA8B,CACnD,QAAwB,EACxB,MAAoB,EACpB,UAAU,GAA+B,sBAAsB,CAAC,MAAM,CAAC;IAEvE,MAAM,eAAe,CAAC,QAAQ,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,CAAC,CAAC;AACrF,CAAC","sourcesContent":["import {\n\tapplySqliteMigrations as applyMigrations,\n\ttype SqliteDatabase,\n\ttype SqliteMigration,\n} from \"@draht/chord/sqlite\";\nimport { DEFAULT_SQLITE_SCHEMA, type SqliteSchema } from \"./schema.ts\";\n\nexport type { SqliteMigration } from \"@draht/chord/sqlite\";\n\n/** Build immutable, ordered schema history for a set of SQLite identifiers. */\nexport function createSqliteMigrations(schema: SqliteSchema): readonly SqliteMigration[] {\n\tconst { tables, indexes } = schema;\n\t// next_id is TEXT because node:sqlite rejects INTEGER results outside JavaScript's safe integer range.\n\tconst initialSchema: readonly string[] = [\n\t\t`CREATE TABLE ${tables.durableMetadata} (\n\t\t\tsingleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n\t\t\tnext_id TEXT NOT NULL,\n\t\t\tnext_seq INTEGER NOT NULL\n\t\t) STRICT`,\n\t\t`INSERT INTO ${tables.durableMetadata} (singleton, next_id, next_seq) VALUES (1, '2', 1)`,\n\t\t`CREATE TABLE ${tables.recordIds} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\trecord_type TEXT NOT NULL CHECK (record_type IN ('conversation', 'entry', 'task', 'submission', 'document'))\n\t\t) STRICT`,\n\t\t`CREATE TABLE ${tables.conversations} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\towner_conversation_id INTEGER,\n\t\t\towner_task_id INTEGER,\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.conversationsByOwnerConversation} ON ${tables.conversations} (owner_conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.conversationsByOwnerTask} ON ${tables.conversations} (owner_task_id, id)`,\n\t\t`CREATE TABLE ${tables.entries} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\thead INTEGER,\n\t\t\tcommit_seq INTEGER NOT NULL,\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.entriesByConversation} ON ${tables.entries} (conversation_id, id DESC)`,\n\t\t`CREATE INDEX ${indexes.entryHeadsByConversation} ON ${tables.entries} (conversation_id, id DESC) WHERE head IS NOT NULL`,\n\t\t`CREATE TABLE ${tables.tasks} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\tkind TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL CHECK (status IN ('pending', 'running', 'waiting', 'completing', 'terminal')),\n\t\t\tabort_requested INTEGER NOT NULL CHECK (abort_requested IN (0, 1)),\n\t\t\tbackground INTEGER NOT NULL CHECK (background IN (0, 1)),\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.tasksByStatus} ON ${tables.tasks} (status, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByConversation} ON ${tables.tasks} (conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByKind} ON ${tables.tasks} (kind, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByAbortRequested} ON ${tables.tasks} (abort_requested, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByBackground} ON ${tables.tasks} (background, id)`,\n\t\t`CREATE TABLE ${tables.submissions} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\trequest_id TEXT,\n\t\t\tstatus TEXT NOT NULL CHECK (status IN ('queued', 'placed', 'done', 'unanswered')),\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.submissionsByRequest} ON ${tables.submissions} (conversation_id, request_id)`,\n\t\t`CREATE INDEX ${indexes.submissionsByConversation} ON ${tables.submissions} (conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.submissionsByStatus} ON ${tables.submissions} (status, id)`,\n\t\t`CREATE TABLE ${tables.documents} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tkind TEXT NOT NULL,\n\t\t\tfamily INTEGER NOT NULL CHECK (family IN (0, 1)),\n\t\t\tkey_value TEXT NOT NULL,\n\t\t\tscope_kind TEXT NOT NULL CHECK (scope_kind IN ('session', 'conversation', 'task')),\n\t\t\towner_id INTEGER NOT NULL,\n\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\tretired_at INTEGER,\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.documentsByAddress}\n\t\t\tON ${tables.documents} (kind, scope_kind, owner_id, family, key_value, created_at DESC, retired_at)`,\n\t\t`CREATE INDEX ${indexes.documentsByScope} ON ${tables.documents} (scope_kind, owner_id, id)`,\n\t\t`CREATE INDEX ${indexes.documentsByScopeKind} ON ${tables.documents} (scope_kind, owner_id, kind, id)`,\n\t\t`CREATE TABLE ${tables.documentRevisions} (\n\t\t\tdocument_id INTEGER NOT NULL,\n\t\t\tseq INTEGER NOT NULL,\n\t\t\tkind TEXT NOT NULL CHECK (kind IN ('base', 'delta')),\n\t\t\tversion INTEGER NOT NULL,\n\t\t\tcontent TEXT NOT NULL CHECK (json_valid(content)),\n\t\t\tPRIMARY KEY (document_id, seq)\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.documentRevisionsByKind} ON ${tables.documentRevisions} (document_id, kind, seq DESC)`,\n\t];\n\t// Version 2 adds the `sleeping` task status. SQLite cannot change a CHECK constraint in place, so the table is rebuilt.\n\tconst rebuiltTasks = `${tables.tasks}_v2`;\n\tconst sleepingStatus: readonly string[] = [\n\t\t`CREATE TABLE ${rebuiltTasks} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\tkind TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL CHECK (status IN ('pending', 'running', 'waiting', 'sleeping', 'completing', 'terminal')),\n\t\t\tabort_requested INTEGER NOT NULL CHECK (abort_requested IN (0, 1)),\n\t\t\tbackground INTEGER NOT NULL CHECK (background IN (0, 1)),\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`INSERT INTO ${rebuiltTasks} (id, conversation_id, kind, status, abort_requested, background, record)\n\t\t\tSELECT id, conversation_id, kind, status, abort_requested, background, record FROM ${tables.tasks}`,\n\t\t`DROP TABLE ${tables.tasks}`,\n\t\t`ALTER TABLE ${rebuiltTasks} RENAME TO ${tables.tasks}`,\n\t\t`CREATE INDEX ${indexes.tasksByStatus} ON ${tables.tasks} (status, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByConversation} ON ${tables.tasks} (conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByKind} ON ${tables.tasks} (kind, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByAbortRequested} ON ${tables.tasks} (abort_requested, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByBackground} ON ${tables.tasks} (background, id)`,\n\t];\n\treturn [\n\t\t{ version: 1, statements: initialSchema },\n\t\t{ version: 2, statements: sleepingStatus },\n\t];\n}\n\nexport const SQLITE_MIGRATIONS: readonly SqliteMigration[] = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA);\n\nexport const CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0;\n\n/** Apply all pending schema migrations atomically. */\nexport async function applySqliteMigrations(\n\tdatabase: SqliteDatabase,\n\tmigrations: readonly SqliteMigration[] = SQLITE_MIGRATIONS,\n): Promise<void> {\n\tawait applySqliteMigrationsForSchema(database, DEFAULT_SQLITE_SCHEMA, migrations);\n}\n\n/** Apply migrations rendered for a particular schema. */\nexport async function applySqliteMigrationsForSchema(\n\tdatabase: SqliteDatabase,\n\tschema: SqliteSchema,\n\tmigrations: readonly SqliteMigration[] = createSqliteMigrations(schema),\n): Promise<void> {\n\tawait applyMigrations(database, migrations, { table: schema.tables.durableSchema });\n}\n"]}
1
+ {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/storage/sqlite/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,qBAAqB,IAAI,eAAe,GAGxC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,qBAAqB,EAAqB,MAAM,aAAa,CAAC;AAIvE,+EAA+E;AAC/E,MAAM,UAAU,sBAAsB,CAAC,MAAoB;IAC1D,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IACnC,uGAAuG;IACvG,MAAM,aAAa,GAAsB;QACxC,gBAAgB,MAAM,CAAC,eAAe;;;;WAI7B;QACT,eAAe,MAAM,CAAC,eAAe,oDAAoD;QACzF,gBAAgB,MAAM,CAAC,SAAS;;;WAGvB;QACT,gBAAgB,MAAM,CAAC,aAAa;;;;;WAK3B;QACT,gBAAgB,OAAO,CAAC,gCAAgC,OAAO,MAAM,CAAC,aAAa,8BAA8B;QACjH,gBAAgB,OAAO,CAAC,wBAAwB,OAAO,MAAM,CAAC,aAAa,sBAAsB;QACjG,gBAAgB,MAAM,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;IACF,OAAO;QACN,EAAE,OAAO,EAAE,CAAC,EAAE,UAAU,EAAE,aAAa,EAAE;QACzC,EAAE,OAAO,EAAE,CAAC,EAAE,UAAU,EAAE,cAAc,EAAE;QAC1C,EAAE,OAAO,EAAE,CAAC,EAAE,UAAU,EAAE,mBAAmB,EAAE;KAC/C,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAA+B,sBAAsB,CAAC,qBAAqB,CAAC,CAAC;AAE3G,MAAM,CAAC,MAAM,6BAA6B,GAAG,iBAAiB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC,CAAC;AAEpF,sDAAsD;AACtD,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAC1C,QAAwB,EACxB,UAAU,GAA+B,iBAAiB;IAE1D,MAAM,8BAA8B,CAAC,QAAQ,EAAE,qBAAqB,EAAE,UAAU,CAAC,CAAC;AACnF,CAAC;AAED,yDAAyD;AACzD,MAAM,CAAC,KAAK,UAAU,8BAA8B,CACnD,QAAwB,EACxB,MAAoB,EACpB,UAAU,GAA+B,sBAAsB,CAAC,MAAM,CAAC;IAEvE,MAAM,eAAe,CAAC,QAAQ,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,CAAC,CAAC;AACrF,CAAC","sourcesContent":["import {\n\tapplySqliteMigrations as applyMigrations,\n\ttype SqliteDatabase,\n\ttype SqliteMigration,\n} from \"@draht/chord/sqlite\";\nimport { DEFAULT_SQLITE_SCHEMA, type SqliteSchema } from \"./schema.ts\";\n\nexport type { SqliteMigration } from \"@draht/chord/sqlite\";\n\n/** Build immutable, ordered schema history for a set of SQLite identifiers. */\nexport function createSqliteMigrations(schema: SqliteSchema): readonly SqliteMigration[] {\n\tconst { tables, indexes } = schema;\n\t// next_id is TEXT because node:sqlite rejects INTEGER results outside JavaScript's safe integer range.\n\tconst initialSchema: readonly string[] = [\n\t\t`CREATE TABLE ${tables.durableMetadata} (\n\t\t\tsingleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n\t\t\tnext_id TEXT NOT NULL,\n\t\t\tnext_seq INTEGER NOT NULL\n\t\t) STRICT`,\n\t\t`INSERT INTO ${tables.durableMetadata} (singleton, next_id, next_seq) VALUES (1, '2', 1)`,\n\t\t`CREATE TABLE ${tables.recordIds} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\trecord_type TEXT NOT NULL CHECK (record_type IN ('conversation', 'entry', 'task', 'submission', 'document'))\n\t\t) STRICT`,\n\t\t`CREATE TABLE ${tables.conversations} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\towner_conversation_id INTEGER,\n\t\t\towner_task_id INTEGER,\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.conversationsByOwnerConversation} ON ${tables.conversations} (owner_conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.conversationsByOwnerTask} ON ${tables.conversations} (owner_task_id, id)`,\n\t\t`CREATE TABLE ${tables.entries} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\thead INTEGER,\n\t\t\tcommit_seq INTEGER NOT NULL,\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.entriesByConversation} ON ${tables.entries} (conversation_id, id DESC)`,\n\t\t`CREATE INDEX ${indexes.entryHeadsByConversation} ON ${tables.entries} (conversation_id, id DESC) WHERE head IS NOT NULL`,\n\t\t`CREATE TABLE ${tables.tasks} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\tkind TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL CHECK (status IN ('pending', 'running', 'waiting', 'completing', 'terminal')),\n\t\t\tabort_requested INTEGER NOT NULL CHECK (abort_requested IN (0, 1)),\n\t\t\tbackground INTEGER NOT NULL CHECK (background IN (0, 1)),\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.tasksByStatus} ON ${tables.tasks} (status, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByConversation} ON ${tables.tasks} (conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByKind} ON ${tables.tasks} (kind, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByAbortRequested} ON ${tables.tasks} (abort_requested, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByBackground} ON ${tables.tasks} (background, id)`,\n\t\t`CREATE TABLE ${tables.submissions} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\trequest_id TEXT,\n\t\t\tstatus TEXT NOT NULL CHECK (status IN ('queued', 'placed', 'done', 'unanswered')),\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.submissionsByRequest} ON ${tables.submissions} (conversation_id, request_id)`,\n\t\t`CREATE INDEX ${indexes.submissionsByConversation} ON ${tables.submissions} (conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.submissionsByStatus} ON ${tables.submissions} (status, id)`,\n\t\t`CREATE TABLE ${tables.documents} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tkind TEXT NOT NULL,\n\t\t\tfamily INTEGER NOT NULL CHECK (family IN (0, 1)),\n\t\t\tkey_value TEXT NOT NULL,\n\t\t\tscope_kind TEXT NOT NULL CHECK (scope_kind IN ('session', 'conversation', 'task')),\n\t\t\towner_id INTEGER NOT NULL,\n\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\tretired_at INTEGER,\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.documentsByAddress}\n\t\t\tON ${tables.documents} (kind, scope_kind, owner_id, family, key_value, created_at DESC, retired_at)`,\n\t\t`CREATE INDEX ${indexes.documentsByScope} ON ${tables.documents} (scope_kind, owner_id, id)`,\n\t\t`CREATE INDEX ${indexes.documentsByScopeKind} ON ${tables.documents} (scope_kind, owner_id, kind, id)`,\n\t\t`CREATE TABLE ${tables.documentRevisions} (\n\t\t\tdocument_id INTEGER NOT NULL,\n\t\t\tseq INTEGER NOT NULL,\n\t\t\tkind TEXT NOT NULL CHECK (kind IN ('base', 'delta')),\n\t\t\tversion INTEGER NOT NULL,\n\t\t\tcontent TEXT NOT NULL CHECK (json_valid(content)),\n\t\t\tPRIMARY KEY (document_id, seq)\n\t\t) STRICT`,\n\t\t`CREATE INDEX ${indexes.documentRevisionsByKind} ON ${tables.documentRevisions} (document_id, kind, seq DESC)`,\n\t];\n\t// Version 2 adds the `sleeping` task status. SQLite cannot change a CHECK constraint in place, so the table is rebuilt.\n\tconst rebuiltTasks = `${tables.tasks}_v2`;\n\tconst sleepingStatus: readonly string[] = [\n\t\t`CREATE TABLE ${rebuiltTasks} (\n\t\t\tid INTEGER PRIMARY KEY,\n\t\t\tconversation_id INTEGER NOT NULL,\n\t\t\tkind TEXT NOT NULL,\n\t\t\tstatus TEXT NOT NULL CHECK (status IN ('pending', 'running', 'waiting', 'sleeping', 'completing', 'terminal')),\n\t\t\tabort_requested INTEGER NOT NULL CHECK (abort_requested IN (0, 1)),\n\t\t\tbackground INTEGER NOT NULL CHECK (background IN (0, 1)),\n\t\t\trecord TEXT NOT NULL CHECK (json_valid(record))\n\t\t) STRICT`,\n\t\t`INSERT INTO ${rebuiltTasks} (id, conversation_id, kind, status, abort_requested, background, record)\n\t\t\tSELECT id, conversation_id, kind, status, abort_requested, background, record FROM ${tables.tasks}`,\n\t\t`DROP TABLE ${tables.tasks}`,\n\t\t`ALTER TABLE ${rebuiltTasks} RENAME TO ${tables.tasks}`,\n\t\t`CREATE INDEX ${indexes.tasksByStatus} ON ${tables.tasks} (status, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByConversation} ON ${tables.tasks} (conversation_id, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByKind} ON ${tables.tasks} (kind, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByAbortRequested} ON ${tables.tasks} (abort_requested, id)`,\n\t\t`CREATE INDEX ${indexes.tasksByBackground} ON ${tables.tasks} (background, id)`,\n\t];\n\t// Version 3 stores indexed strings as plain text instead of JSON string literals. An escaped lone surrogate or NUL\n\t// (which `json_extract` would corrupt) refuses it first; the CHECK's name is the error. Without `\\\\`, `\\u` is an escape.\n\tconst escapes = (column: string): string => {\n\t\tconst unescaped = `replace(${column}, '\\\\\\\\', '')`;\n\t\treturn `(${unescaped} GLOB '*\\\\ud[89a-f]*' OR ${unescaped} GLOB '*\\\\u0000*')`;\n\t};\n\tconst check = `${tables.durableSchema}_v3_check`;\n\tconst plainIndexedStrings: readonly string[] = [\n\t\t`CREATE TABLE ${check} (refused INTEGER\n\t\t\tCONSTRAINT \"an indexed string holds a lone surrogate or NUL, which plain text cannot keep\" CHECK (refused = 0))`,\n\t\t`INSERT INTO ${check} SELECT\n\t\t\t(SELECT count(*) FROM ${tables.tasks} WHERE ${escapes(\"kind\")})\n\t\t\t+ (SELECT count(*) FROM ${tables.submissions} WHERE request_id IS NOT NULL AND ${escapes(\"request_id\")})\n\t\t\t+ (SELECT count(*) FROM ${tables.documents} WHERE ${escapes(\"kind\")} OR ${escapes(\"key_value\")})`,\n\t\t`DROP TABLE ${check}`,\n\t\t`UPDATE ${tables.tasks} SET kind = json_extract(kind, '$')`,\n\t\t`UPDATE ${tables.submissions} SET request_id = json_extract(request_id, '$') WHERE request_id IS NOT NULL`,\n\t\t`UPDATE ${tables.documents} SET kind = json_extract(kind, '$'), key_value = json_extract(key_value, '$')`,\n\t];\n\treturn [\n\t\t{ version: 1, statements: initialSchema },\n\t\t{ version: 2, statements: sleepingStatus },\n\t\t{ version: 3, statements: plainIndexedStrings },\n\t];\n}\n\nexport const SQLITE_MIGRATIONS: readonly SqliteMigration[] = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA);\n\nexport const CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0;\n\n/** Apply all pending schema migrations atomically. */\nexport async function applySqliteMigrations(\n\tdatabase: SqliteDatabase,\n\tmigrations: readonly SqliteMigration[] = SQLITE_MIGRATIONS,\n): Promise<void> {\n\tawait applySqliteMigrationsForSchema(database, DEFAULT_SQLITE_SCHEMA, migrations);\n}\n\n/** Apply migrations rendered for a particular schema. */\nexport async function applySqliteMigrationsForSchema(\n\tdatabase: SqliteDatabase,\n\tschema: SqliteSchema,\n\tmigrations: readonly SqliteMigration[] = createSqliteMigrations(schema),\n): Promise<void> {\n\tawait applyMigrations(database, migrations, { table: schema.tables.durableSchema });\n}\n"]}
@@ -10,8 +10,6 @@ export type ScopeColumns = {
10
10
  export declare const parseJson: <T>(value: string) => T;
11
11
  /** Encodes a value as a stored JSON column. */
12
12
  export declare const encodeJson: (value: unknown) => string;
13
- /** Encodes an indexed string column. Some SQLite bindings replace lone UTF-16 surrogates; JSON keeps it lossless. */
14
- export declare const encodeIndexedString: (value: string) => string;
15
13
  /** A document scope's columns. */
16
14
  export declare const scopeColumns: (scope: DocumentRecord["scope"]) => ScopeColumns;
17
15
  /** A document address's columns, as `documents` stores and indexes them. */
@@ -1 +1 @@
1
- {"version":3,"file":"rows.d.ts","sourceRoot":"","sources":["../../../src/storage/sqlite/rows.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEtF,6DAA6D;AAC7D,MAAM,MAAM,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;AAE1C,qEAAqE;AACrE,MAAM,MAAM,YAAY,GAAG;IAC1B,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC;IACpD,QAAQ,CAAC,OAAO,EAAE,MAAM,C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AAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,mCAAmC;AACnC,eAAO,MAAM,SAAS,GAAI,CAAC,SAAS,MAAM,KAAG,CAA2B,CAAC;AAEzE,+CAA+C;AAC/C,eAAO,MAAM,UAAU,UAAW,OAAO,KAAG,MAAyC,CAAC;AAEtF,kCAAkC;AAClC,eAAO,MAAM,YAAY,UAAW,cAAc,CAAC,OAAO,CAAC,KAAG,YAS7D,CAAC;AAEF,4EAA4E;AAC5E,eAAO,MAAM,YAAY,YAAa,eAAe,GAAG,cAAc,GAAG,cAAc;eAvBlE,cAAc,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC;aACjC,MAAM;;;;CA8BxB,CAAC;AAEF,gEAAgE;AAChE,eAAO,MAAM,iBAAiB,SACvB,MAAM,aACD,MAAM,WACR,MAAM,UACP,MAAM,YACJ,MAAM,KACd,MAAsE,CAAC;AAE1E,uCAAuC;AACvC,eAAO,MAAM,UAAU,YAAa,eAAe,GAAG,cAAc,GAAG,cAAc,KAAG,MAGvF,CAAC;AAEF,4GAA4G;AAC5G,eAAO,MAAM,aAAa,WAAY,cAAc,KAAG,OACa,CAAC;AAErE,kHAAkH;AAClH,wBAAgB,WAAW,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,EAAE,CAa1D"}
@@ -1,10 +1,8 @@
1
- // How Durable's records map to SQLite: JSON text, indexed strings, and a document's scope and address columns.
1
+ // How Durable's records map to SQLite: JSON text, and a document's scope and address columns.
2
2
  /** Parses a stored JSON column. */
3
3
  export const parseJson = (value) => JSON.parse(value);
4
4
  /** Encodes a value as a stored JSON column. */
5
5
  export const encodeJson = (value) => JSON.stringify(value);
6
- /** Encodes an indexed string column. Some SQLite bindings replace lone UTF-16 surrogates; JSON keeps it lossless. */
7
- export const encodeIndexedString = (value) => JSON.stringify(value);
8
6
  /** A document scope's columns. */
9
7
  export const scopeColumns = (scope) => {
10
8
  switch (scope.kind) {
@@ -20,10 +18,10 @@ export const scopeColumns = (scope) => {
20
18
  export const addressParts = (address) => {
21
19
  const scope = scopeColumns(address.scope);
22
20
  return {
23
- kind: encodeIndexedString(address.kind),
21
+ kind: address.kind,
24
22
  ...scope,
25
23
  family: address.key === undefined ? 0 : 1,
26
- keyValue: encodeIndexedString(address.key ?? ""),
24
+ keyValue: address.key ?? "",
27
25
  };
28
26
  };
29
27
  /** One string per document address, from its stored columns. */
@@ -1 +1 @@
1
- {"version":3,"file":"rows.js","sourceRoot":"","sources":["../../../src/storage/sqlite/rows.ts"],"names":[],"mappings":"AAAA,+GAA+G;AAa/G,mCAAmC;AACnC,MAAM,CAAC,MAAM,SAAS,GAAG,CAAI,KAAa,EAAK,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAM,CAAC;AAEzE,+CAA+C;AAC/C,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,KAAc,EAAU,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAW,CAAC;AAEtF,qHAAqH;AACrH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAEpF,kCAAkC;AAClC,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,KAA8B,EAAgB,EAAE;IAC5E,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;QAC7C,KAAK,cAAc;YAClB,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,KAAK,CAAC,cAAc,EAAE,CAAC;QACrE,KAAK,MAAM;YACV,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;IACtD,CAAC;AACF,CAAC,CAAC;AAEF,4EAA4E;AAC5E,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,O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I;QACV,KAAK,CAAC,MAAM;QACZ,KAAK,CAAC,QAAQ;QACd,KAAK,CAAC,SAAS;QACf,KAAK,CAAC,OAAO;QACb,MAAM,CAAC,SAAS;QAChB,MAAM,CAAC,SAAS,IAAI,IAAI;QACxB,UAAU,CAAC,MAAM,CAAC;KAClB,CAAC;AACH,CAAC","sourcesContent":["// How Durable's records map to SQLite: JSON text, indexed strings, and a document's scope and address columns.\n\nimport type { DocumentAddress, DocumentCreate, DocumentRecord } from \"../../types.ts\";\n\n/** A value of a stored cell, as Durable's rows hold them. */\nexport type Cell = string | number | null;\n\n/** A document's scope as its `scope_kind` and `owner_id` columns. */\nexport type ScopeColumns = {\n\treadonly scopeKind: DocumentRecord[\"scope\"][\"kind\"];\n\treadonly ownerId: number;\n};\n\n/** Parses a stored JSON column. */\nexport const parseJson = <T>(value: string): T => JSON.parse(value) as T;\n\n/** Encodes a value as a stored JSON column. */\nexport const encodeJson = (value: unknown): string => JSON.stringify(value) as string;\n\n/** Encodes an indexed string column. Some SQLite bindings replace lone UTF-16 surrogates; JSON keeps it lossless. */\nexport const encodeIndexedString = (value: string): string => JSON.stringify(value);\n\n/** A document scope's columns. */\nexport const scopeColumns = (scope: DocumentRecord[\"scope\"]): ScopeColumns => {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn { scopeKind: \"session\", ownerId: 0 };\n\t\tcase \"conversation\":\n\t\t\treturn { scopeKind: \"conversation\", ownerId: scope.conversationId };\n\t\tcase \"task\":\n\t\t\treturn { scopeKind: \"task\", ownerId: scope.taskId };\n\t}\n};\n\n/** A document address's columns, as `documents` stores and indexes them. */\nexport const addressParts = (address: DocumentAddress | DocumentCreate | DocumentRecord) => {\n\tconst scope = scopeColumns(address.scope);\n\treturn {\n\t\tkind: encodeIndexedString(address.kind),\n\t\t...scope,\n\t\tfamily: address.key === undefined ? 0 : 1,\n\t\tkeyValue: encodeIndexedString(address.key ?? \"\"),\n\t};\n};\n\n/** One string per document address, from its stored columns. */\nexport const addressColumnsKey = (\n\tkind: string,\n\tscopeKind: string,\n\townerId: number,\n\tfamily: number,\n\tkeyValue: string,\n): string => JSON.stringify([kind, scopeKind, ownerId, family, keyValue]);\n\n/** One string per document address. */\nexport const addressKey = (address: DocumentAddress | DocumentCreate | DocumentRecord): string => {\n\tconst parts = addressParts(address);\n\treturn addressColumnsKey(parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue);\n};\n\n/** Whether a document keeps only its current state: its revisions go at each new base and at retirement. */\nexport const isCurrentOnly = (record: DocumentRecord): boolean =>\n\trecord.scope.kind !== \"conversation\" || record.history === \"latest\";\n\n/** A document record's `documents` row: id, kind, family, key, scope, owner, created and retired seqs, record. */\nexport function documentRow(record: DocumentRecord): Cell[] {\n\tconst parts = addressParts(record);\n\treturn [\n\t\trecord.id,\n\t\tparts.kind,\n\t\tparts.family,\n\t\tparts.keyValue,\n\t\tparts.scopeKind,\n\t\tparts.ownerId,\n\t\trecord.createdAt,\n\t\trecord.retiredAt ?? null,\n\t\tencodeJson(record),\n\t];\n}\n"]}
1
+ {"version":3,"file":"rows.js","sourceRoot":"","sources":["../../../src/storage/sqlite/rows.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAa9F,mCAAmC;AACnC,MAAM,CAAC,MAAM,SAAS,GAAG,CAAI,KAAa,EAAK,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAM,CAAC;AAEzE,+CAA+C;AAC/C,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,KAAc,EAAU,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAW,CAAC;AAEtF,kCAAkC;AAClC,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,KAA8B,EAAgB,EAAE;IAC5E,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;QAC7C,KAAK,cAAc;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AAK,CAAC,IAAI,KAAK,cAAc,IAAI,MAAM,CAAC,OAAO,KAAK,QAAQ,CAAC;AAErE,kHAAkH;AAClH,MAAM,UAAU,WAAW,CAAC,MAAsB;IACjD,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;IACnC,OAAO;QACN,MAAM,CAAC,EAAE;QACT,KAAK,CAAC,IAAI;QACV,KAAK,CAAC,MAAM;QACZ,KAAK,CAAC,QAAQ;QACd,KAAK,CAAC,SAAS;QACf,KAAK,CAAC,OAAO;QACb,MAAM,CAAC,SAAS;QAChB,MAAM,CAAC,SAAS,IAAI,IAAI;QACxB,UAAU,CAAC,MAAM,CAAC;KAClB,CAAC;AACH,CAAC","sourcesContent":["// How Durable's records map to SQLite: JSON text, and a document's scope and address columns.\n\nimport type { DocumentAddress, DocumentCreate, DocumentRecord } from \"../../types.ts\";\n\n/** A value of a stored cell, as Durable's rows hold them. */\nexport type Cell = string | number | null;\n\n/** A document's scope as its `scope_kind` and `owner_id` columns. */\nexport type ScopeColumns = {\n\treadonly scopeKind: DocumentRecord[\"scope\"][\"kind\"];\n\treadonly ownerId: number;\n};\n\n/** Parses a stored JSON column. */\nexport const parseJson = <T>(value: string): T => JSON.parse(value) as T;\n\n/** Encodes a value as a stored JSON column. */\nexport const encodeJson = (value: unknown): string => JSON.stringify(value) as string;\n\n/** A document scope's columns. */\nexport const scopeColumns = (scope: DocumentRecord[\"scope\"]): ScopeColumns => {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn { scopeKind: \"session\", ownerId: 0 };\n\t\tcase \"conversation\":\n\t\t\treturn { scopeKind: \"conversation\", ownerId: scope.conversationId };\n\t\tcase \"task\":\n\t\t\treturn { scopeKind: \"task\", ownerId: scope.taskId };\n\t}\n};\n\n/** A document address's columns, as `documents` stores and indexes them. */\nexport const addressParts = (address: DocumentAddress | DocumentCreate | DocumentRecord) => {\n\tconst scope = scopeColumns(address.scope);\n\treturn {\n\t\tkind: address.kind,\n\t\t...scope,\n\t\tfamily: address.key === undefined ? 0 : 1,\n\t\tkeyValue: address.key ?? \"\",\n\t};\n};\n\n/** One string per document address, from its stored columns. */\nexport const addressColumnsKey = (\n\tkind: string,\n\tscopeKind: string,\n\townerId: number,\n\tfamily: number,\n\tkeyValue: string,\n): string => JSON.stringify([kind, scopeKind, ownerId, family, keyValue]);\n\n/** One string per document address. */\nexport const addressKey = (address: DocumentAddress | DocumentCreate | DocumentRecord): string => {\n\tconst parts = addressParts(address);\n\treturn addressColumnsKey(parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue);\n};\n\n/** Whether a document keeps only its current state: its revisions go at each new base and at retirement. */\nexport const isCurrentOnly = (record: DocumentRecord): boolean =>\n\trecord.scope.kind !== \"conversation\" || record.history === \"latest\";\n\n/** A document record's `documents` row: id, kind, family, key, scope, owner, created and retired seqs, record. */\nexport function documentRow(record: DocumentRecord): Cell[] {\n\tconst parts = addressParts(record);\n\treturn [\n\t\trecord.id,\n\t\tparts.kind,\n\t\tparts.family,\n\t\tparts.keyValue,\n\t\tparts.scopeKind,\n\t\tparts.ownerId,\n\t\trecord.createdAt,\n\t\trecord.retiredAt ?? null,\n\t\tencodeJson(record),\n\t];\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { Context } from "@draht/chord/context";
2
2
  import type { JsonValue } from "@draht/chord/json";
3
- import type { SqliteDatabase } from "@draht/chord/sqlite";
3
+ import { type SqliteDatabase } from "@draht/chord/sqlite";
4
4
  import type { CommitResult, ConversationId, ConversationQuery, ConversationRecord, Cursor, DocumentAddress, DocumentId, DocumentPoint, DocumentQuery, DocumentRecord, EntryId, EntryQuery, EntryRecord, Id, Page, Seq, Storage, StorageWrite, StoredDocument, SubmissionId, SubmissionQuery, SubmissionRecord, TaskId, TaskQuery, TaskRecord } from "../../types.ts";
5
5
  type StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;
6
6
  export type SqliteStorageOptions = {
@@ -1 +1 @@
1
- {"version":3,"file":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CAAC,CAI3F;IAEK,eAAe,CACpB,KAAK,EAAE,eAAe,EACtB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,QAAQ,EAAE,OAAO,GACf,OAAO,CAAC,IAAI,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,CAwBzC;IAEK,mBAAmB,CACxB,cAAc,EAAE,cAAc,EAC9B,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,OAAO,GACf,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAQvC;IAEK,YAAY,CACjB,OAAO,EAAE,eAAe,EACxB,EAAE,EAAE,aAAa,EACjB,QAAQ,EAAE,OAAO,GACf,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAgBrC;IAEK,QAAQ,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,aAAa,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAIxG;IAEK,aAAa,CAClB,KAAK,EAAE,aAAa,EACpB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,QAAQ,EAAE,OAAO,GACf,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC,CAwBvC;IAED,KAAK,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAMtC;YAEa,aAAa;IAS3B;;;OAGG;YACW,SAAS;YAUT,gBAAgB;YAKhB,mBAAmB;IAqCjC,OAAO,CAAC,eAAe;IASvB,4GAA4G;YAC9F,aAAa;IAwB3B,OAAO,CAAC,UAAU;CAGlB"}
@@ -1,10 +1,11 @@
1
1
  import { apply } from "@draht/chord/delta";
2
+ import { BOUND_LIMIT } from "@draht/chord/sqlite";
2
3
  import { StorageRequestError } from "../../errors.js";
3
4
  import { idFromNumber, seqFromNumber } from "../../ids.js";
4
5
  import { nextCursor, scanStart } from "../scan.js";
5
6
  import { CommitState, claimOf, PendingWrites, prepareDocumentActions } from "./commit.js";
6
7
  import { applySqliteMigrationsForSchema } from "./migrations.js";
7
- import { addressParts, encodeIndexedString, isCurrentOnly, parseJson, scopeColumns } from "./rows.js";
8
+ import { addressParts, isCurrentOnly, parseJson, scopeColumns } from "./rows.js";
8
9
  import { createSqliteSchema } from "./schema.js";
9
10
  const cursorId = (cursor) => {
10
11
  const after = cursor?.after;
@@ -193,7 +194,7 @@ export class SqliteStorage {
193
194
  params.push(query.ownerTaskId);
194
195
  }
195
196
  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
+ const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.conversations} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} ${BOUND_LIMIT}`, ...params);
197
198
  return page(rows.map((row) => parseJson(row.record)), limit, start.order);
198
199
  }
199
200
  entry(idOrConversationId, idOrContext, context) {
@@ -277,7 +278,7 @@ export class SqliteStorage {
277
278
  params.push(upper);
278
279
  }
279
280
  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
+ const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(" AND ")} ORDER BY id DESC ${BOUND_LIMIT}`, ...params);
281
282
  values.push(...rows.map((row) => parseJson(row.record)));
282
283
  if (values.length > limit || conversation.parent === undefined)
283
284
  break;
@@ -320,7 +321,7 @@ export class SqliteStorage {
320
321
  params.push(segment.upper);
321
322
  }
322
323
  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
+ const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(" AND ")} ORDER BY id ASC ${BOUND_LIMIT}`, ...params);
324
325
  values.push(...rows.map((row) => parseJson(row.record)));
325
326
  if (values.length > limit)
326
327
  break;
@@ -344,7 +345,7 @@ export class SqliteStorage {
344
345
  }
345
346
  if (query.kind !== undefined) {
346
347
  clauses.push("kind = ?");
347
- params.push(encodeIndexedString(query.kind));
348
+ params.push(query.kind);
348
349
  }
349
350
  if (query.status !== undefined) {
350
351
  clauses.push("status = ?");
@@ -359,7 +360,7 @@ export class SqliteStorage {
359
360
  params.push(query.background ? 1 : 0);
360
361
  }
361
362
  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
+ const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.tasks} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} ${BOUND_LIMIT}`, ...params);
363
364
  return page(rows.map((row) => parseJson(row.record)), limit, start.order);
364
365
  }
365
366
  async submission(id, _context) {
@@ -382,12 +383,12 @@ export class SqliteStorage {
382
383
  params.push(query.status);
383
384
  }
384
385
  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
+ const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.submissions} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} ${BOUND_LIMIT}`, ...params);
386
387
  return page(rows.map((row) => parseJson(row.record)), limit, start.order);
387
388
  }
388
389
  async submissionByRequest(conversationId, requestId, _context) {
389
390
  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
+ const row = await this.db.get(`SELECT record FROM ${this.schema.tables.submissions} WHERE conversation_id = ? AND request_id = ?`, conversationId, requestId);
391
392
  return row === undefined ? undefined : parseJson(row.record);
392
393
  }
393
394
  async findDocument(address, at, _context) {
@@ -419,7 +420,7 @@ export class SqliteStorage {
419
420
  const params = [scope.scopeKind, scope.ownerId, cursorId(cursor) ?? -1];
420
421
  if (query.kind !== undefined) {
421
422
  clauses.push("kind = ?");
422
- params.push(encodeIndexedString(query.kind));
423
+ params.push(query.kind);
423
424
  }
424
425
  if (query.at === "current") {
425
426
  clauses.push("retired_at IS NULL");
@@ -429,7 +430,7 @@ export class SqliteStorage {
429
430
  params.push(query.at, query.at);
430
431
  }
431
432
  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
+ const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.documents} WHERE ${clauses.join(" AND ")} ORDER BY id ${BOUND_LIMIT}`, ...params);
433
434
  return page(rows.map((row) => parseJson(row.record)), limit);
434
435
  }
435
436
  close(_context) {