dsh-memu-memory 1.4.3 → 1.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +15 -0
- package/README.md +34 -15
- package/README.zh.md +35 -13
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/preset-mount.js +13 -7
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +38 -7
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +97 -13
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/preset-mount.test.mjs +12 -4
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
- package/tests/worker-lifecycle.test.mjs +2 -1
package/lib/backup.js
CHANGED
|
@@ -2,9 +2,10 @@ import crypto from 'node:crypto'
|
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
import { spawn } from 'node:child_process'
|
|
5
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
5
6
|
import {
|
|
6
7
|
backupsDir, dataDir, ensureDir, indexDir, isSafeId, librariesDir,
|
|
7
|
-
readJson, warn,
|
|
8
|
+
readJson, warn, writeJson,
|
|
8
9
|
} from './paths.js'
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -113,38 +114,49 @@ function hasSqliteHeader(file) {
|
|
|
113
114
|
|
|
114
115
|
// ---------------------------------------------------------------- lock & leases
|
|
115
116
|
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
117
|
+
// Reentrancy belongs to one asynchronous operation, never every caller sharing
|
|
118
|
+
// its process. Restore's awaited safety backup inherits this ownership context.
|
|
119
|
+
const heldBackupLocks = new Map()
|
|
120
|
+
const backupLockContext = new AsyncLocalStorage()
|
|
121
|
+
|
|
122
|
+
function backupBusy() {
|
|
123
|
+
const error = new Error('memory store is busy: backup; retry the operation')
|
|
124
|
+
error.code = 'DSH_MEMU_STORE_BUSY'
|
|
125
|
+
return error
|
|
126
|
+
}
|
|
121
127
|
|
|
122
128
|
function acquireBackupLock() {
|
|
123
129
|
const lock = path.resolve(lockAnchor()) + '.lock'
|
|
124
|
-
if (heldBackupLocks.has(lock))
|
|
130
|
+
if (heldBackupLocks.has(lock)) throw backupBusy()
|
|
125
131
|
ensureDir(backupsDir())
|
|
126
132
|
const until = Date.now() + 500
|
|
127
133
|
let fd
|
|
128
134
|
while (fd === undefined) {
|
|
129
135
|
try {
|
|
130
136
|
fd = fs.openSync(lock, 'wx', 0o600)
|
|
131
|
-
fs.writeFileSync(fd, String(process.pid))
|
|
137
|
+
try { fs.writeFileSync(fd, String(process.pid)) } catch (error) {
|
|
138
|
+
fs.closeSync(fd); fd = undefined
|
|
139
|
+
try { fs.unlinkSync(lock) } catch {}
|
|
140
|
+
throw error
|
|
141
|
+
}
|
|
132
142
|
} catch (error) {
|
|
133
143
|
if (error?.code !== 'EEXIST') throw error
|
|
134
144
|
try {
|
|
145
|
+
const stat = fs.lstatSync(lock)
|
|
146
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw backupBusy()
|
|
135
147
|
const owner = Number(fs.readFileSync(lock, 'utf8'))
|
|
136
|
-
|
|
148
|
+
const validOwner = Number.isSafeInteger(owner) && owner > 0
|
|
149
|
+
if ((validOwner && !pidAlive(owner)) || (!validOwner && Date.now() - stat.mtimeMs >= 10_000)) {
|
|
150
|
+
fs.unlinkSync(lock); continue
|
|
151
|
+
}
|
|
137
152
|
} catch {}
|
|
138
|
-
if (Date.now() >= until)
|
|
139
|
-
const busy = new Error('memory store is busy: backup; retry the operation')
|
|
140
|
-
busy.code = 'DSH_MEMU_STORE_BUSY'
|
|
141
|
-
throw busy
|
|
142
|
-
}
|
|
153
|
+
if (Date.now() >= until) throw backupBusy()
|
|
143
154
|
pause(10)
|
|
144
155
|
}
|
|
145
156
|
}
|
|
146
|
-
|
|
147
|
-
|
|
157
|
+
const owner = Symbol('backup operation')
|
|
158
|
+
heldBackupLocks.set(lock, owner)
|
|
159
|
+
return { lock, owner, release: () => {
|
|
148
160
|
heldBackupLocks.delete(lock)
|
|
149
161
|
try { fs.closeSync(fd) } catch {}
|
|
150
162
|
for (let attempt = 0; ; attempt += 1) {
|
|
@@ -155,27 +167,29 @@ function acquireBackupLock() {
|
|
|
155
167
|
break
|
|
156
168
|
}
|
|
157
169
|
}
|
|
158
|
-
}
|
|
170
|
+
} }
|
|
159
171
|
}
|
|
160
172
|
|
|
161
173
|
/**
|
|
162
174
|
* The one lock that coordinates create/delete/restore/prune. It is reentrant
|
|
163
|
-
* inside
|
|
175
|
+
* inside one async ownership context, so a restore may create its safety backup and prune
|
|
164
176
|
* while still holding it. A synchronous action returns its value synchronously;
|
|
165
177
|
* an async action returns a Promise and the lock stays held until it settles.
|
|
166
178
|
*/
|
|
167
179
|
export function withBackupLock(action) {
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
180
|
+
const lock = path.resolve(lockAnchor()) + '.lock'
|
|
181
|
+
const parent = backupLockContext.getStore()
|
|
182
|
+
if (heldBackupLocks.has(lock) && parent?.get(lock) === heldBackupLocks.get(lock)) return action()
|
|
183
|
+
const acquired = acquireBackupLock()
|
|
184
|
+
const context = new Map(parent)
|
|
185
|
+
context.set(lock, acquired.owner)
|
|
186
|
+
return backupLockContext.run(context, () => {
|
|
187
|
+
let result
|
|
188
|
+
try { result = action() } catch (error) { acquired.release(); throw error }
|
|
189
|
+
if (result && typeof result.then === 'function') return Promise.resolve(result).finally(acquired.release)
|
|
190
|
+
acquired.release()
|
|
191
|
+
return result
|
|
192
|
+
})
|
|
179
193
|
}
|
|
180
194
|
|
|
181
195
|
function pidAlive(pid) {
|
|
@@ -638,7 +652,7 @@ function engineSummary() {
|
|
|
638
652
|
* `exec` only exists so tests can stand in for the engine interpreter; the
|
|
639
653
|
* default path spawns the verified venv binary and nothing else.
|
|
640
654
|
*/
|
|
641
|
-
async function writeStores(staging, exec) {
|
|
655
|
+
async function writeStores(staging, exec, checkpointMaintenance) {
|
|
642
656
|
ensureDir(path.join(staging, 'libraries'))
|
|
643
657
|
ensureDir(path.join(staging, 'index'))
|
|
644
658
|
ensureDir(path.join(staging, 'prompts'))
|
|
@@ -646,6 +660,16 @@ async function writeStores(staging, exec) {
|
|
|
646
660
|
// Consolidation ledger: per-session ranges/operations. It now participates in
|
|
647
661
|
// backup/restore so a restored install does not re-fork work it already did.
|
|
648
662
|
copyRegular(path.join(dataDir(), 'consolidation.json'), path.join(staging, 'consolidation.json'))
|
|
663
|
+
// The snapshot and its journal form one maintenance store. Publish only a
|
|
664
|
+
// complete checkpoint, copied before releasing the same maintenance lock.
|
|
665
|
+
// Dynamic import avoids the state -> backup -> maintenance -> memory cycle.
|
|
666
|
+
const maintenance = await import('./maintenance-ledger.js')
|
|
667
|
+
maintenance.withMaintenanceLock(() => {
|
|
668
|
+
const checkpoint = checkpointMaintenance || maintenance.checkpointMaintenanceLedger
|
|
669
|
+
const result = checkpoint({ ifExists: true })
|
|
670
|
+
if (result && typeof result.then === 'function') throw new Error('maintenance backup checkpoints must be synchronous')
|
|
671
|
+
if (result && !copyRegular(maintenance.maintenanceLedgerPath(), path.join(staging, 'maintenance.json'))) throw new Error('maintenance backup checkpoint is missing')
|
|
672
|
+
})
|
|
649
673
|
for (const name of readdirSafe(indexDir())) {
|
|
650
674
|
// Local deleted-memory stashes are a time-boxed undo buffer, not library
|
|
651
675
|
// data: they must never leak permanently deleted bodies into a backup.
|
|
@@ -731,7 +755,7 @@ function cleanupStaging() {
|
|
|
731
755
|
* throw happens before anything is published, so no partial or torn backup can
|
|
732
756
|
* ever appear in backups/.
|
|
733
757
|
*/
|
|
734
|
-
export async function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null } = {}) {
|
|
758
|
+
export async function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null, checkpointMaintenance = null } = {}) {
|
|
735
759
|
return withBackupLock(async () => {
|
|
736
760
|
ensureDir(backupsDir())
|
|
737
761
|
cleanupStaging()
|
|
@@ -742,7 +766,7 @@ export async function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushSt
|
|
|
742
766
|
// Plugin state is flushed first: a backup must never capture the pending
|
|
743
767
|
// bookkeeping edits that are still only in memory.
|
|
744
768
|
if (typeof flushState === 'function') flushState()
|
|
745
|
-
const snapshots = await writeStores(staging, pythonExec)
|
|
769
|
+
const snapshots = await writeStores(staging, pythonExec, checkpointMaintenance)
|
|
746
770
|
const files = collectFiles(staging)
|
|
747
771
|
const totals = { files: 0, bytes: 0 }
|
|
748
772
|
for (const rel of Object.keys(files)) {
|
|
@@ -1042,6 +1066,7 @@ function liveTargetFor(rel) {
|
|
|
1042
1066
|
if (parts.length === 1) {
|
|
1043
1067
|
if (head === 'state.json') return stateFile()
|
|
1044
1068
|
if (head === 'consolidation.json') return path.join(dataDir(), 'consolidation.json')
|
|
1069
|
+
if (head === 'maintenance.json') return path.join(dataDir(), 'maintenance.json')
|
|
1045
1070
|
if (head === 'global.sqlite3') return globalDbFile()
|
|
1046
1071
|
if (head === 'global.sqlite3-wal') return globalDbFile() + '-wal'
|
|
1047
1072
|
if (head === 'global.sqlite3-shm') return globalDbFile() + '-shm'
|
|
@@ -1205,6 +1230,10 @@ export async function restoreFromBackup(name, { beforeRestore = null, flushState
|
|
|
1205
1230
|
return withBackupLock(async () => {
|
|
1206
1231
|
const found = findBackup(name)
|
|
1207
1232
|
const plan = verifyInventory(found)
|
|
1233
|
+
const maintenance = await import('./maintenance-ledger.js')
|
|
1234
|
+
const hasMaintenance = plan.rels.includes('maintenance.json')
|
|
1235
|
+
const maintenanceSnapshot = hasMaintenance ? readJsonQuiet(path.join(found.dir, 'maintenance.json')) : null
|
|
1236
|
+
if (hasMaintenance) maintenance.validateMaintenanceSnapshot(maintenanceSnapshot)
|
|
1208
1237
|
const vector = planVectorActive(found, plan.rels)
|
|
1209
1238
|
writeLease(found.name, { pid: process.pid, at: Date.now(), kind: 'restore' })
|
|
1210
1239
|
let safety = null
|
|
@@ -1214,7 +1243,13 @@ export async function restoreFromBackup(name, { beforeRestore = null, flushState
|
|
|
1214
1243
|
: createBackup({ label: 'before-restore', flushState }))
|
|
1215
1244
|
safety = typeof created === 'string' ? created : (created && created.dir ? created.dir : null)
|
|
1216
1245
|
const rels = restoreOrder(plan.rels.filter(rel => rel !== 'index/vector-active.json' || vector.restore))
|
|
1246
|
+
// Each operation holds the maintenance lock for its generation switch.
|
|
1247
|
+
// Release it before large database copies to bound maintenance contention;
|
|
1248
|
+
// restore is recoverable, not a cross-store transaction.
|
|
1249
|
+
if (hasMaintenance) maintenance.restoreMaintenanceSnapshot(maintenanceSnapshot)
|
|
1250
|
+
else maintenance.checkpointMaintenanceLedger({ ifExists: true })
|
|
1217
1251
|
for (const rel of rels) {
|
|
1252
|
+
if (rel === 'maintenance.json') continue
|
|
1218
1253
|
const target = liveTargetFor(rel)
|
|
1219
1254
|
if (rel.endsWith('.sqlite3')) dropCompanions(target)
|
|
1220
1255
|
writeAtomicCopy(path.join(found.dir, rel.split('/').join(path.sep)), target)
|
|
@@ -56,7 +56,7 @@ export const RUNTIME_STATE = Object.freeze([
|
|
|
56
56
|
{ layer: 'temporary-map', file: 'lib/media.js:21', name: 'captures', keyedBy: 'sessionId', clearedBy: 'capture settle' },
|
|
57
57
|
{ layer: 'temporary-map', file: 'lib/private.js:1063', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
|
|
58
58
|
{ layer: 'temporary-map', file: 'lib/curator.js:57', name: 'jobs', keyedBy: 'job id', clearedBy: 'curation settle' },
|
|
59
|
-
{ layer: 'cache', file: 'lib/state.js:
|
|
59
|
+
{ layer: 'cache', file: 'lib/state.js:1608', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
|
|
60
60
|
{ layer: 'cache', file: 'lib/paths.js:52', name: 'readFailures', keyedBy: 'absolute file', clearedBy: 'a later successful read' },
|
|
61
61
|
])
|
|
62
62
|
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Shared process-local LRU. Byte accounting is an estimate, not an RSS claim.
|
|
2
|
+
const registry = new Map()
|
|
3
|
+
|
|
4
|
+
export function estimateBytes(value) {
|
|
5
|
+
const seen = new WeakSet()
|
|
6
|
+
const stack = [value]
|
|
7
|
+
let bytes = 0
|
|
8
|
+
while (stack.length) {
|
|
9
|
+
const item = stack.pop()
|
|
10
|
+
if (typeof item === 'string') { bytes += item.length * 2 + 16; continue }
|
|
11
|
+
if (item === null || typeof item !== 'object') { bytes += 8; continue }
|
|
12
|
+
if (seen.has(item)) continue
|
|
13
|
+
seen.add(item)
|
|
14
|
+
bytes += 48
|
|
15
|
+
if (ArrayBuffer.isView(item)) bytes += item.byteLength
|
|
16
|
+
else if (item instanceof ArrayBuffer) bytes += item.byteLength
|
|
17
|
+
else if (item instanceof Map) for (const [key, val] of item) { bytes += 24; stack.push(key, val) }
|
|
18
|
+
else if (item instanceof Set) for (const val of item) { bytes += 16; stack.push(val) }
|
|
19
|
+
else for (const [key, val] of Object.entries(item)) { bytes += key.length * 2 + 16; stack.push(val) }
|
|
20
|
+
}
|
|
21
|
+
return bytes
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createBoundedCache({ maxBytes = 32 * 1024 * 1024, maxEntries = 256, ttlMs = 120000, now = Date.now, sizeOf = estimateBytes, onEvict = null, name = null } = {}) {
|
|
25
|
+
if (!(maxBytes >= 0) || !(maxEntries >= 1) || !(ttlMs >= 0)) throw new Error('invalid bounded cache limits')
|
|
26
|
+
const entries = new Map()
|
|
27
|
+
let bytes = 0
|
|
28
|
+
let hits = 0
|
|
29
|
+
let misses = 0
|
|
30
|
+
let evictions = 0
|
|
31
|
+
let expirations = 0
|
|
32
|
+
let oversized = 0
|
|
33
|
+
function remove(key, reason = null) {
|
|
34
|
+
const record = entries.get(key)
|
|
35
|
+
if (!record) return false
|
|
36
|
+
entries.delete(key)
|
|
37
|
+
bytes -= record.bytes
|
|
38
|
+
if (reason) {
|
|
39
|
+
evictions++
|
|
40
|
+
if (reason === 'ttl') expirations++
|
|
41
|
+
onEvict?.(key, record.value, reason)
|
|
42
|
+
}
|
|
43
|
+
return true
|
|
44
|
+
}
|
|
45
|
+
const cache = {
|
|
46
|
+
get size() { return entries.size },
|
|
47
|
+
get(key) {
|
|
48
|
+
const record = entries.get(key)
|
|
49
|
+
if (!record) { misses++; return undefined }
|
|
50
|
+
if (now() >= record.expiresAt) { remove(key, 'ttl'); misses++; return undefined }
|
|
51
|
+
entries.delete(key)
|
|
52
|
+
entries.set(key, record)
|
|
53
|
+
hits++
|
|
54
|
+
return record.value
|
|
55
|
+
},
|
|
56
|
+
set(key, value) {
|
|
57
|
+
const size = Math.max(0, Number(sizeOf(value, key))) + estimateBytes(key)
|
|
58
|
+
if (!Number.isFinite(size)) throw new Error('invalid cache byte estimate')
|
|
59
|
+
remove(key)
|
|
60
|
+
if (size > maxBytes) { oversized++; return cache }
|
|
61
|
+
entries.set(key, { value, bytes: size, expiresAt: now() + ttlMs })
|
|
62
|
+
bytes += size
|
|
63
|
+
while (bytes > maxBytes || entries.size > maxEntries) remove(entries.keys().next().value, 'capacity')
|
|
64
|
+
return cache
|
|
65
|
+
},
|
|
66
|
+
delete: key => remove(key),
|
|
67
|
+
clear() { for (const key of entries.keys()) remove(key, 'clear') },
|
|
68
|
+
keys() { return entries.keys() },
|
|
69
|
+
*entries() { for (const [key, record] of entries) yield [key, record.value] },
|
|
70
|
+
[Symbol.iterator]() { return cache.entries() },
|
|
71
|
+
stats() { return { size: entries.size, bytes, maxBytes, maxEntries, ttlMs, hits, misses, evictions, expirations, oversized, byteAccounting: 'estimate' } },
|
|
72
|
+
}
|
|
73
|
+
if (name) registry.set(name, cache)
|
|
74
|
+
return cache
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Counts/limits only; never returns cache keys, bodies or private library ids. */
|
|
78
|
+
export function cacheDiagnostics() {
|
|
79
|
+
return Object.fromEntries([...registry].map(([name, cache]) => [name, cache.stats()]))
|
|
80
|
+
}
|