@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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,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 \"@draht/chord/context\";\nimport { apply, type Op } from \"@draht/chord/delta\";\nimport type { JsonValue } from \"@draht/chord/json\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteValue } from \"@draht/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"]}
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../../src/storage/sqlite/storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAW,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,WAAW,EAA8D,MAAM,qBAAqB,CAAC;AAC9G,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,aAAa,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACjF,OAAO,EAAE,kBAAkB,EAAqB,MAAM,aAAa,CAAC;AAqBpE,MAAM,QAAQ,GAAG,CAAuB,MAA0B,EAAiB,EAAE;IACpF,MAAM,KAAK,GAAG,MAAM,EAAE,KAAK,CAAC;IAC5B,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC;QAC5D,MAAM,IAAI,mBA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C,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 \"@draht/chord/context\";\nimport { apply, type Op } from \"@draht/chord/delta\";\nimport type { JsonValue } from \"@draht/chord/json\";\nimport { BOUND_LIMIT, type SqliteDatabase, type SqliteExecutor, type SqliteValue } from \"@draht/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, 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} ${BOUND_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 ${BOUND_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 ${BOUND_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(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} ${BOUND_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} ${BOUND_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\trequestId,\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(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 ${BOUND_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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"documents.d.ts","sourceRoot":"","sources":["../../../src/storage/store/documents.ts"],"names":[],"mappings":"AAKA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,eAAe,IAAI,aAAa,EAErC,KAAK,cAAc,IAAI,YAAY,EAGnC,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D,OAAO,KAAK,EACX,eAAe,EACf,cAAc,EACd,UAAU,EACV,aAAa,EACb,cAAc,EAEd,cAAc,EACd,MAAM,gBAAgB,CAAC;AAGxB,kHAAkH;AAClH,eAAO,MAAM,gBAAgB,YAAI,SAAS,EAAE,eAAe,EAAE,OAAO,CAAU,CAAC;AAE/E,4FAA4F;AAC5F,wBAAgB,WAAW,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,CAAC,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,cAAc,GAAG,SAAS,CAAA;CAAE,GACzE;IAAE,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,UAAU,CAAA;CAAE,CAAC;AAE9D;;;GAGG;AACH,wBAAsB,MAAM,CAC3B,QAAQ,EAAE,IAAI,CAAC,cAAc,EAAE,KAAK,GAAG,KAAK,CAAC,EAC7C,EAAE,EAAE,UAAU,EACd,EAAE,EAAE,aAAa,EACjB,KAAK,EAAE,MAAM,GACX,OAAO,CAAC,YAAY,CAAC,CAgBvB"}
@@ -1,10 +1,8 @@
1
1
  // Durable's documents in the store's documents engine (slice 6b §1.5, R1): a Durable address as an engine address
2
- // under the storage's owner name (its scope as the namespace, its kind and key JSON-encoded as Durable's indexed
3
- // strings), a Durable record as an engine record and back (the Durable record in `meta`), and a document read at a
4
- // point.
2
+ // under the storage's owner name (its scope as the namespace, its kind and key as they are), a Durable record as an
3
+ // engine record and back (the Durable record in `meta`), and a document read at a point.
5
4
  import { loadContent, readDocumentEntry, } from "@draht/chord";
6
5
  import { seqFromNumber } from "../../ids.js";
7
- import { encodeIndexed } from "./tables.js";
8
6
  /** The namespaces a storage claims under its owner: Durable's scopes (Chord's namespaces never contain a `:`). */
9
7
  export const SCOPE_NAMESPACES = ["session", "conversation:", "task:"];
10
8
  /** The engine namespace of a Durable scope: `session`, `conversation:<id>`, `task:<id>`. */
@@ -20,8 +18,8 @@ export function namespaceOf(scope) {
20
18
  }
21
19
  /** The engine address of a Durable address under `owner`. */
22
20
  export function addressOf(address, owner) {
23
- const at = { owner, namespace: namespaceOf(address.scope), kind: encodeIndexed(address.kind) };
24
- return address.key === undefined ? at : { ...at, key: encodeIndexed(address.key) };
21
+ const at = { owner, namespace: namespaceOf(address.scope), kind: address.kind };
22
+ return address.key === undefined ? at : { ...at, key: address.key };
25
23
  }
