mindoodb 0.2.1 → 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.
Files changed (69) hide show
  1. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts +2 -0
  2. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts.map +1 -1
  3. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js +13 -2
  4. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js.map +1 -1
  5. package/dist/browser/index.mjs +4 -0
  6. package/dist/cloudflare/MindooDatabaseObject.d.ts +7 -0
  7. package/dist/cloudflare/MindooDatabaseObject.d.ts.map +1 -1
  8. package/dist/cloudflare/MindooDatabaseObject.js +52 -3
  9. package/dist/cloudflare/MindooDatabaseObject.js.map +1 -1
  10. package/dist/cloudflare/MindooServerObject.d.ts +2 -0
  11. package/dist/cloudflare/MindooServerObject.d.ts.map +1 -1
  12. package/dist/cloudflare/MindooServerObject.js +22 -1
  13. package/dist/cloudflare/MindooServerObject.js.map +1 -1
  14. package/dist/cloudflare/http.d.ts +10 -0
  15. package/dist/cloudflare/http.d.ts.map +1 -1
  16. package/dist/cloudflare/http.js +21 -2
  17. package/dist/cloudflare/http.js.map +1 -1
  18. package/dist/cloudflare/types.d.ts +6 -0
  19. package/dist/cloudflare/types.d.ts.map +1 -1
  20. package/dist/cloudflare/worker.d.ts.map +1 -1
  21. package/dist/cloudflare/worker.js +21 -0
  22. package/dist/cloudflare/worker.js.map +1 -1
  23. package/dist/core/BaseMindooDB.d.ts +81 -1
  24. package/dist/core/BaseMindooDB.d.ts.map +1 -1
  25. package/dist/core/BaseMindooDB.js +568 -28
  26. package/dist/core/BaseMindooDB.js.map +1 -1
  27. package/dist/core/BaseMindooTenantDirectory.d.ts +2 -0
  28. package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
  29. package/dist/core/BaseMindooTenantDirectory.js +7 -1
  30. package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
  31. package/dist/core/applyChangesInSlices.d.ts +18 -5
  32. package/dist/core/applyChangesInSlices.d.ts.map +1 -1
  33. package/dist/core/applyChangesInSlices.js +31 -18
  34. package/dist/core/applyChangesInSlices.js.map +1 -1
  35. package/dist/core/documentLoadGuard.d.ts +41 -5
  36. package/dist/core/documentLoadGuard.d.ts.map +1 -1
  37. package/dist/core/documentLoadGuard.js +70 -7
  38. package/dist/core/documentLoadGuard.js.map +1 -1
  39. package/dist/core/errors.d.ts +5 -0
  40. package/dist/core/errors.d.ts.map +1 -1
  41. package/dist/core/errors.js +9 -0
  42. package/dist/core/errors.js.map +1 -1
  43. package/dist/core/index.d.ts +4 -3
  44. package/dist/core/index.d.ts.map +1 -1
  45. package/dist/core/index.js +10 -5
  46. package/dist/core/index.js.map +1 -1
  47. package/dist/core/live/LiveChannel.d.ts +5 -0
  48. package/dist/core/live/LiveChannel.d.ts.map +1 -1
  49. package/dist/core/live/LiveChannel.js +4 -2
  50. package/dist/core/live/LiveChannel.js.map +1 -1
  51. package/dist/core/personalShares.d.ts +10 -0
  52. package/dist/core/personalShares.d.ts.map +1 -1
  53. package/dist/core/personalShares.js +12 -1
  54. package/dist/core/personalShares.js.map +1 -1
  55. package/dist/core/types.d.ts +29 -0
  56. package/dist/core/types.d.ts.map +1 -1
  57. package/dist/core/types.js.map +1 -1
  58. package/dist/core/userkeys/scopedSealedKeys.d.ts +12 -0
  59. package/dist/core/userkeys/scopedSealedKeys.d.ts.map +1 -0
  60. package/dist/core/userkeys/scopedSealedKeys.js +65 -0
  61. package/dist/core/userkeys/scopedSealedKeys.js.map +1 -0
  62. package/dist/server/DeviceDiscoveryService.d.ts +19 -0
  63. package/dist/server/DeviceDiscoveryService.d.ts.map +1 -1
  64. package/dist/server/DeviceDiscoveryService.js +24 -19
  65. package/dist/server/DeviceDiscoveryService.js.map +1 -1
  66. package/dist/server/TenantManager.d.ts.map +1 -1
  67. package/dist/server/TenantManager.js +3 -0
  68. package/dist/server/TenantManager.js.map +1 -1
  69. package/package.json +1 -1
