dsh-memu-memory 1.4.4 → 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 +11 -0
- package/README.md +33 -14
- package/README.zh.md +34 -12
- 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/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 +30 -4
- 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 +93 -10
- 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/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/lib/global-graph.js
CHANGED
|
@@ -24,12 +24,15 @@
|
|
|
24
24
|
// cannot smuggle a bad edge in.
|
|
25
25
|
|
|
26
26
|
import { createHash } from 'node:crypto'
|
|
27
|
+
import path from 'node:path'
|
|
27
28
|
import { record } from './activity-log.js'
|
|
28
|
-
import { loadGlobalIndex, updateGlobalIndex } from './state.js'
|
|
29
|
-
import { redactSecrets } from './paths.js'
|
|
29
|
+
import { loadGlobalIndex, readGlobalIndex, indexReadRevision, updateGlobalIndex } from './state.js'
|
|
30
|
+
import { redactSecrets, dataDir, indexDir, readFailure, warn } from './paths.js'
|
|
30
31
|
import { groundEvidence, groundLinkNote } from './curator-evidence.js'
|
|
31
32
|
import { globalConflictCheck } from './text-retrieval.js'
|
|
32
33
|
import { graphDomain } from './graph.js'
|
|
34
|
+
import { cachedGraphOverview } from './graph-overview.js'
|
|
35
|
+
import { getGraphAdjacency } from './graph-adjacency-index.js'
|
|
33
36
|
import {
|
|
34
37
|
GLOBAL_LINK_KINDS,
|
|
35
38
|
LINK_CONFIDENCE_MIN,
|
|
@@ -246,6 +249,46 @@ export function applyGlobalLinks(entries, writes, { now = new Date().toISOString
|
|
|
246
249
|
|
|
247
250
|
const GRAPH_HIDDEN_STATUS = new Set(['suppressed', 'expired'])
|
|
248
251
|
|
|
252
|
+
export function getGlobalGraphOverview(args = {}) {
|
|
253
|
+
const index = readGlobalIndex(), domainFilter = graphDomain(args.domain)
|
|
254
|
+
if (readFailure(path.join(indexDir(), 'global.json'))) throw new Error('cannot read graph index; restore it before reading')
|
|
255
|
+
const key = [dataDir(), 'global', domainFilter], revision = indexReadRevision(index)
|
|
256
|
+
return cachedGraphOverview({ key, revision,
|
|
257
|
+
adjacency: revision ? build => getGraphAdjacency({ scope: 'global', libraryId: null,
|
|
258
|
+
key, revision, entityRevision: 'none', build }) : null,
|
|
259
|
+
onAdjacencyError: () => warn('global graph adjacency read failed; using canonical graph topology'), build: () => {
|
|
260
|
+
const entries = index.entries || {}, visible = new Set(), domains = new Set(), nodes = new Map(), edges = [], seen = new Set()
|
|
261
|
+
const add = id => {
|
|
262
|
+
if (nodes.has(id)) return
|
|
263
|
+
const entry = entries[id], strength = Number(entry?.strength ?? entry?.confidence ?? .5)
|
|
264
|
+
nodes.set(id, { id, title: entry?.title || '[deleted]', layer: entry?.layer || null, kind: 'global',
|
|
265
|
+
domain: entry ? graphDomain(entry.domain) || 'unknown' : null, status: entry?.status || 'active',
|
|
266
|
+
strength: Number.isFinite(strength) ? Math.max(0, Math.min(1, strength)) : .5, degree: 0, missing: !entry })
|
|
267
|
+
}
|
|
268
|
+
for (const [id, entry] of Object.entries(entries)) {
|
|
269
|
+
if (!entry || GRAPH_HIDDEN_STATUS.has(entry.status || 'active')) continue
|
|
270
|
+
const domain = graphDomain(entry.domain) || 'unknown'
|
|
271
|
+
domains.add(domain)
|
|
272
|
+
if (!domainFilter || domain === domainFilter) visible.add(id)
|
|
273
|
+
}
|
|
274
|
+
for (const from of visible) {
|
|
275
|
+
add(from)
|
|
276
|
+
for (const link of entries[from].links || []) {
|
|
277
|
+
const to = String(link?.to || '')
|
|
278
|
+
if (!GLOBAL_LINK_KINDS.includes(link?.kind) || !to || (entries[to] && !visible.has(to))) continue
|
|
279
|
+
const key = link.id || JSON.stringify([from, link.kind, to])
|
|
280
|
+
if (seen.has(key)) continue
|
|
281
|
+
seen.add(key); add(to)
|
|
282
|
+
const [edgeFrom, edgeTo] = link.kind === 'related' ? [from, to].sort() : [from, to]
|
|
283
|
+
edges.push({ from: edgeFrom, to: edgeTo, kind: link.kind, note: link.note,
|
|
284
|
+
confidence: Number.isFinite(Number(link.confidence)) ? Number(link.confidence) : .7, source: link.source || null })
|
|
285
|
+
nodes.get(from).degree++; nodes.get(to).degree++
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return { nodes: [...nodes.values()], edges, domains: [...domains].sort() }
|
|
289
|
+
} }, { ...args, scope: 'global' })
|
|
290
|
+
}
|
|
291
|
+
|
|
249
292
|
/**
|
|
250
293
|
* getGlobalGraph({ focusId, depth, limit }) — read-only node graph over the
|
|
251
294
|
* global index. Private memory has getGraph in graph.js; global edges live in
|
|
@@ -258,6 +301,7 @@ const GRAPH_HIDDEN_STATUS = new Set(['suppressed', 'expired'])
|
|
|
258
301
|
*/
|
|
259
302
|
export function getGlobalGraph({ focusId = null, depth = 1, limit = 200, domain } = {}) {
|
|
260
303
|
const index = loadGlobalIndex()
|
|
304
|
+
if (readFailure(path.join(indexDir(), 'global.json'))) throw new Error('cannot read graph index; restore it before reading')
|
|
261
305
|
const entries = index.entries || {}
|
|
262
306
|
const cap = Math.max(1, Math.min(200, Math.floor(Number(limit) || 200)))
|
|
263
307
|
const hops = Math.max(0, Math.min(2, Math.floor(Number(depth) || 0)))
|
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import { dataDir, warn, withFileLock } from './paths.js'
|
|
5
|
+
import { recordDiagnostic } from './diagnostics.js'
|
|
6
|
+
import { createBoundedCache } from './bounded-cache.js'
|
|
7
|
+
|
|
8
|
+
export const GRAPH_ADJACENCY_VERSION = 1
|
|
9
|
+
export const GRAPH_ADJACENCY_LIMITS = Object.freeze({
|
|
10
|
+
maxBytes: 16 * 1024 * 1024, maxEntries: 32, ttlMs: 120000,
|
|
11
|
+
maxDiskBytes: 256 * 1024 * 1024, maxIdentities: 16,
|
|
12
|
+
maxIndexBytes: 128 * 1024 * 1024, maxNodesBytes: 16 * 1024 * 1024,
|
|
13
|
+
maxNodes: 1000000, maxEdges: 4000000, slots: 2,
|
|
14
|
+
})
|
|
15
|
+
const NS = 'dsh-memu-memory/graph-adjacency'
|
|
16
|
+
const HEX = /^[a-f0-9]{64}$/
|
|
17
|
+
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
|
|
18
|
+
const SLOT = /^slot-[01]$/
|
|
19
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0
|
|
20
|
+
const hash = value => crypto.createHash('sha256').update(value).digest('hex')
|
|
21
|
+
const json = value => JSON.stringify(value)
|
|
22
|
+
const stats = { loads: 0, hits: 0, fallbacks: 0, published: 0, publishFailures: 0, evictedIdentities: 0, lastError: null }
|
|
23
|
+
const cache = createBoundedCache({ name: 'graph-adjacency', ...GRAPH_ADJACENCY_LIMITS,
|
|
24
|
+
sizeOf: state => 2048 + state.ids.reduce((n, id) => n + 48 + id.length * 2, 0)
|
|
25
|
+
+ state.kinds.reduce((n, kind) => n + 48 + kind.length * 2, 0) + state.out.byteLength + state.incoming.byteLength })
|
|
26
|
+
|
|
27
|
+
function failure(suffix) {
|
|
28
|
+
const error = new Error(`graph adjacency ${suffix.toLowerCase()}`)
|
|
29
|
+
error.code = `GRAPH_ADJACENCY_${suffix}`
|
|
30
|
+
return error
|
|
31
|
+
}
|
|
32
|
+
function insist(ok, suffix = 'CORRUPT') { if (!ok) throw failure(suffix) }
|
|
33
|
+
function codeOf(error) {
|
|
34
|
+
return /^GRAPH_ADJACENCY_(MISSING|STALE|CORRUPT|UNSAFE|IO|CAPACITY)$/.test(error?.code)
|
|
35
|
+
? error.code : error?.code === 'ENOENT' ? 'GRAPH_ADJACENCY_MISSING' : 'GRAPH_ADJACENCY_IO'
|
|
36
|
+
}
|
|
37
|
+
function report(code) {
|
|
38
|
+
stats.lastError = code
|
|
39
|
+
warn(`${code}: using current authorized graph source`)
|
|
40
|
+
recordDiagnostic({ level: 'warn', scope: 'graph', code, alert: false,
|
|
41
|
+
message: 'Graph adjacency unavailable; using current authorized graph source.',
|
|
42
|
+
hint: 'The adjacency index is derived and is rebuilt on demand. Canonical graph data is unchanged.',
|
|
43
|
+
source: 'graph-adjacency', detail: { code } })
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Only complete JSON descriptors are admitted. In particular, undefined cannot
|
|
47
|
+
// collapse a missing permission input into an existing persisted view.
|
|
48
|
+
function canonical(value) {
|
|
49
|
+
const active = new Set()
|
|
50
|
+
let count = 0
|
|
51
|
+
function visit(item, depth) {
|
|
52
|
+
if (++count > 100000 || depth > 32) throw new TypeError('graph adjacency descriptor too large')
|
|
53
|
+
if (item === null || typeof item === 'boolean' || typeof item === 'string') return item
|
|
54
|
+
if (typeof item === 'number' && Number.isFinite(item)) return item
|
|
55
|
+
if (typeof item !== 'object' || active.has(item)
|
|
56
|
+
|| (!Array.isArray(item) && ![Object.prototype, null].includes(Object.getPrototypeOf(item)))) {
|
|
57
|
+
throw new TypeError('graph adjacency requires complete JSON descriptors')
|
|
58
|
+
}
|
|
59
|
+
active.add(item)
|
|
60
|
+
const result = Array.isArray(item) ? Array.from(item, val => visit(val, depth + 1))
|
|
61
|
+
: Object.fromEntries(Object.keys(item).sort().map(key => [key, visit(item[key], depth + 1)]))
|
|
62
|
+
active.delete(item)
|
|
63
|
+
return result
|
|
64
|
+
}
|
|
65
|
+
const text = json(visit(value, 0))
|
|
66
|
+
if (Buffer.byteLength(text) > 1024 * 1024) throw new TypeError('graph adjacency descriptor too large')
|
|
67
|
+
return text
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function graphAdjacencyLocation({ directory = path.join(dataDir(), 'rt', 'graph-adjacency'), scope, libraryId = null, key } = {}) {
|
|
71
|
+
if (!['private', 'global'].includes(scope) || (scope === 'private' && (typeof libraryId !== 'string' || !libraryId.trim()))
|
|
72
|
+
|| (scope === 'global' && libraryId !== null) || key === undefined || key === null
|
|
73
|
+
|| (typeof key === 'string' && !key.trim()) || typeof directory !== 'string' || !directory) {
|
|
74
|
+
throw new TypeError('graph adjacency requires scope, owner and complete permission key')
|
|
75
|
+
}
|
|
76
|
+
const identity = hash(canonical([GRAPH_ADJACENCY_VERSION, scope, libraryId, hash(canonical(key))]))
|
|
77
|
+
directory = path.resolve(directory)
|
|
78
|
+
const root = path.join(directory, identity)
|
|
79
|
+
return { directory, identity, root, pointer: path.join(root, 'current.json') }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function descriptor(options) {
|
|
83
|
+
const location = graphAdjacencyLocation(options)
|
|
84
|
+
for (const key of ['revision', 'entityRevision']) {
|
|
85
|
+
if (typeof options[key] !== 'string' || !options[key].trim() || options[key].length > 1048576) {
|
|
86
|
+
throw new TypeError(`graph adjacency requires ${key}`)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (typeof options.build !== 'function') throw new TypeError('graph adjacency requires source builder')
|
|
90
|
+
return { ...location, source: {
|
|
91
|
+
revision: hash(options.revision), entityRevision: hash(options.entityRevision),
|
|
92
|
+
permission: hash(canonical(options.key)), owner: hash(canonical([options.scope, options.libraryId ?? null])),
|
|
93
|
+
} }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function stamp(stat) { return [stat.size, stat.mtimeNs, stat.ctimeNs, stat.ino, stat.dev].join(':') }
|
|
97
|
+
function inspect(file, directory = false) {
|
|
98
|
+
const stat = fs.lstatSync(file, { bigint: true })
|
|
99
|
+
insist(!stat.isSymbolicLink() && (directory ? stat.isDirectory() : stat.isFile() && stat.nlink === 1n), 'UNSAFE')
|
|
100
|
+
return stat
|
|
101
|
+
}
|
|
102
|
+
function directoryChain(directory, create = false) {
|
|
103
|
+
const resolved = path.resolve(directory), base = path.parse(resolved).root
|
|
104
|
+
let current = base
|
|
105
|
+
inspect(current, true)
|
|
106
|
+
for (const part of path.relative(base, resolved).split(path.sep).filter(Boolean)) {
|
|
107
|
+
current = path.join(current, part)
|
|
108
|
+
if (create) {
|
|
109
|
+
try { fs.mkdirSync(current, { mode: 0o700 }) } catch (error) { if (error.code !== 'EEXIST') throw error }
|
|
110
|
+
}
|
|
111
|
+
inspect(current, true)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function readFile(file, max) {
|
|
115
|
+
directoryChain(path.dirname(file))
|
|
116
|
+
const before = inspect(file)
|
|
117
|
+
insist(before.size <= BigInt(max), 'CAPACITY')
|
|
118
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0))
|
|
119
|
+
try {
|
|
120
|
+
insist(stamp(fs.fstatSync(fd, { bigint: true })) === stamp(before), 'UNSAFE')
|
|
121
|
+
const result = Buffer.alloc(Number(before.size))
|
|
122
|
+
let offset = 0
|
|
123
|
+
while (offset < result.length) {
|
|
124
|
+
const count = fs.readSync(fd, result, offset, result.length - offset, offset)
|
|
125
|
+
insist(count > 0)
|
|
126
|
+
offset += count
|
|
127
|
+
}
|
|
128
|
+
insist(stamp(fs.fstatSync(fd, { bigint: true })) === stamp(before) && stamp(inspect(file)) === stamp(before), 'CORRUPT')
|
|
129
|
+
return result
|
|
130
|
+
} finally { fs.closeSync(fd) }
|
|
131
|
+
}
|
|
132
|
+
function readJson(file, max = 32768) {
|
|
133
|
+
try { return JSON.parse(readFile(file, max).toString('utf8')) } catch (error) {
|
|
134
|
+
if (error instanceof SyntaxError) throw failure('CORRUPT')
|
|
135
|
+
throw error
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function seal(payload) { return { payload, checksum: hash(canonical(payload)) } }
|
|
139
|
+
function unseal(value) {
|
|
140
|
+
insist(value && typeof value === 'object' && HEX.test(value.checksum))
|
|
141
|
+
insist(hash(canonical(value.payload)) === value.checksum)
|
|
142
|
+
return value.payload
|
|
143
|
+
}
|
|
144
|
+
function syncDirectory(directory) {
|
|
145
|
+
let fd
|
|
146
|
+
try { fd = fs.openSync(directory, 'r'); fs.fsyncSync(fd) } catch (error) {
|
|
147
|
+
if (!['EISDIR', 'EINVAL', 'ENOTSUP', 'EPERM', 'EACCES', 'EBADF'].includes(error.code)) throw error
|
|
148
|
+
} finally { if (fd !== undefined) fs.closeSync(fd) }
|
|
149
|
+
}
|
|
150
|
+
function removeFile(file) {
|
|
151
|
+
try { inspect(file); fs.unlinkSync(file) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
152
|
+
}
|
|
153
|
+
function writeFile(file, bytes) {
|
|
154
|
+
directoryChain(path.dirname(file))
|
|
155
|
+
try { inspect(file) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
156
|
+
const next = `${file}.next`
|
|
157
|
+
removeFile(next)
|
|
158
|
+
let fd
|
|
159
|
+
try {
|
|
160
|
+
fd = fs.openSync(next, 'wx', 0o600)
|
|
161
|
+
fs.writeFileSync(fd, bytes)
|
|
162
|
+
fs.fsyncSync(fd)
|
|
163
|
+
fs.closeSync(fd); fd = undefined
|
|
164
|
+
directoryChain(path.dirname(file))
|
|
165
|
+
fs.renameSync(next, file)
|
|
166
|
+
syncDirectory(path.dirname(file))
|
|
167
|
+
} finally { if (fd !== undefined) fs.closeSync(fd) }
|
|
168
|
+
}
|
|
169
|
+
const ownerPayload = identity => ({ namespace: NS, version: GRAPH_ADJACENCY_VERSION, identity })
|
|
170
|
+
function checkOwner(directory, identity, create = false, repairPending = false) {
|
|
171
|
+
directoryChain(directory, create)
|
|
172
|
+
const owner = path.join(directory, 'owner.json')
|
|
173
|
+
try { insist(canonical(unseal(readJson(owner))) === canonical(ownerPayload(identity)), 'UNSAFE') } catch (error) {
|
|
174
|
+
if (error.code !== 'ENOENT' || (!create && !repairPending)) throw error
|
|
175
|
+
const names = fs.readdirSync(directory).filter(name => identity !== 'namespace' || name !== 'publication.lock')
|
|
176
|
+
if (names.length === 1 && names[0] === 'owner.json.next') {
|
|
177
|
+
insist(canonical(unseal(readJson(`${owner}.next`))) === canonical(ownerPayload(identity)), 'UNSAFE')
|
|
178
|
+
} else insist(create && names.length === 0, 'UNSAFE')
|
|
179
|
+
writeFile(owner, json(seal(ownerPayload(identity))))
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function locked(desc, action, create = false) {
|
|
183
|
+
directoryChain(desc.directory, create)
|
|
184
|
+
const lock = path.join(desc.directory, 'publication.lock')
|
|
185
|
+
try { inspect(lock) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
186
|
+
return withFileLock(path.join(desc.directory, 'publication'), () => {
|
|
187
|
+
directoryChain(desc.directory)
|
|
188
|
+
checkOwner(desc.directory, 'namespace', create)
|
|
189
|
+
return action()
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
function pointerAt(desc) {
|
|
193
|
+
checkOwner(desc.root, desc.identity)
|
|
194
|
+
const pointer = unseal(readJson(desc.pointer))
|
|
195
|
+
insist(pointer.namespace === NS && pointer.version === GRAPH_ADJACENCY_VERSION && pointer.identity === desc.identity
|
|
196
|
+
&& SLOT.test(pointer.slot) && UUID.test(pointer.generation) && HEX.test(pointer.manifest))
|
|
197
|
+
return pointer
|
|
198
|
+
}
|
|
199
|
+
function sameSource(a, b) {
|
|
200
|
+
return a && b && ['revision', 'entityRevision', 'permission', 'owner'].every(key => HEX.test(a[key]) && a[key] === b[key])
|
|
201
|
+
}
|
|
202
|
+
function fileStamps(desc, pointer) {
|
|
203
|
+
directoryChain(desc.root)
|
|
204
|
+
const slot = path.join(desc.root, pointer.slot)
|
|
205
|
+
directoryChain(slot)
|
|
206
|
+
return [path.join(desc.directory, 'owner.json'), path.join(desc.root, 'owner.json'), desc.pointer,
|
|
207
|
+
path.join(slot, 'manifest.json'), path.join(slot, 'nodes.json'), path.join(slot, 'edges.idx')]
|
|
208
|
+
.map(file => stamp(inspect(file))).join('|')
|
|
209
|
+
}
|
|
210
|
+
function layout(nodes, edges) {
|
|
211
|
+
const out = 32, incoming = out + (nodes + 1) * 4, outRows = incoming + (nodes + 1) * 4
|
|
212
|
+
const inRows = outRows + edges * 4, records = inRows + edges * 4
|
|
213
|
+
return { out, incoming, outRows, inRows, records, bytes: records + edges * 16 }
|
|
214
|
+
}
|
|
215
|
+
function validId(id) { return typeof id === 'string' && id.length > 0 && Buffer.byteLength(id) <= 1024 }
|
|
216
|
+
function validKind(kind) { return typeof kind === 'string' && /^[A-Za-z0-9_.:-]{0,64}$/.test(kind) }
|
|
217
|
+
function validateBinary(buffer, ids, kinds, expectedEdges) {
|
|
218
|
+
insist(buffer.length >= 40 && buffer.toString('ascii', 0, 4) === 'DMGA' && buffer.readUInt32LE(4) === GRAPH_ADJACENCY_VERSION)
|
|
219
|
+
const nodes = buffer.readUInt32LE(8), edges = buffer.readUInt32LE(12)
|
|
220
|
+
insist(nodes === ids.length && edges === expectedEdges && nodes <= GRAPH_ADJACENCY_LIMITS.maxNodes
|
|
221
|
+
&& edges <= GRAPH_ADJACENCY_LIMITS.maxEdges && buffer.readUInt32LE(16) === 16
|
|
222
|
+
&& buffer.subarray(20, 32).every(byte => byte === 0))
|
|
223
|
+
const loc = layout(nodes, edges)
|
|
224
|
+
insist(buffer.length === loc.bytes)
|
|
225
|
+
let previous = -1
|
|
226
|
+
for (let row = 0; row < edges; row++) {
|
|
227
|
+
const pos = loc.records + row * 16
|
|
228
|
+
insist(buffer.readUInt32LE(pos) < nodes && buffer.readUInt32LE(pos + 4) < nodes
|
|
229
|
+
&& buffer.readUInt32LE(pos + 8) < kinds.length && buffer.readUInt32LE(pos + 12) > previous)
|
|
230
|
+
previous = buffer.readUInt32LE(pos + 12)
|
|
231
|
+
}
|
|
232
|
+
const arrays = []
|
|
233
|
+
for (const [offset, rows, field] of [[loc.out, loc.outRows, 0], [loc.incoming, loc.inRows, 4]]) {
|
|
234
|
+
// Copy offsets: a subarray would accidentally retain the whole edge table.
|
|
235
|
+
const offsets = new Uint32Array(nodes + 1)
|
|
236
|
+
for (let i = 0; i <= nodes; i++) offsets[i] = buffer.readUInt32LE(offset + i * 4)
|
|
237
|
+
insist(offsets[0] === 0 && offsets[nodes] === edges)
|
|
238
|
+
for (let i = 0; i < nodes; i++) {
|
|
239
|
+
insist(offsets[i] <= offsets[i + 1] && offsets[i + 1] <= edges)
|
|
240
|
+
let last = -1
|
|
241
|
+
for (let j = offsets[i]; j < offsets[i + 1]; j++) {
|
|
242
|
+
const row = buffer.readUInt32LE(rows + j * 4)
|
|
243
|
+
insist(row < edges && row > last && buffer.readUInt32LE(loc.records + row * 16 + field) === i)
|
|
244
|
+
last = row
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
arrays.push(offsets)
|
|
248
|
+
}
|
|
249
|
+
return { out: arrays[0], incoming: arrays[1], loc }
|
|
250
|
+
}
|
|
251
|
+
function load(desc) {
|
|
252
|
+
const pointer = pointerAt(desc), key = `${desc.root}:${hash(canonical(desc.source))}`
|
|
253
|
+
const before = fileStamps(desc, pointer), cached = cache.get(key)
|
|
254
|
+
if (cached && cached.signature === before && cached.generation === pointer.generation) { stats.hits++; return cached }
|
|
255
|
+
cache.delete(key)
|
|
256
|
+
const slot = path.join(desc.root, pointer.slot)
|
|
257
|
+
const manifestBytes = readFile(path.join(slot, 'manifest.json'), 32768)
|
|
258
|
+
insist(hash(manifestBytes) === pointer.manifest)
|
|
259
|
+
let manifest
|
|
260
|
+
try { manifest = JSON.parse(manifestBytes) } catch { throw failure('CORRUPT') }
|
|
261
|
+
insist(manifest.namespace === NS && manifest.version === GRAPH_ADJACENCY_VERSION && manifest.identity === desc.identity
|
|
262
|
+
&& manifest.generation === pointer.generation && Number.isSafeInteger(manifest.edgeCount) && manifest.edgeCount >= 0
|
|
263
|
+
&& Number.isSafeInteger(manifest.nodeCount) && manifest.nodeCount >= 0)
|
|
264
|
+
insist(sameSource(manifest.source, desc.source), 'STALE')
|
|
265
|
+
const files = {}
|
|
266
|
+
for (const [name, max] of [['nodes.json', GRAPH_ADJACENCY_LIMITS.maxNodesBytes], ['edges.idx', GRAPH_ADJACENCY_LIMITS.maxIndexBytes]]) {
|
|
267
|
+
const info = manifest.files?.[name]
|
|
268
|
+
insist(info && Number.isSafeInteger(info.bytes) && info.bytes >= 0 && info.bytes <= max && HEX.test(info.sha256))
|
|
269
|
+
files[name] = readFile(path.join(slot, name), max)
|
|
270
|
+
insist(files[name].length === info.bytes && hash(files[name]) === info.sha256)
|
|
271
|
+
}
|
|
272
|
+
let metadata
|
|
273
|
+
try { metadata = JSON.parse(files['nodes.json']) } catch { throw failure('CORRUPT') }
|
|
274
|
+
const { ids, kinds } = metadata
|
|
275
|
+
insist(metadata.version === GRAPH_ADJACENCY_VERSION && Array.isArray(ids) && ids.length === manifest.nodeCount
|
|
276
|
+
&& ids.length <= GRAPH_ADJACENCY_LIMITS.maxNodes && Array.isArray(kinds) && kinds.length <= 65536
|
|
277
|
+
&& ids.every((id, i) => validId(id) && (i === 0 || compare(ids[i - 1], id) < 0))
|
|
278
|
+
&& kinds.every((kind, i) => validKind(kind) && (i === 0 || compare(kinds[i - 1], kind) < 0)))
|
|
279
|
+
const binary = validateBinary(files['edges.idx'], ids, kinds, manifest.edgeCount)
|
|
280
|
+
insist(fileStamps(desc, pointer) === before)
|
|
281
|
+
const state = { ids, kinds, ...binary, edgeCount: manifest.edgeCount, signature: before,
|
|
282
|
+
generation: pointer.generation, file: path.join(slot, 'edges.idx'), indexStamp: stamp(inspect(path.join(slot, 'edges.idx'))) }
|
|
283
|
+
cache.set(key, state); stats.loads++
|
|
284
|
+
return state
|
|
285
|
+
}
|
|
286
|
+
function topology(build) {
|
|
287
|
+
const graph = build()
|
|
288
|
+
if (!graph || !Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) throw new TypeError('invalid authorized graph source')
|
|
289
|
+
const ids = [...new Set(graph.nodes.map(node => {
|
|
290
|
+
if (!validId(node?.id)) throw new TypeError('invalid authorized graph node ID')
|
|
291
|
+
return node.id
|
|
292
|
+
}))].sort(compare)
|
|
293
|
+
const known = new Set(ids), edges = []
|
|
294
|
+
graph.edges.forEach((edge, ordinal) => {
|
|
295
|
+
if (!validId(edge?.from) || !validId(edge?.to) || !validKind(edge.kind ?? '')) throw new TypeError('invalid authorized graph edge')
|
|
296
|
+
if (known.has(edge.from) && known.has(edge.to)) edges.push({ from: edge.from, to: edge.to, kind: edge.kind ?? '', ordinal })
|
|
297
|
+
})
|
|
298
|
+
return { ids, edges }
|
|
299
|
+
}
|
|
300
|
+
function encode(source) {
|
|
301
|
+
const { ids, edges } = source, loc = layout(ids.length, edges.length)
|
|
302
|
+
insist(ids.length <= GRAPH_ADJACENCY_LIMITS.maxNodes && edges.length <= GRAPH_ADJACENCY_LIMITS.maxEdges
|
|
303
|
+
&& loc.bytes <= GRAPH_ADJACENCY_LIMITS.maxIndexBytes && (!edges.length || edges.at(-1).ordinal <= 0xffffffff), 'CAPACITY')
|
|
304
|
+
const kinds = [...new Set(edges.map(edge => edge.kind))].sort(compare)
|
|
305
|
+
insist(kinds.length <= 65536, 'CAPACITY')
|
|
306
|
+
const nodes = Buffer.from(json({ version: GRAPH_ADJACENCY_VERSION, ids, kinds }))
|
|
307
|
+
insist(nodes.length <= GRAPH_ADJACENCY_LIMITS.maxNodesBytes, 'CAPACITY')
|
|
308
|
+
const bytes = Buffer.alloc(loc.bytes), byId = new Map(ids.map((id, i) => [id, i])), byKind = new Map(kinds.map((kind, i) => [kind, i]))
|
|
309
|
+
bytes.write('DMGA'); bytes.writeUInt32LE(GRAPH_ADJACENCY_VERSION, 4)
|
|
310
|
+
bytes.writeUInt32LE(ids.length, 8); bytes.writeUInt32LE(edges.length, 12); bytes.writeUInt32LE(16, 16)
|
|
311
|
+
const out = new Uint32Array(ids.length + 1), incoming = new Uint32Array(ids.length + 1)
|
|
312
|
+
edges.forEach((edge, row) => {
|
|
313
|
+
const from = byId.get(edge.from), to = byId.get(edge.to), pos = loc.records + row * 16
|
|
314
|
+
out[from + 1]++; incoming[to + 1]++
|
|
315
|
+
bytes.writeUInt32LE(from, pos); bytes.writeUInt32LE(to, pos + 4)
|
|
316
|
+
bytes.writeUInt32LE(byKind.get(edge.kind), pos + 8); bytes.writeUInt32LE(edge.ordinal, pos + 12)
|
|
317
|
+
})
|
|
318
|
+
for (let i = 1; i <= ids.length; i++) { out[i] += out[i - 1]; incoming[i] += incoming[i - 1] }
|
|
319
|
+
for (let i = 0; i <= ids.length; i++) { bytes.writeUInt32LE(out[i], loc.out + i * 4); bytes.writeUInt32LE(incoming[i], loc.incoming + i * 4) }
|
|
320
|
+
const outCursor = out.slice(), inCursor = incoming.slice()
|
|
321
|
+
edges.forEach((edge, row) => {
|
|
322
|
+
bytes.writeUInt32LE(row, loc.outRows + outCursor[byId.get(edge.from)]++ * 4)
|
|
323
|
+
bytes.writeUInt32LE(row, loc.inRows + inCursor[byId.get(edge.to)]++ * 4)
|
|
324
|
+
})
|
|
325
|
+
return { 'nodes.json': nodes, 'edges.idx': bytes }
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const SLOT_FILES = new Set(['nodes.json', 'edges.idx', 'manifest.json', 'nodes.json.next', 'edges.idx.next', 'manifest.json.next'])
|
|
329
|
+
const ROOT_FILES = new Set(['owner.json', 'current.json', 'current.json.next', 'slot-0', 'slot-1'])
|
|
330
|
+
// Destruction is confined to exact reserved names below a checksum-validated
|
|
331
|
+
// ownership marker. Unknown content and all links/hardlinks prevent recycling.
|
|
332
|
+
function inventory(root, identity) {
|
|
333
|
+
checkOwner(root, identity, false, true)
|
|
334
|
+
const files = [], dirs = []
|
|
335
|
+
let bytes = 0
|
|
336
|
+
for (const name of fs.readdirSync(root)) {
|
|
337
|
+
insist(ROOT_FILES.has(name), 'UNSAFE')
|
|
338
|
+
const full = path.join(root, name)
|
|
339
|
+
if (SLOT.test(name)) {
|
|
340
|
+
inspect(full, true); dirs.push(full)
|
|
341
|
+
for (const child of fs.readdirSync(full)) {
|
|
342
|
+
insist(SLOT_FILES.has(child), 'UNSAFE')
|
|
343
|
+
const file = path.join(full, child), info = inspect(file)
|
|
344
|
+
files.push(file); bytes += Number(info.size)
|
|
345
|
+
}
|
|
346
|
+
} else { const info = inspect(full); files.push(full); bytes += Number(info.size) }
|
|
347
|
+
}
|
|
348
|
+
let age
|
|
349
|
+
try { age = Number(inspect(path.join(root, 'current.json')).mtimeMs) } catch (error) {
|
|
350
|
+
if (error.code !== 'ENOENT') throw error
|
|
351
|
+
age = Number(inspect(path.join(root, 'owner.json')).mtimeMs)
|
|
352
|
+
}
|
|
353
|
+
return { root, identity, files, dirs, bytes, age }
|
|
354
|
+
}
|
|
355
|
+
function eraseSlot(root, slot) {
|
|
356
|
+
const directory = path.join(root, slot)
|
|
357
|
+
try { inspect(directory, true) } catch (error) { if (error.code === 'ENOENT') return; throw error }
|
|
358
|
+
const names = fs.readdirSync(directory)
|
|
359
|
+
for (const name of names) { insist(SLOT_FILES.has(name), 'UNSAFE'); inspect(path.join(directory, name)) }
|
|
360
|
+
for (const name of names) removeFile(path.join(directory, name))
|
|
361
|
+
}
|
|
362
|
+
function diskRoom(desc, reserve, newIdentity) {
|
|
363
|
+
const roots = []
|
|
364
|
+
let total = 0
|
|
365
|
+
const names = fs.readdirSync(desc.directory)
|
|
366
|
+
insist(names.length <= 128, 'CAPACITY')
|
|
367
|
+
for (const name of names) {
|
|
368
|
+
if (['owner.json', 'publication.lock'].includes(name)) continue
|
|
369
|
+
insist(HEX.test(name), 'UNSAFE')
|
|
370
|
+
const root = path.join(desc.directory, name)
|
|
371
|
+
const item = inventory(root, name)
|
|
372
|
+
total += item.bytes; roots.push(item)
|
|
373
|
+
}
|
|
374
|
+
let count = roots.length + (newIdentity ? 1 : 0)
|
|
375
|
+
for (const item of roots.filter(item => item.root !== desc.root).sort((a, b) => a.age - b.age || compare(a.identity, b.identity))) {
|
|
376
|
+
if (total + reserve <= GRAPH_ADJACENCY_LIMITS.maxDiskBytes && count <= GRAPH_ADJACENCY_LIMITS.maxIdentities) break
|
|
377
|
+
inventory(item.root, item.identity)
|
|
378
|
+
for (const file of item.files) removeFile(file)
|
|
379
|
+
for (const dir of item.dirs) fs.rmdirSync(dir)
|
|
380
|
+
fs.rmdirSync(item.root)
|
|
381
|
+
for (const key of [...cache.keys()]) if (key.startsWith(`${item.root}:`)) cache.delete(key)
|
|
382
|
+
total -= item.bytes; count--; stats.evictedIdentities++
|
|
383
|
+
}
|
|
384
|
+
insist(total + reserve <= GRAPH_ADJACENCY_LIMITS.maxDiskBytes && count <= GRAPH_ADJACENCY_LIMITS.maxIdentities, 'CAPACITY')
|
|
385
|
+
}
|
|
386
|
+
function publish(desc, source) {
|
|
387
|
+
const files = encode(source)
|
|
388
|
+
return locked(desc, () => {
|
|
389
|
+
let exists = true
|
|
390
|
+
try { inspect(desc.root, true) } catch (error) { if (error.code === 'ENOENT') exists = false; else throw error }
|
|
391
|
+
if (exists) checkOwner(desc.root, desc.identity, false, true)
|
|
392
|
+
let previous = null
|
|
393
|
+
if (exists) {
|
|
394
|
+
try { previous = pointerAt(desc) } catch (error) {
|
|
395
|
+
if (codeOf(error) === 'GRAPH_ADJACENCY_UNSAFE') throw error
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
// Without a trusted pointer, only a fully owned, ordinary reserved layout
|
|
399
|
+
// may be reused. The other fixed slot remains untouched until publication.
|
|
400
|
+
if (exists) inventory(desc.root, desc.identity)
|
|
401
|
+
const slot = previous?.slot === 'slot-0' ? 'slot-1' : 'slot-0'
|
|
402
|
+
if (exists) eraseSlot(desc.root, slot)
|
|
403
|
+
const reserve = Object.values(files).reduce((n, buffer) => n + buffer.length, 0) + 65536
|
|
404
|
+
diskRoom(desc, reserve, !exists)
|
|
405
|
+
checkOwner(desc.root, desc.identity, true)
|
|
406
|
+
const target = path.join(desc.root, slot)
|
|
407
|
+
directoryChain(target, true)
|
|
408
|
+
const generation = crypto.randomUUID(), manifest = {
|
|
409
|
+
namespace: NS, version: GRAPH_ADJACENCY_VERSION, identity: desc.identity,
|
|
410
|
+
generation, source: desc.source, nodeCount: source.ids.length, edgeCount: source.edges.length,
|
|
411
|
+
files: Object.fromEntries(Object.entries(files).map(([name, buffer]) => [name, { bytes: buffer.length, sha256: hash(buffer) }])),
|
|
412
|
+
}
|
|
413
|
+
for (const [name, buffer] of Object.entries(files)) writeFile(path.join(target, name), buffer)
|
|
414
|
+
for (const [name, info] of Object.entries(manifest.files)) {
|
|
415
|
+
const written = readFile(path.join(target, name), info.bytes)
|
|
416
|
+
insist(written.length === info.bytes && hash(written) === info.sha256)
|
|
417
|
+
}
|
|
418
|
+
const manifestBytes = Buffer.from(json(manifest))
|
|
419
|
+
writeFile(path.join(target, 'manifest.json'), manifestBytes)
|
|
420
|
+
insist(hash(readFile(path.join(target, 'manifest.json'), 32768)) === hash(manifestBytes))
|
|
421
|
+
const pointer = { namespace: NS, version: GRAPH_ADJACENCY_VERSION, identity: desc.identity, slot, generation, manifest: hash(manifestBytes) }
|
|
422
|
+
writeFile(desc.pointer, json(seal(pointer)))
|
|
423
|
+
stats.published++
|
|
424
|
+
return true
|
|
425
|
+
}, true)
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function binarySearch(ids, id) {
|
|
429
|
+
if (typeof id !== 'string') return -1
|
|
430
|
+
let lo = 0, hi = ids.length - 1
|
|
431
|
+
while (lo <= hi) {
|
|
432
|
+
const mid = Math.floor((lo + hi) / 2), order = compare(ids[mid], id)
|
|
433
|
+
if (order === 0) return mid
|
|
434
|
+
if (order < 0) lo = mid + 1
|
|
435
|
+
else hi = mid - 1
|
|
436
|
+
}
|
|
437
|
+
return -1
|
|
438
|
+
}
|
|
439
|
+
function readRows(state, { outgoing = [], incoming = [], all = false }) {
|
|
440
|
+
const fd = fs.openSync(state.file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)), results = []
|
|
441
|
+
try {
|
|
442
|
+
insist(stamp(fs.fstatSync(fd, { bigint: true })) === state.indexStamp)
|
|
443
|
+
let rows
|
|
444
|
+
if (all) rows = Array.from({ length: state.edgeCount }, (_, i) => i)
|
|
445
|
+
else {
|
|
446
|
+
const found = new Set()
|
|
447
|
+
for (const [ids, offsets, table] of [[outgoing, state.out, state.loc.outRows], [incoming, state.incoming, state.loc.inRows]]) {
|
|
448
|
+
for (const id of new Set(ids)) {
|
|
449
|
+
const index = binarySearch(state.ids, id)
|
|
450
|
+
if (index < 0) continue
|
|
451
|
+
const start = offsets[index], count = offsets[index + 1] - start
|
|
452
|
+
if (!count) continue
|
|
453
|
+
const order = Buffer.alloc(count * 4)
|
|
454
|
+
insist(fs.readSync(fd, order, 0, order.length, table + start * 4) === order.length)
|
|
455
|
+
for (let j = 0; j < count; j++) { const row = order.readUInt32LE(j * 4); insist(row < state.edgeCount); found.add(row) }
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
rows = [...found].sort((a, b) => a - b)
|
|
459
|
+
}
|
|
460
|
+
const fromIds = new Set(outgoing), toIds = new Set(incoming)
|
|
461
|
+
// Coalesce adjacent edge records, capped at 512 KiB transient read buffers.
|
|
462
|
+
for (let i = 0; i < rows.length;) {
|
|
463
|
+
let end = i + 1
|
|
464
|
+
while (end < rows.length && rows[end] === rows[end - 1] + 1 && end - i < 32768) end++
|
|
465
|
+
const bytes = Buffer.alloc((end - i) * 16)
|
|
466
|
+
insist(fs.readSync(fd, bytes, 0, bytes.length, state.loc.records + rows[i] * 16) === bytes.length)
|
|
467
|
+
for (let j = 0; j < end - i; j++) {
|
|
468
|
+
const pos = j * 16, from = bytes.readUInt32LE(pos), to = bytes.readUInt32LE(pos + 4), kind = bytes.readUInt32LE(pos + 8)
|
|
469
|
+
insist(from < state.ids.length && to < state.ids.length && kind < state.kinds.length
|
|
470
|
+
&& (all || fromIds.has(state.ids[from]) || toIds.has(state.ids[to])))
|
|
471
|
+
results.push({ from: state.ids[from], to: state.ids[to], kind: state.kinds[kind], ordinal: bytes.readUInt32LE(pos + 12) })
|
|
472
|
+
}
|
|
473
|
+
i = end
|
|
474
|
+
}
|
|
475
|
+
insist(stamp(fs.fstatSync(fd, { bigint: true })) === state.indexStamp)
|
|
476
|
+
return results
|
|
477
|
+
} finally { fs.closeSync(fd) }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** A handle never owns cached disk metadata; eviction releases it immediately. */
|
|
481
|
+
export function getGraphAdjacency(options = {}) {
|
|
482
|
+
const desc = descriptor(options)
|
|
483
|
+
let source = null, backend = 'persistent', fallback = null, generation = null, published = false
|
|
484
|
+
function recover(error) {
|
|
485
|
+
fallback = codeOf(error); backend = 'source'; generation = null
|
|
486
|
+
stats.fallbacks++; report(fallback)
|
|
487
|
+
source = topology(options.build)
|
|
488
|
+
try { published = publish(desc, source) } catch (publishError) {
|
|
489
|
+
stats.publishFailures++; report(codeOf(publishError))
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
function use(select) {
|
|
493
|
+
if (source) return select(null)
|
|
494
|
+
try {
|
|
495
|
+
return locked(desc, () => {
|
|
496
|
+
const state = load(desc), pointer = pointerAt(desc)
|
|
497
|
+
generation = state.generation
|
|
498
|
+
const result = select(state)
|
|
499
|
+
insist(fileStamps(desc, pointer) === state.signature)
|
|
500
|
+
return result
|
|
501
|
+
})
|
|
502
|
+
} catch (error) {
|
|
503
|
+
recover(error)
|
|
504
|
+
return select(null)
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
use(() => null)
|
|
508
|
+
const read = ({ outgoing = [], incoming = [], all = false } = {}) => {
|
|
509
|
+
if (!Array.isArray(outgoing) || !Array.isArray(incoming)) throw new TypeError('graph adjacency selection requires ID arrays')
|
|
510
|
+
const from = new Set(outgoing), to = new Set(incoming)
|
|
511
|
+
return use(state => state ? readRows(state, { outgoing, incoming, all })
|
|
512
|
+
: source.edges.filter(edge => all || from.has(edge.from) || to.has(edge.to)).map(edge => ({ ...edge })))
|
|
513
|
+
}
|
|
514
|
+
return {
|
|
515
|
+
get nodeIds() { return use(state => [...(state ? state.ids : source.ids)]) },
|
|
516
|
+
get edgeCount() { return use(state => state ? state.edgeCount : source.edges.length) },
|
|
517
|
+
outgoing: id => read({ outgoing: [id] }), incoming: id => read({ incoming: [id] }), readAll: () => read({ all: true }),
|
|
518
|
+
selectMany: selection => read(selection), outgoingMany: ids => read({ outgoing: ids }), incomingMany: ids => read({ incoming: ids }),
|
|
519
|
+
get backend() { return backend }, get fallback() { return fallback },
|
|
520
|
+
get generation() { return generation }, get published() { return published },
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export function graphAdjacencyDiagnostics() { return { ...stats, cache: cache.stats(), limits: { ...GRAPH_ADJACENCY_LIMITS } } }
|
|
525
|
+
export function clearGraphAdjacencyCache() { cache.clear() }
|