mindoodb 0.2.3 → 0.2.5
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 +6 -5
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts +7 -0
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts.map +1 -1
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js +17 -0
- package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js.map +1 -1
- package/dist/appendonlystores/network/GuestTicketClient.d.ts +62 -0
- package/dist/appendonlystores/network/GuestTicketClient.d.ts.map +1 -0
- package/dist/appendonlystores/network/GuestTicketClient.js +163 -0
- package/dist/appendonlystores/network/GuestTicketClient.js.map +1 -0
- package/dist/appendonlystores/network/HttpTransport.d.ts +3 -0
- package/dist/appendonlystores/network/HttpTransport.d.ts.map +1 -1
- package/dist/appendonlystores/network/HttpTransport.js +13 -0
- package/dist/appendonlystores/network/HttpTransport.js.map +1 -1
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts +54 -1
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts.map +1 -1
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js +95 -11
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js.map +1 -1
- package/dist/appendonlystores/network/index.d.ts +1 -0
- package/dist/appendonlystores/network/index.d.ts.map +1 -1
- package/dist/appendonlystores/network/index.js +5 -1
- package/dist/appendonlystores/network/index.js.map +1 -1
- package/dist/browser/cache/IndexedDBLocalCacheStore.d.ts +1 -0
- package/dist/browser/cache/IndexedDBLocalCacheStore.d.ts.map +1 -1
- package/dist/browser/cache/IndexedDBLocalCacheStore.js +18 -0
- package/dist/browser/cache/IndexedDBLocalCacheStore.js.map +1 -1
- package/dist/browser/index.d.ts +1 -0
- package/dist/browser/index.d.ts.map +1 -1
- package/dist/browser/index.js +4 -1
- package/dist/browser/index.js.map +1 -1
- package/dist/browser/index.mjs +39 -0
- package/dist/cloudflare/MindooDatabaseObject.d.ts.map +1 -1
- package/dist/cloudflare/MindooDatabaseObject.js +11 -0
- package/dist/cloudflare/MindooDatabaseObject.js.map +1 -1
- package/dist/cloudflare/http.d.ts +4 -0
- package/dist/cloudflare/http.d.ts.map +1 -1
- package/dist/cloudflare/http.js +6 -4
- package/dist/cloudflare/http.js.map +1 -1
- package/dist/core/BaseMindooDB.d.ts +91 -40
- package/dist/core/BaseMindooDB.d.ts.map +1 -1
- package/dist/core/BaseMindooDB.js +532 -295
- package/dist/core/BaseMindooDB.js.map +1 -1
- package/dist/core/BaseMindooTenant.d.ts +12 -0
- package/dist/core/BaseMindooTenant.d.ts.map +1 -1
- package/dist/core/BaseMindooTenant.js +45 -7
- package/dist/core/BaseMindooTenant.js.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.d.ts +129 -0
- package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.js +426 -0
- package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
- package/dist/core/accesscontrol/directoryProjection.d.ts.map +1 -1
- package/dist/core/accesscontrol/directoryProjection.js +11 -0
- package/dist/core/accesscontrol/directoryProjection.js.map +1 -1
- package/dist/core/accesscontrol/types.d.ts +27 -2
- package/dist/core/accesscontrol/types.d.ts.map +1 -1
- package/dist/core/accesscontrol/types.js +16 -0
- package/dist/core/accesscontrol/types.js.map +1 -1
- package/dist/core/appendonlystores/bloom.d.ts +9 -0
- package/dist/core/appendonlystores/bloom.d.ts.map +1 -1
- package/dist/core/appendonlystores/bloom.js +30 -0
- package/dist/core/appendonlystores/bloom.js.map +1 -1
- package/dist/core/appendonlystores/network/AuthenticationService.d.ts +43 -1
- package/dist/core/appendonlystores/network/AuthenticationService.d.ts.map +1 -1
- package/dist/core/appendonlystores/network/AuthenticationService.js +69 -1
- package/dist/core/appendonlystores/network/AuthenticationService.js.map +1 -1
- package/dist/core/appendonlystores/network/NetworkTransport.d.ts +5 -0
- package/dist/core/appendonlystores/network/NetworkTransport.d.ts.map +1 -1
- package/dist/core/appendonlystores/network/types.d.ts +17 -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/rpc/RpcContentAddressedStore.d.ts +7 -0
- package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.d.ts.map +1 -1
- package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.js +7 -1
- package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.js.map +1 -1
- package/dist/core/appendonlystores/rpc/SqlRpc.d.ts +116 -0
- package/dist/core/appendonlystores/rpc/SqlRpc.d.ts.map +1 -0
- package/dist/core/appendonlystores/rpc/SqlRpc.js +276 -0
- package/dist/core/appendonlystores/rpc/SqlRpc.js.map +1 -0
- package/dist/core/appendonlystores/rpc/StoreRpcServer.d.ts +6 -2
- package/dist/core/appendonlystores/rpc/StoreRpcServer.d.ts.map +1 -1
- package/dist/core/appendonlystores/rpc/StoreRpcServer.js +1 -1
- package/dist/core/appendonlystores/rpc/StoreRpcServer.js.map +1 -1
- package/dist/core/appendonlystores/sqlite/SqliteContentAddressedStore.d.ts.map +1 -1
- package/dist/core/appendonlystores/sqlite/SqliteContentAddressedStore.js +32 -2
- package/dist/core/appendonlystores/sqlite/SqliteContentAddressedStore.js.map +1 -1
- package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts +10 -6
- package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts.map +1 -1
- package/dist/core/appendonlystores/sqlite/SqliteDriver.js +68 -2
- package/dist/core/appendonlystores/sqlite/SqliteDriver.js.map +1 -1
- package/dist/core/appendonlystores/sqlite/sqliteSchema.d.ts +59 -0
- package/dist/core/appendonlystores/sqlite/sqliteSchema.d.ts.map +1 -0
- package/dist/core/appendonlystores/sqlite/sqliteSchema.js +64 -0
- package/dist/core/appendonlystores/sqlite/sqliteSchema.js.map +1 -0
- package/dist/core/archive/documentArchive.d.ts.map +1 -1
- package/dist/core/archive/documentArchive.js +3 -2
- package/dist/core/archive/documentArchive.js.map +1 -1
- package/dist/core/builtinDbInvariants.d.ts +8 -2
- package/dist/core/builtinDbInvariants.d.ts.map +1 -1
- package/dist/core/builtinDbInvariants.js +8 -2
- package/dist/core/builtinDbInvariants.js.map +1 -1
- package/dist/core/cache/DocStateTable.d.ts +144 -0
- package/dist/core/cache/DocStateTable.d.ts.map +1 -0
- package/dist/core/cache/DocStateTable.js +398 -0
- package/dist/core/cache/DocStateTable.js.map +1 -0
- package/dist/core/cache/EncryptedLocalCacheStore.d.ts +11 -0
- package/dist/core/cache/EncryptedLocalCacheStore.d.ts.map +1 -1
- package/dist/core/cache/EncryptedLocalCacheStore.js +20 -0
- package/dist/core/cache/EncryptedLocalCacheStore.js.map +1 -1
- package/dist/core/cache/FulltextTable.d.ts +89 -0
- package/dist/core/cache/FulltextTable.d.ts.map +1 -0
- package/dist/core/cache/FulltextTable.js +225 -0
- package/dist/core/cache/FulltextTable.js.map +1 -0
- package/dist/core/cache/LocalCacheStore.d.ts +16 -0
- package/dist/core/cache/LocalCacheStore.d.ts.map +1 -1
- package/dist/core/cache/LocalCacheStore.js +11 -0
- package/dist/core/cache/LocalCacheStore.js.map +1 -1
- package/dist/core/cache/SqliteLocalCacheStore.d.ts +34 -0
- package/dist/core/cache/SqliteLocalCacheStore.d.ts.map +1 -0
- package/dist/core/cache/SqliteLocalCacheStore.js +104 -0
- package/dist/core/cache/SqliteLocalCacheStore.js.map +1 -0
- package/dist/core/cache/SummaryTable.d.ts +140 -0
- package/dist/core/cache/SummaryTable.d.ts.map +1 -0
- package/dist/core/cache/SummaryTable.js +374 -0
- package/dist/core/cache/SummaryTable.js.map +1 -0
- package/dist/core/cache/createSqliteCacheStore.d.ts +27 -0
- package/dist/core/cache/createSqliteCacheStore.d.ts.map +1 -0
- package/dist/core/cache/createSqliteCacheStore.js +26 -0
- package/dist/core/cache/createSqliteCacheStore.js.map +1 -0
- package/dist/core/collation/collationKey.d.ts +41 -0
- package/dist/core/collation/collationKey.d.ts.map +1 -0
- package/dist/core/collation/collationKey.js +475 -0
- package/dist/core/collation/collationKey.js.map +1 -0
- package/dist/core/crypto/argon2id.d.ts +34 -0
- package/dist/core/crypto/argon2id.d.ts.map +1 -0
- package/dist/core/crypto/argon2id.js +461 -0
- package/dist/core/crypto/argon2id.js.map +1 -0
- package/dist/core/guestTickets.d.ts +177 -0
- package/dist/core/guestTickets.d.ts.map +1 -0
- package/dist/core/guestTickets.js +293 -0
- package/dist/core/guestTickets.js.map +1 -0
- package/dist/core/index.d.ts +12 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +53 -3
- package/dist/core/index.js.map +1 -1
- package/dist/core/indexing/ChangefeedIndex.d.ts +98 -0
- package/dist/core/indexing/ChangefeedIndex.d.ts.map +1 -0
- package/dist/core/indexing/ChangefeedIndex.js +284 -0
- package/dist/core/indexing/ChangefeedIndex.js.map +1 -0
- package/dist/core/indexing/fulltext/DocumentFullTextIndex.d.ts +26 -2
- package/dist/core/indexing/fulltext/DocumentFullTextIndex.d.ts.map +1 -1
- package/dist/core/indexing/fulltext/DocumentFullTextIndex.js +143 -3
- package/dist/core/indexing/fulltext/DocumentFullTextIndex.js.map +1 -1
- package/dist/core/indexing/fulltext/TableSearchEngine.d.ts +60 -0
- package/dist/core/indexing/fulltext/TableSearchEngine.d.ts.map +1 -0
- package/dist/core/indexing/fulltext/TableSearchEngine.js +150 -0
- package/dist/core/indexing/fulltext/TableSearchEngine.js.map +1 -0
- package/dist/core/indexing/summary/DocumentSummaryStore.d.ts +112 -1
- package/dist/core/indexing/summary/DocumentSummaryStore.d.ts.map +1 -1
- package/dist/core/indexing/summary/DocumentSummaryStore.js +435 -12
- package/dist/core/indexing/summary/DocumentSummaryStore.js.map +1 -1
- package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.d.ts.map +1 -1
- package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.js +3 -1
- package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.js.map +1 -1
- package/dist/core/indexing/summary/summarySortKey.d.ts +12 -0
- package/dist/core/indexing/summary/summarySortKey.d.ts.map +1 -0
- package/dist/core/indexing/summary/summarySortKey.js +67 -0
- package/dist/core/indexing/summary/summarySortKey.js.map +1 -0
- package/dist/core/indexing/summary/summarySql.d.ts +72 -0
- package/dist/core/indexing/summary/summarySql.d.ts.map +1 -0
- package/dist/core/indexing/summary/summarySql.js +377 -0
- package/dist/core/indexing/summary/summarySql.js.map +1 -0
- package/dist/core/indexing/summary/types.d.ts +20 -0
- package/dist/core/indexing/summary/types.d.ts.map +1 -1
- package/dist/core/indexing/summary/types.js +25 -1
- package/dist/core/indexing/summary/types.js.map +1 -1
- package/dist/core/keys/KeyBag.d.ts.map +1 -1
- package/dist/core/keys/KeyBag.js +4 -1
- package/dist/core/keys/KeyBag.js.map +1 -1
- package/dist/core/query/executeQuery.d.ts +2 -0
- package/dist/core/query/executeQuery.d.ts.map +1 -1
- package/dist/core/query/executeQuery.js +166 -18
- package/dist/core/query/executeQuery.js.map +1 -1
- package/dist/core/query/executeQueryInclude.d.ts.map +1 -1
- package/dist/core/query/executeQueryInclude.js +2 -0
- package/dist/core/query/executeQueryInclude.js.map +1 -1
- package/dist/core/query/queryCursor.d.ts +8 -0
- package/dist/core/query/queryCursor.d.ts.map +1 -0
- package/dist/core/query/queryCursor.js +66 -0
- package/dist/core/query/queryCursor.js.map +1 -0
- package/dist/core/query/topK.d.ts +13 -0
- package/dist/core/query/topK.d.ts.map +1 -0
- package/dist/core/query/topK.js +65 -0
- package/dist/core/query/topK.js.map +1 -0
- package/dist/core/query/types.d.ts +23 -1
- package/dist/core/query/types.d.ts.map +1 -1
- package/dist/core/query/types.js.map +1 -1
- package/dist/core/types.d.ts +83 -1
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js +6 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/utils/largeArrays.d.ts +18 -0
- package/dist/core/utils/largeArrays.d.ts.map +1 -0
- package/dist/core/utils/largeArrays.js +50 -0
- package/dist/core/utils/largeArrays.js.map +1 -0
- package/dist/guest/guestDeposit.d.ts +76 -0
- package/dist/guest/guestDeposit.d.ts.map +1 -0
- package/dist/guest/guestDeposit.js +272 -0
- package/dist/guest/guestDeposit.js.map +1 -0
- package/dist/guest/guestLink.d.ts +61 -0
- package/dist/guest/guestLink.d.ts.map +1 -0
- package/dist/guest/guestLink.js +149 -0
- package/dist/guest/guestLink.js.map +1 -0
- package/dist/guest/guestRead.d.ts +34 -0
- package/dist/guest/guestRead.d.ts.map +1 -0
- package/dist/guest/guestRead.js +110 -0
- package/dist/guest/guestRead.js.map +1 -0
- package/dist/guest/index.d.ts +25 -0
- package/dist/guest/index.d.ts.map +1 -0
- package/dist/guest/index.js +41 -0
- package/dist/guest/index.js.map +1 -0
- package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.d.ts.map +1 -1
- package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.js +10 -5
- package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +9 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/server/GuestTicketPinWorker.d.ts +29 -0
- package/dist/node/server/GuestTicketPinWorker.d.ts.map +1 -0
- package/dist/node/server/GuestTicketPinWorker.js +126 -0
- package/dist/node/server/GuestTicketPinWorker.js.map +1 -0
- package/dist/node/server/MindooDBServer.d.ts +0 -2
- package/dist/node/server/MindooDBServer.d.ts.map +1 -1
- package/dist/node/server/MindooDBServer.js +7 -17
- package/dist/node/server/MindooDBServer.js.map +1 -1
- package/dist/node/server/TenantManager.d.ts +5 -1
- package/dist/node/server/TenantManager.d.ts.map +1 -1
- package/dist/node/server/TenantManager.js +10 -2
- package/dist/node/server/TenantManager.js.map +1 -1
- package/dist/server/GuestTicketService.d.ts +92 -0
- package/dist/server/GuestTicketService.d.ts.map +1 -0
- package/dist/server/GuestTicketService.js +214 -0
- package/dist/server/GuestTicketService.js.map +1 -0
- package/dist/server/TenantManager.d.ts +17 -0
- package/dist/server/TenantManager.d.ts.map +1 -1
- package/dist/server/TenantManager.js +37 -1
- package/dist/server/TenantManager.js.map +1 -1
- package/dist/server/corsOrigins.d.ts +15 -0
- package/dist/server/corsOrigins.d.ts.map +1 -0
- package/dist/server/corsOrigins.js +36 -0
- package/dist/server/corsOrigins.js.map +1 -0
- package/dist/server/http/MindooDBServerCore.d.ts +8 -0
- package/dist/server/http/MindooDBServerCore.d.ts.map +1 -1
- package/dist/server/http/MindooDBServerCore.js +41 -4
- package/dist/server/http/MindooDBServerCore.js.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +4 -1
- package/dist/server/index.js.map +1 -1
- package/dist/sqlite/index.d.ts +2 -0
- package/dist/sqlite/index.d.ts.map +1 -1
- package/dist/sqlite/index.js +11 -1
- package/dist/sqlite/index.js.map +1 -1
- package/package.json +9 -1
|
@@ -43,6 +43,7 @@ const recipients_1 = require("./userkeys/recipients");
|
|
|
43
43
|
const sealedTypes_1 = require("./userkeys/sealedTypes");
|
|
44
44
|
const depositKeys_1 = require("./userkeys/depositKeys");
|
|
45
45
|
const fingerprint_1 = require("./userkeys/fingerprint");
|
|
46
|
+
const LocalCacheStore_1 = require("./cache/LocalCacheStore");
|
|
46
47
|
const DocumentSummaryStore_1 = require("./indexing/summary/DocumentSummaryStore");
|
|
47
48
|
const types_6 = require("./indexing/summary/types");
|
|
48
49
|
const DocumentFullTextIndex_1 = require("./indexing/fulltext/DocumentFullTextIndex");
|
|
@@ -51,7 +52,10 @@ const types_8 = require("./extraction/types");
|
|
|
51
52
|
const executeQuery_1 = require("./query/executeQuery");
|
|
52
53
|
const queryView_1 = require("./query/queryView");
|
|
53
54
|
const queryLive_1 = require("./query/queryLive");
|
|
55
|
+
const largeArrays_1 = require("./utils/largeArrays");
|
|
54
56
|
const BackgroundTaskTracker_1 = require("./BackgroundTaskTracker");
|
|
57
|
+
const ChangefeedIndex_1 = require("./indexing/ChangefeedIndex");
|
|
58
|
+
const DocStateTable_1 = require("./cache/DocStateTable");
|
|
55
59
|
/**
|
|
56
60
|
* Default chunk size for attachments: 256KB
|
|
57
61
|
*/
|
|
@@ -190,6 +194,8 @@ const DOC_DELTA_CACHE_TYPE = "docdelta";
|
|
|
190
194
|
*/
|
|
191
195
|
const L2_DELTA_MIN_BASE_BYTES = 256 * 1024;
|
|
192
196
|
const L2_DELTA_MAX_COUNT = 32;
|
|
197
|
+
/** Doc-state rows read per query when a database opens. */
|
|
198
|
+
const DOC_STATE_READ_PAGE = 5000;
|
|
193
199
|
const L2_DELTA_MAX_BASE_RATIO = 0.25;
|
|
194
200
|
function newL2Gen() {
|
|
195
201
|
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
@@ -324,22 +330,11 @@ class BaseMindooDB {
|
|
|
324
330
|
* lookup.
|
|
325
331
|
*/
|
|
326
332
|
this.creatorInfoCache = new Map();
|
|
327
|
-
// Internal changefeed index:
|
|
328
|
-
//
|
|
329
|
-
|
|
330
|
-
//
|
|
331
|
-
this.
|
|
332
|
-
/**
|
|
333
|
-
* Lazily-deferred repair marker for {@link indexLookup}: when set, positions
|
|
334
|
-
* stored in the map for array indices >= this value may be stale (entries
|
|
335
|
-
* shifted by an {@link updateIndex} splice). Key presence is always exact.
|
|
336
|
-
* Reads go through {@link getDocIndexPosition}, which validates a hit
|
|
337
|
-
* against {@link index} and triggers {@link flushIndexLookupPatch} only when
|
|
338
|
-
* the position actually moved. This turns the per-update O(index size)
|
|
339
|
-
* lookup rewrite into a single deferred pass — bulk syncs that append at the
|
|
340
|
-
* index tail never pay it at all.
|
|
341
|
-
*/
|
|
342
|
-
this.indexLookupStaleFrom = null;
|
|
333
|
+
// Internal changefeed index: ordered by (changeSeq, docId) for deterministic
|
|
334
|
+
// iteration, O(1) lookup by docId and O(1) amortized updates (see
|
|
335
|
+
// ChangefeedIndex). lastModified remains available for UX metadata but is
|
|
336
|
+
// not the primary cursor key.
|
|
337
|
+
this.index = new ChangefeedIndex_1.ChangefeedIndex();
|
|
343
338
|
this.nextChangeSeq = 1;
|
|
344
339
|
/**
|
|
345
340
|
* Identity of this changefeed numbering. Cursors carry it (`feedEpoch`): a
|
|
@@ -606,6 +601,17 @@ class BaseMindooDB {
|
|
|
606
601
|
*/
|
|
607
602
|
this.locallyIndexedEntryIds = new Set();
|
|
608
603
|
this.cacheMetaDirty = false;
|
|
604
|
+
/**
|
|
605
|
+
* Documents whose persisted state (index entry, L2 bookkeeping) changed
|
|
606
|
+
* since the last flush. Only used when the cache store offers a
|
|
607
|
+
* {@link DocStateTable}: the flush then writes just these rows instead of
|
|
608
|
+
* the whole checkpoint.
|
|
609
|
+
*/
|
|
610
|
+
this.docStateDirty = new Set();
|
|
611
|
+
/** The next doc-state flush rewrites every row (index rebuilt or migrated). */
|
|
612
|
+
this.docStateReplaceAll = true;
|
|
613
|
+
/** A `db-meta` checkpoint may still exist next to the doc-state rows. */
|
|
614
|
+
this.docStateLegacyMetaPresent = true;
|
|
609
615
|
/**
|
|
610
616
|
* Per-document fingerprint (`changeSeq:automergeHeads`) of the state last
|
|
611
617
|
* written to the L2 cache by {@link flushDirtyDocToCache}. Lets the periodic
|
|
@@ -709,6 +715,17 @@ class BaseMindooDB {
|
|
|
709
715
|
this.partialSeriesProbes = new Map();
|
|
710
716
|
/** Group key series last probed without success, by key id (ms), see ingestGroupKey. */
|
|
711
717
|
this.groupKeyMisses = new Map();
|
|
718
|
+
/**
|
|
719
|
+
* Build a lightweight read-only tombstone for a deleted document, emitted
|
|
720
|
+
* by {@link iterateChangesSince} instead of materializing the deleted
|
|
721
|
+
* body. Reports `isDeleted() === true`, `isAccessible() === true` and
|
|
722
|
+
* `getData() === {}` — the counterpart to {@link buildInaccessibleDoc} for
|
|
723
|
+
* genuine deletions (distinguish the two via `isAccessible()`). Consumers
|
|
724
|
+
* that need the last state of a deleted document can use
|
|
725
|
+
* {@link iterateDocumentHistory} or {@link getDocumentAtTimestamp}.
|
|
726
|
+
*/
|
|
727
|
+
/** Shared empty payload of placeholder documents (never changed). */
|
|
728
|
+
this.emptyPayload = null;
|
|
712
729
|
(0, databaseIdValidation_1.validateDatabaseId)(store.getId(), "dbId");
|
|
713
730
|
(0, databaseIdValidation_1.validateDatabaseId)(attachmentStore.getId(), "dbId");
|
|
714
731
|
if (store.getId() !== attachmentStore.getId()) {
|
|
@@ -1184,8 +1201,8 @@ class BaseMindooDB {
|
|
|
1184
1201
|
cacheManager.register(this);
|
|
1185
1202
|
// A summary store created before the cache manager was attached picks
|
|
1186
1203
|
// up persistence now.
|
|
1187
|
-
this.summaryStore?.attachCache(cacheManager, `${this.getCachePrefix()}/summary
|
|
1188
|
-
this.fulltextIndex?.attachCache(cacheManager, `${this.getCachePrefix()}/fulltext
|
|
1204
|
+
this.summaryStore?.attachCache(cacheManager, `${this.getCachePrefix()}/summary`, { useTable: this.summaryTableAllowed() });
|
|
1205
|
+
this.fulltextIndex?.attachCache(cacheManager, `${this.getCachePrefix()}/fulltext`, { useTable: this.summaryTableAllowed() });
|
|
1189
1206
|
for (const index of this.filingIndexes) {
|
|
1190
1207
|
this.attachFilingIndexCache(index);
|
|
1191
1208
|
}
|
|
@@ -1274,6 +1291,14 @@ class BaseMindooDB {
|
|
|
1274
1291
|
}
|
|
1275
1292
|
this.cacheManager = null;
|
|
1276
1293
|
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Whether the summary and the full-text index may keep their rows in the
|
|
1296
|
+
* cache store's tables. Time-travel snapshots keep records: the tenant
|
|
1297
|
+
* lists and purges their caches by record type.
|
|
1298
|
+
*/
|
|
1299
|
+
summaryTableAllowed() {
|
|
1300
|
+
return !this.isTimeTravelMode();
|
|
1301
|
+
}
|
|
1277
1302
|
/**
|
|
1278
1303
|
* Get (lazily creating) the document summary buffer for this database.
|
|
1279
1304
|
*
|
|
@@ -1288,7 +1313,7 @@ class BaseMindooDB {
|
|
|
1288
1313
|
if (!this.summaryStore) {
|
|
1289
1314
|
this.summaryStore = new DocumentSummaryStore_1.DocumentSummaryStore(this, config);
|
|
1290
1315
|
if (this.cacheManager) {
|
|
1291
|
-
this.summaryStore.attachCache(this.cacheManager, `${this.getCachePrefix()}/summary
|
|
1316
|
+
this.summaryStore.attachCache(this.cacheManager, `${this.getCachePrefix()}/summary`, { useTable: this.summaryTableAllowed() });
|
|
1292
1317
|
}
|
|
1293
1318
|
}
|
|
1294
1319
|
else if (config !== undefined) {
|
|
@@ -1454,7 +1479,7 @@ class BaseMindooDB {
|
|
|
1454
1479
|
getAttachmentExtractors: () => this.attachmentTextExtractors,
|
|
1455
1480
|
});
|
|
1456
1481
|
if (this.cacheManager) {
|
|
1457
|
-
this.fulltextIndex.attachCache(this.cacheManager, `${this.getCachePrefix()}/fulltext
|
|
1482
|
+
this.fulltextIndex.attachCache(this.cacheManager, `${this.getCachePrefix()}/fulltext`, { useTable: this.summaryTableAllowed() });
|
|
1458
1483
|
}
|
|
1459
1484
|
}
|
|
1460
1485
|
else if (config !== undefined) {
|
|
@@ -1953,12 +1978,88 @@ class BaseMindooDB {
|
|
|
1953
1978
|
await this.flushDirtyDocToCache(store, prefix, docId, internal);
|
|
1954
1979
|
written++;
|
|
1955
1980
|
}
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1981
|
+
await this.advanceCursorPastLocalWrites();
|
|
1982
|
+
// Write metadata: rows of changed documents when the cache store has a
|
|
1983
|
+
// doc-state table, otherwise the whole checkpoint.
|
|
1984
|
+
const docStateTable = this.getDocStateTableFor(store);
|
|
1985
|
+
if (docStateTable) {
|
|
1986
|
+
await this.flushDocState(store, docStateTable, prefix);
|
|
1987
|
+
}
|
|
1988
|
+
else {
|
|
1989
|
+
const meta = this.exportMetadataCheckpoint();
|
|
1990
|
+
await store.put("db-meta", prefix, meta);
|
|
1991
|
+
this.docStateDirty.clear();
|
|
1992
|
+
}
|
|
1959
1993
|
written++;
|
|
1960
1994
|
return written;
|
|
1961
1995
|
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Move {@link processedEntryCursor} past entries this instance wrote and
|
|
1998
|
+
* indexed itself.
|
|
1999
|
+
*
|
|
2000
|
+
* Local writes index their documents directly but leave the cursor where
|
|
2001
|
+
* the last {@link syncStoreChanges} put it, so the next sync (at the latest
|
|
2002
|
+
* on the next open) re-reads every local entry since then: after a bulk
|
|
2003
|
+
* import of a million documents, one full store scan. Here the cursor
|
|
2004
|
+
* walks forward over the entries right behind it as long as each one is a
|
|
2005
|
+
* local entry that is indexed already; the first other entry (from a pull,
|
|
2006
|
+
* another writer, or a local write that has not been indexed yet) stops
|
|
2007
|
+
* the walk and is left to the next sync.
|
|
2008
|
+
*
|
|
2009
|
+
* Runs inside the sync coalescing slot, so it never interleaves with a
|
|
2010
|
+
* sync run over the same cursor.
|
|
2011
|
+
*/
|
|
2012
|
+
async advanceCursorPastLocalWrites() {
|
|
2013
|
+
if (this.locallyIndexedEntryIds.size === 0 ||
|
|
2014
|
+
this.isTimeTravelMode() ||
|
|
2015
|
+
this.sealedIngestDepth > 0 ||
|
|
2016
|
+
this.syncStoreChangesInFlight !== null ||
|
|
2017
|
+
!this.supportsCursorScan(this.store)) {
|
|
2018
|
+
return;
|
|
2019
|
+
}
|
|
2020
|
+
const run = (async () => {
|
|
2021
|
+
let cursor = this.processedEntryCursor;
|
|
2022
|
+
let advanced = false;
|
|
2023
|
+
while (this.locallyIndexedEntryIds.size > 0) {
|
|
2024
|
+
const page = await this.store.scanEntriesSince(cursor, 1000);
|
|
2025
|
+
let blocked = false;
|
|
2026
|
+
for (const entry of page.entries) {
|
|
2027
|
+
if (!this.isIndexedLocalEntry(entry) || entry.receiptOrder === undefined) {
|
|
2028
|
+
blocked = true;
|
|
2029
|
+
break;
|
|
2030
|
+
}
|
|
2031
|
+
this.locallyIndexedEntryIds.delete(entry.id);
|
|
2032
|
+
cursor = { receiptOrder: entry.receiptOrder, id: entry.id };
|
|
2033
|
+
advanced = true;
|
|
2034
|
+
}
|
|
2035
|
+
if (blocked || !page.hasMore || page.entries.length === 0) {
|
|
2036
|
+
break;
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
if (advanced) {
|
|
2040
|
+
this.processedEntryCursor = cursor;
|
|
2041
|
+
this.cacheMetaDirty = true;
|
|
2042
|
+
}
|
|
2043
|
+
})();
|
|
2044
|
+
this.syncStoreChangesInFlight = run.finally(() => {
|
|
2045
|
+
this.syncStoreChangesInFlight = null;
|
|
2046
|
+
});
|
|
2047
|
+
await this.syncStoreChangesInFlight;
|
|
2048
|
+
}
|
|
2049
|
+
/** Whether `entry` was written by this instance and its document indexed with it. */
|
|
2050
|
+
isIndexedLocalEntry(entry) {
|
|
2051
|
+
if (!this.locallyIndexedEntryIds.has(entry.id)) {
|
|
2052
|
+
return false;
|
|
2053
|
+
}
|
|
2054
|
+
if (!this.index.has(entry.docId)) {
|
|
2055
|
+
return false;
|
|
2056
|
+
}
|
|
2057
|
+
if (!this.isDocumentReplayEntry(entry)) {
|
|
2058
|
+
return true;
|
|
2059
|
+
}
|
|
2060
|
+
const parsed = (0, idGeneration_1.parseDocEntryId)(entry.id);
|
|
2061
|
+
return parsed !== null && this.getEntryIdForAutomergeHash(entry.docId, parsed.automergeHash) === entry.id;
|
|
2062
|
+
}
|
|
1962
2063
|
/**
|
|
1963
2064
|
* Serialize and persist a single document into the L2 cache store.
|
|
1964
2065
|
*
|
|
@@ -1974,12 +2075,11 @@ class BaseMindooDB {
|
|
|
1974
2075
|
* (if any) still need to be applied to bring the persisted doc current.
|
|
1975
2076
|
*
|
|
1976
2077
|
* Both fields are derived inline (no extra index lookups beyond the
|
|
1977
|
-
* O(1)
|
|
2078
|
+
* O(1) index lookup) so this stays cheap to call from the periodic
|
|
1978
2079
|
* flush as well as from the upcoming flush-before-evict path.
|
|
1979
2080
|
*/
|
|
1980
2081
|
async flushDirtyDocToCache(store, prefix, docId, internal) {
|
|
1981
|
-
const
|
|
1982
|
-
const changeSeq = indexEntryIdx === undefined ? 0 : this.index[indexEntryIdx].changeSeq;
|
|
2082
|
+
const changeSeq = this.index.get(docId)?.changeSeq ?? 0;
|
|
1983
2083
|
const automergeHeads = automerge_adapter_1.Automerge.getHeads(internal.doc);
|
|
1984
2084
|
// Skip the Automerge.save + L2 write when the exact same state was
|
|
1985
2085
|
// already flushed (docs marked dirty by a load rather than a change).
|
|
@@ -2069,6 +2169,7 @@ class BaseMindooDB {
|
|
|
2069
2169
|
else {
|
|
2070
2170
|
this.l2DeltaCounts.delete(docId);
|
|
2071
2171
|
}
|
|
2172
|
+
this.docStateDirty.add(docId);
|
|
2072
2173
|
this.cacheMetaDirty = true;
|
|
2073
2174
|
this.cacheManager?.markDirty();
|
|
2074
2175
|
}
|
|
@@ -2092,7 +2193,7 @@ class BaseMindooDB {
|
|
|
2092
2193
|
*/
|
|
2093
2194
|
async dropUnlistedL2Deltas(store, docPrefix, baseKeys) {
|
|
2094
2195
|
try {
|
|
2095
|
-
const deltaKeys =
|
|
2196
|
+
const deltaKeys = await (0, LocalCacheStore_1.listCacheIds)(store, DOC_DELTA_CACHE_TYPE, docPrefix);
|
|
2096
2197
|
if (deltaKeys.length === 0) {
|
|
2097
2198
|
return;
|
|
2098
2199
|
}
|
|
@@ -2159,6 +2260,7 @@ class BaseMindooDB {
|
|
|
2159
2260
|
this.lastFlushedDocState.set(docId, flushKey);
|
|
2160
2261
|
if (this.l2RecordChangeSeqs.get(docId) !== changeSeq) {
|
|
2161
2262
|
this.l2RecordChangeSeqs.set(docId, changeSeq);
|
|
2263
|
+
this.docStateDirty.add(docId);
|
|
2162
2264
|
this.cacheMetaDirty = true;
|
|
2163
2265
|
this.cacheManager?.markDirty();
|
|
2164
2266
|
}
|
|
@@ -2169,24 +2271,37 @@ class BaseMindooDB {
|
|
|
2169
2271
|
this.l2Chains.delete(docId);
|
|
2170
2272
|
this.setL2DeltaCount(docId, 0);
|
|
2171
2273
|
if (this.l2RecordChangeSeqs.delete(docId)) {
|
|
2274
|
+
this.docStateDirty.add(docId);
|
|
2172
2275
|
this.cacheMetaDirty = true;
|
|
2173
2276
|
this.cacheManager?.markDirty();
|
|
2174
2277
|
}
|
|
2175
2278
|
}
|
|
2176
|
-
|
|
2279
|
+
/**
|
|
2280
|
+
* The metadata checkpoint as a JSON-ready object. With `docStateRows` the
|
|
2281
|
+
* per-document parts (index, L2 bookkeeping) are left out because they are
|
|
2282
|
+
* stored as rows of a {@link DocStateTable}, and so is the automerge-hash
|
|
2283
|
+
* lookup, which is rebuilt per document from the store on demand (see
|
|
2284
|
+
* {@link ensureAutomergeDepsResolved}).
|
|
2285
|
+
*/
|
|
2286
|
+
buildMetadataCheckpoint(docStateRows) {
|
|
2177
2287
|
const checkpoint = {
|
|
2178
2288
|
version: 2,
|
|
2179
2289
|
processedEntryCursor: this.processedEntryCursor,
|
|
2180
|
-
index: this.index,
|
|
2181
2290
|
nextChangeSeq: this.nextChangeSeq,
|
|
2182
2291
|
changeFeedEpoch: this.changeFeedEpoch,
|
|
2183
2292
|
};
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2293
|
+
if (docStateRows) {
|
|
2294
|
+
checkpoint.docStateRows = true;
|
|
2295
|
+
}
|
|
2296
|
+
else {
|
|
2297
|
+
checkpoint.index = this.index.toArray();
|
|
2298
|
+
// Serialize automergeHashToEntryId: Map<string, Map<string,string>> -> nested object
|
|
2299
|
+
const hashMap = {};
|
|
2300
|
+
for (const [docId, inner] of this.automergeHashToEntryId) {
|
|
2301
|
+
hashMap[docId] = Object.fromEntries(inner);
|
|
2302
|
+
}
|
|
2303
|
+
checkpoint.automergeHashToEntryId = hashMap;
|
|
2188
2304
|
}
|
|
2189
|
-
checkpoint.automergeHashToEntryId = hashMap;
|
|
2190
2305
|
// Persisted sync scan cursors (sync-v5, phase 1). Additive field: older
|
|
2191
2306
|
// readers ignore it, older checkpoints simply restore an empty map.
|
|
2192
2307
|
if (this.syncScanCursors.size > 0) {
|
|
@@ -2203,7 +2318,7 @@ class BaseMindooDB {
|
|
|
2203
2318
|
}
|
|
2204
2319
|
// Additive field: older checkpoints restore an empty map, which makes
|
|
2205
2320
|
// the warmer read each record header once (the previous behavior).
|
|
2206
|
-
if (this.l2RecordChangeSeqs.size > 0) {
|
|
2321
|
+
if (!docStateRows && this.l2RecordChangeSeqs.size > 0) {
|
|
2207
2322
|
checkpoint.l2RecordChangeSeqs = Object.fromEntries(this.l2RecordChangeSeqs);
|
|
2208
2323
|
}
|
|
2209
2324
|
// The map above is complete only when it was complete on restore.
|
|
@@ -2211,7 +2326,7 @@ class BaseMindooDB {
|
|
|
2211
2326
|
checkpoint.l2Tracked = true;
|
|
2212
2327
|
}
|
|
2213
2328
|
// Additive field: older readers ignore it and read v3 records not at all.
|
|
2214
|
-
if (this.l2DeltaCounts.size > 0) {
|
|
2329
|
+
if (!docStateRows && this.l2DeltaCounts.size > 0) {
|
|
2215
2330
|
checkpoint.l2DeltaCounts = Object.fromEntries(this.l2DeltaCounts);
|
|
2216
2331
|
}
|
|
2217
2332
|
// Persist the KeyBag fingerprint observed at the last reconciliation
|
|
@@ -2246,7 +2361,114 @@ class BaseMindooDB {
|
|
|
2246
2361
|
if (this.quarantineLog.size > 0) {
|
|
2247
2362
|
checkpoint.quarantineLog = Object.fromEntries(this.quarantineLog);
|
|
2248
2363
|
}
|
|
2249
|
-
return
|
|
2364
|
+
return checkpoint;
|
|
2365
|
+
}
|
|
2366
|
+
exportMetadataCheckpoint() {
|
|
2367
|
+
return new TextEncoder().encode(JSON.stringify(this.buildMetadataCheckpoint(false)));
|
|
2368
|
+
}
|
|
2369
|
+
/** The doc-state row of `docId`, or `null` when it has no index entry. */
|
|
2370
|
+
buildDocStateRow(docId) {
|
|
2371
|
+
const entry = this.index.get(docId);
|
|
2372
|
+
if (!entry) {
|
|
2373
|
+
return null;
|
|
2374
|
+
}
|
|
2375
|
+
return {
|
|
2376
|
+
docId,
|
|
2377
|
+
changeSeq: entry.changeSeq,
|
|
2378
|
+
lastModified: entry.lastModified,
|
|
2379
|
+
isDeleted: entry.isDeleted,
|
|
2380
|
+
decryptionKeyId: entry.decryptionKeyId,
|
|
2381
|
+
accessState: entry.accessState,
|
|
2382
|
+
awaitingWitness: entry.awaitingWitness,
|
|
2383
|
+
witnessed: entry.witnessed,
|
|
2384
|
+
l2ChangeSeq: this.l2RecordChangeSeqs.get(docId) ?? null,
|
|
2385
|
+
l2DeltaCount: this.l2DeltaCounts.get(docId) ?? 0,
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
/**
|
|
2389
|
+
* Persist the metadata through a {@link DocStateTable}: the small rest of
|
|
2390
|
+
* the checkpoint plus the rows of documents that changed since the last
|
|
2391
|
+
* flush, in one transaction. O(changes) instead of O(documents).
|
|
2392
|
+
*/
|
|
2393
|
+
async flushDocState(store, table, prefix) {
|
|
2394
|
+
const replaceAll = this.docStateReplaceAll;
|
|
2395
|
+
const dirty = this.docStateDirty;
|
|
2396
|
+
this.docStateDirty = new Set();
|
|
2397
|
+
this.docStateReplaceAll = false;
|
|
2398
|
+
const upserts = [];
|
|
2399
|
+
const deletes = [];
|
|
2400
|
+
try {
|
|
2401
|
+
if (replaceAll) {
|
|
2402
|
+
for (const entry of this.index.values()) {
|
|
2403
|
+
upserts.push(this.buildDocStateRow(entry.docId));
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
else {
|
|
2407
|
+
for (const docId of dirty) {
|
|
2408
|
+
const row = this.buildDocStateRow(docId);
|
|
2409
|
+
if (row) {
|
|
2410
|
+
upserts.push(row);
|
|
2411
|
+
}
|
|
2412
|
+
else {
|
|
2413
|
+
deletes.push(docId);
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
// Every so often all rows also go into one packed snapshot: an open
|
|
2418
|
+
// reads it instead of a row per document (see readSnapshot).
|
|
2419
|
+
let snapshot;
|
|
2420
|
+
if (table.wantsSnapshot?.(prefix, this.index.size)) {
|
|
2421
|
+
snapshot = replaceAll ? upserts : [];
|
|
2422
|
+
if (!replaceAll) {
|
|
2423
|
+
for (const entry of this.index.values()) {
|
|
2424
|
+
snapshot.push(this.buildDocStateRow(entry.docId));
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
const metaJson = JSON.stringify(this.buildMetadataCheckpoint(true));
|
|
2429
|
+
await table.write(prefix, { metaJson, upserts, deletes, replaceAll, ...(snapshot ? { snapshot } : {}) });
|
|
2430
|
+
}
|
|
2431
|
+
catch (error) {
|
|
2432
|
+
// Written again by the next flush.
|
|
2433
|
+
for (const docId of dirty) {
|
|
2434
|
+
this.docStateDirty.add(docId);
|
|
2435
|
+
}
|
|
2436
|
+
this.docStateReplaceAll = this.docStateReplaceAll || replaceAll;
|
|
2437
|
+
throw error;
|
|
2438
|
+
}
|
|
2439
|
+
if (this.docStateLegacyMetaPresent) {
|
|
2440
|
+
// A checkpoint left from the "checkpoint" backend would be restored
|
|
2441
|
+
// instead of the rows (it counts as newer, see restoreFromCache).
|
|
2442
|
+
await store.delete("db-meta", prefix);
|
|
2443
|
+
this.docStateLegacyMetaPresent = false;
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
/**
|
|
2447
|
+
* The doc-state table for this database's metadata, or `null` for the
|
|
2448
|
+
* `db-meta` checkpoint. Stores without cursor scan keep the checkpoint:
|
|
2449
|
+
* their processed-entry list is part of it.
|
|
2450
|
+
*/
|
|
2451
|
+
getDocStateTableFor(store) {
|
|
2452
|
+
// Time-travel snapshots keep the checkpoint too: the tenant lists and
|
|
2453
|
+
// purges their caches by record type.
|
|
2454
|
+
if (!this.supportsCursorScan(this.store) || this.isTimeTravelMode()) {
|
|
2455
|
+
return null;
|
|
2456
|
+
}
|
|
2457
|
+
return (0, DocStateTable_1.getDocStateTable)(store);
|
|
2458
|
+
}
|
|
2459
|
+
/** Read every doc-state row of this database, in changefeed order. */
|
|
2460
|
+
async readAllDocStateRows(table, prefix) {
|
|
2461
|
+
const rows = [];
|
|
2462
|
+
let after = null;
|
|
2463
|
+
for (;;) {
|
|
2464
|
+
const page = await table.readRows(prefix, after, DOC_STATE_READ_PAGE);
|
|
2465
|
+
(0, largeArrays_1.pushAll)(rows, page);
|
|
2466
|
+
if (page.length < DOC_STATE_READ_PAGE) {
|
|
2467
|
+
return rows;
|
|
2468
|
+
}
|
|
2469
|
+
const last = page[page.length - 1];
|
|
2470
|
+
after = { changeSeq: last.changeSeq, docId: last.docId };
|
|
2471
|
+
}
|
|
2250
2472
|
}
|
|
2251
2473
|
/**
|
|
2252
2474
|
* Attempt to restore state from cache. Returns true on success.
|
|
@@ -2254,20 +2476,52 @@ class BaseMindooDB {
|
|
|
2254
2476
|
async restoreFromCache(store) {
|
|
2255
2477
|
const prefix = this.getCachePrefix();
|
|
2256
2478
|
try {
|
|
2257
|
-
// 1. Load metadata checkpoint
|
|
2479
|
+
// 1. Load metadata checkpoint. With a doc-state table, a `db-meta`
|
|
2480
|
+
// checkpoint is newer than the rows (the first row flush deletes it):
|
|
2481
|
+
// restore it and write all rows on the next flush.
|
|
2482
|
+
const docStateTable = this.getDocStateTableFor(store);
|
|
2258
2483
|
const metaBytes = await store.get("db-meta", prefix);
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2484
|
+
let checkpoint;
|
|
2485
|
+
let docStateRows = null;
|
|
2486
|
+
if (metaBytes) {
|
|
2487
|
+
checkpoint = JSON.parse(new TextDecoder().decode(metaBytes));
|
|
2488
|
+
this.docStateReplaceAll = true;
|
|
2489
|
+
this.docStateLegacyMetaPresent = true;
|
|
2262
2490
|
}
|
|
2263
|
-
|
|
2491
|
+
else {
|
|
2492
|
+
const metaJson = docStateTable
|
|
2493
|
+
? await docStateTable.readMeta(prefix)
|
|
2494
|
+
: null;
|
|
2495
|
+
if (!metaJson) {
|
|
2496
|
+
this.logger.debug("No cache metadata found, will do full rebuild");
|
|
2497
|
+
return false;
|
|
2498
|
+
}
|
|
2499
|
+
checkpoint = JSON.parse(metaJson);
|
|
2500
|
+
docStateRows =
|
|
2501
|
+
(await docStateTable.readSnapshot?.(prefix)) ??
|
|
2502
|
+
(await this.readAllDocStateRows(docStateTable, prefix));
|
|
2503
|
+
this.docStateReplaceAll = false;
|
|
2504
|
+
this.docStateLegacyMetaPresent = false;
|
|
2505
|
+
}
|
|
2506
|
+
this.docStateDirty.clear();
|
|
2264
2507
|
if (checkpoint.version !== 2) {
|
|
2265
2508
|
this.logger.warn(`Unknown cache version ${checkpoint.version}, ignoring cache`);
|
|
2266
2509
|
return false;
|
|
2267
2510
|
}
|
|
2268
2511
|
// 2. Restore metadata
|
|
2269
2512
|
this.processedEntryCursor = checkpoint.processedEntryCursor ?? null;
|
|
2270
|
-
|
|
2513
|
+
const restoredIndex = docStateRows
|
|
2514
|
+
? docStateRows.map((row) => ({
|
|
2515
|
+
docId: row.docId,
|
|
2516
|
+
changeSeq: row.changeSeq,
|
|
2517
|
+
lastModified: row.lastModified,
|
|
2518
|
+
isDeleted: row.isDeleted,
|
|
2519
|
+
decryptionKeyId: row.decryptionKeyId,
|
|
2520
|
+
accessState: row.accessState,
|
|
2521
|
+
awaitingWitness: row.awaitingWitness,
|
|
2522
|
+
witnessed: row.witnessed,
|
|
2523
|
+
}))
|
|
2524
|
+
: (checkpoint.index ?? []);
|
|
2271
2525
|
this.nextChangeSeq = checkpoint.nextChangeSeq ?? 1;
|
|
2272
2526
|
if (checkpoint.processedEntryIds) {
|
|
2273
2527
|
this.processedEntryIds = checkpoint.processedEntryIds;
|
|
@@ -2287,6 +2541,16 @@ class BaseMindooDB {
|
|
|
2287
2541
|
}
|
|
2288
2542
|
this.l2DeltaCounts.clear();
|
|
2289
2543
|
this.l2Chains.clear();
|
|
2544
|
+
if (docStateRows) {
|
|
2545
|
+
for (const row of docStateRows) {
|
|
2546
|
+
if (row.l2ChangeSeq !== null) {
|
|
2547
|
+
this.l2RecordChangeSeqs.set(row.docId, row.l2ChangeSeq);
|
|
2548
|
+
}
|
|
2549
|
+
if (row.l2DeltaCount > 0) {
|
|
2550
|
+
this.l2DeltaCounts.set(row.docId, Math.min(row.l2DeltaCount, L2_DELTA_MAX_COUNT));
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2290
2554
|
if (checkpoint.l2DeltaCounts && typeof checkpoint.l2DeltaCounts === "object") {
|
|
2291
2555
|
for (const [docId, count] of Object.entries(checkpoint.l2DeltaCounts)) {
|
|
2292
2556
|
if (typeof count === "number" && Number.isInteger(count) && count > 0) {
|
|
@@ -2377,32 +2641,31 @@ class BaseMindooDB {
|
|
|
2377
2641
|
}
|
|
2378
2642
|
}
|
|
2379
2643
|
}
|
|
2380
|
-
//
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
this.index[i].changeSeq = i + 1;
|
|
2644
|
+
// Normalize entries of older checkpoints, then load the index.
|
|
2645
|
+
for (let i = 0; i < restoredIndex.length; i++) {
|
|
2646
|
+
const entry = restoredIndex[i];
|
|
2647
|
+
if (typeof entry.changeSeq !== "number") {
|
|
2648
|
+
entry.changeSeq = i + 1;
|
|
2386
2649
|
}
|
|
2387
|
-
if (!
|
|
2388
|
-
|
|
2650
|
+
if (!entry.decryptionKeyId) {
|
|
2651
|
+
entry.decryptionKeyId = "default";
|
|
2389
2652
|
}
|
|
2390
|
-
if (!
|
|
2391
|
-
|
|
2653
|
+
if (!entry.accessState) {
|
|
2654
|
+
entry.accessState = "visible";
|
|
2392
2655
|
}
|
|
2393
|
-
if (typeof
|
|
2656
|
+
if (typeof entry.awaitingWitness !== "boolean") {
|
|
2394
2657
|
// Caches written before the witness-aware flag: treat as not awaiting.
|
|
2395
|
-
|
|
2658
|
+
entry.awaitingWitness = false;
|
|
2396
2659
|
}
|
|
2397
|
-
if (typeof
|
|
2660
|
+
if (typeof entry.witnessed !== "boolean") {
|
|
2398
2661
|
// Caches written before the witness-aware flag: treat as not witnessed.
|
|
2399
|
-
|
|
2662
|
+
entry.witnessed = false;
|
|
2400
2663
|
}
|
|
2401
|
-
this.indexLookup.set(this.index[i].docId, i);
|
|
2402
2664
|
}
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2665
|
+
this.index.load(restoredIndex);
|
|
2666
|
+
// New changes must sort after every restored entry.
|
|
2667
|
+
if (this.nextChangeSeq <= this.index.maxSlotSeq) {
|
|
2668
|
+
this.nextChangeSeq = this.index.maxSlotSeq + 1;
|
|
2406
2669
|
}
|
|
2407
2670
|
// A checkpoint without an epoch predates epochs: its cursors (held by
|
|
2408
2671
|
// views, summaries, filing indexes) cannot be trusted, give it a new one.
|
|
@@ -2425,9 +2688,10 @@ class BaseMindooDB {
|
|
|
2425
2688
|
}
|
|
2426
2689
|
}
|
|
2427
2690
|
// 3. Load cached documents
|
|
2428
|
-
|
|
2691
|
+
// Only this database's records (stores with sorted keys list them
|
|
2692
|
+
// without reading the ids of every other database).
|
|
2429
2693
|
const docPrefix = `${prefix}/`;
|
|
2430
|
-
const allOwnedKeys =
|
|
2694
|
+
const allOwnedKeys = await (0, LocalCacheStore_1.listCacheIds)(store, "doc", docPrefix);
|
|
2431
2695
|
// The persisted per-doc L2 state must not outlive its record (a
|
|
2432
2696
|
// record lost outside this instance would otherwise be skipped by the
|
|
2433
2697
|
// warmer forever).
|
|
@@ -2695,6 +2959,25 @@ class BaseMindooDB {
|
|
|
2695
2959
|
verifyEntrySignatureForDb(entry, encryptedData) {
|
|
2696
2960
|
return this.tenant.verifyEntrySignature(entry, encryptedData, { dbId: this.store.getId() });
|
|
2697
2961
|
}
|
|
2962
|
+
/**
|
|
2963
|
+
* The verify key for an entry a guest ticket wrote (docs/accesscontrol.md
|
|
2964
|
+
* §6.14), or null when it is not one: a ticket key is no grant key, so it is
|
|
2965
|
+
* trusted only for the ticket's deliveries in its database.
|
|
2966
|
+
*/
|
|
2967
|
+
async guestTicketVerifyKey(entry) {
|
|
2968
|
+
try {
|
|
2969
|
+
const directory = (await this.tenant.openDirectory());
|
|
2970
|
+
if (typeof directory.isGuestTicketEntry !== "function")
|
|
2971
|
+
return null;
|
|
2972
|
+
if (!(await directory.isGuestTicketEntry(entry, this.store.getId())))
|
|
2973
|
+
return null;
|
|
2974
|
+
const subtle = this.tenant.getCryptoAdapter().getSubtle();
|
|
2975
|
+
return await subtle.importKey("spki", this.tenant.pemToArrayBuffer(entry.createdByPublicKey), { name: "Ed25519" }, false, ["verify"]);
|
|
2976
|
+
}
|
|
2977
|
+
catch {
|
|
2978
|
+
return null;
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2698
2981
|
async getOrImportPublicKey(publicKey, trustedTime) {
|
|
2699
2982
|
const directory = await this.tenant.openDirectory();
|
|
2700
2983
|
let isTrusted = false;
|
|
@@ -2846,24 +3129,11 @@ class BaseMindooDB {
|
|
|
2846
3129
|
return false;
|
|
2847
3130
|
}
|
|
2848
3131
|
}
|
|
2849
|
-
/**
|
|
2850
|
-
* Compare two index entries for sorting.
|
|
2851
|
-
* Returns negative if a < b, positive if a > b, 0 if equal.
|
|
2852
|
-
* Sorts by deterministic changeSeq first, then by docId for uniqueness.
|
|
2853
|
-
*/
|
|
2854
|
-
compareIndexEntries(a, b) {
|
|
2855
|
-
if (a.changeSeq !== b.changeSeq) {
|
|
2856
|
-
return a.changeSeq - b.changeSeq;
|
|
2857
|
-
}
|
|
2858
|
-
return a.docId.localeCompare(b.docId);
|
|
2859
|
-
}
|
|
2860
3132
|
/**
|
|
2861
3133
|
* Update the index entry for a document.
|
|
2862
3134
|
*
|
|
2863
|
-
* When a document changes, it gets a new monotonic sequence and
|
|
2864
|
-
*
|
|
2865
|
-
* The lookup map is only patched for the range of entries that actually
|
|
2866
|
-
* shifted.
|
|
3135
|
+
* When a document changes, it gets a new monotonic sequence and moves to
|
|
3136
|
+
* the end of the `(changeSeq, docId)` order (O(1), see ChangefeedIndex).
|
|
2867
3137
|
*
|
|
2868
3138
|
* Idempotent: if every tracked field (`lastModified`, `isDeleted`,
|
|
2869
3139
|
* `decryptionKeyId`, `accessState`) matches the existing entry the
|
|
@@ -2915,10 +3185,9 @@ class BaseMindooDB {
|
|
|
2915
3185
|
awaitingWitness,
|
|
2916
3186
|
witnessed,
|
|
2917
3187
|
};
|
|
2918
|
-
const
|
|
3188
|
+
const existingEntry = this.index.get(docId);
|
|
2919
3189
|
// Check if the entry already exists and hasn't changed position
|
|
2920
|
-
if (
|
|
2921
|
-
const existingEntry = this.index[existingIndex];
|
|
3190
|
+
if (existingEntry !== undefined) {
|
|
2922
3191
|
// If only metadata flags stayed identical and caller replays same state, skip.
|
|
2923
3192
|
// `awaitingWitness` is part of this identity so a witness receipt (which
|
|
2924
3193
|
// changes only `receivedAt`, not Automerge content) still bumps changeSeq
|
|
@@ -2935,83 +3204,22 @@ class BaseMindooDB {
|
|
|
2935
3204
|
existingEntry.witnessed === witnessed) {
|
|
2936
3205
|
return; // No change needed
|
|
2937
3206
|
}
|
|
2938
|
-
// Remove from current position; positions after it are repaired lazily
|
|
2939
|
-
// via indexLookupStaleFrom below.
|
|
2940
|
-
this.index.splice(existingIndex, 1);
|
|
2941
|
-
this.indexLookup.delete(docId);
|
|
2942
|
-
}
|
|
2943
|
-
// Find insertion point using binary search to maintain sorted order
|
|
2944
|
-
let insertIndex = this.index.length; // Default to end
|
|
2945
|
-
// Binary search for insertion point
|
|
2946
|
-
let left = 0;
|
|
2947
|
-
let right = this.index.length - 1;
|
|
2948
|
-
while (left <= right) {
|
|
2949
|
-
const mid = Math.floor((left + right) / 2);
|
|
2950
|
-
const cmp = this.compareIndexEntries(newEntry, this.index[mid]);
|
|
2951
|
-
if (cmp < 0) {
|
|
2952
|
-
right = mid - 1;
|
|
2953
|
-
insertIndex = mid;
|
|
2954
|
-
}
|
|
2955
|
-
else {
|
|
2956
|
-
left = mid + 1;
|
|
2957
|
-
insertIndex = mid + 1;
|
|
2958
|
-
}
|
|
2959
3207
|
}
|
|
2960
|
-
//
|
|
2961
|
-
|
|
3208
|
+
// The new entry has the highest changeSeq, so it goes to the end of the
|
|
3209
|
+
// changefeed; the index supersedes the old position in O(1).
|
|
3210
|
+
this.index.set(newEntry);
|
|
2962
3211
|
this.nextChangeSeq = assignedSeq + 1;
|
|
2963
|
-
this.
|
|
2964
|
-
// Entries at/after the first splice point may have shifted. Instead of
|
|
2965
|
-
// rewriting the lookup map here (O(index size) per update — twice, in the
|
|
2966
|
-
// old implementation), record the dirty range and let readers repair it
|
|
2967
|
-
// lazily. A fresh insert at the tail (the common bulk-sync case) shifts
|
|
2968
|
-
// nothing and stays clean.
|
|
2969
|
-
const shiftedFrom = existingIndex !== undefined
|
|
2970
|
-
? Math.min(existingIndex, insertIndex)
|
|
2971
|
-
: insertIndex;
|
|
2972
|
-
if (shiftedFrom < this.index.length - 1) {
|
|
2973
|
-
this.indexLookupStaleFrom =
|
|
2974
|
-
this.indexLookupStaleFrom === null
|
|
2975
|
-
? shiftedFrom
|
|
2976
|
-
: Math.min(this.indexLookupStaleFrom, shiftedFrom);
|
|
2977
|
-
}
|
|
3212
|
+
this.docStateDirty.add(docId);
|
|
2978
3213
|
// Reactive support: record the transition for coalesced change events.
|
|
2979
3214
|
// Reached only when the index actually changed (identical replays
|
|
2980
3215
|
// returned early above).
|
|
2981
3216
|
this.noteChangeForListeners(docId, lastModified, isDeleted);
|
|
2982
3217
|
this.performanceCallback?.onIndexUpdate?.({
|
|
2983
3218
|
docId,
|
|
2984
|
-
operation:
|
|
3219
|
+
operation: existingEntry === undefined ? "insert" : "update",
|
|
2985
3220
|
time: Date.now() - startedAt,
|
|
2986
3221
|
});
|
|
2987
3222
|
}
|
|
2988
|
-
/**
|
|
2989
|
-
* Resolve a document's position in the sorted {@link index} through the
|
|
2990
|
-
* lookup map, repairing lazily-deferred staleness (see
|
|
2991
|
-
* {@link indexLookupStaleFrom}) only when the cached position no longer
|
|
2992
|
-
* matches. All `indexLookup.get` reads must go through this accessor.
|
|
2993
|
-
*/
|
|
2994
|
-
getDocIndexPosition(docId) {
|
|
2995
|
-
const pos = this.indexLookup.get(docId);
|
|
2996
|
-
if (pos === undefined) {
|
|
2997
|
-
return undefined;
|
|
2998
|
-
}
|
|
2999
|
-
if (this.index[pos]?.docId === docId) {
|
|
3000
|
-
return pos;
|
|
3001
|
-
}
|
|
3002
|
-
this.flushIndexLookupPatch();
|
|
3003
|
-
return this.indexLookup.get(docId);
|
|
3004
|
-
}
|
|
3005
|
-
/** Rewrite the stale tail of {@link indexLookup} recorded by {@link updateIndex}. */
|
|
3006
|
-
flushIndexLookupPatch() {
|
|
3007
|
-
if (this.indexLookupStaleFrom === null) {
|
|
3008
|
-
return;
|
|
3009
|
-
}
|
|
3010
|
-
for (let i = this.indexLookupStaleFrom; i < this.index.length; i++) {
|
|
3011
|
-
this.indexLookup.set(this.index[i].docId, i);
|
|
3012
|
-
}
|
|
3013
|
-
this.indexLookupStaleFrom = null;
|
|
3014
|
-
}
|
|
3015
3223
|
/**
|
|
3016
3224
|
* Write entries created by this instance to the docs store. The callers
|
|
3017
3225
|
* index the affected documents right away (see
|
|
@@ -3111,7 +3319,14 @@ class BaseMindooDB {
|
|
|
3111
3319
|
if (resolvedEntryIds.length === automergeHashes.length) {
|
|
3112
3320
|
return resolvedEntryIds;
|
|
3113
3321
|
}
|
|
3114
|
-
this.
|
|
3322
|
+
if (this.automergeHashToEntryId.has(docId)) {
|
|
3323
|
+
this.logger.warn(`Falling back to metadata scan for unresolved automerge dependency hashes in doc ${docId}`);
|
|
3324
|
+
}
|
|
3325
|
+
else {
|
|
3326
|
+
// Expected once per document after an open from doc-state rows, which
|
|
3327
|
+
// do not persist this lookup.
|
|
3328
|
+
this.logger.debug(`Loading automerge hash lookup of doc ${docId} from the store`);
|
|
3329
|
+
}
|
|
3115
3330
|
await this.hydrateAutomergeHashMappingsFromStore(docId);
|
|
3116
3331
|
const recoveredEntryIds = this.resolveAutomergeDepsToEntryIds(docId, automergeHashes);
|
|
3117
3332
|
if (recoveredEntryIds.length === automergeHashes.length) {
|
|
@@ -3367,8 +3582,7 @@ class BaseMindooDB {
|
|
|
3367
3582
|
origin = entry;
|
|
3368
3583
|
}
|
|
3369
3584
|
}
|
|
3370
|
-
const
|
|
3371
|
-
const indexEntry = indexPos === undefined ? undefined : this.index[indexPos];
|
|
3585
|
+
const indexEntry = this.index.get(docId);
|
|
3372
3586
|
results.push({
|
|
3373
3587
|
docId,
|
|
3374
3588
|
createdAt: origin?.createdAt ?? indexEntry?.lastModified ?? 0,
|
|
@@ -3576,12 +3790,11 @@ class BaseMindooDB {
|
|
|
3576
3790
|
*/
|
|
3577
3791
|
async forgetPurgedDocument(docId) {
|
|
3578
3792
|
await this.purgeMaterializedDocument(docId);
|
|
3579
|
-
const
|
|
3793
|
+
const existing = this.index.get(docId);
|
|
3580
3794
|
// Already a tombstone (soft-deleted earlier, or purged before): views have
|
|
3581
3795
|
// removed it, and bumping it again on every repeated purge would only
|
|
3582
3796
|
// churn the changefeed.
|
|
3583
|
-
if (
|
|
3584
|
-
const existing = this.index[position];
|
|
3797
|
+
if (existing !== undefined && !existing.isDeleted) {
|
|
3585
3798
|
this.updateIndex(docId, Math.max(existing.lastModified, (0, timeSource_1.semanticNow)()), true, existing.decryptionKeyId, existing.accessState, false, false, true);
|
|
3586
3799
|
}
|
|
3587
3800
|
this.cacheMetaDirty = true;
|
|
@@ -3614,8 +3827,8 @@ class BaseMindooDB {
|
|
|
3614
3827
|
* After running, if any transition occurred we mark the cache metadata
|
|
3615
3828
|
* dirty so the new visibility state survives a process restart.
|
|
3616
3829
|
*/
|
|
3617
|
-
async reconcileKeyVisibility() {
|
|
3618
|
-
await this.reconcileKeyVisibilityOf();
|
|
3830
|
+
async reconcileKeyVisibility(keyIds) {
|
|
3831
|
+
await this.reconcileKeyVisibilityOf(keyIds);
|
|
3619
3832
|
}
|
|
3620
3833
|
/**
|
|
3621
3834
|
* {@link reconcileKeyVisibility}, limited to the documents encrypted with one
|
|
@@ -3654,8 +3867,7 @@ class BaseMindooDB {
|
|
|
3654
3867
|
if (keyIds && !keyIds.has(visibility.decryptionKeyId)) {
|
|
3655
3868
|
continue;
|
|
3656
3869
|
}
|
|
3657
|
-
const
|
|
3658
|
-
const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
|
|
3870
|
+
const existing = this.index.get(docId);
|
|
3659
3871
|
await this.ingestSealed(visibility.decryptionKeyId, metadataByDoc.get(docId));
|
|
3660
3872
|
const canRead = await this.canReadWithKey(visibility.decryptionKeyId, docId, metadataByDoc.get(docId));
|
|
3661
3873
|
if (canRead) {
|
|
@@ -3898,16 +4110,16 @@ class BaseMindooDB {
|
|
|
3898
4110
|
entry.entryType === "doc_undelete" ||
|
|
3899
4111
|
entry.entryType === "doc_snapshot")
|
|
3900
4112
|
.map((entry) => entry.docId))).sort((left, right) => left.localeCompare(right));
|
|
3901
|
-
const missingDocIds = lifecycleDocIds.filter((docId) => !this.
|
|
4113
|
+
const missingDocIds = lifecycleDocIds.filter((docId) => !this.index.has(docId));
|
|
3902
4114
|
if (missingDocIds.length === 0) {
|
|
3903
4115
|
return;
|
|
3904
4116
|
}
|
|
3905
4117
|
this.logger.warn(`Detected stale cache checkpoint for ${this.store.getId()} - ` +
|
|
3906
4118
|
`index is missing ${missingDocIds.length} document(s): ${missingDocIds.join(", ")}. ` +
|
|
3907
4119
|
`Rebuilding metadata from local store.`);
|
|
3908
|
-
this.index
|
|
3909
|
-
this.
|
|
3910
|
-
this.
|
|
4120
|
+
this.index.clear();
|
|
4121
|
+
this.docStateDirty.clear();
|
|
4122
|
+
this.docStateReplaceAll = true;
|
|
3911
4123
|
this.docCache.clear();
|
|
3912
4124
|
this.lastFlushedDocState.clear();
|
|
3913
4125
|
this.l2RecordChangeSeqs.clear();
|
|
@@ -3925,7 +4137,7 @@ class BaseMindooDB {
|
|
|
3925
4137
|
this.cacheManager?.markDirty();
|
|
3926
4138
|
await this.syncStoreChanges();
|
|
3927
4139
|
this.logger.info(`Metadata rebuild complete for ${this.store.getId()} - ` +
|
|
3928
|
-
`index now has ${this.index.
|
|
4140
|
+
`index now has ${this.index.size} document(s).`);
|
|
3929
4141
|
}
|
|
3930
4142
|
/**
|
|
3931
4143
|
* Sync changes from the content-addressed store by finding new entries and processing them.
|
|
@@ -4113,10 +4325,7 @@ class BaseMindooDB {
|
|
|
4113
4325
|
// most of the tenant: the doc is skipped before it ever reaches
|
|
4114
4326
|
// the index, so record it for `getInaccessibleDocumentCount`.
|
|
4115
4327
|
this.noteInaccessibleDocument(docId);
|
|
4116
|
-
const
|
|
4117
|
-
const existing = existingIndex === undefined
|
|
4118
|
-
? undefined
|
|
4119
|
-
: this.index[existingIndex];
|
|
4328
|
+
const existing = this.index.get(docId);
|
|
4120
4329
|
if (existing?.accessState === "visible") {
|
|
4121
4330
|
await this.purgeMaterializedDocument(docId);
|
|
4122
4331
|
this.updateIndex(docId, existing.lastModified, true, representativeEntry.decryptionKeyId, "inaccessible");
|
|
@@ -4190,8 +4399,7 @@ class BaseMindooDB {
|
|
|
4190
4399
|
// existing index entry (if any). We do NOT need a second pass
|
|
4191
4400
|
// over the underlying store - the key is missing, so we just
|
|
4192
4401
|
// record an inaccessibility tombstone.
|
|
4193
|
-
const
|
|
4194
|
-
const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
|
|
4402
|
+
const existing = this.index.get(docId);
|
|
4195
4403
|
if (existing?.accessState === "visible") {
|
|
4196
4404
|
const lifecycleEntriesInBatch = entryMetadataList.filter((entry) => entry.entryType === "doc_create" ||
|
|
4197
4405
|
entry.entryType === "doc_change" ||
|
|
@@ -4206,7 +4414,7 @@ class BaseMindooDB {
|
|
|
4206
4414
|
const representative = lifecycleEntriesInBatch[0] ?? entryMetadataList[0];
|
|
4207
4415
|
const decryptionKeyId = representative?.decryptionKeyId ?? existing.decryptionKeyId;
|
|
4208
4416
|
const batchLastModified = entryMetadataList.length > 0
|
|
4209
|
-
?
|
|
4417
|
+
? (0, largeArrays_1.maxOf)(entryMetadataList, (entry) => entry.createdAt)
|
|
4210
4418
|
: 0;
|
|
4211
4419
|
const lastModified = Math.max(existing.lastModified, batchLastModified);
|
|
4212
4420
|
await this.purgeMaterializedDocument(docId);
|
|
@@ -4235,19 +4443,27 @@ class BaseMindooDB {
|
|
|
4235
4443
|
});
|
|
4236
4444
|
}
|
|
4237
4445
|
};
|
|
4446
|
+
// Sort keys per document, computed once: the comparator runs
|
|
4447
|
+
// O(n log n) times, and a cold rebuild sorts every document.
|
|
4448
|
+
const minReceiptByDoc = new Map();
|
|
4449
|
+
const minCreatedAtByDoc = new Map();
|
|
4450
|
+
for (const [docId, list] of entriesByDoc) {
|
|
4451
|
+
minReceiptByDoc.set(docId, (0, largeArrays_1.minOf)(list, (e) => e.receiptOrder ?? Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER));
|
|
4452
|
+
minCreatedAtByDoc.set(docId, (0, largeArrays_1.minOf)(list, (e) => e.createdAt));
|
|
4453
|
+
}
|
|
4238
4454
|
const documentEntries = Array.from(entriesByDoc.entries()).sort((a, b) => {
|
|
4239
4455
|
// Prefer the store's receiptOrder (unique, reflects the actual write
|
|
4240
4456
|
// order) so a cold rebuild assigns changeSeqs in the same order the
|
|
4241
4457
|
// live session did — `createdAt` has millisecond resolution and ties
|
|
4242
4458
|
// for same-ms writes, which would otherwise flip the feed order to
|
|
4243
4459
|
// the docId tie-break after a restart.
|
|
4244
|
-
const aMinReceipt =
|
|
4245
|
-
const bMinReceipt =
|
|
4460
|
+
const aMinReceipt = minReceiptByDoc.get(a[0]);
|
|
4461
|
+
const bMinReceipt = minReceiptByDoc.get(b[0]);
|
|
4246
4462
|
if (aMinReceipt !== bMinReceipt) {
|
|
4247
4463
|
return aMinReceipt - bMinReceipt;
|
|
4248
4464
|
}
|
|
4249
|
-
const aMinCreatedAt =
|
|
4250
|
-
const bMinCreatedAt =
|
|
4465
|
+
const aMinCreatedAt = minCreatedAtByDoc.get(a[0]);
|
|
4466
|
+
const bMinCreatedAt = minCreatedAtByDoc.get(b[0]);
|
|
4251
4467
|
if (aMinCreatedAt !== bMinCreatedAt) {
|
|
4252
4468
|
return aMinCreatedAt - bMinCreatedAt;
|
|
4253
4469
|
}
|
|
@@ -4262,7 +4478,7 @@ class BaseMindooDB {
|
|
|
4262
4478
|
// cursor-capable stores track progress via processedEntryCursor, so we
|
|
4263
4479
|
// avoid growing an unbounded in-memory id list.
|
|
4264
4480
|
if (!this.supportsCursorScan(this.store)) {
|
|
4265
|
-
this.processedEntryIds
|
|
4481
|
+
(0, largeArrays_1.pushAll)(this.processedEntryIds, newEntryMetadata.map((em) => em.id));
|
|
4266
4482
|
}
|
|
4267
4483
|
for (const entryMeta of newEntryMetadata) {
|
|
4268
4484
|
this.locallyIndexedEntryIds.delete(entryMeta.id);
|
|
@@ -4270,14 +4486,14 @@ class BaseMindooDB {
|
|
|
4270
4486
|
this.processedEntryCursor = nextCursor;
|
|
4271
4487
|
this.cacheMetaDirty = true;
|
|
4272
4488
|
this.cacheManager?.markDirty();
|
|
4273
|
-
this.logger.debug(`Synced ${newEntryMetadata.length} new entries, index now has ${this.index.
|
|
4489
|
+
this.logger.debug(`Synced ${newEntryMetadata.length} new entries, index now has ${this.index.size} documents`);
|
|
4274
4490
|
this.performanceCallback?.onSyncOperation?.({
|
|
4275
4491
|
operation: "findNewEntries",
|
|
4276
4492
|
time: Date.now() - syncStartedAt,
|
|
4277
4493
|
details: {
|
|
4278
4494
|
newEntryCount: newEntryMetadata.length,
|
|
4279
4495
|
documentCount: entriesByDoc.size,
|
|
4280
|
-
indexSize: this.index.
|
|
4496
|
+
indexSize: this.index.size,
|
|
4281
4497
|
},
|
|
4282
4498
|
});
|
|
4283
4499
|
}
|
|
@@ -4447,7 +4663,7 @@ class BaseMindooDB {
|
|
|
4447
4663
|
let cursor = null;
|
|
4448
4664
|
while (true) {
|
|
4449
4665
|
const page = await store.scanEntriesSince(cursor, 1000, effectiveFilters);
|
|
4450
|
-
|
|
4666
|
+
(0, largeArrays_1.pushAll)(all, page.entries);
|
|
4451
4667
|
cursor = page.nextCursor;
|
|
4452
4668
|
if (!page.hasMore) {
|
|
4453
4669
|
break;
|
|
@@ -4477,7 +4693,7 @@ class BaseMindooDB {
|
|
|
4477
4693
|
let cursor = this.processedEntryCursor;
|
|
4478
4694
|
while (true) {
|
|
4479
4695
|
const page = await this.store.scanEntriesSince(cursor, 1000, this.mergeTimeTravelScanFilters());
|
|
4480
|
-
|
|
4696
|
+
(0, largeArrays_1.pushAll)(allNew, page.entries);
|
|
4481
4697
|
cursor = page.nextCursor;
|
|
4482
4698
|
if (!page.hasMore) {
|
|
4483
4699
|
break;
|
|
@@ -4704,7 +4920,7 @@ class BaseMindooDB {
|
|
|
4704
4920
|
? new Set(batchRejected.map((entry) => entry.id))
|
|
4705
4921
|
: null;
|
|
4706
4922
|
if (rejectedIds) {
|
|
4707
|
-
|
|
4923
|
+
(0, largeArrays_1.pushAll)(rejected, batchRejected);
|
|
4708
4924
|
this.logger.warn(`Dense sync: target rejected ${batchRejected.length} of ${entries.length} entries in batch at offset ${offset}`);
|
|
4709
4925
|
}
|
|
4710
4926
|
for (const entry of entries) {
|
|
@@ -4895,7 +5111,7 @@ class BaseMindooDB {
|
|
|
4895
5111
|
}
|
|
4896
5112
|
const allEntries = [];
|
|
4897
5113
|
for (const preparedDoc of prepared) {
|
|
4898
|
-
|
|
5114
|
+
(0, largeArrays_1.pushAll)(allEntries, preparedDoc.entries);
|
|
4899
5115
|
}
|
|
4900
5116
|
if (allEntries.length > 0) {
|
|
4901
5117
|
await this.putLocalEntries(allEntries);
|
|
@@ -4903,6 +5119,7 @@ class BaseMindooDB {
|
|
|
4903
5119
|
for (const { index, internalDoc } of prepared) {
|
|
4904
5120
|
await this.storeCachedDocument(internalDoc);
|
|
4905
5121
|
this.updateIndex(internalDoc.id, internalDoc.lastModified, false, internalDoc.decryptionKeyId, "visible", internalDoc.awaitingWitness ?? false, internalDoc.witnessed ?? false);
|
|
5122
|
+
this.prepareSummaryEntry(internalDoc);
|
|
4906
5123
|
results[index] = this.wrapDocument(internalDoc);
|
|
4907
5124
|
}
|
|
4908
5125
|
if (prepared.length > 0) {
|
|
@@ -4955,12 +5172,12 @@ class BaseMindooDB {
|
|
|
4955
5172
|
* bare ObjectId without a prefix) that does not collide with any document
|
|
4956
5173
|
* already present in the local index. A collision is practically impossible
|
|
4957
5174
|
* (128-bit UUID7), so this is only a cheap O(1) safety net reusing the
|
|
4958
|
-
* existing
|
|
5175
|
+
* existing index lookup — no extra bookkeeping.
|
|
4959
5176
|
*/
|
|
4960
5177
|
generateUnusedDocId(prefix) {
|
|
4961
5178
|
for (;;) {
|
|
4962
5179
|
const candidate = (0, idGeneration_1.generateDocId)(prefix);
|
|
4963
|
-
if (this.
|
|
5180
|
+
if (!this.index.has(candidate)) {
|
|
4964
5181
|
return candidate;
|
|
4965
5182
|
}
|
|
4966
5183
|
}
|
|
@@ -5251,6 +5468,7 @@ class BaseMindooDB {
|
|
|
5251
5468
|
// Update cache and index
|
|
5252
5469
|
await this.storeCachedDocument(internalDoc);
|
|
5253
5470
|
this.updateIndex(docId, internalDoc.lastModified, false, internalDoc.decryptionKeyId, "visible", awaitingWitness, witnessed);
|
|
5471
|
+
this.prepareSummaryEntry(internalDoc);
|
|
5254
5472
|
this.markDocDirty(docId);
|
|
5255
5473
|
this.logger.info(`Document ${docId} created successfully`);
|
|
5256
5474
|
this.logger.debug(`Document ${docId} cached and indexed (lastModified: ${internalDoc.lastModified})`);
|
|
@@ -5901,8 +6119,7 @@ class BaseMindooDB {
|
|
|
5901
6119
|
return false;
|
|
5902
6120
|
}
|
|
5903
6121
|
await this.purgeMaterializedDocument(internalDoc.id);
|
|
5904
|
-
const
|
|
5905
|
-
const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
|
|
6122
|
+
const existing = this.index.get(internalDoc.id);
|
|
5906
6123
|
if (existing?.accessState === "visible") {
|
|
5907
6124
|
this.updateIndex(internalDoc.id, existing.lastModified, true, internalDoc.decryptionKeyId, "inaccessible");
|
|
5908
6125
|
this.cacheMetaDirty = true;
|
|
@@ -8166,7 +8383,7 @@ class BaseMindooDB {
|
|
|
8166
8383
|
// list of id prefixes (matched on the `<prefix>_` boundary; see matchesDocIdPrefix).
|
|
8167
8384
|
const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
|
|
8168
8385
|
const docIds = [];
|
|
8169
|
-
for (const entry of this.index) {
|
|
8386
|
+
for (const entry of this.index.values()) {
|
|
8170
8387
|
if (entry.accessState === "visible" && !entry.isDeleted) {
|
|
8171
8388
|
if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
|
|
8172
8389
|
continue;
|
|
@@ -8178,7 +8395,7 @@ class BaseMindooDB {
|
|
|
8178
8395
|
async getDeletedDocumentIds(options) {
|
|
8179
8396
|
const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
|
|
8180
8397
|
const docIds = [];
|
|
8181
|
-
for (const entry of this.index) {
|
|
8398
|
+
for (const entry of this.index.values()) {
|
|
8182
8399
|
if (entry.accessState === "visible" && entry.isDeleted) {
|
|
8183
8400
|
if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
|
|
8184
8401
|
continue;
|
|
@@ -8196,7 +8413,7 @@ class BaseMindooDB {
|
|
|
8196
8413
|
// and, on a time-travel instance, already reflects existence and deletion
|
|
8197
8414
|
// at the cutoff (every scan feeding it is bounded by timeTravelDate). So
|
|
8198
8415
|
// the scan below only has to supply dates, never lifecycle state.
|
|
8199
|
-
const candidates = this.index.filter((entry) => entry.accessState === "visible" &&
|
|
8416
|
+
const candidates = this.index.toArray().filter((entry) => entry.accessState === "visible" &&
|
|
8200
8417
|
matchesLifecycle(entry.isDeleted) &&
|
|
8201
8418
|
(idPrefix === undefined || (0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix)));
|
|
8202
8419
|
if (candidates.length === 0) {
|
|
@@ -10720,6 +10937,7 @@ class BaseMindooDB {
|
|
|
10720
10937
|
// changefeed must re-emit the doc even when `lastModified` collides with
|
|
10721
10938
|
// the previous change in the same millisecond.
|
|
10722
10939
|
this.updateIndex(docId, internalDoc.lastModified, internalDoc.isDeleted, internalDoc.decryptionKeyId, "visible", internalDoc.awaitingWitness, internalDoc.witnessed, true);
|
|
10940
|
+
this.prepareSummaryEntry(internalDoc);
|
|
10723
10941
|
if (recipients) {
|
|
10724
10942
|
internalDoc.sealedRecipients = recipients;
|
|
10725
10943
|
}
|
|
@@ -11018,35 +11236,39 @@ class BaseMindooDB {
|
|
|
11018
11236
|
* the cache instead of the store.
|
|
11019
11237
|
*
|
|
11020
11238
|
* Called after every yielded document, so it must be cheap when the runway
|
|
11021
|
-
* ahead is still full: `
|
|
11022
|
-
*
|
|
11023
|
-
*
|
|
11239
|
+
* ahead is still full: `lookahead.reader` is a second reader walking ahead
|
|
11240
|
+
* of the iteration, and a call that still has half a window of runway left
|
|
11241
|
+
* returns without touching the store. Without that check the
|
|
11024
11242
|
* pass issues a fetch per yielded document, and — because each call would
|
|
11025
11243
|
* scan past the cached documents to find a full window of uncached ones —
|
|
11026
11244
|
* it also runs unboundedly ahead of the cursor, materializing the whole
|
|
11027
11245
|
* changefeed tail and evicting it from L1 before iteration arrives.
|
|
11028
11246
|
*
|
|
11029
|
-
* Returns the
|
|
11247
|
+
* Returns the number of documents prefetched.
|
|
11030
11248
|
*/
|
|
11031
|
-
async prefetchIterationWindow(
|
|
11249
|
+
async prefetchIterationWindow(iteration, lookahead, idPrefix, persist = true, preparedDocument) {
|
|
11032
11250
|
const windowSize = this.iteratePrefetchWindowDocs;
|
|
11033
11251
|
if (windowSize <= 0) {
|
|
11034
|
-
return
|
|
11252
|
+
return 0;
|
|
11253
|
+
}
|
|
11254
|
+
let ahead = lookahead.reader;
|
|
11255
|
+
if (!ahead || ahead.consumed < iteration.consumed) {
|
|
11256
|
+
ahead = lookahead.reader = iteration.fork();
|
|
11035
11257
|
}
|
|
11036
|
-
|
|
11037
|
-
if (from - startIndex >= Math.ceil(windowSize / 2)) {
|
|
11258
|
+
if (ahead.consumed - iteration.consumed >= Math.ceil(windowSize / 2)) {
|
|
11038
11259
|
// Enough runway left; refilling now would trade one batched fetch per
|
|
11039
11260
|
// window for one per document.
|
|
11040
|
-
return
|
|
11261
|
+
return 0;
|
|
11041
11262
|
}
|
|
11042
11263
|
const docIds = [];
|
|
11043
11264
|
const seen = new Set();
|
|
11044
11265
|
// Look ahead a bounded number of uncached docs so iteration does not
|
|
11045
11266
|
// materialize the entire remaining changefeed tail up front.
|
|
11046
|
-
|
|
11047
|
-
|
|
11048
|
-
|
|
11049
|
-
|
|
11267
|
+
while (docIds.length < windowSize) {
|
|
11268
|
+
const entry = ahead.next();
|
|
11269
|
+
if (!entry) {
|
|
11270
|
+
break;
|
|
11271
|
+
}
|
|
11050
11272
|
// Skip docs that iterateChangesSince will emit as lightweight
|
|
11051
11273
|
// tombstones anyway: inaccessible docs are never materialized, and
|
|
11052
11274
|
// deleted docs are yielded without body materialization.
|
|
@@ -11061,11 +11283,15 @@ class BaseMindooDB {
|
|
|
11061
11283
|
if (seen.has(docId) || this.docCache.has(docId)) {
|
|
11062
11284
|
continue;
|
|
11063
11285
|
}
|
|
11286
|
+
// The iteration will not load documents its caller already prepared.
|
|
11287
|
+
if (preparedDocument?.(docId, entry.changeSeq) !== undefined) {
|
|
11288
|
+
continue;
|
|
11289
|
+
}
|
|
11064
11290
|
seen.add(docId);
|
|
11065
11291
|
docIds.push(docId);
|
|
11066
11292
|
}
|
|
11067
11293
|
if (docIds.length === 0) {
|
|
11068
|
-
return
|
|
11294
|
+
return 0;
|
|
11069
11295
|
}
|
|
11070
11296
|
// Prefetch is opportunistic: iteration can still fall back to on-demand
|
|
11071
11297
|
// loads, so individual prefetch failures are logged and ignored here.
|
|
@@ -11103,49 +11329,22 @@ class BaseMindooDB {
|
|
|
11103
11329
|
this.l2Prefetched.delete(docId);
|
|
11104
11330
|
}
|
|
11105
11331
|
}
|
|
11106
|
-
return
|
|
11107
|
-
prefetchedThrough: scannedThrough,
|
|
11108
|
-
prefetchedDocuments: docIds.length,
|
|
11109
|
-
};
|
|
11332
|
+
return docIds.length;
|
|
11110
11333
|
}
|
|
11111
|
-
|
|
11112
|
-
|
|
11113
|
-
|
|
11114
|
-
|
|
11115
|
-
|
|
11334
|
+
/**
|
|
11335
|
+
* The changefeed position a cursor continues after, or `null` to start at
|
|
11336
|
+
* the beginning.
|
|
11337
|
+
*/
|
|
11338
|
+
changefeedPositionForCursor(actualCursor) {
|
|
11116
11339
|
const cursorSeq = typeof actualCursor.changeSeq === "number" ? actualCursor.changeSeq : 0;
|
|
11117
11340
|
// A cursor of another numbering, or one past every number this feed ever
|
|
11118
11341
|
// handed out, cannot be placed: start over rather than skip documents.
|
|
11119
11342
|
if ((actualCursor.feedEpoch !== undefined && actualCursor.feedEpoch !== this.changeFeedEpoch) ||
|
|
11120
|
-
cursorSeq >= this.nextChangeSeq
|
|
11121
|
-
|
|
11122
|
-
|
|
11123
|
-
let left = 0;
|
|
11124
|
-
let right = indexSnapshot.length - 1;
|
|
11125
|
-
while (left <= right) {
|
|
11126
|
-
const mid = Math.floor((left + right) / 2);
|
|
11127
|
-
const entry = indexSnapshot[mid];
|
|
11128
|
-
const cursorComparable = {
|
|
11129
|
-
docId: actualCursor.docId,
|
|
11130
|
-
changeSeq: cursorSeq,
|
|
11131
|
-
};
|
|
11132
|
-
const cmp = this.compareIndexEntries(cursorComparable, entry);
|
|
11133
|
-
if (cmp < 0) {
|
|
11134
|
-
right = mid - 1;
|
|
11135
|
-
startIndex = mid;
|
|
11136
|
-
}
|
|
11137
|
-
else {
|
|
11138
|
-
left = mid + 1;
|
|
11139
|
-
startIndex = mid + 1;
|
|
11140
|
-
}
|
|
11141
|
-
}
|
|
11142
|
-
if (startIndex < indexSnapshot.length) {
|
|
11143
|
-
const entry = indexSnapshot[startIndex];
|
|
11144
|
-
if (entry.changeSeq === cursorSeq && entry.docId === actualCursor.docId) {
|
|
11145
|
-
startIndex++;
|
|
11146
|
-
}
|
|
11343
|
+
cursorSeq >= this.nextChangeSeq ||
|
|
11344
|
+
cursorSeq <= 0) {
|
|
11345
|
+
return null;
|
|
11147
11346
|
}
|
|
11148
|
-
return
|
|
11347
|
+
return { docId: actualCursor.docId ?? "", changeSeq: cursorSeq };
|
|
11149
11348
|
}
|
|
11150
11349
|
resolveDagTimestamp(timestamp) {
|
|
11151
11350
|
return timestamp === "now" ? (0, timeSource_1.semanticNow)() : timestamp;
|
|
@@ -11448,12 +11647,14 @@ class BaseMindooDB {
|
|
|
11448
11647
|
docId: "",
|
|
11449
11648
|
};
|
|
11450
11649
|
const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
|
|
11451
|
-
|
|
11452
|
-
|
|
11650
|
+
// The reader sees the index as it is now, without copying it (see
|
|
11651
|
+
// ChangefeedIndex): changes made while the caller iterates are left for
|
|
11652
|
+
// the next pass.
|
|
11653
|
+
const startPosition = this.changefeedPositionForCursor(actualCursor);
|
|
11654
|
+
const reader = this.index.reader(startPosition);
|
|
11453
11655
|
let yieldedDocuments = 0;
|
|
11454
11656
|
try {
|
|
11455
|
-
for (let
|
|
11456
|
-
const entry = indexSnapshot[i];
|
|
11657
|
+
for (let entry = reader.next(); entry; entry = reader.next()) {
|
|
11457
11658
|
if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
|
|
11458
11659
|
continue;
|
|
11459
11660
|
const currentCursor = {
|
|
@@ -11477,13 +11678,13 @@ class BaseMindooDB {
|
|
|
11477
11678
|
time: Date.now() - startedAt,
|
|
11478
11679
|
details: {
|
|
11479
11680
|
yieldedDocuments,
|
|
11480
|
-
|
|
11681
|
+
startChangeSeq: startPosition?.changeSeq ?? 0,
|
|
11481
11682
|
},
|
|
11482
11683
|
});
|
|
11483
11684
|
}
|
|
11484
11685
|
}
|
|
11485
11686
|
getLatestChangeCursor() {
|
|
11486
|
-
const latestEntry = this.index
|
|
11687
|
+
const latestEntry = this.index.last();
|
|
11487
11688
|
if (!latestEntry) {
|
|
11488
11689
|
return null;
|
|
11489
11690
|
}
|
|
@@ -11505,16 +11706,17 @@ class BaseMindooDB {
|
|
|
11505
11706
|
lastModified: 0,
|
|
11506
11707
|
docId: "",
|
|
11507
11708
|
};
|
|
11508
|
-
const
|
|
11709
|
+
const startPosition = this.changefeedPositionForCursor(actualCursor);
|
|
11509
11710
|
const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
|
|
11510
11711
|
if (!idPrefix) {
|
|
11511
|
-
return this.index.
|
|
11712
|
+
return this.index.countAfter(startPosition);
|
|
11512
11713
|
}
|
|
11513
11714
|
// Prefix-filtered count must walk the tail: the index is ordered by
|
|
11514
11715
|
// (changeSeq, docId), not by docId, so matches are not contiguous.
|
|
11515
11716
|
let count = 0;
|
|
11516
|
-
|
|
11517
|
-
|
|
11717
|
+
const reader = this.index.reader(startPosition);
|
|
11718
|
+
for (let entry = reader.next(); entry; entry = reader.next()) {
|
|
11719
|
+
if ((0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
|
|
11518
11720
|
count++;
|
|
11519
11721
|
}
|
|
11520
11722
|
return count;
|
|
@@ -11530,29 +11732,28 @@ class BaseMindooDB {
|
|
|
11530
11732
|
};
|
|
11531
11733
|
const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
|
|
11532
11734
|
const persistLoaded = options?.persistLoadedDocuments !== false;
|
|
11735
|
+
const preparedDocument = options?.preparedDocument;
|
|
11533
11736
|
this.logger.debug(`Starting iteration from cursor ${JSON.stringify(actualCursor)}`);
|
|
11534
|
-
//
|
|
11535
|
-
// updates do not reorder
|
|
11536
|
-
|
|
11537
|
-
|
|
11538
|
-
|
|
11539
|
-
const startIndex = this.getStartIndexForCursor(indexSnapshot, actualCursor);
|
|
11737
|
+
// Read the index as it is now, without copying it (see ChangefeedIndex),
|
|
11738
|
+
// so concurrent updates do not reorder or skip entries while iterating.
|
|
11739
|
+
// Starts right after the cursor position.
|
|
11740
|
+
const startPosition = this.changefeedPositionForCursor(actualCursor);
|
|
11741
|
+
const reader = this.index.reader(startPosition);
|
|
11540
11742
|
let prefetchedDocuments = 0;
|
|
11541
|
-
//
|
|
11542
|
-
// so concurrent iterations do not share a runway.
|
|
11543
|
-
|
|
11544
|
-
|
|
11545
|
-
|
|
11546
|
-
|
|
11547
|
-
prefetchedDocuments +=
|
|
11743
|
+
// The prefetch windows walk ahead with their own reader. Kept per
|
|
11744
|
+
// generator run so concurrent iterations do not share a runway.
|
|
11745
|
+
const lookahead = {
|
|
11746
|
+
reader: null,
|
|
11747
|
+
};
|
|
11748
|
+
const prefetchAhead = async () => {
|
|
11749
|
+
prefetchedDocuments += await this.prefetchIterationWindow(reader, lookahead, idPrefix, persistLoaded, preparedDocument);
|
|
11548
11750
|
};
|
|
11549
|
-
await
|
|
11751
|
+
await prefetchAhead();
|
|
11550
11752
|
let yieldedDocuments = 0;
|
|
11551
11753
|
let loadedDocuments = 0;
|
|
11552
11754
|
try {
|
|
11553
|
-
// Iterate through the
|
|
11554
|
-
for (let
|
|
11555
|
-
const entry = indexSnapshot[i];
|
|
11755
|
+
// Iterate through the index and yield documents one at a time.
|
|
11756
|
+
for (let entry = reader.next(); entry; entry = reader.next()) {
|
|
11556
11757
|
// Skip entries outside the requested id prefix before any body load,
|
|
11557
11758
|
// so prefix-filtered iteration never decrypts/materializes unrelated docs.
|
|
11558
11759
|
if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
|
|
@@ -11575,7 +11776,7 @@ class BaseMindooDB {
|
|
|
11575
11776
|
doc: this.buildInaccessibleDoc(entry),
|
|
11576
11777
|
cursor: inaccessibleCursor,
|
|
11577
11778
|
};
|
|
11578
|
-
await
|
|
11779
|
+
await prefetchAhead();
|
|
11579
11780
|
continue;
|
|
11580
11781
|
}
|
|
11581
11782
|
if (entry.isDeleted) {
|
|
@@ -11593,7 +11794,24 @@ class BaseMindooDB {
|
|
|
11593
11794
|
};
|
|
11594
11795
|
yieldedDocuments++;
|
|
11595
11796
|
yield { doc: this.buildDeletedDoc(entry), cursor: deletedCursor };
|
|
11596
|
-
await
|
|
11797
|
+
await prefetchAhead();
|
|
11798
|
+
continue;
|
|
11799
|
+
}
|
|
11800
|
+
const prepared = preparedDocument?.(entry.docId, entry.changeSeq);
|
|
11801
|
+
if (prepared !== undefined) {
|
|
11802
|
+
// The caller extracted this state when it was written: no load.
|
|
11803
|
+
yieldedDocuments++;
|
|
11804
|
+
yield {
|
|
11805
|
+
doc: this.buildPreparedDoc(entry),
|
|
11806
|
+
cursor: {
|
|
11807
|
+
changeSeq: entry.changeSeq,
|
|
11808
|
+
lastModified: entry.lastModified,
|
|
11809
|
+
docId: entry.docId,
|
|
11810
|
+
feedEpoch: this.changeFeedEpoch,
|
|
11811
|
+
},
|
|
11812
|
+
prepared,
|
|
11813
|
+
};
|
|
11814
|
+
await prefetchAhead();
|
|
11597
11815
|
continue;
|
|
11598
11816
|
}
|
|
11599
11817
|
try {
|
|
@@ -11624,7 +11842,7 @@ class BaseMindooDB {
|
|
|
11624
11842
|
// Deleted documents are included so external indexes can handle deletions
|
|
11625
11843
|
yieldedDocuments++;
|
|
11626
11844
|
yield { doc, cursor: currentCursor };
|
|
11627
|
-
await
|
|
11845
|
+
await prefetchAhead();
|
|
11628
11846
|
}
|
|
11629
11847
|
catch (error) {
|
|
11630
11848
|
if ((0, documentLoadGuard_1.isDocumentTooLargeError)(error)) {
|
|
@@ -11643,7 +11861,7 @@ class BaseMindooDB {
|
|
|
11643
11861
|
feedEpoch: this.changeFeedEpoch,
|
|
11644
11862
|
},
|
|
11645
11863
|
};
|
|
11646
|
-
await
|
|
11864
|
+
await prefetchAhead();
|
|
11647
11865
|
continue;
|
|
11648
11866
|
}
|
|
11649
11867
|
if ((0, errors_1.isSymmetricKeyNotFound)(error)) {
|
|
@@ -11667,7 +11885,7 @@ class BaseMindooDB {
|
|
|
11667
11885
|
feedEpoch: this.changeFeedEpoch,
|
|
11668
11886
|
},
|
|
11669
11887
|
};
|
|
11670
|
-
await
|
|
11888
|
+
await prefetchAhead();
|
|
11671
11889
|
continue;
|
|
11672
11890
|
}
|
|
11673
11891
|
this.logger.error(`Error processing document ${entry.docId}:`, error);
|
|
@@ -11685,7 +11903,7 @@ class BaseMindooDB {
|
|
|
11685
11903
|
yieldedDocuments,
|
|
11686
11904
|
prefetchedDocuments,
|
|
11687
11905
|
loadedDocuments,
|
|
11688
|
-
|
|
11906
|
+
startChangeSeq: startPosition?.changeSeq ?? 0,
|
|
11689
11907
|
},
|
|
11690
11908
|
});
|
|
11691
11909
|
}
|
|
@@ -11924,8 +12142,8 @@ class BaseMindooDB {
|
|
|
11924
12142
|
await this.purgeMaterializedDocument(docId);
|
|
11925
12143
|
return null;
|
|
11926
12144
|
}
|
|
11927
|
-
const
|
|
11928
|
-
if (
|
|
12145
|
+
const indexEntry = this.index.get(docId);
|
|
12146
|
+
if (indexEntry === undefined) {
|
|
11929
12147
|
// Doc isn't in the in-memory changefeed index. Either the cache is
|
|
11930
12148
|
// ahead of the index (very rare race during initial restore) or the
|
|
11931
12149
|
// L2 record is orphaned. Drop and fall through.
|
|
@@ -11938,7 +12156,7 @@ class BaseMindooDB {
|
|
|
11938
12156
|
}
|
|
11939
12157
|
return null;
|
|
11940
12158
|
}
|
|
11941
|
-
const currentChangeSeq =
|
|
12159
|
+
const currentChangeSeq = indexEntry.changeSeq;
|
|
11942
12160
|
// Later flushes of this document append to the record chain just read.
|
|
11943
12161
|
this.adoptL2Chain(deserialized);
|
|
11944
12162
|
// Fresh hit: index agrees with the persisted state.
|
|
@@ -12177,7 +12395,7 @@ class BaseMindooDB {
|
|
|
12177
12395
|
// flush-before-evict) persists them anyway. Unknown docs (legacy
|
|
12178
12396
|
// checkpoint) stay in and are checked against their record header below.
|
|
12179
12397
|
const docIds = [];
|
|
12180
|
-
for (const entry of this.index) {
|
|
12398
|
+
for (const entry of this.index.values()) {
|
|
12181
12399
|
if (entry.accessState === "visible" &&
|
|
12182
12400
|
this.l2RecordChangeSeqs.get(entry.docId) !== entry.changeSeq &&
|
|
12183
12401
|
!this.docCache.has(entry.docId)) {
|
|
@@ -12295,12 +12513,11 @@ class BaseMindooDB {
|
|
|
12295
12513
|
* the doc (legacy checkpoint) from the record header (no Automerge load).
|
|
12296
12514
|
*/
|
|
12297
12515
|
async isL2RecordCurrent(docId) {
|
|
12298
|
-
const
|
|
12516
|
+
const entry = this.index.get(docId);
|
|
12299
12517
|
const store = this.cacheManager?.getStore() ?? null;
|
|
12300
|
-
if (
|
|
12518
|
+
if (entry === undefined || !store) {
|
|
12301
12519
|
return false;
|
|
12302
12520
|
}
|
|
12303
|
-
const entry = this.index[indexEntryIdx];
|
|
12304
12521
|
if (entry.accessState !== "visible") {
|
|
12305
12522
|
return false;
|
|
12306
12523
|
}
|
|
@@ -12341,7 +12558,7 @@ class BaseMindooDB {
|
|
|
12341
12558
|
getQuarantineLog() {
|
|
12342
12559
|
const flat = [];
|
|
12343
12560
|
for (const records of this.quarantineLog.values()) {
|
|
12344
|
-
|
|
12561
|
+
(0, largeArrays_1.pushAll)(flat, records);
|
|
12345
12562
|
}
|
|
12346
12563
|
return flat;
|
|
12347
12564
|
}
|
|
@@ -13249,14 +13466,17 @@ class BaseMindooDB {
|
|
|
13249
13466
|
? Number.MAX_SAFE_INTEGER
|
|
13250
13467
|
: (meta.receivedAt ?? meta.createdAt);
|
|
13251
13468
|
const cryptoKey = await this.getOrImportPublicKey(entry.createdByPublicKey, trustedTimeForTrust);
|
|
13252
|
-
|
|
13469
|
+
// A delivery by a guest ticket (docs/accesscontrol.md §6.14) is not
|
|
13470
|
+
// signed by a grant key; the tenant's entry check knows its shape.
|
|
13471
|
+
const verifyKey = cryptoKey ?? (await this.guestTicketVerifyKey(entry));
|
|
13472
|
+
if (!verifyKey) {
|
|
13253
13473
|
// Author key not (yet) trusted by the directory. Remember it so a
|
|
13254
13474
|
// later grantaccess sync can re-materialize the doc (reconcileAuthorTrust).
|
|
13255
13475
|
this.recordPendingUntrustedAuthor(entry.createdByPublicKey, docId);
|
|
13256
13476
|
quarantine(meta, "invalid_signature", "author key not trusted by directory");
|
|
13257
13477
|
continue;
|
|
13258
13478
|
}
|
|
13259
|
-
if (!(await this.verifyEntrySignatureWithKey(
|
|
13479
|
+
if (!(await this.verifyEntrySignatureWithKey(verifyKey, entry))) {
|
|
13260
13480
|
quarantine(meta, "invalid_signature", "signature verification failed");
|
|
13261
13481
|
continue;
|
|
13262
13482
|
}
|
|
@@ -13470,9 +13690,7 @@ class BaseMindooDB {
|
|
|
13470
13690
|
// of whether L1/L2 still hold a cached copy. This keeps the public
|
|
13471
13691
|
// contract of `loadDocumentInternal` aligned with `getDocument` /
|
|
13472
13692
|
// `getAllDocumentIds`.
|
|
13473
|
-
|
|
13474
|
-
if (indexEntryIdx !== undefined &&
|
|
13475
|
-
this.index[indexEntryIdx].accessState === "inaccessible") {
|
|
13693
|
+
if (this.index.get(docId)?.accessState === "inaccessible") {
|
|
13476
13694
|
return null;
|
|
13477
13695
|
}
|
|
13478
13696
|
if (this.docCache.has(docId)) {
|
|
@@ -13572,8 +13790,7 @@ class BaseMindooDB {
|
|
|
13572
13790
|
if ((0, sealedTypes_1.isSealedKeyId)(loadKeyId) &&
|
|
13573
13791
|
!(await this.tenant.hasDecryptionKey(loadKeyId))) {
|
|
13574
13792
|
this.logger.debug(`Document ${docId} is sealed and not unwrapable; treating as missing`);
|
|
13575
|
-
const
|
|
13576
|
-
const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
|
|
13793
|
+
const existing = this.index.get(docId);
|
|
13577
13794
|
if (existing?.accessState === "visible") {
|
|
13578
13795
|
await this.purgeMaterializedDocument(docId);
|
|
13579
13796
|
this.updateIndex(docId, existing.lastModified, true, loadKeyId, "inaccessible");
|
|
@@ -14124,8 +14341,7 @@ class BaseMindooDB {
|
|
|
14124
14341
|
*/
|
|
14125
14342
|
async markUndecryptableDocument(entry) {
|
|
14126
14343
|
this.noteInaccessibleDocument(entry.docId);
|
|
14127
|
-
const
|
|
14128
|
-
const current = position === undefined ? undefined : this.index[position];
|
|
14344
|
+
const current = this.index.get(entry.docId);
|
|
14129
14345
|
if (current?.accessState !== "visible")
|
|
14130
14346
|
return;
|
|
14131
14347
|
await this.purgeMaterializedDocument(entry.docId);
|
|
@@ -14145,15 +14361,36 @@ class BaseMindooDB {
|
|
|
14145
14361
|
};
|
|
14146
14362
|
return this.wrapDocument(internalDoc);
|
|
14147
14363
|
}
|
|
14364
|
+
/** Placeholder for a document its iteration consumer prepared (no data). */
|
|
14365
|
+
buildPreparedDoc(entry) {
|
|
14366
|
+
this.emptyPayload ?? (this.emptyPayload = automerge_adapter_1.Automerge.init());
|
|
14367
|
+
return this.wrapDocument({
|
|
14368
|
+
id: entry.docId,
|
|
14369
|
+
doc: this.emptyPayload,
|
|
14370
|
+
createdAt: 0,
|
|
14371
|
+
lastModified: entry.lastModified,
|
|
14372
|
+
decryptionKeyId: entry.decryptionKeyId,
|
|
14373
|
+
isDeleted: false,
|
|
14374
|
+
awaitingWitness: entry.awaitingWitness ?? false,
|
|
14375
|
+
witnessed: entry.witnessed ?? false,
|
|
14376
|
+
});
|
|
14377
|
+
}
|
|
14148
14378
|
/**
|
|
14149
|
-
*
|
|
14150
|
-
*
|
|
14151
|
-
*
|
|
14152
|
-
* `getData() === {}` — the counterpart to {@link buildInaccessibleDoc} for
|
|
14153
|
-
* genuine deletions (distinguish the two via `isAccessible()`). Consumers
|
|
14154
|
-
* that need the last state of a deleted document can use
|
|
14155
|
-
* {@link iterateDocumentHistory} or {@link getDocumentAtTimestamp}.
|
|
14379
|
+
* Hand a document the user just wrote to the summary buffer while it is
|
|
14380
|
+
* in memory (see DocumentSummaryStore.prepareDocument). Call after
|
|
14381
|
+
* updateIndex, so the index holds the document's new changefeed position.
|
|
14156
14382
|
*/
|
|
14383
|
+
prepareSummaryEntry(internalDoc) {
|
|
14384
|
+
const store = this.summaryStore;
|
|
14385
|
+
if (!store || internalDoc.isDeleted) {
|
|
14386
|
+
return;
|
|
14387
|
+
}
|
|
14388
|
+
const entry = this.index.get(internalDoc.id);
|
|
14389
|
+
if (!entry || entry.isDeleted || entry.accessState !== "visible" || entry.lastModified !== internalDoc.lastModified) {
|
|
14390
|
+
return;
|
|
14391
|
+
}
|
|
14392
|
+
store.prepareDocument(internalDoc.id, this.wrapDocument(internalDoc), entry.changeSeq);
|
|
14393
|
+
}
|
|
14157
14394
|
buildDeletedDoc(entry) {
|
|
14158
14395
|
const internalDoc = {
|
|
14159
14396
|
id: entry.docId,
|