@tearleads/client-sdk 0.1.209 → 0.1.211
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/organizations/index.js +5 -5
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/principalMutationScope.js +7 -1
- package/client/organizations/principalMutationScope.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +8 -6
- package/client/organizations/principalMutations.js +8 -8
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/organizations/recipientAdmission.d.ts +2 -1
- package/client/organizations/recipientAdmission.js +2 -2
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/client/runtime/workflowRuntime.d.ts +2 -1
- package/client/runtime/workflowRuntime.js +1 -1
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/data/persistence/container-contents/documentMoveIntentPersistence.js +47 -30
- package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
- package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +6 -14
- package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
- package/package.json +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntentErrors.js +2 -2
- package/workflows/container-contents/documentMove/documentMoveIntentErrors.js.map +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +3 -2
- package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntentSync.js +4 -3
- package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -1
- package/workflows/container-contents/pendingWrites/index.js +3 -3
- package/workflows/container-contents/pendingWrites/index.js.map +1 -1
- package/workflows/container-contents/recovery/accessRestoration.js +4 -7
- package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA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AAY,CAAC,OAAO,CAAC,WAAW;YACvE,SAAS,EAAE,YAAY,CAAC,SAAS,IAAI,IAAI;YACzC,gCAAgC,EAC9B,YAAY,CAAC,MAAM,CAAC,oBAAoB;YAC1C,iCAAiC,EAC/B,YAAY,CAAC,MAAM,CAAC,qBAAqB;SAC5C,CAAC,CAAC;QACH,IAAI,GAAG,qBAAqB,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;QAEjD,OAAO;YACL,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;YACrD,SAAS,EAAE,eAAe,EAAE;YAC5B,IAAI;YACJ,MAAM;YACN,KAAK;YACL,KAAK;YACL,IAAI;YACJ,0BAA0B;YAC1B,8BAA8B,EAAE,qBAAqB,EAAE;SACxD,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,SAAS,CAAC,WAAW;YACnB,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,0BAA0B,EAAE,2BAA2B,EACvD,8BAA8B,EAAE,+BAA+B,EAC/D,IAAI,EAAE,YAAY,EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { createRuntimeIdentityResolution } from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly identityTrustDomain: string | null;\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AAIjG,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAEL,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,4BAA4B,GAE7B,MAAM,qDAAqD,CAAC;AAW7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAI1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAC9E,OAAO,EAA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SAAS,CAAC,WAAW;YACnB,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,0BAA0B,EAAE,2BAA2B,EACvD,8BAA8B,EAAE,+BAA+B,EAC/D,IAAI,EAAE,YAAY,EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { createRuntimeIdentityResolution } from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n /** Resolved once by the composition root; constant for the client's life. */\n readonly identityTrustDomain: string | null;\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
|
|
@@ -5,7 +5,7 @@ import { documentProjectionTables } from "../../sqlite/schema/documentProjection
|
|
|
5
5
|
import { sqliteRowsPerStatement } from "../../sqlite/sqliteBindBudget.js";
|
|
6
6
|
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
7
7
|
import { ensureSqlTables, runSerializedSqlMutation, } from "../../sqlite/sqlSchema.js";
|
|
8
|
-
import {
|
|
8
|
+
import { enqueueDocumentPlacementIntent, } from "./documentPlacementIntentEnqueue.js";
|
|
9
9
|
export const DOCUMENT_MOVE_INTENT_TYPE = "document.move";
|
|
10
10
|
const INTENT_IDS_PER_STATEMENT = sqliteRowsPerStatement(1);
|
|
11
11
|
/** Every listed intent's link targets, one keyed read per bind budget. */
|
|
@@ -86,15 +86,32 @@ function mapDocumentMoveIntentRecord(row) {
|
|
|
86
86
|
updatedAt: row.updatedAt,
|
|
87
87
|
};
|
|
88
88
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
89
|
+
/**
|
|
90
|
+
* The document placement intent lane, bound to one executor and clock.
|
|
91
|
+
* `markMoveIntentSynced` opens no transaction of its own: it runs inside the
|
|
92
|
+
* caller's relink commit, so build it from that commit's executor.
|
|
93
|
+
*/
|
|
94
|
+
export class DocumentMoveIntentRepository {
|
|
95
|
+
execSql;
|
|
96
|
+
now;
|
|
97
|
+
constructor(execSql, now = () => new Date()) {
|
|
98
|
+
this.execSql = execSql;
|
|
99
|
+
this.now = now;
|
|
100
|
+
}
|
|
101
|
+
async ensureSchema() {
|
|
102
|
+
await ensureSqlTables(this.execSql, documentPlacementIntentTables);
|
|
103
|
+
}
|
|
104
|
+
enqueueMoveIntent(input) {
|
|
105
|
+
return enqueueDocumentPlacementIntent(this.execSql, input, "move", this.now);
|
|
106
|
+
}
|
|
107
|
+
enqueueLinkIntent(input) {
|
|
108
|
+
return enqueueDocumentPlacementIntent(this.execSql, input, "link", this.now);
|
|
109
|
+
}
|
|
110
|
+
enqueueUnlinkIntent(input) {
|
|
111
|
+
return enqueueDocumentPlacementIntent(this.execSql, input, "unlink", this.now);
|
|
112
|
+
}
|
|
113
|
+
async listPendingMoveIntents() {
|
|
114
|
+
return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
|
|
98
115
|
await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);
|
|
99
116
|
return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
|
|
100
117
|
const rows = await tx
|
|
@@ -142,9 +159,9 @@ export const sqlDocumentMoveIntentPersistence = {
|
|
|
142
159
|
});
|
|
143
160
|
});
|
|
144
161
|
});
|
|
145
|
-
}
|
|
146
|
-
async markMoveIntentSynced(
|
|
147
|
-
return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
162
|
+
}
|
|
163
|
+
async markMoveIntentSynced(input) {
|
|
164
|
+
return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
|
|
148
165
|
const deleted = await lockedExecSql(`DELETE FROM local_intents
|
|
149
166
|
WHERE lane = ?
|
|
150
167
|
AND subject_id = ?
|
|
@@ -166,10 +183,10 @@ export const sqlDocumentMoveIntentPersistence = {
|
|
|
166
183
|
}
|
|
167
184
|
return deleted.length > 0;
|
|
168
185
|
});
|
|
169
|
-
}
|
|
170
|
-
async recordMoveIntentError(
|
|
171
|
-
await getClientSQLitePersistenceRuntime(execSql).guardedTransaction(async (db) => {
|
|
172
|
-
const updatedAt =
|
|
186
|
+
}
|
|
187
|
+
async recordMoveIntentError(input) {
|
|
188
|
+
await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(async (db) => {
|
|
189
|
+
const updatedAt = this.now().toISOString();
|
|
173
190
|
await db
|
|
174
191
|
.update(localIntents)
|
|
175
192
|
.set({
|
|
@@ -193,18 +210,18 @@ export const sqlDocumentMoveIntentPersistence = {
|
|
|
193
210
|
: [])))
|
|
194
211
|
.run();
|
|
195
212
|
}, input.stillCurrent ?? (() => true), { behavior: "immediate" });
|
|
196
|
-
}
|
|
213
|
+
}
|
|
197
214
|
/**
|
|
198
215
|
* Evidence for the org-access-restored re-arm gate: a parked
|
|
199
216
|
* permission-denied move proves a queued write was refused.
|
|
200
217
|
*/
|
|
201
|
-
async hasDeniedMoveIntents(
|
|
202
|
-
await
|
|
203
|
-
await ensureSqlTables(execSql, [
|
|
218
|
+
async hasDeniedMoveIntents(input) {
|
|
219
|
+
await this.ensureSchema();
|
|
220
|
+
await ensureSqlTables(this.execSql, [
|
|
204
221
|
...documentProjectionTables,
|
|
205
222
|
...containerTables,
|
|
206
223
|
]);
|
|
207
|
-
const rows = await execSql(`SELECT intent.subject_id AS document_id
|
|
224
|
+
const rows = await this.execSql(`SELECT intent.subject_id AS document_id
|
|
208
225
|
FROM local_intents intent
|
|
209
226
|
${input?.organizationId ? DENIED_INTENT_ORGANIZATION_JOINS_SQL : ""}
|
|
210
227
|
WHERE intent.lane = ?
|
|
@@ -217,19 +234,19 @@ export const sqlDocumentMoveIntentPersistence = {
|
|
|
217
234
|
...(input?.organizationId ? [input.organizationId] : []),
|
|
218
235
|
]);
|
|
219
236
|
return rows.length > 0;
|
|
220
|
-
}
|
|
237
|
+
}
|
|
221
238
|
/**
|
|
222
239
|
* Flip parked permission-denied moves back to pending so the re-armed
|
|
223
240
|
* structural pass replays them (access restored, or a manual retry scoped
|
|
224
241
|
* to one document).
|
|
225
242
|
*/
|
|
226
|
-
async resetDeniedMoveIntents(
|
|
227
|
-
await
|
|
228
|
-
await ensureSqlTables(execSql, [
|
|
243
|
+
async resetDeniedMoveIntents(input) {
|
|
244
|
+
await this.ensureSchema();
|
|
245
|
+
await ensureSqlTables(this.execSql, [
|
|
229
246
|
...documentProjectionTables,
|
|
230
247
|
...containerTables,
|
|
231
248
|
]);
|
|
232
|
-
await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
249
|
+
await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
|
|
233
250
|
// Organization scoping resolves each intent's organization through the
|
|
234
251
|
// container joins above: restoring one organization's access must not
|
|
235
252
|
// un-park moves that another organization still denies. Rows with no
|
|
@@ -249,7 +266,7 @@ export const sqlDocumentMoveIntentPersistence = {
|
|
|
249
266
|
OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)
|
|
250
267
|
)`
|
|
251
268
|
: ""}`, [
|
|
252
|
-
|
|
269
|
+
this.now().toISOString(),
|
|
253
270
|
LOCAL_INTENT_LANES.documentPlacement,
|
|
254
271
|
...DOCUMENT_PLACEMENT_INTENT_TYPES,
|
|
255
272
|
...(input?.localId ? [input.localId] : []),
|
|
@@ -258,6 +275,6 @@ export const sqlDocumentMoveIntentPersistence = {
|
|
|
258
275
|
: []),
|
|
259
276
|
]);
|
|
260
277
|
});
|
|
261
|
-
}
|
|
262
|
-
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
263
280
|
//# sourceMappingURL=documentMoveIntentPersistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentMoveIntentPersistence.js","sourceRoot":"","sources":["documentMoveIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,eAAe,EACf,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EAAE,wBAAwB,EAAE,MAAM,8CAA8C,CAAC;AACxF,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAEL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6BAC9B,8BAA8B;oBACvC;gBACL,CAAC,CAAC,EACN,EAAE,EACL;gBACE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;gBACxB,kBAAkB,CAAC,iBAAiB;gBACpC,GAAG,+BAA+B;gBAClC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC1C,GAAG,CAAC,KAAK,EAAE,cAAc;oBACvB,CAAC,CAAC,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC;oBAC9D,CAAC,CAAC,EAAE,CAAC;aACR,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n containerTables,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport { documentProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport {\n enqueueDocumentLinkIntent,\n enqueueDocumentMoveIntent,\n enqueueDocumentUnlinkIntent,\n} from \"./documentPlacementIntentEnqueue\";\n\ntype DocumentIntentLinkTarget = {\n containerId: string;\n operation: \"link\" | \"unlink\";\n};\n\nexport const DOCUMENT_MOVE_INTENT_TYPE = \"document.move\";\nconst INTENT_IDS_PER_STATEMENT = sqliteRowsPerStatement(1);\n\n/** Every listed intent's link targets, one keyed read per bind budget. */\nasync function loadLinkTargetsByIntent(\n tx: ClientSQLiteTransactionScope,\n intentIds: readonly string[],\n): Promise<ReadonlyMap<string, readonly DocumentIntentLinkTarget[]>> {\n const targetsByIntent = new Map<string, DocumentIntentLinkTarget[]>();\n const uniqueIds = [...new Set(intentIds)];\n for (\n let index = 0;\n index < uniqueIds.length;\n index += INTENT_IDS_PER_STATEMENT\n ) {\n const rows = await tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n intentId: documentIntentLinkTargets.intentId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n uniqueIds.slice(index, index + INTENT_IDS_PER_STATEMENT),\n ),\n );\n for (const { intentId, ...target } of rows) {\n const targets = targetsByIntent.get(intentId) ?? [];\n targets.push(target);\n targetsByIntent.set(intentId, targets);\n }\n }\n return targetsByIntent;\n}\nconst placementLane = inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement);\nexport const DOCUMENT_LINK_INTENT_TYPE = \"document.link\";\nconst DOCUMENT_PLACEMENT_INTENT_TYPES = [\n DOCUMENT_MOVE_INTENT_TYPE,\n DOCUMENT_LINK_INTENT_TYPE,\n];\n\n// Resolves the organization a parked move belongs to, in confidence order:\n// the move's target container, the document's preserved projection\n// attribution, then the container the document currently sits in. Normal\n// saves routinely leave projection attribution empty (deferred-tail\n// reporting resolves through the same container join), so the container rows\n// carry the common case; rows with no resolvable organization stay in every\n// scope (device-first shapes, matching orphan priming).\nconst DENIED_INTENT_ORGANIZATION_SQL = `COALESCE(\n NULLIF(target_container.organization_id, ''),\n NULLIF(projection.organization_id, ''),\n NULLIF(projection_container.organization_id, '')\n)`;\n\nconst DENIED_INTENT_ORGANIZATION_JOINS_SQL = `\n LEFT JOIN containers target_container\n ON target_container.id = intent.target_container_id\n LEFT JOIN document_projection projection\n ON projection.local_id = intent.local_id\n LEFT JOIN containers projection_container\n ON projection_container.id = projection.container_id`;\n\n/**\n * - `pending`: replays on every structural pass.\n * - `blocked`: the last pass could not proceed locally (missing local\n * document / destination); replays, since hydration can heal it.\n * - `denied`: parked on a 403 until the access-restored replay (row 7).\n * - `unavailable`: terminal — after a projection refresh the destination\n * itself is proven deleted (coded 404 on its own projection probe). No\n * mutation 409 is ever terminal: with the destination live it can only\n * name an ancestor or source, and the next pass's fresh paths outrun it.\n * Container ids never return, so no replay can commit the intent as\n * written; it leaves the replay set until the local container tombstone\n * cascade retargets it or the user re-enqueues the move.\n */\nexport type DocumentMoveIntentSyncStatus =\n | \"pending\"\n | \"blocked\"\n | \"denied\"\n | \"unavailable\";\n\nexport interface DocumentMoveIntentRecord {\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n id: string;\n documentId: string;\n intentType:\n | typeof DOCUMENT_MOVE_INTENT_TYPE\n | typeof DOCUMENT_LINK_INTENT_TYPE;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: DocumentMoveIntentSyncStatus;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedDocumentMoveIntentRecord {\n id: string | null;\n documentId: string;\n intentType: string;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string | null;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: string;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction parseDocumentMoveIntentSyncStatus(\n value: unknown,\n): DocumentMoveIntentSyncStatus {\n if (value === \"blocked\" || value === \"denied\" || value === \"unavailable\") {\n return value;\n }\n return \"pending\";\n}\n\nfunction resolveRecordedSyncStatus(input: {\n blocked?: boolean | undefined;\n denied?: boolean | undefined;\n unavailable?: boolean | undefined;\n}): DocumentMoveIntentSyncStatus {\n if (input.unavailable) return \"unavailable\";\n if (input.denied) return \"denied\";\n return input.blocked ? \"blocked\" : \"pending\";\n}\n\nfunction mapDocumentMoveIntentRecord(\n row: SelectedDocumentMoveIntentRecord,\n): DocumentMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n documentId: row.documentId,\n intentType:\n row.intentType === DOCUMENT_LINK_INTENT_TYPE\n ? DOCUMENT_LINK_INTENT_TYPE\n : DOCUMENT_MOVE_INTENT_TYPE,\n lastAttemptedAt: row.lastAttemptedAt,\n lastError: row.lastError,\n // Placement intents always carry their local document row.\n localId: row.localId ?? \"\",\n replaceLinkedContainers: Boolean(row.replaceLinkedContainers),\n sourceContainerId: row.sourceContainerId,\n syncStatus: parseDocumentMoveIntentSyncStatus(row.syncStatus),\n targetContainerId: row.targetContainerId,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport const sqlDocumentMoveIntentPersistence = {\n async ensureSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n },\n\n enqueueMoveIntent: enqueueDocumentMoveIntent,\n enqueueLinkIntent: enqueueDocumentLinkIntent,\n enqueueUnlinkIntent: enqueueDocumentUnlinkIntent,\n\n async listPendingMoveIntents(\n execSql: ExecSql,\n ): Promise<DocumentMoveIntentRecord[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const rows = await tx\n .select({\n id: localIntents.id,\n documentId: localIntents.subjectId,\n intentType: localIntents.intentType,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n lastError: localIntents.lastError,\n localId: localIntents.localId,\n replaceLinkedContainers: localIntents.replaceLinkedContainers,\n sourceContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n targetContainerId: localIntents.targetContainerId,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n // Blocked intents replay too: \"blocked\" names the reason the last\n // attempt could not proceed (missing local doc / destination), not a\n // terminal verdict. The blocking condition can heal after hydration or\n // recovery, and re-checking is cheap — a still-blocked intent simply\n // re-records its reason without counting as lane progress.\n // Unavailable intents never replay: the server proved a cited container\n // is gone, so every replay would re-issue the same doomed requests\n // (#2278 #4). Only the tombstone cascade or a re-enqueue revives them.\n .where(\n and(\n placementLane,\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n inArray(\n localIntents.intentType,\n DOCUMENT_PLACEMENT_INTENT_TYPES,\n ),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n const targetsByIntent = await loadLinkTargetsByIntent(\n tx,\n rows.map((row) => row.id ?? \"\"),\n );\n return rows.map((row) => {\n const targets = targetsByIntent.get(row.id ?? \"\") ?? [];\n const added = targets\n .filter((target) => target.operation === \"link\")\n .map((target) => target.containerId)\n .sort();\n const removed = targets\n .filter((target) => target.operation === \"unlink\")\n .map((target) => target.containerId)\n .sort();\n return {\n ...mapDocumentMoveIntentRecord(row),\n ...(added.length ? { additionalLinkContainerIds: added } : {}),\n ...(removed.length ? { removedLinkContainerIds: removed } : {}),\n };\n });\n },\n );\n });\n },\n\n async markMoveIntentSynced(\n execSql: ExecSql,\n input: {\n documentId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt: string;\n },\n ): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const deleted = await lockedExecSql(\n `DELETE FROM local_intents\n WHERE lane = ?\n AND subject_id = ?\n AND intent_type IN (?, ?)\n AND updated_at = ?\n ${input.expectedIntentId ? \"AND id = ?\" : \"\"}\n RETURNING id`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n input.documentId,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n input.expectedUpdatedAt,\n ...(input.expectedIntentId ? [input.expectedIntentId] : []),\n ],\n );\n for (const { id } of deleted) {\n await getClientSQLitePersistenceRuntime(lockedExecSql)\n .db.delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, String(id)))\n .run();\n }\n return deleted.length > 0;\n });\n },\n\n async recordMoveIntentError(\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n /**\n * A permission denial (403): the intent parks as `denied` — excluded\n * from routine structural replays — until the org-access-restored\n * signal or a manual retry flips it back to pending (edge-case row 7).\n */\n denied?: boolean | undefined;\n documentId: string;\n /** Exact intent revision read by the pass; preferred over wall-clock CAS. */\n expectedIntentId?: string | undefined;\n /**\n * Optimistic concurrency: when given, the error only records against\n * the intent revision the pass read — a re-enqueued move (new\n * updatedAt) is never parked by a stale in-flight failure.\n */\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n /**\n * Server proof that a cited container was deleted (coded 404 or\n * `container_unavailable` 409): the intent parks terminally as\n * `unavailable`, outside every replay, until the tombstone cascade\n * retargets it or a re-enqueue replaces it. Outranks `denied`: a\n * restored permission cannot revive a deleted container.\n */\n unavailable?: boolean | undefined;\n },\n ): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).guardedTransaction(\n async (db) => {\n const updatedAt = new Date().toISOString();\n await db\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: resolveRecordedSyncStatus(input),\n updatedAt,\n })\n .where(\n and(\n placementLane,\n eq(localIntents.subjectId, input.documentId),\n // Blocked/denied rows must stay updatable: a retried intent\n // records its fresh outcome, and a transient failure flips it\n // back to pending instead of freezing it forever.\n inArray(localIntents.syncStatus, [\n \"pending\",\n \"blocked\",\n \"denied\",\n ]),\n inArray(localIntents.intentType, DOCUMENT_PLACEMENT_INTENT_TYPES),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n },\n input.stillCurrent ?? (() => true),\n { behavior: \"immediate\" },\n );\n },\n /**\n * Evidence for the org-access-restored re-arm gate: a parked\n * permission-denied move proves a queued write was refused.\n */\n async hasDeniedMoveIntents(\n execSql: ExecSql,\n input?: { organizationId?: string },\n ): Promise<boolean> {\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n const rows = await execSql(\n `SELECT intent.subject_id AS document_id\n FROM local_intents intent\n ${input?.organizationId ? DENIED_INTENT_ORGANIZATION_JOINS_SQL : \"\"}\n WHERE intent.lane = ?\n AND intent.sync_status = 'denied'\n AND intent.intent_type IN (?, ?)\n ${input?.organizationId ? `AND (${DENIED_INTENT_ORGANIZATION_SQL} = ? OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)` : \"\"}\n LIMIT 1`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.organizationId ? [input.organizationId] : []),\n ],\n );\n return rows.length > 0;\n },\n /**\n * Flip parked permission-denied moves back to pending so the re-armed\n * structural pass replays them (access restored, or a manual retry scoped\n * to one document).\n */\n async resetDeniedMoveIntents(\n execSql: ExecSql,\n input?: { localId?: string; organizationId?: string },\n ): Promise<void> {\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // Organization scoping resolves each intent's organization through the\n // container joins above: restoring one organization's access must not\n // un-park moves that another organization still denies. Rows with no\n // resolvable organization are included (device-first shapes).\n await lockedExecSql(\n `UPDATE local_intents\n SET sync_status = 'pending', updated_at = ?\n WHERE lane = ?\n AND sync_status = 'denied'\n AND intent_type IN (?, ?)\n ${input?.localId ? \"AND local_id = ?\" : \"\"}\n ${\n input?.organizationId\n ? `AND local_id IN (\n SELECT intent.local_id FROM local_intents intent\n ${DENIED_INTENT_ORGANIZATION_JOINS_SQL}\n WHERE intent.lane = ?\n AND (${DENIED_INTENT_ORGANIZATION_SQL} = ?\n OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)\n )`\n : \"\"\n }`,\n [\n new Date().toISOString(),\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.localId ? [input.localId] : []),\n ...(input?.organizationId\n ? [LOCAL_INTENT_LANES.documentPlacement, input.organizationId]\n : []),\n ],\n );\n });\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"documentMoveIntentPersistence.js","sourceRoot":"","sources":["documentMoveIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,eAAe,EACf,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EAAE,wBAAwB,EAAE,MAAM,8CAA8C,CAAC;AACxF,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,8BAA8B,GAE/B,MAAM,kCAAkC,CAAC;AAO1C,MAAM,CAAC,MAAM,yBAAyB,GAAG,eAAe,CAAC;AACzD,MAAM,wBAAwB,GAAG,sBAAsB,CAAC,CAAC,CAAC,CAAC;AAE3D,0EAA0E;AAC1E,KAAK,UAAU,uBAAuB,CACpC,EAAgC,EAChC,SAA4B;IAE5B,MAAM,eAAe,GAAG,IAAI,GAAG,EAAsC,CAAC;IACtE,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IAC1C,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK,GAAG,SAAS,CAAC,MAAM,EACxB,KAAK,IAAI,wBAAwB,EACjC,CAAC;QACD,MAAM,IAAI,GAA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AAE;gBACxB,kBAAkB,CAAC,iBAAiB;gBACpC,GAAG,+BAA+B;gBAClC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC1C,GAAG,CAAC,KAAK,EAAE,cAAc;oBACvB,CAAC,CAAC,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC;oBAC9D,CAAC,CAAC,EAAE,CAAC;aACR,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n containerTables,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport { documentProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport {\n enqueueDocumentPlacementIntent,\n type PlacementIntentInput,\n} from \"./documentPlacementIntentEnqueue\";\n\ntype DocumentIntentLinkTarget = {\n containerId: string;\n operation: \"link\" | \"unlink\";\n};\n\nexport const DOCUMENT_MOVE_INTENT_TYPE = \"document.move\";\nconst INTENT_IDS_PER_STATEMENT = sqliteRowsPerStatement(1);\n\n/** Every listed intent's link targets, one keyed read per bind budget. */\nasync function loadLinkTargetsByIntent(\n tx: ClientSQLiteTransactionScope,\n intentIds: readonly string[],\n): Promise<ReadonlyMap<string, readonly DocumentIntentLinkTarget[]>> {\n const targetsByIntent = new Map<string, DocumentIntentLinkTarget[]>();\n const uniqueIds = [...new Set(intentIds)];\n for (\n let index = 0;\n index < uniqueIds.length;\n index += INTENT_IDS_PER_STATEMENT\n ) {\n const rows = await tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n intentId: documentIntentLinkTargets.intentId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n uniqueIds.slice(index, index + INTENT_IDS_PER_STATEMENT),\n ),\n );\n for (const { intentId, ...target } of rows) {\n const targets = targetsByIntent.get(intentId) ?? [];\n targets.push(target);\n targetsByIntent.set(intentId, targets);\n }\n }\n return targetsByIntent;\n}\nconst placementLane = inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement);\nexport const DOCUMENT_LINK_INTENT_TYPE = \"document.link\";\nconst DOCUMENT_PLACEMENT_INTENT_TYPES = [\n DOCUMENT_MOVE_INTENT_TYPE,\n DOCUMENT_LINK_INTENT_TYPE,\n];\n\n// Resolves the organization a parked move belongs to, in confidence order:\n// the move's target container, the document's preserved projection\n// attribution, then the container the document currently sits in. Normal\n// saves routinely leave projection attribution empty (deferred-tail\n// reporting resolves through the same container join), so the container rows\n// carry the common case; rows with no resolvable organization stay in every\n// scope (device-first shapes, matching orphan priming).\nconst DENIED_INTENT_ORGANIZATION_SQL = `COALESCE(\n NULLIF(target_container.organization_id, ''),\n NULLIF(projection.organization_id, ''),\n NULLIF(projection_container.organization_id, '')\n)`;\n\nconst DENIED_INTENT_ORGANIZATION_JOINS_SQL = `\n LEFT JOIN containers target_container\n ON target_container.id = intent.target_container_id\n LEFT JOIN document_projection projection\n ON projection.local_id = intent.local_id\n LEFT JOIN containers projection_container\n ON projection_container.id = projection.container_id`;\n\n/**\n * - `pending`: replays on every structural pass.\n * - `blocked`: the last pass could not proceed locally (missing local\n * document / destination); replays, since hydration can heal it.\n * - `denied`: parked on a 403 until the access-restored replay (row 7).\n * - `unavailable`: terminal — after a projection refresh the destination\n * itself is proven deleted (coded 404 on its own projection probe). No\n * mutation 409 is ever terminal: with the destination live it can only\n * name an ancestor or source, and the next pass's fresh paths outrun it.\n * Container ids never return, so no replay can commit the intent as\n * written; it leaves the replay set until the local container tombstone\n * cascade retargets it or the user re-enqueues the move.\n */\nexport type DocumentMoveIntentSyncStatus =\n | \"pending\"\n | \"blocked\"\n | \"denied\"\n | \"unavailable\";\n\nexport interface DocumentMoveIntentRecord {\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n id: string;\n documentId: string;\n intentType:\n | typeof DOCUMENT_MOVE_INTENT_TYPE\n | typeof DOCUMENT_LINK_INTENT_TYPE;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: DocumentMoveIntentSyncStatus;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedDocumentMoveIntentRecord {\n id: string | null;\n documentId: string;\n intentType: string;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string | null;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: string;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction parseDocumentMoveIntentSyncStatus(\n value: unknown,\n): DocumentMoveIntentSyncStatus {\n if (value === \"blocked\" || value === \"denied\" || value === \"unavailable\") {\n return value;\n }\n return \"pending\";\n}\n\nfunction resolveRecordedSyncStatus(input: {\n blocked?: boolean | undefined;\n denied?: boolean | undefined;\n unavailable?: boolean | undefined;\n}): DocumentMoveIntentSyncStatus {\n if (input.unavailable) return \"unavailable\";\n if (input.denied) return \"denied\";\n return input.blocked ? \"blocked\" : \"pending\";\n}\n\nfunction mapDocumentMoveIntentRecord(\n row: SelectedDocumentMoveIntentRecord,\n): DocumentMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n documentId: row.documentId,\n intentType:\n row.intentType === DOCUMENT_LINK_INTENT_TYPE\n ? DOCUMENT_LINK_INTENT_TYPE\n : DOCUMENT_MOVE_INTENT_TYPE,\n lastAttemptedAt: row.lastAttemptedAt,\n lastError: row.lastError,\n // Placement intents always carry their local document row.\n localId: row.localId ?? \"\",\n replaceLinkedContainers: Boolean(row.replaceLinkedContainers),\n sourceContainerId: row.sourceContainerId,\n syncStatus: parseDocumentMoveIntentSyncStatus(row.syncStatus),\n targetContainerId: row.targetContainerId,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\n/**\n * The document placement intent lane, bound to one executor and clock.\n * `markMoveIntentSynced` opens no transaction of its own: it runs inside the\n * caller's relink commit, so build it from that commit's executor.\n */\nexport class DocumentMoveIntentRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensureSchema(): Promise<void> {\n await ensureSqlTables(this.execSql, documentPlacementIntentTables);\n }\n\n enqueueMoveIntent(input: PlacementIntentInput): Promise<void> {\n return enqueueDocumentPlacementIntent(\n this.execSql,\n input,\n \"move\",\n this.now,\n );\n }\n\n enqueueLinkIntent(\n input: PlacementIntentInput & { sourceContainerId: string },\n ): Promise<void> {\n return enqueueDocumentPlacementIntent(\n this.execSql,\n input,\n \"link\",\n this.now,\n );\n }\n\n enqueueUnlinkIntent(\n input: PlacementIntentInput & { removedContainerId: string },\n ): Promise<void> {\n return enqueueDocumentPlacementIntent(\n this.execSql,\n input,\n \"unlink\",\n this.now,\n );\n }\n\n async listPendingMoveIntents(): Promise<DocumentMoveIntentRecord[]> {\n return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const rows = await tx\n .select({\n id: localIntents.id,\n documentId: localIntents.subjectId,\n intentType: localIntents.intentType,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n lastError: localIntents.lastError,\n localId: localIntents.localId,\n replaceLinkedContainers: localIntents.replaceLinkedContainers,\n sourceContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n targetContainerId: localIntents.targetContainerId,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n // Blocked intents replay too: \"blocked\" names the reason the last\n // attempt could not proceed (missing local doc / destination), not a\n // terminal verdict. The blocking condition can heal after hydration or\n // recovery, and re-checking is cheap — a still-blocked intent simply\n // re-records its reason without counting as lane progress.\n // Unavailable intents never replay: the server proved a cited container\n // is gone, so every replay would re-issue the same doomed requests\n // (#2278 #4). Only the tombstone cascade or a re-enqueue revives them.\n .where(\n and(\n placementLane,\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n inArray(\n localIntents.intentType,\n DOCUMENT_PLACEMENT_INTENT_TYPES,\n ),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n const targetsByIntent = await loadLinkTargetsByIntent(\n tx,\n rows.map((row) => row.id ?? \"\"),\n );\n return rows.map((row) => {\n const targets = targetsByIntent.get(row.id ?? \"\") ?? [];\n const added = targets\n .filter((target) => target.operation === \"link\")\n .map((target) => target.containerId)\n .sort();\n const removed = targets\n .filter((target) => target.operation === \"unlink\")\n .map((target) => target.containerId)\n .sort();\n return {\n ...mapDocumentMoveIntentRecord(row),\n ...(added.length ? { additionalLinkContainerIds: added } : {}),\n ...(removed.length ? { removedLinkContainerIds: removed } : {}),\n };\n });\n },\n );\n });\n }\n\n async markMoveIntentSynced(input: {\n documentId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt: string;\n }): Promise<boolean> {\n return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n const deleted = await lockedExecSql(\n `DELETE FROM local_intents\n WHERE lane = ?\n AND subject_id = ?\n AND intent_type IN (?, ?)\n AND updated_at = ?\n ${input.expectedIntentId ? \"AND id = ?\" : \"\"}\n RETURNING id`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n input.documentId,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n input.expectedUpdatedAt,\n ...(input.expectedIntentId ? [input.expectedIntentId] : []),\n ],\n );\n for (const { id } of deleted) {\n await getClientSQLitePersistenceRuntime(lockedExecSql)\n .db.delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, String(id)))\n .run();\n }\n return deleted.length > 0;\n });\n }\n\n async recordMoveIntentError(input: {\n blocked?: boolean | undefined;\n /**\n * A permission denial (403): the intent parks as `denied` — excluded\n * from routine structural replays — until the org-access-restored\n * signal or a manual retry flips it back to pending (edge-case row 7).\n */\n denied?: boolean | undefined;\n documentId: string;\n /** Exact intent revision read by the pass; preferred over wall-clock CAS. */\n expectedIntentId?: string | undefined;\n /**\n * Optimistic concurrency: when given, the error only records against\n * the intent revision the pass read — a re-enqueued move (new\n * updatedAt) is never parked by a stale in-flight failure.\n */\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n /**\n * Server proof that a cited container was deleted (coded 404 or\n * `container_unavailable` 409): the intent parks terminally as\n * `unavailable`, outside every replay, until the tombstone cascade\n * retargets it or a re-enqueue replaces it. Outranks `denied`: a\n * restored permission cannot revive a deleted container.\n */\n unavailable?: boolean | undefined;\n }): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (db) => {\n const updatedAt = this.now().toISOString();\n await db\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: resolveRecordedSyncStatus(input),\n updatedAt,\n })\n .where(\n and(\n placementLane,\n eq(localIntents.subjectId, input.documentId),\n // Blocked/denied rows must stay updatable: a retried intent\n // records its fresh outcome, and a transient failure flips it\n // back to pending instead of freezing it forever.\n inArray(localIntents.syncStatus, [\n \"pending\",\n \"blocked\",\n \"denied\",\n ]),\n inArray(localIntents.intentType, DOCUMENT_PLACEMENT_INTENT_TYPES),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n },\n input.stillCurrent ?? (() => true),\n { behavior: \"immediate\" },\n );\n }\n\n /**\n * Evidence for the org-access-restored re-arm gate: a parked\n * permission-denied move proves a queued write was refused.\n */\n async hasDeniedMoveIntents(input?: {\n organizationId?: string;\n }): Promise<boolean> {\n await this.ensureSchema();\n await ensureSqlTables(this.execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n const rows = await this.execSql(\n `SELECT intent.subject_id AS document_id\n FROM local_intents intent\n ${input?.organizationId ? DENIED_INTENT_ORGANIZATION_JOINS_SQL : \"\"}\n WHERE intent.lane = ?\n AND intent.sync_status = 'denied'\n AND intent.intent_type IN (?, ?)\n ${input?.organizationId ? `AND (${DENIED_INTENT_ORGANIZATION_SQL} = ? OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)` : \"\"}\n LIMIT 1`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.organizationId ? [input.organizationId] : []),\n ],\n );\n return rows.length > 0;\n }\n\n /**\n * Flip parked permission-denied moves back to pending so the re-armed\n * structural pass replays them (access restored, or a manual retry scoped\n * to one document).\n */\n async resetDeniedMoveIntents(input?: {\n localId?: string;\n organizationId?: string;\n }): Promise<void> {\n await this.ensureSchema();\n await ensureSqlTables(this.execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n // Organization scoping resolves each intent's organization through the\n // container joins above: restoring one organization's access must not\n // un-park moves that another organization still denies. Rows with no\n // resolvable organization are included (device-first shapes).\n await lockedExecSql(\n `UPDATE local_intents\n SET sync_status = 'pending', updated_at = ?\n WHERE lane = ?\n AND sync_status = 'denied'\n AND intent_type IN (?, ?)\n ${input?.localId ? \"AND local_id = ?\" : \"\"}\n ${\n input?.organizationId\n ? `AND local_id IN (\n SELECT intent.local_id FROM local_intents intent\n ${DENIED_INTENT_ORGANIZATION_JOINS_SQL}\n WHERE intent.lane = ?\n AND (${DENIED_INTENT_ORGANIZATION_SQL} = ?\n OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)\n )`\n : \"\"\n }`,\n [\n this.now().toISOString(),\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.localId ? [input.localId] : []),\n ...(input?.organizationId\n ? [LOCAL_INTENT_LANES.documentPlacement, input.organizationId]\n : []),\n ],\n );\n });\n }\n}\n"]}
|
|
@@ -94,7 +94,7 @@ async function ensurePlacementIntentSchema(execSql) {
|
|
|
94
94
|
await ensureSqlTables(execSql, documentPlacementIntentTables);
|
|
95
95
|
await ensureSqlTables(execSql, documentContainerProjectionTables);
|
|
96
96
|
}
|
|
97
|
-
async function enqueuePlacementIntentRows(tx, input, operation) {
|
|
97
|
+
async function enqueuePlacementIntentRows(tx, input, operation, now) {
|
|
98
98
|
const [previous] = await tx
|
|
99
99
|
.select()
|
|
100
100
|
.from(localIntents)
|
|
@@ -105,7 +105,7 @@ async function enqueuePlacementIntentRows(tx, input, operation) {
|
|
|
105
105
|
: [];
|
|
106
106
|
const targets = resolveTargets(input, previousTargets, operation, operation === "move" ? await loadSurvivingMoveTarget(tx, previous) : null);
|
|
107
107
|
const id = input.id ?? crypto.randomUUID();
|
|
108
|
-
const updatedAt =
|
|
108
|
+
const updatedAt = now().toISOString();
|
|
109
109
|
// An additive intent retains the active placement and any pending move.
|
|
110
110
|
// Its targets are separate from the discovery projection: only explicit
|
|
111
111
|
// user additions may be replayed, never stale server-discovered links.
|
|
@@ -143,21 +143,13 @@ async function enqueuePlacementIntentRows(tx, input, operation) {
|
|
|
143
143
|
/** Only for a document commit side effect: failures must escape its transaction. */
|
|
144
144
|
export async function enqueueDocumentPlacementIntentInTransaction(transactionExecSql, input, operation) {
|
|
145
145
|
await ensurePlacementIntentSchema(transactionExecSql);
|
|
146
|
-
await enqueuePlacementIntentRows(getClientSQLitePersistenceRuntime(transactionExecSql).db, input, operation);
|
|
146
|
+
await enqueuePlacementIntentRows(getClientSQLitePersistenceRuntime(transactionExecSql).db, input, operation, () => new Date());
|
|
147
147
|
}
|
|
148
|
-
|
|
148
|
+
/** Serialized standalone enqueue: one plain transaction under the lock. */
|
|
149
|
+
export async function enqueueDocumentPlacementIntent(execSql, input, operation, now) {
|
|
149
150
|
await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
150
151
|
await ensurePlacementIntentSchema(lockedExecSql);
|
|
151
|
-
await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) => enqueuePlacementIntentRows(tx, input, operation));
|
|
152
|
+
await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) => enqueuePlacementIntentRows(tx, input, operation, now));
|
|
152
153
|
});
|
|
153
154
|
}
|
|
154
|
-
export function enqueueDocumentMoveIntent(execSql, input) {
|
|
155
|
-
return enqueuePlacementIntent(execSql, input, "move");
|
|
156
|
-
}
|
|
157
|
-
export function enqueueDocumentLinkIntent(execSql, input) {
|
|
158
|
-
return enqueuePlacementIntent(execSql, input, "link");
|
|
159
|
-
}
|
|
160
|
-
export function enqueueDocumentUnlinkIntent(execSql, input) {
|
|
161
|
-
return enqueuePlacementIntent(execSql, input, "unlink");
|
|
162
|
-
}
|
|
163
155
|
//# sourceMappingURL=documentPlacementIntentEnqueue.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentPlacementIntentEnqueue.js","sourceRoot":"","sources":["documentPlacementIntentEnqueue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7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;IAErC,MAAM,2BAA2B,CAAC,kBAAkB,CAAC,CAAC;IACtD,MAAM,0BAA0B,CAC9B,iCAAiC,CAAC,kBAAkB,CAAC,CAAC,EAAE,EACxD,KAAK,EACL,SAAS,CACV,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,sBAAsB,CACnC,OAAgB,EAChB,KAA2B,EAC3B,SAAqC;IAErC,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC9D,MAAM,2BAA2B,CAAC,aAAa,CAAC,CAAC;QACjD,MAAM,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CACxE,0BAA0B,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,CAAC,CACjD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,OAAgB,EAChB,KAA2B;IAE3B,OAAO,sBAAsB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,OAAgB,EAChB,KAA2D;IAE3D,OAAO,sBAAsB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,2BAA2B,CACzC,OAAgB,EAChB,KAA4D;IAE5D,OAAO,sBAAsB,CAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\n\ninterface PlacementIntentInput {\n id?: string | undefined;\n documentId: string;\n localId: string;\n replaceLinkedContainers?: boolean | undefined;\n removedContainerId?: string | undefined;\n sourceContainerId?: string | null | undefined;\n targetContainerId: string;\n}\n\nasync function loadDocumentIntentLinkTargets(\n tx: ClientSQLiteTransactionScope,\n intentId: string,\n) {\n return tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, intentId));\n}\n\ntype LinkTarget = { containerId: string; operation: \"link\" | \"unlink\" };\n\nasync function loadSurvivingMoveTarget(\n tx: ClientSQLiteTransactionScope,\n previous: typeof localIntents.$inferSelect | undefined,\n): Promise<string | null> {\n if (previous?.intentType !== \"document.move\") return null;\n const [link] = await tx\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(\n and(\n eq(documentContainerProjection.documentId, previous.subjectId),\n eq(documentContainerProjection.containerId, previous.targetContainerId),\n ),\n )\n .limit(1);\n return link?.containerId ?? null;\n}\n\nfunction resolveTargets(\n input: PlacementIntentInput,\n previous: LinkTarget[],\n operation: \"move\" | \"link\" | \"unlink\",\n previousMoveTarget: string | null,\n): LinkTarget[] {\n const targets = new Map(\n previous.map((target) => [target.containerId, target.operation]),\n );\n if (operation === \"link\") targets.set(input.targetContainerId, \"link\");\n else if (operation === \"unlink\") {\n if (!input.removedContainerId)\n throw new Error(\"Unlink intent requires a removed container\");\n targets.set(input.removedContainerId, \"unlink\");\n } else if (input.replaceLinkedContainers) targets.clear();\n else {\n if (\n previousMoveTarget &&\n previousMoveTarget !== input.sourceContainerId &&\n previousMoveTarget !== input.targetContainerId &&\n targets.get(previousMoveTarget) !== \"unlink\"\n ) {\n targets.set(previousMoveTarget, \"link\");\n }\n targets.delete(input.targetContainerId);\n if (\n input.sourceContainerId &&\n input.sourceContainerId !== input.targetContainerId\n )\n targets.set(input.sourceContainerId, \"unlink\");\n }\n return uniqueSortedStrings([...targets.keys()]).map((containerId) => ({\n containerId,\n operation: targets.get(containerId) ?? \"link\",\n }));\n}\n\nfunction placementIntentType(\n operation: \"move\" | \"link\" | \"unlink\",\n previous: typeof localIntents.$inferSelect | undefined,\n): \"document.move\" | \"document.link\" {\n return operation === \"move\" || previous?.intentType === \"document.move\"\n ? \"document.move\"\n : \"document.link\";\n}\n\nfunction resolveUnlinkPlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n) {\n return {\n sourceContainerId:\n previous?.intentType === \"document.move\"\n ? previous.sourceContainerId\n : input.targetContainerId,\n targetContainerId:\n previous?.intentType === \"document.move\" &&\n previous.targetContainerId !== input.removedContainerId\n ? previous.targetContainerId\n : input.targetContainerId,\n replaceLinkedContainers: previous?.replaceLinkedContainers ?? false,\n };\n}\n\nfunction resolvePlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n operation: \"move\" | \"link\" | \"unlink\",\n) {\n if (operation === \"unlink\") {\n return resolveUnlinkPlacement(input, previous);\n }\n const linkOnly = operation === \"link\";\n const sourceContainerId =\n previous?.intentType === \"document.move\"\n ? (previous.sourceContainerId ?? input.sourceContainerId ?? null)\n : (input.sourceContainerId ?? null);\n return {\n sourceContainerId: linkOnly\n ? (previous?.sourceContainerId ?? input.sourceContainerId ?? null)\n : sourceContainerId,\n targetContainerId: linkOnly\n ? (previous?.targetContainerId ??\n input.sourceContainerId ??\n input.targetContainerId)\n : input.targetContainerId,\n replaceLinkedContainers:\n previous?.replaceLinkedContainers ||\n (input.replaceLinkedContainers ?? false),\n };\n}\n\nasync function ensurePlacementIntentSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n}\n\nasync function enqueuePlacementIntentRows(\n tx: ClientSQLiteTransactionScope,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n const [previous] = await tx\n .select()\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, input.documentId),\n ),\n )\n .limit(1);\n const previousTargets = previous?.id\n ? await loadDocumentIntentLinkTargets(tx, previous.id)\n : [];\n const targets = resolveTargets(\n input,\n previousTargets,\n operation,\n operation === \"move\" ? await loadSurvivingMoveTarget(tx, previous) : null,\n );\n const id = input.id ?? crypto.randomUUID();\n const updatedAt = new Date().toISOString();\n // An additive intent retains the active placement and any pending move.\n // Its targets are separate from the discovery projection: only explicit\n // user additions may be replayed, never stale server-discovered links.\n const next = {\n id,\n lane: LOCAL_INTENT_LANES.documentPlacement,\n subjectId: input.documentId,\n localId: input.localId,\n intentType: placementIntentType(operation, previous),\n lastAttemptedAt: null,\n lastError: null,\n syncStatus: \"pending\",\n updatedAt,\n ...resolvePlacement(input, previous, operation),\n };\n await tx\n .insert(localIntents)\n .values({ ...next, createdAt: updatedAt })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: next,\n })\n .run();\n if (previous?.id)\n await tx\n .delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, previous.id))\n .run();\n if (targets.length)\n await tx\n .insert(documentIntentLinkTargets)\n .values(targets.map((target) => ({ intentId: id, ...target })))\n .run();\n}\n\n/** Only for a document commit side effect: failures must escape its transaction. */\nexport async function enqueueDocumentPlacementIntentInTransaction(\n transactionExecSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n await ensurePlacementIntentSchema(transactionExecSql);\n await enqueuePlacementIntentRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n input,\n operation,\n );\n}\n\nasync function enqueuePlacementIntent(\n execSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensurePlacementIntentSchema(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) =>\n enqueuePlacementIntentRows(tx, input, operation),\n );\n });\n}\n\nexport function enqueueDocumentMoveIntent(\n execSql: ExecSql,\n input: PlacementIntentInput,\n): Promise<void> {\n return enqueuePlacementIntent(execSql, input, \"move\");\n}\n\nexport function enqueueDocumentLinkIntent(\n execSql: ExecSql,\n input: PlacementIntentInput & { sourceContainerId: string },\n): Promise<void> {\n return enqueuePlacementIntent(execSql, input, \"link\");\n}\n\nexport function enqueueDocumentUnlinkIntent(\n execSql: ExecSql,\n input: PlacementIntentInput & { removedContainerId: string },\n): Promise<void> {\n return enqueuePlacementIntent(execSql, input, \"unlink\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentPlacementIntentEnqueue.js","sourceRoot":"","sources":["documentPlacementIntentEnqueue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAYhC,KAAK,UAAU,6BAA6B,CAC1C,EAAgC,EAChC,QAAgB;IAEhB,OAAO,EAAE;SACN,MAAM,CAAC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,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC9D,MAAM,2BAA2B,CAAC,aAAa,CAAC,CAAC;QACjD,MAAM,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CACxE,0BAA0B,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,CAAC,CACtD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\n\nexport interface PlacementIntentInput {\n id?: string | undefined;\n documentId: string;\n localId: string;\n replaceLinkedContainers?: boolean | undefined;\n removedContainerId?: string | undefined;\n sourceContainerId?: string | null | undefined;\n targetContainerId: string;\n}\n\nasync function loadDocumentIntentLinkTargets(\n tx: ClientSQLiteTransactionScope,\n intentId: string,\n) {\n return tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, intentId));\n}\n\ntype LinkTarget = { containerId: string; operation: \"link\" | \"unlink\" };\n\nasync function loadSurvivingMoveTarget(\n tx: ClientSQLiteTransactionScope,\n previous: typeof localIntents.$inferSelect | undefined,\n): Promise<string | null> {\n if (previous?.intentType !== \"document.move\") return null;\n const [link] = await tx\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(\n and(\n eq(documentContainerProjection.documentId, previous.subjectId),\n eq(documentContainerProjection.containerId, previous.targetContainerId),\n ),\n )\n .limit(1);\n return link?.containerId ?? null;\n}\n\nfunction resolveTargets(\n input: PlacementIntentInput,\n previous: LinkTarget[],\n operation: \"move\" | \"link\" | \"unlink\",\n previousMoveTarget: string | null,\n): LinkTarget[] {\n const targets = new Map(\n previous.map((target) => [target.containerId, target.operation]),\n );\n if (operation === \"link\") targets.set(input.targetContainerId, \"link\");\n else if (operation === \"unlink\") {\n if (!input.removedContainerId)\n throw new Error(\"Unlink intent requires a removed container\");\n targets.set(input.removedContainerId, \"unlink\");\n } else if (input.replaceLinkedContainers) targets.clear();\n else {\n if (\n previousMoveTarget &&\n previousMoveTarget !== input.sourceContainerId &&\n previousMoveTarget !== input.targetContainerId &&\n targets.get(previousMoveTarget) !== \"unlink\"\n ) {\n targets.set(previousMoveTarget, \"link\");\n }\n targets.delete(input.targetContainerId);\n if (\n input.sourceContainerId &&\n input.sourceContainerId !== input.targetContainerId\n )\n targets.set(input.sourceContainerId, \"unlink\");\n }\n return uniqueSortedStrings([...targets.keys()]).map((containerId) => ({\n containerId,\n operation: targets.get(containerId) ?? \"link\",\n }));\n}\n\nfunction placementIntentType(\n operation: \"move\" | \"link\" | \"unlink\",\n previous: typeof localIntents.$inferSelect | undefined,\n): \"document.move\" | \"document.link\" {\n return operation === \"move\" || previous?.intentType === \"document.move\"\n ? \"document.move\"\n : \"document.link\";\n}\n\nfunction resolveUnlinkPlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n) {\n return {\n sourceContainerId:\n previous?.intentType === \"document.move\"\n ? previous.sourceContainerId\n : input.targetContainerId,\n targetContainerId:\n previous?.intentType === \"document.move\" &&\n previous.targetContainerId !== input.removedContainerId\n ? previous.targetContainerId\n : input.targetContainerId,\n replaceLinkedContainers: previous?.replaceLinkedContainers ?? false,\n };\n}\n\nfunction resolvePlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n operation: \"move\" | \"link\" | \"unlink\",\n) {\n if (operation === \"unlink\") {\n return resolveUnlinkPlacement(input, previous);\n }\n const linkOnly = operation === \"link\";\n const sourceContainerId =\n previous?.intentType === \"document.move\"\n ? (previous.sourceContainerId ?? input.sourceContainerId ?? null)\n : (input.sourceContainerId ?? null);\n return {\n sourceContainerId: linkOnly\n ? (previous?.sourceContainerId ?? input.sourceContainerId ?? null)\n : sourceContainerId,\n targetContainerId: linkOnly\n ? (previous?.targetContainerId ??\n input.sourceContainerId ??\n input.targetContainerId)\n : input.targetContainerId,\n replaceLinkedContainers:\n previous?.replaceLinkedContainers ||\n (input.replaceLinkedContainers ?? false),\n };\n}\n\nasync function ensurePlacementIntentSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n}\n\nasync function enqueuePlacementIntentRows(\n tx: ClientSQLiteTransactionScope,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n now: () => Date,\n): Promise<void> {\n const [previous] = await tx\n .select()\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, input.documentId),\n ),\n )\n .limit(1);\n const previousTargets = previous?.id\n ? await loadDocumentIntentLinkTargets(tx, previous.id)\n : [];\n const targets = resolveTargets(\n input,\n previousTargets,\n operation,\n operation === \"move\" ? await loadSurvivingMoveTarget(tx, previous) : null,\n );\n const id = input.id ?? crypto.randomUUID();\n const updatedAt = now().toISOString();\n // An additive intent retains the active placement and any pending move.\n // Its targets are separate from the discovery projection: only explicit\n // user additions may be replayed, never stale server-discovered links.\n const next = {\n id,\n lane: LOCAL_INTENT_LANES.documentPlacement,\n subjectId: input.documentId,\n localId: input.localId,\n intentType: placementIntentType(operation, previous),\n lastAttemptedAt: null,\n lastError: null,\n syncStatus: \"pending\",\n updatedAt,\n ...resolvePlacement(input, previous, operation),\n };\n await tx\n .insert(localIntents)\n .values({ ...next, createdAt: updatedAt })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: next,\n })\n .run();\n if (previous?.id)\n await tx\n .delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, previous.id))\n .run();\n if (targets.length)\n await tx\n .insert(documentIntentLinkTargets)\n .values(targets.map((target) => ({ intentId: id, ...target })))\n .run();\n}\n\n/** Only for a document commit side effect: failures must escape its transaction. */\nexport async function enqueueDocumentPlacementIntentInTransaction(\n transactionExecSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n await ensurePlacementIntentSchema(transactionExecSql);\n await enqueuePlacementIntentRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n input,\n operation,\n () => new Date(),\n );\n}\n\n/** Serialized standalone enqueue: one plain transaction under the lock. */\nexport async function enqueueDocumentPlacementIntent(\n execSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n now: () => Date,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensurePlacementIntentSchema(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) =>\n enqueuePlacementIntentRows(tx, input, operation, now),\n );\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
|
|
2
2
|
export async function recordPendingDocumentMoveIntentError(input) {
|
|
3
3
|
if (!input.isCurrent())
|
|
4
4
|
return false;
|
|
5
|
-
await
|
|
5
|
+
await new DocumentMoveIntentRepository(input.state.runtime.infra.execSql).recordMoveIntentError({
|
|
6
6
|
blocked: input.blocked,
|
|
7
7
|
denied: input.denied,
|
|
8
8
|
documentId: input.documentId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentMoveIntentErrors.js","sourceRoot":"","sources":["documentMoveIntentErrors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"documentMoveIntentErrors.js","sourceRoot":"","sources":["documentMoveIntentErrors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAG1H,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAU1D;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,IAAI,4BAA4B,CACpC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAClC,CAAC,qBAAqB,CAAC;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,SAAS;QAC7B,WAAW,EAAE,KAAK,CAAC,WAAW;KAC/B,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,SAAS,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport async function recordPendingDocumentMoveIntentError(input: {\n blocked?: boolean | undefined;\n denied?: boolean | undefined;\n documentId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n isCurrent: () => boolean;\n message: string;\n state: { runtime: ContainerContentsWorkflowRuntime };\n unavailable?: boolean | undefined;\n}): Promise<boolean> {\n if (!input.isCurrent()) return false;\n await new DocumentMoveIntentRepository(\n input.state.runtime.infra.execSql,\n ).recordMoveIntentError({\n blocked: input.blocked,\n denied: input.denied,\n documentId: input.documentId,\n expectedIntentId: input.expectedIntentId,\n expectedUpdatedAt: input.expectedUpdatedAt,\n message: input.message,\n stillCurrent: input.isCurrent,\n unavailable: input.unavailable,\n });\n return input.isCurrent();\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { replaceDocumentLinksInTransaction } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
|
|
2
|
-
import {
|
|
2
|
+
import { DocumentMoveIntentRepository, } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
|
|
3
3
|
import { loadDocumentMovePlacement } from "../../../data/persistence/container-contents/documentPlacement.js";
|
|
4
4
|
import { getClientSQLitePersistenceRuntime } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
|
|
5
5
|
/** Called inside the relink commit; a refusal must roll that entire commit back. */
|
|
@@ -13,7 +13,8 @@ export async function settleDocumentMoveIntent(input) {
|
|
|
13
13
|
throw new Error("Document move intent was superseded before local settlement");
|
|
14
14
|
return;
|
|
15
15
|
}
|
|
16
|
-
|
|
16
|
+
// The relink transaction's executor: settlement commits with the relink.
|
|
17
|
+
const settled = await new DocumentMoveIntentRepository(input.execSql).markMoveIntentSynced({
|
|
17
18
|
documentId: input.intent.documentId,
|
|
18
19
|
expectedIntentId: input.intent.id,
|
|
19
20
|
expectedUpdatedAt: input.intent.updatedAt,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentMoveIntentSettlement.js","sourceRoot":"","sources":["documentMoveIntentSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,qFAAqF,CAAC;AACxI,OAAO,EAEL,
|
|
1
|
+
{"version":3,"file":"documentMoveIntentSettlement.js","sourceRoot":"","sources":["documentMoveIntentSettlement.ts"],"names":[],"mappings":"AAAA,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zB,CAAC;AACJ,CAAC","sourcesContent":["import { replaceDocumentLinksInTransaction } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport {\n type DocumentMoveIntentRecord,\n DocumentMoveIntentRepository,\n} from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { loadDocumentMovePlacement } from \"../../../data/persistence/container-contents/documentPlacement\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\n/** Called inside the relink commit; a refusal must roll that entire commit back. */\nexport async function settleDocumentMoveIntent(input: {\n execSql: ExecSql;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n linkedContainerIds: readonly string[];\n partial: boolean;\n}): Promise<void> {\n if (!input.isCurrent()) {\n throw new Error(\"Document move generation changed before local settlement\");\n }\n if (input.partial) {\n const intent = await loadDocumentMovePlacement(\n getClientSQLitePersistenceRuntime(input.execSql).db,\n input.intent.documentId,\n );\n if (intent?.id !== input.intent.id)\n throw new Error(\n \"Document move intent was superseded before local settlement\",\n );\n return;\n }\n // The relink transaction's executor: settlement commits with the relink.\n const settled = await new DocumentMoveIntentRepository(\n input.execSql,\n ).markMoveIntentSynced({\n documentId: input.intent.documentId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n });\n if (!settled || !input.isCurrent()) {\n throw new Error(\n \"Document move intent was superseded before local settlement\",\n );\n }\n await replaceDocumentLinksInTransaction(\n input.execSql,\n input.intent.documentId,\n input.linkedContainerIds,\n );\n}\n"]}
|