@optimystic/db-p2p 0.21.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/cluster/client.d.ts +10 -0
- package/dist/src/cluster/client.d.ts.map +1 -1
- package/dist/src/cluster/client.js +30 -1
- package/dist/src/cluster/client.js.map +1 -1
- package/dist/src/cluster/cluster-policy.d.ts +13 -2
- package/dist/src/cluster/cluster-policy.d.ts.map +1 -1
- package/dist/src/cluster/cluster-policy.js +51 -4
- package/dist/src/cluster/cluster-policy.js.map +1 -1
- package/dist/src/cluster/cluster-repo.d.ts +42 -17
- package/dist/src/cluster/cluster-repo.d.ts.map +1 -1
- package/dist/src/cluster/cluster-repo.js +229 -122
- package/dist/src/cluster/cluster-repo.js.map +1 -1
- package/dist/src/cluster/cluster-size-coupling.d.ts +28 -0
- package/dist/src/cluster/cluster-size-coupling.d.ts.map +1 -0
- package/dist/src/cluster/cluster-size-coupling.js +35 -0
- package/dist/src/cluster/cluster-size-coupling.js.map +1 -0
- package/dist/src/cluster/quorum-restore.d.ts +6 -0
- package/dist/src/cluster/quorum-restore.d.ts.map +1 -1
- package/dist/src/cluster/quorum-restore.js +1 -1
- package/dist/src/cluster/quorum-restore.js.map +1 -1
- package/dist/src/cluster/reconcile-block.d.ts.map +1 -1
- package/dist/src/cluster/reconcile-block.js +15 -3
- package/dist/src/cluster/reconcile-block.js.map +1 -1
- package/dist/src/cluster/service.d.ts +32 -1
- package/dist/src/cluster/service.d.ts.map +1 -1
- package/dist/src/cluster/service.js +43 -2
- package/dist/src/cluster/service.js.map +1 -1
- package/dist/src/cohort-topic/stream-util.d.ts +22 -6
- package/dist/src/cohort-topic/stream-util.d.ts.map +1 -1
- package/dist/src/cohort-topic/stream-util.js +56 -10
- package/dist/src/cohort-topic/stream-util.js.map +1 -1
- package/dist/src/dispute/dispute-service.d.ts.map +1 -1
- package/dist/src/dispute/dispute-service.js +9 -3
- package/dist/src/dispute/dispute-service.js.map +1 -1
- package/dist/src/index.d.ts +5 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +5 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/libp2p-key-network.d.ts +134 -7
- package/dist/src/libp2p-key-network.d.ts.map +1 -1
- package/dist/src/libp2p-key-network.js +174 -37
- package/dist/src/libp2p-key-network.js.map +1 -1
- package/dist/src/libp2p-node-base.d.ts +3 -2
- package/dist/src/libp2p-node-base.d.ts.map +1 -1
- package/dist/src/libp2p-node-base.js +859 -778
- package/dist/src/libp2p-node-base.js.map +1 -1
- package/dist/src/libp2p-node-rn.d.ts +2 -2
- package/dist/src/libp2p-node-rn.d.ts.map +1 -1
- package/dist/src/libp2p-node-rn.js.map +1 -1
- package/dist/src/libp2p-node.d.ts +2 -2
- package/dist/src/libp2p-node.d.ts.map +1 -1
- package/dist/src/libp2p-node.js.map +1 -1
- package/dist/src/logger.d.ts +17 -1
- package/dist/src/logger.d.ts.map +1 -1
- package/dist/src/logger.js +19 -2
- package/dist/src/logger.js.map +1 -1
- package/dist/src/network/network-manager-service.d.ts +2 -0
- package/dist/src/network/network-manager-service.d.ts.map +1 -1
- package/dist/src/network/network-manager-service.js +4 -0
- package/dist/src/network/network-manager-service.js.map +1 -1
- package/dist/src/optimystic-node.d.ts +35 -0
- package/dist/src/optimystic-node.d.ts.map +1 -0
- package/dist/src/optimystic-node.js +2 -0
- package/dist/src/optimystic-node.js.map +1 -0
- package/dist/src/owned-block-seed.d.ts +6 -3
- package/dist/src/owned-block-seed.d.ts.map +1 -1
- package/dist/src/owned-block-seed.js +16 -3
- package/dist/src/owned-block-seed.js.map +1 -1
- package/dist/src/peer-address-book.d.ts +72 -0
- package/dist/src/peer-address-book.d.ts.map +1 -0
- package/dist/src/peer-address-book.js +123 -0
- package/dist/src/peer-address-book.js.map +1 -0
- package/dist/src/repo/client.d.ts.map +1 -1
- package/dist/src/repo/client.js +11 -2
- package/dist/src/repo/client.js.map +1 -1
- package/dist/src/repo/cluster-coordinator.d.ts +30 -0
- package/dist/src/repo/cluster-coordinator.d.ts.map +1 -1
- package/dist/src/repo/cluster-coordinator.js +95 -3
- package/dist/src/repo/cluster-coordinator.js.map +1 -1
- package/dist/src/repo/coordinator-repo.d.ts +78 -14
- package/dist/src/repo/coordinator-repo.d.ts.map +1 -1
- package/dist/src/repo/coordinator-repo.js +266 -81
- package/dist/src/repo/coordinator-repo.js.map +1 -1
- package/dist/src/rn.d.ts +5 -0
- package/dist/src/rn.d.ts.map +1 -1
- package/dist/src/rn.js +5 -0
- package/dist/src/rn.js.map +1 -1
- package/dist/src/storage/block-storage.d.ts.map +1 -1
- package/dist/src/storage/block-storage.js +57 -5
- package/dist/src/storage/block-storage.js.map +1 -1
- package/dist/src/storage/cached-raw-storage.d.ts +83 -0
- package/dist/src/storage/cached-raw-storage.d.ts.map +1 -0
- package/dist/src/storage/cached-raw-storage.js +152 -0
- package/dist/src/storage/cached-raw-storage.js.map +1 -0
- package/dist/src/storage/cached-store-driver.d.ts +186 -0
- package/dist/src/storage/cached-store-driver.d.ts.map +1 -0
- package/dist/src/storage/cached-store-driver.js +775 -0
- package/dist/src/storage/cached-store-driver.js.map +1 -0
- package/dist/src/storage/i-block-storage.d.ts +20 -1
- package/dist/src/storage/i-block-storage.d.ts.map +1 -1
- package/dist/src/storage/i-raw-storage.d.ts +12 -5
- package/dist/src/storage/i-raw-storage.d.ts.map +1 -1
- package/dist/src/storage/shared-cache-pool.d.ts +234 -0
- package/dist/src/storage/shared-cache-pool.d.ts.map +1 -0
- package/dist/src/storage/shared-cache-pool.js +354 -0
- package/dist/src/storage/shared-cache-pool.js.map +1 -0
- package/dist/src/storage/storage-repo.d.ts +56 -3
- package/dist/src/storage/storage-repo.d.ts.map +1 -1
- package/dist/src/storage/storage-repo.js +124 -18
- package/dist/src/storage/storage-repo.js.map +1 -1
- package/dist/src/testing/raw-storage-conformance.d.ts +2 -1
- package/dist/src/testing/raw-storage-conformance.d.ts.map +1 -1
- package/dist/src/testing/raw-storage-conformance.js +52 -2
- package/dist/src/testing/raw-storage-conformance.js.map +1 -1
- package/package.json +3 -3
- package/readme.md +668 -653
- package/src/cluster/block-transfer.ts +424 -424
- package/src/cluster/client.ts +119 -88
- package/src/cluster/cluster-error.ts +64 -64
- package/src/cluster/cluster-policy.ts +203 -152
- package/src/cluster/cluster-repo.ts +245 -125
- package/src/cluster/cluster-size-coupling.ts +45 -0
- package/src/cluster/commit-cert.ts +139 -139
- package/src/cluster/i-transaction-state-store.ts +43 -43
- package/src/cluster/memory-transaction-state-store.ts +56 -56
- package/src/cluster/peer-key-binding.ts +37 -37
- package/src/cluster/persistent-transaction-state-store.ts +92 -92
- package/src/cluster/quorum-restore.ts +223 -223
- package/src/cluster/reconcile-block.ts +203 -191
- package/src/cluster/service.ts +293 -241
- package/src/cluster/supermajority-coupling.ts +37 -37
- package/src/cohort-topic/bootstrap-evidence-builder.ts +122 -122
- package/src/cohort-topic/bootstrap-evidence-verifiers.ts +132 -132
- package/src/cohort-topic/bootstrap-parent-reference.ts +159 -159
- package/src/cohort-topic/change-bridge.ts +109 -109
- package/src/cohort-topic/cohort-gossip-driver.ts +231 -231
- package/src/cohort-topic/cohort-gossip-transport.ts +84 -84
- package/src/cohort-topic/fret-trust-anchor.ts +153 -153
- package/src/cohort-topic/host.ts +2901 -2901
- package/src/cohort-topic/index.ts +13 -13
- package/src/cohort-topic/membership-publish-sink.ts +20 -20
- package/src/cohort-topic/membership-source.ts +68 -68
- package/src/cohort-topic/peer-codec.ts +31 -31
- package/src/cohort-topic/peer-sig.ts +86 -86
- package/src/cohort-topic/protocols.ts +71 -71
- package/src/cohort-topic/reactivity-membership-gate.ts +77 -77
- package/src/cohort-topic/size-estimator.ts +16 -16
- package/src/cohort-topic/stream-util.ts +135 -87
- package/src/cohort-topic/threshold-crypto.ts +239 -239
- package/src/cohort-topic/topic-router.ts +77 -77
- package/src/dispute/arbitrator-selection.ts +138 -138
- package/src/dispute/cascade.ts +524 -524
- package/src/dispute/dispute-service.ts +11 -5
- package/src/dispute/invalidation.ts +625 -625
- package/src/inbound-authorization.ts +190 -190
- package/src/index.ts +52 -47
- package/src/libp2p-key-network.ts +1120 -958
- package/src/libp2p-node-base.ts +1675 -1591
- package/src/libp2p-node-rn.ts +30 -30
- package/src/libp2p-node.ts +36 -36
- package/src/logger.ts +19 -2
- package/src/matchmaking/aggregate-counts.ts +104 -104
- package/src/matchmaking/index.ts +20 -20
- package/src/matchmaking/module.ts +363 -363
- package/src/matchmaking/protocols.ts +51 -51
- package/src/matchmaking/provider-manager.ts +95 -95
- package/src/matchmaking/query-handler.ts +88 -88
- package/src/matchmaking/query-transport.ts +492 -492
- package/src/matchmaking/seeker-manager.ts +64 -64
- package/src/matchmaking/seeker-walk-client.ts +293 -293
- package/src/matchmaking/traffic-validation.ts +195 -195
- package/src/network/network-manager-service.ts +5 -0
- package/src/optimystic-node.ts +36 -0
- package/src/owned-block-seed.ts +53 -40
- package/src/peer-address-book.ts +149 -0
- package/src/protocol-limits.ts +33 -33
- package/src/reactivity/forwarder-host.ts +438 -438
- package/src/reactivity/index.ts +19 -19
- package/src/reactivity/notify-transport.ts +144 -144
- package/src/reactivity/origination-manager.ts +192 -192
- package/src/reactivity/protocols.ts +61 -61
- package/src/reactivity/push-state-gossip.ts +291 -291
- package/src/reactivity/recover-transport.ts +408 -408
- package/src/reactivity/rotation-rereg-scheduler.ts +256 -256
- package/src/reactivity/subscriber-registry.ts +96 -96
- package/src/reactivity/subscription-manager.ts +450 -450
- package/src/reactivity/topic-bytes.ts +37 -37
- package/src/repo/client.ts +12 -2
- package/src/repo/cluster-coordinator.ts +99 -3
- package/src/repo/coordinator-repo.ts +305 -82
- package/src/repo/types.ts +7 -7
- package/src/rn.ts +39 -34
- package/src/rpc-deadline.ts +45 -45
- package/src/storage/arachnode-partition.ts +74 -74
- package/src/storage/block-storage.ts +59 -6
- package/src/storage/cached-raw-storage.ts +180 -0
- package/src/storage/cached-store-driver.ts +859 -0
- package/src/storage/i-block-storage.ts +20 -1
- package/src/storage/i-kv-store.ts +8 -8
- package/src/storage/i-raw-storage.ts +12 -5
- package/src/storage/kv-raw-storage.ts +135 -135
- package/src/storage/memory-kv-store.ts +28 -28
- package/src/storage/memory-storage.ts +25 -25
- package/src/storage/memory-store-driver.ts +157 -157
- package/src/storage/raw-store-codec.ts +42 -42
- package/src/storage/raw-store-driver.ts +80 -80
- package/src/storage/ring-selector.ts +317 -317
- package/src/storage/ring-shift-coordinator.ts +271 -271
- package/src/storage/shared-cache-pool.ts +452 -0
- package/src/storage/storage-repo.ts +1014 -903
- package/src/testing/cohort-topic-mesh-harness.ts +663 -663
- package/src/testing/index.ts +8 -8
- package/src/testing/matchmaking-mesh-harness.ts +475 -475
- package/src/testing/raw-storage-conformance.ts +453 -397
- package/src/testing/reactivity-mesh-harness.ts +922 -922
- package/dist/src/storage/restoration-coordinator-v2.d.ts +0 -67
- package/dist/src/storage/restoration-coordinator-v2.d.ts.map +0 -1
- package/dist/src/storage/restoration-coordinator-v2.js +0 -172
- package/dist/src/storage/restoration-coordinator-v2.js.map +0 -1
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import type { BlockId, ActionId } from "@optimystic/db-core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Which of the cache's entry classes a pool entry belongs to. Mirrors the sub-states of
|
|
5
|
+
* `CachedStoreDriver`'s per-block cache state; the pool itself never branches on the class —
|
|
6
|
+
* it exists so the owning store can locate the entry's home when the pool evicts it.
|
|
7
|
+
*/
|
|
8
|
+
export type CacheEntryClass = 'meta' | 'revs' | 'pendList' | 'pending' | 'tx' | 'mat';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The owner side of the eviction contract. When the pool evicts an entry it calls
|
|
12
|
+
* `onPoolEvict` exactly once; the owner must remove its own reference to the entry (and only
|
|
13
|
+
* that) so the evicted value becomes unreachable. The callback runs synchronously inside a
|
|
14
|
+
* pool mutation and MUST NOT call back into any pool method — the pool's accounting is
|
|
15
|
+
* mid-update when it fires.
|
|
16
|
+
*/
|
|
17
|
+
export interface PoolEntryOwner {
|
|
18
|
+
onPoolEvict(entry: PoolEntry): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One cached value's residency record: simultaneously the value holder the owning store's
|
|
23
|
+
* maps point at, and the node the pool's queues link. Owners create these as plain object
|
|
24
|
+
* literals (`where: 'none'`), install the reference in their own state FIRST, and then call
|
|
25
|
+
* {@link SharedCachePool.admit} — that order guarantees evictions triggered by the admission
|
|
26
|
+
* can never observe the owner's block state as empty while the new entry is in flight.
|
|
27
|
+
*
|
|
28
|
+
* `charge` is the entry's whole budget cost: `base` (fixed bookkeeping — entry object, owner
|
|
29
|
+
* map slot, queue slot, key string) plus the owner-computed content bytes. Negatives and
|
|
30
|
+
* empty container states therefore still cost `base`, which is what keeps a remote probe
|
|
31
|
+
* stream of nonexistent keys inside the budget instead of growing bookkeeping for free.
|
|
32
|
+
*/
|
|
33
|
+
export interface PoolEntry<V = unknown> {
|
|
34
|
+
readonly key: string;
|
|
35
|
+
readonly store: CacheStoreHandle;
|
|
36
|
+
readonly owner: PoolEntryOwner;
|
|
37
|
+
readonly cls: CacheEntryClass;
|
|
38
|
+
readonly blockId: BlockId;
|
|
39
|
+
readonly actionId: ActionId | undefined;
|
|
40
|
+
value: V;
|
|
41
|
+
/** Fixed bookkeeping charge (entry + map slots + key string); never changes. */
|
|
42
|
+
readonly base: number;
|
|
43
|
+
/** Total budgeted bytes: `base` + content. Managed via {@link SharedCachePool.updated}. */
|
|
44
|
+
charge: number;
|
|
45
|
+
/** Which queue currently holds the entry; `'none'` = not resident. Pool-managed. */
|
|
46
|
+
where: 'a1in' | 'am' | 'none';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A store's registration with the pool. `id` is process-unique and never reused (monotonic
|
|
51
|
+
* counter), so entries and ghost keys of a departed store can never alias a later one.
|
|
52
|
+
* `bytes`/`entries` are live occupancy, maintained by the pool — read-only for callers.
|
|
53
|
+
*/
|
|
54
|
+
export class CacheStoreHandle {
|
|
55
|
+
bytes = 0;
|
|
56
|
+
entries = 0;
|
|
57
|
+
constructor(
|
|
58
|
+
readonly id: string,
|
|
59
|
+
readonly label: string | undefined,
|
|
60
|
+
) {}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface CachePoolStats {
|
|
64
|
+
maxBytes: number;
|
|
65
|
+
maxEntries: number;
|
|
66
|
+
bytes: number;
|
|
67
|
+
entries: number;
|
|
68
|
+
a1in: { bytes: number; entries: number };
|
|
69
|
+
am: { bytes: number; entries: number };
|
|
70
|
+
/** Ghost (A1out) key count. Ghost keys are bookkeeping outside the byte budget, bounded by their own cap. */
|
|
71
|
+
ghostKeys: number;
|
|
72
|
+
hits: number;
|
|
73
|
+
admissions: number;
|
|
74
|
+
/** Admissions that went straight to Am because the key was in the ghost set (the 2Q reuse signal). */
|
|
75
|
+
ghostHits: number;
|
|
76
|
+
evictions: number;
|
|
77
|
+
bypasses: number;
|
|
78
|
+
stores: { id: string; label: string | undefined; bytes: number; entries: number }[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface SharedCachePoolOptions {
|
|
82
|
+
/** Byte budget for all resident entries across all registered stores. Default is per-platform (see {@link defaultCachePool}). */
|
|
83
|
+
maxBytes?: number;
|
|
84
|
+
/** Entry-count secondary rail (guards the many-tiny-entries case). Default `max(16, maxBytes / 512)`. */
|
|
85
|
+
maxEntries?: number;
|
|
86
|
+
/**
|
|
87
|
+
* `'2q'` (default): Johnson & Shasha 2Q — A1in probation FIFO at ~25% of EACH budget rail
|
|
88
|
+
* (bytes and entries), A1out ghost keys at ~50% of the entry cap, Am protected LRU.
|
|
89
|
+
* `'lru'`: a plain shared LRU
|
|
90
|
+
* with no admission control — kept ONLY as the comparison baseline for measuring whether
|
|
91
|
+
* 2Q's pollution resistance earns its complexity (see the pool spec's measurement test).
|
|
92
|
+
*/
|
|
93
|
+
admission?: '2q' | 'lru';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Separator for pool keys: NUL, spelled as an escape so this file stays plain text — a literal
|
|
98
|
+
* NUL byte in the source makes the whole file binary to git (no diff, no blame, no review).
|
|
99
|
+
* NUL is the one character no id can carry: block ids are user-supplied collection URI paths
|
|
100
|
+
* (which may well contain spaces) and action ids are base64url with an optional `tx:`/`stamp:`
|
|
101
|
+
* prefix, so `(storeId, class, blockId, actionId?)` always splits back unambiguously.
|
|
102
|
+
*/
|
|
103
|
+
const SEP = '\u0000';
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* A shared, bounded, clean-value cache pool: one per process (see {@link defaultCachePool}),
|
|
107
|
+
* shared by every `CachedStoreDriver` so that N stores compete inside ONE memory budget
|
|
108
|
+
* instead of keeping N unbounded caches. The pool owns residency and eviction only; all
|
|
109
|
+
* cache *semantics* (coherence, negatives, completeness) stay in the owning store.
|
|
110
|
+
*
|
|
111
|
+
* **Always evict, never refuse, never grow unbounded.** Entries are never pinned and never
|
|
112
|
+
* dirty (the cache is write-through; see `CachedStoreDriver`), so eviction is always safe
|
|
113
|
+
* and there is no exhaustion condition to raise. At the bound the pool evicts; the one entry
|
|
114
|
+
* class that can grow while resident (a store's revision map) is simply evicted like any
|
|
115
|
+
* other when its growth pushes the pool over budget.
|
|
116
|
+
*
|
|
117
|
+
* **2Q admission** (default): a first-touch entry enters the A1in probation FIFO; re-hits
|
|
118
|
+
* inside A1in do NOT promote (FIFO order stands, which is also what absorbs the several
|
|
119
|
+
* correlated touches one logical operation makes); eviction from A1in demotes the key to
|
|
120
|
+
* the A1out ghost set; a later admission of a ghosted key — reuse across operations — goes
|
|
121
|
+
* straight to the protected Am LRU. Am evictions do NOT ghost. One-pass bulk scans
|
|
122
|
+
* therefore live and die inside A1in without displacing any store's hot Am set.
|
|
123
|
+
*
|
|
124
|
+
* **Large values bypass**: an entry whose charge exceeds 1/16 of the byte budget is not
|
|
125
|
+
* admitted at all (the owner reads/writes through), so one oversized value cannot flush
|
|
126
|
+
* the pool.
|
|
127
|
+
*
|
|
128
|
+
* **Budget sanity**: `maxBytes`/`maxEntries` must be positive finite numbers — anything else
|
|
129
|
+
* throws. Absurdly small values are accepted as-is: they cannot break coherence (the owning
|
|
130
|
+
* cache is correct at any residency, including zero), they just degrade toward read-through.
|
|
131
|
+
*
|
|
132
|
+
* Not safe for use from multiple threads; like the caches it serves, it relies on JS
|
|
133
|
+
* single-threaded execution — every mutation completes synchronously.
|
|
134
|
+
*/
|
|
135
|
+
export class SharedCachePool {
|
|
136
|
+
private maxBytesValue: number;
|
|
137
|
+
private maxEntriesValue: number;
|
|
138
|
+
private readonly admission: '2q' | 'lru';
|
|
139
|
+
private bypassLimit = 0;
|
|
140
|
+
private a1inTargetBytes = 0;
|
|
141
|
+
private a1inTargetEntries = 0;
|
|
142
|
+
private ghostCap = 0;
|
|
143
|
+
|
|
144
|
+
private readonly a1in = new Map<string, PoolEntry>();
|
|
145
|
+
private readonly am = new Map<string, PoolEntry>();
|
|
146
|
+
private readonly ghost = new Set<string>();
|
|
147
|
+
private a1inBytes = 0;
|
|
148
|
+
|
|
149
|
+
private bytesTotal = 0;
|
|
150
|
+
private entriesTotal = 0;
|
|
151
|
+
private storeCounter = 0;
|
|
152
|
+
private readonly stores = new Map<string, CacheStoreHandle>();
|
|
153
|
+
|
|
154
|
+
private hits = 0;
|
|
155
|
+
private admissions = 0;
|
|
156
|
+
private ghostHits = 0;
|
|
157
|
+
private evictions = 0;
|
|
158
|
+
private bypasses = 0;
|
|
159
|
+
|
|
160
|
+
constructor(options?: SharedCachePoolOptions) {
|
|
161
|
+
this.admission = options?.admission ?? '2q';
|
|
162
|
+
this.maxBytesValue = validateBound('maxBytes', options?.maxBytes ?? platformDefaultBytes());
|
|
163
|
+
this.maxEntriesValue = validateBound('maxEntries',
|
|
164
|
+
options?.maxEntries ?? Math.max(16, Math.floor(this.maxBytesValue / 512)));
|
|
165
|
+
this.recomputeDerived();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
get maxBytes(): number { return this.maxBytesValue; }
|
|
169
|
+
get maxEntries(): number { return this.maxEntriesValue; }
|
|
170
|
+
get bytes(): number { return this.bytesTotal; }
|
|
171
|
+
get entries(): number { return this.entriesTotal; }
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Re-budget a live pool (e.g. host config change, or a host correcting the platform
|
|
175
|
+
* default). Shrinking evicts immediately down to the new bound.
|
|
176
|
+
*/
|
|
177
|
+
setBudget(budget: { maxBytes?: number; maxEntries?: number }): void {
|
|
178
|
+
if (budget.maxBytes !== undefined) {
|
|
179
|
+
this.maxBytesValue = validateBound('maxBytes', budget.maxBytes);
|
|
180
|
+
}
|
|
181
|
+
if (budget.maxEntries !== undefined) {
|
|
182
|
+
this.maxEntriesValue = validateBound('maxEntries', budget.maxEntries);
|
|
183
|
+
}
|
|
184
|
+
this.recomputeDerived();
|
|
185
|
+
this.evictToFit(0, 0);
|
|
186
|
+
this.trimGhost();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Register a store. The returned handle's `id` is unique for the pool's lifetime — never reused. */
|
|
190
|
+
registerStore(label?: string): CacheStoreHandle {
|
|
191
|
+
const handle = new CacheStoreHandle(`s${++this.storeCounter}`, label);
|
|
192
|
+
this.stores.set(handle.id, handle);
|
|
193
|
+
return handle;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Release a departing store: evict any of its entries still resident (defensively — the
|
|
198
|
+
* owner normally clears first), purge its ghost keys, and remove it from the registry.
|
|
199
|
+
* Idempotent. This forced removal notifies the owner like any other eviction — `drop` here
|
|
200
|
+
* would de-account entries the owner still references, leaving it serving values the pool
|
|
201
|
+
* no longer counts. It does NOT ghost (the ghosts are being purged anyway) and does NOT
|
|
202
|
+
* count as a budget eviction: it is a lifecycle release, not memory pressure.
|
|
203
|
+
*/
|
|
204
|
+
unregisterStore(handle: CacheStoreHandle): void {
|
|
205
|
+
for (const queue of [this.a1in, this.am]) {
|
|
206
|
+
for (const entry of [...queue.values()]) {
|
|
207
|
+
if (entry.store !== handle) continue;
|
|
208
|
+
this.unlink(entry);
|
|
209
|
+
entry.owner.onPoolEvict(entry);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
this.purgeGhosts(handle);
|
|
213
|
+
this.stores.delete(handle.id);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Drop every ghost key belonging to `handle` (used by store clear/close — pre-clear recency must not survive the clear). */
|
|
217
|
+
purgeGhosts(handle: CacheStoreHandle): void {
|
|
218
|
+
const prefix = handle.id + SEP;
|
|
219
|
+
for (const key of [...this.ghost]) {
|
|
220
|
+
if (key.startsWith(prefix)) this.ghost.delete(key);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Build the pool key for an entry. Store-id first: keying by block id alone would alias name-derived header block ids across stores. */
|
|
225
|
+
keyFor(store: CacheStoreHandle, cls: CacheEntryClass, blockId: BlockId, actionId?: ActionId): string {
|
|
226
|
+
return actionId === undefined
|
|
227
|
+
? store.id + SEP + cls + SEP + blockId
|
|
228
|
+
: store.id + SEP + cls + SEP + blockId + SEP + actionId;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Would an entry of this total charge be admitted? `false` = large-value bypass (counted);
|
|
233
|
+
* the owner must then read/write through without caching. Also the gate for value
|
|
234
|
+
* *updates*: an update growing past the limit should drop the entry instead.
|
|
235
|
+
*/
|
|
236
|
+
admits(charge: number): boolean {
|
|
237
|
+
if (charge > this.bypassLimit) {
|
|
238
|
+
this.bypasses++;
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Admit a non-resident entry the owner has ALREADY installed in its own state. Evicts
|
|
246
|
+
* first (so the incoming entry can never be its own victim), then links: to Am when the
|
|
247
|
+
* key is in the ghost set (2Q reuse signal), to A1in probation otherwise.
|
|
248
|
+
*/
|
|
249
|
+
admit(entry: PoolEntry): void {
|
|
250
|
+
if (entry.where !== 'none') {
|
|
251
|
+
throw new Error(`pool admit of already-resident entry ${entry.key}`);
|
|
252
|
+
}
|
|
253
|
+
this.evictToFit(entry.charge, 1);
|
|
254
|
+
this.admissions++;
|
|
255
|
+
if (this.admission === 'lru') {
|
|
256
|
+
this.link(entry, 'am');
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (this.ghost.delete(entry.key)) {
|
|
260
|
+
this.ghostHits++;
|
|
261
|
+
this.link(entry, 'am');
|
|
262
|
+
} else {
|
|
263
|
+
this.link(entry, 'a1in');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Record a read hit: Am refreshes to MRU; A1in stays put (FIFO — no intra-probation promotion). */
|
|
268
|
+
touch(entry: PoolEntry): void {
|
|
269
|
+
this.hits++;
|
|
270
|
+
this.refresh(entry);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Re-account a resident entry after the owner mutated its value (write hit, or container
|
|
275
|
+
* growth like a revision-map fill). Queue position refreshes like a touch (without
|
|
276
|
+
* counting a hit); growth over budget evicts — possibly the updated entry itself, which
|
|
277
|
+
* is why owners call this LAST and never touch their cache state after.
|
|
278
|
+
*
|
|
279
|
+
* NOTE: growth here is NOT re-checked against {@link admits}' large-value bypass, so a
|
|
280
|
+
* container entry (a block's revision map or pending-id set) can grow past 1/16 of the
|
|
281
|
+
* budget and squat where a single oversized value would have been refused. Bounded and
|
|
282
|
+
* self-correcting today: an over-share entry keeps `a1inBytes` above its target, so
|
|
283
|
+
* probation evicts it preferentially, and anything past `maxBytes` is evicted outright.
|
|
284
|
+
* If a block ever accumulates enough revisions for one map to hold a real fraction of the
|
|
285
|
+
* budget (order 20k revs at the 32 MB Node default), gate growth on `admits(charge)` in
|
|
286
|
+
* the owner's revision/pending-list paths and drop the entry when it fails, exactly as
|
|
287
|
+
* `CachedStoreDriver.cachePoint` already does for point values.
|
|
288
|
+
*/
|
|
289
|
+
updated(entry: PoolEntry, newCharge: number): void {
|
|
290
|
+
if (entry.where === 'none') return;
|
|
291
|
+
const delta = newCharge - entry.charge;
|
|
292
|
+
entry.charge = newCharge;
|
|
293
|
+
this.bytesTotal += delta;
|
|
294
|
+
entry.store.bytes += delta;
|
|
295
|
+
if (entry.where === 'a1in') this.a1inBytes += delta;
|
|
296
|
+
this.refresh(entry);
|
|
297
|
+
if (delta > 0) this.evictToFit(0, 0);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Remove an entry WITHOUT the eviction callback — for owners invalidating or clearing
|
|
302
|
+
* their own entries (the owner is already removing its reference). Never ghosts: an
|
|
303
|
+
* invalidation says nothing about reuse. No-op if not resident.
|
|
304
|
+
*/
|
|
305
|
+
drop(entry: PoolEntry): void {
|
|
306
|
+
if (entry.where === 'none') return;
|
|
307
|
+
this.unlink(entry);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
stats(): CachePoolStats {
|
|
311
|
+
const amBytes = this.bytesTotal - this.a1inBytes;
|
|
312
|
+
return {
|
|
313
|
+
maxBytes: this.maxBytesValue,
|
|
314
|
+
maxEntries: this.maxEntriesValue,
|
|
315
|
+
bytes: this.bytesTotal,
|
|
316
|
+
entries: this.entriesTotal,
|
|
317
|
+
a1in: { bytes: this.a1inBytes, entries: this.a1in.size },
|
|
318
|
+
am: { bytes: amBytes, entries: this.am.size },
|
|
319
|
+
ghostKeys: this.ghost.size,
|
|
320
|
+
hits: this.hits,
|
|
321
|
+
admissions: this.admissions,
|
|
322
|
+
ghostHits: this.ghostHits,
|
|
323
|
+
evictions: this.evictions,
|
|
324
|
+
bypasses: this.bypasses,
|
|
325
|
+
stores: [...this.stores.values()].map(s => ({ id: s.id, label: s.label, bytes: s.bytes, entries: s.entries })),
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ---- internals ----
|
|
330
|
+
|
|
331
|
+
private recomputeDerived(): void {
|
|
332
|
+
this.bypassLimit = Math.floor(this.maxBytesValue / 16);
|
|
333
|
+
this.a1inTargetBytes = Math.floor(this.maxBytesValue / 4);
|
|
334
|
+
this.a1inTargetEntries = Math.floor(this.maxEntriesValue / 4);
|
|
335
|
+
this.ghostCap = Math.floor(this.maxEntriesValue / 2);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private link(entry: PoolEntry, where: 'a1in' | 'am'): void {
|
|
339
|
+
entry.where = where;
|
|
340
|
+
(where === 'a1in' ? this.a1in : this.am).set(entry.key, entry);
|
|
341
|
+
if (where === 'a1in') this.a1inBytes += entry.charge;
|
|
342
|
+
this.bytesTotal += entry.charge;
|
|
343
|
+
this.entriesTotal++;
|
|
344
|
+
entry.store.bytes += entry.charge;
|
|
345
|
+
entry.store.entries++;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private unlink(entry: PoolEntry): void {
|
|
349
|
+
(entry.where === 'a1in' ? this.a1in : this.am).delete(entry.key);
|
|
350
|
+
if (entry.where === 'a1in') this.a1inBytes -= entry.charge;
|
|
351
|
+
this.bytesTotal -= entry.charge;
|
|
352
|
+
this.entriesTotal--;
|
|
353
|
+
entry.store.bytes -= entry.charge;
|
|
354
|
+
entry.store.entries--;
|
|
355
|
+
entry.where = 'none';
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Map insertion order gives A1in its FIFO and Am its LRU: refresh = delete + re-insert. */
|
|
359
|
+
private refresh(entry: PoolEntry): void {
|
|
360
|
+
if (entry.where !== 'am') return;
|
|
361
|
+
this.am.delete(entry.key);
|
|
362
|
+
this.am.set(entry.key, entry);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
private evictToFit(incomingCharge: number, incomingEntries: number): void {
|
|
366
|
+
while (this.bytesTotal + incomingCharge > this.maxBytesValue
|
|
367
|
+
|| this.entriesTotal + incomingEntries > this.maxEntriesValue) {
|
|
368
|
+
const victim = this.pickVictim();
|
|
369
|
+
if (victim === undefined) break; // pool empty — nothing left to evict
|
|
370
|
+
this.evict(victim);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
private pickVictim(): PoolEntry | undefined {
|
|
375
|
+
if (this.admission === 'lru') {
|
|
376
|
+
return first(this.am) ?? first(this.a1in);
|
|
377
|
+
}
|
|
378
|
+
// 2Q: take A1in's FIFO head while probation is over its share of EITHER rail (or Am has
|
|
379
|
+
// nothing); otherwise the protected queue's LRU entry. Probation needs a share of the
|
|
380
|
+
// entry rail too, not just the byte rail: entries small enough that the entry count binds
|
|
381
|
+
// first (cached negatives are near-empty) would otherwise leave `a1inBytes` permanently
|
|
382
|
+
// under its byte target, so every admission would evict from Am and a one-pass scan would
|
|
383
|
+
// flush the protected set — 2Q silently degraded to plain LRU.
|
|
384
|
+
const a1inHead = first(this.a1in);
|
|
385
|
+
if (a1inHead !== undefined && (this.a1inBytes > this.a1inTargetBytes
|
|
386
|
+
|| this.a1in.size > this.a1inTargetEntries || this.am.size === 0)) {
|
|
387
|
+
return a1inHead;
|
|
388
|
+
}
|
|
389
|
+
return first(this.am) ?? a1inHead;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
private evict(entry: PoolEntry): void {
|
|
393
|
+
const fromA1in = entry.where === 'a1in';
|
|
394
|
+
this.unlink(entry);
|
|
395
|
+
if (fromA1in && this.admission === '2q') {
|
|
396
|
+
this.pushGhost(entry.key);
|
|
397
|
+
}
|
|
398
|
+
this.evictions++;
|
|
399
|
+
entry.owner.onPoolEvict(entry);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private pushGhost(key: string): void {
|
|
403
|
+
this.ghost.delete(key);
|
|
404
|
+
this.ghost.add(key);
|
|
405
|
+
this.trimGhost();
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
private trimGhost(): void {
|
|
409
|
+
while (this.ghost.size > this.ghostCap) {
|
|
410
|
+
const oldest = this.ghost.values().next().value;
|
|
411
|
+
if (oldest === undefined) break;
|
|
412
|
+
this.ghost.delete(oldest);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function first(queue: Map<string, PoolEntry>): PoolEntry | undefined {
|
|
418
|
+
return queue.values().next().value;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function validateBound(name: string, value: number): number {
|
|
422
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
|
423
|
+
throw new TypeError(`SharedCachePool ${name} must be a positive finite number, got ${value}`);
|
|
424
|
+
}
|
|
425
|
+
return Math.floor(value);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Honest per-platform default byte budget: ~8 MB on React Native (the phone running twenty
|
|
430
|
+
* workspaces is the device least able to afford more), 16 MB in browsers, 32 MB on Node
|
|
431
|
+
* (desktop / provider hosts). Hosts with better knowledge should size explicitly — either
|
|
432
|
+
* `defaultCachePool().setBudget(...)` or their own `SharedCachePool` passed to each cache.
|
|
433
|
+
*/
|
|
434
|
+
function platformDefaultBytes(): number {
|
|
435
|
+
const g = globalThis as { navigator?: { product?: string }; window?: unknown };
|
|
436
|
+
if (g.navigator?.product === 'ReactNative') return 8 * 1024 * 1024;
|
|
437
|
+
if (g.window !== undefined) return 16 * 1024 * 1024;
|
|
438
|
+
return 32 * 1024 * 1024;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
let defaultPool: SharedCachePool | undefined;
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* The process-wide shared pool every `CachedStoreDriver` joins unless handed a specific one.
|
|
445
|
+
* Lazily created on first use with the platform-default budget; re-budget it live via
|
|
446
|
+
* `setBudget`. One pool per process is the point: twenty workspaces' caches compete inside
|
|
447
|
+
* one budget instead of each sizing itself as if it were alone.
|
|
448
|
+
*/
|
|
449
|
+
export function defaultCachePool(): SharedCachePool {
|
|
450
|
+
defaultPool ??= new SharedCachePool();
|
|
451
|
+
return defaultPool;
|
|
452
|
+
}
|