mindoodb 0.2.2 → 0.2.3
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/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts +2 -0
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts.map +1 -1
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js +13 -2
- package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js.map +1 -1
- package/dist/browser/index.mjs +1 -0
- package/dist/core/BaseMindooDB.d.ts +37 -0
- package/dist/core/BaseMindooDB.d.ts.map +1 -1
- package/dist/core/BaseMindooDB.js +361 -26
- package/dist/core/BaseMindooDB.js.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.d.ts +2 -0
- package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
- package/dist/core/BaseMindooTenantDirectory.js +7 -1
- package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/personalShares.d.ts +10 -0
- package/dist/core/personalShares.d.ts.map +1 -1
- package/dist/core/personalShares.js +12 -1
- package/dist/core/personalShares.js.map +1 -1
- package/dist/server/TenantManager.d.ts.map +1 -1
- package/dist/server/TenantManager.js +3 -0
- package/dist/server/TenantManager.js.map +1 -1
- package/package.json +1 -1
|
@@ -159,11 +159,50 @@ const DEFAULT_WARMER_SCHEDULER = {
|
|
|
159
159
|
* touching the document store, and apply only missing changes when
|
|
160
160
|
* stale (see Phase 1c of the L1/L2 cache plan).
|
|
161
161
|
*
|
|
162
|
+
* v3: a record may be followed by incremental records (type
|
|
163
|
+
* {@link DOC_DELTA_CACHE_TYPE}): `Automerge.saveSince()` of the changes
|
|
164
|
+
* flushed after it, each with a full v3 header of the state it brings the
|
|
165
|
+
* document to. The base header carries a random `gen`; a delta only counts
|
|
166
|
+
* when it has the same `gen` and the next `seq`, and only as many deltas
|
|
167
|
+
* as the metadata checkpoint lists (`l2DeltaCounts`) are read. So a delta
|
|
168
|
+
* left behind by a crash or by an older base is ignored, and the document
|
|
169
|
+
* is then brought up to date from the store like any stale L2 record.
|
|
170
|
+
* v2 records are still read (as a base without deltas); readers of v2
|
|
171
|
+
* skip v3 records and materialize the document from the store.
|
|
172
|
+
*
|
|
162
173
|
* v1 records are silently ignored on restore - the next read of that
|
|
163
174
|
* doc falls through to the normal materialization path and re-flushes
|
|
164
|
-
* with a
|
|
175
|
+
* with a v3 header.
|
|
176
|
+
*/
|
|
177
|
+
const DOC_CACHE_HEADER_VERSION = 3;
|
|
178
|
+
/** Header versions of L2 document records this code can read. */
|
|
179
|
+
const READABLE_DOC_CACHE_HEADER_VERSIONS = new Set([2, 3]);
|
|
180
|
+
/** Cache store type of incremental L2 document records (see v3 above). */
|
|
181
|
+
const DOC_DELTA_CACHE_TYPE = "docdelta";
|
|
182
|
+
/**
|
|
183
|
+
* When a flush writes only the changes since the last flush instead of the
|
|
184
|
+
* whole document: a full `Automerge.save()` costs roughly 65 ms per MB of
|
|
185
|
+
* document (blocking) and rewrites all of it, a delta of a small change
|
|
186
|
+
* well under 1 ms and a few hundred bytes. Small documents are always
|
|
187
|
+
* saved in full (one record, no read overhead). The chain is compacted
|
|
188
|
+
* into a new full record once it is long or large, so reading a document
|
|
189
|
+
* stays about as fast as loading one full record.
|
|
165
190
|
*/
|
|
166
|
-
const
|
|
191
|
+
const L2_DELTA_MIN_BASE_BYTES = 256 * 1024;
|
|
192
|
+
const L2_DELTA_MAX_COUNT = 32;
|
|
193
|
+
const L2_DELTA_MAX_BASE_RATIO = 0.25;
|
|
194
|
+
function newL2Gen() {
|
|
195
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
196
|
+
}
|
|
197
|
+
/** Frame an L2 record: 4-byte header length (big-endian) + header JSON + payload. */
|
|
198
|
+
function frameDocCacheRecord(header, payload) {
|
|
199
|
+
const headerBytes = new TextEncoder().encode(JSON.stringify(header));
|
|
200
|
+
const value = new Uint8Array(4 + headerBytes.length + payload.length);
|
|
201
|
+
new DataView(value.buffer).setUint32(0, headerBytes.length, false);
|
|
202
|
+
value.set(headerBytes, 4);
|
|
203
|
+
value.set(payload, 4 + headerBytes.length);
|
|
204
|
+
return value;
|
|
205
|
+
}
|
|
167
206
|
/**
|
|
168
207
|
* How many quarantine records one document keeps in the audit log.
|
|
169
208
|
*
|
|
@@ -595,6 +634,15 @@ class BaseMindooDB {
|
|
|
595
634
|
* the store, as on any L2 miss.
|
|
596
635
|
*/
|
|
597
636
|
this.l2RecordsTracked = true;
|
|
637
|
+
/**
|
|
638
|
+
* Per document, how many incremental L2 records follow its base record
|
|
639
|
+
* (see {@link DOC_CACHE_HEADER_VERSION} v3). Persisted in the metadata
|
|
640
|
+
* checkpoint; readers read exactly this many, so a delta written after the
|
|
641
|
+
* last checkpoint (crash) is ignored. Missing entry: no deltas.
|
|
642
|
+
*/
|
|
643
|
+
this.l2DeltaCounts = new Map();
|
|
644
|
+
/** Writer state of the L2 record chain per document (not persisted). */
|
|
645
|
+
this.l2Chains = new Map();
|
|
598
646
|
/** L2 records fetched in one batch for a prefetch window (consumed by tryLoadFromL2). */
|
|
599
647
|
this.l2Prefetched = new Map();
|
|
600
648
|
/**
|
|
@@ -1936,11 +1984,12 @@ class BaseMindooDB {
|
|
|
1936
1984
|
// Skip the Automerge.save + L2 write when the exact same state was
|
|
1937
1985
|
// already flushed (docs marked dirty by a load rather than a change).
|
|
1938
1986
|
const flushKey = `${changeSeq}:${automergeHeads.join(",")}`;
|
|
1939
|
-
if (this.lastFlushedDocState.get(docId) === flushKey
|
|
1987
|
+
if (this.lastFlushedDocState.get(docId) === flushKey &&
|
|
1988
|
+
!this.l2Chains.get(docId)?.compactDue) {
|
|
1940
1989
|
return;
|
|
1941
1990
|
}
|
|
1942
|
-
const
|
|
1943
|
-
const header =
|
|
1991
|
+
const key = `${prefix}/${docId}`;
|
|
1992
|
+
const header = {
|
|
1944
1993
|
version: DOC_CACHE_HEADER_VERSION,
|
|
1945
1994
|
id: internal.id,
|
|
1946
1995
|
createdAt: internal.createdAt,
|
|
@@ -1951,16 +2000,154 @@ class BaseMindooDB {
|
|
|
1951
2000
|
witnessed: internal.witnessed ?? false,
|
|
1952
2001
|
changeSeq,
|
|
1953
2002
|
automergeHeads,
|
|
2003
|
+
};
|
|
2004
|
+
// Only the changes since the last flush, when the chain allows it.
|
|
2005
|
+
const chain = this.l2Chains.get(docId);
|
|
2006
|
+
const delta = chain ? this.l2DeltaFor(internal.doc, chain) : null;
|
|
2007
|
+
if (chain && delta) {
|
|
2008
|
+
const seq = chain.count + 1;
|
|
2009
|
+
await store.put(DOC_DELTA_CACHE_TYPE, `${key}#${seq}`, frameDocCacheRecord({ ...header, kind: "delta", gen: chain.gen, seq }, delta));
|
|
2010
|
+
chain.count = seq;
|
|
2011
|
+
chain.deltaBytes += delta.byteLength;
|
|
2012
|
+
chain.heads = automergeHeads;
|
|
2013
|
+
this.setL2DeltaCount(docId, seq);
|
|
2014
|
+
this.rememberL2Record(docId, changeSeq, flushKey);
|
|
2015
|
+
return;
|
|
2016
|
+
}
|
|
2017
|
+
// Full record: a new base (new `gen`), then the old deltas are dropped.
|
|
2018
|
+
const amBinary = automerge_adapter_1.Automerge.save(internal.doc);
|
|
2019
|
+
const gen = newL2Gen();
|
|
2020
|
+
await store.put("doc", key, frameDocCacheRecord({ ...header, kind: "base", gen }, amBinary));
|
|
2021
|
+
const staleDeltas = this.l2DeltaCounts.get(docId) ?? 0;
|
|
2022
|
+
this.l2Chains.set(docId, {
|
|
2023
|
+
gen,
|
|
2024
|
+
heads: automergeHeads,
|
|
2025
|
+
count: 0,
|
|
2026
|
+
deltaBytes: 0,
|
|
2027
|
+
baseBytes: amBinary.byteLength,
|
|
1954
2028
|
});
|
|
1955
|
-
|
|
1956
|
-
// Format: 4-byte header length (big-endian) + header JSON + Automerge binary
|
|
1957
|
-
const value = new Uint8Array(4 + headerBytes.length + amBinary.length);
|
|
1958
|
-
const view = new DataView(value.buffer);
|
|
1959
|
-
view.setUint32(0, headerBytes.length, false);
|
|
1960
|
-
value.set(headerBytes, 4);
|
|
1961
|
-
value.set(amBinary, 4 + headerBytes.length);
|
|
1962
|
-
await store.put("doc", `${prefix}/${docId}`, value);
|
|
2029
|
+
this.setL2DeltaCount(docId, 0);
|
|
1963
2030
|
this.rememberL2Record(docId, changeSeq, flushKey);
|
|
2031
|
+
await this.deleteL2Deltas(store, key, staleDeltas);
|
|
2032
|
+
}
|
|
2033
|
+
/**
|
|
2034
|
+
* The bytes to append to the L2 record chain of a document, or `null`
|
|
2035
|
+
* when a full record is due: small document, long or large chain, or the
|
|
2036
|
+
* document no longer contains the flushed heads (e.g. it was rebuilt).
|
|
2037
|
+
*/
|
|
2038
|
+
l2DeltaFor(doc, chain) {
|
|
2039
|
+
if (typeof automerge_adapter_1.Automerge.saveSince !== "function" ||
|
|
2040
|
+
typeof automerge_adapter_1.Automerge.hasHeads !== "function" ||
|
|
2041
|
+
chain.compactDue ||
|
|
2042
|
+
chain.baseBytes < L2_DELTA_MIN_BASE_BYTES ||
|
|
2043
|
+
chain.count >= L2_DELTA_MAX_COUNT) {
|
|
2044
|
+
return null;
|
|
2045
|
+
}
|
|
2046
|
+
try {
|
|
2047
|
+
if (!automerge_adapter_1.Automerge.hasHeads(doc, chain.heads)) {
|
|
2048
|
+
return null;
|
|
2049
|
+
}
|
|
2050
|
+
const delta = automerge_adapter_1.Automerge.saveSince(doc, chain.heads);
|
|
2051
|
+
if (chain.deltaBytes + delta.byteLength > chain.baseBytes * L2_DELTA_MAX_BASE_RATIO) {
|
|
2052
|
+
return null;
|
|
2053
|
+
}
|
|
2054
|
+
return delta;
|
|
2055
|
+
}
|
|
2056
|
+
catch {
|
|
2057
|
+
return null;
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
/** Persisted delta count of a document's L2 record (0 = none). */
|
|
2061
|
+
setL2DeltaCount(docId, count) {
|
|
2062
|
+
const previous = this.l2DeltaCounts.get(docId) ?? 0;
|
|
2063
|
+
if (previous === count) {
|
|
2064
|
+
return;
|
|
2065
|
+
}
|
|
2066
|
+
if (count > 0) {
|
|
2067
|
+
this.l2DeltaCounts.set(docId, count);
|
|
2068
|
+
}
|
|
2069
|
+
else {
|
|
2070
|
+
this.l2DeltaCounts.delete(docId);
|
|
2071
|
+
}
|
|
2072
|
+
this.cacheMetaDirty = true;
|
|
2073
|
+
this.cacheManager?.markDirty();
|
|
2074
|
+
}
|
|
2075
|
+
/** Best effort: drop deltas `1..count` of the record at `key`. */
|
|
2076
|
+
async deleteL2Deltas(store, key, count) {
|
|
2077
|
+
for (let seq = 1; seq <= count; seq++) {
|
|
2078
|
+
try {
|
|
2079
|
+
await store.delete(DOC_DELTA_CACHE_TYPE, `${key}#${seq}`);
|
|
2080
|
+
}
|
|
2081
|
+
catch (e) {
|
|
2082
|
+
this.logger.warn(`Failed to delete L2 delta ${key}#${seq}: ${e}`);
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
/**
|
|
2087
|
+
* Delete delta records the checkpoint does not list: left behind when a
|
|
2088
|
+
* crash hit between a full write and the deletion of the old deltas, when
|
|
2089
|
+
* the checkpoint was lost, or by a MindooDB version without deltas (which
|
|
2090
|
+
* rewrote the base and dropped `l2DeltaCounts`). Readers ignore them
|
|
2091
|
+
* anyway; this only frees the space. Best effort.
|
|
2092
|
+
*/
|
|
2093
|
+
async dropUnlistedL2Deltas(store, docPrefix, baseKeys) {
|
|
2094
|
+
try {
|
|
2095
|
+
const deltaKeys = (await store.list(DOC_DELTA_CACHE_TYPE)).filter((key) => key.startsWith(docPrefix));
|
|
2096
|
+
if (deltaKeys.length === 0) {
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
const bases = new Set(baseKeys.map((key) => key.slice(docPrefix.length)));
|
|
2100
|
+
for (const key of deltaKeys) {
|
|
2101
|
+
const rest = key.slice(docPrefix.length);
|
|
2102
|
+
const hash = rest.lastIndexOf("#");
|
|
2103
|
+
const docId = hash > 0 ? rest.slice(0, hash) : rest;
|
|
2104
|
+
const seq = hash > 0 ? Number(rest.slice(hash + 1)) : NaN;
|
|
2105
|
+
const listed = bases.has(docId) && Number.isInteger(seq) && seq >= 1 &&
|
|
2106
|
+
seq <= (this.l2DeltaCounts.get(docId) ?? 0);
|
|
2107
|
+
if (!listed) {
|
|
2108
|
+
await store.delete(DOC_DELTA_CACHE_TYPE, key);
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
catch (e) {
|
|
2113
|
+
this.logger.warn(`Cleaning up unlisted L2 deltas failed: ${e}`);
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
/** Delete the L2 record of `docId` and its deltas; callers then {@link forgetL2Record}. */
|
|
2117
|
+
async deleteL2Record(store, docId) {
|
|
2118
|
+
const key = `${this.getCachePrefix()}/${docId}`;
|
|
2119
|
+
const deltas = this.l2DeltaCounts.get(docId) ?? 0;
|
|
2120
|
+
await store.delete("doc", key);
|
|
2121
|
+
await this.deleteL2Deltas(store, key, deltas);
|
|
2122
|
+
}
|
|
2123
|
+
/** The persisted deltas of the given documents' records, aligned with `docIds`. */
|
|
2124
|
+
async readL2Deltas(store, docIds) {
|
|
2125
|
+
const prefix = this.getCachePrefix();
|
|
2126
|
+
const keys = [];
|
|
2127
|
+
for (const docId of docIds) {
|
|
2128
|
+
const count = this.l2DeltaCounts.get(docId) ?? 0;
|
|
2129
|
+
for (let seq = 1; seq <= count; seq++)
|
|
2130
|
+
keys.push(`${prefix}/${docId}#${seq}`);
|
|
2131
|
+
}
|
|
2132
|
+
if (keys.length === 0) {
|
|
2133
|
+
return docIds.map(() => []);
|
|
2134
|
+
}
|
|
2135
|
+
let values;
|
|
2136
|
+
try {
|
|
2137
|
+
values = await store.getMany(DOC_DELTA_CACHE_TYPE, keys);
|
|
2138
|
+
}
|
|
2139
|
+
catch (e) {
|
|
2140
|
+
// Without its deltas the base is an older, still consistent state.
|
|
2141
|
+
this.logger.warn(`Reading L2 deltas failed; using base records only: ${e}`);
|
|
2142
|
+
return docIds.map(() => []);
|
|
2143
|
+
}
|
|
2144
|
+
let offset = 0;
|
|
2145
|
+
return docIds.map((docId) => {
|
|
2146
|
+
const count = this.l2DeltaCounts.get(docId) ?? 0;
|
|
2147
|
+
const slice = values.slice(offset, offset + count);
|
|
2148
|
+
offset += count;
|
|
2149
|
+
return slice;
|
|
2150
|
+
});
|
|
1964
2151
|
}
|
|
1965
2152
|
/**
|
|
1966
2153
|
* Record that the L2 cache holds `docId` at `changeSeq` (with the given
|
|
@@ -1979,6 +2166,8 @@ class BaseMindooDB {
|
|
|
1979
2166
|
/** Forget everything known about the L2 record of `docId`. */
|
|
1980
2167
|
forgetL2Record(docId) {
|
|
1981
2168
|
this.lastFlushedDocState.delete(docId);
|
|
2169
|
+
this.l2Chains.delete(docId);
|
|
2170
|
+
this.setL2DeltaCount(docId, 0);
|
|
1982
2171
|
if (this.l2RecordChangeSeqs.delete(docId)) {
|
|
1983
2172
|
this.cacheMetaDirty = true;
|
|
1984
2173
|
this.cacheManager?.markDirty();
|
|
@@ -2021,6 +2210,10 @@ class BaseMindooDB {
|
|
|
2021
2210
|
if (this.l2RecordsTracked) {
|
|
2022
2211
|
checkpoint.l2Tracked = true;
|
|
2023
2212
|
}
|
|
2213
|
+
// Additive field: older readers ignore it and read v3 records not at all.
|
|
2214
|
+
if (this.l2DeltaCounts.size > 0) {
|
|
2215
|
+
checkpoint.l2DeltaCounts = Object.fromEntries(this.l2DeltaCounts);
|
|
2216
|
+
}
|
|
2024
2217
|
// Persist the KeyBag fingerprint observed at the last reconciliation
|
|
2025
2218
|
// so the next restore can decide whether to skip the visibility
|
|
2026
2219
|
// metadata scan. `null` is acceptable - older checkpoints simply
|
|
@@ -2092,6 +2285,15 @@ class BaseMindooDB {
|
|
|
2092
2285
|
}
|
|
2093
2286
|
}
|
|
2094
2287
|
}
|
|
2288
|
+
this.l2DeltaCounts.clear();
|
|
2289
|
+
this.l2Chains.clear();
|
|
2290
|
+
if (checkpoint.l2DeltaCounts && typeof checkpoint.l2DeltaCounts === "object") {
|
|
2291
|
+
for (const [docId, count] of Object.entries(checkpoint.l2DeltaCounts)) {
|
|
2292
|
+
if (typeof count === "number" && Number.isInteger(count) && count > 0) {
|
|
2293
|
+
this.l2DeltaCounts.set(docId, Math.min(count, L2_DELTA_MAX_COUNT));
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2095
2297
|
this.lastReconciledKeyBagFingerprint =
|
|
2096
2298
|
typeof checkpoint.keyBagFingerprint === "string"
|
|
2097
2299
|
? checkpoint.keyBagFingerprint
|
|
@@ -2237,6 +2439,15 @@ class BaseMindooDB {
|
|
|
2237
2439
|
}
|
|
2238
2440
|
}
|
|
2239
2441
|
}
|
|
2442
|
+
if (this.l2DeltaCounts.size > 0) {
|
|
2443
|
+
const ownedDocIds = new Set(allOwnedKeys.map((key) => key.slice(docPrefix.length)));
|
|
2444
|
+
for (const docId of Array.from(this.l2DeltaCounts.keys())) {
|
|
2445
|
+
if (!ownedDocIds.has(docId)) {
|
|
2446
|
+
this.setL2DeltaCount(docId, 0);
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
await this.dropUnlistedL2Deltas(store, docPrefix, allOwnedKeys);
|
|
2240
2451
|
if (this.restoreToL2) {
|
|
2241
2452
|
// L2-only restore: leave L1 empty; let lazy reads via
|
|
2242
2453
|
// tryLoadFromL2 promote individual docs as they are needed. We
|
|
@@ -2262,6 +2473,7 @@ class BaseMindooDB {
|
|
|
2262
2473
|
}
|
|
2263
2474
|
const batch = targetKeys.slice(offset, offset + this.cacheRestoreBatchSize);
|
|
2264
2475
|
const batchValues = await store.getMany("doc", batch);
|
|
2476
|
+
const batchDeltas = await this.readL2Deltas(store, batch.map((key) => key.slice(docPrefix.length)));
|
|
2265
2477
|
for (let i = 0; i < batch.length; i++) {
|
|
2266
2478
|
if (restoredDocs >= this.cacheRestoreLimit) {
|
|
2267
2479
|
break;
|
|
@@ -2270,7 +2482,7 @@ class BaseMindooDB {
|
|
|
2270
2482
|
if (!docBytes)
|
|
2271
2483
|
continue;
|
|
2272
2484
|
try {
|
|
2273
|
-
const deserialized = this.deserializeDoc(docBytes);
|
|
2485
|
+
const deserialized = this.deserializeDoc(docBytes, batchDeltas[i]);
|
|
2274
2486
|
if (deserialized === null) {
|
|
2275
2487
|
skippedLegacyDocs++;
|
|
2276
2488
|
continue;
|
|
@@ -2285,11 +2497,12 @@ class BaseMindooDB {
|
|
|
2285
2497
|
const canRead = await this.tenant.hasDecryptionKey(deserialized.internal.decryptionKeyId);
|
|
2286
2498
|
if (!canRead) {
|
|
2287
2499
|
const docId = batch[i].slice(docPrefix.length);
|
|
2288
|
-
await
|
|
2500
|
+
await this.deleteL2Record(store, docId);
|
|
2289
2501
|
this.docCache.delete(docId);
|
|
2290
2502
|
this.forgetL2Record(docId);
|
|
2291
2503
|
continue;
|
|
2292
2504
|
}
|
|
2505
|
+
this.adoptL2Chain(deserialized);
|
|
2293
2506
|
// Legacy checkpoints lack the per-doc L2 state; the header
|
|
2294
2507
|
// just read provides it for free.
|
|
2295
2508
|
if (!this.l2RecordChangeSeqs.has(deserialized.internal.id)) {
|
|
@@ -2335,15 +2548,91 @@ class BaseMindooDB {
|
|
|
2335
2548
|
amBinary: value.slice(4 + headerLen),
|
|
2336
2549
|
};
|
|
2337
2550
|
}
|
|
2338
|
-
deserializeDoc(value) {
|
|
2339
|
-
const { header, amBinary } = this.parseDocCacheRecord(value);
|
|
2340
|
-
if (
|
|
2551
|
+
deserializeDoc(value, deltas = []) {
|
|
2552
|
+
const { header: baseHeader, amBinary } = this.parseDocCacheRecord(value);
|
|
2553
|
+
if (!READABLE_DOC_CACHE_HEADER_VERSIONS.has(baseHeader.version)) {
|
|
2341
2554
|
// v1 records (no `version`) and unknown future versions: skip
|
|
2342
2555
|
// gracefully so they get re-flushed with the current header on
|
|
2343
2556
|
// the next dirty cycle.
|
|
2344
2557
|
return null;
|
|
2345
2558
|
}
|
|
2346
|
-
|
|
2559
|
+
// Deltas of this base, in order; the first missing, foreign or
|
|
2560
|
+
// unreadable one ends the chain (a crash may have cut it short).
|
|
2561
|
+
let header = baseHeader;
|
|
2562
|
+
const gen = typeof baseHeader.gen === "string" ? baseHeader.gen : null;
|
|
2563
|
+
const parsed = [];
|
|
2564
|
+
if (gen) {
|
|
2565
|
+
for (const bytes of deltas) {
|
|
2566
|
+
if (!bytes)
|
|
2567
|
+
break;
|
|
2568
|
+
let delta;
|
|
2569
|
+
try {
|
|
2570
|
+
delta = this.parseDocCacheRecord(bytes);
|
|
2571
|
+
}
|
|
2572
|
+
catch {
|
|
2573
|
+
break;
|
|
2574
|
+
}
|
|
2575
|
+
if (delta.header.kind !== "delta" ||
|
|
2576
|
+
delta.header.gen !== gen ||
|
|
2577
|
+
delta.header.seq !== parsed.length + 1 ||
|
|
2578
|
+
!READABLE_DOC_CACHE_HEADER_VERSIONS.has(delta.header.version)) {
|
|
2579
|
+
break;
|
|
2580
|
+
}
|
|
2581
|
+
parsed.push(delta);
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
// Base and deltas in one Automerge.load (a saved document followed by
|
|
2585
|
+
// change chunks): faster than loadIncremental, which on large texts
|
|
2586
|
+
// costs about as much again as the load itself. If that fails, load the
|
|
2587
|
+
// base and apply the deltas one by one, keeping the last state that
|
|
2588
|
+
// loaded.
|
|
2589
|
+
let doc = null;
|
|
2590
|
+
let applied = 0;
|
|
2591
|
+
if (parsed.length > 0) {
|
|
2592
|
+
try {
|
|
2593
|
+
const joined = new Uint8Array(amBinary.byteLength + parsed.reduce((n, d) => n + d.amBinary.byteLength, 0));
|
|
2594
|
+
joined.set(amBinary, 0);
|
|
2595
|
+
let offset = amBinary.byteLength;
|
|
2596
|
+
for (const d of parsed) {
|
|
2597
|
+
joined.set(d.amBinary, offset);
|
|
2598
|
+
offset += d.amBinary.byteLength;
|
|
2599
|
+
}
|
|
2600
|
+
doc = automerge_adapter_1.Automerge.load(joined);
|
|
2601
|
+
applied = parsed.length;
|
|
2602
|
+
}
|
|
2603
|
+
catch {
|
|
2604
|
+
doc = null;
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
if (!doc) {
|
|
2608
|
+
doc = automerge_adapter_1.Automerge.load(amBinary);
|
|
2609
|
+
if (applied === 0) {
|
|
2610
|
+
for (const d of parsed) {
|
|
2611
|
+
try {
|
|
2612
|
+
if (d.amBinary.byteLength > 0) {
|
|
2613
|
+
doc = automerge_adapter_1.Automerge.loadIncremental(doc, d.amBinary);
|
|
2614
|
+
}
|
|
2615
|
+
applied++;
|
|
2616
|
+
}
|
|
2617
|
+
catch {
|
|
2618
|
+
break;
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
let deltaBytes = 0;
|
|
2624
|
+
for (let i = 0; i < applied; i++)
|
|
2625
|
+
deltaBytes += parsed[i].amBinary.byteLength;
|
|
2626
|
+
if (applied > 0) {
|
|
2627
|
+
header = parsed[applied - 1].header;
|
|
2628
|
+
// The heads the last delta records must be what loaded.
|
|
2629
|
+
const heads = automerge_adapter_1.Automerge.getHeads(doc);
|
|
2630
|
+
if (!Array.isArray(header.automergeHeads) ||
|
|
2631
|
+
header.automergeHeads.length !== heads.length ||
|
|
2632
|
+
!header.automergeHeads.every((h) => heads.includes(h))) {
|
|
2633
|
+
throw new Error("L2 delta chain does not reach the heads it records");
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2347
2636
|
const internal = {
|
|
2348
2637
|
id: header.id,
|
|
2349
2638
|
doc,
|
|
@@ -2362,8 +2651,38 @@ class BaseMindooDB {
|
|
|
2362
2651
|
persistedHeads: Array.isArray(header.automergeHeads)
|
|
2363
2652
|
? header.automergeHeads
|
|
2364
2653
|
: [],
|
|
2654
|
+
chain: gen
|
|
2655
|
+
? {
|
|
2656
|
+
gen,
|
|
2657
|
+
heads: automerge_adapter_1.Automerge.getHeads(doc),
|
|
2658
|
+
count: applied,
|
|
2659
|
+
deltaBytes,
|
|
2660
|
+
baseBytes: amBinary.byteLength,
|
|
2661
|
+
compactDue: applied > 0,
|
|
2662
|
+
}
|
|
2663
|
+
: null,
|
|
2365
2664
|
};
|
|
2366
2665
|
}
|
|
2666
|
+
/**
|
|
2667
|
+
* Continue the L2 record chain just read: the next flush appends to it
|
|
2668
|
+
* (deltas past the ones that applied are overwritten, not read), or, when
|
|
2669
|
+
* it had deltas, compacts it into a full record.
|
|
2670
|
+
*/
|
|
2671
|
+
adoptL2Chain(deserialized) {
|
|
2672
|
+
const docId = deserialized.internal.id;
|
|
2673
|
+
if (deserialized.chain) {
|
|
2674
|
+
this.l2Chains.set(docId, deserialized.chain);
|
|
2675
|
+
this.setL2DeltaCount(docId, deserialized.chain.count);
|
|
2676
|
+
if (deserialized.chain.compactDue) {
|
|
2677
|
+
// Rewrite in full on the next flush (see L2DeltaChain.compactDue).
|
|
2678
|
+
this.markDocDirty(docId);
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
else {
|
|
2682
|
+
this.l2Chains.delete(docId);
|
|
2683
|
+
this.setL2DeltaCount(docId, 0);
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2367
2686
|
/**
|
|
2368
2687
|
* Get or import a CryptoKey for signature verification, with caching.
|
|
2369
2688
|
* This avoids re-importing the same public key multiple times.
|
|
@@ -3116,6 +3435,7 @@ class BaseMindooDB {
|
|
|
3116
3435
|
* path that triggered the purge.
|
|
3117
3436
|
*/
|
|
3118
3437
|
async purgeMaterializedDocument(docId) {
|
|
3438
|
+
const l2Deltas = this.l2DeltaCounts.get(docId) ?? 0;
|
|
3119
3439
|
this.docCache.delete(docId);
|
|
3120
3440
|
this.dirtyDocIds.delete(docId);
|
|
3121
3441
|
this.forgetL2Record(docId);
|
|
@@ -3128,7 +3448,9 @@ class BaseMindooDB {
|
|
|
3128
3448
|
const store = this.cacheManager?.getStore();
|
|
3129
3449
|
if (store) {
|
|
3130
3450
|
try {
|
|
3131
|
-
|
|
3451
|
+
const key = `${this.getCachePrefix()}/${docId}`;
|
|
3452
|
+
await store.delete("doc", key);
|
|
3453
|
+
await this.deleteL2Deltas(store, key, l2Deltas);
|
|
3132
3454
|
}
|
|
3133
3455
|
catch (error) {
|
|
3134
3456
|
// Best-effort: failure to evict the L2 record only means a stale
|
|
@@ -3589,6 +3911,8 @@ class BaseMindooDB {
|
|
|
3589
3911
|
this.docCache.clear();
|
|
3590
3912
|
this.lastFlushedDocState.clear();
|
|
3591
3913
|
this.l2RecordChangeSeqs.clear();
|
|
3914
|
+
this.l2Chains.clear();
|
|
3915
|
+
this.l2DeltaCounts.clear();
|
|
3592
3916
|
this.automergeHashToEntryId.clear();
|
|
3593
3917
|
this.clearScannedEntryMetadata();
|
|
3594
3918
|
this.processedEntryIds = [];
|
|
@@ -11573,12 +11897,13 @@ class BaseMindooDB {
|
|
|
11573
11897
|
return null;
|
|
11574
11898
|
let deserialized;
|
|
11575
11899
|
try {
|
|
11576
|
-
|
|
11900
|
+
const [deltas] = await this.readL2Deltas(store, [docId]);
|
|
11901
|
+
deserialized = this.deserializeDoc(bytes, deltas);
|
|
11577
11902
|
}
|
|
11578
11903
|
catch (e) {
|
|
11579
11904
|
this.logger.warn(`L2 deserialize failed for ${docId}, evicting stale record: ${e}`);
|
|
11580
11905
|
try {
|
|
11581
|
-
await
|
|
11906
|
+
await this.deleteL2Record(store, docId);
|
|
11582
11907
|
this.forgetL2Record(docId);
|
|
11583
11908
|
}
|
|
11584
11909
|
catch (deleteError) {
|
|
@@ -11587,7 +11912,7 @@ class BaseMindooDB {
|
|
|
11587
11912
|
return null;
|
|
11588
11913
|
}
|
|
11589
11914
|
if (deserialized === null) {
|
|
11590
|
-
// Legacy v1 record - fall through; the full path will rewrite a
|
|
11915
|
+
// Legacy v1 record - fall through; the full path will rewrite a v3 record.
|
|
11591
11916
|
return null;
|
|
11592
11917
|
}
|
|
11593
11918
|
const { internal, persistedChangeSeq } = deserialized;
|
|
@@ -11605,7 +11930,7 @@ class BaseMindooDB {
|
|
|
11605
11930
|
// ahead of the index (very rare race during initial restore) or the
|
|
11606
11931
|
// L2 record is orphaned. Drop and fall through.
|
|
11607
11932
|
try {
|
|
11608
|
-
await
|
|
11933
|
+
await this.deleteL2Record(store, docId);
|
|
11609
11934
|
this.forgetL2Record(docId);
|
|
11610
11935
|
}
|
|
11611
11936
|
catch (deleteError) {
|
|
@@ -11614,6 +11939,8 @@ class BaseMindooDB {
|
|
|
11614
11939
|
return null;
|
|
11615
11940
|
}
|
|
11616
11941
|
const currentChangeSeq = this.index[indexEntryIdx].changeSeq;
|
|
11942
|
+
// Later flushes of this document append to the record chain just read.
|
|
11943
|
+
this.adoptL2Chain(deserialized);
|
|
11617
11944
|
// Fresh hit: index agrees with the persisted state.
|
|
11618
11945
|
if (persistedChangeSeq === currentChangeSeq) {
|
|
11619
11946
|
// Seed the flush-skip fingerprint with the state just read from L2 so
|
|
@@ -11990,7 +12317,9 @@ class BaseMindooDB {
|
|
|
11990
12317
|
return false;
|
|
11991
12318
|
}
|
|
11992
12319
|
const { header } = this.parseDocCacheRecord(bytes);
|
|
11993
|
-
if (header.version
|
|
12320
|
+
if (!READABLE_DOC_CACHE_HEADER_VERSIONS.has(header.version) ||
|
|
12321
|
+
// With deltas the base header is older than the record.
|
|
12322
|
+
(this.l2DeltaCounts.get(docId) ?? 0) > 0 ||
|
|
11994
12323
|
header.changeSeq !== currentChangeSeq ||
|
|
11995
12324
|
!Array.isArray(header.automergeHeads)) {
|
|
11996
12325
|
return false;
|
|
@@ -12345,11 +12674,17 @@ class BaseMindooDB {
|
|
|
12345
12674
|
const stale = [];
|
|
12346
12675
|
const activeSpecs = [];
|
|
12347
12676
|
const activeLabels = [];
|
|
12677
|
+
// A member removed and added again keeps the removed entry with the same key:
|
|
12678
|
+
// that key is wrapped for the active entry, not stale.
|
|
12679
|
+
const activeFingerprints = new Set(Object.values(map)
|
|
12680
|
+
.filter((entry) => !entry.removedAt && entry.keyFingerprint)
|
|
12681
|
+
.map((entry) => entry.keyFingerprint));
|
|
12348
12682
|
for (const [id, entry] of Object.entries(map)) {
|
|
12349
12683
|
const label = entry.label ?? id;
|
|
12350
12684
|
if (entry.removedAt) {
|
|
12351
|
-
if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
|
|
12685
|
+
if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint) && !activeFingerprints.has(entry.keyFingerprint)) {
|
|
12352
12686
|
stale.push(label);
|
|
12687
|
+
}
|
|
12353
12688
|
continue;
|
|
12354
12689
|
}
|
|
12355
12690
|
if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
|