26
24
  /** What a record of `scope` keeps: session and task documents and latest conversation ones their latest state. */
27
25
  export function historyOf(record) {
@@ -1 +1 @@
1
- {"version":3,"file":"documents.js","sourceRoot":"","sources":["../../../src/storage/store/documents.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,iHAAiH;AACjH,mHAAmH;AACnH,SAAS;AAET,OAAO,EAMN,WAAW,EACX,iBAAiB,GACjB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAU7C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,kHAAkH;AAClH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,eAAe,EAAE,OAAO,CAAU,CAAC;AAE/E,4FAA4F;AAC5F,MAAM,UAAU,WAAW,CAAC,KAA8B;IACzD,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,OAAO,SAAS,CAAC;QAClB,KAAK,cAAc;YAClB,OAAO,gBAAgB,KAAK,CAAC,cAAc,EAAE,CAAC;QAC/C,KAAK,MAAM;YACV,OAAO,QAAQ,KAAK,CAAC,MAAM,EAAE,CAAC;IAChC,CAAC;AACF,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,SAAS,CAAC,OAAyC,EAAE,KAAa;IACjF,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;IAC/F,OAAO,OAAO,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;AACpF,CAAC;AAED,kHAAkH;AAClH,MAAM,UAAU,SAAS,CAAC,MAAuC;IAChE,OAAO,MAAM,CAAC,KAAK,CAAC,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AE,EAAE,EAAE,CAAC;IAC5F,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;IACxE,MAAM,KAAK,GAAgB,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACtD,kEAAkE;IAClE,MAAM,KAAK,GAAG,MAAM,CAAC,KAAmB,CAAC;IACzC,OAAO;QACN,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,CAAC,eAAe,EAAE;KAC7F,CAAC;AACH,CAAC","sourcesContent":["// Durable's documents in the store's documents engine (slice 6b §1.5, R1): a Durable address as an engine address\n// under the storage's owner name (its scope as the namespace, its kind and key JSON-encoded as Durable's indexed\n// strings), a Durable record as an engine record and back (the Durable record in `meta`), and a document read at a\n// point.\n\nimport {\n\ttype DocumentEntry,\n\ttype DocumentHistory,\n\ttype DocumentAddress as EngineAddress,\n\ttype DocumentPoint as EnginePoint,\n\ttype DocumentRecord as EngineRecord,\n\tloadContent,\n\treadDocumentEntry,\n} from \"@draht/chord\";\nimport type { SqliteExecutor } from \"@draht/chord/sqlite\";\nimport { seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tDocumentAddress,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentRecord,\n\tJsonObject,\n\tStoredDocument,\n} from \"../../types.ts\";\nimport { encodeIndexed } from \"./tables.ts\";\n\n/** The namespaces a storage claims under its owner: Durable's scopes (Chord's namespaces never contain a `:`). */\nexport const SCOPE_NAMESPACES = [\"session\", \"conversation:\", \"task:\"] as const;\n\n/** The engine namespace of a Durable scope: `session`, `conversation:<id>`, `task:<id>`. */\nexport function namespaceOf(scope: DocumentRecord[\"scope\"]): string {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn \"session\";\n\t\tcase \"conversation\":\n\t\t\treturn `conversation:${scope.conversationId}`;\n\t\tcase \"task\":\n\t\t\treturn `task:${scope.taskId}`;\n\t}\n}\n\n/** The engine address of a Durable address under `owner`. */\nexport function addressOf(address: DocumentAddress | DocumentCreate, owner: string): EngineAddress {\n\tconst at = { owner, namespace: namespaceOf(address.scope), kind: encodeIndexed(address.kind) };\n\treturn address.key === undefined ? at : { ...at, key: encodeIndexed(address.key) };\n}\n\n/** What a record of `scope` keeps: session and task documents and latest conversation ones their latest state. */\nexport function historyOf(record: DocumentCreate | DocumentRecord): DocumentHistory {\n\treturn record.scope.kind === \"conversation\" && record.history === \"rewindable\" ? \"rewindable\" : \"latest\";\n}\n\n/**\n * The engine record of a Durable creation at `seq` (retired at once for an empty lifetime): the Durable record itself,\n * its creation seq included, in `meta`, so a read of a live record parses one JSON text from one column, as\n * `SqliteStorage`'s does (a retirement later sets only the engine's `retired_at`).\n */\nexport function engineRecord(\n\tcreate: DocumentCreate,\n\towner: string,\n\tversion: number,\n\tseq: number,\n\tretired: boolean,\n): EngineRecord {\n\treturn {\n\t\tid: create.id,\n\t\t...addressOf(create, owner),\n\t\thistory: historyOf(create),\n\t\tcreatedAt: seq,\n\t\t...(retired ? { retiredAt: seq } : {}),\n\t\tmeta: JSON.stringify({ ...create, createdAt: seq }),\n\t\trevision: 1,\n\t\tversion,\n\t\tfingerprint: \"\",\n\t};\n}\n\n/**\n * The Durable record of an engine record of this storage's owner and scopes, `undefined` for anyone else's (a Chord\n * document, another owner's): its id is unknown to this storage.\n */\nexport function durableRecord(record: EngineRecord, owner: string): DocumentRecord | undefined {\n\tconst { meta } = record;\n\tif (meta === undefined || !ownedHere(record, owner)) return undefined;\n\treturn recordOfEntry({ meta, retired_at: record.retiredAt ?? null });\n}\n\n/** The Durable record of an engine entry read at one of this storage's addresses or scopes (the record in `meta`). */\nexport function recordOfEntry(entry: DocumentEntry): DocumentRecord {\n\t// Written by `engineRecord`, parsed fresh: a retirement since is set on it in place.\n\tconst record = JSON.parse(entry.meta!) as { -readonly [K in keyof DocumentRecord]: DocumentRecord[K] };\n\tif (entry.retired_at !== undefined && entry.retired_at !== null) record.retiredAt = seqFromNumber(entry.retired_at);\n\treturn record as DocumentRecord;\n}\n\n/** Whether a record is this storage's: `owner`'s, in one of Durable's scopes (not a Chord document of the owner). */\nfunction ownedHere(record: { readonly owner: string; readonly namespace: string }, owner: string): boolean {\n\tconst { namespace } = record;\n\tif (record.owner !== owner) return false;\n\treturn namespace === \"session\" || namespace.startsWith(\"conversation:\") || namespace.startsWith(\"task:\");\n}\n\n/** Whether a document is alive at `at` (the half-open lifetime). */\nexport function aliveAt(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/**\n * A document read at a point, as a tagged result: request errors are told after the guarded read (slice 6b §1.4),\n * never thrown inside it.\n */\nexport type DocumentRead =\n\t| { readonly kind: \"found\"; readonly document: StoredDocument | undefined }\n\t| { readonly kind: \"current_only\"; readonly id: DocumentId };\n\n/**\n * Document `id` of `owner` at `at`: absent (unknown, someone else's, not alive at `at`), a record whose history does\n * not reach back to `at`, or its value from the base at or below `at` and the deltas up to it.\n */\nexport async function readAt(\n\texecutor: Pick<SqliteExecutor, \"get\" | \"all\">,\n\tid: DocumentId,\n\tat: DocumentPoint,\n\towner: string,\n): Promise<DocumentRead> {\n\tconst entry = await readDocumentEntry(executor, id);\n\tif (entry === undefined || entry.meta === null || !ownedHere(entry, owner)) {\n\t\treturn { kind: \"found\", document: undefined };\n\t}\n\tconst record = recordOfEntry(entry);\n\tif (at !== \"current\" && entry.history !== \"rewindable\") return { kind: \"current_only\", id };\n\tif (!aliveAt(record, at)) return { kind: \"found\", document: undefined };\n\tconst point: EnginePoint = at;\n\tconst loaded = await loadContent(executor, id, point);\n\t// The engine stores what Durable's commits gave it: JSON objects.\n\tconst value = loaded.value as JsonObject;\n\treturn {\n\t\tkind: \"found\",\n\t\tdocument: { record, version: loaded.version, value, deltasSinceBase: loaded.deltasSinceBase },\n\t};\n}\n"]}
1
+ {"version":3,"file":"documents.js","sourceRoot":"","sources":["../../../src/storage/store/documents.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,oHAAoH;AACpH,yFAAyF;AAEzF,OAAO,EAMN,WAAW,EACX,iBAAiB,GACjB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAW7C,kHAAkH;AAClH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,eAAe,EAAE,OAAO,CAAU,CAAC;AAE/E,4FAA4F;AAC5F,MAAM,UAAU,WAAW,CAAC,KAA8B;IACzD,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,OAAO,SAAS,CAAC;QAClB,KAAK,cAAc;YAClB,OAAO,gBAAgB,KAAK,CAAC,cAAc,EAAE,CAAC;QAC/C,KAAK,MAAM;YACV,OAAO,QAAQ,KAAK,CAAC,MAAM,EAAE,CAAC;IAChC,CAAC;AACF,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,SAAS,CAAC,OAAyC,EAAE,KAAa;IACjF,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;IAChF,OAAO,OAAO,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC;AACrE,CAAC;AAED,kHAAkH;AAClH,MAAM,UAAU,SAAS,CAAC,MAAuC;IAChE,OAAO,MAAM,CAAC,KAAK,CAAC,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AE,EAAE,EAAE,CAAC;IAC5F,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;IACxE,MAAM,KAAK,GAAgB,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACtD,kEAAkE;IAClE,MAAM,KAAK,GAAG,MAAM,CAAC,KAAmB,CAAC;IACzC,OAAO;QACN,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,CAAC,eAAe,EAAE;KAC7F,CAAC;AACH,CAAC","sourcesContent":["// Durable's documents in the store's documents engine (slice 6b §1.5, R1): a Durable address as an engine address\n// under the storage's owner name (its scope as the namespace, its kind and key as they are), a Durable record as an\n// engine record and back (the Durable record in `meta`), and a document read at a point.\n\nimport {\n\ttype DocumentEntry,\n\ttype DocumentHistory,\n\ttype DocumentAddress as EngineAddress,\n\ttype DocumentPoint as EnginePoint,\n\ttype DocumentRecord as EngineRecord,\n\tloadContent,\n\treadDocumentEntry,\n} from \"@draht/chord\";\nimport type { SqliteExecutor } from \"@draht/chord/sqlite\";\nimport { seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tDocumentAddress,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentRecord,\n\tJsonObject,\n\tStoredDocument,\n} from \"../../types.ts\";\n\n/** The namespaces a storage claims under its owner: Durable's scopes (Chord's namespaces never contain a `:`). */\nexport const SCOPE_NAMESPACES = [\"session\", \"conversation:\", \"task:\"] as const;\n\n/** The engine namespace of a Durable scope: `session`, `conversation:<id>`, `task:<id>`. */\nexport function namespaceOf(scope: DocumentRecord[\"scope\"]): string {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn \"session\";\n\t\tcase \"conversation\":\n\t\t\treturn `conversation:${scope.conversationId}`;\n\t\tcase \"task\":\n\t\t\treturn `task:${scope.taskId}`;\n\t}\n}\n\n/** The engine address of a Durable address under `owner`. */\nexport function addressOf(address: DocumentAddress | DocumentCreate, owner: string): EngineAddress {\n\tconst at = { owner, namespace: namespaceOf(address.scope), kind: address.kind };\n\treturn address.key === undefined ? at : { ...at, key: address.key };\n}\n\n/** What a record of `scope` keeps: session and task documents and latest conversation ones their latest state. */\nexport function historyOf(record: DocumentCreate | DocumentRecord): DocumentHistory {\n\treturn record.scope.kind === \"conversation\" && record.history === \"rewindable\" ? \"rewindable\" : \"latest\";\n}\n\n/**\n * The engine record of a Durable creation at `seq` (retired at once for an empty lifetime): the Durable record itself,\n * its creation seq included, in `meta`, so a read of a live record parses one JSON text from one column, as\n * `SqliteStorage`'s does (a retirement later sets only the engine's `retired_at`).\n */\nexport function engineRecord(\n\tcreate: DocumentCreate,\n\towner: string,\n\tversion: number,\n\tseq: number,\n\tretired: boolean,\n): EngineRecord {\n\treturn {\n\t\tid: create.id,\n\t\t...addressOf(create, owner),\n\t\thistory: historyOf(create),\n\t\tcreatedAt: seq,\n\t\t...(retired ? { retiredAt: seq } : {}),\n\t\tmeta: JSON.stringify({ ...create, createdAt: seq }),\n\t\trevision: 1,\n\t\tversion,\n\t\tfingerprint: \"\",\n\t};\n}\n\n/**\n * The Durable record of an engine record of this storage's owner and scopes, `undefined` for anyone else's (a Chord\n * document, another owner's): its id is unknown to this storage.\n */\nexport function durableRecord(record: EngineRecord, owner: string): DocumentRecord | undefined {\n\tconst { meta } = record;\n\tif (meta === undefined || !ownedHere(record, owner)) return undefined;\n\treturn recordOfEntry({ meta, retired_at: record.retiredAt ?? null });\n}\n\n/** The Durable record of an engine entry read at one of this storage's addresses or scopes (the record in `meta`). */\nexport function recordOfEntry(entry: DocumentEntry): DocumentRecord {\n\t// Written by `engineRecord`, parsed fresh: a retirement since is set on it in place.\n\tconst record = JSON.parse(entry.meta!) as { -readonly [K in keyof DocumentRecord]: DocumentRecord[K] };\n\tif (entry.retired_at !== undefined && entry.retired_at !== null) record.retiredAt = seqFromNumber(entry.retired_at);\n\treturn record as DocumentRecord;\n}\n\n/** Whether a record is this storage's: `owner`'s, in one of Durable's scopes (not a Chord document of the owner). */\nfunction ownedHere(record: { readonly owner: string; readonly namespace: string }, owner: string): boolean {\n\tconst { namespace } = record;\n\tif (record.owner !== owner) return false;\n\treturn namespace === \"session\" || namespace.startsWith(\"conversation:\") || namespace.startsWith(\"task:\");\n}\n\n/** Whether a document is alive at `at` (the half-open lifetime). */\nexport function aliveAt(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/**\n * A document read at a point, as a tagged result: request errors are told after the guarded read (slice 6b §1.4),\n * never thrown inside it.\n */\nexport type DocumentRead =\n\t| { readonly kind: \"found\"; readonly document: StoredDocument | undefined }\n\t| { readonly kind: \"current_only\"; readonly id: DocumentId };\n\n/**\n * Document `id` of `owner` at `at`: absent (unknown, someone else's, not alive at `at`), a record whose history does\n * not reach back to `at`, or its value from the base at or below `at` and the deltas up to it.\n */\nexport async function readAt(\n\texecutor: Pick<SqliteExecutor, \"get\" | \"all\">,\n\tid: DocumentId,\n\tat: DocumentPoint,\n\towner: string,\n): Promise<DocumentRead> {\n\tconst entry = await readDocumentEntry(executor, id);\n\tif (entry === undefined || entry.meta === null || !ownedHere(entry, owner)) {\n\t\treturn { kind: \"found\", document: undefined };\n\t}\n\tconst record = recordOfEntry(entry);\n\tif (at !== \"current\" && entry.history !== \"rewindable\") return { kind: \"current_only\", id };\n\tif (!aliveAt(record, at)) return { kind: \"found\", document: undefined };\n\tconst point: EnginePoint = at;\n\tconst loaded = await loadContent(executor, id, point);\n\t// The engine stores what Durable's commits gave it: JSON objects.\n\tconst value = loaded.value as JsonObject;\n\treturn {\n\t\tkind: \"found\",\n\t\tdocument: { record, version: loaded.version, value, deltasSinceBase: loaded.deltasSinceBase },\n\t};\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import type { ChordStore } from "@draht/chord";
2
+ import type { Context } from "@draht/chord/context";
3
+ /**
4
+ * Rewrites the address columns of `owner`'s documents that an older version laid out differently, from the Durable
5
+ * record each keeps in `meta` (`addressOf`, what a write gives the engine): one indexed read when none is left, and no
6
+ * commit. Rejects, rewriting nothing, when an older version kept an identity this one refuses (`identityProblem`): it
7
+ * would name another document.
8
+ */
9
+ export declare function applyStoreMigrations(store: ChordStore, owner: string, context: Context): Promise<void>;
10
+ //# sourceMappingURL=migrations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../../../src/storage/store/migrations.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAQpD;;;;;GAKG;AACH,wBAAsB,oBAAoB,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAkB5G"}
@@ -0,0 +1,44 @@
1
+ // Durable's document addresses in Chord's `chord_documents` brought to this version's layout at open (declared tables
2
+ // migrate through `evolveTable` in tables.ts). Checked at every open and rewritten without a seq: an import, a backup or
3
+ // a synced copy can bring old rows, only the rows say which layout they are in, and a seq the rewrite took would not
4
+ // replay on other copies. While the storage is open its claims refuse a batch, so no old rows arrive.
5
+ import { identityProblem } from "../../ids.js";
6
+ import { addressOf } from "./documents.js";
7
+ /**
8
+ * Rewrites the address columns of `owner`'s documents that an older version laid out differently, from the Durable
9
+ * record each keeps in `meta` (`addressOf`, what a write gives the engine): one indexed read when none is left, and no
10
+ * commit. Rejects, rewriting nothing, when an older version kept an identity this one refuses (`identityProblem`): it
11
+ * would name another document.
12
+ */
13
+ export async function applyStoreMigrations(store, owner, context) {
14
+ const candidates = await store.read((executor) => executor.all(CANDIDATES, owner), context);
15
+ const rewrites = [];
16
+ for (const row of candidates) {
17
+ const record = JSON.parse(row.meta);
18
+ const problem = identityProblem("Document kind", record.kind) ??
19
+ (record.key === undefined ? undefined : identityProblem("Document key", record.key));
20
+ if (problem !== undefined)
21
+ throw new Error(`StoreStorage: document ${row.id} cannot be migrated: ${problem}`);
22
+ const address = addressOf(record, owner);
23
+ const key = address.key ?? "";
24
+ if (address.kind !== row.kind || key !== row.key)
25
+ rewrites.push([address.kind, key, row.id]);
26
+ }
27
+ if (rewrites.length === 0)
28
+ return;
29
+ // Outside the commit queue: no seq, no outbox commit.
30
+ await store.maintain(async (executor) => {
31
+ for (const rewrite of rewrites)
32
+ await executor.run(REWRITE, ...rewrite);
33
+ });
34
+ }
35
+ // The owner's rows in Durable's scopes in an older layout, found in the engine's address index alone (an open with
36
+ // nothing left reads only it), then read by id. Before plain addresses a kind and a key were JSON string literals (a
37
+ // singleton's key the engine's `""`), so such a kind starts with `"`; a plain kind may too, and the record in `meta`
38
+ // tells them apart.
39
+ const CANDIDATES = `SELECT id, kind, key, meta FROM chord_documents WHERE id IN (
40
+ SELECT id FROM chord_documents
41
+ WHERE owner = ? AND (namespace = 'session' OR namespace GLOB 'conversation:*' OR namespace GLOB 'task:*')
42
+ AND kind GLOB '"*')`;
43
+ const REWRITE = "UPDATE chord_documents SET kind = ?, key = ? WHERE id = ?";
44
+ //# sourceMappingURL=migrations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/storage/store/migrations.ts"],"names":[],"mappings":"AAAA,sHAAsH;AACtH,yHAAyH;AACzH,qHAAqH;AACrH,sGAAsG;AAItG,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAK3C;;;;;GAKG;AACH,MAAM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O,IAAI,QAAQ;YAAE,MAAM,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC;IACzE,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,mHAAmH;AACnH,qHAAqH;AACrH,qHAAqH;AACrH,oBAAoB;AACpB,MAAM,UAAU,GAAG;;;qBAGE,CAAC;AAEtB,MAAM,OAAO,GAAG,2DAA2D,CAAC","sourcesContent":["// Durable's document addresses in Chord's `chord_documents` brought to this version's layout at open (declared tables\n// migrate through `evolveTable` in tables.ts). Checked at every open and rewritten without a seq: an import, a backup or\n// a synced copy can bring old rows, only the rows say which layout they are in, and a seq the rewrite took would not\n// replay on other copies. While the storage is open its claims refuse a batch, so no old rows arrive.\n\nimport type { ChordStore } from \"@draht/chord\";\nimport type { Context } from \"@draht/chord/context\";\nimport { identityProblem } from \"../../ids.ts\";\nimport type { DocumentRecord } from \"../../types.ts\";\nimport { addressOf } from \"./documents.ts\";\n\n/** A row of `owner`'s documents that may still be in an older layout. */\ntype Candidate = { readonly id: number; readonly kind: string; readonly key: string; readonly meta: string };\n\n/**\n * Rewrites the address columns of `owner`'s documents that an older version laid out differently, from the Durable\n * record each keeps in `meta` (`addressOf`, what a write gives the engine): one indexed read when none is left, and no\n * commit. Rejects, rewriting nothing, when an older version kept an identity this one refuses (`identityProblem`): it\n * would name another document.\n */\nexport async function applyStoreMigrations(store: ChordStore, owner: string, context: Context): Promise<void> {\n\tconst candidates = await store.read((executor) => executor.all<Candidate>(CANDIDATES, owner), context);\n\tconst rewrites: [kind: string, key: string, id: number][] = [];\n\tfor (const row of candidates) {\n\t\tconst record = JSON.parse(row.meta) as DocumentRecord;\n\t\tconst problem =\n\t\t\tidentityProblem(\"Document kind\", record.kind) ??\n\t\t\t(record.key === undefined ? undefined : identityProblem(\"Document key\", record.key));\n\t\tif (problem !== undefined) throw new Error(`StoreStorage: document ${row.id} cannot be migrated: ${problem}`);\n\t\tconst address = addressOf(record, owner);\n\t\tconst key = address.key ?? \"\";\n\t\tif (address.kind !== row.kind || key !== row.key) rewrites.push([address.kind, key, row.id]);\n\t}\n\tif (rewrites.length === 0) return;\n\t// Outside the commit queue: no seq, no outbox commit.\n\tawait store.maintain(async (executor) => {\n\t\tfor (const rewrite of rewrites) await executor.run(REWRITE, ...rewrite);\n\t});\n}\n\n// The owner's rows in Durable's scopes in an older layout, found in the engine's address index alone (an open with\n// nothing left reads only it), then read by id. Before plain addresses a kind and a key were JSON string literals (a\n// singleton's key the engine's `\"\"`), so such a kind starts with `\"`; a plain kind may too, and the record in `meta`\n// tells them apart.\nconst CANDIDATES = `SELECT id, kind, key, meta FROM chord_documents WHERE id IN (\n\tSELECT id FROM chord_documents\n\tWHERE owner = ? AND (namespace = 'session' OR namespace GLOB 'conversation:*' OR namespace GLOB 'task:*')\n\tAND kind GLOB '\"*')`;\n\nconst REWRITE = \"UPDATE chord_documents SET kind = ?, key = ? WHERE id = ?\";\n"]}
@@ -18,8 +18,9 @@ export declare class StoreStorage implements Storage {
18
18
  private constructor();
19
19
  /**
20
20
  * Opens Durable's storage in `store` under `owner` (a lowercase `[a-z0-9@/._~-]` name): claims its tables and its
21
- * document namespaces (a second claim is refused `invalid/args`), creates or migrates its tables, and raises the
22
- * store's allocator above every id it holds (one index read). A failure releases what it claimed.
21
+ * document namespaces (a second claim is refused `invalid/args`), creates or migrates its tables, rewrites the
22
+ * document addresses older versions laid out differently (`applyStoreMigrations`), and raises the store's allocator
23
+ * above every id it holds (one index read). A failure releases what it claimed.
23
24
  */
24
25
  static open(store: Store, owner: string, context: Context): Promise<StoreStorage>;
25
26
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../../src/storage/store/storage.ts"],"names":[],"mappings":"AAIA,OAAO,EAMN,KAAK,KAAK,EAEV,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,SAAS,EAAE,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CACd,KAAK,EAAE,eAAe,EACtB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,IAAI,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,CAQzC;IAED,mBAAmB,CAClB,cAAc,EAAE,cAAc,EAC9B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAUvC;IAED,YAAY,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAK/G;IAED,QAAQ,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAKjG;IAED,aAAa,CACZ,KAAK,EAAE,aAAa,EACpB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC,CAYvC;IAED;;;OAGG;IACH,KAAK,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAatC;CAmLD"}
@@ -7,8 +7,9 @@ import { idFromNumber, seqFromNumber } from "../../ids.js";
7
7
  import { nextCursor, scanStart } from "../scan.js";
8
8
  import { DurableCommit } from "./commit.js";
9
9
  import { addressOf, namespaceOf, readAt, recordOfEntry, SCOPE_NAMESPACES } from "./documents.js";
10
+ import { applyStoreMigrations } from "./migrations.js";
10
11
  import { storageQueries } from "./queries.js";
11
- import { Conversations, Entries, EntryHeads, encodeIndexed, RecordIds, Submissions, Tasks } from "./tables.js";
12
+ import { Conversations, Entries, EntryHeads, RecordIds, Submissions, Tasks } from "./tables.js";
12
13
  /** The id condition of a table scan from `start`. */
13
14
  function scanFrom(start) {
14
15
  return start.order === "ascending"
@@ -55,8 +56,9 @@ export class StoreStorage {
55
56
  }
56
57
  /**
57
58
  * Opens Durable's storage in `store` under `owner` (a lowercase `[a-z0-9@/._~-]` name): claims its tables and its
58
- * document namespaces (a second claim is refused `invalid/args`), creates or migrates its tables, and raises the
59
- * store's allocator above every id it holds (one index read). A failure releases what it claimed.
59
+ * document namespaces (a second claim is refused `invalid/args`), creates or migrates its tables, rewrites the
60
+ * document addresses older versions laid out differently (`applyStoreMigrations`), and raises the store's allocator
61
+ * above every id it holds (one index read). A failure releases what it claimed.
60
62
  */
61
63
  static async open(store, owner, context) {
62
64
  // Chord's own: `openStore` or `importStore` made it.
@@ -75,6 +77,7 @@ export class StoreStorage {
75
77
  for (const namespace of SCOPE_NAMESPACES)
76
78
  chord.claims.documents(owner, namespace, claimant);
77
79
  await declared.prepare(context);
80
+ await applyStoreMigrations(chord, owner, context);
78
81
  const highest = await chord.read((executor) => executor.get(`SELECT max("id") AS id FROM "${tables.recordIds.sql.table}"`), context);
79
82
  if (highest?.id != null)
80
83
  chord.ids.raise(highest.id);
@@ -181,7 +184,7 @@ export class StoreStorage {
181
184
  if (query.conversationId !== undefined)
182
185
  conditions.push(["conversation_id", "eq", query.conversationId]);
183
186
  if (query.kind !== undefined)
184
- conditions.push(["kind", "eq", encodeIndexed(query.kind)]);
187
+ conditions.push(["kind", "eq", query.kind]);
185
188
  if (query.status !== undefined)
186
189
  conditions.push(["status", "eq", query.status]);
187
190
  if (query.abortRequested !== undefined)
@@ -213,7 +216,7 @@ export class StoreStorage {
213
216
  const submissions = this.#queries.submissions;
214
217
  const conditions = [
215
218
  ["conversation_id", "eq", conversationId],
216
- ["request_id", "eq", encodeIndexed(requestId)],
219
+ ["request_id", "eq", requestId],
217
220
  ];
218
221
  return this.#read(async (executor) => {
219
222
  const row = await submissions.first(executor, conditions, "ascending");
@@ -236,7 +239,7 @@ export class StoreStorage {
236
239
  const scope = {
237
240
  owner: this.#owner,
238
241
  namespace: namespaceOf(query.scope),
239
- ...(query.kind === undefined ? {} : { kind: encodeIndexed(query.kind) }),
242
+ ...(query.kind === undefined ? {} : { kind: query.kind }),
240
243
  };
241
244
  return this.#store
242
245
  .read((executor) => listDocumentEntries(executor, scope, query.at, after, limit + 1), context)