@tearleads/client-sdk 0.1.256 → 0.1.257
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/client/documents/index.d.ts +5 -2
- package/client/documents/index.js +6 -1
- package/client/documents/index.js.map +1 -1
- package/client/index.d.ts +1 -1
- package/client/index.js.map +1 -1
- package/data/blobs/attachments/types.d.ts +4 -2
- package/data/blobs/attachments/types.js.map +1 -1
- package/data/documents/documentContent.d.ts +2 -0
- package/data/documents/documentContent.js +7 -0
- package/data/documents/documentContent.js.map +1 -1
- package/data/documents/shared/manifestBundleReaders.js +1 -1
- package/data/documents/shared/manifestBundleReaders.js.map +1 -1
- package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
- package/data/documents/shared/projection/documentCreateSigner.js +49 -0
- package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
- package/data/documents/shared/projection/index.d.ts +1 -0
- package/data/documents/shared/projection/index.js +1 -0
- package/data/documents/shared/projection/index.js.map +1 -1
- package/data/documents/shared/readers.js +1 -1
- package/data/documents/shared/readers.js.map +1 -1
- package/data/documents/shared/types.d.ts +1 -0
- package/data/documents/shared/types.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.d.ts +1 -1
- package/data/persistence/documents/documentsPersistence.js +4 -1
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +2 -2
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +2 -2
- package/internal/api-client/apiRequestRuntime.js +12 -8
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/binaryResponseOperationTransport.js +2 -2
- package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
- package/internal/api-client/client/blobs.d.ts +2 -2
- package/internal/api-client/client/blobs.js +21 -9
- package/internal/api-client/client/blobs.js.map +1 -1
- package/internal/api-client/client/writerProjections.js +2 -1
- package/internal/api-client/client/writerProjections.js.map +1 -1
- package/internal/api-client/operationResponse.js +3 -3
- package/internal/api-client/operationResponse.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +6 -1
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionResponse.js +5 -2
- package/internal/api-client/sessionResponse.js.map +1 -1
- package/internal/api-client/types.d.ts +2 -0
- package/internal/api-client/types.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
- package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
- package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
- package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
- package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
- package/stores/documents/documentStore/state.js +3 -1
- package/stores/documents/documentStore/state.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +3 -2
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/stores/documents/index.d.ts +1 -0
- package/stores/documents/index.js +1 -0
- package/stores/documents/index.js.map +1 -1
- package/stores/documents/types.d.ts +1 -0
- package/stores/documents/types.js.map +1 -1
- package/workflows/blobs/upload/index.d.ts +1 -1
- package/workflows/blobs/upload/index.js +36 -18
- package/workflows/blobs/upload/index.js.map +1 -1
- package/workflows/blobs/upload/multipartStageResolution.js +12 -2
- package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
- package/workflows/blobs/upload/multipartUpload.js +10 -2
- package/workflows/blobs/upload/multipartUpload.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
- package/workflows/container-contents/documentQueries/index.d.ts +1 -1
- package/workflows/container-contents/documentQueries/index.js +2 -2
- package/workflows/container-contents/documentQueries/index.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -0
- package/workflows/container-contents/index.js +1 -0
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
- package/workflows/documents/create/createAdoption.js +2 -50
- package/workflows/documents/create/createAdoption.js.map +1 -1
- package/workflows/documents/create/createResponse.js +12 -1
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/create/createSubmission.js +14 -0
- package/workflows/documents/create/createSubmission.js.map +1 -0
- package/workflows/documents/create/index.d.ts +3 -14
- package/workflows/documents/create/index.js +76 -67
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
- package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
- package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
- package/workflows/documents/purge/absentDocumentPurge.js +23 -0
- package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
- package/workflows/documents/purge/index.d.ts +1 -0
- package/workflows/documents/purge/index.js +1 -0
- package/workflows/documents/purge/index.js.map +1 -1
- package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
- package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
|
@@ -167,14 +167,15 @@ export async function ensureRemoteDocument(state, currentDoc, nextRecord, encaps
|
|
|
167
167
|
const created = await remoteDocuments.createRemoteDocument({
|
|
168
168
|
author,
|
|
169
169
|
containerId: runtime.state.containerId,
|
|
170
|
-
|
|
170
|
+
...(seed
|
|
171
|
+
? { seedUpdate: seed.update }
|
|
172
|
+
: { deferredSeedUpdate: deferredSeed?.update }),
|
|
171
173
|
// Derive the remote id from the stable local id so a retry after a lost
|
|
172
174
|
// create response re-sends the same id and adopts the existing remote
|
|
173
175
|
// document instead of creating a duplicate.
|
|
174
176
|
documentId,
|
|
175
177
|
onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(state, generation),
|
|
176
178
|
resolveProjectionUserKey: state.resolveProjectionUserKey,
|
|
177
|
-
seedUpdate: seed?.update,
|
|
178
179
|
stillCurrent: generationIsCurrent,
|
|
179
180
|
warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({
|
|
180
181
|
operation: policyOperation,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,mCAAmC,EACnC,iCAAiC,EAEjC,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mEAAmE,CAAC;AAEjH,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAIL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAGL,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CAChD,KAAyB,EACzB,UAAwC;IAExC,OAAO,0BAA0B,CAAC;QAChC,eAAe,EAAE,mCAAmC;QACpD,UAAU;QACV,KAAK;QACL,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oCAAoC,CAClD,KAAyB,EACzB,UAAwC;IAExC,OAAO,0BAA0B,CAAC;QAChC,eAAe,EAAE,iCAAiC;QAClD,UAAU;QACV,KAAK;KACN,CAAC,CAAC;AACL,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,6CAA6C,CAC3D,KAAyB,EAC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AC,CAAC;QACH,IAAI,SAAS,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACtC,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n // The runtime this create read before its awaits, with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n const created = await remoteDocuments.createRemoteDocument({\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oD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esContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n // The runtime this create read before its awaits, with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n const created = await remoteDocuments.createRemoteDocument({\n author,\n containerId: runtime.state.containerId,\n ...(seed\n ? { seedUpdate: seed.update }\n : { deferredSeedUpdate: deferredSeed?.update }),\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAC3D,cAAc,SAAS,CAAC","sourcesContent":["export * from \"./documentStore\";\nexport { hasPendingLocalDocumentWrites } from \"./registry\";\nexport * from \"./types\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACL,oBAAoB,GAErB,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAC3D,cAAc,SAAS,CAAC","sourcesContent":["export * from \"./documentStore\";\nexport {\n createSeededDocument,\n type SeededDocumentInput,\n} from \"./documentStore/initialization/createSeededDocument\";\nexport { hasPendingLocalDocumentWrites } from \"./registry\";\nexport * from \"./types\";\n"]}
|
|
@@ -49,6 +49,7 @@ export type UpdateDocumentRowFields = (id: string, patch: Readonly<Record<string
|
|
|
49
49
|
export type RemoveDocumentRow = (id: string, options?: DocumentMutationGuard | undefined) => Promise<void>;
|
|
50
50
|
export type DocumentContextValue = DocumentSnapshot & Pick<DocumentStore, "addRow" | "attachFiles" | "relink" | "removeAttachment" | "removeRow" | "replaceAttachment" | "requestSync" | "restoreContent" | "setStructuredFields" | "setText" | "updateRowFields">;
|
|
51
51
|
export interface DocumentSnapshot {
|
|
52
|
+
readonly seedTag?: string | undefined;
|
|
52
53
|
attachments: ReadonlyArray<DocumentAttachment>;
|
|
53
54
|
attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;
|
|
54
55
|
attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAgBA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRestoreContent } from \"../../data/documents/documentRestore\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentRotationProofMode,\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\n/**\n * Host admission checked after readiness and again at local queue execution.\n * The predicate must be synchronous and side-effect-free. False is a no-op;\n * a throw is reported as a write failure and also refuses the mutation.\n * This does not cancel initialization or roll back an already admitted write.\n */\nexport interface DocumentMutationGuard {\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface DocumentMutationOptions extends DocumentMutationGuard {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\nexport type RemoveDocumentRow = (\n id: string,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"restoreContent\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: (\n proof: DocumentRotationProofMode,\n ) => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n /** Whether local writes are queued that have not reached SQLite yet. */\n hasQueuedWrites: () => boolean;\n /**\n * Whether applied local edits have not reached SQLite, e.g. after a failed\n * save, even though no write is queued any more.\n */\n hasUnsavedLocalEdits: () => boolean;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /**\n * Write a past version's text, structured fields, and rows back as one\n * ordinary local edit; attachments are left as they are. Nothing is rewound:\n * the restore is new operations that sync and merge like any other write.\n * Resolves true when the document durably holds the content, false when\n * the restore was refused or did not persist.\n */\n restoreContent: (\n content: DocumentRestoreContent,\n options?: DocumentMutationGuard | undefined,\n ) => Promise<boolean>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAgBA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRestoreContent } from \"../../data/documents/documentRestore\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentRotationProofMode,\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\n/**\n * Host admission checked after readiness and again at local queue execution.\n * The predicate must be synchronous and side-effect-free. False is a no-op;\n * a throw is reported as a write failure and also refuses the mutation.\n * This does not cancel initialization or roll back an already admitted write.\n */\nexport interface DocumentMutationGuard {\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface DocumentMutationOptions extends DocumentMutationGuard {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\nexport type RemoveDocumentRow = (\n id: string,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"restoreContent\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n readonly seedTag?: string | undefined;\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: (\n proof: DocumentRotationProofMode,\n ) => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n /** Whether local writes are queued that have not reached SQLite yet. */\n hasQueuedWrites: () => boolean;\n /**\n * Whether applied local edits have not reached SQLite, e.g. after a failed\n * save, even though no write is queued any more.\n */\n hasUnsavedLocalEdits: () => boolean;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /**\n * Write a past version's text, structured fields, and rows back as one\n * ordinary local edit; attachments are left as they are. Nothing is rewound:\n * the restore is new operations that sync and merge like any other write.\n * Resolves true when the document durably holds the content, false when\n * the restore was refused or did not persist.\n */\n restoreContent: (\n content: DocumentRestoreContent,\n options?: DocumentMutationGuard | undefined,\n ) => Promise<boolean>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}
|
|
@@ -6,4 +6,4 @@ export interface PreparedUploadDocumentAttachmentRequest extends UploadDocumentA
|
|
|
6
6
|
readonly sourceSnapshot?: BlobSourceSnapshot | undefined;
|
|
7
7
|
readonly onStageUnavailable?: ((stageId: string) => Promise<void>) | undefined;
|
|
8
8
|
}
|
|
9
|
-
export declare function uploadPreparedDocumentAttachment(blobs: BlobAttachmentCollaborators, { author, blobId, bindingId, bytes, contentKey, contentKeyEpoch, documentId, documentSync, eventId, expectedBindingId, isRemoteSyncBlocked, nonceSeed, multipart, onMultipartProgress, onStageResolved, onStageUnavailable, resolveProjectionUserKey, signedAt, slotId, sourceSnapshot, warmReferencedPrincipalPolicies, writerProjection, }: PreparedUploadDocumentAttachmentRequest): Promise<UploadDocumentAttachmentResult | null>;
|
|
9
|
+
export declare function uploadPreparedDocumentAttachment(blobs: BlobAttachmentCollaborators, { author, blobId, bindingId, bytes, contentKey, contentKeyEpoch, documentId, documentSync, eventId, expectedBindingId, isRemoteSyncBlocked, nonceSeed, multipart, onMultipartProgress, onStageResolved, onStageUnavailable, resolveProjectionUserKey, signedAt, slotId, sourceSnapshot, stillCurrent, warmReferencedPrincipalPolicies, writerProjection, }: PreparedUploadDocumentAttachmentRequest): Promise<UploadDocumentAttachmentResult | null>;
|
|
@@ -108,9 +108,14 @@ function bindRefusedCarriedSync(apiClient, blobId) {
|
|
|
108
108
|
* without it, and the caller's queued row then syncs on its own.
|
|
109
109
|
*/
|
|
110
110
|
async function bindCarryingDocumentSync(input) {
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
111
|
+
const canBind = () => input.stillCurrent?.() !== false &&
|
|
112
|
+
!input.isRemoteSyncBlocked?.(input.organizationId);
|
|
113
|
+
const bind = (request) => !canBind()
|
|
114
|
+
? null
|
|
115
|
+
: input.apiClient.bindBlobAttachment(input.blobId, request, {
|
|
116
|
+
expectedPaymentRequiredOrganizationId: input.organizationId,
|
|
117
|
+
stillCurrent: canBind,
|
|
118
|
+
});
|
|
114
119
|
if (input.documentSync) {
|
|
115
120
|
const request = { ...input.plainRequest, documentSync: input.documentSync };
|
|
116
121
|
const response = await bind(request);
|
|
@@ -123,6 +128,18 @@ async function bindCarryingDocumentSync(input) {
|
|
|
123
128
|
response: await bind(input.plainRequest),
|
|
124
129
|
};
|
|
125
130
|
}
|
|
131
|
+
function stageBlobBytes(input) {
|
|
132
|
+
return stageMultipartBlobAttachment({
|
|
133
|
+
stillCurrent: input.stillCurrent,
|
|
134
|
+
organizationId: input.material.manifestIdentity.organizationId,
|
|
135
|
+
apiClient: input.apiClient,
|
|
136
|
+
encryption: input.material.encrypted,
|
|
137
|
+
multipart: input.multipart,
|
|
138
|
+
onMultipartProgress: input.onMultipartProgress,
|
|
139
|
+
onStageResolved: input.onStageResolved,
|
|
140
|
+
onStageUnavailable: input.onStageUnavailable,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
126
143
|
async function stageAndBindBlobAttachment(input) {
|
|
127
144
|
const { body, event } = await signBlobAttachmentEvent({
|
|
128
145
|
author: input.author,
|
|
@@ -147,15 +164,7 @@ async function stageAndBindBlobAttachment(input) {
|
|
|
147
164
|
signedAt: input.signedAt,
|
|
148
165
|
targetHash: input.material.targetHash,
|
|
149
166
|
});
|
|
150
|
-
const stageId = await
|
|
151
|
-
organizationId: input.material.manifestIdentity.organizationId,
|
|
152
|
-
apiClient: input.apiClient,
|
|
153
|
-
encryption: input.material.encrypted,
|
|
154
|
-
multipart: input.multipart,
|
|
155
|
-
onMultipartProgress: input.onMultipartProgress,
|
|
156
|
-
onStageResolved: input.onStageResolved,
|
|
157
|
-
onStageUnavailable: input.onStageUnavailable,
|
|
158
|
-
});
|
|
167
|
+
const stageId = await stageBlobBytes(input);
|
|
159
168
|
if (!stageId) {
|
|
160
169
|
return null;
|
|
161
170
|
}
|
|
@@ -172,8 +181,10 @@ async function stageAndBindBlobAttachment(input) {
|
|
|
172
181
|
documentSync: input.documentSync,
|
|
173
182
|
organizationId: input.material.manifestIdentity.organizationId,
|
|
174
183
|
plainRequest,
|
|
184
|
+
stillCurrent: input.stillCurrent,
|
|
185
|
+
isRemoteSyncBlocked: input.isRemoteSyncBlocked,
|
|
175
186
|
});
|
|
176
|
-
if (!response) {
|
|
187
|
+
if (!response || input.stillCurrent?.() === false) {
|
|
177
188
|
return null;
|
|
178
189
|
}
|
|
179
190
|
await assertBlobAttachmentBindResponse({
|
|
@@ -199,7 +210,11 @@ async function stageAndBindBlobAttachment(input) {
|
|
|
199
210
|
writeHeaderHash,
|
|
200
211
|
};
|
|
201
212
|
}
|
|
202
|
-
|
|
213
|
+
function isStaleUploadProjection(error) {
|
|
214
|
+
return shouldRetryWithFreshProjection(error, (message) => message.startsWith("Container writer projection KEK") &&
|
|
215
|
+
message.includes("could not be unwrapped"));
|
|
216
|
+
}
|
|
217
|
+
export async function uploadPreparedDocumentAttachment(blobs, { author, blobId = crypto.randomUUID(), bindingId = crypto.randomUUID(), bytes, contentKey = crypto.getRandomValues(new Uint8Array(32)), contentKeyEpoch = 1, documentId, documentSync, eventId = crypto.randomUUID(), expectedBindingId, isRemoteSyncBlocked, nonceSeed, multipart, onMultipartProgress, onStageResolved, onStageUnavailable, resolveProjectionUserKey, signedAt = new Date().toISOString(), slotId, sourceSnapshot, stillCurrent, warmReferencedPrincipalPolicies, writerProjection, }) {
|
|
203
218
|
const { api: apiClient, execSql } = blobs;
|
|
204
219
|
const targetSecretKey = requireEncapsulationSecretKey(blobs, "Document attachment upload");
|
|
205
220
|
if (contentKey.byteLength !== 32) {
|
|
@@ -222,6 +237,7 @@ export async function uploadPreparedDocumentAttachment(blobs, { author, blobId =
|
|
|
222
237
|
resolveProjectionUserKey: resolveProjectionUserKeyForUpload,
|
|
223
238
|
source,
|
|
224
239
|
sourceSnapshot,
|
|
240
|
+
stillCurrent,
|
|
225
241
|
targetSecretKey,
|
|
226
242
|
warmReferencedPrincipalPolicies,
|
|
227
243
|
writerProjection: freshWriterProjection,
|
|
@@ -231,9 +247,9 @@ export async function uploadPreparedDocumentAttachment(blobs, { author, blobId =
|
|
|
231
247
|
material = await buildMaterial(writerProjection);
|
|
232
248
|
}
|
|
233
249
|
catch (error) {
|
|
234
|
-
if (
|
|
235
|
-
!
|
|
236
|
-
|
|
250
|
+
if (stillCurrent?.() === false ||
|
|
251
|
+
!apiClient.evictDocumentWriterProjection ||
|
|
252
|
+
!isStaleUploadProjection(error)) {
|
|
237
253
|
throw error;
|
|
238
254
|
}
|
|
239
255
|
// The attachment binds to this document; only its projection was stale, so
|
|
@@ -255,6 +271,8 @@ export async function uploadPreparedDocumentAttachment(blobs, { author, blobId =
|
|
|
255
271
|
eventId,
|
|
256
272
|
expectedBindingId,
|
|
257
273
|
material,
|
|
274
|
+
stillCurrent,
|
|
275
|
+
isRemoteSyncBlocked,
|
|
258
276
|
multipart: resolvedMultipart,
|
|
259
277
|
onMultipartProgress,
|
|
260
278
|
onStageResolved,
|
|
@@ -262,7 +280,7 @@ export async function uploadPreparedDocumentAttachment(blobs, { author, blobId =
|
|
|
262
280
|
signedAt,
|
|
263
281
|
slotId,
|
|
264
282
|
});
|
|
265
|
-
if (!result) {
|
|
283
|
+
if (!result || stillCurrent?.() === false) {
|
|
266
284
|
return null;
|
|
267
285
|
}
|
|
268
286
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,6BAA6B,EAC7B,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAEL,6BAA6B,GAC9B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAA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KAAK,EACL,CAAC,OAAO,EAAE,EAAE,CACV,OAAO,CAAC,UAAU,CAAC,iCAAiC,CAAC;gBACrD,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAAC,CAC7C,EACD,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QAED,2EAA2E;QAC3E,+DAA+D;QAC/D,SAAS,CAAC,6BAA6B,CAAC,UAAU,CAAC,CAAC;QACpD,QAAQ,GAAG,MAAM,aAAa,CAAC,SAAS,CAAC,CAAC;IAC5C,CAAC;IACD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,0BAA0B,CAAC;QAC9C,SAAS;QACT,MAAM;QACN,SAAS;QACT,MAAM;QACN,eAAe;QACf,UAAU;QACV,YAAY;QACZ,OAAO;QACP,iBAAiB;QACjB,QAAQ;QACR,SAAS,EAAE,iBAAiB;QAC5B,mBAAmB;QACnB,eAAe;QACf,kBAAkB;QAClB,QAAQ;QACR,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,MAAM;QACN,SAAS;QACT,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,GAAG,MAAM;KACV,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AttachmentBindAccessEventBody,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport {\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobContentKeyBundleRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type { BlobAttachmentBindResponse } from \"@tearleads/validators/response\";\nimport type { BlobSourceSnapshot } from \"../../../data/blobs/attachments/blobSourceSnapshot\";\nimport {\n type BlobAttachmentCollaborators,\n requireEncapsulationSecretKey,\n} from \"../../../data/blobs/attachments/collaborators\";\nimport { prepareBlobEncryption } from \"../../../data/blobs/attachments/crypto\";\nimport {\n signBlobAttachmentEvent,\n signBlobAttachmentWriteHeader,\n} from \"../../../data/blobs/attachments/events\";\nimport {\n verifiedBlobWrapTargetsFromDocumentProjection,\n wrapBlobContentKey,\n} from \"../../../data/blobs/attachments/projection\";\nimport { assertBlobAttachmentBindResponse } from \"../../../data/blobs/attachments/responses\";\nimport type {\n BlobAttachmentApi,\n BlobAttachmentMaterial,\n MultipartStageResolvedListener,\n MultipartUploadProgressListener,\n UploadDocumentAttachmentRequest,\n UploadDocumentAttachmentResult,\n} from \"../../../data/blobs/attachments/types\";\nimport {\n type BlobByteSource,\n createBlobByteSource,\n} from \"../../../data/blobs/blobContracts\";\nimport {\n authorizingContainerPathRefs,\n shouldRetryWithFreshProjection,\n} from \"../../../data/documents/shared/projection\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport type { DocumentCreateAuthor } from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { resolveBlobMutationWriterProjection } from \"../verification/writerProjection\";\nimport { resolveMultipartUploadOptions } from \"./automaticMultipartUpload\";\nimport { stageMultipartBlobAttachment } from \"./multipartUpload\";\n\nasync function buildBlobAttachmentMaterial(\n input: {\n apiClient: BlobAttachmentApi;\n bindingId: string;\n blobId: string;\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n execSql?: ExecSql | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n nonceSeed?: Uint8Array | undefined;\n partSize: number;\n source: BlobByteSource;\n sourceSnapshot?: BlobSourceSnapshot | undefined;\n targetSecretKey: Uint8Array;\n writerProjection?: UploadDocumentAttachmentRequest[\"writerProjection\"];\n } & ProjectionVerificationOptions,\n): Promise<BlobAttachmentMaterial | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n errorLabel: \"Blob attachment\",\n execSql: input.execSql,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection } = resolved;\n\n const targets = verifiedBlobWrapTargetsFromDocumentProjection({\n bindingId: input.bindingId,\n documentId: input.documentId,\n writerProjection,\n });\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n const contentKeyBundle: BlobContentKeyBundleRequest = {\n contentKeyEpoch: input.contentKeyEpoch,\n targetHash,\n targets: await wrapBlobContentKey({\n blobId: input.blobId,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n targets,\n writerProjection,\n ...projectionVerificationOptions(input),\n }),\n };\n const encrypted = await prepareBlobEncryption({\n blobId: input.blobId,\n chunkSize: input.partSize,\n contentKey: input.contentKey,\n contentKeyBundle,\n nonceSeed: input.nonceSeed,\n organizationId: manifestIdentity.organizationId,\n source: input.source,\n sourceSnapshot: input.sourceSnapshot,\n });\n const blobAccessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: input.blobId,\n organizationId: manifestIdentity.organizationId,\n activeBindingIds: [input.bindingId],\n documentManifestHashes: [manifestIdentity.manifestHash],\n linkedContainerManifestHashes: uniqueSortedStrings(\n targets.map((target) => target.containerManifestHash),\n ),\n linkedContainerKeyEpochIds: uniqueSortedStrings(\n targets.map((target) => target.containerKeyEpochId),\n ),\n blobKeyTargetHash: targetHash,\n });\n\n return {\n blobAccessManifestHash,\n contentKeyBundle,\n encrypted,\n manifestIdentity,\n targetHash,\n targets,\n writerProjection,\n };\n}\n\nfunction blobAttachmentBindRequest(input: {\n body: AttachmentBindAccessEventBody;\n event: AccessEvent;\n material: BlobAttachmentMaterial;\n stageId: string;\n writeHeader: WriteHeader;\n}): BlobAttachmentBindRequest {\n return {\n event: readCanonicalRecord(input.event, \"Blob attachment bind event\"),\n body: readCanonicalRecord(input.body, \"Blob attachment bind body\"),\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n contentKeyBundle: input.material.contentKeyBundle,\n stagedBlob: {\n stageId: input.stageId,\n writeHeader: readCanonicalRecord(\n input.writeHeader,\n \"Blob attachment write header\",\n ),\n },\n };\n}\n\n/**\n * Whether the server refused the bind outright (a client error other than a\n * billing pause or an expired session), which rolled back the binding with\n * the update it carried.\n */\nfunction bindRefusedCarriedSync(\n apiClient: BlobAttachmentApi,\n blobId: string,\n): boolean {\n const failure = apiClient.getRequestFailure?.({\n method: \"POST\",\n path: `/blobs/${encodeURIComponent(blobId)}/attachment-bindings`,\n });\n return (\n failure?.kind === \"http\" &&\n failure.status !== null &&\n [400, 403, 404, 409].includes(failure.status)\n );\n}\n\n/**\n * The carried update adds no failure mode: a refused carry binds once more\n * without it, and the caller's queued row then syncs on its own.\n */\nasync function bindCarryingDocumentSync(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly blobId: string;\n readonly documentSync: DocumentSyncRequest | undefined;\n readonly organizationId: string;\n readonly plainRequest: BlobAttachmentBindRequest;\n}): Promise<{\n readonly request: BlobAttachmentBindRequest;\n readonly response: BlobAttachmentBindResponse | null;\n}> {\n const bind = (request: BlobAttachmentBindRequest) =>\n input.apiClient.bindBlobAttachment(input.blobId, request, {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n });\n if (input.documentSync) {\n const request = { ...input.plainRequest, documentSync: input.documentSync };\n const response = await bind(request);\n if (response || !bindRefusedCarriedSync(input.apiClient, input.blobId)) {\n return { request, response };\n }\n }\n return {\n request: input.plainRequest,\n response: await bind(input.plainRequest),\n };\n}\n\nasync function stageAndBindBlobAttachment(input: {\n apiClient: BlobAttachmentApi;\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n contentKeyEpoch: number;\n documentId: string;\n documentSync?: DocumentSyncRequest | undefined;\n eventId: string;\n expectedBindingId: string | null;\n material: BlobAttachmentMaterial;\n multipart: NonNullable<UploadDocumentAttachmentRequest[\"multipart\"]>;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n onStageUnavailable?: ((stageId: string) => Promise<void>) | undefined;\n signedAt: string;\n slotId: string;\n}): Promise<{\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n} | null> {\n const { body, event } = await signBlobAttachmentEvent({\n author: input.author,\n bindingId: input.bindingId,\n blobId: input.blobId,\n documentId: input.documentId,\n eventId: input.eventId,\n expectedBindingId: input.expectedBindingId,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n slotId: input.slotId,\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n });\n const { writeHeader, writeHeaderHash } = await signBlobAttachmentWriteHeader({\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n author: input.author,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n encrypted: input.material.encrypted,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n targetHash: input.material.targetHash,\n });\n const stageId = await stageMultipartBlobAttachment({\n organizationId: input.material.manifestIdentity.organizationId,\n apiClient: input.apiClient,\n encryption: input.material.encrypted,\n multipart: input.multipart,\n onMultipartProgress: input.onMultipartProgress,\n onStageResolved: input.onStageResolved,\n onStageUnavailable: input.onStageUnavailable,\n });\n if (!stageId) {\n return null;\n }\n\n const plainRequest = blobAttachmentBindRequest({\n body,\n event,\n material: input.material,\n stageId,\n writeHeader,\n });\n const { request, response } = await bindCarryingDocumentSync({\n apiClient: input.apiClient,\n blobId: input.blobId,\n documentSync: input.documentSync,\n organizationId: input.material.manifestIdentity.organizationId,\n plainRequest,\n });\n if (!response) {\n return null;\n }\n\n await assertBlobAttachmentBindResponse({\n body,\n bindingId: input.bindingId,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyBundle: input.material.contentKeyBundle,\n documentId: input.documentId,\n event,\n manifestIdentity: input.material.manifestIdentity,\n response,\n slotId: input.slotId,\n targetHash: input.material.targetHash,\n writeHeaderHash,\n });\n\n return {\n request,\n response,\n sha256: input.material.encrypted.sha256,\n byteLength: input.material.encrypted.byteLength,\n writeHeader,\n writeHeaderHash,\n };\n}\n\n/** An upload whose source `inspectBlobSource` already snapshotted. */\nexport interface PreparedUploadDocumentAttachmentRequest\n extends UploadDocumentAttachmentRequest {\n readonly sourceSnapshot?: BlobSourceSnapshot | undefined;\n readonly onStageUnavailable?:\n | ((stageId: string) => Promise<void>)\n | undefined;\n}\n\nexport async function uploadPreparedDocumentAttachment(\n blobs: BlobAttachmentCollaborators,\n {\n author,\n blobId = crypto.randomUUID(),\n bindingId = crypto.randomUUID(),\n bytes,\n contentKey = crypto.getRandomValues(new Uint8Array(32)),\n contentKeyEpoch = 1,\n documentId,\n documentSync,\n eventId = crypto.randomUUID(),\n expectedBindingId,\n isRemoteSyncBlocked,\n nonceSeed,\n multipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n sourceSnapshot,\n warmReferencedPrincipalPolicies,\n writerProjection,\n }: PreparedUploadDocumentAttachmentRequest,\n): Promise<UploadDocumentAttachmentResult | null> {\n const { api: apiClient, execSql } = blobs;\n const targetSecretKey = requireEncapsulationSecretKey(\n blobs,\n \"Document attachment upload\",\n );\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Blob content key must be 32 bytes\");\n }\n const resolveProjectionUserKeyForUpload = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment upload\",\n );\n const resolvedMultipart = resolveMultipartUploadOptions(multipart);\n const source = createBlobByteSource(bytes);\n\n const buildMaterial = (\n freshWriterProjection: UploadDocumentAttachmentRequest[\"writerProjection\"],\n ) =>\n buildBlobAttachmentMaterial({\n apiClient,\n bindingId,\n blobId,\n contentKey,\n contentKeyEpoch,\n documentId,\n execSql,\n isRemoteSyncBlocked,\n nonceSeed,\n partSize: resolvedMultipart.partSize,\n resolveProjectionUserKey: resolveProjectionUserKeyForUpload,\n source,\n sourceSnapshot,\n targetSecretKey,\n warmReferencedPrincipalPolicies,\n writerProjection: freshWriterProjection,\n });\n let material: BlobAttachmentMaterial | null;\n try {\n material = await buildMaterial(writerProjection);\n } catch (error) {\n if (\n !apiClient.evictDocumentWriterProjection ||\n !shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\"Container writer projection KEK\") &&\n message.includes(\"could not be unwrapped\"),\n )\n ) {\n throw error;\n }\n\n // The attachment binds to this document; only its projection was stale, so\n // evict just it rather than wiping the whole projection cache.\n apiClient.evictDocumentWriterProjection(documentId);\n material = await buildMaterial(undefined);\n }\n if (!material) {\n return null;\n }\n const result = await stageAndBindBlobAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n contentKeyEpoch,\n documentId,\n documentSync,\n eventId,\n expectedBindingId,\n material,\n multipart: resolvedMultipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n signedAt,\n slotId,\n });\n if (!result) {\n return null;\n }\n\n return {\n blobId,\n bindingId,\n writerProjection: material.writerProjection,\n ...result,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,6BAA6B,EAC7B,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAEL,6BAA6B,GAC9B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,M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,mBAAmB;QACnB,SAAS,EAAE,iBAAiB;QAC5B,mBAAmB;QACnB,eAAe;QACf,kBAAkB;QAClB,QAAQ;QACR,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,IAAI,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QAC1C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,MAAM;QACN,SAAS;QACT,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,GAAG,MAAM;KACV,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AttachmentBindAccessEventBody,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport {\n computeBlobAccessManifestHash,\n computeBlobContentKeyTargetHash,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobContentKeyBundleRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type { BlobAttachmentBindResponse } from \"@tearleads/validators/response\";\nimport type { BlobSourceSnapshot } from \"../../../data/blobs/attachments/blobSourceSnapshot\";\nimport {\n type BlobAttachmentCollaborators,\n requireEncapsulationSecretKey,\n} from \"../../../data/blobs/attachments/collaborators\";\nimport { prepareBlobEncryption } from \"../../../data/blobs/attachments/crypto\";\nimport {\n signBlobAttachmentEvent,\n signBlobAttachmentWriteHeader,\n} from \"../../../data/blobs/attachments/events\";\nimport {\n verifiedBlobWrapTargetsFromDocumentProjection,\n wrapBlobContentKey,\n} from \"../../../data/blobs/attachments/projection\";\nimport { assertBlobAttachmentBindResponse } from \"../../../data/blobs/attachments/responses\";\nimport type {\n BlobAttachmentApi,\n BlobAttachmentMaterial,\n MultipartStageResolvedListener,\n MultipartUploadProgressListener,\n UploadDocumentAttachmentRequest,\n UploadDocumentAttachmentResult,\n} from \"../../../data/blobs/attachments/types\";\nimport {\n type BlobByteSource,\n createBlobByteSource,\n} from \"../../../data/blobs/blobContracts\";\nimport {\n authorizingContainerPathRefs,\n shouldRetryWithFreshProjection,\n} from \"../../../data/documents/shared/projection\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport type { DocumentCreateAuthor } from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { resolveBlobMutationWriterProjection } from \"../verification/writerProjection\";\nimport { resolveMultipartUploadOptions } from \"./automaticMultipartUpload\";\nimport { stageMultipartBlobAttachment } from \"./multipartUpload\";\n\nasync function buildBlobAttachmentMaterial(\n input: {\n apiClient: BlobAttachmentApi;\n bindingId: string;\n blobId: string;\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n execSql?: ExecSql | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n nonceSeed?: Uint8Array | undefined;\n partSize: number;\n source: BlobByteSource;\n sourceSnapshot?: BlobSourceSnapshot | undefined;\n targetSecretKey: Uint8Array;\n writerProjection?: UploadDocumentAttachmentRequest[\"writerProjection\"];\n } & ProjectionVerificationOptions,\n): Promise<BlobAttachmentMaterial | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n errorLabel: \"Blob attachment\",\n execSql: input.execSql,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection } = resolved;\n\n const targets = verifiedBlobWrapTargetsFromDocumentProjection({\n bindingId: input.bindingId,\n documentId: input.documentId,\n writerProjection,\n });\n const targetHash = await computeBlobContentKeyTargetHash(targets);\n const contentKeyBundle: BlobContentKeyBundleRequest = {\n contentKeyEpoch: input.contentKeyEpoch,\n targetHash,\n targets: await wrapBlobContentKey({\n blobId: input.blobId,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n targets,\n writerProjection,\n ...projectionVerificationOptions(input),\n }),\n };\n const encrypted = await prepareBlobEncryption({\n blobId: input.blobId,\n chunkSize: input.partSize,\n contentKey: input.contentKey,\n contentKeyBundle,\n nonceSeed: input.nonceSeed,\n organizationId: manifestIdentity.organizationId,\n source: input.source,\n sourceSnapshot: input.sourceSnapshot,\n });\n const blobAccessManifestHash = await computeBlobAccessManifestHash({\n version: 1,\n blobId: input.blobId,\n organizationId: manifestIdentity.organizationId,\n activeBindingIds: [input.bindingId],\n documentManifestHashes: [manifestIdentity.manifestHash],\n linkedContainerManifestHashes: uniqueSortedStrings(\n targets.map((target) => target.containerManifestHash),\n ),\n linkedContainerKeyEpochIds: uniqueSortedStrings(\n targets.map((target) => target.containerKeyEpochId),\n ),\n blobKeyTargetHash: targetHash,\n });\n\n return {\n blobAccessManifestHash,\n contentKeyBundle,\n encrypted,\n manifestIdentity,\n targetHash,\n targets,\n writerProjection,\n };\n}\n\nfunction blobAttachmentBindRequest(input: {\n body: AttachmentBindAccessEventBody;\n event: AccessEvent;\n material: BlobAttachmentMaterial;\n stageId: string;\n writeHeader: WriteHeader;\n}): BlobAttachmentBindRequest {\n return {\n event: readCanonicalRecord(input.event, \"Blob attachment bind event\"),\n body: readCanonicalRecord(input.body, \"Blob attachment bind body\"),\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n contentKeyBundle: input.material.contentKeyBundle,\n stagedBlob: {\n stageId: input.stageId,\n writeHeader: readCanonicalRecord(\n input.writeHeader,\n \"Blob attachment write header\",\n ),\n },\n };\n}\n\n/**\n * Whether the server refused the bind outright (a client error other than a\n * billing pause or an expired session), which rolled back the binding with\n * the update it carried.\n */\nfunction bindRefusedCarriedSync(\n apiClient: BlobAttachmentApi,\n blobId: string,\n): boolean {\n const failure = apiClient.getRequestFailure?.({\n method: \"POST\",\n path: `/blobs/${encodeURIComponent(blobId)}/attachment-bindings`,\n });\n return (\n failure?.kind === \"http\" &&\n failure.status !== null &&\n [400, 403, 404, 409].includes(failure.status)\n );\n}\n\n/**\n * The carried update adds no failure mode: a refused carry binds once more\n * without it, and the caller's queued row then syncs on its own.\n */\nasync function bindCarryingDocumentSync(input: {\n readonly apiClient: BlobAttachmentApi;\n readonly blobId: string;\n readonly documentSync: DocumentSyncRequest | undefined;\n readonly organizationId: string;\n readonly plainRequest: BlobAttachmentBindRequest;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly isRemoteSyncBlocked?: UploadDocumentAttachmentRequest[\"isRemoteSyncBlocked\"];\n}): Promise<{\n readonly request: BlobAttachmentBindRequest;\n readonly response: BlobAttachmentBindResponse | null;\n}> {\n const canBind = () =>\n input.stillCurrent?.() !== false &&\n !input.isRemoteSyncBlocked?.(input.organizationId);\n const bind = (request: BlobAttachmentBindRequest) =>\n !canBind()\n ? null\n : input.apiClient.bindBlobAttachment(input.blobId, request, {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n stillCurrent: canBind,\n });\n if (input.documentSync) {\n const request = { ...input.plainRequest, documentSync: input.documentSync };\n const response = await bind(request);\n if (response || !bindRefusedCarriedSync(input.apiClient, input.blobId)) {\n return { request, response };\n }\n }\n return {\n request: input.plainRequest,\n response: await bind(input.plainRequest),\n };\n}\n\ninterface StageAndBindInput {\n stillCurrent?: (() => boolean) | undefined;\n apiClient: BlobAttachmentApi;\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n contentKeyEpoch: number;\n documentId: string;\n documentSync?: DocumentSyncRequest | undefined;\n eventId: string;\n expectedBindingId: string | null;\n isRemoteSyncBlocked?: UploadDocumentAttachmentRequest[\"isRemoteSyncBlocked\"];\n material: BlobAttachmentMaterial;\n multipart: NonNullable<UploadDocumentAttachmentRequest[\"multipart\"]>;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n onStageUnavailable?: ((stageId: string) => Promise<void>) | undefined;\n signedAt: string;\n slotId: string;\n}\n\nfunction stageBlobBytes(input: StageAndBindInput) {\n return stageMultipartBlobAttachment({\n stillCurrent: input.stillCurrent,\n organizationId: input.material.manifestIdentity.organizationId,\n apiClient: input.apiClient,\n encryption: input.material.encrypted,\n multipart: input.multipart,\n onMultipartProgress: input.onMultipartProgress,\n onStageResolved: input.onStageResolved,\n onStageUnavailable: input.onStageUnavailable,\n });\n}\n\nasync function stageAndBindBlobAttachment(input: StageAndBindInput): Promise<{\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n} | null> {\n const { body, event } = await signBlobAttachmentEvent({\n author: input.author,\n bindingId: input.bindingId,\n blobId: input.blobId,\n documentId: input.documentId,\n eventId: input.eventId,\n expectedBindingId: input.expectedBindingId,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n slotId: input.slotId,\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n });\n const { writeHeader, writeHeaderHash } = await signBlobAttachmentWriteHeader({\n authorizingContainerPathRefs: authorizingContainerPathRefs(\n input.material.writerProjection,\n ),\n author: input.author,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyEpoch: input.contentKeyEpoch,\n encrypted: input.material.encrypted,\n manifestIdentity: input.material.manifestIdentity,\n signedAt: input.signedAt,\n targetHash: input.material.targetHash,\n });\n const stageId = await stageBlobBytes(input);\n if (!stageId) {\n return null;\n }\n\n const plainRequest = blobAttachmentBindRequest({\n body,\n event,\n material: input.material,\n stageId,\n writeHeader,\n });\n const { request, response } = await bindCarryingDocumentSync({\n apiClient: input.apiClient,\n blobId: input.blobId,\n documentSync: input.documentSync,\n organizationId: input.material.manifestIdentity.organizationId,\n plainRequest,\n stillCurrent: input.stillCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n });\n if (!response || input.stillCurrent?.() === false) {\n return null;\n }\n\n await assertBlobAttachmentBindResponse({\n body,\n bindingId: input.bindingId,\n blobAccessManifestHash: input.material.blobAccessManifestHash,\n blobId: input.blobId,\n contentKeyBundle: input.material.contentKeyBundle,\n documentId: input.documentId,\n event,\n manifestIdentity: input.material.manifestIdentity,\n response,\n slotId: input.slotId,\n targetHash: input.material.targetHash,\n writeHeaderHash,\n });\n\n return {\n request,\n response,\n sha256: input.material.encrypted.sha256,\n byteLength: input.material.encrypted.byteLength,\n writeHeader,\n writeHeaderHash,\n };\n}\n\n/** An upload whose source `inspectBlobSource` already snapshotted. */\nexport interface PreparedUploadDocumentAttachmentRequest\n extends UploadDocumentAttachmentRequest {\n readonly sourceSnapshot?: BlobSourceSnapshot | undefined;\n readonly onStageUnavailable?:\n | ((stageId: string) => Promise<void>)\n | undefined;\n}\n\nfunction isStaleUploadProjection(error: unknown) {\n return shouldRetryWithFreshProjection(\n error,\n (message) =>\n message.startsWith(\"Container writer projection KEK\") &&\n message.includes(\"could not be unwrapped\"),\n );\n}\n\nexport async function uploadPreparedDocumentAttachment(\n blobs: BlobAttachmentCollaborators,\n {\n author,\n blobId = crypto.randomUUID(),\n bindingId = crypto.randomUUID(),\n bytes,\n contentKey = crypto.getRandomValues(new Uint8Array(32)),\n contentKeyEpoch = 1,\n documentId,\n documentSync,\n eventId = crypto.randomUUID(),\n expectedBindingId,\n isRemoteSyncBlocked,\n nonceSeed,\n multipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n sourceSnapshot,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n }: PreparedUploadDocumentAttachmentRequest,\n): Promise<UploadDocumentAttachmentResult | null> {\n const { api: apiClient, execSql } = blobs;\n const targetSecretKey = requireEncapsulationSecretKey(\n blobs,\n \"Document attachment upload\",\n );\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Blob content key must be 32 bytes\");\n }\n const resolveProjectionUserKeyForUpload = requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment upload\",\n );\n const resolvedMultipart = resolveMultipartUploadOptions(multipart);\n const source = createBlobByteSource(bytes);\n\n const buildMaterial = (\n freshWriterProjection: UploadDocumentAttachmentRequest[\"writerProjection\"],\n ) =>\n buildBlobAttachmentMaterial({\n apiClient,\n bindingId,\n blobId,\n contentKey,\n contentKeyEpoch,\n documentId,\n execSql,\n isRemoteSyncBlocked,\n nonceSeed,\n partSize: resolvedMultipart.partSize,\n resolveProjectionUserKey: resolveProjectionUserKeyForUpload,\n source,\n sourceSnapshot,\n stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies,\n writerProjection: freshWriterProjection,\n });\n let material: BlobAttachmentMaterial | null;\n try {\n material = await buildMaterial(writerProjection);\n } catch (error) {\n if (\n stillCurrent?.() === false ||\n !apiClient.evictDocumentWriterProjection ||\n !isStaleUploadProjection(error)\n ) {\n throw error;\n }\n\n // The attachment binds to this document; only its projection was stale, so\n // evict just it rather than wiping the whole projection cache.\n apiClient.evictDocumentWriterProjection(documentId);\n material = await buildMaterial(undefined);\n }\n if (!material) {\n return null;\n }\n const result = await stageAndBindBlobAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n contentKeyEpoch,\n documentId,\n documentSync,\n eventId,\n expectedBindingId,\n material,\n stillCurrent,\n isRemoteSyncBlocked,\n multipart: resolvedMultipart,\n onMultipartProgress,\n onStageResolved,\n onStageUnavailable,\n signedAt,\n slotId,\n });\n if (!result || stillCurrent?.() === false) {\n return null;\n }\n\n return {\n blobId,\n bindingId,\n writerProjection: material.writerProjection,\n ...result,\n };\n}\n"]}
|
|
@@ -3,8 +3,16 @@ import { assertMultipartStageReplaceable, multipartApiFailureMessage, } from "./
|
|
|
3
3
|
function isMultipartStageStatus(stage) {
|
|
4
4
|
return "completed" in stage && typeof stage.completed === "boolean";
|
|
5
5
|
}
|
|
6
|
+
export function assertUploadCurrent(stillCurrent) {
|
|
7
|
+
if (stillCurrent?.() === false)
|
|
8
|
+
throw new Error("The attachment upload scope changed.");
|
|
9
|
+
}
|
|
6
10
|
async function resumeMultipartStage(input, resumeStageId) {
|
|
7
|
-
|
|
11
|
+
assertUploadCurrent(input.stillCurrent);
|
|
12
|
+
const resumed = await input.apiClient.getMultipartBlobStage(resumeStageId, {
|
|
13
|
+
stillCurrent: input.stillCurrent,
|
|
14
|
+
});
|
|
15
|
+
assertUploadCurrent(input.stillCurrent);
|
|
8
16
|
if (!resumed) {
|
|
9
17
|
await assertMultipartStageReplaceable({
|
|
10
18
|
apiClient: input.apiClient,
|
|
@@ -28,12 +36,14 @@ async function resumeMultipartStage(input, resumeStageId) {
|
|
|
28
36
|
}
|
|
29
37
|
async function initiateWithFirstParts(input, firstParts) {
|
|
30
38
|
const { byteLength, sha256 } = input.encryption;
|
|
39
|
+
assertUploadCurrent(input.stillCurrent);
|
|
31
40
|
const stage = await input.apiClient.initiateMultipartBlobStage({
|
|
32
41
|
organizationId: input.organizationId,
|
|
33
42
|
byteLength,
|
|
34
43
|
firstParts: [...firstParts.descriptors],
|
|
35
44
|
sha256,
|
|
36
|
-
});
|
|
45
|
+
}, { stillCurrent: input.stillCurrent });
|
|
46
|
+
assertUploadCurrent(input.stillCurrent);
|
|
37
47
|
if (!stage) {
|
|
38
48
|
throw new Error(multipartApiFailureMessage({
|
|
39
49
|
apiClient: input.apiClient,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multipartStageResolution.js","sourceRoot":"","sources":["multipartStageResolution.ts"],"names":[],"mappings":"AASA,OAAO,EAIL,0BAA0B,EAC1B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,0BAA0B,CAAC;AAElC,SAAS,sBAAsB,CAC7B,KAA4E;IAE5E,OAAO,W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cesContent":["import type {\n InitiateMultipartBlobStageResponse,\n MultipartBlobStageStatusResponse,\n} from \"@tearleads/validators/response\";\nimport type { BlobEncryptionPlan } from \"../../../data/blobs/attachments/crypto\";\nimport type {\n BlobAttachmentApi,\n MultipartBlobUploadOptions,\n} from \"../../../data/blobs/attachments/types\";\nimport {\n type MultipartFirstParts,\n type MultipartPartSources,\n type PreparedFirstPart,\n prepareFirstMultipartParts,\n readIssuedPartSources,\n releasePreparedParts,\n} from \"./multipartFirstParts\";\nimport {\n assertMultipartStageReplaceable,\n multipartApiFailureMessage,\n} from \"./multipartStageFailures\";\n\nfunction isMultipartStageStatus(\n stage: InitiateMultipartBlobStageResponse | MultipartBlobStageStatusResponse,\n): stage is MultipartBlobStageStatusResponse {\n return \"completed\" in stage && typeof stage.completed === \"boolean\";\n}\n\nexport function assertUploadCurrent(stillCurrent: (() => boolean) | undefined) {\n if (stillCurrent?.() === false)\n throw new Error(\"The attachment upload scope changed.\");\n}\n\ninterface ResolveMultipartStageInput {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly apiClient: BlobAttachmentApi;\n readonly concurrency: number;\n readonly encryption: BlobEncryptionPlan;\n readonly multipart: MultipartBlobUploadOptions;\n readonly organizationId: string;\n readonly onStageUnavailable?:\n | ((stageId: string) => Promise<void>)\n | undefined;\n}\n\ninterface ResolvedMultipartStage {\n readonly prepared: Map<number, PreparedFirstPart>;\n readonly sources: MultipartPartSources;\n readonly status: MultipartBlobStageStatusResponse;\n}\n\nasync function resumeMultipartStage(\n input: ResolveMultipartStageInput,\n resumeStageId: string,\n): Promise<MultipartBlobStageStatusResponse | null> {\n assertUploadCurrent(input.stillCurrent);\n const resumed = await input.apiClient.getMultipartBlobStage(resumeStageId, {\n stillCurrent: input.stillCurrent,\n });\n assertUploadCurrent(input.stillCurrent);\n if (!resumed) {\n await assertMultipartStageReplaceable({\n apiClient: input.apiClient,\n onStageUnavailable: input.onStageUnavailable,\n stageId: resumeStageId,\n });\n return null;\n }\n if (resumed.stageId !== resumeStageId) {\n throw new Error(\n `Multipart blob resume response does not match stage ${resumeStageId}.`,\n );\n }\n // A successful lookup is authoritative: a metadata mismatch indicates\n // inconsistent persisted state or a bad server response, not proof that\n // the existing stage is safe to abandon.\n if (\n resumed.organizationId !== input.organizationId ||\n resumed.byteLength !== input.encryption.byteLength ||\n resumed.sha256 !== input.encryption.sha256\n ) {\n throw new Error(\n `Multipart blob resume stage ${resumeStageId} does not match the requested organization or bytes.`,\n );\n }\n return resumed;\n}\n\nasync function initiateWithFirstParts(\n input: ResolveMultipartStageInput,\n firstParts: MultipartFirstParts,\n): Promise<ResolvedMultipartStage> {\n const { byteLength, sha256 } = input.encryption;\n assertUploadCurrent(input.stillCurrent);\n const stage = await input.apiClient.initiateMultipartBlobStage(\n {\n organizationId: input.organizationId,\n byteLength,\n firstParts: [...firstParts.descriptors],\n sha256,\n },\n { stillCurrent: input.stillCurrent },\n );\n assertUploadCurrent(input.stillCurrent);\n if (!stage) {\n throw new Error(\n multipartApiFailureMessage({\n apiClient: input.apiClient,\n fallback: `Multipart blob stage initiation failed for ${byteLength.toLocaleString()} bytes.`,\n request: { method: \"POST\", path: \"/blobs/stages/multipart\" },\n }),\n );\n }\n if (\n stage.organizationId !== input.organizationId ||\n stage.byteLength !== byteLength ||\n stage.sha256 !== sha256\n ) {\n throw new Error(\n \"Multipart blob stage initiation response does not match its request.\",\n );\n }\n return {\n prepared: firstParts.prepared,\n sources: readIssuedPartSources(firstParts.descriptors, stage),\n status: isMultipartStageStatus(stage)\n ? stage\n : { ...stage, completed: false },\n };\n}\n\n// A new stage carries the parts the upload starts with, so their upload\n// sources come back with the stage instead of one authorization each. Their\n// bytes hold transfer-pool slots until uploaded, or until initiation fails.\nasync function initiateMultipartStage(\n input: ResolveMultipartStageInput,\n): Promise<ResolvedMultipartStage> {\n const firstParts = await prepareFirstMultipartParts(\n input.apiClient,\n input.encryption,\n input.concurrency,\n );\n try {\n return await initiateWithFirstParts(input, firstParts);\n } catch (error) {\n releasePreparedParts(firstParts.prepared);\n throw error;\n }\n}\n\nexport async function resolveMultipartStage(\n input: ResolveMultipartStageInput,\n): Promise<ResolvedMultipartStage> {\n const resumeStageId = input.multipart.resumeStageId;\n const resumed = resumeStageId\n ? await resumeMultipartStage(input, resumeStageId)\n : null;\n return resumed\n ? {\n prepared: new Map(),\n sources: { apiTransport: false, issued: new Map() },\n status: resumed,\n }\n : initiateMultipartStage(input);\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { MAX_MULTIPART_BLOB_PART_BYTES } from "../../../internal/validators/util
|
|
|
3
3
|
import { BLOB_TRANSFER_CONCURRENCY, runBlobTransfer, } from "../../../data/blobs/transferPool.js";
|
|
4
4
|
import { releasePreparedParts, sha256BytesHex, takePartSource, } from "./multipartFirstParts.js";
|
|
5
5
|
import { multipartApiFailureMessage, multipartStagePath, } from "./multipartStageFailures.js";
|
|
6
|
-
import { resolveMultipartStage } from "./multipartStageResolution.js";
|
|
6
|
+
import { assertUploadCurrent, resolveMultipartStage, } from "./multipartStageResolution.js";
|
|
7
7
|
const DEFAULT_MULTIPART_UPLOAD_CONCURRENCY = 4;
|
|
8
8
|
const MAX_MULTIPART_UPLOAD_CONCURRENCY = 4;
|
|
9
9
|
// Fetch exposes no upload progress on every host. Allow a slow shared uplink
|
|
@@ -60,6 +60,7 @@ async function uploadMultipartPartTasks(input) {
|
|
|
60
60
|
signal.addEventListener("abort", aborted, { once: true });
|
|
61
61
|
try {
|
|
62
62
|
const uploaded = await uploadMultipartPartBytes({
|
|
63
|
+
stillCurrent: input.stillCurrent,
|
|
63
64
|
apiClient: input.apiClient,
|
|
64
65
|
encryption: input.encryption,
|
|
65
66
|
prepared: input.prepared,
|
|
@@ -70,6 +71,7 @@ async function uploadMultipartPartTasks(input) {
|
|
|
70
71
|
signal,
|
|
71
72
|
});
|
|
72
73
|
signal.throwIfAborted();
|
|
74
|
+
assertUploadCurrent(input.stillCurrent);
|
|
73
75
|
if (!uploaded) {
|
|
74
76
|
failed = true;
|
|
75
77
|
throw new Error(multipartApiFailureMessage({
|
|
@@ -129,6 +131,7 @@ async function uploadMultipartPartBytes(input) {
|
|
|
129
131
|
input.signal.throwIfAborted();
|
|
130
132
|
const { bytes: encryptedPartBytes, sha256 } = await encryptedPart(input);
|
|
131
133
|
input.signal.throwIfAborted();
|
|
134
|
+
assertUploadCurrent(input.stillCurrent);
|
|
132
135
|
const source = takePartSource(input.sources, input.task.partNumber);
|
|
133
136
|
const uploaded = await input.apiClient.uploadMultipartBlobPartBytes(input.stageId, input.task.partNumber, {
|
|
134
137
|
byteLength: encryptedPartBytes.byteLength,
|
|
@@ -136,8 +139,9 @@ async function uploadMultipartPartBytes(input) {
|
|
|
136
139
|
sha256,
|
|
137
140
|
...(source === undefined ? {} : { source }),
|
|
138
141
|
uploadId: input.uploadId,
|
|
139
|
-
}, { signal: input.signal });
|
|
142
|
+
}, { signal: input.signal, stillCurrent: input.stillCurrent });
|
|
140
143
|
input.signal.throwIfAborted();
|
|
144
|
+
assertUploadCurrent(input.stillCurrent);
|
|
141
145
|
if (uploaded &&
|
|
142
146
|
(uploaded.stageId !== input.stageId ||
|
|
143
147
|
uploaded.uploadId !== input.uploadId ||
|
|
@@ -203,6 +207,7 @@ export async function stageMultipartBlobAttachment(input) {
|
|
|
203
207
|
assertMultipartPlanLimits(input.encryption);
|
|
204
208
|
const concurrency = normalizeMultipartUploadConcurrency(input.multipart.uploadConcurrency);
|
|
205
209
|
const resolved = await resolveMultipartStage({
|
|
210
|
+
stillCurrent: input.stillCurrent,
|
|
206
211
|
apiClient: input.apiClient,
|
|
207
212
|
concurrency,
|
|
208
213
|
encryption: input.encryption,
|
|
@@ -221,10 +226,12 @@ export async function stageMultipartBlobAttachment(input) {
|
|
|
221
226
|
async function uploadResolvedMultipartStage(input, concurrency, { prepared, sources, status, }) {
|
|
222
227
|
// Surface the stage id before any parts upload so the caller can persist it;
|
|
223
228
|
// an upload interrupted mid-flight can then resume this same stage.
|
|
229
|
+
assertUploadCurrent(input.stillCurrent);
|
|
224
230
|
await input.onStageResolved?.({
|
|
225
231
|
partSize: input.encryption.chunkSize,
|
|
226
232
|
stageId: status.stageId,
|
|
227
233
|
});
|
|
234
|
+
assertUploadCurrent(input.stillCurrent);
|
|
228
235
|
if (status.completed) {
|
|
229
236
|
input.onMultipartProgress?.({
|
|
230
237
|
bytesTotal: input.encryption.byteLength,
|
|
@@ -248,6 +255,7 @@ async function uploadResolvedMultipartStage(input, concurrency, { prepared, sour
|
|
|
248
255
|
};
|
|
249
256
|
reportMultipartProgress();
|
|
250
257
|
await uploadMultipartPartTasks({
|
|
258
|
+
stillCurrent: input.stillCurrent,
|
|
251
259
|
apiClient: input.apiClient,
|
|
252
260
|
completeParts,
|
|
253
261
|
concurrency,
|