mindoodb 0.0.2 → 0.0.4
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-server.md +1001 -0
- package/README.md +89 -28
- package/dist/__mocks__/expo-standard-web-crypto.d.ts +10 -0
- package/dist/__mocks__/expo-standard-web-crypto.d.ts.map +1 -0
- package/dist/__mocks__/expo-standard-web-crypto.js +22 -0
- package/dist/__mocks__/expo-standard-web-crypto.js.map +1 -0
- package/dist/appendonlystores/BasicOnDiskContentAddressedStoreFactory.d.ts +8 -0
- package/dist/appendonlystores/BasicOnDiskContentAddressedStoreFactory.d.ts.map +1 -0
- package/dist/appendonlystores/BasicOnDiskContentAddressedStoreFactory.js +16 -0
- package/dist/appendonlystores/BasicOnDiskContentAddressedStoreFactory.js.map +1 -0
- package/dist/appendonlystores/InMemoryContentAddressedStoreFactory.d.ts +1 -1
- package/dist/appendonlystores/InMemoryContentAddressedStoreFactory.d.ts.map +1 -1
- package/dist/appendonlystores/InMemoryContentAddressedStoreFactory.js +2 -2
- package/dist/appendonlystores/InMemoryContentAddressedStoreFactory.js.map +1 -1
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts +30 -1
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts.map +1 -1
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js +152 -5
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js.map +1 -1
- package/dist/appendonlystores/network/HttpTransport.d.ts +17 -2
- package/dist/appendonlystores/network/HttpTransport.d.ts.map +1 -1
- package/dist/appendonlystores/network/HttpTransport.js +129 -0
- package/dist/appendonlystores/network/HttpTransport.js.map +1 -1
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts +22 -2
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts.map +1 -1
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js +110 -0
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js.map +1 -1
- package/dist/appendonlystores/network/index.d.ts +1 -1
- package/dist/appendonlystores/network/index.d.ts.map +1 -1
- package/dist/appendonlystores/network/index.js.map +1 -1
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStore.d.ts +65 -0
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStore.d.ts.map +1 -0
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStore.js +741 -0
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStore.js.map +1 -0
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStoreFactory.d.ts +25 -0
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStoreFactory.d.ts.map +1 -0
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStoreFactory.js +41 -0
- package/dist/browser/appendonlystores/IndexedDBContentAddressedStoreFactory.js.map +1 -0
- package/dist/browser/cache/IndexedDBLocalCacheStore.d.ts +21 -0
- package/dist/browser/cache/IndexedDBLocalCacheStore.d.ts.map +1 -0
- package/dist/browser/cache/IndexedDBLocalCacheStore.js +106 -0
- package/dist/browser/cache/IndexedDBLocalCacheStore.js.map +1 -0
- package/dist/browser/index.d.ts +8 -0
- package/dist/browser/index.d.ts.map +1 -1
- package/dist/browser/index.js +21 -1
- package/dist/browser/index.js.map +1 -1
- package/dist/core/BaseMindooDB.d.ts +115 -13
- package/dist/core/BaseMindooDB.d.ts.map +1 -1
- package/dist/core/BaseMindooDB.js +1232 -269
- package/dist/core/BaseMindooDB.js.map +1 -1
- package/dist/core/BaseMindooTenant.d.ts +69 -6
- package/dist/core/BaseMindooTenant.d.ts.map +1 -1
- package/dist/core/BaseMindooTenant.js +302 -109
- package/dist/core/BaseMindooTenant.js.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.d.ts +13 -10
- package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.js +144 -27
- package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
- package/dist/core/BaseMindooTenantFactory.d.ts +27 -29
- package/dist/core/BaseMindooTenantFactory.d.ts.map +1 -1
- package/dist/core/BaseMindooTenantFactory.js +185 -112
- package/dist/core/BaseMindooTenantFactory.js.map +1 -1
- package/dist/core/MindooDBServerAdmin.d.ts +238 -0
- package/dist/core/MindooDBServerAdmin.d.ts.map +1 -0
- package/dist/core/MindooDBServerAdmin.js +345 -0
- package/dist/core/MindooDBServerAdmin.js.map +1 -0
- package/dist/core/appendonlystores/BasicOnDiskContentAddressedStore.d.ts +68 -0
- package/dist/core/appendonlystores/BasicOnDiskContentAddressedStore.d.ts.map +1 -0
- package/dist/core/appendonlystores/BasicOnDiskContentAddressedStore.js +659 -0
- package/dist/core/appendonlystores/BasicOnDiskContentAddressedStore.js.map +1 -0
- package/dist/core/appendonlystores/InMemoryContentAddressedStore.d.ts +45 -3
- package/dist/core/appendonlystores/InMemoryContentAddressedStore.d.ts.map +1 -1
- package/dist/core/appendonlystores/InMemoryContentAddressedStore.js +184 -23
- package/dist/core/appendonlystores/InMemoryContentAddressedStore.js.map +1 -1
- package/dist/core/appendonlystores/MaterializationPlanner.d.ts +49 -0
- package/dist/core/appendonlystores/MaterializationPlanner.d.ts.map +1 -0
- package/dist/core/appendonlystores/MaterializationPlanner.js +325 -0
- package/dist/core/appendonlystores/MaterializationPlanner.js.map +1 -0
- package/dist/core/appendonlystores/bloom.d.ts +85 -0
- package/dist/core/appendonlystores/bloom.d.ts.map +1 -0
- package/dist/core/appendonlystores/bloom.js +228 -0
- package/dist/core/appendonlystores/bloom.js.map +1 -0
- package/dist/core/appendonlystores/network/NetworkTransport.d.ts +37 -2
- package/dist/core/appendonlystores/network/NetworkTransport.d.ts.map +1 -1
- package/dist/core/appendonlystores/network/types.d.ts +12 -0
- package/dist/core/appendonlystores/network/types.d.ts.map +1 -1
- package/dist/core/appendonlystores/network/types.js.map +1 -1
- package/dist/core/appendonlystores/types.d.ts +206 -0
- package/dist/core/appendonlystores/types.d.ts.map +1 -1
- package/dist/core/automerge-adapter.d.ts +15 -0
- package/dist/core/automerge-adapter.d.ts.map +1 -0
- package/dist/core/automerge-adapter.js +73 -0
- package/dist/core/automerge-adapter.js.map +1 -0
- package/dist/core/cache/CacheManager.d.ts +75 -0
- package/dist/core/cache/CacheManager.d.ts.map +1 -0
- package/dist/core/cache/CacheManager.js +101 -0
- package/dist/core/cache/CacheManager.js.map +1 -0
- package/dist/core/cache/EncryptedLocalCacheStore.d.ts +41 -0
- package/dist/core/cache/EncryptedLocalCacheStore.d.ts.map +1 -0
- package/dist/core/cache/EncryptedLocalCacheStore.js +120 -0
- package/dist/core/cache/EncryptedLocalCacheStore.js.map +1 -0
- package/dist/core/cache/LocalCacheStore.d.ts +50 -0
- package/dist/core/cache/LocalCacheStore.d.ts.map +1 -0
- package/dist/core/cache/LocalCacheStore.js +39 -0
- package/dist/core/cache/LocalCacheStore.js.map +1 -0
- package/dist/core/crypto/pbkdf2Iterations.d.ts +12 -0
- package/dist/core/crypto/pbkdf2Iterations.d.ts.map +1 -0
- package/dist/core/crypto/pbkdf2Iterations.js +55 -0
- package/dist/core/crypto/pbkdf2Iterations.js.map +1 -0
- package/dist/core/crypto/privateKeyEncryption.d.ts +5 -0
- package/dist/core/crypto/privateKeyEncryption.d.ts.map +1 -0
- package/dist/core/crypto/privateKeyEncryption.js +87 -0
- package/dist/core/crypto/privateKeyEncryption.js.map +1 -0
- package/dist/core/index.d.ts +18 -6
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +42 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/indexing/virtualviews/MindooDBVirtualViewDataProvider.d.ts +4 -1
- package/dist/core/indexing/virtualviews/MindooDBVirtualViewDataProvider.d.ts.map +1 -1
- package/dist/core/indexing/virtualviews/MindooDBVirtualViewDataProvider.js +39 -11
- package/dist/core/indexing/virtualviews/MindooDBVirtualViewDataProvider.js.map +1 -1
- package/dist/core/indexing/virtualviews/ViewEntrySortKeyComparator.d.ts +1 -0
- package/dist/core/indexing/virtualviews/ViewEntrySortKeyComparator.d.ts.map +1 -1
- package/dist/core/indexing/virtualviews/ViewEntrySortKeyComparator.js +3 -0
- package/dist/core/indexing/virtualviews/ViewEntrySortKeyComparator.js.map +1 -1
- package/dist/core/indexing/virtualviews/VirtualView.d.ts +43 -0
- package/dist/core/indexing/virtualviews/VirtualView.d.ts.map +1 -1
- package/dist/core/indexing/virtualviews/VirtualView.js +173 -0
- package/dist/core/indexing/virtualviews/VirtualView.js.map +1 -1
- package/dist/core/indexing/virtualviews/VirtualViewEntryData.d.ts +7 -0
- package/dist/core/indexing/virtualviews/VirtualViewEntryData.d.ts.map +1 -1
- package/dist/core/indexing/virtualviews/VirtualViewEntryData.js +28 -0
- package/dist/core/indexing/virtualviews/VirtualViewEntryData.js.map +1 -1
- package/dist/core/keys/KeyBag.d.ts +56 -12
- package/dist/core/keys/KeyBag.d.ts.map +1 -1
- package/dist/core/keys/KeyBag.js +156 -70
- package/dist/core/keys/KeyBag.js.map +1 -1
- package/dist/core/keys/KeyContext.d.ts +4 -0
- package/dist/core/keys/KeyContext.d.ts.map +1 -0
- package/dist/core/keys/KeyContext.js +17 -0
- package/dist/core/keys/KeyContext.js.map +1 -0
- package/dist/core/types.d.ts +512 -60
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js +9 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/uri/MindooURI.d.ts +58 -0
- package/dist/core/uri/MindooURI.d.ts.map +1 -0
- package/dist/core/uri/MindooURI.js +169 -0
- package/dist/core/uri/MindooURI.js.map +1 -0
- package/dist/core/userid/index.d.ts +0 -10
- package/dist/core/userid/index.d.ts.map +1 -1
- package/dist/core/utils/idGeneration.d.ts.map +1 -1
- package/dist/core/utils/idGeneration.js +37 -3
- package/dist/core/utils/idGeneration.js.map +1 -1
- package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.d.ts +544 -0
- package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.d.ts.map +1 -0
- package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.js +1358 -0
- package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.js.map +1 -0
- package/dist/node/attachments/writeAttachmentToFile.d.ts +15 -0
- package/dist/node/attachments/writeAttachmentToFile.d.ts.map +1 -0
- package/dist/node/attachments/writeAttachmentToFile.js +73 -0
- package/dist/node/attachments/writeAttachmentToFile.js.map +1 -0
- package/dist/node/cache/FileSystemLocalCacheStore.d.ts +17 -0
- package/dist/node/cache/FileSystemLocalCacheStore.d.ts.map +1 -0
- package/dist/node/cache/FileSystemLocalCacheStore.js +128 -0
- package/dist/node/cache/FileSystemLocalCacheStore.js.map +1 -0
- package/dist/node/cli/change-identity-password.d.ts +7 -0
- package/dist/node/cli/change-identity-password.d.ts.map +1 -0
- package/dist/node/cli/change-identity-password.js +67 -0
- package/dist/node/cli/change-identity-password.js.map +1 -0
- package/dist/node/cli/cli-utils.d.ts +16 -0
- package/dist/node/cli/cli-utils.d.ts.map +1 -0
- package/dist/node/cli/cli-utils.js +113 -0
- package/dist/node/cli/cli-utils.js.map +1 -0
- package/dist/node/cli/identity-export-public.d.ts +4 -0
- package/dist/node/cli/identity-export-public.d.ts.map +1 -0
- package/dist/node/cli/identity-export-public.js +55 -0
- package/dist/node/cli/identity-export-public.js.map +1 -0
- package/dist/node/cli/identity-info.d.ts +4 -0
- package/dist/node/cli/identity-info.d.ts.map +1 -0
- package/dist/node/cli/identity-info.js +57 -0
- package/dist/node/cli/identity-info.js.map +1 -0
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +8 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/server/CapabilityMatcher.d.ts +45 -0
- package/dist/node/server/CapabilityMatcher.d.ts.map +1 -0
- package/dist/node/server/CapabilityMatcher.js +117 -0
- package/dist/node/server/CapabilityMatcher.js.map +1 -0
- package/dist/node/server/MindooDBServer.d.ts +87 -0
- package/dist/node/server/MindooDBServer.d.ts.map +1 -0
- package/dist/node/server/MindooDBServer.js +1040 -0
- package/dist/node/server/MindooDBServer.js.map +1 -0
- package/dist/node/server/ServerSync.d.ts +41 -0
- package/dist/node/server/ServerSync.d.ts.map +1 -0
- package/dist/node/server/ServerSync.js +187 -0
- package/dist/node/server/ServerSync.js.map +1 -0
- package/dist/node/server/StoreFactory.d.ts +45 -0
- package/dist/node/server/StoreFactory.d.ts.map +1 -0
- package/dist/node/server/StoreFactory.js +89 -0
- package/dist/node/server/StoreFactory.js.map +1 -0
- package/dist/node/server/SystemAdminAuth.d.ts +65 -0
- package/dist/node/server/SystemAdminAuth.d.ts.map +1 -0
- package/dist/node/server/SystemAdminAuth.js +200 -0
- package/dist/node/server/SystemAdminAuth.js.map +1 -0
- package/dist/node/server/SystemIpAllowlist.d.ts +21 -0
- package/dist/node/server/SystemIpAllowlist.d.ts.map +1 -0
- package/dist/node/server/SystemIpAllowlist.js +210 -0
- package/dist/node/server/SystemIpAllowlist.js.map +1 -0
- package/dist/node/server/TenantManager.d.ts +85 -0
- package/dist/node/server/TenantManager.d.ts.map +1 -0
- package/dist/node/server/TenantManager.js +493 -0
- package/dist/node/server/TenantManager.js.map +1 -0
- package/dist/node/server/add-to-network.d.ts +20 -0
- package/dist/node/server/add-to-network.d.ts.map +1 -0
- package/dist/node/server/add-to-network.js +275 -0
- package/dist/node/server/add-to-network.js.map +1 -0
- package/dist/node/server/config.d.ts +51 -0
- package/dist/node/server/config.d.ts.map +1 -0
- package/dist/node/server/config.js +218 -0
- package/dist/node/server/config.js.map +1 -0
- package/dist/node/server/resolveServerPassword.d.ts +7 -0
- package/dist/node/server/resolveServerPassword.d.ts.map +1 -0
- package/dist/node/server/resolveServerPassword.js +25 -0
- package/dist/node/server/resolveServerPassword.js.map +1 -0
- package/dist/node/server/server.d.ts +22 -0
- package/dist/node/server/server.d.ts.map +1 -0
- package/dist/node/server/server.js +225 -0
- package/dist/node/server/server.js.map +1 -0
- package/dist/node/server/serverinit.d.ts +21 -0
- package/dist/node/server/serverinit.d.ts.map +1 -0
- package/dist/node/server/serverinit.js +317 -0
- package/dist/node/server/serverinit.js.map +1 -0
- package/dist/node/server/types.d.ts +162 -0
- package/dist/node/server/types.d.ts.map +1 -0
- package/dist/node/server/types.js +24 -0
- package/dist/node/server/types.js.map +1 -0
- package/dist/node/server/validation.d.ts +47 -0
- package/dist/node/server/validation.d.ts.map +1 -0
- package/dist/node/server/validation.js +114 -0
- package/dist/node/server/validation.js.map +1 -0
- package/dist/reactnative/cache/MMKVLocalCacheStore.d.ts +48 -0
- package/dist/reactnative/cache/MMKVLocalCacheStore.d.ts.map +1 -0
- package/dist/reactnative/cache/MMKVLocalCacheStore.js +113 -0
- package/dist/reactnative/cache/MMKVLocalCacheStore.js.map +1 -0
- package/dist/reactnative/crypto/AESAdapter.d.ts +18 -0
- package/dist/reactnative/crypto/AESAdapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/AESAdapter.js +112 -0
- package/dist/reactnative/crypto/AESAdapter.js.map +1 -0
- package/dist/reactnative/crypto/Ed25519Adapter.d.ts +34 -0
- package/dist/reactnative/crypto/Ed25519Adapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/Ed25519Adapter.js +386 -0
- package/dist/reactnative/crypto/Ed25519Adapter.js.map +1 -0
- package/dist/reactnative/crypto/ExpoGoCryptoAdapter.d.ts +23 -0
- package/dist/reactnative/crypto/ExpoGoCryptoAdapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/ExpoGoCryptoAdapter.js +51 -0
- package/dist/reactnative/crypto/ExpoGoCryptoAdapter.js.map +1 -0
- package/dist/reactnative/crypto/HMACAdapter.d.ts +13 -0
- package/dist/reactnative/crypto/HMACAdapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/HMACAdapter.js +50 -0
- package/dist/reactnative/crypto/HMACAdapter.js.map +1 -0
- package/dist/reactnative/crypto/KeyFormatConverter.d.ts +21 -0
- package/dist/reactnative/crypto/KeyFormatConverter.d.ts.map +1 -0
- package/dist/reactnative/crypto/KeyFormatConverter.js +72 -0
- package/dist/reactnative/crypto/KeyFormatConverter.js.map +1 -0
- package/dist/reactnative/crypto/PBKDF2Adapter.d.ts +19 -0
- package/dist/reactnative/crypto/PBKDF2Adapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/PBKDF2Adapter.js +67 -0
- package/dist/reactnative/crypto/PBKDF2Adapter.js.map +1 -0
- package/dist/reactnative/crypto/QuickCryptoAdapter.d.ts +37 -0
- package/dist/reactnative/crypto/QuickCryptoAdapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/QuickCryptoAdapter.js +72 -0
- package/dist/reactnative/crypto/QuickCryptoAdapter.js.map +1 -0
- package/dist/reactnative/crypto/RSAAdapter.d.ts +38 -0
- package/dist/reactnative/crypto/RSAAdapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/RSAAdapter.js +184 -0
- package/dist/reactnative/crypto/RSAAdapter.js.map +1 -0
- package/dist/reactnative/crypto/ReactNativeCryptoAdapter.d.ts +33 -0
- package/dist/reactnative/crypto/ReactNativeCryptoAdapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/ReactNativeCryptoAdapter.js +61 -0
- package/dist/reactnative/crypto/ReactNativeCryptoAdapter.js.map +1 -0
- package/dist/reactnative/crypto/SHA256Adapter.d.ts +9 -0
- package/dist/reactnative/crypto/SHA256Adapter.d.ts.map +1 -0
- package/dist/reactnative/crypto/SHA256Adapter.js +29 -0
- package/dist/reactnative/crypto/SHA256Adapter.js.map +1 -0
- package/dist/reactnative/crypto/SubtleCryptoPolyfill.d.ts +63 -0
- package/dist/reactnative/crypto/SubtleCryptoPolyfill.d.ts.map +1 -0
- package/dist/reactnative/crypto/SubtleCryptoPolyfill.js +350 -0
- package/dist/reactnative/crypto/SubtleCryptoPolyfill.js.map +1 -0
- package/dist/reactnative/index.d.ts +9 -0
- package/dist/reactnative/index.d.ts.map +1 -0
- package/dist/reactnative/index.js +41 -0
- package/dist/reactnative/index.js.map +1 -0
- package/package.json +63 -7
- package/patches/PATCHES.md +111 -0
- package/patches/react-native+0.76.9.patch +34 -0
- package/patches/react-native-quick-crypto+1.0.7.patch +42 -0
- package/scripts/cli.js +21 -0
- package/scripts/setup-react-native.js +228 -0
- package/templates/reactnative/App.js +252 -0
- package/templates/reactnative/app.json +29 -0
- package/templates/reactnative/babel.config.js +6 -0
- package/templates/reactnative/index.js +26 -0
- package/templates/reactnative/metro.config.snippet.js +39 -0
- package/templates/reactnative/mindoodb-polyfills.js +116 -0
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.computeDocumentMaterializationPlan = computeDocumentMaterializationPlan;
|
|
4
|
+
exports.computeBatchMaterializationPlan = computeBatchMaterializationPlan;
|
|
5
|
+
/**
|
|
6
|
+
* Shared, metadata-only planner for causal document materialization.
|
|
7
|
+
*
|
|
8
|
+
* Why this exists:
|
|
9
|
+
* - local and remote stores need the same causal replay behavior
|
|
10
|
+
* - planner must work without decrypting payloads
|
|
11
|
+
* - replay order must be deterministic across runs
|
|
12
|
+
*
|
|
13
|
+
* Core invariant:
|
|
14
|
+
* - `entryIdsToApply` contains exactly the replay entries needed to reconstruct
|
|
15
|
+
* latest state that are not already covered by the selected snapshot.
|
|
16
|
+
*/
|
|
17
|
+
const DOC_REPLAY_TYPES = new Set(["doc_create", "doc_change", "doc_delete"]);
|
|
18
|
+
/**
|
|
19
|
+
* Returns true for entry types that can influence Automerge latest state replay.
|
|
20
|
+
*/
|
|
21
|
+
function isReplayEntry(meta) {
|
|
22
|
+
return DOC_REPLAY_TYPES.has(meta.entryType);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Computes latest-state heads and all replay entries causally reachable from them.
|
|
26
|
+
*
|
|
27
|
+
* `latestReachable` intentionally excludes unrelated historical branches that are
|
|
28
|
+
* not ancestors of current heads, so coverage/replay decisions only operate on
|
|
29
|
+
* data needed for latest state materialization.
|
|
30
|
+
*/
|
|
31
|
+
function buildLatestStateReachability(replayEntries) {
|
|
32
|
+
const byId = new Map();
|
|
33
|
+
const referenced = new Set();
|
|
34
|
+
for (const entry of replayEntries) {
|
|
35
|
+
byId.set(entry.id, entry);
|
|
36
|
+
}
|
|
37
|
+
for (const entry of replayEntries) {
|
|
38
|
+
for (const depId of entry.dependencyIds) {
|
|
39
|
+
if (byId.has(depId)) {
|
|
40
|
+
referenced.add(depId);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
// Heads are entries that are not referenced as dependencies by any other replay entry.
|
|
45
|
+
const latestHeads = replayEntries
|
|
46
|
+
.filter((e) => !referenced.has(e.id))
|
|
47
|
+
.map((e) => e.id);
|
|
48
|
+
const latestReachable = new Set();
|
|
49
|
+
const stack = [...latestHeads];
|
|
50
|
+
while (stack.length > 0) {
|
|
51
|
+
const id = stack.pop();
|
|
52
|
+
if (latestReachable.has(id)) {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
latestReachable.add(id);
|
|
56
|
+
const entry = byId.get(id);
|
|
57
|
+
if (!entry) {
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
for (const depId of entry.dependencyIds) {
|
|
61
|
+
if (byId.has(depId) && !latestReachable.has(depId)) {
|
|
62
|
+
stack.push(depId);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { latestHeads, latestReachable };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Computes replay entries covered by the given snapshot.
|
|
70
|
+
*
|
|
71
|
+
* Coverage roots are chosen in this order:
|
|
72
|
+
* 1) explicit `snapshotHeadEntryIds` (preferred; most accurate)
|
|
73
|
+
* 2) snapshot `dependencyIds` (compatibility fallback)
|
|
74
|
+
*/
|
|
75
|
+
function coveredBySnapshot(snapshot, replayById) {
|
|
76
|
+
if (!snapshot) {
|
|
77
|
+
return new Set();
|
|
78
|
+
}
|
|
79
|
+
const roots = snapshot.snapshotHeadEntryIds && snapshot.snapshotHeadEntryIds.length > 0
|
|
80
|
+
? snapshot.snapshotHeadEntryIds
|
|
81
|
+
: snapshot.dependencyIds;
|
|
82
|
+
const covered = new Set();
|
|
83
|
+
const stack = [...roots];
|
|
84
|
+
while (stack.length > 0) {
|
|
85
|
+
const id = stack.pop();
|
|
86
|
+
if (covered.has(id)) {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const entry = replayById.get(id);
|
|
90
|
+
if (!entry) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
covered.add(id);
|
|
94
|
+
for (const depId of entry.dependencyIds) {
|
|
95
|
+
if (!covered.has(depId)) {
|
|
96
|
+
stack.push(depId);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return covered;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Produces a stable, dependency-first ordering of replay entries using
|
|
104
|
+
* Kahn's algorithm for topological sorting.
|
|
105
|
+
*
|
|
106
|
+
* The caller passes a set of entry IDs that need to be replayed (the
|
|
107
|
+
* "uncovered" set from {@link computeDocumentMaterializationPlan}) and the
|
|
108
|
+
* full metadata map so the function can inspect each entry's
|
|
109
|
+
* `dependencyIds`. The result is an array where every entry appears
|
|
110
|
+
* *after* all of its causal predecessors, which is the order
|
|
111
|
+
* `Automerge.applyChanges` requires to apply changes correctly.
|
|
112
|
+
*
|
|
113
|
+
* **Why Kahn's algorithm?** It processes nodes in BFS order starting from
|
|
114
|
+
* roots (entries with no in-set dependencies), decrementing the in-degree
|
|
115
|
+
* of each dependent as its predecessors are emitted. This naturally
|
|
116
|
+
* produces a valid topological order for any DAG.
|
|
117
|
+
*
|
|
118
|
+
* **Determinism:** When multiple entries become ready at the same time
|
|
119
|
+
* (in-degree drops to zero simultaneously), the queue is sorted
|
|
120
|
+
* lexicographically before the next dequeue. This guarantees the same
|
|
121
|
+
* output regardless of `Set` or `Map` iteration order, which can vary
|
|
122
|
+
* across JavaScript engines and process runs.
|
|
123
|
+
*
|
|
124
|
+
* **Cycle safety:** In a well-formed Automerge DAG, cycles are impossible.
|
|
125
|
+
* However, if corrupted metadata somehow introduces a cycle, the algorithm
|
|
126
|
+
* detects it (ordered.length < ids.size) and falls back to a simple
|
|
127
|
+
* lexicographic sort so the caller still receives a complete list rather
|
|
128
|
+
* than a partial one.
|
|
129
|
+
*
|
|
130
|
+
* @param ids The entry IDs to sort (typically the uncovered set).
|
|
131
|
+
* @param replayById Lookup map from entry ID to its metadata, used to
|
|
132
|
+
* read `dependencyIds` for graph edges.
|
|
133
|
+
* @returns Entry IDs in dependency-first order suitable for sequential
|
|
134
|
+
* application to an Automerge document.
|
|
135
|
+
*/
|
|
136
|
+
function topologicalByDependencies(ids, replayById) {
|
|
137
|
+
// ── Build the in-degree and reverse-adjacency structures ──────────
|
|
138
|
+
// `indegree` — for each id, how many of its dependencies are also in `ids`
|
|
139
|
+
// `dependents` — for each id, which other ids in the set depend on it
|
|
140
|
+
const indegree = new Map();
|
|
141
|
+
const dependents = new Map();
|
|
142
|
+
for (const id of ids) {
|
|
143
|
+
indegree.set(id, 0);
|
|
144
|
+
dependents.set(id, []);
|
|
145
|
+
}
|
|
146
|
+
for (const id of ids) {
|
|
147
|
+
const entry = replayById.get(id);
|
|
148
|
+
if (!entry) {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
for (const depId of entry.dependencyIds) {
|
|
152
|
+
if (!ids.has(depId)) {
|
|
153
|
+
// Dependency is outside the uncovered set (already covered by
|
|
154
|
+
// the snapshot or not part of the latest-state DAG) — skip it.
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
indegree.set(id, (indegree.get(id) || 0) + 1);
|
|
158
|
+
dependents.get(depId).push(id);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// ── Kahn's BFS ────────────────────────────────────────────────────
|
|
162
|
+
// Seed the queue with root entries (in-degree 0 within the set).
|
|
163
|
+
const queue = Array.from(ids).filter((id) => (indegree.get(id) || 0) === 0);
|
|
164
|
+
queue.sort();
|
|
165
|
+
const ordered = [];
|
|
166
|
+
while (queue.length > 0) {
|
|
167
|
+
const id = queue.shift();
|
|
168
|
+
ordered.push(id);
|
|
169
|
+
for (const dep of dependents.get(id) || []) {
|
|
170
|
+
const next = (indegree.get(dep) || 0) - 1;
|
|
171
|
+
indegree.set(dep, next);
|
|
172
|
+
if (next === 0) {
|
|
173
|
+
queue.push(dep);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
// Re-sort after adding newly ready entries to maintain determinism.
|
|
177
|
+
queue.sort();
|
|
178
|
+
}
|
|
179
|
+
// ── Cycle fallback ────────────────────────────────────────────────
|
|
180
|
+
if (ordered.length !== ids.size) {
|
|
181
|
+
return Array.from(ids).sort();
|
|
182
|
+
}
|
|
183
|
+
return ordered;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Computes a causal materialization plan for one document.
|
|
187
|
+
*
|
|
188
|
+
* Given all store entries for a document, this function answers two questions:
|
|
189
|
+
*
|
|
190
|
+
* 1. **Which snapshot should we load first?**
|
|
191
|
+
* The planner evaluates every `doc_snapshot` entry and selects the one whose
|
|
192
|
+
* causal coverage overlaps the most with the entries needed for the latest
|
|
193
|
+
* document state. A snapshot that covers 90% of the DAG means only 10%
|
|
194
|
+
* of entries need to be replayed — a large win for documents with long
|
|
195
|
+
* histories. When two snapshots cover the same number of latest-state
|
|
196
|
+
* entries, the newer one (by `createdAt`) wins as a deterministic
|
|
197
|
+
* tie-breaker. Correctness never depends on timestamps.
|
|
198
|
+
*
|
|
199
|
+
* 2. **Which change entries must be replayed on top of that snapshot?**
|
|
200
|
+
* Every entry in the latest-state DAG that is *not* causally covered by
|
|
201
|
+
* the selected snapshot is collected and sorted in dependency-first
|
|
202
|
+
* (topological) order. This is the minimal set of Automerge changes
|
|
203
|
+
* the caller must decrypt and apply to reach the current document state.
|
|
204
|
+
*
|
|
205
|
+
* Snapshot selection strategy:
|
|
206
|
+
* - Choose the snapshot with maximal overlap against `latestReachable`.
|
|
207
|
+
* - Break equal-coverage ties by newer `createdAt` (optimization only).
|
|
208
|
+
* - If no snapshots exist, all replay entries are returned (full rebuild).
|
|
209
|
+
*
|
|
210
|
+
* Attachment entries (`attachment_chunk`) are never included — the planner
|
|
211
|
+
* operates exclusively on `doc_create`, `doc_change`, and `doc_delete`
|
|
212
|
+
* entries (the types tracked by `DOC_REPLAY_TYPES`).
|
|
213
|
+
*
|
|
214
|
+
* @param docId The document to plan for.
|
|
215
|
+
* @param allEntriesForDoc Every entry metadata record for this document,
|
|
216
|
+
* including snapshots and attachments (attachments
|
|
217
|
+
* are filtered out internally).
|
|
218
|
+
* @param options Pass `{ includeDiagnostics: true }` to populate the
|
|
219
|
+
* `diagnostics` field with head IDs and coverage counts.
|
|
220
|
+
* @returns A plan containing the snapshot to load (if any) and the ordered
|
|
221
|
+
* list of entry IDs to apply afterwards.
|
|
222
|
+
*/
|
|
223
|
+
function computeDocumentMaterializationPlan(docId, allEntriesForDoc, options) {
|
|
224
|
+
// ── Step 1: Partition entries ──────────────────────────────────────
|
|
225
|
+
// Replay entries are the doc-lifecycle entries (create/change/delete) that
|
|
226
|
+
// form the Automerge DAG. Snapshots are evaluated separately as candidate
|
|
227
|
+
// starting points.
|
|
228
|
+
const replayEntries = allEntriesForDoc.filter(isReplayEntry);
|
|
229
|
+
const replayById = new Map(replayEntries.map((e) => [e.id, e]));
|
|
230
|
+
const snapshots = allEntriesForDoc.filter((e) => e.entryType === "doc_snapshot");
|
|
231
|
+
// ── Step 2: Handle empty replay set ─────────────────────────────────
|
|
232
|
+
// After a dense sync the local store may contain only a snapshot with no
|
|
233
|
+
// individual change entries. In that case select the newest snapshot so
|
|
234
|
+
// the caller can still load the document state.
|
|
235
|
+
if (replayEntries.length === 0) {
|
|
236
|
+
if (snapshots.length > 0) {
|
|
237
|
+
const best = snapshots.reduce((a, b) => (b.createdAt > a.createdAt ? b : a));
|
|
238
|
+
return {
|
|
239
|
+
docId,
|
|
240
|
+
snapshotEntryId: best.id,
|
|
241
|
+
entryIdsToApply: [],
|
|
242
|
+
diagnostics: options?.includeDiagnostics
|
|
243
|
+
? { headEntryIds: [], coveredLatestEntryCount: 0, uncoveredLatestEntryCount: 0 }
|
|
244
|
+
: undefined,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
docId,
|
|
249
|
+
snapshotEntryId: null,
|
|
250
|
+
entryIdsToApply: [],
|
|
251
|
+
diagnostics: options?.includeDiagnostics
|
|
252
|
+
? { headEntryIds: [], coveredLatestEntryCount: 0, uncoveredLatestEntryCount: 0 }
|
|
253
|
+
: undefined,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
// ── Step 3: Build latest-state reachability ───────────────────────
|
|
257
|
+
// Identify the DAG heads (entries with no dependents) and walk backward
|
|
258
|
+
// to collect every entry causally needed for the current document state.
|
|
259
|
+
const { latestHeads, latestReachable } = buildLatestStateReachability(replayEntries);
|
|
260
|
+
// ── Step 4: Score each snapshot by how many latest-state entries it covers
|
|
261
|
+
let bestSnapshot = null;
|
|
262
|
+
let bestCoveredCount = -1;
|
|
263
|
+
for (const snapshot of snapshots) {
|
|
264
|
+
const covered = coveredBySnapshot(snapshot, replayById);
|
|
265
|
+
let coveredLatest = 0;
|
|
266
|
+
for (const id of latestReachable) {
|
|
267
|
+
if (covered.has(id)) {
|
|
268
|
+
coveredLatest++;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (coveredLatest > bestCoveredCount ||
|
|
272
|
+
(coveredLatest === bestCoveredCount && bestSnapshot && snapshot.createdAt > bestSnapshot.createdAt)) {
|
|
273
|
+
bestSnapshot = snapshot;
|
|
274
|
+
bestCoveredCount = coveredLatest;
|
|
275
|
+
}
|
|
276
|
+
if (!bestSnapshot) {
|
|
277
|
+
bestSnapshot = snapshot;
|
|
278
|
+
bestCoveredCount = coveredLatest;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// ── Step 5: Compute the uncovered set ─────────────────────────────
|
|
282
|
+
// These are the entries that the selected snapshot does NOT already include.
|
|
283
|
+
// If no snapshot was selected, the entire latestReachable set is uncovered.
|
|
284
|
+
const covered = coveredBySnapshot(bestSnapshot, replayById);
|
|
285
|
+
const uncovered = new Set();
|
|
286
|
+
for (const id of latestReachable) {
|
|
287
|
+
if (!covered.has(id)) {
|
|
288
|
+
uncovered.add(id);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
// ── Step 6: Sort uncovered entries in dependency-first order ──────
|
|
292
|
+
// This guarantees that Automerge.applyChanges sees each change only after
|
|
293
|
+
// all of its causal predecessors have already been applied.
|
|
294
|
+
const entryIdsToApply = topologicalByDependencies(uncovered, replayById);
|
|
295
|
+
return {
|
|
296
|
+
docId,
|
|
297
|
+
snapshotEntryId: bestSnapshot ? bestSnapshot.id : null,
|
|
298
|
+
entryIdsToApply,
|
|
299
|
+
diagnostics: options?.includeDiagnostics
|
|
300
|
+
? {
|
|
301
|
+
headEntryIds: latestHeads,
|
|
302
|
+
coveredLatestEntryCount: bestCoveredCount < 0 ? 0 : bestCoveredCount,
|
|
303
|
+
uncoveredLatestEntryCount: uncovered.size,
|
|
304
|
+
}
|
|
305
|
+
: undefined,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Computes plans for many documents in one metadata pass.
|
|
310
|
+
*
|
|
311
|
+
* Batch planning is important for networked stores to reduce request/response
|
|
312
|
+
* chattiness during startup and dense sync operations.
|
|
313
|
+
*/
|
|
314
|
+
function computeBatchMaterializationPlan(allEntries, docIds, options) {
|
|
315
|
+
const byDoc = new Map();
|
|
316
|
+
for (const entry of allEntries) {
|
|
317
|
+
if (!byDoc.has(entry.docId)) {
|
|
318
|
+
byDoc.set(entry.docId, []);
|
|
319
|
+
}
|
|
320
|
+
byDoc.get(entry.docId).push(entry);
|
|
321
|
+
}
|
|
322
|
+
const plans = docIds.map((docId) => computeDocumentMaterializationPlan(docId, byDoc.get(docId) || [], options));
|
|
323
|
+
return { plans };
|
|
324
|
+
}
|
|
325
|
+
//# sourceMappingURL=MaterializationPlanner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MaterializationPlanner.js","sourceRoot":"","sources":["../../../src/core/appendonlystores/MaterializationPlanner.ts"],"names":[],"mappings":";;AAsPA,gFAkGC;AAQD,0EAkBC;AA3WD;;;;;;;;;;;GAWG;AACH,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC;AAE7E;;GAEG;AACH,SAAS,aAAa,CAAC,IAAwB;IAC7C,OAAO,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAED;;;;;;GAMG;AACH,SAAS,4BAA4B,CACnC,aAAmC;IAEnC,MAAM,IAAI,GAAG,IAAI,GAAG,EAA8B,CAAC;IACnD,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACrC,KAAK,MAAM,KAAK,IAAI,aAAa,EAAE,CAAC;QAClC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;IACD,KAAK,MAAM,KAAK,IAAI,aAAa,EAAE,CAAC;QAClC,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;YACxC,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;gBACpB,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YACxB,CAAC;QACH,CAAC;IACH,CAAC;IAED,uFAAuF;IACvF,MAAM,WAAW,GAAG,aAAa;SAC9B,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;SACpC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,C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,EAAE,EAAE,CAAC,CAAC;QAC7B,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CACjC,kCAAkC,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,OAAO,CAAC,CAC3E,CAAC;IAEF,OAAO,EAAE,KAAK,EAAE,CAAC;AACnB,CAAC"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bloom filter for compact set-membership summaries of store entry IDs.
|
|
3
|
+
*
|
|
4
|
+
* During network sync, a local store needs to determine which of its entry IDs
|
|
5
|
+
* are missing from a remote store. Naively this requires sending every local ID
|
|
6
|
+
* to the remote for an exact `hasEntries` check — an O(n) network round-trip
|
|
7
|
+
* that dominates sync latency for large stores.
|
|
8
|
+
*
|
|
9
|
+
* A bloom filter provides a probabilistic shortcut: the remote store serializes
|
|
10
|
+
* its full ID set into a compact bitset ({@link StoreIdBloomSummary}) and sends
|
|
11
|
+
* it to the local side in a single response. The local side then tests each of
|
|
12
|
+
* its own IDs against the bloom filter:
|
|
13
|
+
*
|
|
14
|
+
* - **Definite negative** — the ID is certainly absent on the remote; no
|
|
15
|
+
* round-trip needed, the entry can be pushed immediately.
|
|
16
|
+
* - **Probable positive** — the ID *might* exist on the remote (subject to a
|
|
17
|
+
* configurable false-positive rate, default 1 %). Only these IDs require a
|
|
18
|
+
* follow-up `hasEntries` call to confirm.
|
|
19
|
+
*
|
|
20
|
+
* This is used by {@link BasicOnDiskContentAddressedStore.getIdBloomSummary} and
|
|
21
|
+
* consumed by the sync loop in `BaseMindooDB` to partition IDs into
|
|
22
|
+
* "definitely missing" and "maybe existing" buckets before making any network
|
|
23
|
+
* calls.
|
|
24
|
+
*
|
|
25
|
+
* ### Implementation details
|
|
26
|
+
*
|
|
27
|
+
* - Uses **enhanced double hashing** (FNV-1a + DJB2) to derive `k` bit
|
|
28
|
+
* positions from a single ID string, avoiding the need for `k` independent
|
|
29
|
+
* hash functions.
|
|
30
|
+
* - Bit-array size and hash count are computed from the classic bloom filter
|
|
31
|
+
* formulas to satisfy the requested false-positive rate.
|
|
32
|
+
* - The filter is versioned (`"bloom-v1"`) so future changes to hashing or
|
|
33
|
+
* encoding remain backward-compatible.
|
|
34
|
+
*
|
|
35
|
+
* @module bloom
|
|
36
|
+
*/
|
|
37
|
+
import type { StoreIdBloomSummary } from "./types";
|
|
38
|
+
/**
|
|
39
|
+
* Build a bloom filter summary from a list of entry IDs.
|
|
40
|
+
*
|
|
41
|
+
* The resulting {@link StoreIdBloomSummary} is a compact, serializable
|
|
42
|
+
* representation that can be transferred over the network (e.g. in sync
|
|
43
|
+
* protocol responses) and later queried with {@link bloomMightContainId}.
|
|
44
|
+
*
|
|
45
|
+
* Typical usage in the on-disk store:
|
|
46
|
+
* ```ts
|
|
47
|
+
* const ids = await store.getAllIds();
|
|
48
|
+
* const summary = createIdBloomSummary(ids);
|
|
49
|
+
* // send summary to the syncing peer
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* @param ids Array of entry ID strings to include in the filter.
|
|
53
|
+
* @param falsePositiveRate Target false-positive probability (default 1 %).
|
|
54
|
+
* @returns A serializable bloom filter summary (base64-encoded bitset).
|
|
55
|
+
*/
|
|
56
|
+
export declare function createIdBloomSummary(ids: string[], falsePositiveRate?: number): StoreIdBloomSummary;
|
|
57
|
+
/**
|
|
58
|
+
* Test whether an entry ID *might* be present in a bloom filter summary.
|
|
59
|
+
*
|
|
60
|
+
* - Returns `false` only when the ID is **definitely absent** — at least one
|
|
61
|
+
* of its bit-positions is unset, so the ID was never inserted.
|
|
62
|
+
* - Returns `true` when the ID **might be present** — all bit-positions are
|
|
63
|
+
* set, but this could be a false positive (probability ≤ the configured
|
|
64
|
+
* false-positive rate).
|
|
65
|
+
*
|
|
66
|
+
* If the summary version is unrecognized, conservatively returns `true` to
|
|
67
|
+
* avoid incorrectly skipping entries during sync.
|
|
68
|
+
*
|
|
69
|
+
* Used in the sync loop to partition local IDs:
|
|
70
|
+
* ```ts
|
|
71
|
+
* for (const id of localIds) {
|
|
72
|
+
* if (bloomMightContainId(remoteBloom, id)) {
|
|
73
|
+
* maybeExisting.push(id); // needs exact hasEntries() check
|
|
74
|
+
* } else {
|
|
75
|
+
* definitelyMissing.push(id); // can push without round-trip
|
|
76
|
+
* }
|
|
77
|
+
* }
|
|
78
|
+
* ```
|
|
79
|
+
*
|
|
80
|
+
* @param summary The bloom filter summary obtained from the remote store.
|
|
81
|
+
* @param id The entry ID to test.
|
|
82
|
+
* @returns `true` if the ID might be in the set; `false` if it is definitely not.
|
|
83
|
+
*/
|
|
84
|
+
export declare function bloomMightContainId(summary: StoreIdBloomSummary, id: string): boolean;
|
|
85
|
+
//# sourceMappingURL=bloom.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bloom.d.ts","sourceRoot":"","sources":["../../../src/core/appendonlystores/bloom.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AA+HnD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,iBAAiB,GAAE,MAAoC,GAAG,mBAAmB,CAmBhI;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,mBAAmB,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAYrF"}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Bloom filter for compact set-membership summaries of store entry IDs.
|
|
4
|
+
*
|
|
5
|
+
* During network sync, a local store needs to determine which of its entry IDs
|
|
6
|
+
* are missing from a remote store. Naively this requires sending every local ID
|
|
7
|
+
* to the remote for an exact `hasEntries` check — an O(n) network round-trip
|
|
8
|
+
* that dominates sync latency for large stores.
|
|
9
|
+
*
|
|
10
|
+
* A bloom filter provides a probabilistic shortcut: the remote store serializes
|
|
11
|
+
* its full ID set into a compact bitset ({@link StoreIdBloomSummary}) and sends
|
|
12
|
+
* it to the local side in a single response. The local side then tests each of
|
|
13
|
+
* its own IDs against the bloom filter:
|
|
14
|
+
*
|
|
15
|
+
* - **Definite negative** — the ID is certainly absent on the remote; no
|
|
16
|
+
* round-trip needed, the entry can be pushed immediately.
|
|
17
|
+
* - **Probable positive** — the ID *might* exist on the remote (subject to a
|
|
18
|
+
* configurable false-positive rate, default 1 %). Only these IDs require a
|
|
19
|
+
* follow-up `hasEntries` call to confirm.
|
|
20
|
+
*
|
|
21
|
+
* This is used by {@link BasicOnDiskContentAddressedStore.getIdBloomSummary} and
|
|
22
|
+
* consumed by the sync loop in `BaseMindooDB` to partition IDs into
|
|
23
|
+
* "definitely missing" and "maybe existing" buckets before making any network
|
|
24
|
+
* calls.
|
|
25
|
+
*
|
|
26
|
+
* ### Implementation details
|
|
27
|
+
*
|
|
28
|
+
* - Uses **enhanced double hashing** (FNV-1a + DJB2) to derive `k` bit
|
|
29
|
+
* positions from a single ID string, avoiding the need for `k` independent
|
|
30
|
+
* hash functions.
|
|
31
|
+
* - Bit-array size and hash count are computed from the classic bloom filter
|
|
32
|
+
* formulas to satisfy the requested false-positive rate.
|
|
33
|
+
* - The filter is versioned (`"bloom-v1"`) so future changes to hashing or
|
|
34
|
+
* encoding remain backward-compatible.
|
|
35
|
+
*
|
|
36
|
+
* @module bloom
|
|
37
|
+
*/
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.createIdBloomSummary = createIdBloomSummary;
|
|
40
|
+
exports.bloomMightContainId = bloomMightContainId;
|
|
41
|
+
/** Cross-platform Uint8Array -> base64 string. */
|
|
42
|
+
function uint8ArrayToBase64(bytes) {
|
|
43
|
+
let binary = "";
|
|
44
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
45
|
+
binary += String.fromCharCode(bytes[i]);
|
|
46
|
+
}
|
|
47
|
+
return btoa(binary);
|
|
48
|
+
}
|
|
49
|
+
/** Cross-platform base64 string -> Uint8Array. */
|
|
50
|
+
function base64ToUint8Array(base64) {
|
|
51
|
+
const binary = atob(base64);
|
|
52
|
+
const bytes = new Uint8Array(binary.length);
|
|
53
|
+
for (let i = 0; i < binary.length; i++) {
|
|
54
|
+
bytes[i] = binary.charCodeAt(i);
|
|
55
|
+
}
|
|
56
|
+
return bytes;
|
|
57
|
+
}
|
|
58
|
+
/** Default probability of a false positive (1 %). */
|
|
59
|
+
const DEFAULT_FALSE_POSITIVE_RATE = 0.01;
|
|
60
|
+
/** Salt mixed into every hash to namespace this bloom filter version. */
|
|
61
|
+
const DEFAULT_SALT = "mindoodb-bloom-v1";
|
|
62
|
+
/**
|
|
63
|
+
* FNV-1a 32-bit hash.
|
|
64
|
+
*
|
|
65
|
+
* Used as the first of two independent hash bases for enhanced double hashing.
|
|
66
|
+
* FNV-1a is fast, has good avalanche properties, and is simple to implement
|
|
67
|
+
* without external dependencies.
|
|
68
|
+
*/
|
|
69
|
+
function fnv1a32(input) {
|
|
70
|
+
let hash = 0x811c9dc5;
|
|
71
|
+
for (let i = 0; i < input.length; i++) {
|
|
72
|
+
hash ^= input.charCodeAt(i);
|
|
73
|
+
hash = Math.imul(hash, 0x01000193);
|
|
74
|
+
}
|
|
75
|
+
return hash >>> 0;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* DJB2 32-bit hash (Daniel J. Bernstein).
|
|
79
|
+
*
|
|
80
|
+
* Used as the second hash base. Chosen for its simplicity and because it is
|
|
81
|
+
* sufficiently independent from FNV-1a to give good bit dispersion when
|
|
82
|
+
* combined via enhanced double hashing: h(i) = h1 + i * h2.
|
|
83
|
+
*/
|
|
84
|
+
function djb2_32(input) {
|
|
85
|
+
let hash = 5381;
|
|
86
|
+
for (let i = 0; i < input.length; i++) {
|
|
87
|
+
hash = ((hash << 5) + hash + input.charCodeAt(i)) >>> 0;
|
|
88
|
+
}
|
|
89
|
+
return hash >>> 0;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Compute the optimal bit-array size and number of hash functions for a bloom
|
|
93
|
+
* filter given the expected item count and desired false-positive rate.
|
|
94
|
+
*
|
|
95
|
+
* Uses the standard formulas:
|
|
96
|
+
* m = -(n * ln(p)) / (ln2)^2 (bit count)
|
|
97
|
+
* k = (m / n) * ln2 (hash count)
|
|
98
|
+
*
|
|
99
|
+
* A minimum of 64 bits and 1 hash is enforced so the filter remains valid
|
|
100
|
+
* even for very small or empty sets.
|
|
101
|
+
*
|
|
102
|
+
* @param itemCount Expected number of distinct IDs.
|
|
103
|
+
* @param falsePositiveRate Target false-positive probability (0 < p < 1).
|
|
104
|
+
* @returns Optimal `bitCount` and `hashCount`.
|
|
105
|
+
*/
|
|
106
|
+
function computeBloomShape(itemCount, falsePositiveRate) {
|
|
107
|
+
if (itemCount <= 0) {
|
|
108
|
+
return { bitCount: 64, hashCount: 2 };
|
|
109
|
+
}
|
|
110
|
+
const ln2 = Math.log(2);
|
|
111
|
+
const bitCount = Math.max(64, Math.ceil((-itemCount * Math.log(falsePositiveRate)) / (ln2 * ln2)));
|
|
112
|
+
const hashCount = Math.max(1, Math.round((bitCount / itemCount) * ln2));
|
|
113
|
+
return { bitCount, hashCount };
|
|
114
|
+
}
|
|
115
|
+
/** Set a single bit in a byte-packed bitset. */
|
|
116
|
+
function setBit(bitset, bitIndex) {
|
|
117
|
+
const byteIndex = Math.floor(bitIndex / 8);
|
|
118
|
+
const bitOffset = bitIndex % 8;
|
|
119
|
+
bitset[byteIndex] |= 1 << bitOffset;
|
|
120
|
+
}
|
|
121
|
+
/** Test whether a single bit is set in a byte-packed bitset. */
|
|
122
|
+
function getBit(bitset, bitIndex) {
|
|
123
|
+
const byteIndex = Math.floor(bitIndex / 8);
|
|
124
|
+
const bitOffset = bitIndex % 8;
|
|
125
|
+
return (bitset[byteIndex] & (1 << bitOffset)) !== 0;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Derive `hashCount` bit-positions for an ID using enhanced double hashing.
|
|
129
|
+
*
|
|
130
|
+
* Enhanced double hashing computes k positions as:
|
|
131
|
+
* index_i = (h1 + i * h2) mod bitCount
|
|
132
|
+
*
|
|
133
|
+
* where h1 = FNV-1a(salt + id) and h2 = DJB2(id + salt). The salt is
|
|
134
|
+
* prepended/appended in opposite order to reduce correlation between the two
|
|
135
|
+
* hash values.
|
|
136
|
+
*
|
|
137
|
+
* @param id The entry ID to hash.
|
|
138
|
+
* @param bitCount Total bits in the bloom filter.
|
|
139
|
+
* @param hashCount Number of bit positions to produce.
|
|
140
|
+
* @param salt Version-specific salt string.
|
|
141
|
+
* @returns Array of `hashCount` bit-positions in [0, bitCount).
|
|
142
|
+
*/
|
|
143
|
+
function bloomIndexes(id, bitCount, hashCount, salt) {
|
|
144
|
+
const h1 = fnv1a32(`${salt}:${id}`);
|
|
145
|
+
const h2 = djb2_32(`${id}:${salt}`) || 1;
|
|
146
|
+
const indexes = [];
|
|
147
|
+
for (let i = 0; i < hashCount; i++) {
|
|
148
|
+
indexes.push((h1 + i * h2) % bitCount);
|
|
149
|
+
}
|
|
150
|
+
return indexes;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Build a bloom filter summary from a list of entry IDs.
|
|
154
|
+
*
|
|
155
|
+
* The resulting {@link StoreIdBloomSummary} is a compact, serializable
|
|
156
|
+
* representation that can be transferred over the network (e.g. in sync
|
|
157
|
+
* protocol responses) and later queried with {@link bloomMightContainId}.
|
|
158
|
+
*
|
|
159
|
+
* Typical usage in the on-disk store:
|
|
160
|
+
* ```ts
|
|
161
|
+
* const ids = await store.getAllIds();
|
|
162
|
+
* const summary = createIdBloomSummary(ids);
|
|
163
|
+
* // send summary to the syncing peer
|
|
164
|
+
* ```
|
|
165
|
+
*
|
|
166
|
+
* @param ids Array of entry ID strings to include in the filter.
|
|
167
|
+
* @param falsePositiveRate Target false-positive probability (default 1 %).
|
|
168
|
+
* @returns A serializable bloom filter summary (base64-encoded bitset).
|
|
169
|
+
*/
|
|
170
|
+
function createIdBloomSummary(ids, falsePositiveRate = DEFAULT_FALSE_POSITIVE_RATE) {
|
|
171
|
+
const { bitCount, hashCount } = computeBloomShape(ids.length, falsePositiveRate);
|
|
172
|
+
const bitset = new Uint8Array(Math.ceil(bitCount / 8));
|
|
173
|
+
for (const id of ids) {
|
|
174
|
+
const indexes = bloomIndexes(id, bitCount, hashCount, DEFAULT_SALT);
|
|
175
|
+
for (const idx of indexes) {
|
|
176
|
+
setBit(bitset, idx);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
version: "bloom-v1",
|
|
181
|
+
totalIds: ids.length,
|
|
182
|
+
bitCount,
|
|
183
|
+
hashCount,
|
|
184
|
+
salt: DEFAULT_SALT,
|
|
185
|
+
bitsetBase64: uint8ArrayToBase64(bitset),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Test whether an entry ID *might* be present in a bloom filter summary.
|
|
190
|
+
*
|
|
191
|
+
* - Returns `false` only when the ID is **definitely absent** — at least one
|
|
192
|
+
* of its bit-positions is unset, so the ID was never inserted.
|
|
193
|
+
* - Returns `true` when the ID **might be present** — all bit-positions are
|
|
194
|
+
* set, but this could be a false positive (probability ≤ the configured
|
|
195
|
+
* false-positive rate).
|
|
196
|
+
*
|
|
197
|
+
* If the summary version is unrecognized, conservatively returns `true` to
|
|
198
|
+
* avoid incorrectly skipping entries during sync.
|
|
199
|
+
*
|
|
200
|
+
* Used in the sync loop to partition local IDs:
|
|
201
|
+
* ```ts
|
|
202
|
+
* for (const id of localIds) {
|
|
203
|
+
* if (bloomMightContainId(remoteBloom, id)) {
|
|
204
|
+
* maybeExisting.push(id); // needs exact hasEntries() check
|
|
205
|
+
* } else {
|
|
206
|
+
* definitelyMissing.push(id); // can push without round-trip
|
|
207
|
+
* }
|
|
208
|
+
* }
|
|
209
|
+
* ```
|
|
210
|
+
*
|
|
211
|
+
* @param summary The bloom filter summary obtained from the remote store.
|
|
212
|
+
* @param id The entry ID to test.
|
|
213
|
+
* @returns `true` if the ID might be in the set; `false` if it is definitely not.
|
|
214
|
+
*/
|
|
215
|
+
function bloomMightContainId(summary, id) {
|
|
216
|
+
if (summary.version !== "bloom-v1") {
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
const bitset = base64ToUint8Array(summary.bitsetBase64);
|
|
220
|
+
const indexes = bloomIndexes(id, summary.bitCount, summary.hashCount, summary.salt);
|
|
221
|
+
for (const idx of indexes) {
|
|
222
|
+
if (!getBit(bitset, idx)) {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
//# sourceMappingURL=bloom.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bloom.js","sourceRoot":"","sources":["../../../src/core/appendonlystores/bloom.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;;AAmJH,oDAmBC;AA6BD,kDAYC;AA3MD,kDAAkD;AAClD,SAAS,kBAAkB,CAAC,KAAiB;IAC3C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC;AAED,kDAAkD;AAClD,S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