dsh-knit 0.20.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +247 -0
- package/README.en.md +109 -0
- package/README.md +93 -3
- package/SECURITY.md +3 -2
- package/package.json +2 -2
- package/src/client/client.js +530 -50
- package/src/host/context.js +42 -6
- package/src/host/control.js +421 -0
- package/src/host/index-store.js +479 -0
- package/src/host/index.js +1015 -69
- package/src/host/links.js +97 -34
- package/src/host/relations.js +316 -0
- package/src/host/tool.js +96 -6
- package/test/client.test.mjs +540 -12
- package/test/code-context.test.mjs +3 -1
- package/test/context-eval.test.mjs +5 -1
- package/test/context.test.mjs +32 -2
- package/test/control.test.mjs +324 -0
- package/test/deep-corpus.mjs +110 -0
- package/test/deep-scale.test.mjs +1 -1
- package/test/fixture.mjs +50 -0
- package/test/harness.mjs +6 -2
- package/test/host-http.test.mjs +107 -0
- package/test/i18n.test.mjs +12 -6
- package/test/index-incremental.test.mjs +504 -0
- package/test/index-store.test.mjs +340 -0
- package/test/links.test.mjs +50 -0
- package/test/relations.test.mjs +360 -0
- package/test/tier1.test.mjs +2 -2
- package/test/tool.test.mjs +79 -1
package/src/host/context.js
CHANGED
|
@@ -83,6 +83,9 @@
|
|
|
83
83
|
// 在这里写 `doc.kind === 'code'` 会让 `code` 被误认成一个理由码。
|
|
84
84
|
// `classification.js` 零依赖,import 它不会成环。
|
|
85
85
|
import { KIND_CODE } from './classification.js'
|
|
86
|
+
// v0.21:关系**只做投影**(见 D2)。它读的是一份已经算好的「谁提到谁」事实表,
|
|
87
|
+
// 不参与任何分层判断 —— 所以这里 import 它不会让排序多一条路径。
|
|
88
|
+
import { MAX_RELATIONS_PER_ITEM, relationsOf } from './relations.js'
|
|
86
89
|
|
|
87
90
|
/* ── 上限(对外契约的一部分,测试直接断言它们)───────────────── */
|
|
88
91
|
|
|
@@ -307,6 +310,19 @@ const REASON_ORDER = {
|
|
|
307
310
|
related: 6,
|
|
308
311
|
}
|
|
309
312
|
|
|
313
|
+
/**
|
|
314
|
+
* 靠**引用关系**进包的那几个理由码。
|
|
315
|
+
*
|
|
316
|
+
* v0.21 用它把「这条是从哪来的」落成 §6.5 的三值之一:
|
|
317
|
+
* 命中关键词是 `retrieval`,靠关系进来的是 `relation`,用户自己钉的是 `manual`
|
|
318
|
+
* (`manual` 由调用方在装配**之后**改,本模块不认识「固定」这件事 —— 那是控制层的活)。
|
|
319
|
+
*
|
|
320
|
+
* ⚠️ 名字是 `provenance`,**不是** `source`:条目上的 `source` 早在 v0.14 就有,
|
|
321
|
+
* 指的是**文件角色**(`impl` / `test` / `config` / `design` / `doc`,见 `sourceTypeOf()`),
|
|
322
|
+
* 与「来源」是两件事。改那个字段的语义会静默打断客户端与工具 schema,所以另起一个名字。
|
|
323
|
+
*/
|
|
324
|
+
const RELATION_REASON = new Set(['linkTarget', 'linkSource', 'related'])
|
|
325
|
+
|
|
310
326
|
/* ── 主函数 ─────────────────────────────────────────── */
|
|
311
327
|
|
|
312
328
|
/**
|
|
@@ -319,6 +335,9 @@ const REASON_ORDER = {
|
|
|
319
335
|
* @param {Array<object>} input.ranked - 相关度降序的文档(`rankByRelevance().docs`)
|
|
320
336
|
* @param {string} [input.topic] - 当前话题标签(`topicLabel()` 的产物)
|
|
321
337
|
* @param {object} [input.graph] - `buildLinkGraph()` 的产物;不给就退化成「只看命中」
|
|
338
|
+
* @param {Map<string, Array<object>>} [input.relations] - v0.21:`buildRelationFacts()`
|
|
339
|
+
* 的 `incident`(谁提到谁)。**只用来给已经进包的条目补一段可核验的关系**,
|
|
340
|
+
* 不参与任何分层判断;不给就是「这个包不投影关系」。
|
|
322
341
|
* @param {number} [input.maxPrimary] - 覆盖 Primary 上限(默认 `MAX_PRIMARY` = 1)
|
|
323
342
|
* @param {number} [input.maxSupporting] - 覆盖 Supporting 上限(默认 `MAX_SUPPORTING` = 3)
|
|
324
343
|
* @param {number} [input.maxRelated] - 覆盖 Related 上限(默认 `MAX_RELATED` = 5)
|
|
@@ -330,6 +349,7 @@ const REASON_ORDER = {
|
|
|
330
349
|
export function buildContext(input = {}) {
|
|
331
350
|
const ranked = Array.isArray(input.ranked) ? input.ranked.filter(Boolean) : []
|
|
332
351
|
const graph = input.graph
|
|
352
|
+
const incident = input.relations instanceof Map ? input.relations : null
|
|
333
353
|
const topic = typeof input.topic === 'string' ? input.topic : ''
|
|
334
354
|
// `task` 原样透传 —— 它可能很长、可能为空,这里一个字都不加工(加工就是编造)。
|
|
335
355
|
const task = typeof input.task === 'string' ? input.task : ''
|
|
@@ -546,23 +566,39 @@ export function buildContext(input = {}) {
|
|
|
546
566
|
}
|
|
547
567
|
|
|
548
568
|
/**
|
|
549
|
-
* 把内部记录投影成对外的条目:**只有 rel / title / summary / mtimeMs / kind / source /
|
|
569
|
+
* 把内部记录投影成对外的条目:**只有 rel / title / summary / mtimeMs / kind / source /
|
|
570
|
+
* reason / provenance**(外加有关系时的 `relations` + `relationsTotal`)。
|
|
550
571
|
* `raw` / `strength` / `terms` / `fields` 一个都不出去 —— 名次本身就是答案。
|
|
572
|
+
*
|
|
573
|
+
* v0.21:`relations` 与 `relationsTotal` **只在真有关系时才出现**。空数组是纯噪音
|
|
574
|
+
* (没有关系时界面什么也不画),而条目的形状本来是稳定的 —— 少一个恒为空的可选键,
|
|
575
|
+
* 比多 9 个 `"relations":[]` 更省。`relationsTotal` 更只在**被截断**时出现:
|
|
576
|
+
* 界面要说的那句话是「共 N 条关系」,没截断时 `N` 就是列表长度,不必下发。
|
|
551
577
|
*/
|
|
552
578
|
const project = (entry) => {
|
|
553
579
|
const record = entry.record
|
|
554
|
-
|
|
580
|
+
const reason = explainContext(
|
|
581
|
+
{ rel: record.rel, kind: record.kind, matchedTerms: record.termFields },
|
|
582
|
+
entry,
|
|
583
|
+
)
|
|
584
|
+
const item = {
|
|
555
585
|
rel: record.rel,
|
|
556
586
|
title: record.title,
|
|
557
587
|
summary: record.summary,
|
|
558
588
|
mtimeMs: record.mtimeMs,
|
|
559
589
|
kind: record.kind,
|
|
560
590
|
source: record.source,
|
|
561
|
-
reason
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
591
|
+
reason,
|
|
592
|
+
provenance: RELATION_REASON.has(reason.code) ? 'relation' : 'retrieval',
|
|
593
|
+
}
|
|
594
|
+
if (incident) {
|
|
595
|
+
const found = relationsOf(incident, record.rel, MAX_RELATIONS_PER_ITEM)
|
|
596
|
+
if (found.relations.length > 0) {
|
|
597
|
+
item.relations = found.relations
|
|
598
|
+
if (found.total > found.relations.length) item.relationsTotal = found.total
|
|
599
|
+
}
|
|
565
600
|
}
|
|
601
|
+
return item
|
|
566
602
|
}
|
|
567
603
|
|
|
568
604
|
/** 同一层内:名次优先;名次相同按理由强弱;再相同按 rel 字典序(确定性兜底)。 */
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v0.21 上下文控制层 —— 固定 / 排除。
|
|
3
|
+
*
|
|
4
|
+
* 这一层只回答一件事:「用户亲手标的那些文件,在检索与装配的哪一步生效」。
|
|
5
|
+
* 它**不是**第二个排序阶段(与 `relations.js` 同一条纪律):固定不改变任何一篇的名次,
|
|
6
|
+
* 只是把它从三层里**移出来**单独放;排除更早就生效 —— 那篇根本不进入候选集。
|
|
7
|
+
*
|
|
8
|
+
* 三条硬约束(实现说明 §6、D7/D8):
|
|
9
|
+
*
|
|
10
|
+
* 1. **排除在检索之前**:`excluded` 里的 rel 不进候选集 ⇒ 不出现在面板、
|
|
11
|
+
* 不出现在工具输出、不计入 `matched`、不参与任何计数。
|
|
12
|
+
* 2. **固定在排序之后**:固定的条目**从三层移出**,进入独立的「固定上下文」区。
|
|
13
|
+
* 三层的连续编号规则因此一个字不动(固定区不编号,与 v0.14「其他相关文档」同一先例)。
|
|
14
|
+
* 3. **持久化是可选能力**:拿不到存储就只活在本次进程内存里,调用方**必须把这件事说出来**
|
|
15
|
+
* (`persisted: false`),不许让用户以为它记住了。
|
|
16
|
+
*
|
|
17
|
+
* 零 I/O:本模块自己只做纯逻辑;唯一的外部交互是注入进来的那个 `backend.kv`(可选)。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** 存储单元名。必须匹配 `UNIT_NAME_RE = /^[a-z][a-z0-9_]*$/`(`dsh-storage` 的真实正则)。 */
|
|
21
|
+
export const CONTROL_UNIT = 'knit_control'
|
|
22
|
+
/** 单元格式版本。落在介质上;不一致时按空处理,本版不做数据迁移(§6.4)。 */
|
|
23
|
+
export const CONTROL_VERSION = 1
|
|
24
|
+
/** 两张表:固定、排除。无 global 槽(§6.4)。 */
|
|
25
|
+
export const CONTROL_TABLES = ['pinned', 'excluded']
|
|
26
|
+
/** 单个工作区里两类记录各自的硬上限 —— 防的是「状态无限长」,不是界面。 */
|
|
27
|
+
export const MAX_CONTROL_ROWS = 200
|
|
28
|
+
|
|
29
|
+
/** 四个动作(固定 / 取消固定 / 排除 / 恢复)。前两个作用于 pinned,后两个作用于 excluded。 */
|
|
30
|
+
export const CONTROL_ACTIONS = ['pin', 'unpin', 'exclude', 'restore']
|
|
31
|
+
|
|
32
|
+
/** 登记表在后端对象上的挂点(`Symbol.for` ⇒ 同一进程里的多次插件加载拿到同一个)。 */
|
|
33
|
+
const CONTROL_SHARED = Symbol.for('dsh-knit.control')
|
|
34
|
+
|
|
35
|
+
/** 空状态。**永远返回新对象**:调用方比较时用的是引用不等,不是内容不等。 */
|
|
36
|
+
export function emptyControl() {
|
|
37
|
+
return { pinned: [], excluded: [] }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const isRel = (value) => typeof value === 'string' && value.length > 0 && value.length <= 1024
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 把任意输入(来自存储介质 / HTTP)收敛成合法状态。
|
|
44
|
+
*
|
|
45
|
+
* 存储里的东西是不可信输入:畸形记录按**丢弃**处理,不抛错 —— 控制层坏掉
|
|
46
|
+
* 不该把面板路径带崩(与反馈层同一条纪律,§6.11 第 9 条)。
|
|
47
|
+
*
|
|
48
|
+
* @param {unknown} value - 任意形状
|
|
49
|
+
* @returns {{pinned: Array<{rel: string, at: number}>, excluded: Array<{rel: string, at: number}>}}
|
|
50
|
+
*/
|
|
51
|
+
export function normalizeControl(value) {
|
|
52
|
+
const out = emptyControl()
|
|
53
|
+
if (!value || typeof value !== 'object') return out
|
|
54
|
+
const seen = new Set()
|
|
55
|
+
for (const row of Array.isArray(value.pinned) ? value.pinned : []) {
|
|
56
|
+
if (!row || !isRel(row.rel) || seen.has(row.rel)) continue
|
|
57
|
+
seen.add(row.rel)
|
|
58
|
+
out.pinned.push({ rel: row.rel, at: Number.isFinite(row.at) ? row.at : 0 })
|
|
59
|
+
}
|
|
60
|
+
// 先固定的在前(`at` 升序);`at` 相同则按 rel 字典序 —— 确定性优先。
|
|
61
|
+
out.pinned.sort((a, b) => a.at - b.at || (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
|
|
62
|
+
out.pinned = out.pinned.slice(0, MAX_CONTROL_ROWS)
|
|
63
|
+
const excludedSeen = new Set()
|
|
64
|
+
for (const row of Array.isArray(value.excluded) ? value.excluded : []) {
|
|
65
|
+
if (!row || !isRel(row.rel) || excludedSeen.has(row.rel)) continue
|
|
66
|
+
excludedSeen.add(row.rel)
|
|
67
|
+
out.excluded.push({ rel: row.rel, at: Number.isFinite(row.at) ? row.at : 0 })
|
|
68
|
+
}
|
|
69
|
+
out.excluded = out.excluded.slice(0, MAX_CONTROL_ROWS)
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const without = (rows, rel) => rows.filter((row) => row.rel !== rel)
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 施加一个动作,返回**新状态**(不改原对象)。
|
|
77
|
+
*
|
|
78
|
+
* 固定与排除互斥(§6.2):固定一个已排除的 = 先恢复再固定,反过来同理。
|
|
79
|
+
* 幂等:重复固定同一篇不产生第二行,也不刷新 `at`(先固定的在前,顺序不该被重复点击打乱)。
|
|
80
|
+
*
|
|
81
|
+
* @param {object} control - 当前状态
|
|
82
|
+
* @param {string} action - `pin` / `unpin` / `exclude` / `restore`
|
|
83
|
+
* @param {string} rel - 工作区相对路径
|
|
84
|
+
* @param {number} [at] - 时间戳(只在新增记录时写入;不是分数)
|
|
85
|
+
* @returns {{control: object, changed: boolean}} 新状态与「是否真的变了」
|
|
86
|
+
*/
|
|
87
|
+
export function applyAction(control, action, rel, at = Date.now()) {
|
|
88
|
+
const current = normalizeControl(control)
|
|
89
|
+
if (!CONTROL_ACTIONS.includes(action) || !isRel(rel)) {
|
|
90
|
+
return { control: current, changed: false }
|
|
91
|
+
}
|
|
92
|
+
const has = (rows) => rows.some((row) => row.rel === rel)
|
|
93
|
+
if (action === 'pin') {
|
|
94
|
+
if (has(current.pinned)) return { control: current, changed: false }
|
|
95
|
+
return {
|
|
96
|
+
control: {
|
|
97
|
+
pinned: [...current.pinned, { rel, at }].slice(-MAX_CONTROL_ROWS),
|
|
98
|
+
excluded: without(current.excluded, rel),
|
|
99
|
+
},
|
|
100
|
+
changed: true,
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (action === 'unpin') {
|
|
104
|
+
if (!has(current.pinned)) return { control: current, changed: false }
|
|
105
|
+
return { control: { pinned: without(current.pinned, rel), excluded: current.excluded }, changed: true }
|
|
106
|
+
}
|
|
107
|
+
if (action === 'exclude') {
|
|
108
|
+
if (has(current.excluded)) return { control: current, changed: false }
|
|
109
|
+
return {
|
|
110
|
+
control: {
|
|
111
|
+
pinned: without(current.pinned, rel),
|
|
112
|
+
excluded: [...current.excluded, { rel, at }].slice(-MAX_CONTROL_ROWS),
|
|
113
|
+
},
|
|
114
|
+
changed: true,
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (!has(current.excluded)) return { control: current, changed: false }
|
|
118
|
+
return { control: { pinned: current.pinned, excluded: without(current.excluded, rel) }, changed: true }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** `excluded` 的集合视图(`scan()` 每批都要用,别每次线性找)。 */
|
|
122
|
+
export function excludedSet(control) {
|
|
123
|
+
return new Set(normalizeControl(control).excluded.map((row) => row.rel))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 按「先固定在前」给出 rel 列表。 */
|
|
127
|
+
export function pinnedRels(control) {
|
|
128
|
+
return normalizeControl(control).pinned.map((row) => row.rel)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 固定覆盖(D7):把固定的条目从三层**移出**,放进 `pack.pinned`。
|
|
133
|
+
*
|
|
134
|
+
* 条目**只能从这一包里现成的行取**(零新 I/O,与 `relations` 的投影同一条纪律)。
|
|
135
|
+
* 固定了一篇但这一批候选里没有它 —— **不硬凑**(`context.js:494` 那条先例):
|
|
136
|
+
* 用户切到「代码」档时,被固定的 Markdown 自然不在屏幕上,而不是凭空长出来。
|
|
137
|
+
*
|
|
138
|
+
* @param {object} pack - `buildContext()` 的产物
|
|
139
|
+
* @param {object} control - 控制状态
|
|
140
|
+
* @returns {object} 新包(含 `pinned`;没有固定项时原样返回)
|
|
141
|
+
*/
|
|
142
|
+
export function applyPinOverride(pack, control) {
|
|
143
|
+
const rels = pinnedRels(control)
|
|
144
|
+
if (!pack || rels.length === 0) return pack
|
|
145
|
+
const tiers = ['primary', 'supporting', 'related']
|
|
146
|
+
const byRel = new Map()
|
|
147
|
+
for (const tier of tiers) {
|
|
148
|
+
for (const item of Array.isArray(pack[tier]) ? pack[tier] : []) {
|
|
149
|
+
if (item && item.rel && !byRel.has(item.rel)) byRel.set(item.rel, { item, tier })
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const pinned = []
|
|
153
|
+
for (const rel of rels) {
|
|
154
|
+
const found = byRel.get(rel)
|
|
155
|
+
// 「用户固定」是**来源**,不是分数:原样复用行数据,只把来源改成 manual。
|
|
156
|
+
// ⚠️ 不再附加 `tier` 之类的新字段 —— `tool.js` 的 `ITEM_SCHEMA` 是
|
|
157
|
+
// `additionalProperties: false`,多一个键就会在工具校验层静默失败(v0.14 踩过)。
|
|
158
|
+
if (found) pinned.push({ ...found.item, provenance: 'manual' })
|
|
159
|
+
}
|
|
160
|
+
if (pinned.length === 0) return pack
|
|
161
|
+
const taken = new Set(pinned.map((item) => item.rel))
|
|
162
|
+
const next = { ...pack, pinned }
|
|
163
|
+
for (const tier of tiers) {
|
|
164
|
+
const rows = Array.isArray(pack[tier]) ? pack[tier] : []
|
|
165
|
+
next[tier] = rows.filter((item) => !taken.has(item.rel))
|
|
166
|
+
}
|
|
167
|
+
return next
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 可选持久化适配(D8)。
|
|
172
|
+
*
|
|
173
|
+
* 调用方把 `ctx.storage.backend.get('json')` 拿到的后端(或任何同形状的替身)递进来;
|
|
174
|
+
* 拿不到就传 `null` ⇒ `persisted: false`,功能照常,只是活不过这次进程。
|
|
175
|
+
*
|
|
176
|
+
* 三条与契约一一对应的处理:
|
|
177
|
+
* - `backend.get(name)` **会抛** `backend-not-found`(不是返回 undefined)⇒ 调用方必须先 try;
|
|
178
|
+
* 这里对 `backend.kv` 缺失也一律当「没有存储」。
|
|
179
|
+
* - 同名 unit 未关闭再次 `open` 会 reject ⇒ 只开一次并复用(`opening` 记忆化)。
|
|
180
|
+
* - unit **不保证并发写序** ⇒ 这里自己串一条写链。
|
|
181
|
+
*
|
|
182
|
+
* 记录形状:键 = `${root}\u0000${rel}`(unit 的 `single` 布局下键是不透明字符串),
|
|
183
|
+
* 值 = `{ root, rel, at }` —— 同一张表里因此能装多个工作区,读的时候按 root 过滤。
|
|
184
|
+
*
|
|
185
|
+
* @param {{backend?: object|null}} [options] - `backend.kv.open(descriptor)` 是唯一依赖
|
|
186
|
+
* @returns {{persisted: boolean, reason: string, read: Function, write: Function}}
|
|
187
|
+
*/
|
|
188
|
+
export function createControlStore(options = {}) {
|
|
189
|
+
// ⚠️ 显式传 `null` 时默认参数不生效(`index.js` 启动那一刻就是 `null`)——
|
|
190
|
+
// 所以这里再收一道,别让「没有存储」这条**正常路径**变成 TypeError。
|
|
191
|
+
const backend = options && options.backend
|
|
192
|
+
const kv = backend && typeof backend === 'object' ? backend.kv : null
|
|
193
|
+
if (!kv || typeof kv.open !== 'function') {
|
|
194
|
+
return {
|
|
195
|
+
persisted: false,
|
|
196
|
+
reason: 'no-storage',
|
|
197
|
+
read: async () => null,
|
|
198
|
+
write: async () => false,
|
|
199
|
+
flush: async () => false,
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
let opening = null
|
|
204
|
+
let writes = Promise.resolve()
|
|
205
|
+
const lastWritten = new Map() // root → { pinned: Set, excluded: Set }
|
|
206
|
+
|
|
207
|
+
const openUnit = () => {
|
|
208
|
+
if (!opening) {
|
|
209
|
+
opening = Promise.resolve()
|
|
210
|
+
.then(() => kv.open({
|
|
211
|
+
name: CONTROL_UNIT,
|
|
212
|
+
version: CONTROL_VERSION,
|
|
213
|
+
tables: CONTROL_TABLES,
|
|
214
|
+
hasGlobal: false,
|
|
215
|
+
// 整单元一个文档:键因此可以是不透明的 rel,不必满足 per-record 的
|
|
216
|
+
// `[a-zA-Z0-9_-]+`(rel 里有 `/` 和 `.`)。控制状态很小,整份重写无所谓。
|
|
217
|
+
layout: 'single',
|
|
218
|
+
}))
|
|
219
|
+
.then((unit) => unit)
|
|
220
|
+
.catch(() => null) // version-mismatch / malformed-medium / 后端不支持 ⇒ 当空
|
|
221
|
+
}
|
|
222
|
+
return opening
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const store = {
|
|
226
|
+
// **证据到之前不说自己记得**:`persisted` 只在读成功或写成功后才是 true。
|
|
227
|
+
// 真机验收实测过反例:老版本一拿到 `kv` 就报 true,而介质文件从没出现过。
|
|
228
|
+
persisted: false,
|
|
229
|
+
reason: 'unproven',
|
|
230
|
+
/**
|
|
231
|
+
* 读一个工作区的状态。任何失败 ⇒ `null`(调用方退回空状态),绝不抛。
|
|
232
|
+
* @param {string} root - 工作区根
|
|
233
|
+
* @returns {Promise<object|null>} 控制状态或 null
|
|
234
|
+
*/
|
|
235
|
+
read: async (root) => {
|
|
236
|
+
try {
|
|
237
|
+
const unit = await openUnit()
|
|
238
|
+
if (!unit) {
|
|
239
|
+
store.persisted = false
|
|
240
|
+
store.reason = 'open-failed'
|
|
241
|
+
return null
|
|
242
|
+
}
|
|
243
|
+
const all = await unit.loadAll()
|
|
244
|
+
const tables = (all && all.tables) || {}
|
|
245
|
+
const state = emptyControl()
|
|
246
|
+
const marks = new Map()
|
|
247
|
+
for (const table of CONTROL_TABLES) {
|
|
248
|
+
const rows = (tables[table] && typeof tables[table] === 'object') ? tables[table] : {}
|
|
249
|
+
const keys = new Set()
|
|
250
|
+
for (const [key, value] of Object.entries(rows)) {
|
|
251
|
+
if (!key.startsWith(`${root}\u0000`)) continue
|
|
252
|
+
keys.add(key)
|
|
253
|
+
if (!value || typeof value !== 'object') continue
|
|
254
|
+
state[table].push({ rel: value.rel, at: value.at })
|
|
255
|
+
}
|
|
256
|
+
marks.set(table, keys)
|
|
257
|
+
}
|
|
258
|
+
lastWritten.set(root, marks)
|
|
259
|
+
store.persisted = true
|
|
260
|
+
store.reason = 'ok'
|
|
261
|
+
return normalizeControl(state)
|
|
262
|
+
} catch {
|
|
263
|
+
store.persisted = false
|
|
264
|
+
store.reason = 'read-failed'
|
|
265
|
+
return null
|
|
266
|
+
}
|
|
267
|
+
},
|
|
268
|
+
/**
|
|
269
|
+
* 写一个工作区的状态。只写**差量**(新增 / 删除那几行),fire-and-forget:
|
|
270
|
+
* 失败就记一笔并保持内存态,不重试风暴(§6.4)。
|
|
271
|
+
* @param {string} root - 工作区根
|
|
272
|
+
* @param {object} control - 控制状态
|
|
273
|
+
* @returns {Promise<boolean>} 是否落盘成功
|
|
274
|
+
*/
|
|
275
|
+
write: async (root, control) => {
|
|
276
|
+
const next = normalizeControl(control)
|
|
277
|
+
writes = writes.then(async () => {
|
|
278
|
+
const unit = await openUnit()
|
|
279
|
+
if (!unit) {
|
|
280
|
+
store.persisted = false
|
|
281
|
+
store.reason = 'open-failed'
|
|
282
|
+
return false
|
|
283
|
+
}
|
|
284
|
+
const marks = lastWritten.get(root) || new Map()
|
|
285
|
+
for (const table of CONTROL_TABLES) {
|
|
286
|
+
const before = marks.get(table) || new Set()
|
|
287
|
+
const after = new Set(next[table].map((row) => `${root}\u0000${row.rel}`))
|
|
288
|
+
const byKey = new Map(next[table].map((row) => [`${root}\u0000${row.rel}`, row]))
|
|
289
|
+
for (const key of after) {
|
|
290
|
+
if (!before.has(key)) await unit.putRecord(table, key, byKey.get(key))
|
|
291
|
+
}
|
|
292
|
+
for (const key of before) {
|
|
293
|
+
if (!after.has(key)) await unit.deleteRecord(table, key)
|
|
294
|
+
}
|
|
295
|
+
marks.set(table, after)
|
|
296
|
+
}
|
|
297
|
+
lastWritten.set(root, marks)
|
|
298
|
+
store.persisted = true
|
|
299
|
+
store.reason = 'ok'
|
|
300
|
+
return true
|
|
301
|
+
}).catch(() => {
|
|
302
|
+
store.persisted = false
|
|
303
|
+
store.reason = 'write-failed'
|
|
304
|
+
return false
|
|
305
|
+
})
|
|
306
|
+
return writes
|
|
307
|
+
},
|
|
308
|
+
/**
|
|
309
|
+
* 等写链排空(测试与「退出前收尾」用)。生产中不 await —— 面板点一下就该立刻有反馈,
|
|
310
|
+
* 落盘是后台的事。
|
|
311
|
+
* @returns {Promise<boolean>} 最后一次写是否成功
|
|
312
|
+
*/
|
|
313
|
+
flush: async () => writes,
|
|
314
|
+
}
|
|
315
|
+
return store
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 进程内存里的控制状态登记表 —— 面板与工具共用的唯一真源。
|
|
320
|
+
*
|
|
321
|
+
* 有存储时:启动读一次,之后读写都走内存(§6.4「读:启动开一次 loadAll(),之后只走内存」);
|
|
322
|
+
* 没有存储时:`persisted` 恒 false,状态只活这次进程。
|
|
323
|
+
*
|
|
324
|
+
* @param {{backend?: object|null}} [options] - 见 `createControlStore`
|
|
325
|
+
* @returns {object} 登记表
|
|
326
|
+
*/
|
|
327
|
+
export function createControlRegistry(options = {}) {
|
|
328
|
+
const store = createControlStore(options)
|
|
329
|
+
const states = new Map() // root → 控制状态
|
|
330
|
+
const loaded = new Set()
|
|
331
|
+
const loading = new Map() // root → 首访那次装载的 promise
|
|
332
|
+
|
|
333
|
+
const get = (root) => {
|
|
334
|
+
const key = String(root || '')
|
|
335
|
+
if (!states.has(key)) states.set(key, emptyControl())
|
|
336
|
+
return states.get(key)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// 提成局部函数(不是对象方法):`ready()` 也要用它,而对象字面量里的方法是拿不到名字的
|
|
340
|
+
const controlOf = (root) => {
|
|
341
|
+
const key = String(root || '')
|
|
342
|
+
if (!loaded.has(key)) {
|
|
343
|
+
loaded.add(key)
|
|
344
|
+
loading.set(key, store.read(key).then((loadedState) => {
|
|
345
|
+
if (loadedState && loadedState.pinned.length + loadedState.excluded.length > 0) {
|
|
346
|
+
states.set(key, loadedState)
|
|
347
|
+
}
|
|
348
|
+
}).catch(() => {}))
|
|
349
|
+
}
|
|
350
|
+
return get(key)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return {
|
|
354
|
+
// **不是本地副本**:读与写的成败都记在 store 上,这里直接问它 ——
|
|
355
|
+
// 复制一份就会漏掉「读成功」这条证据。
|
|
356
|
+
get persisted() {
|
|
357
|
+
return store.persisted
|
|
358
|
+
},
|
|
359
|
+
get reason() {
|
|
360
|
+
return store.reason
|
|
361
|
+
},
|
|
362
|
+
/** 状态本身(同步,读内存)。首访时顺带异步装载一次。 */
|
|
363
|
+
controlOf,
|
|
364
|
+
/**
|
|
365
|
+
* 等这个工作区首访那次装载落定 —— 只为「`persisted` 是不是一句有证据的话」。
|
|
366
|
+
*
|
|
367
|
+
* `persisted` 的含义是**已证明**(读或写成功过),不是「后端在那儿」:真机验收抓到
|
|
368
|
+
* 的第一版就错在这里 —— 第一次点击报 `persisted: true`,而介质文件从没出现过。
|
|
369
|
+
* @param {string} root - 工作区根
|
|
370
|
+
* @returns {Promise<void>} 装载结束(成功或失败都 resolve)
|
|
371
|
+
*/
|
|
372
|
+
ready(root) {
|
|
373
|
+
controlOf(root)
|
|
374
|
+
return loading.get(String(root || '')) || Promise.resolve()
|
|
375
|
+
},
|
|
376
|
+
/**
|
|
377
|
+
* 改一个动作。返回 `{control, changed, persisted}`。
|
|
378
|
+
*
|
|
379
|
+
* **必须 await**:`persisted` 报的是**这次写的结果**,不是「大概能写」——
|
|
380
|
+
* 不等它就会在写失败时先回一句 `true`(真机验收实测到的缺陷)。
|
|
381
|
+
* @returns {Promise<{control: object, changed: boolean, persisted: boolean}>}
|
|
382
|
+
*/
|
|
383
|
+
async act(root, action, rel, at) {
|
|
384
|
+
const key = String(root || '')
|
|
385
|
+
const { control, changed } = applyAction(get(key), action, rel, at)
|
|
386
|
+
if (!changed) return { control, changed, persisted: store.persisted }
|
|
387
|
+
states.set(key, control)
|
|
388
|
+
await store.write(key, control)
|
|
389
|
+
return { control, changed, persisted: store.persisted }
|
|
390
|
+
},
|
|
391
|
+
/** 测试用:清空登记表。 */
|
|
392
|
+
reset() {
|
|
393
|
+
states.clear()
|
|
394
|
+
loaded.clear()
|
|
395
|
+
},
|
|
396
|
+
/** 等写链排空(测试用;生产中不 await)。 */
|
|
397
|
+
flush: () => store.flush(),
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 一个后端只留一个登记表 —— **这是真机验收时抓到的一条真缺陷的修法**。
|
|
403
|
+
*
|
|
404
|
+
* DSH 会在同一个进程里把插件加载很多次(实测 `[dsh-knit] route ready` 在一次运行里
|
|
405
|
+
* 出现十几次),而 json 后端的 kv 单元**只允许一个活句柄**(原话
|
|
406
|
+
* `unit 'x' is already open; a unit has exactly one live handle`,而且它抛的是**普通
|
|
407
|
+
* Error**,不是 StorageError)。每次加载各开一次 ⇒ 第一次之后全部 open 失败,
|
|
408
|
+
* 而 `controlRegistry` 这个模块级变量被**最后一次**加载覆盖 ⇒ 活跃实例恰恰是打不开的
|
|
409
|
+
* 那个,`persisted` 恒 false(且 `~/.dsh/storages/knit_control.json` 永远不出现)。
|
|
410
|
+
*
|
|
411
|
+
* 句柄挂在**后端对象**上(同一进程里是同一个实例),后加载的实例复用它 —— 内存态与
|
|
412
|
+
* 落盘态因此对所有实例是同一份。后端拿不到就返回 `null`(调用方退回内存态)。
|
|
413
|
+
*
|
|
414
|
+
* @param {object|null} backend - `ctx.storage` 里取到的 kv 后端
|
|
415
|
+
* @returns {object|null} 该后端唯一的登记表,或 null
|
|
416
|
+
*/
|
|
417
|
+
export function sharedControlRegistry(backend) {
|
|
418
|
+
if (!backend || typeof backend !== 'object') return null
|
|
419
|
+
if (!backend[CONTROL_SHARED]) backend[CONTROL_SHARED] = createControlRegistry({ backend })
|
|
420
|
+
return backend[CONTROL_SHARED]
|
|
421
|
+
}
|