@tearleads/client-sdk 0.1.82 → 0.1.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/documents/documentSync.js.map +1 -1
- package/data/documents/shared/crypto.js.map +1 -1
- package/data/documents/shared/types.d.ts +1 -1
- package/data/documents/shared/types.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerDocumentReassignment.js +7 -9
- package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +3 -3
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
- package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataRows.js +4 -20
- package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js +2 -2
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRebindPersistence.js +4 -17
- package/data/persistence/container-contents/containerRebindPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerReconcilePersistence.js +1 -1
- package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRemovalWork.js +1 -1
- package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
- package/data/persistence/container-contents/containerStructuralRepair.js +5 -11
- package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js +34 -9
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
- package/data/persistence/container-contents/dormantContainerMetadata.js +4 -14
- package/data/persistence/container-contents/dormantContainerMetadata.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +5 -9
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryReset.d.ts +6 -0
- package/data/persistence/documents/documentProjectionContainers.js +28 -0
- package/data/persistence/documents/documentProjectionContainers.js.map +1 -0
- package/data/persistence/documents/documentsPersistence.js +5 -9
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstones.js +4 -11
- package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
- package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -1
- package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
- package/data/persistence/documents/internal/discardDocument.js +2 -2
- package/data/persistence/documents/internal/discardDocument.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -22
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentMutationPersistence.js +3 -3
- package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
- package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentRecordIdentity.js.map +1 -1
- package/data/persistence/documents/internal/documentRows.js.map +1 -1
- package/data/persistence/documents/internal/ensureDocumentsSchema.js +1 -1
- package/data/persistence/documents/internal/ensureDocumentsSchema.js.map +1 -1
- package/data/persistence/documents/internal/orphanSideRows.js +1 -1
- package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
- package/data/persistence/documents/internal/rowQueryPersistence.js +1 -1
- package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
- package/data/persistence/documents/internal/syncQueuePersistence.js +2 -2
- package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentHistoryPersistence.d.ts +1 -1
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentHistoryPersistence.js +5 -5
- package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -0
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPendingUpdatePersistence.d.ts +2 -2
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPendingUpdatePersistence.js +2 -2
- package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -0
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPersistenceTypes.d.ts +2 -2
- package/data/persistence/documents/records/documentPersistenceTypes.js.map +1 -0
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentRecordPersistence.d.ts +1 -1
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentRecordPersistence.js +4 -4
- package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -0
- package/data/persistence/documents/records/documentRowsInTransaction.js +68 -0
- package/data/persistence/documents/records/documentRowsInTransaction.js.map +1 -0
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentSyncFailurePersistence.d.ts +2 -2
- package/data/{sqlite/documentPersistence → persistence/documents/records}/documentSyncFailurePersistence.js +3 -3
- package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -0
- package/data/{sqlite/documentPersistence → persistence/documents/records}/index.d.ts +2 -2
- package/data/{sqlite/documentPersistence → persistence/documents/records}/index.js +4 -4
- package/data/persistence/documents/records/index.js.map +1 -0
- package/data/persistence/documents/types.d.ts +2 -2
- package/data/persistence/documents/types.js.map +1 -1
- package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts +2 -0
- package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js +9 -0
- package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -1
- package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js +9 -0
- package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyPersistence.js +3 -9
- package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
- package/{workflows/sync/remoteResetPrincipalScope.d.ts → data/persistence/principalPolicy/principalPolicyRemoteReset.d.ts} +1 -1
- package/{workflows/sync/remoteResetPrincipalScope.js → data/persistence/principalPolicy/principalPolicyRemoteReset.js} +16 -13
- package/data/persistence/principalPolicy/principalPolicyRemoteReset.js.map +1 -0
- package/data/persistence/verifiedManifestBundlePersistence.d.ts +2 -0
- package/data/persistence/verifiedManifestBundlePersistence.js +7 -0
- package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
- package/data/sqlite/{documentPersistence/documentOrphanBlobReclaims.js → schema/documentOrphanBlobReclaimSchema.js} +1 -1
- package/data/sqlite/schema/documentOrphanBlobReclaimSchema.js.map +1 -0
- package/data/sqlite/schema/index.js +1 -1
- package/data/sqlite/schema/index.js.map +1 -1
- package/data/sqlite/sqliteBindBudget.js +12 -0
- package/data/sqlite/sqliteBindBudget.js.map +1 -1
- package/package.json +1 -1
- package/workflows/container-contents/container-state/create/createIntentSeed.js.map +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/metadata/index.js.map +1 -1
- package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
- package/workflows/container-contents/metadata/metadataEvents.js.map +1 -1
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +1 -1
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
- package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
- package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
- package/workflows/container-contents/pendingWrites/index.js +1 -1
- package/workflows/container-contents/pendingWrites/index.js.map +1 -1
- package/workflows/container-contents/recovery/accessRestoration.js +1 -1
- package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
- package/workflows/container-contents/remoteReset/containerRemoteReset.d.ts +185 -0
- package/workflows/container-contents/remoteReset/containerRemoteReset.js +174 -0
- package/workflows/container-contents/remoteReset/containerRemoteReset.js.map +1 -0
- package/workflows/container-contents/remoteReset/remoteResetCursorScope.d.ts +14 -0
- package/workflows/{sync → container-contents/remoteReset}/remoteResetCursorScope.js +2 -2
- package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -0
- package/workflows/documents/create/documentCreationPersistence.js.map +1 -1
- package/workflows/documents/create/index.d.ts +1 -1
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/documentMutationCommit.d.ts +1 -1
- package/workflows/documents/documentMutationCommit.js.map +1 -1
- package/workflows/documents/index.d.ts +2 -2
- package/workflows/documents/index.js +2 -2
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/remoteReset/documentRemoteReset.d.ts +56 -0
- package/workflows/documents/remoteReset/documentRemoteReset.js +135 -0
- package/workflows/documents/remoteReset/documentRemoteReset.js.map +1 -0
- package/workflows/{sync → documents/remoteReset}/remoteResetAttachments.js +3 -3
- package/workflows/documents/remoteReset/remoteResetAttachments.js.map +1 -0
- package/workflows/{sync → documents/remoteReset}/remoteResetPlans.d.ts +1 -1
- package/workflows/{sync → documents/remoteReset}/remoteResetPlans.js +7 -7
- package/workflows/documents/remoteReset/remoteResetPlans.js.map +1 -0
- package/workflows/documents/sync/index.js.map +1 -1
- package/workflows/documents/sync/initialSync.d.ts +1 -1
- package/workflows/documents/sync/initialSync.js.map +1 -1
- package/workflows/documents/sync/readOnlySync.d.ts +1 -1
- package/workflows/documents/sync/readOnlySync.js.map +1 -1
- package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
- package/workflows/documents/sync/syncAttemptState.d.ts +1 -1
- package/workflows/documents/sync/syncAttemptState.js.map +1 -1
- package/workflows/documents/sync/syncResponseResult.js.map +1 -1
- package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
- package/workflows/documents/syncFailures/index.js.map +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
- package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
- package/workflows/documents/syncPlan/syncPlanRequestBounds.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -1
- package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
- package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
- package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
- package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
- package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
- package/workflows/organizations/readModel/organizationRemoteReset.js +25 -0
- package/workflows/organizations/readModel/organizationRemoteReset.js.map +1 -0
- package/workflows/registration/persistRegistrationBootstrap.d.ts +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/workflows/sync/remoteReset.js +60 -229
- package/workflows/sync/remoteReset.js.map +1 -1
- package/workflows/sync/remoteResetScope.d.ts +7 -10
- package/workflows/sync/remoteResetScope.js +26 -108
- package/workflows/sync/remoteResetScope.js.map +1 -1
- package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +0 -1
- package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +0 -1
- package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +0 -1
- package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +0 -1
- package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +0 -1
- package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +0 -1
- package/data/sqlite/documentPersistence/index.js.map +0 -1
- package/workflows/sync/remoteResetAttachments.js.map +0 -1
- package/workflows/sync/remoteResetBatches.js +0 -13
- package/workflows/sync/remoteResetBatches.js.map +0 -1
- package/workflows/sync/remoteResetCursorScope.js.map +0 -1
- package/workflows/sync/remoteResetPlans.js.map +0 -1
- package/workflows/sync/remoteResetPrincipalScope.js.map +0 -1
- /package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPersistenceTypes.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documentHistoryPersistence.js","sourceRoot":"","sources":["documentHistoryPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,yBAAyB,EACzB,cAAc,EACd,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EACL,0BAA0B,EAC1B,sBAAsB,EACtB,cAAc,GACf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAgB,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAG1E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,oCAAoC,GAAG,GAAG,CAAC;AACxD,MAAM,CAAC,MAAM,qCAAqC,GAAG,GAAG,GAAG,IAAI,CAAC;AAShE;;;GAGG;AACH,SAAS,WAAW,CAAC,KAAoB;IACvC,OAAO,GAAG,CACR,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACjD,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACjD,EAAE,CAAC,sBAAsB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAC5C,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,sBAAsB,CAAC,KAAoB;IAClD,OAAO,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,sBAAsB,CAAC,QAAQ,CAAC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AAyB,CAAC,cAAc,CAAC,CAC1C,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,iBAAiB,CAAC,IAAI,EAAE,CAAC;QACzB,cAAc,CAAC,IAAI,EAAE,CAAC;IACxB,CAAC;AACH,CAAC;AAED,MAAM,sBAAuB,SAAQ,KAAK;IACxC;QACE,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAClC,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IACvC,CAAC;CACF;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,OAAgB,EAChB,KAAoB;IAEpB,MAAM,eAAe,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IAC/C,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC,0BAA0B,CAAC;aAClC,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,0BAA0B,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACrD,EAAE,CAAC,0BAA0B,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACtD,CACF,CAAC;QACJ,MAAM,EAAE;aACL,MAAM,CAAC,sBAAsB,CAAC;aAC9B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACjD,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CAClD,CACF,CAAC;IACN,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n createDocument,\n exportFullHistoryIdentity,\n importSnapshot,\n satisfiesVersionVector,\n} from \"@tearleads/loro\";\nimport { and, eq, inArray, isNull, ne, sql } from \"drizzle-orm\";\nimport {\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentTables,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentScope } from \"./documentPersistenceTypes\";\n\n/**\n * Compaction thresholds: once the tail carries this many rows or bytes, the\n * next persist of a full-history-capable document exports a fresh checkpoint\n * and clears the tail. Small enough to keep restore replay short, large\n * enough that a full-history export (O(history)) happens once per burst of\n * edits instead of per keystroke.\n */\nexport const DOCUMENT_HISTORY_COMPACTION_MAX_ROWS = 200;\nexport const DOCUMENT_HISTORY_COMPACTION_MAX_BYTES = 512 * 1024;\n\n/**\n * Row provenance: \"local\" for updates authored on this device, \"remote\" for\n * decrypted pulled updates. Restores advance the outgoing-delta marker across\n * remote rows (already server-side); local rows never advance it.\n */\ntype DocumentHistoryUpdateOrigin = \"local\" | \"remote\";\n\n/**\n * Rows of the update log that are history tail: every row except an \"outbox\"\n * row, which only waits to be sent (see `documentHistoryUpdates`).\n */\nfunction tailInScope(scope: DocumentScope) {\n return and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ne(documentHistoryUpdates.origin, \"outbox\"),\n );\n}\n\n/**\n * Tail rows compaction may fold into a checkpoint and delete: a queued row is\n * the only durable copy of an unsent update, so it waits for settlement even\n * when a checkpoint already covers its operations.\n */\nfunction compactableTailInScope(scope: DocumentScope) {\n return and(tailInScope(scope), isNull(documentHistoryUpdates.updateId));\n}\n\ninterface DocumentHistoryTailUpdate {\n readonly origin: DocumentHistoryUpdateOrigin;\n readonly updateData: string;\n}\n\ninterface DocumentHistoryRestoreState {\n readonly snapshot: string;\n readonly tailUpdates: readonly DocumentHistoryTailUpdate[];\n}\n\nexport async function appendDocumentHistoryUpdates(\n execSql: ExecSql,\n scope: DocumentScope,\n updates: readonly string[],\n origin: DocumentHistoryUpdateOrigin,\n): Promise<void> {\n if (updates.length === 0) {\n return;\n }\n await ensureSqlTables(execSql, documentTables);\n const createdAt = new Date().toISOString();\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n // Chunked: a catch-up pull can carry thousands of updates, and a single\n // multi-row insert would exceed SQLite's bound-variable limit.\n for (let index = 0; index < updates.length; index += HISTORY_ROW_CHUNK) {\n await db.insert(documentHistoryUpdates).values(\n updates.slice(index, index + HISTORY_ROW_CHUNK).map((updateData) => ({\n id: crypto.randomUUID(),\n appKind: scope.appKind,\n localId: scope.localId,\n updateData,\n origin,\n createdAt,\n })),\n );\n }\n });\n}\n\n/**\n * The checkpoint + ordered tail for a scope, or null when NEITHER exists (a\n * discovered shell that has not hydrated content yet; the caller starts the\n * document empty and the remote pull supplies the content). A tail WITHOUT a\n * checkpoint — a crash between the first enqueued edit's tail append and the\n * birth-checkpoint seed — restores as tail-only (`snapshot: \"\"`): those tail\n * rows can be the only durable copy of a local edit, so they must never be\n * silently ignored.\n */\nexport async function loadDocumentHistoryRestoreState(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentHistoryRestoreState | null> {\n await ensureSqlTables(execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Read the TAIL before the (full) checkpoint: if another pane compacts\n // between the two reads, this order yields old-tail + new-checkpoint — a\n // safe superset (the new checkpoint subsumes the old tail, and replay is\n // idempotent by op identity). The reverse order could yield old-checkpoint\n // + already-emptied tail, a torn read that silently drops the compacted\n // ops for the whole session.\n const tail = await db\n .select({\n id: documentHistoryUpdates.id,\n origin: documentHistoryUpdates.origin,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(tailInScope(scope))\n // Insertion order: same-millisecond appends make createdAt tie and a\n // random-uuid tiebreak would replay out of order. importUpdates tolerates\n // out-of-order batches, but replay should still be deterministic.\n .orderBy(sql`rowid`);\n\n const [checkpoint] = await db\n .select({ snapshot: documentHistoryCheckpoints.snapshot })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n )\n .limit(1);\n if (!checkpoint && tail.length === 0) {\n return null;\n }\n\n return {\n snapshot: checkpoint?.snapshot ?? \"\",\n tailUpdates: tail.map((row) => ({\n // Fail toward re-sending: an unrecognized origin never advances the\n // marker, which is the recoverable direction (a redundant re-submit\n // is idempotent; a skipped local op would be orphaned from sync).\n origin:\n row.origin === \"remote\" ? (\"remote\" as const) : (\"local\" as const),\n updateData: row.updateData,\n })),\n };\n}\n\n/**\n * Size of the tail compaction can shrink. Queued rows are excluded: they stay\n * until settlement, so counting them would re-export full history on every\n * persist while offline edits wait to sync.\n */\nexport async function readDocumentHistoryTailSize(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<{ byteLength: number; hasCheckpoint: boolean; rowCount: number }> {\n await ensureSqlTables(execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [totals] = await db\n .select({\n byteLength: sql<number>`coalesce(sum(length(${documentHistoryUpdates.updateData})), 0)`,\n rowCount: sql<number>`count(*)`,\n })\n .from(documentHistoryUpdates)\n .where(compactableTailInScope(scope));\n const [checkpoint] = await db\n .select({ localId: documentHistoryCheckpoints.localId })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n )\n .limit(1);\n return {\n byteLength: Number(totals?.byteLength ?? 0),\n hasCheckpoint: checkpoint !== undefined,\n rowCount: Number(totals?.rowCount ?? 0),\n };\n}\n\ninterface DocumentHistoryTailEntry {\n readonly id: string;\n readonly updateData: string;\n}\n\n/**\n * The current compactable tail rows WITH their payloads, so a compactor can\n * prove each row's ops are covered by the snapshot it is about to install\n * (another pane's append may carry ops this pane's document has not merged\n * yet). Queued rows are never candidates.\n */\nexport async function listDocumentHistoryTailEntries(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentHistoryTailEntry[]> {\n await ensureSqlTables(execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: documentHistoryUpdates.id,\n updateData: documentHistoryUpdates.updateData,\n })\n .from(documentHistoryUpdates)\n .where(compactableTailInScope(scope));\n return rows.flatMap((row) =>\n row.id === null ? [] : [{ id: row.id, updateData: row.updateData }],\n );\n}\n\nconst HISTORY_ROW_CHUNK = 400;\n\n/**\n * Replace the scope's checkpoint with a fresh full-history snapshot and\n * delete ONLY the tail rows the caller captured before exporting it. Every\n * append path writes its tail row after the ops are already in the live\n * document, so any row captured before the export is provably covered by\n * the snapshot — while a row appended concurrently (between export and this\n * delete) survives for the next compaction instead of being lost.\n */\nexport async function replaceDocumentHistoryCheckpoint(\n execSql: ExecSql,\n scope: DocumentScope,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n /**\n * Skip the monotonic version gate. Only for document CREATION, where any\n * existing checkpoint under this localId is the orphan of a failed prior\n * attempt (checkpoint written, record row never committed) — a retry's\n * fresh document need not dominate that orphan to replace it.\n */\n force?: boolean;\n snapshot: string;\n /**\n * Re-checked after acquiring the serialized mutation slot (like the\n * record-save path): a store reset/recreation that happened while this\n * call waited in the queue must abort the write, or a stale compactor\n * could install the OLD document's checkpoint over the new identity's.\n */\n stillCurrent?: () => boolean;\n },\n): Promise<boolean> {\n await ensureSqlTables(execSql, documentTables);\n // Sequential (non-transactional) so callers already inside a transaction\n // can nest this. Crash between the statements leaves the new checkpoint\n // plus covered tail rows — a safe superset, since tail replay is\n // idempotent by op identity. The replacement itself is a compare-and-swap\n // on the stored revision, so the version gate cannot be bypassed by a\n // concurrent compactor between the read and the write: whoever loses the\n // CAS re-reads and re-evaluates the gate against the winner's checkpoint.\n return getClientSQLitePersistenceRuntime(execSql).runMutation(async (tx) => {\n if (input.stillCurrent?.() === false) {\n return false;\n }\n for (let attempt = 0; attempt < CHECKPOINT_CAS_ATTEMPTS; attempt += 1) {\n let replaced: boolean;\n try {\n replaced = await tryReplaceCheckpointOnce(tx, scope, input);\n } catch (error) {\n if (error instanceof CheckpointGateRejected) {\n // A fresher checkpoint dominates this candidate: no write, and\n // the caller's covered rows must stay for the covering pane.\n return false;\n }\n throw error;\n }\n if (!replaced) {\n // CAS lost to a concurrent writer — re-read and re-evaluate the\n // gate against the winner's checkpoint.\n continue;\n }\n for (\n let index = 0;\n index < input.coveredTailIds.length;\n index += HISTORY_ROW_CHUNK\n ) {\n // Never a queued row, even if a caller names one: its operations may\n // be in the checkpoint, but it is still the unsent update itself.\n await tx\n .delete(documentHistoryUpdates)\n .where(\n and(\n compactableTailInScope(scope),\n inArray(\n documentHistoryUpdates.id,\n input.coveredTailIds.slice(index, index + HISTORY_ROW_CHUNK),\n ),\n ),\n );\n }\n return true;\n }\n // Exhaustion must not read as durable success: creation and rebuild\n // callers persist record rows assuming the checkpoint landed.\n throw new Error(\n \"Document history checkpoint replacement lost every CAS attempt\",\n );\n });\n}\n\nconst CHECKPOINT_CAS_ATTEMPTS = 16;\n\ntype MutationDb = Parameters<\n Parameters<\n ReturnType<typeof getClientSQLitePersistenceRuntime>[\"runMutation\"]\n >[0]\n>[0];\n\n/**\n * One compare-and-swap attempt. Returns true when this caller's checkpoint\n * became the stored one, false when a concurrent writer won the CAS (the\n * caller re-reads and retries), and throws CheckpointGateRejected when a\n * fresher stored checkpoint dominates the candidate.\n */\nasync function tryReplaceCheckpointOnce(\n tx: MutationDb,\n scope: DocumentScope,\n input: {\n endVersionVector: string;\n force?: boolean;\n snapshot: string;\n },\n): Promise<boolean> {\n const updatedAt = new Date().toISOString();\n const revision = crypto.randomUUID();\n const [stored] = await tx\n .select({\n endVersionVector: documentHistoryCheckpoints.endVersionVector,\n revision: documentHistoryCheckpoints.revision,\n snapshot: documentHistoryCheckpoints.snapshot,\n })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n )\n .limit(1);\n\n if (!stored) {\n const inserted = await tx\n .insert(documentHistoryCheckpoints)\n .values({\n appKind: scope.appKind,\n localId: scope.localId,\n snapshot: input.snapshot,\n endVersionVector: input.endVersionVector,\n revision,\n updatedAt,\n })\n .onConflictDoNothing({\n target: [\n documentHistoryCheckpoints.appKind,\n documentHistoryCheckpoints.localId,\n ],\n })\n .returning({ localId: documentHistoryCheckpoints.localId });\n // Conflict means a concurrent writer inserted first — retry the gate.\n return inserted.length > 0;\n }\n\n // A stale compactor (a pane whose document has not merged another pane's\n // ops) must never replace a checkpoint it does not cover: the covered\n // pane may already have deleted its tail rows, so regressing the\n // checkpoint would leave those ops with no durable copy at all. Vector\n // dominance proves counter coverage; the retained-prefix identity also\n // proves the candidate carries the exact stored operations at those\n // counters rather than a same-frontier fork.\n if (input.force !== true) {\n if (\n !satisfiesVersionVector(input.endVersionVector, stored.endVersionVector)\n ) {\n throw new CheckpointGateRejected();\n }\n if (\n input.snapshot !== stored.snapshot &&\n !(await candidateContainsStoredCheckpointHistory({\n candidateSnapshot: input.snapshot,\n storedEndVersion: stored.endVersionVector,\n storedSnapshot: stored.snapshot,\n }))\n ) {\n throw new CheckpointGateRejected();\n }\n }\n\n const replaced = await tx\n .update(documentHistoryCheckpoints)\n .set({\n snapshot: input.snapshot,\n endVersionVector: input.endVersionVector,\n revision,\n updatedAt,\n })\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n eq(documentHistoryCheckpoints.revision, stored.revision),\n ),\n )\n .returning({ localId: documentHistoryCheckpoints.localId });\n return replaced.length > 0;\n}\n\nasync function candidateContainsStoredCheckpointHistory(input: {\n candidateSnapshot: string;\n storedEndVersion: string;\n storedSnapshot: string;\n}): Promise<boolean> {\n const [candidateDocument, storedDocument] = await Promise.all([\n createDocument(\"checkpoint-candidate-history-gate\"),\n createDocument(\"checkpoint-stored-history-gate\"),\n ]);\n try {\n importSnapshot(candidateDocument, base64ToBytes(input.candidateSnapshot));\n importSnapshot(storedDocument, base64ToBytes(input.storedSnapshot));\n return (\n exportFullHistoryIdentity(candidateDocument, input.storedEndVersion) ===\n exportFullHistoryIdentity(storedDocument)\n );\n } finally {\n candidateDocument.free();\n storedDocument.free();\n }\n}\n\nclass CheckpointGateRejected extends Error {\n constructor() {\n super(\"checkpoint gate rejected\");\n this.name = \"CheckpointGateRejected\";\n }\n}\n\nexport async function deleteDocumentHistory(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await ensureSqlTables(execSql, documentTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (tx) => {\n await tx\n .delete(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, scope.appKind),\n eq(documentHistoryCheckpoints.localId, scope.localId),\n ),\n );\n await tx\n .delete(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n ),\n );\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ClientSQLiteTransactionScope } from "
|
|
2
|
-
import type { ExecSql } from "
|
|
1
|
+
import type { ClientSQLiteTransactionScope } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
2
|
+
import type { ExecSql } from "../../../sqlite/sqlSchema.js";
|
|
3
3
|
import type { DocumentScope, PendingUpdateFields, PendingUpdateRecord } from "./documentPersistenceTypes.js";
|
|
4
4
|
/**
|
|
5
5
|
* Queued updates are the rows of the local update log that carry an
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { and, asc, eq, inArray, isNotNull, lt, or, sql, } from "drizzle-orm";
|
|
2
|
-
import { documentHistoryUpdates, documents } from "
|
|
3
|
-
import { getClientSQLitePersistenceRuntime } from "
|
|
2
|
+
import { documentHistoryUpdates, documents } from "../../../sqlite/schema/index.js";
|
|
3
|
+
import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
4
4
|
/**
|
|
5
5
|
* Queued updates are the rows of the local update log that carry an
|
|
6
6
|
* `updateId`. A tail row (origin "local") stays in the log after settlement as
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documentPendingUpdatePersistence.js","sourceRoot":"","sources":["documentPendingUpdatePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,GAAG,EACH,EAAE,EACF,OAAO,EACP,SAAS,EACT,EAAE,EACF,EAAE,EAEF,GAAG,GACJ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAE3E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAS7F;;;;;GAKG;AACH,MAAM,aAAa,GAAG,QAAQ,CAAC;AAK/B,SAAS,aAAa,CAAC,KAAoB;IACzC,OAAO,GAAG,CACR,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACjD,EAAE,CAAC,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACjD,SAAS,CAAC,sBAAsB,CAAC,QAAQ,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,SAAS,wBAAwB,CAC/B,GAA6B;IAE7B,yEAAyE;IACzE,0EAA0E;IAC1E,IACE,GAAG,CAAC,yBAAyB,KAAK,IAAI;QACtC,GAAG,CAAC,uBAAuB,KAAK,IAAI,EACpC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC;QACxB,UAAU,EAAE,GAAG,CAAC,UAAU;QAC1B,yBAAyB,EAAE,GAAG,CAAC,yBAAyB;QACxD,uBAAuB,EAAE,GAAG,CAAC,uBAAuB;QACpD,mBAAmB,EAAE,GAAG,CAAC,mBAAmB;QAC5C,UAAU,EAAE,GAAG,CAAC,UAAU;KAC3B,CAAC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q,\n inArray,\n isNotNull,\n lt,\n or,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { documentHistoryUpdates, documents } from \"../../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type {\n DocumentScope,\n PendingUpdateFields,\n PendingUpdateRecord,\n SelectedPendingUpdateRow,\n} from \"./documentPersistenceTypes\";\n\n/**\n * Queued updates are the rows of the local update log that carry an\n * `updateId`. A tail row (origin \"local\") stays in the log after settlement as\n * history until compaction; an \"outbox\" row has no tail role and settlement\n * deletes it.\n */\nconst OUTBOX_ORIGIN = \"outbox\";\n\ntype QueueStatement = Pick<ClientSQLiteTransactionScope, \"delete\" | \"update\">;\ntype QueueRead = Pick<ClientSQLiteTransactionScope, \"selectDistinct\">;\n\nfunction queuedInScope(scope: DocumentScope) {\n return and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n isNotNull(documentHistoryUpdates.updateId),\n );\n}\n\nfunction mapSelectedPendingUpdate(\n row: SelectedPendingUpdateRow,\n): PendingUpdateRecord {\n // A queued row always carries its submission vectors; a row without them\n // cannot be submitted and must fail closed rather than send empty ranges.\n if (\n row.partialStartVersionVector === null ||\n row.partialEndVersionVector === null\n ) {\n throw new Error(\"Queued document update is missing its version vectors\");\n }\n return {\n id: String(row.id ?? \"\"),\n updateData: row.updateData,\n partialStartVersionVector: row.partialStartVersionVector,\n partialEndVersionVector: row.partialEndVersionVector,\n sourceVersionVector: row.sourceVersionVector,\n rekeyCount: row.rekeyCount,\n };\n}\n\n/** The ids among `localIds` (one app kind) with at least one queued update. */\nexport async function listLocalIdsWithQueuedUpdates(\n db: QueueRead,\n appKind: string,\n localIds: readonly string[],\n): Promise<string[]> {\n const uniqueIds = [...new Set(localIds)];\n if (uniqueIds.length === 0) return [];\n const rows = await db\n .selectDistinct({ localId: documentHistoryUpdates.localId })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, appKind),\n inArray(documentHistoryUpdates.localId, uniqueIds),\n isNotNull(documentHistoryUpdates.updateId),\n ),\n )\n .orderBy(asc(documentHistoryUpdates.localId));\n return rows.map((row) => row.localId);\n}\n\nexport async function hasQueuedDocumentUpdates(\n db: QueueRead,\n scope: DocumentScope,\n): Promise<boolean> {\n const ids = await listLocalIdsWithQueuedUpdates(db, scope.appKind, [\n scope.localId,\n ]);\n return ids.length > 0;\n}\n\nexport async function listDocumentPendingUpdates(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<PendingUpdateRecord[]> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: documentHistoryUpdates.updateId,\n updateData: documentHistoryUpdates.updateData,\n partialStartVersionVector:\n documentHistoryUpdates.partialStartVersionVector,\n partialEndVersionVector: documentHistoryUpdates.partialEndVersionVector,\n sourceVersionVector: documentHistoryUpdates.sourceVersionVector,\n rekeyCount: documentHistoryUpdates.rekeyCount,\n })\n .from(documentHistoryUpdates)\n .where(queuedInScope(scope))\n .orderBy(asc(documentHistoryUpdates.createdAt), asc(sql`rowid`));\n\n return rows.map(mapSelectedPendingUpdate);\n}\n\n/** One log row for a queued update; `origin` decides its tail role. */\nexport function queuedUpdateRow(input: {\n createdAt: string;\n origin: \"local\" | typeof OUTBOX_ORIGIN;\n pendingUpdate: PendingUpdateFields;\n scope: DocumentScope;\n updateId: string;\n}) {\n return {\n id: crypto.randomUUID(),\n appKind: input.scope.appKind,\n localId: input.scope.localId,\n updateData: input.pendingUpdate.updateData,\n origin: input.origin,\n createdAt: input.createdAt,\n updateId: input.updateId,\n partialStartVersionVector: input.pendingUpdate.partialStartVersionVector,\n partialEndVersionVector: input.pendingUpdate.partialEndVersionVector,\n sourceVersionVector: input.pendingUpdate.sourceVersionVector ?? null,\n };\n}\n\n/**\n * Queue an update that has no history-tail role: container metadata (its\n * content is its checkpoint) and full-state re-uploads after a remote reset.\n */\nexport async function enqueueDocumentPendingUpdate(\n execSql: ExecSql,\n scope: DocumentScope,\n pendingUpdate: PendingUpdateFields,\n): Promise<string> {\n const updateId = crypto.randomUUID();\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .insert(documentHistoryUpdates)\n .values(\n queuedUpdateRow({\n createdAt: new Date().toISOString(),\n origin: OUTBOX_ORIGIN,\n pendingUpdate,\n scope,\n updateId,\n }),\n )\n .run();\n });\n return updateId;\n}\n\n/**\n * Append a locally authored update to the history tail AND queue it, as one\n * row in one transaction. A crash can therefore never leave the op restorable\n * from history while missing from the outgoing queue, where a null-marker\n * restore would classify it as covered and never send it.\n */\nexport async function enqueueDocumentPendingUpdateWithHistory(\n execSql: ExecSql,\n scope: DocumentScope,\n pendingUpdate: PendingUpdateFields,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n): Promise<string | null> {\n const createdAt = new Date().toISOString();\n return getClientSQLitePersistenceRuntime(execSql).transaction(\n async (tx) => {\n if (options) {\n const matchingDocuments = await tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n sql`${documents.documentId} IS ${options.expectedDocumentId}`,\n eq(\n documents.recoveryGeneration,\n options.expectedRecoveryGeneration,\n ),\n ),\n )\n .limit(1);\n if (matchingDocuments.length === 0) {\n return null;\n }\n }\n\n return insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt,\n pendingUpdate,\n scope,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n}\n\nexport async function insertDocumentPendingUpdateWithHistoryInTransaction(input: {\n createdAt: string;\n pendingUpdate: PendingUpdateFields;\n scope: DocumentScope;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const updateId = crypto.randomUUID();\n await input.tx\n .insert(documentHistoryUpdates)\n .values(\n queuedUpdateRow({\n createdAt: input.createdAt,\n origin: \"local\",\n pendingUpdate: input.pendingUpdate,\n scope: input.scope,\n updateId,\n }),\n )\n .run();\n return updateId;\n}\n\n/**\n * Assign a fresh id to a queued update, keeping every other column. A lost\n * sync ack leaves the server holding the update under the original id with\n * ciphertext a rebuilt submission can never reproduce (each rebuild encrypts\n * with a fresh IV), so the id is permanently poisoned: every resubmission\n * 409s and the whole outgoing batch rolls back. Re-keying lets the next sync\n * pass submit the same ops under a conflict-free id; the server-side copy is\n * harmless because CRDT update import is idempotent.\n *\n * Returns null when no row carries the id, so callers never report progress\n * for a row that lives in some other queue (or nowhere). The UPDATE's own\n * RETURNING row is the progress signal — a pre-flight SELECT would race a\n * second tab sharing the SQLite file, which can settle the row between the\n * read and the write and turn \"rekeyed\" into a spurious re-arm.\n *\n * The persisted per-row bound is enforced here as well: a row already at\n * MAX_PENDING_UPDATE_REKEYS is left untouched and reported as no progress.\n * The in-memory lane counter bounds a busy-loop within one session; this\n * bound survives restarts, so a poisoned row cannot re-key forever at three\n * passes per launch.\n */\nexport const MAX_PENDING_UPDATE_REKEYS = 5;\n\n/**\n * Reset the durable re-key budget for every queued update in a scope. The\n * cap exists to stop a server that keeps conflicting fresh ids from driving\n * a network-speed loop — but a budget burned during an unrelated outage\n * (e.g. yesterday's stale-bundle deadlock 409ing every submit) should not be\n * terminal forever. An explicit manual retry is the deliberate, rate-limited\n * signal that conditions changed, so it gets a fresh budget.\n */\nexport async function resetDocumentPendingUpdateRekeyBudget(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documentHistoryUpdates)\n .set({ rekeyCount: 0 })\n .where(queuedInScope(scope));\n });\n}\n\nexport async function rekeyDocumentPendingUpdate(\n execSql: ExecSql,\n id: string,\n): Promise<string | null> {\n const nextId = crypto.randomUUID();\n let rekeyed = false;\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const updated = await db\n .update(documentHistoryUpdates)\n .set({\n updateId: nextId,\n rekeyCount: sql`${documentHistoryUpdates.rekeyCount} + 1`,\n })\n .where(\n and(\n eq(documentHistoryUpdates.updateId, id),\n lt(documentHistoryUpdates.rekeyCount, MAX_PENDING_UPDATE_REKEYS),\n ),\n )\n .returning({ id: documentHistoryUpdates.updateId });\n rekeyed = updated.length > 0;\n });\n return rekeyed ? nextId : null;\n}\n\n/**\n * Settle queued updates: an outbox row is deleted, and a tail row stops being\n * queued but stays as history until compaction folds it into a checkpoint.\n */\nexport async function settleQueuedDocumentUpdatesInTransaction(\n tx: QueueStatement,\n scope: DocumentScope,\n updateIds: readonly string[],\n): Promise<void> {\n const uniqueIds = [...new Set(updateIds)];\n if (uniqueIds.length === 0) return;\n const selected = and(\n eq(documentHistoryUpdates.appKind, scope.appKind),\n eq(documentHistoryUpdates.localId, scope.localId),\n inArray(documentHistoryUpdates.updateId, uniqueIds),\n );\n await unqueueSelectedUpdates(tx, selected);\n}\n\nasync function unqueueSelectedUpdates(\n tx: QueueStatement,\n selected: SQL | undefined,\n): Promise<void> {\n await tx\n .delete(documentHistoryUpdates)\n .where(and(selected, eq(documentHistoryUpdates.origin, OUTBOX_ORIGIN)))\n .run();\n await tx\n .update(documentHistoryUpdates)\n .set({\n updateId: null,\n partialStartVersionVector: null,\n partialEndVersionVector: null,\n sourceVersionVector: null,\n rekeyCount: 0,\n })\n .where(selected)\n .run();\n}\n\n/** Settle one queued update by id, whatever its scope. */\nexport async function settleDocumentPendingUpdate(\n execSql: ExecSql,\n id: string,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await unqueueSelectedUpdates(db, eq(documentHistoryUpdates.updateId, id));\n });\n}\n\n/**\n * Stop queueing every update in the given scopes: outbox rows are dropped,\n * and local tail rows keep their content as history (it is already in the\n * document).\n */\nexport async function unqueueDocumentScopesInTransaction(\n tx: QueueStatement,\n scopes: readonly DocumentScope[],\n): Promise<void> {\n if (scopes.length === 0) return;\n await unqueueSelectedUpdates(tx, or(...scopes.map(queuedInScope)));\n}\n\nexport async function unqueueDocumentPendingUpdates(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await unqueueDocumentScopesInTransaction(db, [scope]);\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ContainerAccessLevel } from "
|
|
2
|
-
import type { DocumentSyncPullContinuation } from "
|
|
1
|
+
import type { ContainerAccessLevel } from "../../../../internal/crypto/index.js";
|
|
2
|
+
import type { DocumentSyncPullContinuation } from "../../../documents/shared/sync/pullContinuation.js";
|
|
3
3
|
export interface DocumentRecord {
|
|
4
4
|
id: string;
|
|
5
5
|
documentId: string | null;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documentPersistenceTypes.js","sourceRoot":"","sources":["documentPersistenceTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\n\nexport interface DocumentRecord {\n id: string;\n documentId: string | null;\n /**\n * Durable fence advanced by an atomic raw-history recovery install. Writers\n * capture this before waiting for the mutation queue and must refuse to\n * publish when recovery advanced it first.\n */\n recoveryGeneration?: number;\n /** Former server id reserved for deterministic post-purge recreation. */\n recoveryDocumentId?: string | null;\n /**\n * Encoded end version vector of the persisted content frontier. Content\n * itself lives in the durable history (checkpoint + tail); this column\n * exists so priming and coverage predicates can compare versions from a\n * narrow indexed column. Empty string means \"never hydrated\".\n */\n snapshotEndVersion: string;\n accessEpoch: number;\n accessStateHash?: string | null;\n effectiveAccessLevel?: ContainerAccessLevel | null;\n lastCommitLsn?: string | null;\n contentKeyBundle?: string | null;\n documentKekTargets?: string | null;\n documentManifestBundle?: string | null;\n pendingBaseVersion?: string | null;\n pullContinuation?: DocumentSyncPullContinuation | null;\n /**\n * The durable continuation column was non-null but could not be decoded.\n * Keep forcing a page-one pull until a successful settlement replaces the\n * malformed value; ordinary local saves must preserve that recovery signal.\n */\n pullContinuationRecoveryRequired?: true;\n}\n\nexport interface PendingUpdateFields {\n updateData: string;\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n sourceVersionVector?: string | null;\n}\n\nexport interface PendingUpdateRecord extends PendingUpdateFields {\n id: string;\n /**\n * Times this row was assigned a fresh id by lost-ack conflict recovery.\n * Persisted so the bound survives restarts; absent means zero (rows from\n * simple test doubles).\n */\n rekeyCount?: number | undefined;\n}\n\nexport interface DocumentScope {\n appKind: string;\n localId: string;\n}\n\nexport interface SelectedDocumentRecordRow {\n id: string;\n documentId: string | null;\n recoveryGeneration: number;\n recoveryDocumentId: string | null;\n snapshotEndVersion: string;\n accessEpoch: number;\n accessStateHash: string | null;\n effectiveAccessLevel: string | null;\n lastCommitLsn: string | null;\n contentKeyBundle: string | null;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n pendingBaseVersion: string | null;\n pullContinuation: string | null;\n}\n\nexport interface SelectedPendingUpdateRow {\n id: string | null;\n updateData: string;\n partialStartVersionVector: string | null;\n partialEndVersionVector: string | null;\n sourceVersionVector: string | null;\n rekeyCount: number;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ExecSql } from "
|
|
1
|
+
import type { ExecSql } from "../../../sqlite/sqlSchema.js";
|
|
2
2
|
import type { DocumentRecord, DocumentScope, SelectedDocumentRecordRow } from "./documentPersistenceTypes.js";
|
|
3
3
|
/**
|
|
4
4
|
* The ONE select shape for a full documents-row record: every reader that
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { and, desc, eq, sql } from "drizzle-orm";
|
|
2
|
-
import { deserializeDocumentSyncPullContinuation } from "
|
|
3
|
-
import { normalizeEffectiveAccessLevel } from "
|
|
4
|
-
import { documentHistoryUpdates, documents } from "
|
|
5
|
-
import { getClientSQLitePersistenceRuntime } from "
|
|
2
|
+
import { deserializeDocumentSyncPullContinuation } from "../../../documents/shared/sync/pullContinuation.js";
|
|
3
|
+
import { normalizeEffectiveAccessLevel } from "../../../keying/accessLevel.js";
|
|
4
|
+
import { documentHistoryUpdates, documents } from "../../../sqlite/schema/index.js";
|
|
5
|
+
import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
6
|
/**
|
|
7
7
|
* The ONE select shape for a full documents-row record: every reader that
|
|
8
8
|
* feeds mapSelectedDocumentRecord spreads this, so a new record column cannot
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documentRecordPersistence.js","sourceRoot":"","sources":["documentRecordPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iDAAiD,CAAC;AAC1G,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAC3E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAQ7F;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,EAAE,EAAE,SAAS,CAAC,OAAO;IACrB,UAAU,EAAE,SAAS,CAAC,UAAU;IAChC,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,WAAW,EAAE,SAAS,CAAC,WAAW;IAClC,eAAe,EAAE,SAAS,CAAC,eAAe;IAC1C,oBAAoB,EAAE,SAAS,CAAC,oBAAoB;IACpD,aAAa,EAAE,SAAS,CAAC,aAAa;IACtC,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;IACxD,gBAAgB,EAAE,SAAS,CAAC,gBAA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AE;SAClB,MAAM,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC;SACtC,IAAI,CAAC,SAAS,CAAC;SACf,KAAK,CACJ,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAC1E;QACD,yEAAyE;QACzE,oEAAoE;SACnE,OAAO,CACN,IAAI,CAAC,mBAAmB,CAAC,EACzB,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EACzB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CACxB;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IAEZ,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,IAAI,CAAC;AAClC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,OAAgB,EAChB,KAAoB;IAEpB,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC,SAAS,CAAC;aACjB,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, desc, eq, sql } from \"drizzle-orm\";\nimport { deserializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport { documentHistoryUpdates, documents } from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n DocumentScope,\n SelectedDocumentRecordRow,\n} from \"./documentPersistenceTypes\";\n\n/**\n * The ONE select shape for a full documents-row record: every reader that\n * feeds mapSelectedDocumentRecord spreads this, so a new record column cannot\n * silently miss one of them.\n */\nexport const documentRecordSelection = {\n id: documents.localId,\n documentId: documents.documentId,\n recoveryGeneration: documents.recoveryGeneration,\n recoveryDocumentId: documents.recoveryDocumentId,\n snapshotEndVersion: documents.snapshotEndVersion,\n accessEpoch: documents.accessEpoch,\n accessStateHash: documents.accessStateHash,\n effectiveAccessLevel: documents.effectiveAccessLevel,\n lastCommitLsn: documents.lastCommitLsn,\n documentManifestBundle: documents.documentManifestBundle,\n contentKeyBundle: documents.contentKeyBundle,\n documentKekTargets: documents.documentKekTargets,\n pendingBaseVersion: documents.pendingBaseVersion,\n pullContinuation: documents.pullContinuation,\n};\n\nexport function mapSelectedDocumentRecord(\n row: SelectedDocumentRecordRow,\n): DocumentRecord {\n const record: DocumentRecord = {\n id: row.id,\n documentId: row.documentId,\n recoveryGeneration: row.recoveryGeneration,\n snapshotEndVersion: row.snapshotEndVersion,\n accessEpoch: row.accessEpoch,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n lastCommitLsn: row.lastCommitLsn,\n contentKeyBundle: row.contentKeyBundle,\n documentKekTargets: row.documentKekTargets,\n documentManifestBundle: row.documentManifestBundle,\n };\n\n if (row.accessStateHash !== null) {\n record.accessStateHash = row.accessStateHash;\n }\n\n if (row.recoveryDocumentId !== null) {\n record.recoveryDocumentId = row.recoveryDocumentId;\n }\n\n // Only surface the marker when one was persisted, so a row that never stored\n // one keeps its prior shape (and init falls through to seeding it).\n if (row.pendingBaseVersion !== null) {\n record.pendingBaseVersion = row.pendingBaseVersion;\n }\n\n const pullContinuation = deserializeDocumentSyncPullContinuation(\n row.pullContinuation,\n );\n if (pullContinuation !== null) {\n record.pullContinuation = pullContinuation;\n } else if (row.pullContinuation !== null) {\n record.pullContinuationRecoveryRequired = true;\n }\n\n return record;\n}\n\nexport async function loadDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentRecordSelection)\n .from(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .limit(1);\n\n return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;\n}\n\nexport async function findLocalIdByDocumentId(\n execSql: ExecSql,\n appKind: string,\n documentId: string,\n): Promise<string | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const hasPendingUpdates = sql<number>`EXISTS (\n SELECT 1\n FROM ${documentHistoryUpdates}\n WHERE ${documentHistoryUpdates.appKind} = ${documents.appKind}\n AND ${documentHistoryUpdates.localId} = ${documents.localId}\n AND ${documentHistoryUpdates.updateId} IS NOT NULL\n )`;\n const hasPendingLocalWork = sql<number>`(\n ${hasPendingUpdates}\n OR (\n ${documents.pendingBaseVersion} IS NOT NULL\n AND ${documents.pendingBaseVersion} <> ${documents.snapshotEndVersion}\n )\n )`;\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(eq(documents.appKind, appKind), eq(documents.documentId, documentId)),\n )\n // Duplicate remote identities can survive an interrupted local adoption.\n // Preserve queued or deferred edits, then make the fallback stable.\n .orderBy(\n desc(hasPendingLocalWork),\n desc(documents.updatedAt),\n desc(documents.localId),\n )\n .limit(1);\n\n return rows[0]?.localId ?? null;\n}\n\nexport async function deleteDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .delete(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .run();\n });\n}\n"]}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { and, eq, inArray } from "drizzle-orm";
|
|
2
|
+
import { documentHistoryCheckpoints, documentHistoryUpdates, documents, } from "../../../sqlite/schema/index.js";
|
|
3
|
+
// Document rows written inside another subsystem's transaction. Container
|
|
4
|
+
// Contents stores each folder's metadata document in these tables, so it
|
|
5
|
+
// saves, rebinds, and deletes those rows through here.
|
|
6
|
+
/** Inserts or replaces one document row. */
|
|
7
|
+
export async function upsertDocumentRowInTransaction(tx, row) {
|
|
8
|
+
await tx
|
|
9
|
+
.insert(documents)
|
|
10
|
+
.values(row)
|
|
11
|
+
.onConflictDoUpdate({
|
|
12
|
+
target: [documents.appKind, documents.localId],
|
|
13
|
+
set: row,
|
|
14
|
+
})
|
|
15
|
+
.run();
|
|
16
|
+
}
|
|
17
|
+
/** Inserts or replaces one document's history checkpoint. */
|
|
18
|
+
export async function upsertDocumentHistoryCheckpointInTransaction(tx, row) {
|
|
19
|
+
await tx
|
|
20
|
+
.insert(documentHistoryCheckpoints)
|
|
21
|
+
.values(row)
|
|
22
|
+
.onConflictDoUpdate({
|
|
23
|
+
target: [
|
|
24
|
+
documentHistoryCheckpoints.appKind,
|
|
25
|
+
documentHistoryCheckpoints.localId,
|
|
26
|
+
],
|
|
27
|
+
set: row,
|
|
28
|
+
})
|
|
29
|
+
.run();
|
|
30
|
+
}
|
|
31
|
+
/** Deletes the record, checkpoint, and history rows of documents of one kind. */
|
|
32
|
+
export async function deleteDocumentScopeRowsInTransaction(tx, appKind, localIds) {
|
|
33
|
+
const ids = [...localIds];
|
|
34
|
+
await tx
|
|
35
|
+
.delete(documents)
|
|
36
|
+
.where(and(eq(documents.appKind, appKind), inArray(documents.localId, ids)))
|
|
37
|
+
.run();
|
|
38
|
+
await tx
|
|
39
|
+
.delete(documentHistoryCheckpoints)
|
|
40
|
+
.where(and(eq(documentHistoryCheckpoints.appKind, appKind), inArray(documentHistoryCheckpoints.localId, ids)))
|
|
41
|
+
.run();
|
|
42
|
+
await tx
|
|
43
|
+
.delete(documentHistoryUpdates)
|
|
44
|
+
.where(and(eq(documentHistoryUpdates.appKind, appKind), inArray(documentHistoryUpdates.localId, ids)))
|
|
45
|
+
.run();
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Points a document row at a new server document and drops the keys, manifest,
|
|
49
|
+
* and sync position it held for the old one.
|
|
50
|
+
*/
|
|
51
|
+
export async function rebindDocumentRowInTransaction(tx, scope, rebind) {
|
|
52
|
+
await tx
|
|
53
|
+
.update(documents)
|
|
54
|
+
.set({
|
|
55
|
+
accessEpoch: 1,
|
|
56
|
+
accessStateHash: null,
|
|
57
|
+
contentKeyBundle: null,
|
|
58
|
+
documentId: rebind.documentId,
|
|
59
|
+
documentKekTargets: null,
|
|
60
|
+
documentManifestBundle: null,
|
|
61
|
+
lastCommitLsn: null,
|
|
62
|
+
pullContinuation: null,
|
|
63
|
+
updatedAt: rebind.updatedAt,
|
|
64
|
+
})
|
|
65
|
+
.where(and(eq(documents.appKind, scope.appKind), eq(documents.localId, scope.localId)))
|
|
66
|
+
.run();
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=documentRowsInTransaction.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documentRowsInTransaction.js","sourceRoot":"","sources":["documentRowsInTransaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,0BAA0B,EAC1B,sBAAsB,EACtB,SAAS,GACV,MAAM,wBAAwB,CAAC;AAGhC,0EAA0E;AAC1E,yEAAyE;AACzE,uDAAuD;AAEvD,4CAA4C;AAC5C,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,EAAgC,EAChC,GAAkC;IAElC,MAAM,EAAE;SACL,MAAM,CAAC,SAAS,CAAC;SACjB,MAAM,CAAC,GAAG,CAAC;SACX,kBAAkB,CAAC;QAClB,MAAM,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,SAAS,CAAC,OAAO,CAAC;QAC9C,GAAG,EAAE,GAAG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,CAClD,EAAgC,EAChC,KAA6D,EAC7D,MAAmE;IAEnE,MAAM,EAAE;SACL,MAAM,CAAC,SAAS,CAAC;SACjB,GAAG,CAAC;QACH,WAAW,EAAE,CAAC;QACd,eAAe,EAAE,IAAI;QACrB,gBAAgB,EAAE,IAAI;QACtB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,kBAAkB,EAAE,IAAI;QACxB,sBAAsB,EAAE,IAAI;QAC5B,aAAa,EAAE,IAAI;QACnB,gBAAgB,EAAE,IAAI;QACtB,SAAS,EAAE,MAAM,CAAC,SAAS;KAC5B,CAAC;SACD,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CACF;SACA,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, eq, inArray } from \"drizzle-orm\";\nimport {\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documents,\n} from \"../../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\n\n// Document rows written inside another subsystem's transaction. Container\n// Contents stores each folder's metadata document in these tables, so it\n// saves, rebinds, and deletes those rows through here.\n\n/** Inserts or replaces one document row. */\nexport async function upsertDocumentRowInTransaction(\n tx: ClientSQLiteTransactionScope,\n row: typeof documents.$inferInsert,\n): Promise<void> {\n await tx\n .insert(documents)\n .values(row)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: row,\n })\n .run();\n}\n\n/** Inserts or replaces one document's history checkpoint. */\nexport async function upsertDocumentHistoryCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n row: typeof documentHistoryCheckpoints.$inferInsert,\n): Promise<void> {\n await tx\n .insert(documentHistoryCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n documentHistoryCheckpoints.appKind,\n documentHistoryCheckpoints.localId,\n ],\n set: row,\n })\n .run();\n}\n\n/** Deletes the record, checkpoint, and history rows of documents of one kind. */\nexport async function deleteDocumentScopeRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n appKind: string,\n localIds: ReadonlyArray<string>,\n): Promise<void> {\n const ids = [...localIds];\n await tx\n .delete(documents)\n .where(and(eq(documents.appKind, appKind), inArray(documents.localId, ids)))\n .run();\n await tx\n .delete(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, appKind),\n inArray(documentHistoryCheckpoints.localId, ids),\n ),\n )\n .run();\n await tx\n .delete(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, appKind),\n inArray(documentHistoryUpdates.localId, ids),\n ),\n )\n .run();\n}\n\n/**\n * Points a document row at a new server document and drops the keys, manifest,\n * and sync position it held for the old one.\n */\nexport async function rebindDocumentRowInTransaction(\n tx: ClientSQLiteTransactionScope,\n scope: { readonly appKind: string; readonly localId: string },\n rebind: { readonly documentId: string; readonly updatedAt: string },\n): Promise<void> {\n await tx\n .update(documents)\n .set({\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: rebind.documentId,\n documentKekTargets: null,\n documentManifestBundle: null,\n lastCommitLsn: null,\n pullContinuation: null,\n updatedAt: rebind.updatedAt,\n })\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .run();\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type ClientSQLiteTransactionScope } from "
|
|
2
|
-
import { type ExecSql } from "
|
|
1
|
+
import { type ClientSQLiteTransactionScope } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
2
|
+
import { type ExecSql } from "../../../sqlite/sqlSchema.js";
|
|
3
3
|
import type { DocumentScope } from "./documentPersistenceTypes.js";
|
|
4
4
|
interface DocumentSyncFailureFields {
|
|
5
5
|
readonly attemptedAt: string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { and, eq, isNotNull } from "drizzle-orm";
|
|
2
|
-
import { documents, documentTables, localIntents, localIntentTables, } from "
|
|
3
|
-
import { getClientSQLitePersistenceRuntime, } from "
|
|
4
|
-
import { ensureSqlTables } from "
|
|
2
|
+
import { documents, documentTables, localIntents, localIntentTables, } from "../../../sqlite/schema/index.js";
|
|
3
|
+
import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
4
|
+
import { ensureSqlTables } from "../../../sqlite/sqlSchema.js";
|
|
5
5
|
/** The `documents` column values of a scope with no recorded failure. */
|
|
6
6
|
export const CLEARED_DOCUMENT_SYNC_FAILURE = {
|
|
7
7
|
syncFailureAttemptedAt: null,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documentSyncFailurePersistence.js","sourceRoot":"","sources":["documentSyncFailurePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,SAAS,EACT,cAAc,EACd,YAAY,EACZ,iBAAiB,GAClB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAgB,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAS1E,yEAAyE;AACzE,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC3C,sBAAsB,EAAE,IAAI;IAC5B,kBAAkB,EAAE,IAAI;IACxB,iBAAiB,EAAE,IAAI;CACf,CAAC;AAEX,SAAS,UAAU,CAAC,KAAoB;IACtC,OAAO,GAAG,CACR,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB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AAS,CAAC;AAC9B,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,EAAgC,EAChC,KAAoB;IAEpB,MAAM,EAAE;SACL,MAAM,CAAC,SAAS,CAAC;SACjB,GAAG,CAAC,6BAA6B,CAAC;SAClC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;SACxB,GAAG,EAAE,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAgB,EAChB,KAAoB;IAEpB,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC,SAAS,CAAC;aACjB,GAAG,CAAC,6BAA6B,CAAC;aAClC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;aACxB,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, isNotNull } from \"drizzle-orm\";\nimport {\n documents,\n documentTables,\n localIntents,\n localIntentTables,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentScope } from \"./documentPersistenceTypes\";\n\ninterface DocumentSyncFailureFields {\n readonly attemptedAt: string;\n readonly message: string;\n readonly status: number | null;\n}\n\n/** The `documents` column values of a scope with no recorded failure. */\nexport const CLEARED_DOCUMENT_SYNC_FAILURE = {\n syncFailureAttemptedAt: null,\n syncFailureMessage: null,\n syncFailureStatus: null,\n} as const;\n\nfunction scopeWhere(scope: DocumentScope) {\n return and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n );\n}\n\n/**\n * Record the last terminal failure or incoming-update quarantine on a document\n * scope's row. The durable pending-update queue has no status columns, so\n * these columns let the write-queue view explain a blocked document. A newer\n * failure replaces the old. A scope with no `documents` row has nothing left\n * to explain, so the update is a no-op there.\n */\nexport async function recordDocumentSyncFailure(\n execSql: ExecSql,\n scope: DocumentScope,\n failure: DocumentSyncFailureFields,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documents)\n .set({\n syncFailureAttemptedAt: failure.attemptedAt,\n syncFailureMessage: failure.message,\n syncFailureStatus: failure.status,\n })\n .where(scopeWhere(scope))\n .run();\n });\n}\n\n/**\n * Whether any queued local write has recorded a terminal failure — a document\n * row carrying a sync failure or an intent row carrying `last_error`. This is\n * the evidence gate for recovery triggers (e.g. re-arming write lanes when org\n * access is restored): without it a transient denial during bootstrap would\n * fire recovery work with nothing to recover, racing the startup sync passes.\n */\nexport async function hasRecordedTerminalSyncFailures(\n execSql: ExecSql,\n): Promise<boolean> {\n await ensureSqlTables(execSql, [...documentTables, ...localIntentTables]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [failure] = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(isNotNull(documents.syncFailureMessage))\n .limit(1);\n if (failure) {\n return true;\n }\n const [intent] = await db\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(isNotNull(localIntents.lastError))\n .limit(1);\n return intent !== undefined;\n}\n\n/** Clear a scope's recorded failure inside a caller's transaction. */\nexport async function clearDocumentSyncFailureInTransaction(\n tx: ClientSQLiteTransactionScope,\n scope: DocumentScope,\n): Promise<void> {\n await tx\n .update(documents)\n .set(CLEARED_DOCUMENT_SYNC_FAILURE)\n .where(scopeWhere(scope))\n .run();\n}\n\n/**\n * Drop the recorded failure for a scope. Called when a later sync pass for the\n * scope succeeds and whenever the scope's local sync state is torn down, so a\n * stale failure never outlives the condition it describes.\n */\nexport async function clearDocumentSyncFailure(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documents)\n .set(CLEARED_DOCUMENT_SYNC_FAILURE)\n .where(scopeWhere(scope))\n .run();\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type DocumentSyncPullContinuation } from "
|
|
2
|
-
import { type ExecSql } from "
|
|
1
|
+
import { type DocumentSyncPullContinuation } from "../../../documents/shared/sync/pullContinuation.js";
|
|
2
|
+
import { type ExecSql } from "../../../sqlite/sqlSchema.js";
|
|
3
3
|
import type { DocumentRecord } from "./documentPersistenceTypes.js";
|
|
4
4
|
export declare function ensureDocumentTables(execSql: ExecSql): Promise<void>;
|
|
5
5
|
export declare function ensureDocumentProjectionTables(execSql: ExecSql): Promise<void>;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { and, eq, sql } from "drizzle-orm";
|
|
2
|
-
import { DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED, serializeDocumentSyncPullContinuation, } from "
|
|
3
|
-
import { documentProjectionTables, documents, documentTables } from "
|
|
4
|
-
import { getClientSQLitePersistenceRuntime } from "
|
|
5
|
-
import { ensureSqlTables, runSerializedSqlMutation, } from "
|
|
2
|
+
import { DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED, serializeDocumentSyncPullContinuation, } from "../../../documents/shared/sync/pullContinuation.js";
|
|
3
|
+
import { documentProjectionTables, documents, documentTables, } from "../../../sqlite/schema/index.js";
|
|
4
|
+
import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
5
|
+
import { ensureSqlTables, runSerializedSqlMutation, } from "../../../sqlite/sqlSchema.js";
|
|
6
6
|
import { loadDocumentRecord } from "./documentRecordPersistence.js";
|
|
7
7
|
export function ensureDocumentTables(execSql) {
|
|
8
8
|
return ensureSqlTables(execSql, documentTables);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EA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,SAAS,CAAC,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC,EAC1C,EAAE,CAAC,SAAS,CAAC,WAAW,EAAE,KAAK,CAAC,WAAW,CAAC,EAC5C,GAAG,CAAA,GAAG,SAAS,CAAC,eAAe,OAAO,KAAK,CAAC,eAAe,EAAE,EAC7D,GAAG,CAAA,GAAG,SAAS,CAAC,gBAAgB,OAAO,KAAK,CAAC,gBAAgB,EAAE,EAC/D,GAAG,CAAA,GAAG,SAAS,CAAC,kBAAkB,OAAO,KAAK,CAAC,kBAAkB,EAAE,EACnE,GAAG,CAAA,GAAG,SAAS,CAAC,sBAAsB,OAAO,KAAK,CAAC,sBAAsB,EAAE,EAC3E,GAAG,CAAA,GAAG,SAAS,CAAC,aAAa,OAAO,KAAK,CAAC,aAAa,EAAE,EACzD,EAAE,CAAC,SAAS,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CACrD,CACF;aACA,GAAG,EAAE,CAAC;QACT,OAAO,kBAAkB,CAAC,aAAa,EAAE;YACvC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EACL,4BAA4B,EAC5B,uCAAuC,EACvC,0BAA0B,EAC1B,yBAAyB,EACzB,0BAA0B,EAC1B,qCAAqC,EACrC,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,oCAAoC,CAAC;AAO5C,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,wBAAwB,EACxB,+BAA+B,EAC/B,yBAAyB,GAC1B,MAAM,kCAAkC,CAAC","sourcesContent":["import { and, eq, sql } from \"drizzle-orm\";\nimport {\n DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED,\n type DocumentSyncPullContinuation,\n serializeDocumentSyncPullContinuation,\n} from \"../../../documents/shared/sync/pullContinuation\";\nimport {\n documentProjectionTables,\n documents,\n documentTables,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport type { DocumentRecord } from \"./documentPersistenceTypes\";\nimport { loadDocumentRecord } from \"./documentRecordPersistence\";\n\nexport function ensureDocumentTables(execSql: ExecSql): Promise<void> {\n return ensureSqlTables(execSql, documentTables);\n}\n\nexport function ensureDocumentProjectionTables(\n execSql: ExecSql,\n): Promise<void> {\n return ensureSqlTables(execSql, documentProjectionTables);\n}\n\n/** Replace only the exact rejected continuation with a durable recovery marker. */\nexport async function invalidateDocumentSyncPullContinuation(\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n appKind: string;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n): Promise<DocumentRecord | null> {\n await ensureDocumentTables(execSql);\n const expectedContinuation = serializeDocumentSyncPullContinuation(\n input.continuation,\n );\n if (expectedContinuation === null) return null;\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const { db } = getClientSQLitePersistenceRuntime(lockedExecSql);\n await db\n .update(documents)\n .set({ pullContinuation: DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED })\n .where(\n and(\n eq(documents.appKind, input.appKind),\n eq(documents.localId, input.localId),\n eq(documents.documentId, input.documentId),\n eq(documents.accessEpoch, input.accessEpoch),\n sql`${documents.accessStateHash} IS ${input.accessStateHash}`,\n sql`${documents.contentKeyBundle} IS ${input.contentKeyBundle}`,\n sql`${documents.documentKekTargets} IS ${input.documentKekTargets}`,\n sql`${documents.documentManifestBundle} IS ${input.documentManifestBundle}`,\n sql`${documents.lastCommitLsn} IS ${input.lastCommitLsn}`,\n eq(documents.pullContinuation, expectedContinuation),\n ),\n )\n .run();\n return loadDocumentRecord(lockedExecSql, {\n appKind: input.appKind,\n localId: input.localId,\n });\n });\n}\n\nexport {\n enqueueDocumentPendingUpdate,\n enqueueDocumentPendingUpdateWithHistory,\n listDocumentPendingUpdates,\n MAX_PENDING_UPDATE_REKEYS,\n rekeyDocumentPendingUpdate,\n resetDocumentPendingUpdateRekeyBudget,\n settleDocumentPendingUpdate,\n unqueueDocumentPendingUpdates,\n} from \"./documentPendingUpdatePersistence\";\nexport type {\n DocumentRecord,\n DocumentScope,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"./documentPersistenceTypes\";\nexport {\n deleteDocumentRecord,\n documentRecordSelection,\n findLocalIdByDocumentId,\n loadDocumentRecord,\n mapSelectedDocumentRecord,\n} from \"./documentRecordPersistence\";\nexport {\n clearDocumentSyncFailure,\n hasRecordedTerminalSyncFailures,\n recordDocumentSyncFailure,\n} from \"./documentSyncFailurePersistence\";\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { DocumentProjectorRegistryInput, StoredDocumentKind } from "../../documents/documentKinds.js";
|
|
2
2
|
import type { DiscoveredDocumentInput, DocumentSummary } from "../../documents/documentSummary.js";
|
|
3
3
|
import type { DocumentSyncPullContinuation } from "../../documents/shared/sync/pullContinuation.js";
|
|
4
|
-
import type { DocumentRecord as BaseDocumentRecord, PendingUpdateFields, PendingUpdateRecord } from "../../sqlite/documentPersistence/index.js";
|
|
5
4
|
import type { ExecSql } from "../../sqlite/sqlSchema.js";
|
|
6
5
|
import type { DocumentOrphanBlobPersistence } from "./orphanBlobPersistence.js";
|
|
7
|
-
|
|
6
|
+
import type { DocumentRecord as BaseDocumentRecord, PendingUpdateFields, PendingUpdateRecord } from "./records/index.js";
|
|
7
|
+
export type { PendingUpdateRecord } from "./records/index.js";
|
|
8
8
|
export interface StoredDocumentRecord extends BaseDocumentRecord {
|
|
9
9
|
containerId: string | null;
|
|
10
10
|
documentKind?: StoredDocumentKind;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../../sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { DocumentOrphanBlobPersistence } from \"./orphanBlobPersistence\";\n\nexport type { PendingUpdateRecord } from \"../../sqlite/documentPersistence\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence {\n readonly orphanBlobs: DocumentOrphanBlobPersistence;\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<string | null>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows only while the response's security identity survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;\n /**\n * Delete the canonical row and every side row only when its security identity\n * and container placement still match the captured record. The comparison,\n * deletes, and client\n * projection callback must share one write transaction.\n */\n deleteDocumentIfMatches: (\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n /**\n * Delete orphaned side rows only if the canonical document is still absent.\n * The absence check, row cleanup, and client projection callback must share\n * one write transaction so a concurrent create is preserved.\n */\n deleteDocumentSideRowsIfAbsent: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { DocumentOrphanBlobPersistence } from \"./orphanBlobPersistence\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"./records\";\n\nexport type { PendingUpdateRecord } from \"./records\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence {\n readonly orphanBlobs: DocumentOrphanBlobPersistence;\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<string | null>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows only while the response's security identity survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;\n /**\n * Delete the canonical row and every side row only when its security identity\n * and container placement still match the captured record. The comparison,\n * deletes, and client\n * projection callback must share one write transaction.\n */\n deleteDocumentIfMatches: (\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n /**\n * Delete orphaned side rows only if the canonical document is still absent.\n * The absence check, row cleanup, and client projection callback must share\n * one write transaction so a concurrent create is preserved.\n */\n deleteDocumentSideRowsIfAbsent: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
|
|
@@ -7,4 +7,6 @@ export interface DocumentPurgeCheckpoint {
|
|
|
7
7
|
readonly purgeEventHash: string;
|
|
8
8
|
}
|
|
9
9
|
export declare function loadDocumentPurgeCheckpoint(execSql: ExecSql, documentId: string): Promise<DocumentPurgeCheckpoint | null>;
|
|
10
|
+
/** Whether the document was permanently purged, read in the caller's transaction. */
|
|
11
|
+
export declare function hasDocumentPurgeCheckpointInTransaction(tx: ClientSQLiteTransactionScope, documentId: string): Promise<boolean>;
|
|
10
12
|
export declare function storeDocumentPurgeCheckpointInTransaction(tx: ClientSQLiteTransactionScope, checkpoint: DocumentPurgeCheckpoint, updatedAt: string): Promise<void>;
|
|
@@ -17,6 +17,15 @@ export async function loadDocumentPurgeCheckpoint(execSql, documentId) {
|
|
|
17
17
|
.limit(1);
|
|
18
18
|
return row ?? null;
|
|
19
19
|
}
|
|
20
|
+
/** Whether the document was permanently purged, read in the caller's transaction. */
|
|
21
|
+
export async function hasDocumentPurgeCheckpointInTransaction(tx, documentId) {
|
|
22
|
+
const [row] = await tx
|
|
23
|
+
.select({ documentId: documentPurgeCheckpoints.documentId })
|
|
24
|
+
.from(documentPurgeCheckpoints)
|
|
25
|
+
.where(eq(documentPurgeCheckpoints.documentId, documentId))
|
|
26
|
+
.limit(1);
|
|
27
|
+
return row !== undefined;
|
|
28
|
+
}
|
|
20
29
|
export async function storeDocumentPurgeCheckpointInTransaction(tx, checkpoint, updatedAt) {
|
|
21
30
|
const [stored] = await tx
|
|
22
31
|
.select({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentPurgeCheckpointPersistence.js","sourceRoot":"","sources":["documentPurgeCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE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AC;YACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,sEAAsE,CACvE,CAAC;QACJ,CAAC;QACD,OAAO;IACT,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,wBAAwB,CAAC;SAChC,MAAM,CAAC,EAAE,GAAG,UAAU,EAAE,SAAS,EAAE,CAAC;SACpC,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport {\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\nexport interface DocumentPurgeCheckpoint {\n readonly documentId: string;\n readonly documentManifestHash: string;\n readonly organizationId: string;\n readonly purgeEventHash: string;\n}\n\nexport async function loadDocumentPurgeCheckpoint(\n execSql: ExecSql,\n documentId: string,\n): Promise<DocumentPurgeCheckpoint | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const [row] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n documentId: documentPurgeCheckpoints.documentId,\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row ?? null;\n}\n\nexport async function storeDocumentPurgeCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: DocumentPurgeCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const [stored] = await tx\n .select({\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, checkpoint.documentId))\n .limit(1);\n if (stored) {\n if (\n stored.documentManifestHash !== checkpoint.documentManifestHash ||\n stored.organizationId !== checkpoint.organizationId ||\n stored.purgeEventHash !== checkpoint.purgeEventHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Document purge checkpoint conflicts with the verified terminal event\",\n );\n }\n return;\n }\n await tx\n .insert(documentPurgeCheckpoints)\n .values({ ...checkpoint, updatedAt })\n .run();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentPurgeCheckpointPersistence.js","sourceRoot":"","sources":["documentPurgeCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AASvE,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAAgB,EAChB,UAAkB;IAElB,MAAM,eAAe,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;IACvD,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,iCAAiC,CAAC,OAAO,CAAC;SAC3D,EAAE,CAAC,MAAM,CAAC;QACT,UAAU,EAAE,wBAAwB,CAAC,UAAU;QAC/C,oBAAoB,EAAE,wBAAwB,CAAC,oBAAoB;QACnE,cAAc,EAAE,wBAAwB,CAAC,cAAc;QACvD,cAAc,EAAE,wBAAwB,CAAC,cAAc;KACxD,CAAC;SACD,IAAI,CAAC,wBAAwB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,wBAAwB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SAC1D,KAAK,C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AAC;SAChC,MAAM,CAAC,EAAE,GAAG,UAAU,EAAE,SAAS,EAAE,CAAC;SACpC,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport {\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\nexport interface DocumentPurgeCheckpoint {\n readonly documentId: string;\n readonly documentManifestHash: string;\n readonly organizationId: string;\n readonly purgeEventHash: string;\n}\n\nexport async function loadDocumentPurgeCheckpoint(\n execSql: ExecSql,\n documentId: string,\n): Promise<DocumentPurgeCheckpoint | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const [row] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n documentId: documentPurgeCheckpoints.documentId,\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row ?? null;\n}\n\n/** Whether the document was permanently purged, read in the caller's transaction. */\nexport async function hasDocumentPurgeCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<boolean> {\n const [row] = await tx\n .select({ documentId: documentPurgeCheckpoints.documentId })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row !== undefined;\n}\n\nexport async function storeDocumentPurgeCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: DocumentPurgeCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const [stored] = await tx\n .select({\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, checkpoint.documentId))\n .limit(1);\n if (stored) {\n if (\n stored.documentManifestHash !== checkpoint.documentManifestHash ||\n stored.organizationId !== checkpoint.organizationId ||\n stored.purgeEventHash !== checkpoint.purgeEventHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Document purge checkpoint conflicts with the verified terminal event\",\n );\n }\n return;\n }\n await tx\n .insert(documentPurgeCheckpoints)\n .values({ ...checkpoint, updatedAt })\n .run();\n}\n"]}
|
|
@@ -55,6 +55,15 @@ export async function loadStoredPrincipalPolicyCheckpoint(handle, identity) {
|
|
|
55
55
|
}
|
|
56
56
|
: null;
|
|
57
57
|
}
|
|
58
|
+
/** Every principal with a durable policy checkpoint. */
|
|
59
|
+
export function listPrincipalPolicyCheckpointPrincipals(handle) {
|
|
60
|
+
return handle
|
|
61
|
+
.selectDistinct({
|
|
62
|
+
id: principalPolicyCheckpoints.principalId,
|
|
63
|
+
type: principalPolicyCheckpoints.principalType,
|
|
64
|
+
})
|
|
65
|
+
.from(principalPolicyCheckpoints);
|
|
66
|
+
}
|
|
58
67
|
export async function upsertAccessManifestCheckpointInTransaction(tx, checkpoint, updatedAt) {
|
|
59
68
|
const row = { ...checkpoint, updatedAt };
|
|
60
69
|
await tx
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyingCheckpointPersistence.js","sourceRoot":"","sources":["keyingCheckpointPersistence.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAC7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CAAC,CAAC,CAAC,IAAI,CAAC;AACvE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAgB,EAChB,aAAmC,EACnC,WAAmB;IAEnB,MAAM,4BAA4B,CAAC,OAAO,CAAC,CAAC;IAC5C,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,GAAG,GAAG,MAAM,gCAAgC,CAAC,EAAE,EAAE;QACrD,aAAa;QACb,WAAW;KACZ,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7D,CAAC;AACD;;;;GAIG;AACH,MAAM,UAAU,oCAAoC,CAClD,UAAqC,EACrC,IAAuC;IAEvC,IACE,UAAU,CAAC,aAAa,KAAK,IAAI,CAAC,aAAa;QAC/C,UAAU,CAAC,WAAW,KAAK,IAAI,CAAC,WAAW,EAC3C,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,0DAA0D,CAC3D,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC;QACrC,UAAU,CAAC,OAAO,GAAG,CAAC;QACtB,UAAU,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EACjC,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,0CAA0C,CAC3C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccessManifestCheckpoint,\n AccessObjectKind,\n ManagedPrincipalKind,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { and, eq } from \"drizzle-orm\";\nimport {\n accessManifestCheckpoints,\n keyingCheckpointTables,\n principalPolicyCheckpoints,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { recordPrincipalPolicyOrganizationInTransaction } from \"../principalPolicy/principalPolicyOrganizationPersistence\";\n\ntype CheckpointHandle = ClientSQLiteDatabase | ClientSQLiteTransactionScope;\n\ntype AccessManifestCheckpointIdentity = Pick<\n AccessManifestCheckpoint,\n \"objectKind\" | \"organizationId\" | \"objectId\"\n>;\n\ntype PrincipalPolicyCheckpointIdentity = Pick<\n PrincipalPolicyCheckpoint,\n \"principalType\" | \"principalId\"\n>;\n\n/** One key format per checkpoint identity, shared by every batch validator. */\nexport function accessManifestObjectKey(\n identity: AccessManifestCheckpointIdentity,\n): string {\n return JSON.stringify([\n identity.objectKind,\n identity.organizationId,\n identity.objectId,\n ]);\n}\n\nexport function principalPolicyKey(\n identity: PrincipalPolicyCheckpointIdentity,\n): string {\n return JSON.stringify([identity.principalType, identity.principalId]);\n}\n\nasync function loadAccessManifestCheckpointRow(\n handle: CheckpointHandle,\n identity: AccessManifestCheckpointIdentity,\n): Promise<Pick<AccessManifestCheckpoint, \"epoch\" | \"manifestHash\"> | null> {\n const rows = await handle\n .select({\n epoch: accessManifestCheckpoints.epoch,\n manifestHash: accessManifestCheckpoints.manifestHash,\n })\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, identity.objectKind),\n eq(accessManifestCheckpoints.organizationId, identity.organizationId),\n eq(accessManifestCheckpoints.objectId, identity.objectId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\nasync function loadPrincipalPolicyCheckpointRow(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<Pick<PrincipalPolicyCheckpoint, \"version\" | \"stateHash\"> | null> {\n const rows = await handle\n .select({\n version: principalPolicyCheckpoints.version,\n stateHash: principalPolicyCheckpoints.stateHash,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, identity.principalType),\n eq(principalPolicyCheckpoints.principalId, identity.principalId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\n/**\n * A loaded checkpoint row merged back with the identity it was looked up by —\n * the full checkpoint shape every comparison consumes.\n */\nexport async function loadStoredAccessManifestCheckpoint(\n handle: CheckpointHandle,\n checkpoint: AccessManifestCheckpoint,\n): Promise<AccessManifestCheckpoint | null> {\n const row = await loadAccessManifestCheckpointRow(handle, checkpoint);\n return row ? { ...checkpoint, ...row } : null;\n}\n\nexport async function loadStoredPrincipalPolicyCheckpoint(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<PrincipalPolicyCheckpoint | null> {\n const row = await loadPrincipalPolicyCheckpointRow(handle, identity);\n return row\n ? {\n principalType: identity.principalType,\n principalId: identity.principalId,\n ...row,\n }\n : null;\n}\n\nexport async function upsertAccessManifestCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: AccessManifestCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(accessManifestCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n accessManifestCheckpoints.objectKind,\n accessManifestCheckpoints.organizationId,\n accessManifestCheckpoints.objectId,\n ],\n set: row,\n })\n .run();\n}\n\nexport async function upsertPrincipalPolicyCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: PrincipalPolicyCheckpoint,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: checkpoint.principalId,\n principalType: checkpoint.principalType,\n });\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(principalPolicyCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n principalPolicyCheckpoints.principalType,\n principalPolicyCheckpoints.principalId,\n ],\n set: row,\n })\n .run();\n}\n\n// Lazily create the checkpoint tables on first access. Every load/save below\n// calls this, so the tables exist on demand; it is intentionally module-private\n// (no caller outside this file needs it, and exporting it tripped knip).\nasync function ensureKeyingCheckpointTables(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n}\n\nexport async function loadAccessManifestCheckpoint(\n execSql: ExecSql,\n objectKind: AccessObjectKind,\n organizationId: string,\n objectId: string,\n): Promise<AccessManifestCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadAccessManifestCheckpointRow(db, {\n objectKind,\n organizationId,\n objectId,\n });\n\n return row ? { objectKind, objectId, organizationId, ...row } : null;\n}\n\nexport async function loadPrincipalPolicyCheckpoint(\n execSql: ExecSql,\n principalType: ManagedPrincipalKind,\n principalId: string,\n): Promise<PrincipalPolicyCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadPrincipalPolicyCheckpointRow(db, {\n principalType,\n principalId,\n });\n\n return row ? { principalType, principalId, ...row } : null;\n}\n/**\n * The shared shape/ownership guard every checkpoint comparison runs before\n * trusting a durable pin: the pin must belong to the compared principal and\n * carry a well-formed version and hash.\n */\nexport function assertPrincipalPolicyCheckpointShape(\n checkpoint: PrincipalPolicyCheckpoint,\n head: PrincipalPolicyCheckpointIdentity,\n): void {\n if (\n checkpoint.principalType !== head.principalType ||\n checkpoint.principalId !== head.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy checkpoint belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(checkpoint.version) ||\n checkpoint.version < 1 ||\n checkpoint.stateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy checkpoint is malformed\",\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"keyingCheckpointPersistence.js","sourceRoot":"","sources":["keyingCheckpointPersistence.ts"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ACrC,UAAU,CAAC,OAAO,GAAG,CAAC;QACtB,UAAU,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EACjC,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,0CAA0C,CAC3C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccessManifestCheckpoint,\n AccessObjectKind,\n ManagedPrincipalKind,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { and, eq } from \"drizzle-orm\";\nimport {\n accessManifestCheckpoints,\n keyingCheckpointTables,\n principalPolicyCheckpoints,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteDatabase,\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { recordPrincipalPolicyOrganizationInTransaction } from \"../principalPolicy/principalPolicyOrganizationPersistence\";\n\ntype CheckpointHandle = ClientSQLiteDatabase | ClientSQLiteTransactionScope;\n\ntype AccessManifestCheckpointIdentity = Pick<\n AccessManifestCheckpoint,\n \"objectKind\" | \"organizationId\" | \"objectId\"\n>;\n\ntype PrincipalPolicyCheckpointIdentity = Pick<\n PrincipalPolicyCheckpoint,\n \"principalType\" | \"principalId\"\n>;\n\n/** One key format per checkpoint identity, shared by every batch validator. */\nexport function accessManifestObjectKey(\n identity: AccessManifestCheckpointIdentity,\n): string {\n return JSON.stringify([\n identity.objectKind,\n identity.organizationId,\n identity.objectId,\n ]);\n}\n\nexport function principalPolicyKey(\n identity: PrincipalPolicyCheckpointIdentity,\n): string {\n return JSON.stringify([identity.principalType, identity.principalId]);\n}\n\nasync function loadAccessManifestCheckpointRow(\n handle: CheckpointHandle,\n identity: AccessManifestCheckpointIdentity,\n): Promise<Pick<AccessManifestCheckpoint, \"epoch\" | \"manifestHash\"> | null> {\n const rows = await handle\n .select({\n epoch: accessManifestCheckpoints.epoch,\n manifestHash: accessManifestCheckpoints.manifestHash,\n })\n .from(accessManifestCheckpoints)\n .where(\n and(\n eq(accessManifestCheckpoints.objectKind, identity.objectKind),\n eq(accessManifestCheckpoints.organizationId, identity.organizationId),\n eq(accessManifestCheckpoints.objectId, identity.objectId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\nasync function loadPrincipalPolicyCheckpointRow(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<Pick<PrincipalPolicyCheckpoint, \"version\" | \"stateHash\"> | null> {\n const rows = await handle\n .select({\n version: principalPolicyCheckpoints.version,\n stateHash: principalPolicyCheckpoints.stateHash,\n })\n .from(principalPolicyCheckpoints)\n .where(\n and(\n eq(principalPolicyCheckpoints.principalType, identity.principalType),\n eq(principalPolicyCheckpoints.principalId, identity.principalId),\n ),\n )\n .limit(1);\n return rows[0] ?? null;\n}\n\n/**\n * A loaded checkpoint row merged back with the identity it was looked up by —\n * the full checkpoint shape every comparison consumes.\n */\nexport async function loadStoredAccessManifestCheckpoint(\n handle: CheckpointHandle,\n checkpoint: AccessManifestCheckpoint,\n): Promise<AccessManifestCheckpoint | null> {\n const row = await loadAccessManifestCheckpointRow(handle, checkpoint);\n return row ? { ...checkpoint, ...row } : null;\n}\n\nexport async function loadStoredPrincipalPolicyCheckpoint(\n handle: CheckpointHandle,\n identity: PrincipalPolicyCheckpointIdentity,\n): Promise<PrincipalPolicyCheckpoint | null> {\n const row = await loadPrincipalPolicyCheckpointRow(handle, identity);\n return row\n ? {\n principalType: identity.principalType,\n principalId: identity.principalId,\n ...row,\n }\n : null;\n}\n\n/** Every principal with a durable policy checkpoint. */\nexport function listPrincipalPolicyCheckpointPrincipals(\n handle: CheckpointHandle,\n): Promise<{ id: string; type: string }[]> {\n return handle\n .selectDistinct({\n id: principalPolicyCheckpoints.principalId,\n type: principalPolicyCheckpoints.principalType,\n })\n .from(principalPolicyCheckpoints);\n}\n\nexport async function upsertAccessManifestCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: AccessManifestCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(accessManifestCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n accessManifestCheckpoints.objectKind,\n accessManifestCheckpoints.organizationId,\n accessManifestCheckpoints.objectId,\n ],\n set: row,\n })\n .run();\n}\n\nexport async function upsertPrincipalPolicyCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: PrincipalPolicyCheckpoint,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n organizationId,\n principalId: checkpoint.principalId,\n principalType: checkpoint.principalType,\n });\n const row = { ...checkpoint, updatedAt };\n await tx\n .insert(principalPolicyCheckpoints)\n .values(row)\n .onConflictDoUpdate({\n target: [\n principalPolicyCheckpoints.principalType,\n principalPolicyCheckpoints.principalId,\n ],\n set: row,\n })\n .run();\n}\n\n// Lazily create the checkpoint tables on first access. Every load/save below\n// calls this, so the tables exist on demand; it is intentionally module-private\n// (no caller outside this file needs it, and exporting it tripped knip).\nasync function ensureKeyingCheckpointTables(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n}\n\nexport async function loadAccessManifestCheckpoint(\n execSql: ExecSql,\n objectKind: AccessObjectKind,\n organizationId: string,\n objectId: string,\n): Promise<AccessManifestCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadAccessManifestCheckpointRow(db, {\n objectKind,\n organizationId,\n objectId,\n });\n\n return row ? { objectKind, objectId, organizationId, ...row } : null;\n}\n\nexport async function loadPrincipalPolicyCheckpoint(\n execSql: ExecSql,\n principalType: ManagedPrincipalKind,\n principalId: string,\n): Promise<PrincipalPolicyCheckpoint | null> {\n await ensureKeyingCheckpointTables(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const row = await loadPrincipalPolicyCheckpointRow(db, {\n principalType,\n principalId,\n });\n\n return row ? { principalType, principalId, ...row } : null;\n}\n/**\n * The shared shape/ownership guard every checkpoint comparison runs before\n * trusting a durable pin: the pin must belong to the compared principal and\n * carry a well-formed version and hash.\n */\nexport function assertPrincipalPolicyCheckpointShape(\n checkpoint: PrincipalPolicyCheckpoint,\n head: PrincipalPolicyCheckpointIdentity,\n): void {\n if (\n checkpoint.principalType !== head.principalType ||\n checkpoint.principalId !== head.principalId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"principal policy checkpoint belongs to another principal\",\n );\n }\n if (\n !Number.isInteger(checkpoint.version) ||\n checkpoint.version < 1 ||\n checkpoint.stateHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"principal policy checkpoint is malformed\",\n );\n }\n}\n"]}
|