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
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import { buildCorpus } from '../text-retrieval.js'
|
|
5
|
+
import { withFileLock, writeJson } from '../paths.js'
|
|
6
|
+
import {
|
|
7
|
+
FORMAT_VERSION, HEAD_BYTES, fileDigest, fileStamp, headFromEntry, encodeHeads, writePostings,
|
|
8
|
+
invariant, rtError, sha256, writeDurable, syncDirectory,
|
|
9
|
+
} from './format.js'
|
|
10
|
+
import { MAX_SEGMENTS, MAX_DELTA_SEGMENTS, RULER_FINGERPRINT, memoryDocumentText, sourceInfo, indexLocation, readPublished } from './manifest.js'
|
|
11
|
+
|
|
12
|
+
function removeStaging(root, stage) {
|
|
13
|
+
const absoluteRoot = path.resolve(root)
|
|
14
|
+
const absoluteStage = path.resolve(stage)
|
|
15
|
+
invariant(path.dirname(absoluteStage) === absoluteRoot && /^\.build-[sg]-[a-f0-9-]{36}$/.test(path.basename(absoluteStage)), 'RT_UNSAFE_PATH')
|
|
16
|
+
if (fs.existsSync(absoluteStage) && !fs.lstatSync(absoluteStage).isSymbolicLink()) fs.rmSync(absoluteStage, { recursive: true, force: true })
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function buildSegments(root, rows, removedIds, { documentText, shardBytes, maxBuildBytes, segmentDocs }, kind, stages) {
|
|
20
|
+
const segments = []
|
|
21
|
+
const budget = Math.min(maxBuildBytes, 96 * 1024 * 1024)
|
|
22
|
+
let id, stage, records, inverted
|
|
23
|
+
let estimatedBytes = 0
|
|
24
|
+
let shard = -1
|
|
25
|
+
let shardLength = 0
|
|
26
|
+
let bodyFd = null
|
|
27
|
+
let bodyFiles
|
|
28
|
+
const closeBody = () => {
|
|
29
|
+
if (bodyFd === null) return
|
|
30
|
+
const fd = bodyFd
|
|
31
|
+
bodyFd = null
|
|
32
|
+
try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
|
33
|
+
}
|
|
34
|
+
const start = () => {
|
|
35
|
+
invariant(segments.length < MAX_SEGMENTS, 'RT_BUILD_LIMIT')
|
|
36
|
+
id = `s-${crypto.randomUUID()}`
|
|
37
|
+
stage = path.join(root, `.build-${id}`)
|
|
38
|
+
stages.push(stage)
|
|
39
|
+
fs.mkdirSync(path.join(stage, 'bodies'), { recursive: true, mode: 0o700 })
|
|
40
|
+
records = []
|
|
41
|
+
inverted = new Map()
|
|
42
|
+
estimatedBytes = 0
|
|
43
|
+
shard = -1
|
|
44
|
+
shardLength = 0
|
|
45
|
+
bodyFiles = []
|
|
46
|
+
}
|
|
47
|
+
const flush = () => {
|
|
48
|
+
closeBody()
|
|
49
|
+
const heads = encodeHeads(records)
|
|
50
|
+
const terms = writePostings(stage, inverted)
|
|
51
|
+
const artifacts = {
|
|
52
|
+
'heads.bin': heads.buffer, 'metadata.json': JSON.stringify(heads.metadata),
|
|
53
|
+
'terms.json': JSON.stringify(terms), 'removed.json': JSON.stringify(segments.length === 0 ? removedIds : []),
|
|
54
|
+
}
|
|
55
|
+
for (const [name, bytes] of Object.entries(artifacts)) {
|
|
56
|
+
invariant(Buffer.byteLength(bytes) <= (name.endsWith('.json') ? 32 * 1024 * 1024 : 256 * 1024 * 1024), 'RT_BUILD_LIMIT')
|
|
57
|
+
writeDurable(path.join(stage, name), bytes)
|
|
58
|
+
}
|
|
59
|
+
const files = Object.fromEntries([...Object.keys(artifacts), 'postings.bin', 'terms.bin', ...bodyFiles].map(name => [name, fileDigest(path.join(stage, name))]))
|
|
60
|
+
syncDirectory(path.join(stage, 'bodies'))
|
|
61
|
+
syncDirectory(stage)
|
|
62
|
+
segments.push({ id, kind, count: records.length, files })
|
|
63
|
+
}
|
|
64
|
+
start()
|
|
65
|
+
try {
|
|
66
|
+
for (const [entryId, entry] of rows) {
|
|
67
|
+
invariant(entry && typeof entry === 'object', 'RT_SOURCE_INVALID')
|
|
68
|
+
const body = Buffer.from(String(entry.content || ''), 'utf8')
|
|
69
|
+
invariant(body.length <= 16 * 1024 * 1024, 'RT_BUILD_LIMIT')
|
|
70
|
+
const text = documentText(entry)
|
|
71
|
+
invariant(Buffer.byteLength(String(entry.title || '')) + Buffer.byteLength(text) <= 16 * 1024 * 1024, 'RT_BUILD_LIMIT')
|
|
72
|
+
const doc = buildCorpus([{ id: entryId, title: entry.title || '', content: text }]).docs.get(entryId)
|
|
73
|
+
const estimate = () => {
|
|
74
|
+
let bytes = HEAD_BYTES + entryId.length * 2 + 192 + doc.tf.size * 32
|
|
75
|
+
for (const term of doc.tf.keys()) if (!inverted.has(term)) bytes += term.length * 2 + 160
|
|
76
|
+
return bytes
|
|
77
|
+
}
|
|
78
|
+
let nextBytes = estimate()
|
|
79
|
+
if (records.length && (estimatedBytes + nextBytes > budget || records.length >= segmentDocs)) {
|
|
80
|
+
flush()
|
|
81
|
+
start()
|
|
82
|
+
nextBytes = estimate()
|
|
83
|
+
}
|
|
84
|
+
invariant(nextBytes + body.length <= maxBuildBytes, 'RT_BUILD_LIMIT')
|
|
85
|
+
estimatedBytes += nextBytes
|
|
86
|
+
if (bodyFd === null || shardLength + body.length > shardBytes) {
|
|
87
|
+
closeBody()
|
|
88
|
+
shard++
|
|
89
|
+
shardLength = 0
|
|
90
|
+
const name = `bodies/${String(shard).padStart(8, '0')}.bin`
|
|
91
|
+
bodyFiles.push(name)
|
|
92
|
+
bodyFd = fs.openSync(path.join(stage, name), 'wx', 0o600)
|
|
93
|
+
}
|
|
94
|
+
fs.writeFileSync(bodyFd, body)
|
|
95
|
+
const slot = records.length
|
|
96
|
+
records.push(headFromEntry(entryId, entry, { shard, offset: shardLength, length: body.length }, doc.len))
|
|
97
|
+
shardLength += body.length
|
|
98
|
+
for (const [term, tf] of doc.tf) {
|
|
99
|
+
invariant(tf <= 65535, 'RT_TF_OVERFLOW')
|
|
100
|
+
if (!inverted.has(term)) inverted.set(term, [])
|
|
101
|
+
inverted.get(term).push(slot, tf)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
flush()
|
|
105
|
+
return segments
|
|
106
|
+
} finally {
|
|
107
|
+
closeBody()
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function publish(location, source, segments, documentVersion, stages) {
|
|
112
|
+
const generation = `g-${crypto.randomUUID()}`
|
|
113
|
+
const stage = path.join(location.root, `.build-${generation}`)
|
|
114
|
+
fs.mkdirSync(stage, { mode: 0o700 })
|
|
115
|
+
try {
|
|
116
|
+
const manifest = {
|
|
117
|
+
version: FORMAT_VERSION, identity: location.identity, namespace: location.namespace,
|
|
118
|
+
libraryId: location.libraryId, generation, state: 'ready',
|
|
119
|
+
ruler: RULER_FINGERPRINT, documentVersion, source,
|
|
120
|
+
createdAt: new Date().toISOString(), segments,
|
|
121
|
+
}
|
|
122
|
+
const bytes = JSON.stringify(manifest)
|
|
123
|
+
invariant(Buffer.byteLength(bytes) <= 1024 * 1024, 'RT_BUILD_LIMIT')
|
|
124
|
+
writeDurable(path.join(stage, 'manifest.json'), bytes)
|
|
125
|
+
syncDirectory(stage)
|
|
126
|
+
const segmentRoot = path.join(location.root, 'segments')
|
|
127
|
+
fs.mkdirSync(segmentRoot, { recursive: true, mode: 0o700 })
|
|
128
|
+
invariant(!fs.lstatSync(segmentRoot).isSymbolicLink(), 'RT_UNSAFE_PATH')
|
|
129
|
+
// Publication holds current.json's lock; retention never sees unpublished
|
|
130
|
+
// segments until they can be referenced by the same atomic publication.
|
|
131
|
+
for (const staged of stages) fs.renameSync(staged, path.join(segmentRoot, path.basename(staged).slice(7)))
|
|
132
|
+
syncDirectory(segmentRoot)
|
|
133
|
+
fs.renameSync(stage, path.join(location.root, generation))
|
|
134
|
+
syncDirectory(location.root)
|
|
135
|
+
writeJson(path.join(location.root, 'current.json'), { version: FORMAT_VERSION, generation, sha256: sha256(bytes) })
|
|
136
|
+
syncDirectory(location.root)
|
|
137
|
+
return { ok: true, generation, revision: source.revision, count: source.count, segments: segments.length }
|
|
138
|
+
} finally {
|
|
139
|
+
removeStaging(location.root, stage)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function settings(options) {
|
|
144
|
+
const config = {
|
|
145
|
+
documentText: options.documentText ?? memoryDocumentText,
|
|
146
|
+
documentVersion: options.documentVersion ?? 'memory-title-body-tags-captions-v1',
|
|
147
|
+
shardBytes: options.shardBytes ?? 16 * 1024 * 1024,
|
|
148
|
+
maxBuildBytes: options.maxBuildBytes ?? 192 * 1024 * 1024,
|
|
149
|
+
segmentDocs: options.segmentDocs ?? 8192,
|
|
150
|
+
}
|
|
151
|
+
invariant(typeof config.documentText === 'function' && typeof config.documentVersion === 'string' && config.documentVersion.length > 0, 'RT_OPTIONS_INVALID')
|
|
152
|
+
invariant(Number.isSafeInteger(config.shardBytes) && config.shardBytes > 0 && config.shardBytes <= 16 * 1024 * 1024, 'RT_OPTIONS_INVALID')
|
|
153
|
+
invariant(Number.isSafeInteger(config.maxBuildBytes) && config.maxBuildBytes > 0, 'RT_OPTIONS_INVALID')
|
|
154
|
+
invariant(Number.isSafeInteger(config.segmentDocs) && config.segmentDocs > 0 && config.segmentDocs <= 65536, 'RT_OPTIONS_INVALID')
|
|
155
|
+
return config
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Synchronous, caller-scheduled build. Never opens or writes the JSON truth store. */
|
|
159
|
+
export function rebuildRtIndex(options, source) {
|
|
160
|
+
const location = indexLocation(options)
|
|
161
|
+
const config = settings(options)
|
|
162
|
+
const info = sourceInfo(source)
|
|
163
|
+
fs.mkdirSync(location.root, { recursive: true, mode: 0o700 })
|
|
164
|
+
invariant(!fs.lstatSync(location.root).isSymbolicLink(), 'RT_UNSAFE_PATH')
|
|
165
|
+
const pointer = path.join(location.root, 'current.json')
|
|
166
|
+
const stamp = () => { try { return fileStamp(pointer) } catch (error) { if (error.code === 'ENOENT') return null; throw error } }
|
|
167
|
+
const before = stamp()
|
|
168
|
+
const stages = []
|
|
169
|
+
try {
|
|
170
|
+
const entries = Object.entries(source.index.entries)
|
|
171
|
+
invariant(entries.length === info.count, 'RT_COUNT_MISMATCH')
|
|
172
|
+
const segments = buildSegments(location.root, entries, [], config, 'base', stages)
|
|
173
|
+
return withFileLock(pointer, () => {
|
|
174
|
+
invariant(stamp() === before, 'RT_BUILD_STALE')
|
|
175
|
+
return { ...publish(location, info, segments, config.documentVersion, stages), changed: entries.length, removed: 0 }
|
|
176
|
+
})
|
|
177
|
+
} finally { for (const stage of stages) removeStaging(location.root, stage) }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The caller supplies a complete, already-committed delta, serialized per library. */
|
|
181
|
+
export function updateRtIndex(options, { source, previousRevision, previousFingerprint, changedIds, removedIds }) {
|
|
182
|
+
const location = indexLocation(options)
|
|
183
|
+
const config = settings(options)
|
|
184
|
+
const info = sourceInfo(source)
|
|
185
|
+
invariant(typeof previousRevision === 'string' && Array.isArray(changedIds) && Array.isArray(removedIds), 'RT_DELTA_INVALID')
|
|
186
|
+
invariant(changedIds.every(id => typeof id === 'string') && removedIds.every(id => typeof id === 'string'), 'RT_DELTA_INVALID')
|
|
187
|
+
const changed = new Set(changedIds)
|
|
188
|
+
const removed = new Set(removedIds)
|
|
189
|
+
for (const id of changed) invariant(!removed.has(id) && Object.hasOwn(source.index.entries, id), 'RT_DELTA_INVALID')
|
|
190
|
+
for (const id of removed) invariant(!Object.hasOwn(source.index.entries, id), 'RT_DELTA_INVALID')
|
|
191
|
+
if (!fs.existsSync(location.root)) throw rtError('RT_MISSING')
|
|
192
|
+
const pointer = path.join(location.root, 'current.json')
|
|
193
|
+
const { manifest, checksum } = readPublished(location, config.documentVersion)
|
|
194
|
+
invariant(manifest.source.revision === previousRevision, 'RT_REVISION_MISMATCH')
|
|
195
|
+
if (previousFingerprint !== undefined) invariant(manifest.source.fingerprint === previousFingerprint, 'RT_FINGERPRINT_MISMATCH')
|
|
196
|
+
invariant(manifest.segments.filter(segment => segment.kind === 'delta').length < MAX_DELTA_SEGMENTS, 'RT_COMPACTION_REQUIRED')
|
|
197
|
+
invariant(info.revision !== previousRevision || info.fingerprint !== manifest.source.fingerprint, 'RT_DELTA_INVALID')
|
|
198
|
+
invariant(info.count >= manifest.source.count - removed.size && info.count <= manifest.source.count + changed.size - removed.size, 'RT_DELTA_INVALID')
|
|
199
|
+
const stages = []
|
|
200
|
+
try {
|
|
201
|
+
const additions = buildSegments(location.root, [...changed].map(id => [id, source.index.entries[id]]), [...removed], config, 'delta', stages)
|
|
202
|
+
invariant(manifest.segments.length + additions.length <= MAX_SEGMENTS, 'RT_COMPACTION_REQUIRED')
|
|
203
|
+
invariant(manifest.segments.filter(segment => segment.kind === 'delta').length + additions.length <= MAX_DELTA_SEGMENTS, 'RT_COMPACTION_REQUIRED')
|
|
204
|
+
return withFileLock(pointer, () => {
|
|
205
|
+
invariant(readPublished(location, config.documentVersion).checksum === checksum, 'RT_BUILD_STALE')
|
|
206
|
+
return { ...publish(location, info, [...manifest.segments, ...additions], config.documentVersion, stages), changed: changed.size, removed: removed.size }
|
|
207
|
+
})
|
|
208
|
+
} finally { for (const stage of stages) removeStaging(location.root, stage) }
|
|
209
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
|
|
5
|
+
export const FORMAT_VERSION = 2
|
|
6
|
+
export const HEADER_BYTES = 16
|
|
7
|
+
export const HEAD_BYTES = 64
|
|
8
|
+
export const POSTING_BYTES = 8
|
|
9
|
+
export const MAX_FILE_BYTES = 256 * 1024 * 1024
|
|
10
|
+
export const TERM_BLOCK_ROWS = 128
|
|
11
|
+
|
|
12
|
+
export function rtError(code) {
|
|
13
|
+
const error = new Error(code)
|
|
14
|
+
error.code = code
|
|
15
|
+
return error
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function invariant(value, code = 'RT_CORRUPT') {
|
|
19
|
+
if (!value) throw rtError(code)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function sha256(value) {
|
|
23
|
+
return crypto.createHash('sha256').update(value).digest('hex')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function fileDigest(file) {
|
|
27
|
+
const hash = crypto.createHash('sha256')
|
|
28
|
+
const buffer = Buffer.allocUnsafe(64 * 1024)
|
|
29
|
+
const fd = fs.openSync(file, 'r')
|
|
30
|
+
let size = 0
|
|
31
|
+
try {
|
|
32
|
+
for (;;) {
|
|
33
|
+
const length = fs.readSync(fd, buffer, 0, buffer.length, null)
|
|
34
|
+
if (!length) break
|
|
35
|
+
hash.update(buffer.subarray(0, length))
|
|
36
|
+
size += length
|
|
37
|
+
}
|
|
38
|
+
} finally { fs.closeSync(fd) }
|
|
39
|
+
return { size, sha256: hash.digest('hex') }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function fileStamp(file) {
|
|
43
|
+
const stat = fs.lstatSync(file, { bigint: true })
|
|
44
|
+
invariant(stat.isFile() && !stat.isSymbolicLink())
|
|
45
|
+
return `${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.ino}`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function header(magic, count, stride) {
|
|
49
|
+
invariant(Number.isSafeInteger(count) && count >= 0 && count <= 0xffffffff, 'RT_BUILD_LIMIT')
|
|
50
|
+
invariant(HEADER_BYTES + count * stride <= MAX_FILE_BYTES, 'RT_BUILD_LIMIT')
|
|
51
|
+
const buffer = Buffer.alloc(HEADER_BYTES + count * stride)
|
|
52
|
+
buffer.write(magic, 0, 'ascii')
|
|
53
|
+
buffer.writeUInt32LE(FORMAT_VERSION, 4)
|
|
54
|
+
buffer.writeUInt32LE(count, 8)
|
|
55
|
+
buffer.writeUInt32LE(stride, 12)
|
|
56
|
+
return buffer
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function validateBinary(buffer, magic, stride, count = null) {
|
|
60
|
+
return validateBinaryHeader(buffer, buffer.length, magic, stride, count)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function validateBinaryHeader(buffer, byteLength, magic, stride, count = null) {
|
|
64
|
+
invariant(buffer.length >= HEADER_BYTES && buffer.toString('ascii', 0, 4) === magic)
|
|
65
|
+
invariant(buffer.readUInt32LE(4) === FORMAT_VERSION, 'RT_VERSION_MISMATCH')
|
|
66
|
+
const size = buffer.readUInt32LE(8)
|
|
67
|
+
invariant(buffer.readUInt32LE(12) === stride && byteLength === HEADER_BYTES + size * stride)
|
|
68
|
+
invariant(count === null || count === size)
|
|
69
|
+
return size
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Stream a bounded builder batch, retaining only sparse dictionary anchors. */
|
|
73
|
+
export function writePostings(directory, inverted) {
|
|
74
|
+
const postingsFile = path.join(directory, 'postings.bin')
|
|
75
|
+
const dictionaryFile = path.join(directory, 'terms.bin')
|
|
76
|
+
let count = 0
|
|
77
|
+
for (const rows of inverted.values()) count += rows.length / 2
|
|
78
|
+
const binaryHeader = header('DMRP', 0, POSTING_BYTES)
|
|
79
|
+
invariant(HEADER_BYTES + count * POSTING_BYTES <= MAX_FILE_BYTES, 'RT_BUILD_LIMIT')
|
|
80
|
+
binaryHeader.writeUInt32LE(count, 8)
|
|
81
|
+
const anchors = []
|
|
82
|
+
let cursor = 0
|
|
83
|
+
let bytes = 0
|
|
84
|
+
let index = 0
|
|
85
|
+
const buffer = Buffer.alloc(64 * 1024)
|
|
86
|
+
let used = 0
|
|
87
|
+
const termBuffer = Buffer.allocUnsafe(64 * 1024)
|
|
88
|
+
let termUsed = 0
|
|
89
|
+
const postingFd = fs.openSync(postingsFile, 'wx', 0o600)
|
|
90
|
+
let termFd = null
|
|
91
|
+
try {
|
|
92
|
+
termFd = fs.openSync(dictionaryFile, 'wx', 0o600)
|
|
93
|
+
fs.writeFileSync(postingFd, binaryHeader)
|
|
94
|
+
for (const term of [...inverted.keys()].sort()) {
|
|
95
|
+
const rows = inverted.get(term)
|
|
96
|
+
if (index++ % TERM_BLOCK_ROWS === 0) anchors.push([term, bytes, cursor])
|
|
97
|
+
const row = Buffer.from(JSON.stringify([term, cursor, rows.length / 2]) + '\n')
|
|
98
|
+
invariant(bytes + row.length <= MAX_FILE_BYTES && row.length <= 1024 * 1024, 'RT_BUILD_LIMIT')
|
|
99
|
+
if (termUsed + row.length > termBuffer.length) {
|
|
100
|
+
if (termUsed) fs.writeFileSync(termFd, termBuffer.subarray(0, termUsed))
|
|
101
|
+
termUsed = 0
|
|
102
|
+
}
|
|
103
|
+
if (row.length > termBuffer.length) fs.writeFileSync(termFd, row)
|
|
104
|
+
else { row.copy(termBuffer, termUsed); termUsed += row.length }
|
|
105
|
+
bytes += row.length
|
|
106
|
+
for (let i = 0; i < rows.length; i += 2) {
|
|
107
|
+
invariant(Number.isInteger(rows[i + 1]) && rows[i + 1] > 0 && rows[i + 1] <= 65535, 'RT_TF_OVERFLOW')
|
|
108
|
+
if (used === buffer.length) { fs.writeFileSync(postingFd, buffer); used = 0 }
|
|
109
|
+
buffer.writeUInt32LE(rows[i], used)
|
|
110
|
+
buffer.writeUInt16LE(rows[i + 1], used + 4)
|
|
111
|
+
used += POSTING_BYTES
|
|
112
|
+
cursor++
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (used) fs.writeFileSync(postingFd, buffer.subarray(0, used))
|
|
116
|
+
if (termUsed) fs.writeFileSync(termFd, termBuffer.subarray(0, termUsed))
|
|
117
|
+
fs.fsyncSync(postingFd)
|
|
118
|
+
fs.fsyncSync(termFd)
|
|
119
|
+
return { count: inverted.size, bytes, postings: count, anchors }
|
|
120
|
+
} finally {
|
|
121
|
+
try { if (termFd !== null) fs.closeSync(termFd) } finally { fs.closeSync(postingFd) }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const time = value => Number.isFinite(Date.parse(value)) ? Date.parse(value) : 0
|
|
126
|
+
|
|
127
|
+
export function headFromEntry(id, entry, bodyRef = {}, tokenCount = 0) {
|
|
128
|
+
return {
|
|
129
|
+
id, tokenCount, bodyShard: bodyRef.shard ?? 0, bodyOffset: bodyRef.offset ?? 0,
|
|
130
|
+
bodyLength: bodyRef.length ?? 0, attachmentMissing: entry.attachmentMissing === true,
|
|
131
|
+
layer: String(entry.layer || ''), status: String(entry.status || ''),
|
|
132
|
+
visibility: String(entry.visibility || ''), domain: String(entry.domain || ''),
|
|
133
|
+
createdAt: time(entry.createdAt), updatedAt: time(entry.updatedAt),
|
|
134
|
+
strengthBase: Number.isFinite(entry.strengthBase) ? entry.strengthBase : 0,
|
|
135
|
+
strengthAt: time(entry.strengthAt),
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function encodeHeads(records) {
|
|
140
|
+
const metadata = { ids: [], domains: [], layers: [], statuses: [], visibilities: [] }
|
|
141
|
+
const dictionaries = Object.fromEntries(['domains', 'layers', 'statuses', 'visibilities'].map(key => [key, new Map()]))
|
|
142
|
+
const intern = (key, value) => {
|
|
143
|
+
const dict = dictionaries[key]
|
|
144
|
+
if (!dict.has(value)) { dict.set(value, dict.size); metadata[key].push(value) }
|
|
145
|
+
invariant(dict.size <= 65535, 'RT_BUILD_LIMIT')
|
|
146
|
+
return dict.get(value)
|
|
147
|
+
}
|
|
148
|
+
const buffer = header('DMRH', records.length, HEAD_BYTES)
|
|
149
|
+
records.forEach((record, slot) => {
|
|
150
|
+
const offset = HEADER_BYTES + slot * HEAD_BYTES
|
|
151
|
+
metadata.ids.push(record.id)
|
|
152
|
+
for (const [position, value] of [[0, record.tokenCount], [4, record.bodyShard], [8, record.bodyOffset], [12, record.bodyLength]]) {
|
|
153
|
+
invariant(Number.isInteger(value) && value >= 0 && value <= 0xffffffff, 'RT_BUILD_LIMIT')
|
|
154
|
+
buffer.writeUInt32LE(value, offset + position)
|
|
155
|
+
}
|
|
156
|
+
buffer.writeUInt32LE(record.attachmentMissing ? 1 : 0, offset + 16)
|
|
157
|
+
buffer.writeUInt16LE(intern('layers', record.layer), offset + 20)
|
|
158
|
+
buffer.writeUInt16LE(intern('statuses', record.status), offset + 22)
|
|
159
|
+
buffer.writeUInt16LE(intern('visibilities', record.visibility), offset + 24)
|
|
160
|
+
buffer.writeUInt32LE(intern('domains', record.domain), offset + 28)
|
|
161
|
+
for (const [position, value] of [[32, record.createdAt], [40, record.updatedAt], [48, record.strengthBase], [56, record.strengthAt]]) {
|
|
162
|
+
buffer.writeDoubleLE(value, offset + position)
|
|
163
|
+
}
|
|
164
|
+
})
|
|
165
|
+
return { buffer, metadata }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function decodeHead(buffer, metadata, slot) {
|
|
169
|
+
invariant(Number.isInteger(slot) && slot >= 0 && slot < metadata.ids.length)
|
|
170
|
+
const offset = HEADER_BYTES + slot * HEAD_BYTES
|
|
171
|
+
const head = {
|
|
172
|
+
id: metadata.ids[slot], tokenCount: buffer.readUInt32LE(offset),
|
|
173
|
+
bodyShard: buffer.readUInt32LE(offset + 4), bodyOffset: buffer.readUInt32LE(offset + 8),
|
|
174
|
+
bodyLength: buffer.readUInt32LE(offset + 12), attachmentMissing: Boolean(buffer.readUInt32LE(offset + 16) & 1),
|
|
175
|
+
layer: metadata.layers[buffer.readUInt16LE(offset + 20)],
|
|
176
|
+
status: metadata.statuses[buffer.readUInt16LE(offset + 22)],
|
|
177
|
+
visibility: metadata.visibilities[buffer.readUInt16LE(offset + 24)],
|
|
178
|
+
domain: metadata.domains[buffer.readUInt32LE(offset + 28)],
|
|
179
|
+
createdAt: buffer.readDoubleLE(offset + 32), updatedAt: buffer.readDoubleLE(offset + 40),
|
|
180
|
+
strengthBase: buffer.readDoubleLE(offset + 48), strengthAt: buffer.readDoubleLE(offset + 56),
|
|
181
|
+
}
|
|
182
|
+
invariant([head.layer, head.status, head.visibility, head.domain].every(value => typeof value === 'string'))
|
|
183
|
+
invariant([head.createdAt, head.updatedAt, head.strengthBase, head.strengthAt].every(Number.isFinite))
|
|
184
|
+
return head
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function encodePostings(inverted) {
|
|
188
|
+
let count = 0
|
|
189
|
+
for (const rows of inverted.values()) count += rows.length / 2
|
|
190
|
+
const buffer = header('DMRP', count, POSTING_BYTES)
|
|
191
|
+
const terms = []
|
|
192
|
+
let cursor = 0
|
|
193
|
+
for (const term of [...inverted.keys()].sort()) {
|
|
194
|
+
const rows = inverted.get(term)
|
|
195
|
+
terms.push([term, cursor, rows.length / 2])
|
|
196
|
+
for (let i = 0; i < rows.length; i += 2) {
|
|
197
|
+
invariant(Number.isInteger(rows[i + 1]) && rows[i + 1] > 0 && rows[i + 1] <= 65535, 'RT_TF_OVERFLOW')
|
|
198
|
+
const offset = HEADER_BYTES + cursor++ * POSTING_BYTES
|
|
199
|
+
buffer.writeUInt32LE(rows[i], offset)
|
|
200
|
+
buffer.writeUInt16LE(rows[i + 1], offset + 4)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return { buffer, terms }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function readRange(file, offset, length) {
|
|
207
|
+
invariant(Number.isSafeInteger(offset) && offset >= 0 && Number.isSafeInteger(length) && length >= 0 && length <= MAX_FILE_BYTES)
|
|
208
|
+
const buffer = Buffer.allocUnsafe(length)
|
|
209
|
+
const fd = fs.openSync(file, 'r')
|
|
210
|
+
let read = 0
|
|
211
|
+
try {
|
|
212
|
+
while (read < length) {
|
|
213
|
+
const got = fs.readSync(fd, buffer, read, length - read, offset + read)
|
|
214
|
+
invariant(got > 0)
|
|
215
|
+
read += got
|
|
216
|
+
}
|
|
217
|
+
} finally { fs.closeSync(fd) }
|
|
218
|
+
return buffer
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function writeDurable(file, value) {
|
|
222
|
+
const fd = fs.openSync(file, 'wx', 0o600)
|
|
223
|
+
try { fs.writeFileSync(fd, value); fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function syncDirectory(directory) {
|
|
227
|
+
// Windows cannot open directories for fsync; file fsync + atomic rename remain.
|
|
228
|
+
if (process.platform === 'win32') return
|
|
229
|
+
const fd = fs.openSync(directory, 'r')
|
|
230
|
+
try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
|
231
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { FORMAT_VERSION, MAX_FILE_BYTES, invariant, sha256, rtError, fileStamp, readRange } from './format.js'
|
|
4
|
+
|
|
5
|
+
export const MAX_SEGMENTS = 128
|
|
6
|
+
export const MAX_DELTA_SEGMENTS = 7
|
|
7
|
+
const counts = new WeakMap()
|
|
8
|
+
// Hash the actual shared ruler once per process, including delegated tokenizer code.
|
|
9
|
+
export const RULER_FINGERPRINT = sha256(['text-retrieval.js', 'tokenizer-v2.js', 'curator-policy.js']
|
|
10
|
+
.map(name => fs.readFileSync(new URL(`../${name}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n')).join('\n'))
|
|
11
|
+
|
|
12
|
+
export function memoryDocumentText(entry) {
|
|
13
|
+
const tags = Array.isArray(entry?.tags) ? entry.tags.join(' ') : ''
|
|
14
|
+
const captions = (entry?.attachments || []).map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`).join(' ')
|
|
15
|
+
return [entry?.content || '', tags, captions].filter(Boolean).join(' ')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function sourceInfo(source) {
|
|
19
|
+
invariant(source?.index?.entries && typeof source.index.entries === 'object' && !Array.isArray(source.index.entries), 'RT_SOURCE_INVALID')
|
|
20
|
+
invariant(typeof source.revision === 'string' && source.revision.length > 0, 'RT_SOURCE_INVALID')
|
|
21
|
+
const fingerprint = source.fingerprint ?? source.revision
|
|
22
|
+
invariant(typeof fingerprint === 'string' && fingerprint.length > 0, 'RT_SOURCE_INVALID')
|
|
23
|
+
// Only frozen P1 views may reuse counts by identity. Mutable caller snapshots
|
|
24
|
+
// must supply count or pay for recounting; neither path hashes hot-query text.
|
|
25
|
+
let count = source.count
|
|
26
|
+
if (count === undefined) {
|
|
27
|
+
count = Object.isFrozen(source.index.entries) ? counts.get(source.index.entries) : undefined
|
|
28
|
+
if (count === undefined) {
|
|
29
|
+
count = Object.keys(source.index.entries).length
|
|
30
|
+
if (Object.isFrozen(source.index.entries)) counts.set(source.index.entries, count)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
invariant(Number.isSafeInteger(count) && count >= 0, 'RT_SOURCE_INVALID')
|
|
34
|
+
return { revision: source.revision, fingerprint, count }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function indexLocation({ directory, libraryId, namespace = 'memory' }) {
|
|
38
|
+
invariant(typeof directory === 'string' && directory.length > 0, 'RT_OPTIONS_INVALID')
|
|
39
|
+
invariant((typeof libraryId === 'string' && libraryId.length > 0) || libraryId === null, 'RT_OPTIONS_INVALID')
|
|
40
|
+
invariant(typeof namespace === 'string' && namespace.length > 0, 'RT_OPTIONS_INVALID')
|
|
41
|
+
const identity = sha256(JSON.stringify([namespace, libraryId]))
|
|
42
|
+
return { identity, namespace, libraryId, root: path.join(path.resolve(directory), identity) }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function readJsonLimited(file, maxBytes = 32 * 1024 * 1024, expectedHash = null) {
|
|
46
|
+
const stamp = fileStamp(file)
|
|
47
|
+
const size = Number(stamp.split(':', 1)[0])
|
|
48
|
+
invariant(size <= maxBytes)
|
|
49
|
+
const bytes = readRange(file, 0, size)
|
|
50
|
+
invariant(fileStamp(file) === stamp, 'RT_CHANGED_DURING_READ')
|
|
51
|
+
if (expectedHash !== null) invariant(sha256(bytes) === expectedHash)
|
|
52
|
+
try { return JSON.parse(bytes.toString('utf8')) } catch (error) {
|
|
53
|
+
if (error instanceof SyntaxError) throw rtError('RT_CORRUPT')
|
|
54
|
+
throw error
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const validSegmentId = value => /^s-[0-9a-f-]{36}$/.test(value)
|
|
59
|
+
export const validGeneration = value => /^g-[0-9a-f-]{36}$/.test(value)
|
|
60
|
+
export const validArtifact = value => ['heads.bin', 'metadata.json', 'postings.bin', 'terms.json', 'terms.bin', 'removed.json'].includes(value)
|
|
61
|
+
|| /^bodies\/\d{8}\.bin$/.test(value)
|
|
62
|
+
|
|
63
|
+
export function readPublished(location, documentVersion, expectedSource = null) {
|
|
64
|
+
invariant(!fs.lstatSync(location.root).isSymbolicLink())
|
|
65
|
+
const pointer = readJsonLimited(path.join(location.root, 'current.json'), 4096)
|
|
66
|
+
invariant(pointer && typeof pointer === 'object' && !Array.isArray(pointer))
|
|
67
|
+
invariant(pointer.version === FORMAT_VERSION, 'RT_VERSION_MISMATCH')
|
|
68
|
+
invariant(validGeneration(pointer.generation) && /^[a-f0-9]{64}$/.test(pointer.sha256))
|
|
69
|
+
const file = path.join(location.root, pointer.generation, 'manifest.json')
|
|
70
|
+
invariant(!fs.lstatSync(path.dirname(file)).isSymbolicLink())
|
|
71
|
+
const manifest = readJsonLimited(file, 1024 * 1024, pointer.sha256)
|
|
72
|
+
invariant(manifest && typeof manifest === 'object' && !Array.isArray(manifest))
|
|
73
|
+
invariant(manifest.version === FORMAT_VERSION, 'RT_VERSION_MISMATCH')
|
|
74
|
+
invariant(manifest.identity === location.identity, 'RT_IDENTITY_MISMATCH')
|
|
75
|
+
invariant(manifest.namespace === location.namespace && manifest.libraryId === location.libraryId, 'RT_IDENTITY_MISMATCH')
|
|
76
|
+
invariant(manifest.generation === pointer.generation && manifest.state === 'ready')
|
|
77
|
+
invariant(manifest.ruler === RULER_FINGERPRINT && manifest.documentVersion === documentVersion, 'RT_RULER_MISMATCH')
|
|
78
|
+
invariant(typeof manifest.source?.revision === 'string' && typeof manifest.source?.fingerprint === 'string')
|
|
79
|
+
invariant(Number.isSafeInteger(manifest.source.count) && manifest.source.count >= 0)
|
|
80
|
+
if (expectedSource) {
|
|
81
|
+
invariant(manifest.source.revision === expectedSource.revision, 'RT_REVISION_MISMATCH')
|
|
82
|
+
invariant(manifest.source.fingerprint === expectedSource.fingerprint, 'RT_FINGERPRINT_MISMATCH')
|
|
83
|
+
invariant(manifest.source.count === expectedSource.count, 'RT_COUNT_MISMATCH')
|
|
84
|
+
}
|
|
85
|
+
invariant(Array.isArray(manifest.segments) && manifest.segments.length > 0 && manifest.segments.length <= MAX_SEGMENTS)
|
|
86
|
+
const seen = new Set()
|
|
87
|
+
for (const segment of manifest.segments) {
|
|
88
|
+
invariant(validSegmentId(segment.id) && !seen.has(segment.id))
|
|
89
|
+
seen.add(segment.id)
|
|
90
|
+
invariant(Number.isSafeInteger(segment.count) && segment.count >= 0 && segment.files && typeof segment.files === 'object')
|
|
91
|
+
const names = Object.keys(segment.files)
|
|
92
|
+
invariant(names.length >= 5 && names.length <= 65536)
|
|
93
|
+
invariant(segment.kind === 'base' || segment.kind === 'delta')
|
|
94
|
+
invariant(['heads.bin', 'metadata.json', 'postings.bin', 'terms.json', 'terms.bin', 'removed.json'].every(name => names.includes(name)))
|
|
95
|
+
for (const [name, descriptor] of Object.entries(segment.files)) {
|
|
96
|
+
invariant(validArtifact(name) && Number.isSafeInteger(descriptor?.size) && descriptor.size >= 0 && descriptor.size <= MAX_FILE_BYTES)
|
|
97
|
+
invariant(/^[a-f0-9]{64}$/.test(descriptor.sha256))
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { manifest, checksum: pointer.sha256 }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function failureCode(error) {
|
|
104
|
+
return /^RT_[A-Z_]+$/.test(error?.code || '') ? error.code : error?.code === 'ENOENT' ? 'RT_MISSING' : 'RT_IO_ERROR'
|
|
105
|
+
}
|