@abloatai/humans 0.37.0
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/README.md +52 -0
- package/dist/Ablo.d.ts +208 -0
- package/dist/Ablo.js +120 -0
- package/dist/client.d.ts +317 -0
- package/dist/client.js +13 -0
- package/dist/core.d.ts +35 -0
- package/dist/core.js +48 -0
- package/dist/humans.d.ts +28 -0
- package/dist/humans.js +34 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +6 -0
- package/dist/local/BaseSyncedStore.d.ts +807 -0
- package/dist/local/BaseSyncedStore.js +1516 -0
- package/dist/local/Database.d.ts +322 -0
- package/dist/local/Database.js +1589 -0
- package/dist/local/InstanceCache.d.ts +255 -0
- package/dist/local/InstanceCache.js +1263 -0
- package/dist/local/LazyReferenceCollection.d.ts +177 -0
- package/dist/local/LazyReferenceCollection.js +461 -0
- package/dist/local/Model.d.ts +475 -0
- package/dist/local/Model.js +950 -0
- package/dist/local/ModelRegistry.d.ts +225 -0
- package/dist/local/ModelRegistry.js +539 -0
- package/dist/local/NetworkMonitor.d.ts +28 -0
- package/dist/local/NetworkMonitor.js +79 -0
- package/dist/local/RuntimeContext.d.ts +52 -0
- package/dist/local/RuntimeContext.js +80 -0
- package/dist/local/SyncClient.d.ts +516 -0
- package/dist/local/SyncClient.js +1754 -0
- package/dist/local/adapters/alwaysOnline.d.ts +14 -0
- package/dist/local/adapters/alwaysOnline.js +17 -0
- package/dist/local/adapters/inMemoryStorage.d.ts +37 -0
- package/dist/local/adapters/inMemoryStorage.js +122 -0
- package/dist/local/client/clientPrelude.d.ts +52 -0
- package/dist/local/client/clientPrelude.js +60 -0
- package/dist/local/client/consoleLogger.d.ts +35 -0
- package/dist/local/client/consoleLogger.js +44 -0
- package/dist/local/client/createInternalComponents.d.ts +50 -0
- package/dist/local/client/createInternalComponents.js +98 -0
- package/dist/local/client/createModelProxy.d.ts +248 -0
- package/dist/local/client/createModelProxy.js +880 -0
- package/dist/local/client/modelRegistration.d.ts +10 -0
- package/dist/local/client/modelRegistration.js +316 -0
- package/dist/local/client/options.d.ts +440 -0
- package/dist/local/client/options.js +7 -0
- package/dist/local/client/reactiveEngine.d.ts +53 -0
- package/dist/local/client/reactiveEngine.js +705 -0
- package/dist/local/client/resourceTypes.d.ts +12 -0
- package/dist/local/client/resourceTypes.js +10 -0
- package/dist/local/client/schemaConfig.d.ts +44 -0
- package/dist/local/client/schemaConfig.js +185 -0
- package/dist/local/client/storeCluster.d.ts +46 -0
- package/dist/local/client/storeCluster.js +133 -0
- package/dist/local/client/storeLifecycle.d.ts +61 -0
- package/dist/local/client/storeLifecycle.js +236 -0
- package/dist/local/client/validateAbloOptions.d.ts +42 -0
- package/dist/local/client/validateAbloOptions.js +43 -0
- package/dist/local/client/wsMutationExecutor.d.ts +27 -0
- package/dist/local/client/wsMutationExecutor.js +72 -0
- package/dist/local/context.d.ts +42 -0
- package/dist/local/context.js +81 -0
- package/dist/local/coordination/ClaimLog.d.ts +26 -0
- package/dist/local/coordination/ClaimLog.js +32 -0
- package/dist/local/interfaces/index.d.ts +311 -0
- package/dist/local/interfaces/index.js +9 -0
- package/dist/local/localModelContract.d.ts +14 -0
- package/dist/local/localModelContract.js +1 -0
- package/dist/local/logPosition.d.ts +31 -0
- package/dist/local/logPosition.js +53 -0
- package/dist/local/mutationPersistence.d.ts +6 -0
- package/dist/local/mutationPersistence.js +1 -0
- package/dist/local/mutators/RecordingMutation.d.ts +36 -0
- package/dist/local/mutators/RecordingMutation.js +182 -0
- package/dist/local/mutators/Transaction.d.ts +40 -0
- package/dist/local/mutators/Transaction.js +58 -0
- package/dist/local/mutators/UndoManager.d.ts +258 -0
- package/dist/local/mutators/UndoManager.js +665 -0
- package/dist/local/mutators/defineMutators.d.ts +60 -0
- package/dist/local/mutators/defineMutators.js +18 -0
- package/dist/local/mutators/inverseOp.d.ts +126 -0
- package/dist/local/mutators/inverseOp.js +71 -0
- package/dist/local/mutators/mutateActions.d.ts +45 -0
- package/dist/local/mutators/mutateActions.js +105 -0
- package/dist/local/mutators/readerActions.d.ts +33 -0
- package/dist/local/mutators/readerActions.js +57 -0
- package/dist/local/mutators/undoApply.d.ts +51 -0
- package/dist/local/mutators/undoApply.js +117 -0
- package/dist/local/persistence.d.ts +7 -0
- package/dist/local/persistence.js +9 -0
- package/dist/local/query/QueryProcessor.d.ts +75 -0
- package/dist/local/query/QueryProcessor.js +255 -0
- package/dist/local/query/client.d.ts +64 -0
- package/dist/local/query/client.js +138 -0
- package/dist/local/query/types.d.ts +85 -0
- package/dist/local/query/types.js +16 -0
- package/dist/local/schema/serialize.d.ts +1 -0
- package/dist/local/schema/serialize.js +1 -0
- package/dist/local/store/queryApi.d.ts +13 -0
- package/dist/local/store/queryApi.js +35 -0
- package/dist/local/storeContract.d.ts +145 -0
- package/dist/local/storeContract.js +12 -0
- package/dist/local/stores/DatabaseManager.d.ts +112 -0
- package/dist/local/stores/DatabaseManager.js +400 -0
- package/dist/local/stores/ObjectStore.d.ts +115 -0
- package/dist/local/stores/ObjectStore.js +393 -0
- package/dist/local/stores/ObjectStoreContract.d.ts +38 -0
- package/dist/local/stores/ObjectStoreContract.js +1 -0
- package/dist/local/stores/StoreManager.d.ts +114 -0
- package/dist/local/stores/StoreManager.js +304 -0
- package/dist/local/stores/SyncActionStore.d.ts +99 -0
- package/dist/local/stores/SyncActionStore.js +506 -0
- package/dist/local/stores/openIDBWithTimeout.d.ts +65 -0
- package/dist/local/stores/openIDBWithTimeout.js +153 -0
- package/dist/local/stores/persistenceCleanup.d.ts +7 -0
- package/dist/local/stores/persistenceCleanup.js +26 -0
- package/dist/local/stores/persistenceIdentity.d.ts +27 -0
- package/dist/local/stores/persistenceIdentity.js +38 -0
- package/dist/local/stores/syncAction.d.ts +26 -0
- package/dist/local/stores/syncAction.js +16 -0
- package/dist/local/stores/v1PersistenceDeletion.d.ts +8 -0
- package/dist/local/stores/v1PersistenceDeletion.js +16 -0
- package/dist/local/sync/BootstrapFetcher.d.ts +284 -0
- package/dist/local/sync/BootstrapFetcher.js +964 -0
- package/dist/local/sync/ConnectionManager.d.ts +8 -0
- package/dist/local/sync/ConnectionManager.js +8 -0
- package/dist/local/sync/OnDemandLoader.d.ts +231 -0
- package/dist/local/sync/OnDemandLoader.js +743 -0
- package/dist/local/sync/SubscriptionManager.d.ts +159 -0
- package/dist/local/sync/SubscriptionManager.js +243 -0
- package/dist/local/sync/SyncWebSocket.d.ts +173 -0
- package/dist/local/sync/SyncWebSocket.js +438 -0
- package/dist/local/sync/bootstrapApply.d.ts +73 -0
- package/dist/local/sync/bootstrapApply.js +73 -0
- package/dist/local/sync/commitFrames.d.ts +8 -0
- package/dist/local/sync/commitFrames.js +8 -0
- package/dist/local/sync/connectionManagerLifecycle.d.ts +23 -0
- package/dist/local/sync/connectionManagerLifecycle.js +126 -0
- package/dist/local/sync/contextPorts.d.ts +18 -0
- package/dist/local/sync/contextPorts.js +31 -0
- package/dist/local/sync/createClaimStream.d.ts +64 -0
- package/dist/local/sync/createClaimStream.js +475 -0
- package/dist/local/sync/createSnapshot.d.ts +29 -0
- package/dist/local/sync/createSnapshot.js +116 -0
- package/dist/local/sync/credentialLifecycle.d.ts +7 -0
- package/dist/local/sync/credentialLifecycle.js +7 -0
- package/dist/local/sync/deltaPipeline.d.ts +116 -0
- package/dist/local/sync/deltaPipeline.js +357 -0
- package/dist/local/sync/groupChange.d.ts +116 -0
- package/dist/local/sync/groupChange.js +244 -0
- package/dist/local/sync/initialize.d.ts +27 -0
- package/dist/local/sync/initialize.js +137 -0
- package/dist/local/sync/participants.d.ts +132 -0
- package/dist/local/sync/participants.js +342 -0
- package/dist/local/sync/persistedPrefix.d.ts +12 -0
- package/dist/local/sync/persistedPrefix.js +22 -0
- package/dist/local/sync/reconnect.d.ts +23 -0
- package/dist/local/sync/reconnect.js +55 -0
- package/dist/local/sync/schemaDrift.d.ts +55 -0
- package/dist/local/sync/schemaDrift.js +53 -0
- package/dist/local/sync/schemas.d.ts +71 -0
- package/dist/local/sync/schemas.js +94 -0
- package/dist/local/sync/socketEventWiring.d.ts +31 -0
- package/dist/local/sync/socketEventWiring.js +130 -0
- package/dist/local/sync/syncCursor.d.ts +40 -0
- package/dist/local/sync/syncCursor.js +55 -0
- package/dist/local/sync/syncPlan.d.ts +54 -0
- package/dist/local/sync/syncPlan.js +50 -0
- package/dist/local/sync/terminalSessionLifecycle.d.ts +20 -0
- package/dist/local/sync/terminalSessionLifecycle.js +50 -0
- package/dist/local/sync/wsFrameHandlers.d.ts +8 -0
- package/dist/local/sync/wsFrameHandlers.js +8 -0
- package/dist/local/transactions/databaseCommitOutbox.d.ts +15 -0
- package/dist/local/transactions/databaseCommitOutbox.js +16 -0
- package/dist/local/transactions/localMutation.d.ts +10 -0
- package/dist/local/transactions/localMutation.js +37 -0
- package/dist/local/transactions/mutations/MutationQueue.d.ts +511 -0
- package/dist/local/transactions/mutations/MutationQueue.js +1498 -0
- package/dist/local/transactions/mutations/MutationStore.d.ts +20 -0
- package/dist/local/transactions/mutations/MutationStore.js +53 -0
- package/dist/local/transactions/mutations/UnconfirmedWrites.d.ts +82 -0
- package/dist/local/transactions/mutations/UnconfirmedWrites.js +104 -0
- package/dist/local/transactions/mutations/batchProcessing.d.ts +64 -0
- package/dist/local/transactions/mutations/batchProcessing.js +349 -0
- package/dist/local/transactions/mutations/coalesceRules.d.ts +58 -0
- package/dist/local/transactions/mutations/coalesceRules.js +140 -0
- package/dist/local/transactions/mutations/commitApi.d.ts +19 -0
- package/dist/local/transactions/mutations/commitApi.js +74 -0
- package/dist/local/transactions/mutations/commitLane.d.ts +70 -0
- package/dist/local/transactions/mutations/commitLane.js +140 -0
- package/dist/local/transactions/mutations/commitLatency.d.ts +52 -0
- package/dist/local/transactions/mutations/commitLatency.js +130 -0
- package/dist/local/transactions/mutations/commitPayload.d.ts +165 -0
- package/dist/local/transactions/mutations/commitPayload.js +152 -0
- package/dist/local/transactions/mutations/commitTransport.d.ts +36 -0
- package/dist/local/transactions/mutations/commitTransport.js +104 -0
- package/dist/local/transactions/mutations/deltaConfirmation.d.ts +63 -0
- package/dist/local/transactions/mutations/deltaConfirmation.js +235 -0
- package/dist/local/transactions/mutations/durableCommitRestore.d.ts +17 -0
- package/dist/local/transactions/mutations/durableCommitRestore.js +95 -0
- package/dist/local/transactions/mutations/durableWriteStore.d.ts +14 -0
- package/dist/local/transactions/mutations/durableWriteStore.js +12 -0
- package/dist/local/transactions/mutations/executionSelection.d.ts +6 -0
- package/dist/local/transactions/mutations/executionSelection.js +42 -0
- package/dist/local/transactions/mutations/failureHandling.d.ts +16 -0
- package/dist/local/transactions/mutations/failureHandling.js +130 -0
- package/dist/local/transactions/mutations/failurePolicy.d.ts +13 -0
- package/dist/local/transactions/mutations/failurePolicy.js +48 -0
- package/dist/local/transactions/mutations/localMutation.d.ts +58 -0
- package/dist/local/transactions/mutations/localMutation.js +75 -0
- package/dist/local/transactions/mutations/modelOperations.d.ts +44 -0
- package/dist/local/transactions/mutations/modelOperations.js +144 -0
- package/dist/local/transactions/mutations/mutationPersistence.d.ts +25 -0
- package/dist/local/transactions/mutations/mutationPersistence.js +188 -0
- package/dist/local/transactions/mutations/pendingDrain.d.ts +33 -0
- package/dist/local/transactions/mutations/pendingDrain.js +112 -0
- package/dist/local/transactions/mutations/processingScheduler.d.ts +14 -0
- package/dist/local/transactions/mutations/processingScheduler.js +24 -0
- package/dist/local/transactions/mutations/queueCoalescing.d.ts +13 -0
- package/dist/local/transactions/mutations/queueCoalescing.js +35 -0
- package/dist/local/transactions/mutations/replayValidation.d.ts +187 -0
- package/dist/local/transactions/mutations/replayValidation.js +164 -0
- package/dist/local/transactions/reconnectDrain.d.ts +11 -0
- package/dist/local/transactions/reconnectDrain.js +13 -0
- package/dist/local/utils/mobxSetup.d.ts +53 -0
- package/dist/local/utils/mobxSetup.js +330 -0
- package/dist/local/views/QueryView.d.ts +79 -0
- package/dist/local/views/QueryView.js +218 -0
- package/dist/local/views/ViewRegistry.d.ts +20 -0
- package/dist/local/views/ViewRegistry.js +57 -0
- package/dist/local/views/incrementalView.d.ts +45 -0
- package/dist/local/views/incrementalView.js +69 -0
- package/dist/plugin.d.ts +285 -0
- package/dist/plugin.js +106 -0
- package/dist/presenceStream.d.ts +69 -0
- package/dist/presenceStream.js +200 -0
- package/dist/react/AbloProvider.d.ts +242 -0
- package/dist/react/AbloProvider.js +456 -0
- package/dist/react/ClientSideSuspense.d.ts +36 -0
- package/dist/react/ClientSideSuspense.js +17 -0
- package/dist/react/DefaultFallback.d.ts +24 -0
- package/dist/react/DefaultFallback.js +43 -0
- package/dist/react/context.d.ts +55 -0
- package/dist/react/context.js +29 -0
- package/dist/react/createAbloReact.d.ts +50 -0
- package/dist/react/createAbloReact.js +48 -0
- package/dist/react/internalContext.d.ts +33 -0
- package/dist/react/internalContext.js +3 -0
- package/dist/react/useAblo.d.ts +96 -0
- package/dist/react/useAblo.js +120 -0
- package/dist/react/useCurrentUserId.d.ts +2 -0
- package/dist/react/useCurrentUserId.js +12 -0
- package/dist/react/useErrorListener.d.ts +2 -0
- package/dist/react/useErrorListener.js +14 -0
- package/dist/react/useMutationFailureListener.d.ts +8 -0
- package/dist/react/useMutationFailureListener.js +19 -0
- package/dist/react/useMutators.d.ts +56 -0
- package/dist/react/useMutators.js +84 -0
- package/dist/react/useSyncStatus.d.ts +19 -0
- package/dist/react/useSyncStatus.js +37 -0
- package/dist/react/useUndoScope.d.ts +34 -0
- package/dist/react/useUndoScope.js +73 -0
- package/dist/react.d.ts +18 -0
- package/dist/react.js +14 -0
- package/dist/reactRuntime.d.ts +4 -0
- package/dist/reactRuntime.js +2 -0
- package/dist/surface.d.ts +36 -0
- package/dist/surface.js +77 -0
- package/dist/useReactive.d.ts +6 -0
- package/dist/useReactive.js +43 -0
- package/package.json +119 -0
- package/src/Ablo.ts +456 -0
- package/src/client.ts +374 -0
- package/src/core.ts +104 -0
- package/src/humans.ts +61 -0
- package/src/index.ts +40 -0
- package/src/local/BaseSyncedStore.ts +1991 -0
- package/src/local/Database.ts +2052 -0
- package/src/local/InstanceCache.ts +1503 -0
- package/src/local/LazyReferenceCollection.ts +563 -0
- package/src/local/Model.ts +1124 -0
- package/src/local/ModelRegistry.ts +762 -0
- package/src/local/NetworkMonitor.ts +88 -0
- package/src/local/RuntimeContext.ts +141 -0
- package/src/local/SyncClient.ts +2131 -0
- package/src/local/adapters/alwaysOnline.ts +20 -0
- package/src/local/adapters/inMemoryStorage.ts +141 -0
- package/src/local/client/clientPrelude.ts +112 -0
- package/src/local/client/consoleLogger.ts +60 -0
- package/src/local/client/createInternalComponents.ts +163 -0
- package/src/local/client/createModelProxy.ts +1390 -0
- package/src/local/client/modelRegistration.ts +350 -0
- package/src/local/client/options.ts +526 -0
- package/src/local/client/reactiveEngine.ts +935 -0
- package/src/local/client/resourceTypes.ts +37 -0
- package/src/local/client/schemaConfig.ts +194 -0
- package/src/local/client/storeCluster.ts +172 -0
- package/src/local/client/storeLifecycle.ts +343 -0
- package/src/local/client/validateAbloOptions.ts +95 -0
- package/src/local/client/wsMutationExecutor.ts +110 -0
- package/src/local/context.ts +96 -0
- package/src/local/coordination/ClaimLog.ts +39 -0
- package/src/local/interfaces/index.ts +468 -0
- package/src/local/localModelContract.ts +15 -0
- package/src/local/logPosition.ts +84 -0
- package/src/local/mutationPersistence.ts +7 -0
- package/src/local/mutators/RecordingMutation.ts +222 -0
- package/src/local/mutators/Transaction.ts +97 -0
- package/src/local/mutators/UndoManager.ts +741 -0
- package/src/local/mutators/defineMutators.ts +76 -0
- package/src/local/mutators/inverseOp.ts +83 -0
- package/src/local/mutators/mutateActions.ts +167 -0
- package/src/local/mutators/readerActions.ts +99 -0
- package/src/local/mutators/undoApply.ts +141 -0
- package/src/local/persistence.ts +16 -0
- package/src/local/query/QueryProcessor.ts +347 -0
- package/src/local/query/client.ts +197 -0
- package/src/local/query/types.ts +102 -0
- package/src/local/schema/serialize.ts +1 -0
- package/src/local/store/queryApi.ts +56 -0
- package/src/local/storeContract.ts +146 -0
- package/src/local/stores/DatabaseManager.ts +507 -0
- package/src/local/stores/ObjectStore.ts +449 -0
- package/src/local/stores/ObjectStoreContract.ts +48 -0
- package/src/local/stores/StoreManager.ts +388 -0
- package/src/local/stores/SyncActionStore.ts +579 -0
- package/src/local/stores/openIDBWithTimeout.ts +195 -0
- package/src/local/stores/persistenceCleanup.ts +43 -0
- package/src/local/stores/persistenceIdentity.ts +83 -0
- package/src/local/stores/syncAction.ts +21 -0
- package/src/local/stores/v1PersistenceDeletion.ts +21 -0
- package/src/local/sync/BootstrapFetcher.ts +1224 -0
- package/src/local/sync/ConnectionManager.ts +15 -0
- package/src/local/sync/OnDemandLoader.ts +927 -0
- package/src/local/sync/SubscriptionManager.ts +300 -0
- package/src/local/sync/SyncWebSocket.ts +584 -0
- package/src/local/sync/bootstrapApply.ts +130 -0
- package/src/local/sync/commitFrames.ts +16 -0
- package/src/local/sync/connectionManagerLifecycle.ts +158 -0
- package/src/local/sync/contextPorts.ts +37 -0
- package/src/local/sync/createClaimStream.ts +668 -0
- package/src/local/sync/createSnapshot.ts +160 -0
- package/src/local/sync/credentialLifecycle.ts +18 -0
- package/src/local/sync/deltaPipeline.ts +473 -0
- package/src/local/sync/groupChange.ts +343 -0
- package/src/local/sync/initialize.ts +205 -0
- package/src/local/sync/participants.ts +564 -0
- package/src/local/sync/persistedPrefix.ts +27 -0
- package/src/local/sync/reconnect.ts +88 -0
- package/src/local/sync/schemaDrift.ts +86 -0
- package/src/local/sync/schemas.ts +118 -0
- package/src/local/sync/socketEventWiring.ts +196 -0
- package/src/local/sync/syncCursor.ts +62 -0
- package/src/local/sync/syncPlan.ts +89 -0
- package/src/local/sync/terminalSessionLifecycle.ts +66 -0
- package/src/local/sync/wsFrameHandlers.ts +20 -0
- package/src/local/transactions/databaseCommitOutbox.ts +33 -0
- package/src/local/transactions/localMutation.ts +58 -0
- package/src/local/transactions/mutations/MutationQueue.ts +1998 -0
- package/src/local/transactions/mutations/MutationStore.ts +65 -0
- package/src/local/transactions/mutations/UnconfirmedWrites.ts +133 -0
- package/src/local/transactions/mutations/batchProcessing.ts +469 -0
- package/src/local/transactions/mutations/coalesceRules.ts +192 -0
- package/src/local/transactions/mutations/commitApi.ts +97 -0
- package/src/local/transactions/mutations/commitLane.ts +191 -0
- package/src/local/transactions/mutations/commitLatency.ts +164 -0
- package/src/local/transactions/mutations/commitPayload.ts +281 -0
- package/src/local/transactions/mutations/commitTransport.ts +174 -0
- package/src/local/transactions/mutations/deltaConfirmation.ts +298 -0
- package/src/local/transactions/mutations/durableCommitRestore.ts +128 -0
- package/src/local/transactions/mutations/durableWriteStore.ts +21 -0
- package/src/local/transactions/mutations/executionSelection.ts +42 -0
- package/src/local/transactions/mutations/failureHandling.ts +154 -0
- package/src/local/transactions/mutations/failurePolicy.ts +61 -0
- package/src/local/transactions/mutations/localMutation.ts +135 -0
- package/src/local/transactions/mutations/modelOperations.ts +210 -0
- package/src/local/transactions/mutations/mutationPersistence.ts +231 -0
- package/src/local/transactions/mutations/pendingDrain.ts +160 -0
- package/src/local/transactions/mutations/processingScheduler.ts +35 -0
- package/src/local/transactions/mutations/queueCoalescing.ts +45 -0
- package/src/local/transactions/mutations/replayValidation.ts +192 -0
- package/src/local/transactions/reconnectDrain.ts +24 -0
- package/src/local/utils/mobxSetup.ts +388 -0
- package/src/local/views/QueryView.ts +311 -0
- package/src/local/views/ViewRegistry.ts +61 -0
- package/src/local/views/incrementalView.ts +92 -0
- package/src/plugin.ts +396 -0
- package/src/presenceStream.ts +279 -0
- package/src/react/AbloProvider.tsx +744 -0
- package/src/react/ClientSideSuspense.tsx +57 -0
- package/src/react/DefaultFallback.tsx +60 -0
- package/src/react/context.ts +89 -0
- package/src/react/createAbloReact.ts +116 -0
- package/src/react/internalContext.ts +38 -0
- package/src/react/useAblo.ts +280 -0
- package/src/react/useCurrentUserId.ts +17 -0
- package/src/react/useErrorListener.ts +22 -0
- package/src/react/useMutationFailureListener.ts +34 -0
- package/src/react/useMutators.ts +184 -0
- package/src/react/useSyncStatus.ts +42 -0
- package/src/react/useUndoScope.ts +143 -0
- package/src/react.ts +69 -0
- package/src/reactRuntime.ts +10 -0
- package/src/surface.ts +106 -0
- package/src/useReactive.ts +51 -0
|
@@ -0,0 +1,1390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the typed client for a single schema model — the object reached as
|
|
3
|
+
* `ablo.<model>`.
|
|
4
|
+
*
|
|
5
|
+
* Each schema model gets one {@link ModelOperations}: the async server reads
|
|
6
|
+
* `get` and `list`, with the same point lookup restricted to the local graph under
|
|
7
|
+
* `local`, the writes `create`, `update`, and `delete`, the coordination
|
|
8
|
+
* namespace `claim` (callable as `claim({ id })`, plus `claim.state`,
|
|
9
|
+
* `claim.queue`, `claim.release`, and `claim.reorder`), `join`, and `onChange`.
|
|
10
|
+
* The factory returns a plain object; the client assembles the `ablo.<model>`
|
|
11
|
+
* lookup table from one of these per model.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { autorun } from 'mobx';
|
|
15
|
+
import {
|
|
16
|
+
AbloClaimedError,
|
|
17
|
+
AbloValidationError,
|
|
18
|
+
toAbloError,
|
|
19
|
+
} from '@abloatai/transaction/errors';
|
|
20
|
+
import {
|
|
21
|
+
reconcileFunctionalUpdate,
|
|
22
|
+
type ModelUpdater,
|
|
23
|
+
type ContentionOptions,
|
|
24
|
+
} from '@abloatai/transaction/resources/functionalUpdate';
|
|
25
|
+
import type { MutationOptions } from '../interfaces/index.js';
|
|
26
|
+
import {
|
|
27
|
+
claimDescription,
|
|
28
|
+
type TrackDependency,
|
|
29
|
+
} from '@abloatai/transaction/coordination/schema';
|
|
30
|
+
import { Model, modelAsRow } from '../Model.js';
|
|
31
|
+
import { toMs } from '@abloatai/transaction/utils/duration';
|
|
32
|
+
import { LEASE_TTL_MS } from '@abloatai/transaction/wire/protocol';
|
|
33
|
+
import {
|
|
34
|
+
heartbeatCadenceMs,
|
|
35
|
+
resolveHeartbeatOptions,
|
|
36
|
+
resolveHeartbeatPlan,
|
|
37
|
+
startClaimHeartbeatLoop,
|
|
38
|
+
} from '@abloatai/transaction/coordination/claimHeartbeatLoop';
|
|
39
|
+
import { assertWriteOptions } from '@abloatai/transaction/resources/writeOptionsSchema';
|
|
40
|
+
import { subTarget } from '@abloatai/transaction/coordination';
|
|
41
|
+
// A named claim-meta crossing (see `claim-meta-crossings-are-enumerated` in
|
|
42
|
+
// .dependency-cruiser.cjs): the reactive proxy's self-claim targets are
|
|
43
|
+
// decodes that build a public claim, so their `meta` converts wire→declared
|
|
44
|
+
// here like the other enumerated crossings.
|
|
45
|
+
import { declaredMeta } from '@abloatai/transaction/coordination/claimMeta';
|
|
46
|
+
import type { ModelTarget } from '@abloatai/transaction/coordination/schema';
|
|
47
|
+
import type { ModelRegistry } from '../ModelRegistry.js';
|
|
48
|
+
import type { InstanceCache } from '../InstanceCache.js';
|
|
49
|
+
import type { SyncClient } from '../SyncClient.js';
|
|
50
|
+
import type { OnDemandLoader } from '../sync/OnDemandLoader.js';
|
|
51
|
+
import type { JoinedParticipant } from '../sync/participants.js';
|
|
52
|
+
import { ModelScope } from '@abloatai/transaction/types';
|
|
53
|
+
import type {
|
|
54
|
+
Duration,
|
|
55
|
+
Claim,
|
|
56
|
+
ClaimHeartbeat,
|
|
57
|
+
ClaimHeartbeatOptions,
|
|
58
|
+
HeldClaim,
|
|
59
|
+
HeldLease,
|
|
60
|
+
ClaimWaitOptions,
|
|
61
|
+
ClaimTarget,
|
|
62
|
+
Snapshot,
|
|
63
|
+
} from '@abloatai/transaction/types/streams';
|
|
64
|
+
|
|
65
|
+
// The request contract — every option and parameter shape a caller passes to a
|
|
66
|
+
// read, a write, or a claim — lives in the settlement core (ADR 0016). This
|
|
67
|
+
// factory binds it to reactive model instances; the shapes themselves are
|
|
68
|
+
// transport- and consumer-agnostic. Re-exported so `./createModelProxy` stays a
|
|
69
|
+
// working import path for the whole surface.
|
|
70
|
+
export type {
|
|
71
|
+
ModelListScope,
|
|
72
|
+
ModelTrackParams,
|
|
73
|
+
ModelTrackResult,
|
|
74
|
+
LocalReadOptions,
|
|
75
|
+
LocalCountOptions,
|
|
76
|
+
ServerReadOptions,
|
|
77
|
+
ServerGetOptions,
|
|
78
|
+
ServerRetrieveOptions,
|
|
79
|
+
ClaimTargetOptions,
|
|
80
|
+
ClaimParams,
|
|
81
|
+
ClaimLookupParams,
|
|
82
|
+
ClaimReorderParams,
|
|
83
|
+
ClaimOptions,
|
|
84
|
+
ClaimReadApi,
|
|
85
|
+
AwaitedClaimMethod,
|
|
86
|
+
ClaimApi,
|
|
87
|
+
ModelRetrieveParams,
|
|
88
|
+
ModelCreateParams,
|
|
89
|
+
ModelUpdateParams,
|
|
90
|
+
ModelDeleteParams,
|
|
91
|
+
JoinOptions,
|
|
92
|
+
} from '@abloatai/transaction/resources/modelOperations';
|
|
93
|
+
export type { Claim, ClaimHeartbeat, ClaimHeartbeatOptions, HeldClaim, HeldLease };
|
|
94
|
+
|
|
95
|
+
import type {
|
|
96
|
+
ClaimApi,
|
|
97
|
+
ClaimLookupParams,
|
|
98
|
+
ClaimOptions,
|
|
99
|
+
ClaimParams,
|
|
100
|
+
ClaimReorderParams,
|
|
101
|
+
JoinOptions,
|
|
102
|
+
LocalCountOptions,
|
|
103
|
+
LocalReadOptions,
|
|
104
|
+
ModelCreateParams,
|
|
105
|
+
ModelDeleteParams,
|
|
106
|
+
ModelRetrieveParams,
|
|
107
|
+
ModelTrackParams,
|
|
108
|
+
ModelTrackResult,
|
|
109
|
+
ModelUpdateParams,
|
|
110
|
+
ServerReadOptions,
|
|
111
|
+
} from '@abloatai/transaction/resources/modelOperations';
|
|
112
|
+
import type { HttpModelClient } from '@abloatai/transaction/transport/httpClient';
|
|
113
|
+
import type { ParticipantKind } from '@abloatai/transaction/types/participant';
|
|
114
|
+
|
|
115
|
+
export interface ModelClientMeta {
|
|
116
|
+
readonly key: string;
|
|
117
|
+
readonly typename: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const modelClientMeta = new WeakMap<object, ModelClientMeta>();
|
|
121
|
+
|
|
122
|
+
export function getModelClientMeta(modelClient: unknown): ModelClientMeta | undefined {
|
|
123
|
+
if (typeof modelClient !== 'object' || modelClient === null) return undefined;
|
|
124
|
+
return modelClientMeta.get(modelClient);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The entity a coordination read names, without the sub-entity narrowing —
|
|
130
|
+
* projected from {@link ModelTarget} so the two members are spelled once.
|
|
131
|
+
*/
|
|
132
|
+
type EntityHalf = Pick<ModelTarget, 'model' | 'id'>;
|
|
133
|
+
|
|
134
|
+
// Model-agnostic by construction: every member below names a target by
|
|
135
|
+
// `{ model, id }` and answers in claim/snapshot terms, so the row type never
|
|
136
|
+
// appears. It carried a `<T>` that nothing in the body read, which made
|
|
137
|
+
// `ModelCollaboration<Task>` and `ModelCollaboration<Invoice>` the same type
|
|
138
|
+
// while reading as though they differed.
|
|
139
|
+
export interface ModelCollaboration {
|
|
140
|
+
createClaim(options: {
|
|
141
|
+
/**
|
|
142
|
+
* The locator, in the spelling the SDK surface and the HTTP routes use.
|
|
143
|
+
* The canonical {@link ModelTarget} rather than a shape spelled here: this
|
|
144
|
+
* boundary is what a claim's narrowing has to cross, and a member missing
|
|
145
|
+
* from it dies before the socket sees it.
|
|
146
|
+
*/
|
|
147
|
+
target: ModelTarget;
|
|
148
|
+
/** Peer-visible description of the work (`'rewriting the risk section'`). */
|
|
149
|
+
description?: string;
|
|
150
|
+
ttl?: Duration;
|
|
151
|
+
/**
|
|
152
|
+
* Block on the server's fair FIFO queue when the target is held, rather
|
|
153
|
+
* than failing. Resolves only once the lease is genuinely ours (the head
|
|
154
|
+
* of the line). `takeClaim` sets this so writers serialize on contention.
|
|
155
|
+
*/
|
|
156
|
+
queue?: boolean;
|
|
157
|
+
/** Reject (don't wait) if the queue is already this deep when we join. */
|
|
158
|
+
maxQueueDepth?: number;
|
|
159
|
+
/** Cap on the queued wait before rejecting with `grant_timeout`. */
|
|
160
|
+
waitTimeoutMs?: number;
|
|
161
|
+
/** Abort the queued wait — rejects with `claim_wait_aborted`. */
|
|
162
|
+
signal?: AbortSignal;
|
|
163
|
+
}): Promise<Claim>;
|
|
164
|
+
createSnapshot(modelKey: string, id: string): Snapshot;
|
|
165
|
+
/**
|
|
166
|
+
* Current coordination state on a target — who (if anyone) holds it.
|
|
167
|
+
* Synchronous reactive snapshot read off the presence/claim stream;
|
|
168
|
+
* `null` when the target is free. The wiring site computes it because
|
|
169
|
+
* only it knows the local participant id (needed to distinguish "I
|
|
170
|
+
* hold it" from "someone else holds it").
|
|
171
|
+
*
|
|
172
|
+
* Named `state` to match the public `ablo.<model>.claim.state({ id })` read —
|
|
173
|
+
* one verb for "who holds this" across every claim surface; the only
|
|
174
|
+
* difference is this internal contract takes an explicit `{ model, id }`
|
|
175
|
+
* target because it isn't bound to a single model.
|
|
176
|
+
*/
|
|
177
|
+
state(target: EntityHalf): Claim | null;
|
|
178
|
+
/**
|
|
179
|
+
* Every active claim on a target, not just one. Sub-row claims on disjoint
|
|
180
|
+
* parts of a row are all granted, so a row can have several holders at once
|
|
181
|
+
* and `state` answers with only the first of them.
|
|
182
|
+
*/
|
|
183
|
+
holders(target: EntityHalf): readonly Claim[];
|
|
184
|
+
/**
|
|
185
|
+
* The reactive wait queue on a target — the FIFO line of queued claims
|
|
186
|
+
* behind the holder. Synchronous snapshot off the synced claim stream.
|
|
187
|
+
*/
|
|
188
|
+
queue(target: EntityHalf): readonly Claim[];
|
|
189
|
+
/**
|
|
190
|
+
* Re-rank the wait queue on a target (privileged — server-gated). `order` is
|
|
191
|
+
* the desired front-of-line ordering, taken from `queue(target)`.
|
|
192
|
+
*/
|
|
193
|
+
reorder(target: EntityHalf, order: readonly Claim[]): void;
|
|
194
|
+
/**
|
|
195
|
+
* Resolve once no participant holds an active claim on the target.
|
|
196
|
+
* The contender's "wait until it's free" — delegates to the claim
|
|
197
|
+
* stream's `waitFor`.
|
|
198
|
+
*/
|
|
199
|
+
waitFor(
|
|
200
|
+
target: EntityHalf,
|
|
201
|
+
options?: ClaimWaitOptions,
|
|
202
|
+
): Promise<void>;
|
|
203
|
+
/**
|
|
204
|
+
* The local participant's id. Used to distinguish "I already hold this"
|
|
205
|
+
* from "someone else holds it" in `claimOrWait`.
|
|
206
|
+
*/
|
|
207
|
+
readonly selfParticipantId: string;
|
|
208
|
+
/**
|
|
209
|
+
* The local participant's kind (`'user' | 'agent' | 'system'`). Used to stamp
|
|
210
|
+
* the synthesized self-claim returned from `claim.state` when this client
|
|
211
|
+
* holds the lease: server presence frames exclude a holder's own claims, so
|
|
212
|
+
* the holder builds its own view.
|
|
213
|
+
*/
|
|
214
|
+
readonly selfParticipantKind?: ParticipantKind;
|
|
215
|
+
/**
|
|
216
|
+
* Subscribes the connection to a scope's sync group(s) — read interest. The
|
|
217
|
+
* typed surface calls this on single-entity reads and claim observation so a
|
|
218
|
+
* client lands in the same entity-scoped group the holder's claim presence
|
|
219
|
+
* fans out on; a peer subscribed only to broader `org:` or `user:` groups
|
|
220
|
+
* would otherwise never see claim broadcasts. Fire-and-forget and best-effort:
|
|
221
|
+
* read interest must never make a read reject or stall. Optional so minimal
|
|
222
|
+
* test doubles can omit it.
|
|
223
|
+
*/
|
|
224
|
+
enterScope?(scope: Record<string, string>): void | Promise<void>;
|
|
225
|
+
/**
|
|
226
|
+
* Pins a scope's sync group(s) — write intent: a row this client holds an
|
|
227
|
+
* active claim on stays subscribed regardless of navigation. Same
|
|
228
|
+
* fire-and-forget, best-effort semantics as `enterScope`.
|
|
229
|
+
*/
|
|
230
|
+
pinScope?(scope: Record<string, string>): void | Promise<void>;
|
|
231
|
+
/**
|
|
232
|
+
* Opens a presence and claim subscription on this model's sync group(s) and
|
|
233
|
+
* returns the live participant handle. Backs `ablo.<model>.join(ids)`.
|
|
234
|
+
* WebSocket only, since presence needs a live socket; it is absent on other
|
|
235
|
+
* client constructions, where the proxy throws a clear error.
|
|
236
|
+
*/
|
|
237
|
+
createJoin?(
|
|
238
|
+
modelKey: string,
|
|
239
|
+
ids: string | readonly string[],
|
|
240
|
+
options?: JoinOptions,
|
|
241
|
+
): Promise<JoinedParticipant>;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The synchronous, local-only reads — reached as `ablo.<model>.local.*`.
|
|
247
|
+
*
|
|
248
|
+
* Every verb mirrors its asynchronous sibling on the base surface, and the one
|
|
249
|
+
* word in front is the whole difference. It is a narrowing, not a claim about
|
|
250
|
+
* the other side: `get` consults the local graph and then the network,
|
|
251
|
+
* while `local.get` is restricted to what is already resident — which is
|
|
252
|
+
* also why it can return a value instead of a promise. There is nothing to
|
|
253
|
+
* await.
|
|
254
|
+
*
|
|
255
|
+
* These reads exist only here. Exposing them at the top level too would undo
|
|
256
|
+
* the distinction the namespace draws.
|
|
257
|
+
*/
|
|
258
|
+
export interface LocalReads<T> {
|
|
259
|
+
/**
|
|
260
|
+
* Snapshot of a single row from the local graph. `undefined` when the row is
|
|
261
|
+
* not resident — a graph that is still empty, or a `lazy` model not yet
|
|
262
|
+
* loaded. Pairs with reactive selectors:
|
|
263
|
+
* `useAblo((ablo) => ablo.<model>.local.get(id))`.
|
|
264
|
+
*/
|
|
265
|
+
get(id: string): T | undefined;
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Snapshot of a filtered collection from the local graph. Empty until
|
|
269
|
+
* `get`, `list`, or bootstrap has warmed the graph.
|
|
270
|
+
*/
|
|
271
|
+
list(options?: LocalReadOptions<T>): T[];
|
|
272
|
+
|
|
273
|
+
/** Count rows in the local graph. */
|
|
274
|
+
count(options?: LocalCountOptions<T>): number;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* What a reactive client adds on top of the base per-model surface: a live
|
|
279
|
+
* graph to read (`local`), the synchronous projection of the claim reads, and
|
|
280
|
+
* the two subscriptions a persistent socket makes possible.
|
|
281
|
+
*
|
|
282
|
+
* `claim` is here rather than inherited because the two transports carry
|
|
283
|
+
* deliberately different claim types, and the difference is load-bearing: a
|
|
284
|
+
* stateless client has no local copy, so `state`/`queue`/`reorder` must be
|
|
285
|
+
* awaited, while a reactive client resolves them synchronously — which is
|
|
286
|
+
* precisely what lets a React render read claim state inline. The stateless
|
|
287
|
+
* form is *derived* from this one through {@link AwaitedClaimMethod}, so the
|
|
288
|
+
* only permitted difference between them is that promise wrapper.
|
|
289
|
+
*/
|
|
290
|
+
interface ReactiveModelSurface<T, Fields = T> {
|
|
291
|
+
/** The synchronous local-graph reads. */
|
|
292
|
+
local: LocalReads<T>;
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Claim a row so other writers wait or are rejected until you're done, and
|
|
296
|
+
* inspect or manage that coordination through the same namespace. Call it to
|
|
297
|
+
* take a claim handle; reach for its members to observe and steer the wait line:
|
|
298
|
+
*
|
|
299
|
+
* - `claim.state({ id })` — who holds the row now, or `null` when free
|
|
300
|
+
* - `claim.queue({ id })` — who's lined up behind the holder
|
|
301
|
+
* - `claim.release({ id })` — drop a claim early (usually implicit on scope exit)
|
|
302
|
+
* - `claim.reorder({ id, order })` — re-rank the wait line
|
|
303
|
+
*
|
|
304
|
+
* ```ts
|
|
305
|
+
* const claim = await ablo.weatherReports.claim({
|
|
306
|
+
* id: 'report_stockholm',
|
|
307
|
+
* description: 'Fetching fresh weather before updating the report.',
|
|
308
|
+
* });
|
|
309
|
+
* const weather = await getWeather(claim.data.location);
|
|
310
|
+
* await ablo.weatherReports.update({
|
|
311
|
+
* id: claim.target.id,
|
|
312
|
+
* data: { forecast: weather },
|
|
313
|
+
* claim,
|
|
314
|
+
* });
|
|
315
|
+
* await claim.release();
|
|
316
|
+
*
|
|
317
|
+
* const holder = ablo.weatherReports.claim.state({ id: 'report_stockholm' });
|
|
318
|
+
* ```
|
|
319
|
+
*/
|
|
320
|
+
claim: ClaimApi<T, Fields>;
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Joins the sync group(s) for one or more rows of this model and returns a
|
|
324
|
+
* live participant handle — presence (`.peers`), the scoped claim stream
|
|
325
|
+
* (`.claims`), and `.leave()` / `await using` disposal. This is a presence
|
|
326
|
+
* subscription: it reports who else is here and what they hold, not row
|
|
327
|
+
* values changing — for the latter, use `onChange`.
|
|
328
|
+
*
|
|
329
|
+
* WebSocket only: presence needs a live socket, so this is absent on HTTP
|
|
330
|
+
* clients and throws on any non-WebSocket construction.
|
|
331
|
+
*
|
|
332
|
+
* ```ts
|
|
333
|
+
* await using participant = await ablo.sections.join(sectionIds, { ttl: '5m' });
|
|
334
|
+
* participant.peers; // who else is here
|
|
335
|
+
* ```
|
|
336
|
+
*/
|
|
337
|
+
join(
|
|
338
|
+
ids: string | readonly string[],
|
|
339
|
+
options?: JoinOptions,
|
|
340
|
+
): Promise<JoinedParticipant>;
|
|
341
|
+
|
|
342
|
+
/** Subscribe to changes; the callback runs on every change. */
|
|
343
|
+
onChange(
|
|
344
|
+
callback: (entities: T[]) => void,
|
|
345
|
+
options?: LocalReadOptions<T>,
|
|
346
|
+
): () => void;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Everything reachable as `ablo.<model>` on a reactive client.
|
|
351
|
+
*
|
|
352
|
+
* The base is not written here — it is the transport-independent per-model
|
|
353
|
+
* surface, taken whole. A reactive client is that surface plus what a live
|
|
354
|
+
* graph makes possible, so this type states the relationship instead of
|
|
355
|
+
* restating the members, and a verb added to the base arrives here on its own.
|
|
356
|
+
*
|
|
357
|
+
* `claim` is the one member the base cannot supply directly: the two forms
|
|
358
|
+
* differ by an awaitedness transform, so it is replaced rather than inherited.
|
|
359
|
+
* See {@link ReactiveModelSurface}.
|
|
360
|
+
*/
|
|
361
|
+
export type ModelOperations<T, CreateInput> = Omit<
|
|
362
|
+
HttpModelClient<T, CreateInput>,
|
|
363
|
+
'claim'
|
|
364
|
+
> &
|
|
365
|
+
ReactiveModelSurface<T, CreateInput>;
|
|
366
|
+
|
|
367
|
+
export function createModelProxy<T, C>(
|
|
368
|
+
schemaKey: string,
|
|
369
|
+
registeredModelName: string,
|
|
370
|
+
objectPool: Pick<InstanceCache, 'get' | 'getByType' | 'getOfType'>,
|
|
371
|
+
syncClient: Pick<
|
|
372
|
+
SyncClient,
|
|
373
|
+
| 'add'
|
|
374
|
+
| 'delete'
|
|
375
|
+
| 'getMutationQueue'
|
|
376
|
+
| 'getOrganizationId'
|
|
377
|
+
| 'syncNow'
|
|
378
|
+
| 'update'
|
|
379
|
+
| 'waitForConfirmation'
|
|
380
|
+
>,
|
|
381
|
+
registry: Pick<ModelRegistry, 'getModelByName'>,
|
|
382
|
+
/**
|
|
383
|
+
* The one thing this factory asks of the loader: fetch rows for a model.
|
|
384
|
+
*
|
|
385
|
+
* Declared as the slice rather than the whole `OnDemandLoader` because the
|
|
386
|
+
* whole is a class, and a parameter typed as a class can only ever be
|
|
387
|
+
* satisfied by an instance of it — so every caller that has a narrower
|
|
388
|
+
* collaborator, a test most of all, is pushed into a cast through `unknown`
|
|
389
|
+
* to supply the one method that is actually read.
|
|
390
|
+
*/
|
|
391
|
+
hydration: Pick<OnDemandLoader, 'fetch'>,
|
|
392
|
+
collaboration?: ModelCollaboration,
|
|
393
|
+
/** The client-wide `wait` default; a per-call `wait` still wins over it. */
|
|
394
|
+
defaultWait?: 'queued' | 'confirmed',
|
|
395
|
+
): ModelOperations<T, C> {
|
|
396
|
+
/**
|
|
397
|
+
* Resolve a row **this** resource owns.
|
|
398
|
+
*
|
|
399
|
+
* The pool is one id space, so `objectPool.get(id)` happily returns another
|
|
400
|
+
* model's row. Every write path below addresses rows by bare id, so without
|
|
401
|
+
* this an id from a sibling model resolves and gets written — silently
|
|
402
|
+
* corrupting a row the caller never named.
|
|
403
|
+
*
|
|
404
|
+
* `undefined` means genuinely absent. A row belonging to another model throws:
|
|
405
|
+
* unlike a read, a cross-model *write* is never a legitimate outcome, and
|
|
406
|
+
* naming both models turns a silent corruption into a one-line diagnosis.
|
|
407
|
+
*/
|
|
408
|
+
const ownRowOrThrow = (id: string): Model | undefined => {
|
|
409
|
+
const own = objectPool.getOfType(id, registeredModelName);
|
|
410
|
+
if (own) return own;
|
|
411
|
+
const foreign = objectPool.get(id);
|
|
412
|
+
if (!foreign) return undefined;
|
|
413
|
+
const owner = foreign.getModelName();
|
|
414
|
+
throw new AbloValidationError(
|
|
415
|
+
`No ${registeredModelName} with id ${id} — that id belongs to a ${owner}. ` +
|
|
416
|
+
`Read or write it through ${owner}.`,
|
|
417
|
+
{ code: 'entity_not_found' },
|
|
418
|
+
);
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
const ModelClass = registry.getModelByName(registeredModelName);
|
|
422
|
+
if (!ModelClass) {
|
|
423
|
+
throw new AbloValidationError(
|
|
424
|
+
`Ablo: schema model "${schemaKey}" resolved to "${registeredModelName}", ` +
|
|
425
|
+
'but no matching constructor was registered.',
|
|
426
|
+
{ code: 'model_not_registered' },
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// The coordination plane must speak the same wire dialect as the commit
|
|
431
|
+
// plane: the lowercased typename (`task`), not the schema key (`tasks`). The
|
|
432
|
+
// server's commit-time claim guard probes the lease store with the commit
|
|
433
|
+
// operation's model name, so a lease recorded under the schema key never
|
|
434
|
+
// matches — which would silently disarm the guard for every model whose
|
|
435
|
+
// schema key differs from its typename (a plural key against a singular
|
|
436
|
+
// typename, i.e. nearly all of them). Public surfaces such as
|
|
437
|
+
// `Claim.target.model` keep the schema key; only the wire and coordination
|
|
438
|
+
// targets use this.
|
|
439
|
+
const wireModel = registeredModelName.toLowerCase();
|
|
440
|
+
|
|
441
|
+
// Last-line guarantee for the public surface: any rejection from a lower
|
|
442
|
+
// layer (transport timeout, IndexedDB failure, a third-party throw) is
|
|
443
|
+
// coerced to an AbloError before it reaches the consumer. The SDK's
|
|
444
|
+
// contract is that callers only ever catch tagged errors — `instanceof
|
|
445
|
+
// AbloError` / `e.type` always hold. Internal helpers stay unwrapped; only
|
|
446
|
+
// the methods exposed on `operations` are guarded.
|
|
447
|
+
const guard = <A extends unknown[], R>(
|
|
448
|
+
fn: (...args: A) => Promise<R>,
|
|
449
|
+
): ((...args: A) => Promise<R>) => {
|
|
450
|
+
return async (...args: A): Promise<R> => {
|
|
451
|
+
try {
|
|
452
|
+
return await fn(...args);
|
|
453
|
+
} catch (err) {
|
|
454
|
+
throw toAbloError(err);
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
const load = async (options?: ServerReadOptions<T>): Promise<T[]> => {
|
|
460
|
+
const rows = await hydration.fetch<T>(schemaKey, options);
|
|
461
|
+
return rows.map((row) => modelAsRow<T>(row));
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const waitForMutation = async (
|
|
465
|
+
model: Model,
|
|
466
|
+
options?: MutationOptions,
|
|
467
|
+
): Promise<void> => {
|
|
468
|
+
// A per-call `wait` wins; otherwise the client-wide default decides. This
|
|
469
|
+
// is the single point that turns "confirmed" into actually waiting, so a
|
|
470
|
+
// client configured that way rejects on a refused write everywhere rather
|
|
471
|
+
// than in the one place a caller remembered to ask.
|
|
472
|
+
if ((options?.wait ?? defaultWait) !== 'confirmed') return;
|
|
473
|
+
// Let sibling writes from the same synchronous burst enter the mutation
|
|
474
|
+
// queue before forcing a drain. Without this yield, every confirmed
|
|
475
|
+
// create/update calls syncNow() alone, defeating the queue's microtask
|
|
476
|
+
// coalescer and producing one SQL transaction per delta.
|
|
477
|
+
await Promise.resolve();
|
|
478
|
+
await syncClient.syncNow();
|
|
479
|
+
await syncClient.waitForConfirmation(model.getModelName(), model.id);
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
// Claims this proxy currently holds, keyed by entity id. Lets the flat
|
|
483
|
+
// `release({ id })` and `update({ id, data })` find the lease and snapshot a
|
|
484
|
+
// `claim({ id })` took, without a per-call handle. Released on dispose,
|
|
485
|
+
// explicit release, or TTL expiry.
|
|
486
|
+
//
|
|
487
|
+
// `target`, `description`, and `expiresAt` are kept alongside the lease so
|
|
488
|
+
// `claim.state` can synthesize a self-claim: the server excludes a holder's
|
|
489
|
+
// own presence frames, so this proxy is the only place that knows the client
|
|
490
|
+
// holds the row. `expiresAt` is the client's best estimate from the requested
|
|
491
|
+
// TTL (a real epoch-millisecond expiry, not a fabricated watermark), defaulting
|
|
492
|
+
// to the server's keepalive lease window when no TTL was requested.
|
|
493
|
+
const activeClaims = new Map<
|
|
494
|
+
string,
|
|
495
|
+
{
|
|
496
|
+
lease: Claim;
|
|
497
|
+
snapshot: Snapshot;
|
|
498
|
+
target: ClaimTarget;
|
|
499
|
+
description: string;
|
|
500
|
+
expiresAt: number;
|
|
501
|
+
}
|
|
502
|
+
>();
|
|
503
|
+
|
|
504
|
+
// Server keepalive lease window — the same `LEASE_TTL_MS` the wire protocol
|
|
505
|
+
// declares, so the client's estimate and the server's lease cannot drift.
|
|
506
|
+
// This is the fallback expiry estimate when a claim is taken without an
|
|
507
|
+
// explicit TTL.
|
|
508
|
+
const DEFAULT_LEASE_TTL_MS = LEASE_TTL_MS;
|
|
509
|
+
|
|
510
|
+
const isClaimHandle = (value: unknown): value is Claim<T> =>
|
|
511
|
+
typeof value === 'object' &&
|
|
512
|
+
value !== null &&
|
|
513
|
+
(value as { object?: unknown }).object === 'claim' &&
|
|
514
|
+
typeof (value as { id?: unknown }).id === 'string' &&
|
|
515
|
+
typeof (value as { release?: unknown }).release === 'function';
|
|
516
|
+
|
|
517
|
+
const mutationOptions = (
|
|
518
|
+
params:
|
|
519
|
+
| ModelCreateParams<T, C>
|
|
520
|
+
| ModelUpdateParams<T, C>
|
|
521
|
+
| ModelDeleteParams<T, C>,
|
|
522
|
+
): MutationOptions => {
|
|
523
|
+
const rest: MutationOptions = {
|
|
524
|
+
idempotencyKey: params.idempotencyKey,
|
|
525
|
+
label: params.label,
|
|
526
|
+
wait: params.wait,
|
|
527
|
+
readAt: params.readAt,
|
|
528
|
+
onStale: params.onStale,
|
|
529
|
+
fenceToken: params.fenceToken,
|
|
530
|
+
claimRef: params.claimRef,
|
|
531
|
+
reads: params.reads,
|
|
532
|
+
track: params.track,
|
|
533
|
+
};
|
|
534
|
+
// The write-options schema — the runtime twin of the compile-time params.
|
|
535
|
+
// Catches plain-JavaScript callers (for example `onStale: 'rejct'`) at the
|
|
536
|
+
// call site with a typed error instead of a silent no-op or a server 400.
|
|
537
|
+
assertWriteOptions(rest, `${schemaKey} write`);
|
|
538
|
+
return rest;
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
const releaseClaim = async (id: string): Promise<void> => {
|
|
542
|
+
const held = activeClaims.get(id);
|
|
543
|
+
if (!held) return;
|
|
544
|
+
activeClaims.delete(id);
|
|
545
|
+
await held.lease.release?.();
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
const takeClaim = async (
|
|
549
|
+
params: ClaimParams<C>,
|
|
550
|
+
): Promise<HeldClaim<T> | null> => {
|
|
551
|
+
if (!collaboration) {
|
|
552
|
+
throw new AbloValidationError(
|
|
553
|
+
`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`,
|
|
554
|
+
{ code: 'model_claim_not_configured' },
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
const { id, ...options } = params;
|
|
558
|
+
// Is someone else already on this target? Read the local coordination
|
|
559
|
+
// snapshot up front — it decides whether a re-read is needed after the
|
|
560
|
+
// claim (a free or already-held target cannot have changed underneath us).
|
|
561
|
+
const held = collaboration.state({ model: wireModel, id });
|
|
562
|
+
const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
|
|
563
|
+
const failFast = options.queue === false;
|
|
564
|
+
|
|
565
|
+
// The try-claim (`queue: false`): a held target is an expected outcome,
|
|
566
|
+
// not an error, so it resolves `null` — the caller reads `if (!claim)`
|
|
567
|
+
// and moves on; who holds it stays readable via `claim.state`. Best-effort
|
|
568
|
+
// at the client (a racing claim not yet synced into our snapshot slips
|
|
569
|
+
// through here) — the commit-time claim guard is the authoritative
|
|
570
|
+
// backstop that rejects the loser's first write. For work-distribution
|
|
571
|
+
// dedup that's exactly right: don't wait (that would double-process), skip.
|
|
572
|
+
if (failFast && contended) {
|
|
573
|
+
return null;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// Ensure the row exists locally before claiming.
|
|
577
|
+
let model = ownRowOrThrow(id);
|
|
578
|
+
if (!model) {
|
|
579
|
+
await load({ where: [['id', id]] });
|
|
580
|
+
model = ownRowOrThrow(id);
|
|
581
|
+
}
|
|
582
|
+
if (!model) {
|
|
583
|
+
throw new AbloValidationError(
|
|
584
|
+
`Entity not found: ${registeredModelName}/${id}`,
|
|
585
|
+
{ code: 'entity_not_found' },
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// Write intent: enter the entity scope before acquiring the lease so the
|
|
590
|
+
// holder's claim presence broadcasts to everyone in this entity group,
|
|
591
|
+
// including a peer that subscribed just before us. Pinning before the lease
|
|
592
|
+
// rather than after closes the subscribe-versus-broadcast race: the server
|
|
593
|
+
// fans presence out at claim time, so this client must be in the group when
|
|
594
|
+
// the claim lands. Awaited because the broadcast ordering depends on it;
|
|
595
|
+
// still best-effort (the store swallows reconcile errors).
|
|
596
|
+
await collaboration.pinScope?.({ [schemaKey]: id });
|
|
597
|
+
|
|
598
|
+
// Acquire the lease. By default (`queue` is not false) this goes through the
|
|
599
|
+
// server's fair FIFO queue: `queue: true` resolves only once the lease is
|
|
600
|
+
// genuinely ours, blocking behind any current holder, with no check-then-act
|
|
601
|
+
// gap because the server orders contenders. Fail-fast skips the queue: an
|
|
602
|
+
// observed conflict was already rejected above, so this just records the lease.
|
|
603
|
+
const lease = await collaboration.createClaim({
|
|
604
|
+
target: {
|
|
605
|
+
model: wireModel,
|
|
606
|
+
id,
|
|
607
|
+
// The whole sub-entity locator in one move — listing its members here
|
|
608
|
+
// is what let `fields` die between the caller and the lease, so the
|
|
609
|
+
// claim covered the whole row while the caller believed it named parts.
|
|
610
|
+
...subTarget(options, schemaKey),
|
|
611
|
+
},
|
|
612
|
+
description: claimDescription(options),
|
|
613
|
+
ttl: options.ttl,
|
|
614
|
+
queue: !failFast,
|
|
615
|
+
maxQueueDepth: options.maxQueueDepth,
|
|
616
|
+
// The one wait cap, declared once on ClaimTargetOptions — the socket
|
|
617
|
+
// wait and the HTTP poll-wait both honor it as `grant_timeout`.
|
|
618
|
+
waitTimeoutMs: options.waitTimeoutMs,
|
|
619
|
+
signal: options.signal,
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
// Only when the claim actually waited behind another holder can the row have
|
|
623
|
+
// changed underneath us — re-read so the claimed snapshot reflects what that
|
|
624
|
+
// holder committed before releasing. Either of two signals suffices:
|
|
625
|
+
// - `lease.waited` — the server granted the claim after the client
|
|
626
|
+
// provably queued behind a holder. Authoritative; it works even when the
|
|
627
|
+
// local snapshot is blind, since claim fan-out is entity-scoped and a
|
|
628
|
+
// broadly-subscribed client never observes peers' claims.
|
|
629
|
+
// - `contended` — the local snapshot saw a holder up front. Kept for the
|
|
630
|
+
// no-queue paths, where no grant frame exists.
|
|
631
|
+
if ((contended || lease.waited === true) && !failFast) {
|
|
632
|
+
// `type: 'complete'` forces the round-trip: the hydration ledger would
|
|
633
|
+
// otherwise serve the local row for an already-hydrated id, and the
|
|
634
|
+
// holder's final write may not have fanned out yet — the exact
|
|
635
|
+
// stale-snapshot race this re-read closes.
|
|
636
|
+
await load({ where: [['id', id]], type: 'complete' });
|
|
637
|
+
model = ownRowOrThrow(id) ?? model;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const snapshot = collaboration.createSnapshot(schemaKey, id);
|
|
641
|
+
const description = claimDescription(options);
|
|
642
|
+
// The self-claim's `ClaimTarget` mirrors what a peer's `claim.state` would
|
|
643
|
+
// report (`state` maps `held.target.model` to `type`), so a holder and a
|
|
644
|
+
// peer see the same `target.type` for one row — the wire model token.
|
|
645
|
+
// Its `meta` is the DECLARED shape (the handle is a public claim), so the
|
|
646
|
+
// wire-shaped projection converts back through `declaredMeta` — the same
|
|
647
|
+
// crossing the HTTP handle assembly makes.
|
|
648
|
+
const { meta: selfMeta, ...selfNarrowed } = subTarget(options, schemaKey);
|
|
649
|
+
const selfTarget: ClaimTarget = {
|
|
650
|
+
type: wireModel,
|
|
651
|
+
id,
|
|
652
|
+
...selfNarrowed,
|
|
653
|
+
...(selfMeta !== undefined ? { meta: declaredMeta(selfMeta) } : {}),
|
|
654
|
+
};
|
|
655
|
+
const ttlMs =
|
|
656
|
+
options.ttl !== undefined ? toMs(options.ttl) : DEFAULT_LEASE_TTL_MS;
|
|
657
|
+
const expiresAt = Date.now() + ttlMs;
|
|
658
|
+
activeClaims.set(id, {
|
|
659
|
+
lease,
|
|
660
|
+
snapshot,
|
|
661
|
+
target: selfTarget,
|
|
662
|
+
description,
|
|
663
|
+
expiresAt,
|
|
664
|
+
});
|
|
665
|
+
const { meta: targetMeta, ...targetNarrowed } = subTarget(options, schemaKey);
|
|
666
|
+
const target = {
|
|
667
|
+
type: schemaKey,
|
|
668
|
+
id,
|
|
669
|
+
...targetNarrowed,
|
|
670
|
+
...(targetMeta !== undefined ? { meta: declaredMeta(targetMeta) } : {}),
|
|
671
|
+
};
|
|
672
|
+
// One reading of the heartbeat options — cadence and callbacks from
|
|
673
|
+
// whichever spelling the caller used (plan object, shorthand, or the
|
|
674
|
+
// deprecated flat callbacks).
|
|
675
|
+
const plan = resolveHeartbeatPlan(options);
|
|
676
|
+
// A beat resolves with the server's extended expiry; keep the local
|
|
677
|
+
// self-claim estimate in step so `claim.state` renders the real window,
|
|
678
|
+
// and surface every answer through the plan's `onBeat` (pressure signal).
|
|
679
|
+
const heartbeat = async (
|
|
680
|
+
beatOptions?: Duration | ClaimHeartbeatOptions,
|
|
681
|
+
): Promise<ClaimHeartbeat> => {
|
|
682
|
+
if (!lease.heartbeat) {
|
|
683
|
+
throw new AbloValidationError(
|
|
684
|
+
'This claim handle has no heartbeat wiring, which the standard Ablo({ schema, apiKey }) client provides on every claim. This appears only when a claim is minted through an internal path that predates heartbeats.',
|
|
685
|
+
{ code: 'claim_not_wired' },
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
const resolved = resolveHeartbeatOptions(beatOptions);
|
|
689
|
+
const beat = await lease.heartbeat({
|
|
690
|
+
ttl: resolved.ttl ?? options.ttl,
|
|
691
|
+
...(resolved.details !== undefined ? { details: resolved.details } : {}),
|
|
692
|
+
});
|
|
693
|
+
const held = activeClaims.get(id);
|
|
694
|
+
if (held) held.expiresAt = beat.expiresAt;
|
|
695
|
+
plan.onBeat?.(beat);
|
|
696
|
+
return beat;
|
|
697
|
+
};
|
|
698
|
+
|
|
699
|
+
// Opt-in auto-heartbeat: the loop beats until release, and a definitive
|
|
700
|
+
// loss stops it and surfaces through the plan's `onLost`.
|
|
701
|
+
const stopHeartbeatLoop = plan.loop
|
|
702
|
+
? startClaimHeartbeatLoop({
|
|
703
|
+
beat: () => heartbeat(),
|
|
704
|
+
intervalMs: heartbeatCadenceMs(ttlMs, plan.cadence),
|
|
705
|
+
...(plan.onLost ? { onLost: plan.onLost } : {}),
|
|
706
|
+
})
|
|
707
|
+
: undefined;
|
|
708
|
+
|
|
709
|
+
const release = () => {
|
|
710
|
+
stopHeartbeatLoop?.();
|
|
711
|
+
return releaseClaim(id);
|
|
712
|
+
};
|
|
713
|
+
return {
|
|
714
|
+
object: 'claim',
|
|
715
|
+
id: lease.id,
|
|
716
|
+
readAt: snapshot.stamp,
|
|
717
|
+
// The fencing token the server minted for this grant, forwarded from the
|
|
718
|
+
// lease so writes taken under this handle carry it (Option B).
|
|
719
|
+
...(lease.fenceToken !== undefined ? { fenceToken: lease.fenceToken } : {}),
|
|
720
|
+
target,
|
|
721
|
+
description,
|
|
722
|
+
data: modelAsRow<T>(model),
|
|
723
|
+
release,
|
|
724
|
+
revoke: () => {
|
|
725
|
+
void release();
|
|
726
|
+
},
|
|
727
|
+
heartbeat,
|
|
728
|
+
[Symbol.asyncDispose]: release,
|
|
729
|
+
};
|
|
730
|
+
};
|
|
731
|
+
|
|
732
|
+
// The row-free sibling of `takeClaim`: locks a key by id alone, for a row that
|
|
733
|
+
// lives only in the customer's own database and was never synced into Ablo.
|
|
734
|
+
// Everything about the lease — the fail-fast contention check, the scope pin,
|
|
735
|
+
// the `createClaim` grant, the heartbeat wiring, and the `activeClaims`
|
|
736
|
+
// bookkeeping — is identical; what's dropped is the object-pool `load` (and its
|
|
737
|
+
// `entity_not_found` throw), the post-grant re-read, and the `.data` field,
|
|
738
|
+
// since there is no local row to hydrate or return.
|
|
739
|
+
const takeRowFreeClaim = async (
|
|
740
|
+
id: string,
|
|
741
|
+
options: ClaimOptions<C>,
|
|
742
|
+
): Promise<HeldLease | null> => {
|
|
743
|
+
if (!collaboration) {
|
|
744
|
+
throw new AbloValidationError(
|
|
745
|
+
`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`,
|
|
746
|
+
{ code: 'model_claim_not_configured' },
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
// Is someone else already on this target? Read the local coordination
|
|
750
|
+
// snapshot up front so a `queue: false` caller can reject before announcing
|
|
751
|
+
// a claim the server would refuse.
|
|
752
|
+
const held = collaboration.state({ model: wireModel, id });
|
|
753
|
+
const contended = !!held && held.heldBy !== collaboration.selfParticipantId;
|
|
754
|
+
const failFast = options.queue === false;
|
|
755
|
+
|
|
756
|
+
// The try-claim (`queue: false`): resolve `null` if a holder is already
|
|
757
|
+
// visible — an expected outcome, not an error. Best-effort at the client —
|
|
758
|
+
// a row this participant never synced usually carries no local claim state
|
|
759
|
+
// either, so a peer gets the deterministic `null` only once it has
|
|
760
|
+
// observed the holder (entered the row's entity scope). The server's
|
|
761
|
+
// queue is the backstop for the queuing path.
|
|
762
|
+
if (failFast && contended) {
|
|
763
|
+
return null;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// Enter the entity scope before acquiring the lease so the holder's claim
|
|
767
|
+
// presence broadcasts to everyone in this entity group — the same ordering
|
|
768
|
+
// the row-bearing path relies on. No pool `load` and no `entity_not_found`
|
|
769
|
+
// throw: the row lives only in the customer's database, so there is nothing
|
|
770
|
+
// to hydrate here and nothing to re-read after the grant.
|
|
771
|
+
await collaboration.pinScope?.({ [schemaKey]: id });
|
|
772
|
+
|
|
773
|
+
const lease = await collaboration.createClaim({
|
|
774
|
+
target: {
|
|
775
|
+
model: wireModel,
|
|
776
|
+
id,
|
|
777
|
+
// The whole sub-entity locator in one move — listing its members here
|
|
778
|
+
// is what let `fields` die between the caller and the lease, so the
|
|
779
|
+
// claim covered the whole row while the caller believed it named parts.
|
|
780
|
+
...subTarget(options, schemaKey),
|
|
781
|
+
},
|
|
782
|
+
description: claimDescription(options),
|
|
783
|
+
ttl: options.ttl,
|
|
784
|
+
queue: !failFast,
|
|
785
|
+
maxQueueDepth: options.maxQueueDepth,
|
|
786
|
+
// The one wait cap, declared once on ClaimTargetOptions — the socket
|
|
787
|
+
// wait and the HTTP poll-wait both honor it as `grant_timeout`.
|
|
788
|
+
waitTimeoutMs: options.waitTimeoutMs,
|
|
789
|
+
signal: options.signal,
|
|
790
|
+
});
|
|
791
|
+
|
|
792
|
+
// A watermark-only snapshot: `createSnapshot` still reads the engine's
|
|
793
|
+
// current `lastSyncId` even though the pool holds no row (the bucket is
|
|
794
|
+
// empty). It costs nothing extra and gives a write taken under this lease a
|
|
795
|
+
// real `readAt` to guard against changes since the lease was acquired.
|
|
796
|
+
const snapshot = collaboration.createSnapshot(schemaKey, id);
|
|
797
|
+
const description = claimDescription(options);
|
|
798
|
+
const selfTarget: ClaimTarget = {
|
|
799
|
+
type: wireModel,
|
|
800
|
+
id,
|
|
801
|
+
...subTarget(options, schemaKey),
|
|
802
|
+
};
|
|
803
|
+
const ttlMs =
|
|
804
|
+
options.ttl !== undefined ? toMs(options.ttl) : DEFAULT_LEASE_TTL_MS;
|
|
805
|
+
const expiresAt = Date.now() + ttlMs;
|
|
806
|
+
activeClaims.set(id, {
|
|
807
|
+
lease,
|
|
808
|
+
snapshot,
|
|
809
|
+
target: selfTarget,
|
|
810
|
+
description,
|
|
811
|
+
expiresAt,
|
|
812
|
+
});
|
|
813
|
+
const target = {
|
|
814
|
+
type: schemaKey,
|
|
815
|
+
id,
|
|
816
|
+
...subTarget(options, schemaKey),
|
|
817
|
+
};
|
|
818
|
+
// One reading of the heartbeat options — cadence and callbacks from
|
|
819
|
+
// whichever spelling the caller used.
|
|
820
|
+
const plan = resolveHeartbeatPlan(options);
|
|
821
|
+
// A beat resolves with the server's extended expiry; keep the local
|
|
822
|
+
// self-claim estimate in step so `claim.state` renders the real window.
|
|
823
|
+
const heartbeat = async (
|
|
824
|
+
beatOptions?: Duration | ClaimHeartbeatOptions,
|
|
825
|
+
): Promise<ClaimHeartbeat> => {
|
|
826
|
+
if (!lease.heartbeat) {
|
|
827
|
+
throw new AbloValidationError(
|
|
828
|
+
'This claim handle has no heartbeat wiring, which the standard Ablo({ schema, apiKey }) client provides on every claim. This appears only when a claim is minted through an internal path that predates heartbeats.',
|
|
829
|
+
{ code: 'claim_not_wired' },
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
const resolved = resolveHeartbeatOptions(beatOptions);
|
|
833
|
+
const beat = await lease.heartbeat({
|
|
834
|
+
ttl: resolved.ttl ?? options.ttl,
|
|
835
|
+
...(resolved.details !== undefined ? { details: resolved.details } : {}),
|
|
836
|
+
});
|
|
837
|
+
const held = activeClaims.get(id);
|
|
838
|
+
if (held) held.expiresAt = beat.expiresAt;
|
|
839
|
+
plan.onBeat?.(beat);
|
|
840
|
+
return beat;
|
|
841
|
+
};
|
|
842
|
+
|
|
843
|
+
const stopHeartbeatLoop = plan.loop
|
|
844
|
+
? startClaimHeartbeatLoop({
|
|
845
|
+
beat: () => heartbeat(),
|
|
846
|
+
intervalMs: heartbeatCadenceMs(ttlMs, plan.cadence),
|
|
847
|
+
...(plan.onLost ? { onLost: plan.onLost } : {}),
|
|
848
|
+
})
|
|
849
|
+
: undefined;
|
|
850
|
+
|
|
851
|
+
const release = () => {
|
|
852
|
+
stopHeartbeatLoop?.();
|
|
853
|
+
return releaseClaim(id);
|
|
854
|
+
};
|
|
855
|
+
return {
|
|
856
|
+
object: 'claim',
|
|
857
|
+
id: lease.id,
|
|
858
|
+
readAt: snapshot.stamp,
|
|
859
|
+
// Forward the grant's fencing token so writes under this row-free lease
|
|
860
|
+
// carry it (Option B), exactly as the row-bearing claim does.
|
|
861
|
+
...(lease.fenceToken !== undefined ? { fenceToken: lease.fenceToken } : {}),
|
|
862
|
+
target,
|
|
863
|
+
description,
|
|
864
|
+
release,
|
|
865
|
+
revoke: () => {
|
|
866
|
+
void release();
|
|
867
|
+
},
|
|
868
|
+
heartbeat,
|
|
869
|
+
[Symbol.asyncDispose]: release,
|
|
870
|
+
};
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
// `claim` overloads on its first argument: an options object claims a synced
|
|
874
|
+
// row and resolves to a HeldClaim (carrying `.data`); a bare id claims a key
|
|
875
|
+
// whose row Ablo doesn't hold and resolves to a HeldLease (no `.data`). Both
|
|
876
|
+
// route their throws through `toAbloError` via the guarded takers, so the
|
|
877
|
+
// two-signature shape survives — wrapping the dispatcher itself in `guard`
|
|
878
|
+
// would collapse the overloads to one.
|
|
879
|
+
const guardedTakeClaim = guard(takeClaim);
|
|
880
|
+
const guardedTakeRowFreeClaim = guard(takeRowFreeClaim);
|
|
881
|
+
function claim(
|
|
882
|
+
params: ClaimParams<C> & { queue: false },
|
|
883
|
+
): Promise<HeldClaim<T> | null>;
|
|
884
|
+
function claim(params: ClaimParams<C>): Promise<HeldClaim<T>>;
|
|
885
|
+
function claim(
|
|
886
|
+
id: string,
|
|
887
|
+
opts: ClaimOptions<C> & { queue: false },
|
|
888
|
+
): Promise<HeldLease | null>;
|
|
889
|
+
function claim(id: string, opts?: ClaimOptions<C>): Promise<HeldLease>;
|
|
890
|
+
function claim(
|
|
891
|
+
arg: ClaimParams<C> | string,
|
|
892
|
+
opts?: ClaimOptions<C>,
|
|
893
|
+
): Promise<HeldClaim<T> | HeldLease | null> {
|
|
894
|
+
return typeof arg === 'string'
|
|
895
|
+
? guardedTakeRowFreeClaim(arg, opts ?? {})
|
|
896
|
+
: guardedTakeClaim(arg);
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// `claim` is a callable namespace: invoke it to take a claim, reach its
|
|
900
|
+
// members to read/steer the coordination plane. Attach the readers to the
|
|
901
|
+
// callable so `ablo.<model>.claim(...)` and `ablo.<model>.claim.state(...)`
|
|
902
|
+
// are the same object.
|
|
903
|
+
// `state` and `queue` take a caller-named `meta` shape. The runtime cannot
|
|
904
|
+
// check it and is not meant to: `target.meta` is application data the
|
|
905
|
+
// protocol carries verbatim and never interprets, so naming its type is the
|
|
906
|
+
// caller asserting what it put there — the same bargain as parsing your own
|
|
907
|
+
// JSON into an interface. These read as `Claim` here, and the one assertion
|
|
908
|
+
// that applies the caller's parameter is on the assignment below, in one
|
|
909
|
+
// place rather than at every call site.
|
|
910
|
+
/**
|
|
911
|
+
* This client's own claim on a row, as a claim-state object.
|
|
912
|
+
*
|
|
913
|
+
* The server excludes a holder's own presence frames and the client skips
|
|
914
|
+
* them, so a row this client holds is absent from every peer-derived read.
|
|
915
|
+
* Both `state` and `list` therefore synthesize it from the stored lease, and
|
|
916
|
+
* they do it through here so the two answers cannot describe the same
|
|
917
|
+
* holding differently.
|
|
918
|
+
*/
|
|
919
|
+
const ownClaimState = (id: string): Claim | null => {
|
|
920
|
+
const own = activeClaims.get(id);
|
|
921
|
+
if (!own) return null;
|
|
922
|
+
return {
|
|
923
|
+
object: 'claim',
|
|
924
|
+
id: own.lease.id,
|
|
925
|
+
status: 'active',
|
|
926
|
+
target: own.target,
|
|
927
|
+
description: own.description,
|
|
928
|
+
heldBy: collaboration?.selfParticipantId ?? '',
|
|
929
|
+
participantKind: collaboration?.selfParticipantKind ?? 'user',
|
|
930
|
+
expiresAt: own.expiresAt,
|
|
931
|
+
// Symmetric with the peer projection: a holder reading its own claim
|
|
932
|
+
// sees the same `meta` an observer does.
|
|
933
|
+
...(own.target.meta !== undefined ? { meta: own.target.meta } : {}),
|
|
934
|
+
};
|
|
935
|
+
};
|
|
936
|
+
|
|
937
|
+
const claimReaders = {
|
|
938
|
+
state(params: ClaimLookupParams<T>): Claim | null {
|
|
939
|
+
// Read interest: a passive observer of a row's claim state must enter that
|
|
940
|
+
// row's entity scope, or it sits only on broader `org:`/`user:` groups and
|
|
941
|
+
// never receives the holder's entity-scoped claim presence. Best-effort
|
|
942
|
+
// and fire-and-forget — it never blocks or rejects the read.
|
|
943
|
+
void collaboration?.enterScope?.({ [schemaKey]: params.id });
|
|
944
|
+
// Self-awareness: the server excludes a holder's own presence frames and
|
|
945
|
+
// the client skips them, so `state` would return null for a row this client
|
|
946
|
+
// holds. Synthesize the active claim from the stored lease so the holder
|
|
947
|
+
// sees its own claim, honoring the documented contract on `claim.state`.
|
|
948
|
+
return (
|
|
949
|
+
ownClaimState(params.id) ??
|
|
950
|
+
collaboration?.state({ model: wireModel, id: params.id }) ??
|
|
951
|
+
null
|
|
952
|
+
);
|
|
953
|
+
},
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* Every claim on the row, holders first. Sub-row claims on disjoint parts
|
|
957
|
+
* are all granted, so a row can have several holders at once and
|
|
958
|
+
* {@link state} answers with one of them — this is the read that renders
|
|
959
|
+
* all of them. Same list envelope as {@link queue}, reactive on the same
|
|
960
|
+
* snapshot, so a render reads it inline.
|
|
961
|
+
*/
|
|
962
|
+
list(params: ClaimLookupParams<T>): { readonly object: 'list'; readonly data: readonly Claim[] } {
|
|
963
|
+
void collaboration?.enterScope?.({ [schemaKey]: params.id });
|
|
964
|
+
const own = ownClaimState(params.id);
|
|
965
|
+
const peers = collaboration?.holders({ model: wireModel, id: params.id }) ?? [];
|
|
966
|
+
return {
|
|
967
|
+
object: 'list',
|
|
968
|
+
// Own claim first: the server excludes a holder's own presence frames,
|
|
969
|
+
// so it is never among `peers` and the two never duplicate.
|
|
970
|
+
data: own ? [own, ...peers] : [...peers],
|
|
971
|
+
};
|
|
972
|
+
},
|
|
973
|
+
|
|
974
|
+
queue(params: ClaimLookupParams<T>): { readonly object: 'list'; readonly data: readonly Claim[] } {
|
|
975
|
+
return {
|
|
976
|
+
object: 'list',
|
|
977
|
+
data: collaboration?.queue({ model: wireModel, id: params.id }) ?? [],
|
|
978
|
+
};
|
|
979
|
+
},
|
|
980
|
+
|
|
981
|
+
reorder(params: ClaimReorderParams<T>): void {
|
|
982
|
+
collaboration?.reorder({ model: wireModel, id: params.id }, params.order);
|
|
983
|
+
},
|
|
984
|
+
|
|
985
|
+
release: guard((params: ClaimLookupParams<T> | Claim<T>): Promise<void> =>
|
|
986
|
+
releaseClaim(isClaimHandle(params) ? params.target.id : params.id),
|
|
987
|
+
),
|
|
988
|
+
};
|
|
989
|
+
|
|
990
|
+
// The one place the caller's `meta` parameter is applied — see the note on
|
|
991
|
+
// `claimReaders`. Everything else about this object is checked structurally.
|
|
992
|
+
const claimApi = Object.assign(claim, claimReaders) as ClaimApi<T, C>;
|
|
993
|
+
|
|
994
|
+
const local: LocalReads<T> = {
|
|
995
|
+
get(id: string): T | undefined {
|
|
996
|
+
// Scoped to this model: an id belonging to a sibling model reads as
|
|
997
|
+
// absent rather than being handed back as if it were a `T`.
|
|
998
|
+
return objectPool.getOfType(id, registeredModelName) as T | undefined;
|
|
999
|
+
},
|
|
1000
|
+
|
|
1001
|
+
list(options): T[] {
|
|
1002
|
+
const all = objectPool.getByType(
|
|
1003
|
+
ModelClass,
|
|
1004
|
+
(options?.state ?? ModelScope.live) as ModelScope,
|
|
1005
|
+
) as T[];
|
|
1006
|
+
let result = all;
|
|
1007
|
+
|
|
1008
|
+
if (options?.where) {
|
|
1009
|
+
const where = options.where as Record<string, unknown>;
|
|
1010
|
+
result = result.filter((item) => {
|
|
1011
|
+
for (const [key, value] of Object.entries(where)) {
|
|
1012
|
+
if ((item as Record<string, unknown>)[key] !== value) return false;
|
|
1013
|
+
}
|
|
1014
|
+
return true;
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
if (options?.filter) {
|
|
1019
|
+
result = result.filter(options.filter);
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
const orderEntry = options?.orderBy ? Object.entries(options.orderBy)[0] : undefined;
|
|
1023
|
+
if (orderEntry) {
|
|
1024
|
+
const [field, dir] = orderEntry;
|
|
1025
|
+
result = [...result].sort((a, b) => {
|
|
1026
|
+
const av = (a as Record<string, unknown>)[field];
|
|
1027
|
+
const bv = (b as Record<string, unknown>)[field];
|
|
1028
|
+
if (av == null || bv == null) return 0;
|
|
1029
|
+
const cmp = av < bv ? -1 : av > bv ? 1 : 0;
|
|
1030
|
+
return dir === 'desc' ? -cmp : cmp;
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
if (options?.offset) result = result.slice(options.offset);
|
|
1035
|
+
if (options?.limit) result = result.slice(0, options.limit);
|
|
1036
|
+
|
|
1037
|
+
return result;
|
|
1038
|
+
},
|
|
1039
|
+
|
|
1040
|
+
count(options): number {
|
|
1041
|
+
return local.list(options).length;
|
|
1042
|
+
},
|
|
1043
|
+
};
|
|
1044
|
+
|
|
1045
|
+
const get = guard(
|
|
1046
|
+
async (params: ModelRetrieveParams): Promise<T | undefined> => {
|
|
1047
|
+
// Read-interest enrolment: authoritative point reads enter the same
|
|
1048
|
+
// entity scope as the claim stream, while remaining settled reads.
|
|
1049
|
+
void collaboration?.enterScope?.({ [schemaKey]: params.id });
|
|
1050
|
+
const rows = await load({
|
|
1051
|
+
...params,
|
|
1052
|
+
where: [['id', params.id]],
|
|
1053
|
+
limit: 1,
|
|
1054
|
+
});
|
|
1055
|
+
return rows[0];
|
|
1056
|
+
},
|
|
1057
|
+
);
|
|
1058
|
+
|
|
1059
|
+
const operations: ModelOperations<T, C> = {
|
|
1060
|
+
local,
|
|
1061
|
+
|
|
1062
|
+
get,
|
|
1063
|
+
retrieve: get,
|
|
1064
|
+
|
|
1065
|
+
// No automatic scope enrolment on bulk `list`: that would subscribe to an
|
|
1066
|
+
// unbounded set of rows' entity groups.
|
|
1067
|
+
list: guard(load),
|
|
1068
|
+
|
|
1069
|
+
create: guard(async (params: ModelCreateParams<T, C>): Promise<T> => {
|
|
1070
|
+
const id = params.id ?? Model.generateId();
|
|
1071
|
+
const opts = mutationOptions(params);
|
|
1072
|
+
const claim = params.claim;
|
|
1073
|
+
let autoLease: Claim | undefined;
|
|
1074
|
+
if (claim && !isClaimHandle(claim)) {
|
|
1075
|
+
if (!collaboration) {
|
|
1076
|
+
throw new AbloValidationError(
|
|
1077
|
+
`Model "${schemaKey}" was built without the collaboration runtime, so claim() is unavailable here. Claiming needs no per-model config — use the standard Ablo({ schema, apiKey }) client and every model is claimable.`,
|
|
1078
|
+
{ code: 'model_claim_not_configured' },
|
|
1079
|
+
);
|
|
1080
|
+
}
|
|
1081
|
+
// Write intent: enter the new row's entity scope before acquiring the
|
|
1082
|
+
// create-claim so the holder's claim presence broadcasts to everyone
|
|
1083
|
+
// already in this entity group (closing the subscribe-versus-broadcast
|
|
1084
|
+
// race — see `takeClaim`). Released with the lease in the `finally`
|
|
1085
|
+
// below. Awaited for broadcast ordering; still best-effort.
|
|
1086
|
+
await collaboration.pinScope?.({ [schemaKey]: id });
|
|
1087
|
+
autoLease = await collaboration.createClaim({
|
|
1088
|
+
target: {
|
|
1089
|
+
model: wireModel,
|
|
1090
|
+
id,
|
|
1091
|
+
...subTarget(claim, schemaKey),
|
|
1092
|
+
},
|
|
1093
|
+
description: claimDescription(claim, 'creating'),
|
|
1094
|
+
ttl: claim.ttl,
|
|
1095
|
+
queue: claim.queue !== false,
|
|
1096
|
+
maxQueueDepth: claim.maxQueueDepth,
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// Default `organizationId` from the client's identity, matching the other
|
|
1101
|
+
// write path — without this, a caller that omits it would create an
|
|
1102
|
+
// org-unscoped row on one write path but not the other. An explicit value
|
|
1103
|
+
// in `data` still wins via the spread.
|
|
1104
|
+
const orgDefault =
|
|
1105
|
+
(params.data as Record<string, unknown>).organizationId ??
|
|
1106
|
+
syncClient.getOrganizationId();
|
|
1107
|
+
const model = new ModelClass({
|
|
1108
|
+
id,
|
|
1109
|
+
...(orgDefault != null ? { organizationId: orgDefault } : {}),
|
|
1110
|
+
...(params.data as Record<string, unknown>),
|
|
1111
|
+
createdAt: new Date(),
|
|
1112
|
+
updatedAt: new Date(),
|
|
1113
|
+
});
|
|
1114
|
+
const effective: MutationOptions = {
|
|
1115
|
+
...opts,
|
|
1116
|
+
...(autoLease ? { claim: autoLease } : {}),
|
|
1117
|
+
...(isClaimHandle(claim) ? { claim: { id: claim.id } } : {}),
|
|
1118
|
+
};
|
|
1119
|
+
try {
|
|
1120
|
+
syncClient.add(model, effective);
|
|
1121
|
+
await waitForMutation(model, effective);
|
|
1122
|
+
return modelAsRow<T>(model);
|
|
1123
|
+
} finally {
|
|
1124
|
+
await autoLease?.release?.().catch(() => {});
|
|
1125
|
+
}
|
|
1126
|
+
}),
|
|
1127
|
+
|
|
1128
|
+
// `update` is overloaded — classic `update({ id, data })` + functional
|
|
1129
|
+
// `update(id, current => next)`. The IIFE keeps the shared error-guard
|
|
1130
|
+
// wrapping while exposing the two public signatures (a plain `guard(...)`
|
|
1131
|
+
// would collapse them to one).
|
|
1132
|
+
update: ((): ModelOperations<T, C>['update'] => {
|
|
1133
|
+
const updateImpl = guard(
|
|
1134
|
+
async (
|
|
1135
|
+
arg: ModelUpdateParams<T, C> | string,
|
|
1136
|
+
updater?: ModelUpdater<T>,
|
|
1137
|
+
contention?: ContentionOptions,
|
|
1138
|
+
): Promise<T | undefined> => {
|
|
1139
|
+
// Functional form: update(id, current => next). Same guarantee as the
|
|
1140
|
+
// HTTP client (shared reconcile loop), implemented with this transport's
|
|
1141
|
+
// own read-fresh + confirmed compare-and-swap. A forced server round-trip
|
|
1142
|
+
// gets the latest row + watermark; the write is stale-guarded by it, so
|
|
1143
|
+
// concurrent writers reconcile instead of clobbering — no claim needed.
|
|
1144
|
+
if (typeof arg === 'string') {
|
|
1145
|
+
const id = arg;
|
|
1146
|
+
if (typeof updater !== 'function') {
|
|
1147
|
+
throw new AbloValidationError(
|
|
1148
|
+
`${registeredModelName}.update('${id}', updater): the second argument must ` +
|
|
1149
|
+
`be an updater function (current) => next. To write a fixed value, use ` +
|
|
1150
|
+
`update({ id, data }).`,
|
|
1151
|
+
{ code: 'write_options_invalid' },
|
|
1152
|
+
);
|
|
1153
|
+
}
|
|
1154
|
+
if (!collaboration) {
|
|
1155
|
+
throw new AbloValidationError(
|
|
1156
|
+
`${registeredModelName}.update(id, updater) needs the collaboration runtime ` +
|
|
1157
|
+
`(a live WebSocket) to read the row's watermark for its compare-and-swap. ` +
|
|
1158
|
+
`Use the standard Ablo({ schema, apiKey }) client.`,
|
|
1159
|
+
{ code: 'model_claim_not_configured' },
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
return reconcileFunctionalUpdate<T, T>(updater, contention, {
|
|
1163
|
+
model: registeredModelName,
|
|
1164
|
+
id,
|
|
1165
|
+
readFresh: async () => {
|
|
1166
|
+
// `type: 'complete'` forces the round-trip — the hydration ledger
|
|
1167
|
+
// would otherwise serve a possibly-stale local row for a hydrated id.
|
|
1168
|
+
await load({ where: [['id', id]], type: 'complete' });
|
|
1169
|
+
const fresh = ownRowOrThrow(id);
|
|
1170
|
+
const snapshot = collaboration.createSnapshot(schemaKey, id);
|
|
1171
|
+
return {
|
|
1172
|
+
data: fresh ? modelAsRow<T>(fresh) : undefined,
|
|
1173
|
+
stamp: snapshot.stamp,
|
|
1174
|
+
};
|
|
1175
|
+
},
|
|
1176
|
+
writeNext: async (patch, readAt) => {
|
|
1177
|
+
const model = ownRowOrThrow(id);
|
|
1178
|
+
if (!model) {
|
|
1179
|
+
throw new AbloValidationError(
|
|
1180
|
+
`Entity not found: ${registeredModelName}/${id}`,
|
|
1181
|
+
{ code: 'entity_not_found' },
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
const effective: MutationOptions = {
|
|
1185
|
+
wait: 'confirmed',
|
|
1186
|
+
readAt,
|
|
1187
|
+
onStale: 'reject',
|
|
1188
|
+
};
|
|
1189
|
+
model.applyChanges(patch);
|
|
1190
|
+
syncClient.update(model, effective);
|
|
1191
|
+
await waitForMutation(model, effective);
|
|
1192
|
+
return modelAsRow<T>(model);
|
|
1193
|
+
},
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
const params = arg;
|
|
1197
|
+
const autoClaim =
|
|
1198
|
+
params.claim && !isClaimHandle(params.claim) ? params.claim : null;
|
|
1199
|
+
if (autoClaim) {
|
|
1200
|
+
const handle = await takeClaim({ ...autoClaim, id: params.id });
|
|
1201
|
+
// A declined try-claim is `null` only on the standalone verb; a
|
|
1202
|
+
// write that could not take its claim is a failed write.
|
|
1203
|
+
if (!handle) {
|
|
1204
|
+
throw new AbloClaimedError(
|
|
1205
|
+
`${registeredModelName}/${params.id} is held by another participant, so this update's claim could not be taken.`,
|
|
1206
|
+
{ code: 'entity_claimed' },
|
|
1207
|
+
);
|
|
1208
|
+
}
|
|
1209
|
+
try {
|
|
1210
|
+
return await operations.update({ ...params, claim: handle });
|
|
1211
|
+
} finally {
|
|
1212
|
+
await handle.release();
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
const { id } = params;
|
|
1216
|
+
const model = ownRowOrThrow(id);
|
|
1217
|
+
if (!model)
|
|
1218
|
+
throw new AbloValidationError(
|
|
1219
|
+
`Entity not found: ${registeredModelName}/${id}`,
|
|
1220
|
+
{ code: 'entity_not_found' },
|
|
1221
|
+
);
|
|
1222
|
+
// If we hold a claim on this row, guard the write with its snapshot
|
|
1223
|
+
// watermark + lease so it's stale-rejected and attributed to the claim.
|
|
1224
|
+
const claimed = activeClaims.get(id);
|
|
1225
|
+
const opts = mutationOptions(params);
|
|
1226
|
+
const handle = isClaimHandle(params.claim) ? params.claim : undefined;
|
|
1227
|
+
const effective: MutationOptions | undefined = claimed
|
|
1228
|
+
? {
|
|
1229
|
+
wait: 'confirmed',
|
|
1230
|
+
readAt: claimed.snapshot.stamp,
|
|
1231
|
+
onStale: 'reject',
|
|
1232
|
+
claimRef: { id: claimed.lease.id },
|
|
1233
|
+
...opts,
|
|
1234
|
+
}
|
|
1235
|
+
: {
|
|
1236
|
+
// A carried handle engages the same stale guard as a claim this
|
|
1237
|
+
// proxy took itself — the watermark rides on the handle, so it
|
|
1238
|
+
// works across clients (HTTP-minted handles included).
|
|
1239
|
+
...(handle?.readAt !== undefined
|
|
1240
|
+
? {
|
|
1241
|
+
wait: 'confirmed' as const,
|
|
1242
|
+
readAt: handle.readAt,
|
|
1243
|
+
onStale: 'reject' as const,
|
|
1244
|
+
...(handle.fenceToken !== undefined
|
|
1245
|
+
? { fenceToken: handle.fenceToken }
|
|
1246
|
+
: {}),
|
|
1247
|
+
}
|
|
1248
|
+
: {}),
|
|
1249
|
+
...opts,
|
|
1250
|
+
...(handle ? { claim: { id: handle.id } } : {}),
|
|
1251
|
+
};
|
|
1252
|
+
// Local user update: `applyChanges` keeps change tracking on so the
|
|
1253
|
+
// edited fields land in `modifiedProperties` and are actually sent to
|
|
1254
|
+
// the server. (`updateFromData` is the hydration path and would discard
|
|
1255
|
+
// the tracking, producing an empty `input: {}` no-op mutation.)
|
|
1256
|
+
model.applyChanges(params.data);
|
|
1257
|
+
syncClient.update(model, effective);
|
|
1258
|
+
await waitForMutation(model, effective);
|
|
1259
|
+
return modelAsRow<T>(model);
|
|
1260
|
+
},
|
|
1261
|
+
);
|
|
1262
|
+
function update(params: ModelUpdateParams<T, C>): Promise<T>;
|
|
1263
|
+
function update(
|
|
1264
|
+
id: string,
|
|
1265
|
+
updater: ModelUpdater<T>,
|
|
1266
|
+
options?: ContentionOptions,
|
|
1267
|
+
): Promise<T | undefined>;
|
|
1268
|
+
function update(
|
|
1269
|
+
arg: ModelUpdateParams<T, C> | string,
|
|
1270
|
+
updater?: ModelUpdater<T>,
|
|
1271
|
+
contention?: ContentionOptions,
|
|
1272
|
+
): Promise<T | undefined> {
|
|
1273
|
+
return updateImpl(arg, updater, contention);
|
|
1274
|
+
}
|
|
1275
|
+
return update;
|
|
1276
|
+
})(),
|
|
1277
|
+
|
|
1278
|
+
delete: guard(async (params: ModelDeleteParams<T, C>): Promise<void> => {
|
|
1279
|
+
const autoClaim =
|
|
1280
|
+
params.claim && !isClaimHandle(params.claim) ? params.claim : null;
|
|
1281
|
+
if (autoClaim) {
|
|
1282
|
+
const handle = await takeClaim({ ...autoClaim, id: params.id });
|
|
1283
|
+
// Same rule as update: a write that could not take its claim fails.
|
|
1284
|
+
if (!handle) {
|
|
1285
|
+
throw new AbloClaimedError(
|
|
1286
|
+
`${registeredModelName}/${params.id} is held by another participant, so this delete's claim could not be taken.`,
|
|
1287
|
+
{ code: 'entity_claimed' },
|
|
1288
|
+
);
|
|
1289
|
+
}
|
|
1290
|
+
try {
|
|
1291
|
+
await operations.delete({ ...params, claim: handle });
|
|
1292
|
+
} finally {
|
|
1293
|
+
await handle.release();
|
|
1294
|
+
}
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
const { id } = params;
|
|
1298
|
+
// Scoped: "ensure absent" stays idempotent for an id this model simply
|
|
1299
|
+
// doesn't hold, but an id owned by a sibling model throws rather than
|
|
1300
|
+
// deleting a row the caller never addressed.
|
|
1301
|
+
const model = ownRowOrThrow(id);
|
|
1302
|
+
// Idempotent delete: "ensure absent". A row that isn't in this client's
|
|
1303
|
+
// replicated view is already gone from its perspective, so a delete is a
|
|
1304
|
+
// no-op success rather than an `entity_not_found` error. This matches the
|
|
1305
|
+
// HTTP client and makes delete safe to retry or race (two actors deleting
|
|
1306
|
+
// the same row).
|
|
1307
|
+
if (!model) return;
|
|
1308
|
+
const claimed = activeClaims.get(id);
|
|
1309
|
+
const opts = mutationOptions(params);
|
|
1310
|
+
const handle = isClaimHandle(params.claim) ? params.claim : undefined;
|
|
1311
|
+
const effective: MutationOptions | undefined = claimed
|
|
1312
|
+
? {
|
|
1313
|
+
wait: 'confirmed',
|
|
1314
|
+
readAt: claimed.snapshot.stamp,
|
|
1315
|
+
onStale: 'reject',
|
|
1316
|
+
claimRef: { id: claimed.lease.id },
|
|
1317
|
+
...(claimed.lease.fenceToken !== undefined
|
|
1318
|
+
? { fenceToken: claimed.lease.fenceToken }
|
|
1319
|
+
: {}),
|
|
1320
|
+
...opts,
|
|
1321
|
+
}
|
|
1322
|
+
: {
|
|
1323
|
+
...(handle?.readAt !== undefined
|
|
1324
|
+
? {
|
|
1325
|
+
wait: 'confirmed' as const,
|
|
1326
|
+
readAt: handle.readAt,
|
|
1327
|
+
onStale: 'reject' as const,
|
|
1328
|
+
}
|
|
1329
|
+
: {}),
|
|
1330
|
+
...opts,
|
|
1331
|
+
...(handle ? { claim: { id: handle.id } } : {}),
|
|
1332
|
+
};
|
|
1333
|
+
syncClient.delete(model, effective);
|
|
1334
|
+
await waitForMutation(model, effective);
|
|
1335
|
+
}),
|
|
1336
|
+
|
|
1337
|
+
// `claim` is a callable namespace (take a claim) carrying the coordination
|
|
1338
|
+
// readers (`claim.state` / `claim.queue` / `claim.release` / `claim.reorder`).
|
|
1339
|
+
claim: claimApi,
|
|
1340
|
+
|
|
1341
|
+
track: guard(async (params: ModelTrackParams): Promise<ModelTrackResult> => {
|
|
1342
|
+
const dep: TrackDependency = {
|
|
1343
|
+
model: wireModel,
|
|
1344
|
+
id: params.id,
|
|
1345
|
+
...(params.readAt !== undefined ? { readAt: params.readAt } : {}),
|
|
1346
|
+
};
|
|
1347
|
+
// A track carries no write, so it rides the commit lane as a zero-operation
|
|
1348
|
+
// commit: the queue tolerates disconnects and de-dupes replays, and the
|
|
1349
|
+
// server's track-only path registers the premise and reports anything
|
|
1350
|
+
// that already fired. Reuse the same lane the batch `commits.create` door
|
|
1351
|
+
// uses rather than opening a bespoke transport.
|
|
1352
|
+
const clientTxId =
|
|
1353
|
+
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
|
1354
|
+
? crypto.randomUUID()
|
|
1355
|
+
: `tx_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
1356
|
+
const queue = syncClient.getMutationQueue();
|
|
1357
|
+
await queue.enqueueCommit(clientTxId, [], { track: [dep] });
|
|
1358
|
+
const { notifications } = await queue.waitForCommitReceipt(clientTxId);
|
|
1359
|
+
return notifications && notifications.length > 0 ? { notifications } : {};
|
|
1360
|
+
}),
|
|
1361
|
+
|
|
1362
|
+
join: guard(
|
|
1363
|
+
(
|
|
1364
|
+
ids: string | readonly string[],
|
|
1365
|
+
options?: JoinOptions,
|
|
1366
|
+
): Promise<JoinedParticipant> => {
|
|
1367
|
+
if (!collaboration?.createJoin) {
|
|
1368
|
+
throw new AbloValidationError(
|
|
1369
|
+
`Model "${schemaKey}" was built without a WebSocket runtime, so join() is unavailable here. Presence needs a live socket — use the standard Ablo({ schema, apiKey }) client (not the HTTP transport).`,
|
|
1370
|
+
{ code: 'model_join_not_configured' },
|
|
1371
|
+
);
|
|
1372
|
+
}
|
|
1373
|
+
return collaboration.createJoin(schemaKey, ids, options);
|
|
1374
|
+
},
|
|
1375
|
+
),
|
|
1376
|
+
|
|
1377
|
+
onChange(callback, options): () => void {
|
|
1378
|
+
return autorun(() => {
|
|
1379
|
+
callback(local.list(options));
|
|
1380
|
+
});
|
|
1381
|
+
},
|
|
1382
|
+
};
|
|
1383
|
+
|
|
1384
|
+
modelClientMeta.set(operations, {
|
|
1385
|
+
key: schemaKey,
|
|
1386
|
+
typename: registeredModelName,
|
|
1387
|
+
});
|
|
1388
|
+
|
|
1389
|
+
return operations;
|
|
1390
|
+
}
|