@tearleads/client-sdk 0.1.211 → 0.1.212
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/persistence/container-contents/containerContentsPersistence.js +2 -2
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +2 -2
- package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -6
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
- package/data/persistence/documents/internal/discardDocument.js +4 -4
- package/data/persistence/documents/internal/discardDocument.js.map +1 -1
- package/data/persistence/documents/internal/discoveredDocumentUpsert.js +3 -3
- package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -8
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentMutationPersistence.js +4 -3
- package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentPullContinuationPersistence.js +2 -2
- package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/rowQueryPersistence.js +3 -3
- package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
- package/data/persistence/documents/internal/syncQueuePersistence.js +12 -13
- package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
- package/data/persistence/documents/records/documentHistoryPersistence.d.ts +24 -20
- package/data/persistence/documents/records/documentHistoryPersistence.js +59 -90
- package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -1
- package/data/persistence/documents/records/documentPendingUpdatePersistence.d.ts +10 -25
- package/data/persistence/documents/records/documentPendingUpdatePersistence.js +19 -79
- package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -1
- package/data/persistence/documents/records/documentQueuedUpdateReplacement.d.ts +4 -14
- package/data/persistence/documents/records/documentQueuedUpdateReplacement.js +27 -42
- package/data/persistence/documents/records/documentQueuedUpdateReplacement.js.map +1 -1
- package/data/persistence/documents/records/documentRecordPersistence.d.ts +5 -8
- package/data/persistence/documents/records/documentRecordPersistence.js +2 -55
- package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -1
- package/data/persistence/documents/records/documentRecordRepository.d.ts +133 -0
- package/data/persistence/documents/records/documentRecordRepository.js +286 -0
- package/data/persistence/documents/records/documentRecordRepository.js.map +1 -0
- package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +9 -12
- package/data/persistence/documents/records/documentSyncFailurePersistence.js +19 -34
- package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
- package/data/persistence/documents/records/index.d.ts +4 -19
- package/data/persistence/documents/records/index.js +5 -29
- package/data/persistence/documents/records/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/sync/attachmentUploadFailure.js +2 -2
- package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js +2 -2
- package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +2 -2
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
- package/workflows/container-contents/pendingWrites/index.js +4 -3
- package/workflows/container-contents/pendingWrites/index.js.map +1 -1
- package/workflows/container-contents/recovery/accessRestoration.js +2 -2
- package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
- package/workflows/documents/index.d.ts +1 -1
- package/workflows/documents/index.js +1 -1
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/syncRekeys/syncRecoveryRekey.js +3 -2
- package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
- package/workflows/organizations/readModel/listLocalOrganizations.js +2 -2
- package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
|
@@ -6,7 +6,7 @@ import { documentTables } from "../../sqlite/schema/documentRecordSchema.js";
|
|
|
6
6
|
import { keyingCheckpointTables } from "../../sqlite/schema/keyingCheckpointSchema.js";
|
|
7
7
|
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
8
8
|
import { ensureSqlTables, runOncePerConnection, runSerializedSqlMutation, } from "../../sqlite/sqlSchema.js";
|
|
9
|
-
import {
|
|
9
|
+
import { DocumentRecordRepository } from "../documents/records/index.js";
|
|
10
10
|
import { hasQueuedDocumentUpdates, settleQueuedDocumentUpdatesInTransaction, } from "../documents/records/documentPendingUpdatePersistence.js";
|
|
11
11
|
import { getLatestTimestamp } from "../latestTimestamp.js";
|
|
12
12
|
import { loadContainerById } from "./containerPersistence.js";
|
|
@@ -38,7 +38,7 @@ async function saveStoredContainer(execSql, container, record, options) {
|
|
|
38
38
|
localUpdatedAt,
|
|
39
39
|
});
|
|
40
40
|
if (options && "pendingUpdate" in options) {
|
|
41
|
-
await enqueueDocumentPendingUpdate(
|
|
41
|
+
await new DocumentRecordRepository(lockedExecSql).enqueueDocumentPendingUpdate(getContainerMetadataScope(container.id), options.pendingUpdate);
|
|
42
42
|
}
|
|
43
43
|
return saved;
|
|
44
44
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerContentsPersistence.js","sourceRoot":"","sources":["containerContentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,4BAA4B,EAC5B,UAAU,EACV,eAAe,EACf,iBAAiB,GAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EACL,i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import {\n containerHydrationTombstones,\n containers,\n containerTables,\n localIntentTables,\n} from \"../../sqlite/schema\";\nimport { containerSyncWatermarkTables } from \"../../sqlite/schema/containerSyncWatermarkSchema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n ensureSqlTables,\n runOncePerConnection,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { enqueueDocumentPendingUpdate } from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { getLatestTimestamp } from \"../latestTimestamp\";\nimport { loadContainerById } from \"./containerPersistence\";\nimport {\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n listDormantMetadataSweepRequests,\n} from \"./dormantMetadataSweep\";\n\nexport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n ContainerMoveIntentRecord,\n LocalRootDescendantReparentInput,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nexport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\n\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n SaveContainerOptions,\n SaveContainerWithPendingUpdateOptions,\n} from \"./containerContentsPersistenceTypes\";\nimport { deleteStoredContainers } from \"./containerDeletionPersistence\";\nimport {\n commitStoredHydratedContainer,\n loadStoredHeldContainerBinding,\n} from \"./containerHydrationPersistence\";\nimport { containerIntentPersistence } from \"./containerIntentPersistence\";\nimport {\n commitStoredMetadataMutation,\n settleStoredMetadataPendingUpdates,\n} from \"./containerMetadataMutationPersistence\";\nimport { containerMetadataPullContinuationPersistence } from \"./containerMetadataPullContinuationPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n selectContainersWithMetadataRecords,\n} from \"./containerMetadataRows\";\nimport { abandonStoredMoveIntentRevision } from \"./containerMoveAbandonPersistence\";\nimport { containerPendingUpdatePersistence } from \"./containerPendingUpdatePersistence\";\nimport { rebindStoredHeldContainer } from \"./containerRebindPersistence\";\nimport { containerReconcilePersistence } from \"./containerReconcilePersistence\";\nimport { isSupersededContainerBinding } from \"./supersededContainerBindings\";\n\nasync function saveStoredContainer(\n execSql: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[0],\n container: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[1],\n record: ContainerMetadataRecord | null,\n options?:\n | SaveContainerOptions\n | SaveContainerWithPendingUpdateOptions\n | undefined,\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt =\n options?.localUpdatedAt ?? options?.updatedAt ?? new Date().toISOString();\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const save = async (tx: ClientSQLiteTransactionScope) => {\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: options?.createIntent,\n moveIntent: options?.moveIntent,\n record,\n serverTimestamps: options?.serverTimestamps,\n tx,\n localUpdatedAt,\n });\n if (options && \"pendingUpdate\" in options) {\n await enqueueDocumentPendingUpdate(\n lockedExecSql,\n getContainerMetadataScope(container.id),\n options.pendingUpdate,\n );\n }\n return saved;\n };\n if (!options?.stillCurrent) {\n return runtime.transaction(save);\n }\n const outcome = await runtime.guardedTransaction(\n save,\n options.stillCurrent,\n { behavior: \"immediate\" },\n );\n // Guarded callers recheck the same monotonic generation immediately after\n // this await. Returning the untouched candidate keeps the long-standing\n // non-null save contract while the transaction itself remains rolled back.\n return outcome.result ?? container;\n });\n}\n\nexport const sqlContainerContentsPersistence: ContainerContentsPersistence = {\n ...containerIntentPersistence,\n ...containerMetadataPullContinuationPersistence,\n commitHydratedContainer: commitStoredHydratedContainer,\n commitMetadataMutation: commitStoredMetadataMutation,\n settleAcceptedMetadataPendingUpdates: settleStoredMetadataPendingUpdates,\n listDormantMetadataSweepRequests,\n ...containerPendingUpdatePersistence,\n ...containerReconcilePersistence,\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n async containerExists(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ id: containers.id })\n .from(containers)\n .where(eq(containers.id, containerId))\n .limit(1);\n return rows.length > 0;\n },\n async deleteContainer(execSql, containerId, options) {\n await sqlContainerContentsPersistence.deleteContainers(execSql, [\n {\n containerId,\n reason: options?.reason ?? \"deleted\",\n updatedAt: options?.updatedAt ?? new Date().toISOString(),\n },\n ]);\n },\n async deleteContainers(execSql, removals, options) {\n return deleteStoredContainers(execSql, removals, options);\n },\n async ensureSchema(execSql) {\n // Once ensured on this connection, skip the outer mutation lock entirely:\n // ensureSchema runs on every query path, and re-acquiring the lock just to\n // no-op would queue reads behind unrelated writes.\n await runOncePerConnection(execSql, \"ensure:container-contents\", () =>\n // One ensure, so a cold connection sends three DDL messages in total.\n ensureSqlTables(execSql, [\n ...containerTables,\n ...documentTables,\n ...localIntentTables,\n // Metadata rows consult document purge checkpoints before writing.\n ...keyingCheckpointTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ]),\n );\n },\n async loadHeldContainerBinding(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return loadStoredHeldContainerBinding(execSql, containerId);\n },\n async isSupersededContainerBinding(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return isSupersededContainerBinding(execSql, input);\n },\n async abandonMoveIntentRevision(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return abandonStoredMoveIntentRevision(execSql, input);\n },\n async rebindHeldContainer(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return rebindStoredHeldContainer(execSql, input);\n },\n async loadContainerMetadataRecord(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return selectContainerMetadataRecord(execSql, containerId);\n },\n async loadContainerHydrationTombstones(execSql) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n containerId: containerHydrationTombstones.containerId,\n generation: containerHydrationTombstones.generation,\n reason: containerHydrationTombstones.reason,\n updatedAt: containerHydrationTombstones.updatedAt,\n })\n .from(containerHydrationTombstones)\n .where(eq(containerHydrationTombstones.cleared, false));\n return rows.flatMap((row) =>\n row.reason === \"access_revoked\" || row.reason === \"deleted\"\n ? [{ ...row, reason: row.reason }]\n : [],\n );\n },\n async loadContainers(execSql) {\n return selectContainersWithMetadataRecords(execSql);\n },\n async loadContainerMetadataState(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const container = await loadContainerById(execSql, containerId);\n if (!container) {\n return null;\n }\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n },\n async saveContainer(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerWithPendingUpdate(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerAndDeletePendingUpdates(\n execSql,\n container,\n record,\n pendingUpdateIds,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt = new Date().toISOString();\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const scope = getContainerMetadataScope(container.id);\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n scope,\n pendingUpdateIds,\n );\n const hasRemainingPendingUpdates = await hasQueuedDocumentUpdates(\n tx,\n scope,\n );\n const containerToSave = hasRemainingPendingUpdates\n ? container\n : {\n ...container,\n serverUpdatedAt: getLatestTimestamp(\n container.serverUpdatedAt,\n localUpdatedAt,\n ),\n };\n\n return saveContainerContentsContainerRows({\n container: containerToSave,\n record,\n tx,\n localUpdatedAt,\n });\n },\n );\n });\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"containerContentsPersistence.js","sourceRoot":"","sources":["containerContentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,4BAA4B,EAC5B,UAAU,EACV,eAAe,EACf,iBAAiB,GAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,wBAAwB,EACxB,wCAAwC,GACzC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,gCAAgC,EAChC,mCAAmC,EACnC,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAWhC,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAQzE,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EACL,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,0BAA0B,EAAE,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BACF,MAAM,0BAA0B,GAAG,MAAM,wBAAwB,CAC/D,EAAE,EACF,KAAK,CACN,CAAC;gBACF,MAAM,eAAe,GAAG,0BAA0B;oBAChD,CAAC,CAAC,SAAS;oBACX,CAAC,CAAC;wBACE,GAAG,SAAS;wBACZ,eAAe,EAAE,kBAAkB,CACjC,SAAS,CAAC,eAAe,EACzB,cAAc,CACf;qBACF,CAAC;gBAEN,OAAO,kCAAkC,CAAC;oBACxC,SAAS,EAAE,eAAe;oBAC1B,MAAM;oBACN,EAAE;oBACF,cAAc;iBACf,CAAC,CAAC;YACL,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { eq } from \"drizzle-orm\";\nimport {\n containerHydrationTombstones,\n containers,\n containerTables,\n localIntentTables,\n} from \"../../sqlite/schema\";\nimport { containerSyncWatermarkTables } from \"../../sqlite/schema/containerSyncWatermarkSchema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n ensureSqlTables,\n runOncePerConnection,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { getLatestTimestamp } from \"../latestTimestamp\";\nimport { loadContainerById } from \"./containerPersistence\";\nimport {\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n listDormantMetadataSweepRequests,\n} from \"./dormantMetadataSweep\";\n\nexport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n ContainerMoveIntentRecord,\n LocalRootDescendantReparentInput,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nexport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\n\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n SaveContainerOptions,\n SaveContainerWithPendingUpdateOptions,\n} from \"./containerContentsPersistenceTypes\";\nimport { deleteStoredContainers } from \"./containerDeletionPersistence\";\nimport {\n commitStoredHydratedContainer,\n loadStoredHeldContainerBinding,\n} from \"./containerHydrationPersistence\";\nimport { containerIntentPersistence } from \"./containerIntentPersistence\";\nimport {\n commitStoredMetadataMutation,\n settleStoredMetadataPendingUpdates,\n} from \"./containerMetadataMutationPersistence\";\nimport { containerMetadataPullContinuationPersistence } from \"./containerMetadataPullContinuationPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n selectContainersWithMetadataRecords,\n} from \"./containerMetadataRows\";\nimport { abandonStoredMoveIntentRevision } from \"./containerMoveAbandonPersistence\";\nimport { containerPendingUpdatePersistence } from \"./containerPendingUpdatePersistence\";\nimport { rebindStoredHeldContainer } from \"./containerRebindPersistence\";\nimport { containerReconcilePersistence } from \"./containerReconcilePersistence\";\nimport { isSupersededContainerBinding } from \"./supersededContainerBindings\";\n\nasync function saveStoredContainer(\n execSql: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[0],\n container: Parameters<ContainerContentsPersistence[\"saveContainer\"]>[1],\n record: ContainerMetadataRecord | null,\n options?:\n | SaveContainerOptions\n | SaveContainerWithPendingUpdateOptions\n | undefined,\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt =\n options?.localUpdatedAt ?? options?.updatedAt ?? new Date().toISOString();\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const save = async (tx: ClientSQLiteTransactionScope) => {\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: options?.createIntent,\n moveIntent: options?.moveIntent,\n record,\n serverTimestamps: options?.serverTimestamps,\n tx,\n localUpdatedAt,\n });\n if (options && \"pendingUpdate\" in options) {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).enqueueDocumentPendingUpdate(\n getContainerMetadataScope(container.id),\n options.pendingUpdate,\n );\n }\n return saved;\n };\n if (!options?.stillCurrent) {\n return runtime.transaction(save);\n }\n const outcome = await runtime.guardedTransaction(\n save,\n options.stillCurrent,\n { behavior: \"immediate\" },\n );\n // Guarded callers recheck the same monotonic generation immediately after\n // this await. Returning the untouched candidate keeps the long-standing\n // non-null save contract while the transaction itself remains rolled back.\n return outcome.result ?? container;\n });\n}\n\nexport const sqlContainerContentsPersistence: ContainerContentsPersistence = {\n ...containerIntentPersistence,\n ...containerMetadataPullContinuationPersistence,\n commitHydratedContainer: commitStoredHydratedContainer,\n commitMetadataMutation: commitStoredMetadataMutation,\n settleAcceptedMetadataPendingUpdates: settleStoredMetadataPendingUpdates,\n listDormantMetadataSweepRequests,\n ...containerPendingUpdatePersistence,\n ...containerReconcilePersistence,\n claimDormantMetadataSweepAttempt,\n completeDormantMetadataSweepRequest,\n async containerExists(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ id: containers.id })\n .from(containers)\n .where(eq(containers.id, containerId))\n .limit(1);\n return rows.length > 0;\n },\n async deleteContainer(execSql, containerId, options) {\n await sqlContainerContentsPersistence.deleteContainers(execSql, [\n {\n containerId,\n reason: options?.reason ?? \"deleted\",\n updatedAt: options?.updatedAt ?? new Date().toISOString(),\n },\n ]);\n },\n async deleteContainers(execSql, removals, options) {\n return deleteStoredContainers(execSql, removals, options);\n },\n async ensureSchema(execSql) {\n // Once ensured on this connection, skip the outer mutation lock entirely:\n // ensureSchema runs on every query path, and re-acquiring the lock just to\n // no-op would queue reads behind unrelated writes.\n await runOncePerConnection(execSql, \"ensure:container-contents\", () =>\n // One ensure, so a cold connection sends three DDL messages in total.\n ensureSqlTables(execSql, [\n ...containerTables,\n ...documentTables,\n ...localIntentTables,\n // Metadata rows consult document purge checkpoints before writing.\n ...keyingCheckpointTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ]),\n );\n },\n async loadHeldContainerBinding(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return loadStoredHeldContainerBinding(execSql, containerId);\n },\n async isSupersededContainerBinding(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return isSupersededContainerBinding(execSql, input);\n },\n async abandonMoveIntentRevision(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return abandonStoredMoveIntentRevision(execSql, input);\n },\n async rebindHeldContainer(execSql, input) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return rebindStoredHeldContainer(execSql, input);\n },\n async loadContainerMetadataRecord(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n return selectContainerMetadataRecord(execSql, containerId);\n },\n async loadContainerHydrationTombstones(execSql) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n containerId: containerHydrationTombstones.containerId,\n generation: containerHydrationTombstones.generation,\n reason: containerHydrationTombstones.reason,\n updatedAt: containerHydrationTombstones.updatedAt,\n })\n .from(containerHydrationTombstones)\n .where(eq(containerHydrationTombstones.cleared, false));\n return rows.flatMap((row) =>\n row.reason === \"access_revoked\" || row.reason === \"deleted\"\n ? [{ ...row, reason: row.reason }]\n : [],\n );\n },\n async loadContainers(execSql) {\n return selectContainersWithMetadataRecords(execSql);\n },\n async loadContainerMetadataState(execSql, containerId) {\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const container = await loadContainerById(execSql, containerId);\n if (!container) {\n return null;\n }\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n },\n async saveContainer(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerWithPendingUpdate(execSql, container, record, options) {\n return saveStoredContainer(execSql, container, record, options);\n },\n async saveContainerAndDeletePendingUpdates(\n execSql,\n container,\n record,\n pendingUpdateIds,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const localUpdatedAt = new Date().toISOString();\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const scope = getContainerMetadataScope(container.id);\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n scope,\n pendingUpdateIds,\n );\n const hasRemainingPendingUpdates = await hasQueuedDocumentUpdates(\n tx,\n scope,\n );\n const containerToSave = hasRemainingPendingUpdates\n ? container\n : {\n ...container,\n serverUpdatedAt: getLatestTimestamp(\n container.serverUpdatedAt,\n localUpdatedAt,\n ),\n };\n\n return saveContainerContentsContainerRows({\n container: containerToSave,\n record,\n tx,\n localUpdatedAt,\n });\n },\n );\n });\n },\n};\n"]}
|
|
@@ -3,7 +3,7 @@ import { documentSyncPullContinuationsEqual } from "../../documents/shared/sync/
|
|
|
3
3
|
import { inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, } from "../../sqlite/schema/index.js";
|
|
4
4
|
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
5
5
|
import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
|
|
6
|
-
import {
|
|
6
|
+
import { DocumentRecordRepository, } from "../documents/records/index.js";
|
|
7
7
|
import { hasQueuedDocumentUpdates, settleQueuedDocumentUpdatesInTransaction, } from "../documents/records/documentPendingUpdatePersistence.js";
|
|
8
8
|
import { clearDocumentSyncFailureInTransaction } from "../documents/records/documentSyncFailurePersistence.js";
|
|
9
9
|
import { resetAccessDiscovery } from "./containerAccessDiscovery.js";
|
|
@@ -92,7 +92,7 @@ async function hasPendingStructuralIntent(tx, containerId) {
|
|
|
92
92
|
async function enqueuePendingUpdate(execSql, containerId, pendingUpdate) {
|
|
93
93
|
if (!pendingUpdate)
|
|
94
94
|
return;
|
|
95
|
-
await enqueueDocumentPendingUpdate(
|
|
95
|
+
await new DocumentRecordRepository(execSql).enqueueDocumentPendingUpdate(getContainerMetadataScope(containerId), pendingUpdate);
|
|
96
96
|
}
|
|
97
97
|
function staleServerMutationResult(currentState, input) {
|
|
98
98
|
const incomingServerUpdatedAt = input.saveOptions?.serverTimestamps?.updatedAt;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerMetadataMutationPersistence.js","sourceRoot":"","sources":["containerMetadataMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,8CAA8C,CAAC;AAClG,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EACL,4BAA4B,GAE7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,wBAAwB,EACxB,wCAAwC,GACzC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,qDAAqD,CAAC;AAC5G,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAM5B,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AACxF,OAAO,EACL,oCAAoC,EACpC,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,kCAAkC,EAClC,6BAA6B,GAC9B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEL,iBAAiB,GAClB,MAAM,wB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,CAAC,MAAM,EAAE,CAAC;YACxC,OAAO,OAAO,CAAC,MAAM,CAAC;QACxB,CAAC;QACD,OAAO;YACL,SAAS,EAAE,KAAc;YACzB,YAAY,EAAE,MAAM,wBAAwB,CAC1C,aAAa,EACb,KAAK,CAAC,SAAS,CAAC,EAAE,CACnB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAEI,EACJ,KAEI;IAEJ,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC/D,MAAM,OAAO,GAAG,MAAM,iCAAiC,CACrD,aAAa,CACd,CAAC,kBAAkB,CAClB,KAAK,EAAE,EAAE,EAAE,EAAE;YACX,MAAM,YAAY,GAAG,MAAM,wBAAwB,CACjD,aAAa,EACb,KAAK,CAAC,WAAW,CAClB,CAAC;YACF,IACE,YAAY,EAAE,MAAM;gBACpB,4BAA4B,CAC1B,YAAY,CAAC,MAAM,EACnB,KAAK,CAAC,cAAc,CACrB,EACD,CAAC;gBACD,MAAM,4BAA4B,CAChC,EAAE,EACF,KAAK,CAAC,WAAW,EACjB,KAAK,CAAC,gBAAgB,CACvB,CAAC;YACJ,CAAC;YACD,OAAO,YAAY,CAAC;QACtB,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,EAAE,EACjD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IACnD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport { documentSyncPullContinuationsEqual } from \"../../documents/shared/sync/pullContinuation\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n enqueueDocumentPendingUpdate,\n type PendingUpdateFields,\n} from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { clearDocumentSyncFailureInTransaction } from \"../documents/records/documentSyncFailurePersistence\";\nimport { resetAccessDiscovery } from \"./containerAccessDiscovery\";\nimport {\n assertHeldContainerBinding,\n heldContainerBinding,\n} from \"./containerBinding\";\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\nimport {\n ContainerCreateIntentSupersededError,\n deleteContainerMoveIntentRevision,\n} from \"./containerIntentPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n} from \"./containerMetadataRows\";\nimport {\n type ContainerRecord,\n loadContainerById,\n} from \"./containerPersistence\";\nimport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\nimport { assertPrimaryDocumentSelection } from \"./linkedDocumentSummary\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nfunction committedMetadataMutationResult(input: {\n container: ContainerRecord;\n createIntentSettled: boolean;\n moveIntentSettled: boolean;\n}) {\n return {\n committed: true as const,\n container: input.container,\n ...(input.createIntentSettled\n ? { createIntentSettled: true as const }\n : {}),\n ...(input.moveIntentSettled ? { moveIntentSettled: true as const } : {}),\n };\n}\n\nfunction sameMetadataSecurityIdentity(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableValue(current.accessStateHash, expected.accessStateHash) &&\n sameNullableValue(current.contentKeyBundle, expected.contentKeyBundle) &&\n sameNullableValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n )\n );\n}\n\nfunction sameMetadataRecord(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n sameMetadataSecurityIdentity(current, expected) &&\n sameNullableValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.metadataUpdates === expected.metadataUpdates &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired)\n );\n}\n\nfunction sameContainerRecord(\n current: ContainerRecord,\n expected: ContainerRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.parentId === expected.parentId &&\n current.organizationId === expected.organizationId &&\n current.metadataDocumentId === expected.metadataDocumentId &&\n (current.systemSlot ?? null) === (expected.systemSlot ?? null) &&\n (current.effectiveAccessLevel ?? null) ===\n (expected.effectiveAccessLevel ?? null) &&\n (current.localUpdatedAt ?? null) === (expected.localUpdatedAt ?? null) &&\n (current.serverCreatedAt ?? null) === (expected.serverCreatedAt ?? null) &&\n (current.serverUpdatedAt ?? null) === (expected.serverUpdatedAt ?? null) &&\n current.name === expected.name &&\n (current.icon ?? null) === (expected.icon ?? null)\n );\n}\n\nasync function loadStoredContainerState(\n execSql: Parameters<\n ContainerContentsPersistence[\"loadContainerMetadataState\"]\n >[0],\n containerId: string,\n): Promise<StoredContainerState | null> {\n const container = await loadContainerById(execSql, containerId);\n if (!container) return null;\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getContainerMetadataScope(containerId),\n ids,\n );\n}\n\nfunction clearMetadataSyncFailure(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<void> {\n return clearDocumentSyncFailureInTransaction(tx, {\n appKind: CONTAINER_METADATA_APP_KIND,\n localId: containerId,\n });\n}\n\nasync function hasPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n return hasQueuedDocumentUpdates(tx, getContainerMetadataScope(containerId));\n}\n\nasync function hasPendingStructuralIntent(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n // A pending create or any surviving (unsynced) move of this container.\n const structural = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n eq(localIntents.subjectId, containerId),\n or(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n ),\n ),\n )\n .limit(1);\n return structural.length > 0;\n}\n\nasync function enqueuePendingUpdate(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n containerId: string,\n pendingUpdate: PendingUpdateFields | undefined,\n): Promise<void> {\n if (!pendingUpdate) return;\n await enqueueDocumentPendingUpdate(\n execSql,\n getContainerMetadataScope(containerId),\n pendingUpdate,\n );\n}\n\ntype CommitMetadataMutationInput = Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n>[1];\n\nfunction staleServerMutationResult(\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n) {\n const incomingServerUpdatedAt =\n input.saveOptions?.serverTimestamps?.updatedAt;\n const hasOlderContainerTimestamp =\n incomingServerUpdatedAt != null &&\n currentState?.container.serverUpdatedAt != null &&\n currentState.container.serverUpdatedAt > incomingServerUpdatedAt;\n const hasOlderMetadataAccessEpoch =\n currentState?.record != null &&\n currentState.record.documentId === input.record.documentId &&\n currentState.record.accessEpoch > input.record.accessEpoch;\n return currentState?.record &&\n (hasOlderContainerTimestamp || hasOlderMetadataAccessEpoch)\n ? {\n committed: false as const,\n currentState,\n staleServerState: true as const,\n }\n : null;\n}\n\nfunction metadataMutationStateMatches(\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n): currentState is StoredContainerState & {\n record: ContainerMetadataRecord;\n} {\n return Boolean(\n currentState?.record &&\n sameContainerRecord(currentState.container, input.expectedContainer) &&\n sameMetadataRecord(currentState.record, input.expectedRecord),\n );\n}\n\nasync function rejectMetadataMutationConflict(input: {\n currentState: StoredContainerState | null;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { currentState, mutation, tx } = input;\n if (\n currentState?.record &&\n mutation.settleAcceptedPendingOnConflict &&\n sameMetadataSecurityIdentity(currentState.record, mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.container.id,\n mutation.acceptedPendingUpdateIds,\n );\n }\n return { committed: false as const, currentState };\n}\n\nasync function prepareContainerMutationWrite(input: {\n currentContainer: ContainerRecord;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}): Promise<{ container: ContainerRecord; localUpdatedAt: string }> {\n const { currentContainer, mutation, tx } = input;\n const requestedLocalUpdatedAt =\n mutation.saveOptions?.localUpdatedAt ??\n mutation.saveOptions?.updatedAt ??\n new Date().toISOString();\n // Nothing below writes local intents, so one read answers both checks.\n let pendingStructuralIntent: boolean | undefined;\n const hasStructuralIntent = async () => {\n pendingStructuralIntent ??= await hasPendingStructuralIntent(\n tx,\n mutation.container.id,\n );\n return pendingStructuralIntent;\n };\n const preserveDurableStructure =\n mutation.preserveDurableStructureWhenPending === true &&\n (await hasStructuralIntent());\n // Syncing metadata is not a local edit. Preserve the durable edit clock,\n // including an edit another pane made while this request was in flight.\n const localUpdatedAt =\n preserveDurableStructure || mutation.settleAcceptedPendingOnConflict\n ? (currentContainer.localUpdatedAt ?? requestedLocalUpdatedAt)\n : requestedLocalUpdatedAt;\n const structurallyRebasedContainer = preserveDurableStructure\n ? { ...mutation.container, parentId: currentContainer.parentId }\n : mutation.container;\n const didSettleOutgoing =\n mutation.acceptedPendingUpdateIds.length > 0 &&\n !(await hasPendingUpdates(tx, mutation.container.id)) &&\n !(await hasStructuralIntent());\n // Only container responses establish the server's structural clock. A\n // metadata acknowledgement supplies no such timestamp; marking it with our\n // wall clock would make later valid listings appear stale forever.\n return {\n container: structurallyRebasedContainer,\n localUpdatedAt: didSettleOutgoing\n ? (currentContainer.serverUpdatedAt ?? localUpdatedAt)\n : localUpdatedAt,\n };\n}\n\n/** Server acknowledgements and listings cannot rebind a held folder. */\nfunction assertMutationKeepsHeldBinding(\n currentState: StoredContainerState & { record: ContainerMetadataRecord },\n input: CommitMetadataMutationInput,\n): void {\n const recordDocumentIds =\n input.record.documentId === currentState.record.documentId\n ? []\n : [input.record.documentId];\n assertHeldContainerBinding(heldContainerBinding(currentState), {\n organizationId: input.container.organizationId,\n metadataDocumentIds: [\n input.container.metadataDocumentId,\n ...recordDocumentIds,\n ],\n });\n}\n\nasync function settleMetadataStructuralIntents(\n tx: ClientSQLiteTransactionScope,\n input: CommitMetadataMutationInput,\n): Promise<void> {\n if (\n input.createIntentSettlement &&\n (await settleContainerCreateIntentRevision({\n ...input.createIntentSettlement,\n tx,\n })) === \"superseded\"\n ) {\n throw new ContainerCreateIntentSupersededError();\n }\n if (\n input.moveIntentSettlement &&\n !(await deleteContainerMoveIntentRevision({\n ...input.moveIntentSettlement,\n tx,\n }))\n ) {\n throw new Error(\n \"Container move intent was superseded before local settlement\",\n );\n }\n}\n\nexport async function commitStoredMetadataMutation(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n input: Parameters<ContainerContentsPersistence[\"commitMetadataMutation\"]>[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n );\n const staleServerResult = staleServerMutationResult(\n currentState,\n input,\n );\n if (staleServerResult) return staleServerResult;\n if (!metadataMutationStateMatches(currentState, input)) {\n return rejectMetadataMutationConflict({\n currentState,\n mutation: input,\n tx,\n });\n }\n assertMutationKeepsHeldBinding(currentState, input);\n await assertPrimaryDocumentSelection(\n lockedExecSql,\n currentState.container,\n input.primaryDocumentId,\n );\n\n await enqueuePendingUpdate(\n lockedExecSql,\n input.container.id,\n input.pendingUpdate,\n );\n await deleteAcceptedPendingUpdates(\n tx,\n input.container.id,\n input.acceptedPendingUpdateIds,\n );\n if (input.clearSyncFailure) {\n await clearMetadataSyncFailure(tx, input.container.id);\n }\n const { container, localUpdatedAt } =\n await prepareContainerMutationWrite({\n currentContainer: currentState.container,\n mutation: input,\n tx,\n });\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: input.saveOptions?.createIntent,\n localUpdatedAt,\n moveIntent: input.saveOptions?.moveIntent,\n record: input.record,\n serverTimestamps: input.saveOptions?.serverTimestamps,\n tx,\n });\n await resetAccessDiscovery(tx, currentState.container, saved);\n await settleMetadataStructuralIntents(tx, input);\n return committedMetadataMutationResult({\n container: saved,\n createIntentSettled: input.createIntentSettlement !== undefined,\n moveIntentSettled: input.moveIntentSettlement !== undefined,\n });\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentState: await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n ),\n };\n });\n}\n\nexport async function settleStoredMetadataPendingUpdates(\n execSql: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[0],\n input: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.containerId,\n );\n if (\n currentState?.record &&\n sameMetadataSecurityIdentity(\n currentState.record,\n input.expectedRecord,\n )\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.containerId,\n input.pendingUpdateIds,\n );\n }\n return currentState;\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n return outcome.committed ? outcome.result : null;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerMetadataMutationPersistence.js","sourceRoot":"","sources":["containerMetadataMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,8CAA8C,CAAC;AAClG,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EACL,wBAAwB,GAEzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,wBAAwB,EACxB,wCAAwC,GACzC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,qDAAqD,CAAC;AAC5G,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAM5B,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AACxF,OAAO,EACL,oCAAoC,EACpC,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,kCAAkC,EAClC,6BAA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"../../documents/shared/sync/pullContinuation\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n DocumentRecordRepository,\n type PendingUpdateFields,\n} from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { clearDocumentSyncFailureInTransaction } from \"../documents/records/documentSyncFailurePersistence\";\nimport { resetAccessDiscovery } from \"./containerAccessDiscovery\";\nimport {\n assertHeldContainerBinding,\n heldContainerBinding,\n} from \"./containerBinding\";\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\nimport {\n ContainerCreateIntentSupersededError,\n deleteContainerMoveIntentRevision,\n} from \"./containerIntentPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n} from \"./containerMetadataRows\";\nimport {\n type ContainerRecord,\n loadContainerById,\n} from \"./containerPersistence\";\nimport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\nimport { assertPrimaryDocumentSelection } from \"./linkedDocumentSummary\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nfunction committedMetadataMutationResult(input: {\n container: ContainerRecord;\n createIntentSettled: boolean;\n moveIntentSettled: boolean;\n}) {\n return {\n committed: true as const,\n container: input.container,\n ...(input.createIntentSettled\n ? { createIntentSettled: true as const }\n : {}),\n ...(input.moveIntentSettled ? { moveIntentSettled: true as const } : {}),\n };\n}\n\nfunction sameMetadataSecurityIdentity(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableValue(current.accessStateHash, expected.accessStateHash) &&\n sameNullableValue(current.contentKeyBundle, expected.contentKeyBundle) &&\n sameNullableValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n )\n );\n}\n\nfunction sameMetadataRecord(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n sameMetadataSecurityIdentity(current, expected) &&\n sameNullableValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.metadataUpdates === expected.metadataUpdates &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired)\n );\n}\n\nfunction sameContainerRecord(\n current: ContainerRecord,\n expected: ContainerRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.parentId === expected.parentId &&\n current.organizationId === expected.organizationId &&\n current.metadataDocumentId === expected.metadataDocumentId &&\n (current.systemSlot ?? null) === (expected.systemSlot ?? null) &&\n (current.effectiveAccessLevel ?? null) ===\n (expected.effectiveAccessLevel ?? null) &&\n (current.localUpdatedAt ?? null) === (expected.localUpdatedAt ?? null) &&\n (current.serverCreatedAt ?? null) === (expected.serverCreatedAt ?? null) &&\n (current.serverUpdatedAt ?? null) === (expected.serverUpdatedAt ?? null) &&\n current.name === expected.name &&\n (current.icon ?? null) === (expected.icon ?? null)\n );\n}\n\nasync function loadStoredContainerState(\n execSql: Parameters<\n ContainerContentsPersistence[\"loadContainerMetadataState\"]\n >[0],\n containerId: string,\n): Promise<StoredContainerState | null> {\n const container = await loadContainerById(execSql, containerId);\n if (!container) return null;\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getContainerMetadataScope(containerId),\n ids,\n );\n}\n\nfunction clearMetadataSyncFailure(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<void> {\n return clearDocumentSyncFailureInTransaction(tx, {\n appKind: CONTAINER_METADATA_APP_KIND,\n localId: containerId,\n });\n}\n\nasync function hasPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n return hasQueuedDocumentUpdates(tx, getContainerMetadataScope(containerId));\n}\n\nasync function hasPendingStructuralIntent(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n // A pending create or any surviving (unsynced) move of this container.\n const structural = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n eq(localIntents.subjectId, containerId),\n or(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n ),\n ),\n )\n .limit(1);\n return structural.length > 0;\n}\n\nasync function enqueuePendingUpdate(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n containerId: string,\n pendingUpdate: PendingUpdateFields | undefined,\n): Promise<void> {\n if (!pendingUpdate) return;\n await new DocumentRecordRepository(execSql).enqueueDocumentPendingUpdate(\n getContainerMetadataScope(containerId),\n pendingUpdate,\n );\n}\n\ntype CommitMetadataMutationInput = Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n>[1];\n\nfunction staleServerMutationResult(\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n) {\n const incomingServerUpdatedAt =\n input.saveOptions?.serverTimestamps?.updatedAt;\n const hasOlderContainerTimestamp =\n incomingServerUpdatedAt != null &&\n currentState?.container.serverUpdatedAt != null &&\n currentState.container.serverUpdatedAt > incomingServerUpdatedAt;\n const hasOlderMetadataAccessEpoch =\n currentState?.record != null &&\n currentState.record.documentId === input.record.documentId &&\n currentState.record.accessEpoch > input.record.accessEpoch;\n return currentState?.record &&\n (hasOlderContainerTimestamp || hasOlderMetadataAccessEpoch)\n ? {\n committed: false as const,\n currentState,\n staleServerState: true as const,\n }\n : null;\n}\n\nfunction metadataMutationStateMatches(\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n): currentState is StoredContainerState & {\n record: ContainerMetadataRecord;\n} {\n return Boolean(\n currentState?.record &&\n sameContainerRecord(currentState.container, input.expectedContainer) &&\n sameMetadataRecord(currentState.record, input.expectedRecord),\n );\n}\n\nasync function rejectMetadataMutationConflict(input: {\n currentState: StoredContainerState | null;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { currentState, mutation, tx } = input;\n if (\n currentState?.record &&\n mutation.settleAcceptedPendingOnConflict &&\n sameMetadataSecurityIdentity(currentState.record, mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.container.id,\n mutation.acceptedPendingUpdateIds,\n );\n }\n return { committed: false as const, currentState };\n}\n\nasync function prepareContainerMutationWrite(input: {\n currentContainer: ContainerRecord;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}): Promise<{ container: ContainerRecord; localUpdatedAt: string }> {\n const { currentContainer, mutation, tx } = input;\n const requestedLocalUpdatedAt =\n mutation.saveOptions?.localUpdatedAt ??\n mutation.saveOptions?.updatedAt ??\n new Date().toISOString();\n // Nothing below writes local intents, so one read answers both checks.\n let pendingStructuralIntent: boolean | undefined;\n const hasStructuralIntent = async () => {\n pendingStructuralIntent ??= await hasPendingStructuralIntent(\n tx,\n mutation.container.id,\n );\n return pendingStructuralIntent;\n };\n const preserveDurableStructure =\n mutation.preserveDurableStructureWhenPending === true &&\n (await hasStructuralIntent());\n // Syncing metadata is not a local edit. Preserve the durable edit clock,\n // including an edit another pane made while this request was in flight.\n const localUpdatedAt =\n preserveDurableStructure || mutation.settleAcceptedPendingOnConflict\n ? (currentContainer.localUpdatedAt ?? requestedLocalUpdatedAt)\n : requestedLocalUpdatedAt;\n const structurallyRebasedContainer = preserveDurableStructure\n ? { ...mutation.container, parentId: currentContainer.parentId }\n : mutation.container;\n const didSettleOutgoing =\n mutation.acceptedPendingUpdateIds.length > 0 &&\n !(await hasPendingUpdates(tx, mutation.container.id)) &&\n !(await hasStructuralIntent());\n // Only container responses establish the server's structural clock. A\n // metadata acknowledgement supplies no such timestamp; marking it with our\n // wall clock would make later valid listings appear stale forever.\n return {\n container: structurallyRebasedContainer,\n localUpdatedAt: didSettleOutgoing\n ? (currentContainer.serverUpdatedAt ?? localUpdatedAt)\n : localUpdatedAt,\n };\n}\n\n/** Server acknowledgements and listings cannot rebind a held folder. */\nfunction assertMutationKeepsHeldBinding(\n currentState: StoredContainerState & { record: ContainerMetadataRecord },\n input: CommitMetadataMutationInput,\n): void {\n const recordDocumentIds =\n input.record.documentId === currentState.record.documentId\n ? []\n : [input.record.documentId];\n assertHeldContainerBinding(heldContainerBinding(currentState), {\n organizationId: input.container.organizationId,\n metadataDocumentIds: [\n input.container.metadataDocumentId,\n ...recordDocumentIds,\n ],\n });\n}\n\nasync function settleMetadataStructuralIntents(\n tx: ClientSQLiteTransactionScope,\n input: CommitMetadataMutationInput,\n): Promise<void> {\n if (\n input.createIntentSettlement &&\n (await settleContainerCreateIntentRevision({\n ...input.createIntentSettlement,\n tx,\n })) === \"superseded\"\n ) {\n throw new ContainerCreateIntentSupersededError();\n }\n if (\n input.moveIntentSettlement &&\n !(await deleteContainerMoveIntentRevision({\n ...input.moveIntentSettlement,\n tx,\n }))\n ) {\n throw new Error(\n \"Container move intent was superseded before local settlement\",\n );\n }\n}\n\nexport async function commitStoredMetadataMutation(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n input: Parameters<ContainerContentsPersistence[\"commitMetadataMutation\"]>[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n );\n const staleServerResult = staleServerMutationResult(\n currentState,\n input,\n );\n if (staleServerResult) return staleServerResult;\n if (!metadataMutationStateMatches(currentState, input)) {\n return rejectMetadataMutationConflict({\n currentState,\n mutation: input,\n tx,\n });\n }\n assertMutationKeepsHeldBinding(currentState, input);\n await assertPrimaryDocumentSelection(\n lockedExecSql,\n currentState.container,\n input.primaryDocumentId,\n );\n\n await enqueuePendingUpdate(\n lockedExecSql,\n input.container.id,\n input.pendingUpdate,\n );\n await deleteAcceptedPendingUpdates(\n tx,\n input.container.id,\n input.acceptedPendingUpdateIds,\n );\n if (input.clearSyncFailure) {\n await clearMetadataSyncFailure(tx, input.container.id);\n }\n const { container, localUpdatedAt } =\n await prepareContainerMutationWrite({\n currentContainer: currentState.container,\n mutation: input,\n tx,\n });\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: input.saveOptions?.createIntent,\n localUpdatedAt,\n moveIntent: input.saveOptions?.moveIntent,\n record: input.record,\n serverTimestamps: input.saveOptions?.serverTimestamps,\n tx,\n });\n await resetAccessDiscovery(tx, currentState.container, saved);\n await settleMetadataStructuralIntents(tx, input);\n return committedMetadataMutationResult({\n container: saved,\n createIntentSettled: input.createIntentSettlement !== undefined,\n moveIntentSettled: input.moveIntentSettlement !== undefined,\n });\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentState: await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n ),\n };\n });\n}\n\nexport async function settleStoredMetadataPendingUpdates(\n execSql: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[0],\n input: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.containerId,\n );\n if (\n currentState?.record &&\n sameMetadataSecurityIdentity(\n currentState.record,\n input.expectedRecord,\n )\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.containerId,\n input.pendingUpdateIds,\n );\n }\n return currentState;\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n return outcome.committed ? outcome.result : null;\n });\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
2
2
|
import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
|
|
3
|
-
import {
|
|
3
|
+
import { DocumentRecordRepository } from "../documents/records/index.js";
|
|
4
4
|
import { selectContainerMetadataRecord } from "./containerMetadataRows.js";
|
|
5
5
|
import { CONTAINER_METADATA_APP_KIND } from "./dormantContainerMetadata.js";
|
|
6
6
|
export const containerMetadataPullContinuationPersistence = {
|
|
@@ -8,7 +8,7 @@ export const containerMetadataPullContinuationPersistence = {
|
|
|
8
8
|
return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
9
9
|
const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);
|
|
10
10
|
const invalidate = async () => {
|
|
11
|
-
await invalidateDocumentSyncPullContinuation(
|
|
11
|
+
await new DocumentRecordRepository(lockedExecSql).invalidateDocumentSyncPullContinuation({
|
|
12
12
|
accessEpoch: input.accessEpoch,
|
|
13
13
|
accessStateHash: input.accessStateHash,
|
|
14
14
|
appKind: CONTAINER_METADATA_APP_KIND,
|
package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerMetadataPullContinuationPersistence.js","sourceRoot":"","sources":["containerMetadataPullContinuationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"containerMetadataPullContinuationPersistence.js","sourceRoot":"","sources":["containerMetadataPullContinuationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE,OAAO,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAOzE,MAAM,CAAC,MAAM,4CAA4C,GACvD;IACE,KAAK,CAAC,kCAAkC,CAAC,OAAO,EAAE,KAAK;QACrD,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC/D,MAAM,OAAO,GAAG,iCAAiC,CAAC,aAAa,CAAC,CAAC;YACjE,MAAM,UAAU,GAAG,KAAK,IAAI,EAAE;gBAC5B,MAAM,IAAI,wBAAwB,CAChC,aAAa,CACd,CAAC,sCAAsC,CAAC;oBACvC,WAAW,EAAE,KAAK,CAAC,WAAW;oBAC9B,eAAe,EAAE,KAAK,CAAC,eAAe;oBACtC,OAAO,EAAE,2BAA2B;oBACpC,YAAY,EAAE,KAAK,CAAC,YAAY;oBAChC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;oBACxC,UAAU,EAAE,KAAK,CAAC,UAAU;oBAC5B,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;oBAC5C,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;oBACpD,aAAa,EAAE,KAAK,CAAC,aAAa;oBAClC,OAAO,EAAE,KAAK,CAAC,WAAW;iBAC3B,CAAC,CAAC;gBACH,OAAO,6BAA6B,CAClC,aAAa,EACb,KAAK,CAAC,WAAW,CAClB,CAAC;YACJ,CAAC,CAAC;YACF,IAAI,CAAC,KAAK,CAAC,YAAY;gBAAE,OAAO,OAAO,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;YAChE,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,UAAU,EACV,KAAK,CAAC,YAAY,CACnB,CAAC;YACF,OAAO,OAAO,CAAC,MAAM,CAAC;QACxB,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../documents/records\";\nimport type { ContainerContentsPersistence } from \"./containerContentsPersistenceTypes\";\nimport { selectContainerMetadataRecord } from \"./containerMetadataRows\";\nimport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\n\ntype MetadataPullContinuationPersistence = Pick<\n ContainerContentsPersistence,\n \"invalidateMetadataPullContinuation\"\n>;\n\nexport const containerMetadataPullContinuationPersistence: MetadataPullContinuationPersistence =\n {\n async invalidateMetadataPullContinuation(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const invalidate = async () => {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).invalidateDocumentSyncPullContinuation({\n accessEpoch: input.accessEpoch,\n accessStateHash: input.accessStateHash,\n appKind: CONTAINER_METADATA_APP_KIND,\n continuation: input.continuation,\n contentKeyBundle: input.contentKeyBundle,\n documentId: input.documentId,\n documentKekTargets: input.documentKekTargets,\n documentManifestBundle: input.documentManifestBundle,\n lastCommitLsn: input.lastCommitLsn,\n localId: input.containerId,\n });\n return selectContainerMetadataRecord(\n lockedExecSql,\n input.containerId,\n );\n };\n if (!input.stillCurrent) return runtime.transaction(invalidate);\n const outcome = await runtime.guardedTransaction(\n invalidate,\n input.stillCurrent,\n );\n return outcome.result;\n });\n },\n };\n"]}
|
|
@@ -2,31 +2,31 @@ import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
|
|
|
2
2
|
import { documents } from "../../sqlite/schema/documentRecordSchema.js";
|
|
3
3
|
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
4
4
|
import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
|
|
5
|
-
import {
|
|
5
|
+
import { DocumentRecordRepository } from "../documents/records/index.js";
|
|
6
6
|
import { listLocalIdsWithQueuedUpdates } from "../documents/records/documentPendingUpdatePersistence.js";
|
|
7
7
|
import { getContainerMetadataScope } from "./containerMetadataRows.js";
|
|
8
8
|
import { CONTAINER_METADATA_APP_KIND } from "./dormantContainerMetadata.js";
|
|
9
9
|
export const containerPendingUpdatePersistence = {
|
|
10
10
|
async deletePendingUpdate(execSql, id) {
|
|
11
11
|
await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
12
|
-
await settleDocumentPendingUpdate(
|
|
12
|
+
await new DocumentRecordRepository(lockedExecSql).settleDocumentPendingUpdate(id);
|
|
13
13
|
});
|
|
14
14
|
},
|
|
15
15
|
async deletePendingUpdates(execSql, containerId) {
|
|
16
16
|
await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
17
|
-
await unqueueDocumentPendingUpdates(
|
|
17
|
+
await new DocumentRecordRepository(lockedExecSql).unqueueDocumentPendingUpdates(getContainerMetadataScope(containerId));
|
|
18
18
|
});
|
|
19
19
|
},
|
|
20
20
|
async enqueuePendingUpdate(execSql, input) {
|
|
21
21
|
return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
22
|
-
return enqueueDocumentPendingUpdate(
|
|
22
|
+
return new DocumentRecordRepository(lockedExecSql).enqueueDocumentPendingUpdate(getContainerMetadataScope(input.containerId), input);
|
|
23
23
|
});
|
|
24
24
|
},
|
|
25
25
|
async listPendingUpdates(execSql, containerId) {
|
|
26
|
-
return listDocumentPendingUpdates(
|
|
26
|
+
return new DocumentRecordRepository(execSql).listDocumentPendingUpdates(getContainerMetadataScope(containerId));
|
|
27
27
|
},
|
|
28
28
|
async rekeyPendingUpdate(execSql, id) {
|
|
29
|
-
return rekeyDocumentPendingUpdate(
|
|
29
|
+
return new DocumentRecordRepository(execSql).rekeyDocumentPendingUpdate(id);
|
|
30
30
|
},
|
|
31
31
|
async listContainerIdsWithPendingUpdates(execSql, containerIds) {
|
|
32
32
|
return listLocalIdsWithQueuedUpdates(getClientSQLitePersistenceRuntime(execSql).db, CONTAINER_METADATA_APP_KIND, containerIds);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerPendingUpdatePersistence.js","sourceRoot":"","sources":["containerPendingUpdatePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,
|
|
1
|
+
{"version":3,"file":"containerPendingUpdatePersistence.js","sourceRoot":"","sources":["containerPendingUpdatePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAE,wB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KAAK,CAAC,kBAAkB,CAAC,OAAO,EAAE,EAAE;QAClC,OAAO,IAAI,wBAAwB,CAAC,OAAO,CAAC,CAAC,0BAA0B,CACrE,EAAE,CACH,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,kCAAkC,CAAC,OAAO,EAAE,YAAY;QAC5D,OAAO,6BAA6B,CAClC,iCAAiC,CAAC,OAAO,CAAC,CAAC,EAAE,EAC7C,2BAA2B,EAC3B,YAAY,CACb,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,qCAAqC,CAAC,OAAO,EAAE,YAAY;QAC/D,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC;QAC7D,IAAI,kBAAkB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACpC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;QAC1D,MAAM,IAAI,GAAG,MAAM,EAAE;aAClB,MAAM,CAAC,EAAE,WAAW,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC;aAC1C,IAAI,CAAC,SAAS,CAAC;aACf,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,2BAA2B,CAAC,EAClD,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,kBAAkB,CAAC,EAC9C,SAAS,CAAC,SAAS,CAAC,gBAAgB,CAAC,CACtC,CACF;aACA,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;QAEnC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,CAAC;CACF,CAAC","sourcesContent":["import { and, asc, eq, inArray, isNotNull } from \"drizzle-orm\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../documents/records\";\nimport { listLocalIdsWithQueuedUpdates } from \"../documents/records/documentPendingUpdatePersistence\";\nimport type { ContainerContentsPersistence } from \"./containerContentsPersistenceTypes\";\nimport { getContainerMetadataScope } from \"./containerMetadataRows\";\nimport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\n\ntype ContainerPendingUpdatePersistence = Pick<\n ContainerContentsPersistence,\n | \"deletePendingUpdate\"\n | \"deletePendingUpdates\"\n | \"enqueuePendingUpdate\"\n | \"listPendingUpdates\"\n | \"rekeyPendingUpdate\"\n | \"listContainerIdsWithPendingUpdates\"\n | \"listContainerIdsWithPullContinuations\"\n>;\n\nexport const containerPendingUpdatePersistence: ContainerPendingUpdatePersistence =\n {\n async deletePendingUpdate(execSql, id) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).settleDocumentPendingUpdate(id);\n });\n },\n async deletePendingUpdates(execSql, containerId) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).unqueueDocumentPendingUpdates(getContainerMetadataScope(containerId));\n });\n },\n async enqueuePendingUpdate(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n return new DocumentRecordRepository(\n lockedExecSql,\n ).enqueueDocumentPendingUpdate(\n getContainerMetadataScope(input.containerId),\n input,\n );\n });\n },\n async listPendingUpdates(execSql, containerId) {\n return new DocumentRecordRepository(execSql).listDocumentPendingUpdates(\n getContainerMetadataScope(containerId),\n );\n },\n async rekeyPendingUpdate(execSql, id) {\n return new DocumentRecordRepository(execSql).rekeyDocumentPendingUpdate(\n id,\n );\n },\n async listContainerIdsWithPendingUpdates(execSql, containerIds) {\n return listLocalIdsWithQueuedUpdates(\n getClientSQLitePersistenceRuntime(execSql).db,\n CONTAINER_METADATA_APP_KIND,\n containerIds,\n );\n },\n async listContainerIdsWithPullContinuations(execSql, containerIds) {\n const uniqueContainerIds = Array.from(new Set(containerIds));\n if (uniqueContainerIds.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ containerId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, CONTAINER_METADATA_APP_KIND),\n inArray(documents.localId, uniqueContainerIds),\n isNotNull(documents.pullContinuation),\n ),\n )\n .orderBy(asc(documents.localId));\n\n return rows.map((row) => row.containerId);\n },\n };\n"]}
|
|
@@ -4,8 +4,7 @@ import { resolveDocumentProjectorRegistry, } from "../../../documents/documentKi
|
|
|
4
4
|
import { documentAttachmentBlobProjection, documentPendingAttachments, documentPlacementIntentTables, inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, } from "../../../sqlite/schema/index.js";
|
|
5
5
|
import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
6
|
import { ensureSqlTables, runSerializedSqlMutation, } from "../../../sqlite/sqlSchema.js";
|
|
7
|
-
import {
|
|
8
|
-
import { deleteDocumentHistory } from "../records/documentHistoryPersistence.js";
|
|
7
|
+
import { DocumentRecordRepository } from "../records/index.js";
|
|
9
8
|
import { getDocumentScope, resolveDocumentSaveTimestamp, saveDocumentRows, } from "./documentRows.js";
|
|
10
9
|
import { queueDocumentAttachmentStorageKeys } from "./orphanSideRows.js";
|
|
11
10
|
function buildDiscardShellDocument(localId, existingDocument) {
|
|
@@ -78,8 +77,9 @@ async function clearDiscardedDocumentRows(input) {
|
|
|
78
77
|
.delete(documentAttachmentBlobProjection)
|
|
79
78
|
.where(and(eq(documentAttachmentBlobProjection.localId, localId), isNotNull(documentAttachmentBlobProjection.detachedAt)))
|
|
80
79
|
.run();
|
|
81
|
-
|
|
82
|
-
await
|
|
80
|
+
const records = new DocumentRecordRepository(lockedExecSql);
|
|
81
|
+
await records.deleteDocumentHistory(getDocumentScope(localId));
|
|
82
|
+
await records.clearDocumentSyncFailure(getDocumentScope(localId));
|
|
83
83
|
}
|
|
84
84
|
async function saveDiscardShell(input) {
|
|
85
85
|
const { candidate, documentProjectors, localId, lockedExecSql, tx } = input;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discardDocument.js","sourceRoot":"","sources":["discardDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAGL,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAM9E,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,kCAAkC,EAAE,MAAM,kBAAkB,CAAC;AAEtE,SAAS,yBAAyB,CAChC,OAAe,EACf,gBAAsC;IAEtC,OAAO;QACL,EAAE,EAAE,OAAO;QACX,WAAW,EAAE,gBAAgB,CAAC,WAAW;QACzC,eAAe,EAAE,gBAAgB,CAAC,eAAe,IAAI,IAAI;QACzD,WAAW,EAAE,gBAAgB,CAAC,WAAW;QACzC,gBAAgB,EAAE,IAAI;QACtB,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,kBAAkB,EAAE,IAAI;QACxB,sBAAsB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D;IACC,MAAM,EAAE,kBAAkB,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC3D,OAAO,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QACrE,MAAM,eAAe,CAAC,aAAa,EAAE,6BAA6B,CAAC,CAAC;QACpE,OAAO,0BAA0B,CAAC;YAChC,kBAAkB,EAAE,gCAAgC,CAClD,KAAK,CAAC,kBAAkB,CACzB;YACD,kBAAkB;YAClB,OAAO;YACP,aAAa;YACb,WAAW;SACZ,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, isNotNull } from \"drizzle-orm\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../../documents/documentKinds\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport { clearDocumentSyncFailure } from \"../records\";\nimport { deleteDocumentHistory } from \"../records/documentHistoryPersistence\";\nimport type {\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../types\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\nfunction buildDiscardShellDocument(\n localId: string,\n existingDocument: StoredDocumentRecord,\n): StoredDocumentRecord {\n return {\n id: localId,\n accessEpoch: existingDocument.accessEpoch,\n accessStateHash: existingDocument.accessStateHash ?? null,\n containerId: existingDocument.containerId,\n contentKeyBundle: null,\n documentId: existingDocument.documentId,\n documentKekTargets: null,\n documentManifestBundle: null,\n effectiveAccessLevel: existingDocument.effectiveAccessLevel ?? null,\n lastCommitLsn: null,\n pendingBaseVersion: null,\n pullContinuation: null,\n recoveryGeneration: existingDocument.recoveryGeneration ?? 0,\n snapshotEndVersion: \"\",\n text: \"\",\n ...(existingDocument.documentKind === undefined\n ? {}\n : { documentKind: existingDocument.documentKind }),\n ...(existingDocument.title === undefined\n ? {}\n : { title: existingDocument.title }),\n };\n}\n\ninterface DiscardCandidate {\n detachedStorageKeys: string[];\n existingDocument: StoredDocumentRecord;\n pendingAttachments: ReadonlyArray<{ slotId: string; storageKey: string }>;\n}\n\nasync function loadDiscardCandidate(input: {\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n tx: ClientSQLiteTransactionScope;\n}): Promise<DiscardCandidate | null> {\n const { expectedDocumentId, localId, lockedExecSql, persistence, tx } = input;\n const existingDocument = await persistence.loadDocument(\n lockedExecSql,\n localId,\n );\n if (\n !existingDocument?.documentId ||\n existingDocument.documentId !== expectedDocumentId ||\n !existingDocument.containerId\n ) {\n return null;\n }\n const moveIntentRows = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.localId, localId),\n ),\n )\n .limit(1);\n if (moveIntentRows.length > 0) return null;\n\n const pendingAttachments = await persistence.listPendingAttachments(\n lockedExecSql,\n localId,\n );\n const detachedRows = await tx\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n );\n return {\n detachedStorageKeys: detachedRows.map((row) => row.storageKey),\n existingDocument,\n pendingAttachments,\n };\n}\n\n// Staged-upload rows AND detached local-attachment markers both go: a marker\n// for a locally-discarded detach would otherwise keep filtering the slot out\n// after a re-pull restores it, leaving the attachment permanently invisible.\nasync function clearDiscardedDocumentRows(input: {\n candidate: DiscardCandidate;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, localId, lockedExecSql, tx } = input;\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n for (const pendingAttachment of candidate.pendingAttachments) {\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, pendingAttachment.slotId),\n eq(\n documentAttachmentBlobProjection.storageKey,\n pendingAttachment.storageKey,\n ),\n ),\n )\n .run();\n }\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n await deleteDocumentHistory(lockedExecSql, getDocumentScope(localId));\n await clearDocumentSyncFailure(lockedExecSql, getDocumentScope(localId));\n}\n\nasync function saveDiscardShell(input: {\n candidate: DiscardCandidate;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, documentProjectors, localId, lockedExecSql, tx } = input;\n const shellDocument = buildDiscardShellDocument(\n localId,\n candidate.existingDocument,\n );\n // The document-kind projection derives from discarded content, so clear it\n // inside the transaction and let the next pull rebuild it.\n await documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: shellDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n execSql: lockedExecSql,\n localId,\n });\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: shellDocument,\n tx,\n });\n if (!(await saveDocumentRows({ document: shellDocument, tx, updatedAt }))) {\n throw new Error(\"Document recovery generation changed during discard\");\n }\n}\n\n// Eligibility, teardown, client-projection clearing, and shell replacement\n// share one immediate transaction, so a second connection cannot relink the\n// local id between identity validation and destructive writes.\nasync function discardDocumentRowsToShell(input: {\n documentProjectors: DocumentProjectorRegistry;\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const clientProjectionTables =\n input.documentProjectors.getClientProjectionTables();\n if (clientProjectionTables.length > 0) {\n await ensureSqlTables(input.lockedExecSql, clientProjectionTables);\n }\n return getClientSQLitePersistenceRuntime(input.lockedExecSql).transaction(\n async (tx) => {\n const candidate = await loadDiscardCandidate({ ...input, tx });\n if (!candidate) return { discarded: false };\n await clearDiscardedDocumentRows({\n candidate,\n localId: input.localId,\n lockedExecSql: input.lockedExecSql,\n tx,\n });\n await saveDiscardShell({ ...input, candidate, tx });\n // The deleted rows were these bytes' only pointers from this document,\n // but a hydrated copy is shared by every slot holding the same blob.\n // Queue them for the reference-checked reclaim instead of deleting.\n await queueDocumentAttachmentStorageKeys(tx, [\n ...new Set([\n ...candidate.pendingAttachments.map((row) => row.storageKey),\n ...candidate.detachedStorageKeys,\n ]),\n ]);\n return {\n discarded: true,\n documentKind:\n candidate.existingDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n };\n },\n { behavior: \"immediate\" },\n );\n}\n\n/**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell: drop its queued updates, staged attachment\n * rows (and their settled local-attachment halves, which share the staged\n * storage keys the caller reclaims), detached attachment markers, durable\n * history, recorded sync failure, and document-kind client projection, then\n * overwrite the record with an empty snapshot that keeps its identity,\n * placement, title, and kind. Everything commits in ONE transaction.\n *\n * Refused under the serialized mutation when the document is local-only or\n * unlinked (its rows are the only copy), when its documentId no longer\n * matches the caller's expectation (a stale caller or racing relink must not\n * discard a different identity's edits), or when any move intent references\n * it (the local containerId is then the move's optimistic placement, and\n * reseeding it as server truth would silently commit the move locally while\n * discarding the intent that was meant to perform it).\n */\nexport async function discardStoredDocumentToShell(input: {\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n expectedDocumentId: string;\n localId: string;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const { expectedDocumentId, localId, persistence } = input;\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return discardDocumentRowsToShell({\n documentProjectors: resolveDocumentProjectorRegistry(\n input.documentProjectors,\n ),\n expectedDocumentId,\n localId,\n lockedExecSql,\n persistence,\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"discardDocument.js","sourceRoot":"","sources":["discardDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAGL,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAMtD,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,kCAAkC,EAAE,MAAM,kBAAkB,CAAC;AAEtE,SAAS,yBAAyB,CAChC,OAAe,EACf,gBAAsC;IAEtC,OAAO;QACL,EAAE,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AAS,CAAC,mBAAmB;aACjC,CAAC;SACH,CAAC,CAAC;QACH,OAAO;YACL,SAAS,EAAE,IAAI;YACf,YAAY,EACV,SAAS,CAAC,gBAAgB,CAAC,YAAY,IAAI,qBAAqB;SACnE,CAAC;IACJ,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAAC,KASlD;IACC,MAAM,EAAE,kBAAkB,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC3D,OAAO,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QACrE,MAAM,eAAe,CAAC,aAAa,EAAE,6BAA6B,CAAC,CAAC;QACpE,OAAO,0BAA0B,CAAC;YAChC,kBAAkB,EAAE,gCAAgC,CAClD,KAAK,CAAC,kBAAkB,CACzB;YACD,kBAAkB;YAClB,OAAO;YACP,aAAa;YACb,WAAW;SACZ,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, isNotNull } from \"drizzle-orm\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../../documents/documentKinds\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type {\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../types\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\nfunction buildDiscardShellDocument(\n localId: string,\n existingDocument: StoredDocumentRecord,\n): StoredDocumentRecord {\n return {\n id: localId,\n accessEpoch: existingDocument.accessEpoch,\n accessStateHash: existingDocument.accessStateHash ?? null,\n containerId: existingDocument.containerId,\n contentKeyBundle: null,\n documentId: existingDocument.documentId,\n documentKekTargets: null,\n documentManifestBundle: null,\n effectiveAccessLevel: existingDocument.effectiveAccessLevel ?? null,\n lastCommitLsn: null,\n pendingBaseVersion: null,\n pullContinuation: null,\n recoveryGeneration: existingDocument.recoveryGeneration ?? 0,\n snapshotEndVersion: \"\",\n text: \"\",\n ...(existingDocument.documentKind === undefined\n ? {}\n : { documentKind: existingDocument.documentKind }),\n ...(existingDocument.title === undefined\n ? {}\n : { title: existingDocument.title }),\n };\n}\n\ninterface DiscardCandidate {\n detachedStorageKeys: string[];\n existingDocument: StoredDocumentRecord;\n pendingAttachments: ReadonlyArray<{ slotId: string; storageKey: string }>;\n}\n\nasync function loadDiscardCandidate(input: {\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n tx: ClientSQLiteTransactionScope;\n}): Promise<DiscardCandidate | null> {\n const { expectedDocumentId, localId, lockedExecSql, persistence, tx } = input;\n const existingDocument = await persistence.loadDocument(\n lockedExecSql,\n localId,\n );\n if (\n !existingDocument?.documentId ||\n existingDocument.documentId !== expectedDocumentId ||\n !existingDocument.containerId\n ) {\n return null;\n }\n const moveIntentRows = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.localId, localId),\n ),\n )\n .limit(1);\n if (moveIntentRows.length > 0) return null;\n\n const pendingAttachments = await persistence.listPendingAttachments(\n lockedExecSql,\n localId,\n );\n const detachedRows = await tx\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n );\n return {\n detachedStorageKeys: detachedRows.map((row) => row.storageKey),\n existingDocument,\n pendingAttachments,\n };\n}\n\n// Staged-upload rows AND detached local-attachment markers both go: a marker\n// for a locally-discarded detach would otherwise keep filtering the slot out\n// after a re-pull restores it, leaving the attachment permanently invisible.\nasync function clearDiscardedDocumentRows(input: {\n candidate: DiscardCandidate;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, localId, lockedExecSql, tx } = input;\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n for (const pendingAttachment of candidate.pendingAttachments) {\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, pendingAttachment.slotId),\n eq(\n documentAttachmentBlobProjection.storageKey,\n pendingAttachment.storageKey,\n ),\n ),\n )\n .run();\n }\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n const records = new DocumentRecordRepository(lockedExecSql);\n await records.deleteDocumentHistory(getDocumentScope(localId));\n await records.clearDocumentSyncFailure(getDocumentScope(localId));\n}\n\nasync function saveDiscardShell(input: {\n candidate: DiscardCandidate;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, documentProjectors, localId, lockedExecSql, tx } = input;\n const shellDocument = buildDiscardShellDocument(\n localId,\n candidate.existingDocument,\n );\n // The document-kind projection derives from discarded content, so clear it\n // inside the transaction and let the next pull rebuild it.\n await documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: shellDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n execSql: lockedExecSql,\n localId,\n });\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: shellDocument,\n tx,\n });\n if (!(await saveDocumentRows({ document: shellDocument, tx, updatedAt }))) {\n throw new Error(\"Document recovery generation changed during discard\");\n }\n}\n\n// Eligibility, teardown, client-projection clearing, and shell replacement\n// share one immediate transaction, so a second connection cannot relink the\n// local id between identity validation and destructive writes.\nasync function discardDocumentRowsToShell(input: {\n documentProjectors: DocumentProjectorRegistry;\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const clientProjectionTables =\n input.documentProjectors.getClientProjectionTables();\n if (clientProjectionTables.length > 0) {\n await ensureSqlTables(input.lockedExecSql, clientProjectionTables);\n }\n return getClientSQLitePersistenceRuntime(input.lockedExecSql).transaction(\n async (tx) => {\n const candidate = await loadDiscardCandidate({ ...input, tx });\n if (!candidate) return { discarded: false };\n await clearDiscardedDocumentRows({\n candidate,\n localId: input.localId,\n lockedExecSql: input.lockedExecSql,\n tx,\n });\n await saveDiscardShell({ ...input, candidate, tx });\n // The deleted rows were these bytes' only pointers from this document,\n // but a hydrated copy is shared by every slot holding the same blob.\n // Queue them for the reference-checked reclaim instead of deleting.\n await queueDocumentAttachmentStorageKeys(tx, [\n ...new Set([\n ...candidate.pendingAttachments.map((row) => row.storageKey),\n ...candidate.detachedStorageKeys,\n ]),\n ]);\n return {\n discarded: true,\n documentKind:\n candidate.existingDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n };\n },\n { behavior: \"immediate\" },\n );\n}\n\n/**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell: drop its queued updates, staged attachment\n * rows (and their settled local-attachment halves, which share the staged\n * storage keys the caller reclaims), detached attachment markers, durable\n * history, recorded sync failure, and document-kind client projection, then\n * overwrite the record with an empty snapshot that keeps its identity,\n * placement, title, and kind. Everything commits in ONE transaction.\n *\n * Refused under the serialized mutation when the document is local-only or\n * unlinked (its rows are the only copy), when its documentId no longer\n * matches the caller's expectation (a stale caller or racing relink must not\n * discard a different identity's edits), or when any move intent references\n * it (the local containerId is then the move's optimistic placement, and\n * reseeding it as server truth would silently commit the move locally while\n * discarding the intent that was meant to perform it).\n */\nexport async function discardStoredDocumentToShell(input: {\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n expectedDocumentId: string;\n localId: string;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const { expectedDocumentId, localId, persistence } = input;\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return discardDocumentRowsToShell({\n documentProjectors: resolveDocumentProjectorRegistry(\n input.documentProjectors,\n ),\n expectedDocumentId,\n localId,\n lockedExecSql,\n persistence,\n });\n });\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { KeyingVerificationError } from "../../../../internal/crypto/index.js";
|
|
|
2
2
|
import { DEFAULT_DOCUMENT_KIND, DOCUMENTS_APP_KIND, } from "../../../documents/documentConstants.js";
|
|
3
3
|
import { loadDocumentMovePlacements, } from "../../container-contents/documentPlacement.js";
|
|
4
4
|
import { hasDocumentPurgeCheckpointInTransaction, listPurgedDocumentIdsInTransaction, } from "../../keyingCheckpoints/documentPurgeCheckpointPersistence.js";
|
|
5
|
-
import {
|
|
5
|
+
import { DocumentRecordRepository } from "../records/index.js";
|
|
6
6
|
import { discoveredDocumentPlacement, resolveDiscoveredDocumentPlacement, } from "./discoveredDocumentPlacement.js";
|
|
7
7
|
import { toDocumentSummary } from "./documentProjectionRows.js";
|
|
8
8
|
import { documentSaveTimestampFrom, resolveDocumentSaveTimestamp, saveDocumentRows, saveDocumentRowsBatch, } from "./documentRows.js";
|
|
@@ -40,7 +40,7 @@ async function upsertDiscoveredDocumentWithExec(execSql, input, pendingCreates,
|
|
|
40
40
|
if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {
|
|
41
41
|
throw purgedDocumentError();
|
|
42
42
|
}
|
|
43
|
-
const existingLocalId = await findLocalIdByDocumentId(
|
|
43
|
+
const existingLocalId = await new DocumentRecordRepository(execSql).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, input.documentId);
|
|
44
44
|
const localId = existingLocalId ?? input.documentId;
|
|
45
45
|
const pendingLocalId = pendingCreates.get(input.documentId);
|
|
46
46
|
if (!existingLocalId && pendingLocalId) {
|
|
@@ -78,7 +78,7 @@ async function upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates,
|
|
|
78
78
|
async function resolveDiscoveryTargets(execSql, inputs, pendingCreates, tx) {
|
|
79
79
|
const documentIds = inputs.map((input) => input.documentId);
|
|
80
80
|
const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);
|
|
81
|
-
const existingLocalIds = await findLocalIdsByDocumentIds(
|
|
81
|
+
const existingLocalIds = await new DocumentRecordRepository(execSql).findLocalIdsByDocumentIds(DOCUMENTS_APP_KIND, documentIds);
|
|
82
82
|
const targets = [];
|
|
83
83
|
const pendingLocalIds = new Set();
|
|
84
84
|
for (const input of inputs) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discoveredDocumentUpsert.js","sourceRoot":"","sources":["discoveredDocumentUpsert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAO9C,OAAO,EAEL,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,uCAAuC,EACvC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AI,GAAG,CACrB,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,CAAC,OAAO;QACd,qBAAqB,CACnB,MAAM,EACN,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,EAC1B,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CACrC;KACF,CAAC,CACH,CAAC;IACF,MAAM,KAAK,GAAG,MAAM,qBAAqB,CAAC;QACxC,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QAC9B,EAAE;KACH,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI;QAAE,MAAM,iBAAiB,EAAE,CAAC;IAC3D,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QAC5B,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS;YAAE,OAAO,MAAM,CAAC,OAAO,CAAC;QACrD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QACpE,OAAO,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacements,\n} from \"../../container-contents/documentPlacement\";\nimport {\n hasDocumentPurgeCheckpointInTransaction,\n listPurgedDocumentIdsInTransaction,\n} from \"../../keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { findLocalIdByDocumentId, findLocalIdsByDocumentIds } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n discoveredDocumentPlacement,\n resolveDiscoveredDocumentPlacement,\n} from \"./discoveredDocumentPlacement\";\nimport { toDocumentSummary } from \"./documentProjectionRows\";\nimport {\n documentSaveTimestampFrom,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n saveDocumentRowsBatch,\n} from \"./documentRows\";\nimport { resolvePersistedDocumentRuntimeState } from \"./documentRuntimeState\";\nimport { loadPendingCreateSummary } from \"./pendingCreateAdoption\";\nimport {\n loadStoredDocumentState,\n loadStoredDocumentStates,\n type StoredDocumentState,\n} from \"./rowQueryPersistence\";\n\nconst DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE = \"Syncing document...\";\n\nfunction purgedDocumentError(): KeyingVerificationError {\n return new KeyingVerificationError(\n \"rollback\",\n \"Document discovery targets a permanently purged document\",\n );\n}\n\nfunction fenceSkippedError(): Error {\n return new Error(\"Document recovery generation changed during discovery\");\n}\n\nfunction nextDiscoveredDocument(\n localId: string,\n input: DiscoveredDocumentInput,\n existingDocument: StoredDocumentRecord | null,\n placement: ReturnType<typeof discoveredDocumentPlacement>,\n): StoredDocumentRecord {\n return {\n id: localId,\n documentId: input.documentId,\n documentKind: existingDocument?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n text: existingDocument?.text ?? \"\",\n title: existingDocument?.title ?? DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE,\n snapshotEndVersion: existingDocument?.snapshotEndVersion ?? \"\",\n recoveryGeneration: existingDocument?.recoveryGeneration ?? 0,\n ...placement,\n effectiveAccessLevel:\n input.effectiveAccessLevel ??\n existingDocument?.effectiveAccessLevel ??\n null,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: placement.accessEpoch,\n documentId: input.documentId,\n }),\n };\n}\n\n/** One discovered document, read and written on its own (the per-row path). */\nasync function upsertDiscoveredDocumentWithExec(\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary> {\n if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {\n throw purgedDocumentError();\n }\n const existingLocalId = await findLocalIdByDocumentId(\n execSql,\n DOCUMENTS_APP_KIND,\n input.documentId,\n );\n const localId = existingLocalId ?? input.documentId;\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n return pending;\n }\n const existingDocument =\n (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n const placement = await resolveDiscoveredDocumentPlacement(\n tx,\n existingDocument,\n input,\n );\n const nextDocument = nextDiscoveredDocument(\n localId,\n input,\n existingDocument,\n placement,\n );\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: nextDocument,\n options: existingDocument ? undefined : { updatedAt: input.createdAt },\n tx,\n });\n if (!(await saveDocumentRows({ document: nextDocument, tx, updatedAt }))) {\n throw fenceSkippedError();\n }\n return toDocumentSummary(nextDocument, updatedAt);\n}\n\nasync function upsertDiscoveredDocumentsPerRow(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const summaries: DocumentSummary[] = [];\n for (const input of inputs) {\n summaries.push(\n await upsertDiscoveredDocumentWithExec(\n execSql,\n input,\n pendingCreates,\n tx,\n ),\n );\n }\n return summaries;\n}\n\ntype DiscoveryTarget =\n | { kind: \"pending\"; summary: DocumentSummary }\n | { input: DiscoveredDocumentInput; kind: \"write\"; localId: string };\n\n/**\n * Resolves every input to its pending-create summary or its target local id,\n * in input order, so the first purged or unavailable input throws exactly as\n * the per-row walk would. Returns null when one input's write could change\n * another input's reads, which only the per-row walk handles.\n */\nasync function resolveDiscoveryTargets(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DiscoveryTarget[] | null> {\n const documentIds = inputs.map((input) => input.documentId);\n const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);\n const existingLocalIds = await findLocalIdsByDocumentIds(\n execSql,\n DOCUMENTS_APP_KIND,\n documentIds,\n );\n const targets: DiscoveryTarget[] = [];\n const pendingLocalIds = new Set<string>();\n for (const input of inputs) {\n if (purged.has(input.documentId)) throw purgedDocumentError();\n const existingLocalId = existingLocalIds.get(input.documentId);\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n pendingLocalIds.add(pendingLocalId);\n targets.push({ kind: \"pending\", summary: pending });\n continue;\n }\n targets.push({\n input,\n kind: \"write\",\n localId: existingLocalId ?? input.documentId,\n });\n }\n const writeLocalIds = targets.flatMap((target) =>\n target.kind === \"write\" ? [target.localId] : [],\n );\n const independent =\n new Set(writeLocalIds).size === writeLocalIds.length &&\n !writeLocalIds.some((localId) => pendingLocalIds.has(localId));\n return independent ? targets : null;\n}\n\n/**\n * Whether writing each target leaves every other target's reads unchanged: a\n * stored row at a target local id that carries a different document id would\n * be re-pointed by its write, which another input's lookup could have read.\n */\nfunction targetsReadDisjointRows(\n targets: ReadonlyArray<DiscoveryTarget>,\n states: ReadonlyMap<string, StoredDocumentState>,\n): boolean {\n return targets.every(\n (target) =>\n target.kind !== \"write\" ||\n (states.get(target.localId)?.record.documentId ??\n target.input.documentId) === target.input.documentId,\n );\n}\n\nfunction plannedDiscoveryWrite(\n target: Extract<DiscoveryTarget, { kind: \"write\" }>,\n state: StoredDocumentState | undefined,\n intent: DocumentMovePlacement | undefined,\n) {\n const existingDocument = state?.record ?? null;\n const document = nextDiscoveredDocument(\n target.localId,\n target.input,\n existingDocument,\n discoveredDocumentPlacement(existingDocument, target.input, intent),\n );\n // The joined state read is the row and projection the per-row walk reads\n // again for its timestamp; nothing earlier in this transaction writes it.\n const updatedAt = state\n ? documentSaveTimestampFrom(\n {\n projection: state.projection,\n snapshotEndVersion: state.record.snapshotEndVersion,\n },\n document,\n )\n : target.input.createdAt;\n return { document, updatedAt };\n}\n\n/**\n * Discovery as set statements: one read per table for every input, then\n * multi-row upserts. Inputs whose rows could interact (a repeated document\n * id, a shared local id, or a row another input would re-point) keep the\n * per-row walk, which reads each input after the previous one's writes.\n */\nexport async function upsertDiscoveredDocumentsInTransaction(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const documentIds = inputs.map((input) => input.documentId);\n if (new Set(documentIds).size !== documentIds.length) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const targets = await resolveDiscoveryTargets(\n execSql,\n inputs,\n pendingCreates,\n tx,\n );\n if (!targets) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const writes = targets.flatMap((target) =>\n target.kind === \"write\" ? [target] : [],\n );\n if (writes.length === 0) {\n return targets.flatMap((target) =>\n target.kind === \"pending\" ? [target.summary] : [],\n );\n }\n const states = await loadStoredDocumentStates(\n execSql,\n writes.map((target) => target.localId),\n );\n if (!targetsReadDisjointRows(targets, states)) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const intents = await loadDocumentMovePlacements(\n tx,\n writes.map((target) => target.input.documentId),\n );\n const planned = new Map(\n writes.map((target) => [\n target.localId,\n plannedDiscoveryWrite(\n target,\n states.get(target.localId),\n intents.get(target.input.documentId),\n ),\n ]),\n );\n const saved = await saveDocumentRowsBatch({\n entries: [...planned.values()],\n tx,\n });\n if (saved.size !== planned.size) throw fenceSkippedError();\n return targets.map((target) => {\n if (target.kind === \"pending\") return target.summary;\n const write = planned.get(target.localId);\n if (!write) throw new Error(\"Discovered document write is missing\");\n return toDocumentSummary(write.document, write.updatedAt);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"discoveredDocumentUpsert.js","sourceRoot":"","sources":["discoveredDocumentUpsert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAO9C,OAAO,EAEL,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,uCAAuC,EACvC,kCAAkC,GACnC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAEtD,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EACL,yBAAyB,EACzB,4BAA4B,EAC5B,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,oCAAoC,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,EACL,uBAAuB,EACvB,wBAAwB,GAEzB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,qCAAqC,GAAG,qBAAqB,CAAC;AAEpE,SAAS,mBAAmB;IAC1B,OAAO,IAAI,uBAAuB,CAChC,UAAU,EACV,0DAA0D,CAC3D,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB;IACxB,OAAO,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;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,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QACpE,OAAO,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacements,\n} from \"../../container-contents/documentPlacement\";\nimport {\n hasDocumentPurgeCheckpointInTransaction,\n listPurgedDocumentIdsInTransaction,\n} from \"../../keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n discoveredDocumentPlacement,\n resolveDiscoveredDocumentPlacement,\n} from \"./discoveredDocumentPlacement\";\nimport { toDocumentSummary } from \"./documentProjectionRows\";\nimport {\n documentSaveTimestampFrom,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n saveDocumentRowsBatch,\n} from \"./documentRows\";\nimport { resolvePersistedDocumentRuntimeState } from \"./documentRuntimeState\";\nimport { loadPendingCreateSummary } from \"./pendingCreateAdoption\";\nimport {\n loadStoredDocumentState,\n loadStoredDocumentStates,\n type StoredDocumentState,\n} from \"./rowQueryPersistence\";\n\nconst DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE = \"Syncing document...\";\n\nfunction purgedDocumentError(): KeyingVerificationError {\n return new KeyingVerificationError(\n \"rollback\",\n \"Document discovery targets a permanently purged document\",\n );\n}\n\nfunction fenceSkippedError(): Error {\n return new Error(\"Document recovery generation changed during discovery\");\n}\n\nfunction nextDiscoveredDocument(\n localId: string,\n input: DiscoveredDocumentInput,\n existingDocument: StoredDocumentRecord | null,\n placement: ReturnType<typeof discoveredDocumentPlacement>,\n): StoredDocumentRecord {\n return {\n id: localId,\n documentId: input.documentId,\n documentKind: existingDocument?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n text: existingDocument?.text ?? \"\",\n title: existingDocument?.title ?? DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE,\n snapshotEndVersion: existingDocument?.snapshotEndVersion ?? \"\",\n recoveryGeneration: existingDocument?.recoveryGeneration ?? 0,\n ...placement,\n effectiveAccessLevel:\n input.effectiveAccessLevel ??\n existingDocument?.effectiveAccessLevel ??\n null,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: placement.accessEpoch,\n documentId: input.documentId,\n }),\n };\n}\n\n/** One discovered document, read and written on its own (the per-row path). */\nasync function upsertDiscoveredDocumentWithExec(\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary> {\n if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {\n throw purgedDocumentError();\n }\n const existingLocalId = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, input.documentId);\n const localId = existingLocalId ?? input.documentId;\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n return pending;\n }\n const existingDocument =\n (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n const placement = await resolveDiscoveredDocumentPlacement(\n tx,\n existingDocument,\n input,\n );\n const nextDocument = nextDiscoveredDocument(\n localId,\n input,\n existingDocument,\n placement,\n );\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: nextDocument,\n options: existingDocument ? undefined : { updatedAt: input.createdAt },\n tx,\n });\n if (!(await saveDocumentRows({ document: nextDocument, tx, updatedAt }))) {\n throw fenceSkippedError();\n }\n return toDocumentSummary(nextDocument, updatedAt);\n}\n\nasync function upsertDiscoveredDocumentsPerRow(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const summaries: DocumentSummary[] = [];\n for (const input of inputs) {\n summaries.push(\n await upsertDiscoveredDocumentWithExec(\n execSql,\n input,\n pendingCreates,\n tx,\n ),\n );\n }\n return summaries;\n}\n\ntype DiscoveryTarget =\n | { kind: \"pending\"; summary: DocumentSummary }\n | { input: DiscoveredDocumentInput; kind: \"write\"; localId: string };\n\n/**\n * Resolves every input to its pending-create summary or its target local id,\n * in input order, so the first purged or unavailable input throws exactly as\n * the per-row walk would. Returns null when one input's write could change\n * another input's reads, which only the per-row walk handles.\n */\nasync function resolveDiscoveryTargets(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DiscoveryTarget[] | null> {\n const documentIds = inputs.map((input) => input.documentId);\n const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);\n const existingLocalIds = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdsByDocumentIds(DOCUMENTS_APP_KIND, documentIds);\n const targets: DiscoveryTarget[] = [];\n const pendingLocalIds = new Set<string>();\n for (const input of inputs) {\n if (purged.has(input.documentId)) throw purgedDocumentError();\n const existingLocalId = existingLocalIds.get(input.documentId);\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n pendingLocalIds.add(pendingLocalId);\n targets.push({ kind: \"pending\", summary: pending });\n continue;\n }\n targets.push({\n input,\n kind: \"write\",\n localId: existingLocalId ?? input.documentId,\n });\n }\n const writeLocalIds = targets.flatMap((target) =>\n target.kind === \"write\" ? [target.localId] : [],\n );\n const independent =\n new Set(writeLocalIds).size === writeLocalIds.length &&\n !writeLocalIds.some((localId) => pendingLocalIds.has(localId));\n return independent ? targets : null;\n}\n\n/**\n * Whether writing each target leaves every other target's reads unchanged: a\n * stored row at a target local id that carries a different document id would\n * be re-pointed by its write, which another input's lookup could have read.\n */\nfunction targetsReadDisjointRows(\n targets: ReadonlyArray<DiscoveryTarget>,\n states: ReadonlyMap<string, StoredDocumentState>,\n): boolean {\n return targets.every(\n (target) =>\n target.kind !== \"write\" ||\n (states.get(target.localId)?.record.documentId ??\n target.input.documentId) === target.input.documentId,\n );\n}\n\nfunction plannedDiscoveryWrite(\n target: Extract<DiscoveryTarget, { kind: \"write\" }>,\n state: StoredDocumentState | undefined,\n intent: DocumentMovePlacement | undefined,\n) {\n const existingDocument = state?.record ?? null;\n const document = nextDiscoveredDocument(\n target.localId,\n target.input,\n existingDocument,\n discoveredDocumentPlacement(existingDocument, target.input, intent),\n );\n // The joined state read is the row and projection the per-row walk reads\n // again for its timestamp; nothing earlier in this transaction writes it.\n const updatedAt = state\n ? documentSaveTimestampFrom(\n {\n projection: state.projection,\n snapshotEndVersion: state.record.snapshotEndVersion,\n },\n document,\n )\n : target.input.createdAt;\n return { document, updatedAt };\n}\n\n/**\n * Discovery as set statements: one read per table for every input, then\n * multi-row upserts. Inputs whose rows could interact (a repeated document\n * id, a shared local id, or a row another input would re-point) keep the\n * per-row walk, which reads each input after the previous one's writes.\n */\nexport async function upsertDiscoveredDocumentsInTransaction(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const documentIds = inputs.map((input) => input.documentId);\n if (new Set(documentIds).size !== documentIds.length) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const targets = await resolveDiscoveryTargets(\n execSql,\n inputs,\n pendingCreates,\n tx,\n );\n if (!targets) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const writes = targets.flatMap((target) =>\n target.kind === \"write\" ? [target] : [],\n );\n if (writes.length === 0) {\n return targets.flatMap((target) =>\n target.kind === \"pending\" ? [target.summary] : [],\n );\n }\n const states = await loadStoredDocumentStates(\n execSql,\n writes.map((target) => target.localId),\n );\n if (!targetsReadDisjointRows(targets, states)) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const intents = await loadDocumentMovePlacements(\n tx,\n writes.map((target) => target.input.documentId),\n );\n const planned = new Map(\n writes.map((target) => [\n target.localId,\n plannedDiscoveryWrite(\n target,\n states.get(target.localId),\n intents.get(target.input.documentId),\n ),\n ]),\n );\n const saved = await saveDocumentRowsBatch({\n entries: [...planned.values()],\n tx,\n });\n if (saved.size !== planned.size) throw fenceSkippedError();\n return targets.map((target) => {\n if (target.kind === \"pending\") return target.summary;\n const write = planned.get(target.localId);\n if (!write) throw new Error(\"Discovered document write is missing\");\n return toDocumentSummary(write.document, write.updatedAt);\n });\n}\n"]}
|