@@ -27,6 +27,7 @@ const purgeDocumentHistory_1 = require("./appendonlystores/purgeDocumentHistory"
27
27
  const idGeneration_1 = require("./utils/idGeneration");
28
28
  const timeSource_1 = require("./utils/timeSource");
29
29
  const errors_1 = require("./errors");
30
+ const scopedSealedKeys_1 = require("./userkeys/scopedSealedKeys");
30
31
  const EntrySignature_1 = require("./crypto/EntrySignature");
31
32
  const copyDocument_1 = require("./copy/copyDocument");
32
33
  const copyDocuments_1 = require("./copy/copyDocuments");
@@ -158,11 +159,50 @@ const DEFAULT_WARMER_SCHEDULER = {
158
159
  * touching the document store, and apply only missing changes when
159
160
  * stale (see Phase 1c of the L1/L2 cache plan).
160
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
+ *
161
173
  * v1 records are silently ignored on restore - the next read of that
162
174
  * doc falls through to the normal materialization path and re-flushes
163
- * with a v2 header.
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.
164
190
  */
165
- const DOC_CACHE_HEADER_VERSION = 2;
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
+ }
166
206
  /**
167
207
  * How many quarantine records one document keeps in the audit log.
168
208
  *
@@ -594,6 +634,15 @@ class BaseMindooDB {
594
634
  * the store, as on any L2 miss.
595
635
  */
596
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();
597
646
  /** L2 records fetched in one batch for a prefetch window (consumed by tryLoadFromL2). */
598
647
  this.l2Prefetched = new Map();
599
648
  /**
@@ -671,7 +720,10 @@ class BaseMindooDB {
671
720
  if (attachmentStore.getStoreKind() !== types_4.StoreKind.attachments) {
672
721
  throw new Error(`[BaseMindooDB] Expected attachment store kind ${types_4.StoreKind.attachments} but received ${attachmentStore.getStoreKind()}`);
673
722
  }
674
- this.tenant = tenant;
723
+ // Sealed key series are named after a document id, which is unique per
724
+ // database only: keep this database's series apart in the session cache.
725
+ this.ownerTenant = tenant;
726
+ this.tenant = (0, scopedSealedKeys_1.withScopedSealedKeys)(tenant, store.getId());
675
727
  this.store = store;
676
728
  this.attachmentStore = attachmentStore;
677
729
  this.chunkSizeBytes =
@@ -1932,11 +1984,12 @@ class BaseMindooDB {
1932
1984
  // Skip the Automerge.save + L2 write when the exact same state was
1933
1985
  // already flushed (docs marked dirty by a load rather than a change).
1934
1986
  const flushKey = `${changeSeq}:${automergeHeads.join(",")}`;
1935
- if (this.lastFlushedDocState.get(docId) === flushKey) {
1987
+ if (this.lastFlushedDocState.get(docId) === flushKey &&
1988
+ !this.l2Chains.get(docId)?.compactDue) {
1936
1989
  return;
1937
1990
  }
1938
- const amBinary = automerge_adapter_1.Automerge.save(internal.doc);
1939
- const header = JSON.stringify({
1991
+ const key = `${prefix}/${docId}`;
1992
+ const header = {
1940
1993
  version: DOC_CACHE_HEADER_VERSION,
1941
1994
  id: internal.id,
1942
1995
  createdAt: internal.createdAt,
@@ -1947,16 +2000,154 @@ class BaseMindooDB {
1947
2000
  witnessed: internal.witnessed ?? false,
1948
2001
  changeSeq,
1949
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,
1950
2028
  });
1951
- const headerBytes = new TextEncoder().encode(header);
1952
- // Format: 4-byte header length (big-endian) + header JSON + Automerge binary
1953
- const value = new Uint8Array(4 + headerBytes.length + amBinary.length);
1954
- const view = new DataView(value.buffer);
1955
- view.setUint32(0, headerBytes.length, false);
1956
- value.set(headerBytes, 4);
1957
- value.set(amBinary, 4 + headerBytes.length);
1958
- await store.put("doc", `${prefix}/${docId}`, value);
2029
+ this.setL2DeltaCount(docId, 0);
1959
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
+ });
1960
2151
  }
1961
2152
  /**
1962
2153
  * Record that the L2 cache holds `docId` at `changeSeq` (with the given
@@ -1975,6 +2166,8 @@ class BaseMindooDB {
1975
2166
  /** Forget everything known about the L2 record of `docId`. */
1976
2167
  forgetL2Record(docId) {
1977
2168
  this.lastFlushedDocState.delete(docId);
2169
+ this.l2Chains.delete(docId);
2170
+ this.setL2DeltaCount(docId, 0);
1978
2171
  if (this.l2RecordChangeSeqs.delete(docId)) {
1979
2172
  this.cacheMetaDirty = true;
1980
2173
  this.cacheManager?.markDirty();
@@ -2017,6 +2210,10 @@ class BaseMindooDB {
2017
2210
  if (this.l2RecordsTracked) {
2018
2211
  checkpoint.l2Tracked = true;
2019
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
+ }
2020
2217
  // Persist the KeyBag fingerprint observed at the last reconciliation
2021
2218
  // so the next restore can decide whether to skip the visibility
2022
2219
  // metadata scan. `null` is acceptable - older checkpoints simply
@@ -2088,6 +2285,15 @@ class BaseMindooDB {
2088
2285
  }
2089
2286
  }
2090
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
+ }
2091
2297
  this.lastReconciledKeyBagFingerprint =
2092
2298
  typeof checkpoint.keyBagFingerprint === "string"
2093
2299
  ? checkpoint.keyBagFingerprint
@@ -2233,6 +2439,15 @@ class BaseMindooDB {
2233
2439
  }
2234
2440
  }
2235
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);
2236
2451
  if (this.restoreToL2) {
2237
2452
  // L2-only restore: leave L1 empty; let lazy reads via
2238
2453
  // tryLoadFromL2 promote individual docs as they are needed. We
@@ -2258,6 +2473,7 @@ class BaseMindooDB {
2258
2473
  }
2259
2474
  const batch = targetKeys.slice(offset, offset + this.cacheRestoreBatchSize);
2260
2475
  const batchValues = await store.getMany("doc", batch);
2476
+ const batchDeltas = await this.readL2Deltas(store, batch.map((key) => key.slice(docPrefix.length)));
2261
2477
  for (let i = 0; i < batch.length; i++) {
2262
2478
  if (restoredDocs >= this.cacheRestoreLimit) {
2263
2479
  break;
@@ -2266,7 +2482,7 @@ class BaseMindooDB {
2266
2482
  if (!docBytes)
2267
2483
  continue;
2268
2484
  try {
2269
- const deserialized = this.deserializeDoc(docBytes);
2485
+ const deserialized = this.deserializeDoc(docBytes, batchDeltas[i]);
2270
2486
  if (deserialized === null) {
2271
2487
  skippedLegacyDocs++;
2272
2488
  continue;
@@ -2281,11 +2497,12 @@ class BaseMindooDB {
2281
2497
  const canRead = await this.tenant.hasDecryptionKey(deserialized.internal.decryptionKeyId);
2282
2498
  if (!canRead) {
2283
2499
  const docId = batch[i].slice(docPrefix.length);
2284
- await store.delete("doc", batch[i]);
2500
+ await this.deleteL2Record(store, docId);
2285
2501
  this.docCache.delete(docId);
2286
2502
  this.forgetL2Record(docId);
2287
2503
  continue;
2288
2504
  }
2505
+ this.adoptL2Chain(deserialized);
2289
2506
  // Legacy checkpoints lack the per-doc L2 state; the header
2290
2507
  // just read provides it for free.
2291
2508
  if (!this.l2RecordChangeSeqs.has(deserialized.internal.id)) {
@@ -2331,15 +2548,91 @@ class BaseMindooDB {
2331
2548
  amBinary: value.slice(4 + headerLen),
2332
2549
  };
2333
2550
  }
2334
- deserializeDoc(value) {
2335
- const { header, amBinary } = this.parseDocCacheRecord(value);
2336
- if (header.version !== DOC_CACHE_HEADER_VERSION) {
2551
+ deserializeDoc(value, deltas = []) {
2552
+ const { header: baseHeader, amBinary } = this.parseDocCacheRecord(value);
2553
+ if (!READABLE_DOC_CACHE_HEADER_VERSIONS.has(baseHeader.version)) {
2337
2554
  // v1 records (no `version`) and unknown future versions: skip
2338
2555
  // gracefully so they get re-flushed with the current header on
2339
2556
  // the next dirty cycle.
2340
2557
  return null;
2341
2558
  }
2342
- const doc = automerge_adapter_1.Automerge.load(amBinary);
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
+ }
2343
2636
  const internal = {
2344
2637
  id: header.id,
2345
2638
  doc,
@@ -2358,8 +2651,38 @@ class BaseMindooDB {
2358
2651
  persistedHeads: Array.isArray(header.automergeHeads)
2359
2652
  ? header.automergeHeads
2360
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,
2361
2664
  };
2362
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
+ }
2363
2686
  /**
2364
2687
  * Get or import a CryptoKey for signature verification, with caching.
2365
2688
  * This avoids re-importing the same public key multiple times.
@@ -3112,6 +3435,7 @@ class BaseMindooDB {
3112
3435
  * path that triggered the purge.
3113
3436
  */
3114
3437
  async purgeMaterializedDocument(docId) {
3438
+ const l2Deltas = this.l2DeltaCounts.get(docId) ?? 0;
3115
3439
  this.docCache.delete(docId);
3116
3440
  this.dirtyDocIds.delete(docId);
3117
3441
  this.forgetL2Record(docId);
@@ -3124,7 +3448,9 @@ class BaseMindooDB {
3124
3448
  const store = this.cacheManager?.getStore();
3125
3449
  if (store) {
3126
3450
  try {
3127
- await store.delete("doc", `${this.getCachePrefix()}/${docId}`);
3451
+ const key = `${this.getCachePrefix()}/${docId}`;
3452
+ await store.delete("doc", key);
3453
+ await this.deleteL2Deltas(store, key, l2Deltas);
3128
3454
  }
3129
3455
  catch (error) {
3130
3456
  // Best-effort: failure to evict the L2 record only means a stale
@@ -3585,6 +3911,8 @@ class BaseMindooDB {
3585
3911
  this.docCache.clear();
3586
3912
  this.lastFlushedDocState.clear();
3587
3913
  this.l2RecordChangeSeqs.clear();
3914
+ this.l2Chains.clear();
3915
+ this.l2DeltaCounts.clear();
3588
3916
  this.automergeHashToEntryId.clear();
3589
3917
  this.clearScannedEntryMetadata();
3590
3918
  this.processedEntryIds = [];
@@ -4459,7 +4787,7 @@ class BaseMindooDB {
4459
4787
  return result;
4460
4788
  }
4461
4789
  getTenant() {
4462
- return this.tenant;
4790
+ return this.ownerTenant;
4463
4791
  }
4464
4792
  async createDocument(options) {
4465
4793
  return this.createDocumentInternal(options ?? {});
@@ -7989,6 +8317,147 @@ class BaseMindooDB {
7989
8317
  async deleteDocument(docId, options = {}) {
7990
8318
  return this.deleteDocInternal(docId, options.signingKeyPair, options.signingKeyPassword, options.bypassAccessControlPrecheck, options.attribution);
7991
8319
  }
8320
+ /**
8321
+ * The signed and decrypted Automerge changes of a document, without loading
8322
+ * it: every `doc_create`, `doc_change`, `doc_delete` and `doc_undelete` entry
8323
+ * whose signature verifies, decrypted, in store order. Snapshots are left
8324
+ * out, so nothing here has to be trusted beyond the signed entries.
8325
+ *
8326
+ * For documents this process refuses to load (`DocumentTooLargeError`):
8327
+ * hand the changes to an Automerge instance that may fail on its own, such
8328
+ * as one in a worker, to read the document there.
8329
+ *
8330
+ * Not available while the tenant enforces access control, where each change
8331
+ * is judged against the document state it produces. Returns `null` for an
8332
+ * unknown document.
8333
+ */
8334
+ async getDocumentPayloads(docId) {
8335
+ const allEntryMetadata = await this.scanAllMetadata(this.store, { docId });
8336
+ if (allEntryMetadata.length === 0)
8337
+ return null;
8338
+ await this.ingestSealedKeyFromEntries(allEntryMetadata);
8339
+ if (await this.isAclEnforced()) {
8340
+ throw new Error(`Document ${docId} cannot be read without loading it while access control is enforced`);
8341
+ }
8342
+ const replay = allEntryMetadata
8343
+ .filter((meta) => this.isDocumentReplayEntry(meta))
8344
+ .sort((a, b) => (a.receivedAt ?? a.createdAt) === (b.receivedAt ?? b.createdAt)
8345
+ ? a.id.localeCompare(b.id)
8346
+ : (a.receivedAt ?? a.createdAt) - (b.receivedAt ?? b.createdAt));
8347
+ const fetched = await this.fetchEntries(replay.map((meta) => meta.id));
8348
+ const byId = new Map(fetched.map((entry) => [entry.id, entry]));
8349
+ const changes = [];
8350
+ let decryptionKeyId = null;
8351
+ for (const meta of replay) {
8352
+ const entry = byId.get(meta.id);
8353
+ if (!entry)
8354
+ continue;
8355
+ if (await this.shouldSkipLoadedEntryForBuiltin(entry))
8356
+ continue;
8357
+ if (!(await this.verifyEntrySignatureForDb(entry, entry.encryptedData))) {
8358
+ this.logger.warn(`Invalid signature for entry ${entry.id}, skipping`);
8359
+ continue;
8360
+ }
8361
+ changes.push(await this.tenant.decryptPayload(entry.encryptedData, entry.decryptionKeyId));
8362
+ if (meta.entryType === "doc_create" || decryptionKeyId === null) {
8363
+ decryptionKeyId = entry.decryptionKeyId;
8364
+ }
8365
+ }
8366
+ if (changes.length === 0)
8367
+ return null;
8368
+ return {
8369
+ docId,
8370
+ changes,
8371
+ decryptionKeyId: decryptionKeyId ?? replay[0].decryptionKeyId,
8372
+ heads: this.replayHeads(replay),
8373
+ estimate: (0, documentLoadGuard_1.estimateDocumentLoad)(null, changes),
8374
+ };
8375
+ }
8376
+ /**
8377
+ * Deletes a document this process cannot load, from a lifecycle change built
8378
+ * elsewhere (see {@link getDocumentPayloads}): an Automerge change on top of
8379
+ * the document's current heads that touches nothing but `_lastModified` and
8380
+ * `_attachments` at the root, as `deleteDocument()` would write it. The
8381
+ * change is checked for exactly that before it is signed, encrypted and
8382
+ * stored as a `doc_delete` entry; the body stays in the history, as with
8383
+ * every delete.
8384
+ *
8385
+ * `documentUsernameHash` is the document's `username_hash` field, if any
8386
+ * (the built-in user databases decide who may delete by it).
8387
+ */
8388
+ async deleteDocumentWithChange(docId, lifecycleChange, options = {}) {
8389
+ this.assertWritable("deleteDocumentWithChange");
8390
+ const allEntryMetadata = await this.scanAllMetadata(this.store, { docId });
8391
+ const replay = allEntryMetadata.filter((meta) => this.isDocumentReplayEntry(meta));
8392
+ if (replay.length === 0)
8393
+ throw new errors_1.DocumentNotFoundError(docId);
8394
+ if (await this.isAclEnforced()) {
8395
+ throw new Error(`Document ${docId} cannot be deleted without loading it while access control is enforced`);
8396
+ }
8397
+ const latest = [...replay].sort((a, b) => a.createdAt - b.createdAt).at(-1);
8398
+ if (latest.entryType === "doc_delete")
8399
+ return; // already deleted
8400
+ const decoded = automerge_adapter_1.Automerge.decodeChange(lifecycleChange);
8401
+ const heads = this.replayHeads(replay);
8402
+ const deps = [...(decoded.deps ?? [])].sort();
8403
+ if (deps.length !== heads.length || deps.some((dep, index) => dep !== [...heads].sort()[index])) {
8404
+ throw new Error(`The delete change for ${docId} does not build on the document's current heads`);
8405
+ }
8406
+ const allowedKeys = new Set(["_lastModified", "_attachments"]);
8407
+ for (const op of decoded.ops ?? []) {
8408
+ if (op.obj !== "_root" || typeof op.key !== "string" || !allowedKeys.has(op.key)) {
8409
+ throw new Error(`The delete change for ${docId} touches more than _lastModified and _attachments`);
8410
+ }
8411
+ }
8412
+ await this.assertLifecycleMutationAllowed("doc_delete", undefined, undefined, options.documentUsernameHash ?? null, docId);
8413
+ const createMeta = replay.find((meta) => meta.entryType === "doc_create") ?? replay[0];
8414
+ const decryptionKeyId = createMeta.decryptionKeyId;
8415
+ const now = (0, timeSource_1.semanticNow)();
8416
+ const automergeHash = decoded.hash;
8417
+ const encryptedPayload = await this.tenant.encryptPayload(lifecycleChange, decryptionKeyId);
8418
+ const contentHash = await (0, idGeneration_1.computeContentHash)(encryptedPayload, this.getSubtle());
8419
+ const entryId = await (0, idGeneration_1.generateDocEntryId)(docId, automergeHash, decoded.deps ?? [], this.getSubtle());
8420
+ const dependencyIds = await this.ensureAutomergeDepsResolved(docId, decoded.deps ?? []);
8421
+ const currentUser = await this.tenant.getCurrentUserId();
8422
+ const signature = await this.tenant.signPayload(encryptedPayload);
8423
+ const entryMetadata = {
8424
+ entryType: "doc_delete",
8425
+ id: entryId,
8426
+ contentHash,
8427
+ docId,
8428
+ dependencyIds,
8429
+ createdAt: now,
8430
+ createdByPublicKey: currentUser.userSigningPublicKey,
8431
+ decryptionKeyId,
8432
+ signature,
8433
+ originalSize: lifecycleChange.length,
8434
+ encryptedSize: encryptedPayload.length,
8435
+ entryVersion: types_1.CURRENT_STORE_ENTRY_VERSION,
8436
+ };
8437
+ entryMetadata.metadataSignature = await this.computeEntryMetadataSignature(entryMetadata);
8438
+ await this.putLocalEntries([{ ...entryMetadata, encryptedData: encryptedPayload }]);
8439
+ this.registerAutomergeHashMapping(docId, automergeHash, entryId);
8440
+ this.docCache.delete(docId);
8441
+ this.dirtyDocIds.delete(docId);
8442
+ const awaitingWitness = (0, storeEntryTime_1.isProvisional)(entryMetadata);
8443
+ this.updateIndex(docId, now, true, decryptionKeyId, "visible", awaitingWitness, (0, storeEntryTime_1.isVersioned)(entryMetadata) && !awaitingWitness, true);
8444
+ this.cacheMetaDirty = true;
8445
+ this.cacheManager?.markDirty();
8446
+ this.logger.info(`Document ${docId} deleted from a prepared change`);
8447
+ }
8448
+ /** Automerge hashes of the replay entries nothing else depends on: the document's heads. */
8449
+ replayHeads(replay) {
8450
+ const dependedOn = new Set(replay.flatMap((meta) => meta.dependencyIds));
8451
+ const heads = [];
8452
+ for (const meta of replay) {
8453
+ if (dependedOn.has(meta.id))
8454
+ continue;
8455
+ const parsed = (0, idGeneration_1.parseDocEntryId)(meta.id);
8456
+ if (parsed)
8457
+ heads.push(parsed.automergeHash);
8458
+ }
8459
+ return heads;
8460
+ }
7992
8461
  /**
7993
8462
  * Bulk-delete documents in a single append-only store write.
7994
8463
  *
@@ -11158,6 +11627,49 @@ class BaseMindooDB {
11158
11627
  await prefetchFrom(i + 1);
11159
11628
  }
11160
11629
  catch (error) {
11630
+ if ((0, documentLoadGuard_1.isDocumentTooLargeError)(error)) {
11631
+ // Too large to load in this process (setDocumentLoadBudget): emit
11632
+ // it like an inaccessible document, so consumers (the summary
11633
+ // update behind every query) drop it and go on instead of failing
11634
+ // for every other document of the database.
11635
+ this.logger.warn(`Skipping document ${entry.docId}: ${error.message}`);
11636
+ yieldedDocuments++;
11637
+ yield {
11638
+ doc: this.buildInaccessibleDoc(entry),
11639
+ cursor: {
11640
+ changeSeq: entry.changeSeq,
11641
+ lastModified: entry.lastModified,
11642
+ docId: entry.docId,
11643
+ feedEpoch: this.changeFeedEpoch,
11644
+ },
11645
+ };
11646
+ await prefetchFrom(i + 1);
11647
+ continue;
11648
+ }
11649
+ if ((0, errors_1.isSymmetricKeyNotFound)(error)) {
11650
+ // The index holds the document as readable, but a key it needs is
11651
+ // not here (delegation per account: one group of the database is
11652
+ // shared with this user, another is not; a key series that arrives
11653
+ // only partly). Treat it like the missing-key case of the sync:
11654
+ // drop any plaintext, mark the entry inaccessible, so a key that
11655
+ // arrives later reveals it again, and emit an inaccessible
11656
+ // tombstone, so the summary, full-text and view updates go on with
11657
+ // the other documents instead of failing every query.
11658
+ this.logger.warn(`Skipping document ${entry.docId}: ${error.message}`);
11659
+ await this.markUndecryptableDocument(entry);
11660
+ yieldedDocuments++;
11661
+ yield {
11662
+ doc: this.buildInaccessibleDoc(entry),
11663
+ cursor: {
11664
+ changeSeq: entry.changeSeq,
11665
+ lastModified: entry.lastModified,
11666
+ docId: entry.docId,
11667
+ feedEpoch: this.changeFeedEpoch,
11668
+ },
11669
+ };
11670
+ await prefetchFrom(i + 1);
11671
+ continue;
11672
+ }
11161
11673
  this.logger.error(`Error processing document ${entry.docId}:`, error);
11162
11674
  // Stop processing on error
11163
11675
  throw error;
@@ -11385,12 +11897,13 @@ class BaseMindooDB {
11385
11897
  return null;
11386
11898
  let deserialized;
11387
11899
  try {
11388
- deserialized = this.deserializeDoc(bytes);
11900
+ const [deltas] = await this.readL2Deltas(store, [docId]);
11901
+ deserialized = this.deserializeDoc(bytes, deltas);
11389
11902
  }
11390
11903
  catch (e) {
11391
11904
  this.logger.warn(`L2 deserialize failed for ${docId}, evicting stale record: ${e}`);
11392
11905
  try {
11393
- await store.delete("doc", key);
11906
+ await this.deleteL2Record(store, docId);
11394
11907
  this.forgetL2Record(docId);
11395
11908
  }
11396
11909
  catch (deleteError) {
@@ -11399,7 +11912,7 @@ class BaseMindooDB {
11399
11912
  return null;
11400
11913
  }
11401
11914
  if (deserialized === null) {
11402
- // Legacy v1 record - fall through; the full path will rewrite a v2 record.
11915
+ // Legacy v1 record - fall through; the full path will rewrite a v3 record.
11403
11916
  return null;
11404
11917
  }
11405
11918
  const { internal, persistedChangeSeq } = deserialized;
@@ -11417,7 +11930,7 @@ class BaseMindooDB {
11417
11930
  // ahead of the index (very rare race during initial restore) or the
11418
11931
  // L2 record is orphaned. Drop and fall through.
11419
11932
  try {
11420
- await store.delete("doc", key);
11933
+ await this.deleteL2Record(store, docId);
11421
11934
  this.forgetL2Record(docId);
11422
11935
  }
11423
11936
  catch (deleteError) {
@@ -11426,6 +11939,8 @@ class BaseMindooDB {
11426
11939
  return null;
11427
11940
  }
11428
11941
  const currentChangeSeq = this.index[indexEntryIdx].changeSeq;
11942
+ // Later flushes of this document append to the record chain just read.
11943
+ this.adoptL2Chain(deserialized);
11429
11944
  // Fresh hit: index agrees with the persisted state.
11430
11945
  if (persistedChangeSeq === currentChangeSeq) {
11431
11946
  // Seed the flush-skip fingerprint with the state just read from L2 so
@@ -11802,7 +12317,9 @@ class BaseMindooDB {
11802
12317
  return false;
11803
12318
  }
11804
12319
  const { header } = this.parseDocCacheRecord(bytes);
11805
- if (header.version !== DOC_CACHE_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 ||
11806
12323
  header.changeSeq !== currentChangeSeq ||
11807
12324
  !Array.isArray(header.automergeHeads)) {
11808
12325
  return false;
@@ -12157,11 +12674,17 @@ class BaseMindooDB {
12157
12674
  const stale = [];
12158
12675
  const activeSpecs = [];
12159
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));
12160
12682
  for (const [id, entry] of Object.entries(map)) {
12161
12683
  const label = entry.label ?? id;
12162
12684
  if (entry.removedAt) {
12163
- if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
12685
+ if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint) && !activeFingerprints.has(entry.keyFingerprint)) {
12164
12686
  stale.push(label);
12687
+ }
12165
12688
  continue;
12166
12689
  }
12167
12690
  if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
@@ -13593,6 +14116,23 @@ class BaseMindooDB {
13593
14116
  * never materialized) and `getHeads() === []` — backed by an empty Automerge
13594
14117
  * document so it never touches the underlying ciphertext or the document cache.
13595
14118
  */
14119
+ /**
14120
+ * A document whose key is missing although the index holds it as readable:
14121
+ * forget its plaintext and flip the index entry to `"inaccessible"` (as the
14122
+ * missing-key branch of the sync does), so listings drop it and a key that
14123
+ * arrives later reveals it through `reconcileKeyVisibility`.
14124
+ */
14125
+ async markUndecryptableDocument(entry) {
14126
+ this.noteInaccessibleDocument(entry.docId);
14127
+ const position = this.getDocIndexPosition(entry.docId);
14128
+ const current = position === undefined ? undefined : this.index[position];
14129
+ if (current?.accessState !== "visible")
14130
+ return;
14131
+ await this.purgeMaterializedDocument(entry.docId);
14132
+ this.updateIndex(entry.docId, current.lastModified, true, current.decryptionKeyId, "inaccessible");
14133
+ this.cacheMetaDirty = true;
14134
+ this.cacheManager?.markDirty();
14135
+ }
13596
14136
  buildInaccessibleDoc(entry) {
13597
14137
  const internalDoc = {
13598
14138
  id: entry.docId,