dsh-xlock 0.0.0-stage → 0.2.8
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/README.md +123 -3
- package/cli/xlock.mjs +359 -0
- package/client.js +307 -0
- package/config.json +10 -0
- package/cordis.patch.yml +10 -0
- package/core/archive.mjs +195 -0
- package/core/archivesync.mjs +170 -0
- package/core/audit.mjs +226 -0
- package/core/classify.mjs +123 -0
- package/core/config.mjs +139 -0
- package/core/frames.mjs +216 -0
- package/core/identity.mjs +44 -0
- package/core/intercept.mjs +364 -0
- package/core/live.mjs +173 -0
- package/core/marker.mjs +234 -0
- package/core/origin.mjs +267 -0
- package/core/quarantine.mjs +240 -0
- package/core/repair.mjs +105 -0
- package/core/sessionfs.mjs +128 -0
- package/core/uistate.mjs +141 -0
- package/core/util.mjs +168 -0
- package/core/xlocktool.mjs +112 -0
- package/dsh-xlock.ps1 +50 -0
- package/index.js +255 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +48 -3
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 隔离区与 gc。
|
|
3
|
+
*
|
|
4
|
+
* 隔离目录:%LOCALAPPDATA%\dsh-xlock\quarantine\<UTC戳>-<sessionId短>-<kind>\
|
|
5
|
+
* 内含:原文件(保留原名)+ meta.json(分类/归属/动作/UTC 时间)。
|
|
6
|
+
* 选 LOCALAPPDATA:同步面之外(免二阶冲突)、不进 DSH 遍历视野。
|
|
7
|
+
* 台账:%LOCALAPPDATA%\dsh-xlock\ledger.jsonl —— quarantine/export/delete 全留痕,
|
|
8
|
+
* 删除动作先写台账再删。
|
|
9
|
+
*
|
|
10
|
+
* 导出(divergent 证据)也放同一目录:`<原名>.divergent.jsonl` + meta 记双边画像。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { copyFileSync, existsSync, readdirSync, rmSync, statSync, appendFileSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
14
|
+
import { basename, join } from 'node:path'
|
|
15
|
+
import { atomicWriteText, ensureDir, isoUtc, moveFile, readJsonSafe, utcStamp } from './util.mjs'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 隔离区根目录。
|
|
19
|
+
* @returns {string}
|
|
20
|
+
*/
|
|
21
|
+
export function quarantineRoot() {
|
|
22
|
+
return join(process.env.LOCALAPPDATA || join(process.env.USERPROFILE || '.', 'AppData', 'Local'), 'dsh-xlock', 'quarantine')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function ledgerPath() {
|
|
26
|
+
return join(quarantineRoot(), '..', 'ledger.jsonl')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 追加一条台账。
|
|
31
|
+
* @param {object} entry
|
|
32
|
+
*/
|
|
33
|
+
export function ledgerAppend(entry) {
|
|
34
|
+
try {
|
|
35
|
+
ensureDir(quarantineRoot())
|
|
36
|
+
appendFileSync(ledgerPath(), `${JSON.stringify({ at: isoUtc(), ...entry })}\n`)
|
|
37
|
+
} catch {
|
|
38
|
+
// 台账失败不阻断主流程。
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function sanitizeSessionId(sessionId) {
|
|
43
|
+
return String(sessionId).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 48) || 'unknown'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 隔离一个文件:move 到新隔离目录 + meta.json + 台账。
|
|
48
|
+
* @param {string} srcPath 源文件绝对路径
|
|
49
|
+
* @param {{sessionId:string, kind:string, classifiedAs?:string, machines?:object, divergence?:object, action?:string, note?:string}} meta
|
|
50
|
+
* @returns {string} 隔离目录
|
|
51
|
+
*/
|
|
52
|
+
export function quarantineFile(srcPath, meta) {
|
|
53
|
+
const root = quarantineRoot()
|
|
54
|
+
const dirName = `${utcStamp()}-${sanitizeSessionId(meta.sessionId)}-${meta.kind}`
|
|
55
|
+
const dir = join(root, dirName)
|
|
56
|
+
let n = 2
|
|
57
|
+
let finalDir = dir
|
|
58
|
+
while (existsSync(finalDir)) {
|
|
59
|
+
finalDir = `${dir}-${n++}`
|
|
60
|
+
}
|
|
61
|
+
mkdirSync(finalDir, { recursive: true })
|
|
62
|
+
const dst = join(finalDir, basename(srcPath))
|
|
63
|
+
moveFile(srcPath, dst)
|
|
64
|
+
const metaOut = {
|
|
65
|
+
v: 1,
|
|
66
|
+
at: isoUtc(),
|
|
67
|
+
sessionId: meta.sessionId,
|
|
68
|
+
kind: meta.kind,
|
|
69
|
+
classifiedAs: meta.classifiedAs,
|
|
70
|
+
machines: meta.machines,
|
|
71
|
+
divergence: meta.divergence,
|
|
72
|
+
action: meta.action || 'quarantine',
|
|
73
|
+
note: meta.note,
|
|
74
|
+
sourcePath: srcPath,
|
|
75
|
+
file: basename(dst),
|
|
76
|
+
}
|
|
77
|
+
atomicWriteText(join(finalDir, 'meta.json'), `${JSON.stringify(metaOut, null, 2)}\n`)
|
|
78
|
+
ledgerAppend({ action: 'quarantine', kind: meta.kind, from: srcPath, to: dst, sessionId: meta.sessionId, bytes: fileSize(dst) })
|
|
79
|
+
return finalDir
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 备份留证:COPY 源文件进隔离目录(原文件留在原地不动)+ meta.json + 台账。
|
|
84
|
+
* 用于修复前的原字节留证(tailRepairIfNeeded 的 quarantineCopy 依赖)——
|
|
85
|
+
* 必须是复制语义:修复要在原路径上原位重写,不能先把原文件搬走。
|
|
86
|
+
* @param {string} srcPath 源文件绝对路径
|
|
87
|
+
* @param {{sessionId:string, kind:string, classifiedAs?:string, machines?:object, action?:string, note?:string, extra?:object}} meta
|
|
88
|
+
* @returns {string} 隔离目录
|
|
89
|
+
*/
|
|
90
|
+
export function quarantineCopyOf(srcPath, meta) {
|
|
91
|
+
const root = quarantineRoot()
|
|
92
|
+
const dirName = `${utcStamp()}-${sanitizeSessionId(meta.sessionId)}-${meta.kind}`
|
|
93
|
+
const dir = join(root, dirName)
|
|
94
|
+
let n = 2
|
|
95
|
+
let finalDir = dir
|
|
96
|
+
while (existsSync(finalDir)) {
|
|
97
|
+
finalDir = `${dir}-${n++}`
|
|
98
|
+
}
|
|
99
|
+
mkdirSync(finalDir, { recursive: true })
|
|
100
|
+
const dst = join(finalDir, basename(srcPath))
|
|
101
|
+
copyFileSync(srcPath, dst)
|
|
102
|
+
const metaOut = {
|
|
103
|
+
v: 1,
|
|
104
|
+
at: isoUtc(),
|
|
105
|
+
sessionId: meta.sessionId,
|
|
106
|
+
kind: meta.kind,
|
|
107
|
+
classifiedAs: meta.classifiedAs,
|
|
108
|
+
machines: meta.machines,
|
|
109
|
+
action: meta.action || 'quarantine-copy',
|
|
110
|
+
note: meta.note,
|
|
111
|
+
...meta.extra,
|
|
112
|
+
sourcePath: srcPath,
|
|
113
|
+
file: basename(dst),
|
|
114
|
+
}
|
|
115
|
+
atomicWriteText(join(finalDir, 'meta.json'), `${JSON.stringify(metaOut, null, 2)}\n`)
|
|
116
|
+
ledgerAppend({ action: 'quarantine-copy', kind: meta.kind, from: srcPath, to: dst, sessionId: meta.sessionId, bytes: fileSize(dst) })
|
|
117
|
+
return finalDir
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function fileSize(path) {
|
|
121
|
+
try {
|
|
122
|
+
return statSync(path).size
|
|
123
|
+
} catch {
|
|
124
|
+
return 0
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 导出分叉证据:写 .divergent.jsonl + meta(不移动原文件)。
|
|
130
|
+
* @param {string} dir 隔离目录(通常刚 quarantineFile 的返回值)
|
|
131
|
+
* @param {string} originalName 原副本文件名
|
|
132
|
+
* @param {{copyOnly:Array, differing:Array}} divergence
|
|
133
|
+
* @param {object} extraMeta 额外 meta 字段
|
|
134
|
+
* @returns {string} 导出文件路径
|
|
135
|
+
*/
|
|
136
|
+
export function writeDivergentExport(dir, originalName, divergence, extraMeta = {}) {
|
|
137
|
+
const lines = []
|
|
138
|
+
for (const rec of divergence.copyOnly) lines.push(JSON.stringify(rec.raw))
|
|
139
|
+
for (const d of divergence.differing) {
|
|
140
|
+
lines.push(JSON.stringify({ __xlock_note: 'differing record — COPY side', seq: d.seq }))
|
|
141
|
+
lines.push(JSON.stringify(d.copy.raw))
|
|
142
|
+
if (d.primary) {
|
|
143
|
+
lines.push(JSON.stringify({ __xlock_note: 'differing record — PRIMARY side', seq: d.seq }))
|
|
144
|
+
lines.push(JSON.stringify(d.primary.raw))
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const outPath = join(dir, `${originalName}.divergent.jsonl`)
|
|
148
|
+
writeFileSync(outPath, lines.length > 0 ? `${lines.join('\n')}\n` : '')
|
|
149
|
+
ledgerAppend({ action: 'export', kind: 'divergent', to: outPath, bytes: fileSize(outPath), ...extraMeta })
|
|
150
|
+
return outPath
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 列出隔离区条目。
|
|
155
|
+
* @returns {Array<{dir:string, meta:object, bytes:number, mtimeMs:number}>}
|
|
156
|
+
*/
|
|
157
|
+
export function listQuarantine() {
|
|
158
|
+
const root = quarantineRoot()
|
|
159
|
+
if (!existsSync(root)) return []
|
|
160
|
+
const out = []
|
|
161
|
+
for (const name of readdirSync(root)) {
|
|
162
|
+
const dir = join(root, name)
|
|
163
|
+
let isDir
|
|
164
|
+
try {
|
|
165
|
+
isDir = statSync(dir).isDirectory()
|
|
166
|
+
} catch {
|
|
167
|
+
continue
|
|
168
|
+
}
|
|
169
|
+
if (!isDir) continue
|
|
170
|
+
const meta = readJsonSafe(join(dir, 'meta.json'), {})
|
|
171
|
+
let bytes = 0
|
|
172
|
+
let mtimeMs = 0
|
|
173
|
+
try {
|
|
174
|
+
for (const f of readdirSync(dir)) {
|
|
175
|
+
const st = statSync(join(dir, f))
|
|
176
|
+
bytes += st.size
|
|
177
|
+
if (st.mtimeMs > mtimeMs) mtimeMs = st.mtimeMs
|
|
178
|
+
}
|
|
179
|
+
} catch {
|
|
180
|
+
continue
|
|
181
|
+
}
|
|
182
|
+
out.push({ dir, name, meta, bytes, mtimeMs })
|
|
183
|
+
}
|
|
184
|
+
return out
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 分叉导出类条目(更长保留期)。 */
|
|
188
|
+
function isExportKind(entry) {
|
|
189
|
+
return (
|
|
190
|
+
entry.meta?.kind === 'divergent-export' ||
|
|
191
|
+
(typeof entry.meta?.classifiedAs === 'string' && entry.meta.classifiedAs.includes('divergent'))
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* gc:按保留期与总量上限清理隔离区。
|
|
197
|
+
* @param {{retentionDays:number, exportRetentionDays:number, maxQuarantineBytes:number}} cfg
|
|
198
|
+
* @param {Date} [now]
|
|
199
|
+
* @returns {{deleted:number, freedBytes:number, entries:number}}
|
|
200
|
+
*/
|
|
201
|
+
export function gcQuarantine(cfg, now = new Date()) {
|
|
202
|
+
const entries = listQuarantine()
|
|
203
|
+
const result = { deleted: 0, freedBytes: 0, entries: entries.length }
|
|
204
|
+
const dayMs = 24 * 3600 * 1000
|
|
205
|
+
const victims = []
|
|
206
|
+
for (const entry of entries) {
|
|
207
|
+
const ageDays = (now.getTime() - entry.mtimeMs) / dayMs
|
|
208
|
+
const limit = isExportKind(entry) ? cfg.exportRetentionDays : cfg.retentionDays
|
|
209
|
+
if (limit >= 0 && ageDays > limit) victims.push(entry)
|
|
210
|
+
}
|
|
211
|
+
// 总量上限:最旧优先删除直到不超限。
|
|
212
|
+
const total = entries.reduce((sum, e) => sum + e.bytes, 0)
|
|
213
|
+
if (cfg.maxQuarantineBytes > 0 && total > cfg.maxQuarantineBytes) {
|
|
214
|
+
let over = total - cfg.maxQuarantineBytes
|
|
215
|
+
const byAge = [...entries.filter((e) => !victims.includes(e))].sort((a, b) => a.mtimeMs - b.mtimeMs)
|
|
216
|
+
for (const entry of byAge) {
|
|
217
|
+
if (over <= 0) break
|
|
218
|
+
victims.push(entry)
|
|
219
|
+
over -= entry.bytes
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
for (const entry of victims) {
|
|
223
|
+
ledgerAppend({
|
|
224
|
+
action: 'delete',
|
|
225
|
+
kind: entry.meta?.kind,
|
|
226
|
+
sessionId: entry.meta?.sessionId,
|
|
227
|
+
dir: entry.dir,
|
|
228
|
+
bytes: entry.bytes,
|
|
229
|
+
ageDays: Math.round(((now.getTime() - entry.mtimeMs) / dayMs) * 10) / 10,
|
|
230
|
+
})
|
|
231
|
+
try {
|
|
232
|
+
rmSync(entry.dir, { recursive: true, force: true })
|
|
233
|
+
result.deleted++
|
|
234
|
+
result.freedBytes += entry.bytes
|
|
235
|
+
} catch {
|
|
236
|
+
// 删不掉(占用)→ 留待下次。
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return result
|
|
240
|
+
}
|
package/core/repair.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 尾部修复门禁。
|
|
3
|
+
*
|
|
4
|
+
* 目标缺陷:**完整已提交帧内 JSONL 末行截断**(DSH 拒载:
|
|
5
|
+
* generation.ts:344 "complete frame contains a torn JSONL record")。
|
|
6
|
+
* 修复:截掉末残行 → 只重压缩该帧 → 前序帧字节原样保留 → 原文件先隔离再重写。
|
|
7
|
+
*
|
|
8
|
+
* 不碰的情形(交回 DSH 原生路径 / 报告):
|
|
9
|
+
* - torn final frame(DSH 写打开自愈截断);
|
|
10
|
+
* - 中间帧损坏(无法按帧修复 → audit 报告)。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { closeSync, copyFileSync, ftruncateSync, mkdirSync, openSync, readFileSync, writeSync, fsyncSync, statSync } from 'node:fs'
|
|
14
|
+
import { dirname } from 'node:path'
|
|
15
|
+
import { zstdCompressSync } from 'node:zlib'
|
|
16
|
+
import { walkLog, splitFrames } from './frames.mjs'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 尾部修复(若需要)。
|
|
20
|
+
* @param {string} logPath 会话日志绝对路径(canonical 名)
|
|
21
|
+
* @param {object} opts
|
|
22
|
+
* @param {(src: string, meta: object) => string} opts.quarantineCopy 隔离函数(返回隔离目录)
|
|
23
|
+
* @param {string} opts.sessionId
|
|
24
|
+
* @param {(line: string) => void} [opts.log]
|
|
25
|
+
* @returns {{repaired: boolean, reason?: string, droppedBytes?: number, quarantineDir?: string}}
|
|
26
|
+
*/
|
|
27
|
+
export function tailRepairIfNeeded(logPath, { quarantineCopy, sessionId, log = () => {} }) {
|
|
28
|
+
let size
|
|
29
|
+
try {
|
|
30
|
+
size = statSync(logPath).size
|
|
31
|
+
} catch {
|
|
32
|
+
return { repaired: false, reason: 'missing' }
|
|
33
|
+
}
|
|
34
|
+
if (size < 8) return { repaired: false, reason: 'empty' }
|
|
35
|
+
const buf = readFileSync(logPath)
|
|
36
|
+
const { frames, tornTailStart } = splitFrames(buf)
|
|
37
|
+
if (tornTailStart !== undefined) {
|
|
38
|
+
// DSH 写打开自愈;我们不重复造轮子。
|
|
39
|
+
return { repaired: false, reason: 'torn-tail-frame' }
|
|
40
|
+
}
|
|
41
|
+
if (frames.length === 0) return { repaired: false, reason: 'no-frames' }
|
|
42
|
+
const last = frames[frames.length - 1]
|
|
43
|
+
const text = last.text
|
|
44
|
+
if (text === undefined) return { repaired: false, reason: 'undecodable' }
|
|
45
|
+
const lines = text.split('\n')
|
|
46
|
+
const lastLine = lines[lines.length - 1]
|
|
47
|
+
const trailingPartial = lastLine !== '' // 无换行收尾的残字(或恰好整帧无末换行且完整——见下)
|
|
48
|
+
if (!trailingPartial) return { repaired: false } // 末行以 \n 收尾 → 完整
|
|
49
|
+
|
|
50
|
+
// 残行判定:JSON.parse 失败才是截断;可解析只是缺末换行 → 只补换行不动内容。
|
|
51
|
+
let isTorn
|
|
52
|
+
try {
|
|
53
|
+
JSON.parse(lastLine)
|
|
54
|
+
isTorn = false
|
|
55
|
+
} catch {
|
|
56
|
+
isTorn = true
|
|
57
|
+
}
|
|
58
|
+
if (!isTorn) return { repaired: false }
|
|
59
|
+
|
|
60
|
+
const keptText = lines.slice(0, -1).join('\n') + (lines.length > 1 ? '\n' : '')
|
|
61
|
+
const prefixEnd = last.start
|
|
62
|
+
const newFrame = zstdCompressSync(Buffer.from(keptText, 'utf8'))
|
|
63
|
+
const droppedBytes = last.end - last.start - newFrame.length
|
|
64
|
+
|
|
65
|
+
// 1) 原文件先隔离(kind=torn-pre-repair)
|
|
66
|
+
let quarantineDir
|
|
67
|
+
if (quarantineCopy) {
|
|
68
|
+
try {
|
|
69
|
+
quarantineDir = quarantineCopy(logPath, { sessionId, kind: 'torn-pre-repair', extra: { droppedBytes } })
|
|
70
|
+
} catch (error) {
|
|
71
|
+
// 隔离失败不放弃修复:继续原位修复(原字节已读入 buf)。
|
|
72
|
+
log(`quarantine before repair failed: ${error?.message || error}`)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 2) 原位重写:前缀字节 + 新末帧;截掉多余尾巴。
|
|
77
|
+
mkdirSync(dirname(logPath), { recursive: true })
|
|
78
|
+
const fd = openSync(logPath, 'r+')
|
|
79
|
+
try {
|
|
80
|
+
let offset = 0
|
|
81
|
+
if (prefixEnd > 0) {
|
|
82
|
+
writeSync(fd, buf.subarray(0, prefixEnd), 0, prefixEnd, 0)
|
|
83
|
+
offset = prefixEnd
|
|
84
|
+
}
|
|
85
|
+
writeSync(fd, newFrame, 0, newFrame.length, offset)
|
|
86
|
+
fsyncSync(fd)
|
|
87
|
+
ftruncateSync(fd, offset + newFrame.length)
|
|
88
|
+
fsyncSync(fd)
|
|
89
|
+
} finally {
|
|
90
|
+
closeSync(fd)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// 3) 自检:重走查应无 tornJsonlLastLine。
|
|
94
|
+
const after = walkLog(readFileSync(logPath))
|
|
95
|
+
if (after.health.tornJsonlLastLine) {
|
|
96
|
+
log('repair self-check still reports torn JSONL — leaving for audit')
|
|
97
|
+
}
|
|
98
|
+
return { repaired: true, droppedBytes, quarantineDir }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 便捷包装:把一个文件原样复制进隔离目录(原字节留证)。
|
|
103
|
+
* 由 quarantine.mjs 的 quarantineFile 提供时无需本函数;测试可直接传。
|
|
104
|
+
*/
|
|
105
|
+
export { copyFileSync, readFileSync }
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 会话文件系统视图(CLI 用)。
|
|
3
|
+
*
|
|
4
|
+
* ~/.dsh/sessions/<--normalized-cwd-->/<session-id>/session[.vN].jsonl.zstd
|
|
5
|
+
* CLI 不经 DSH 运行时,直接按目录面扫描(只读 + 显式动作)。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { parseLogFilename } from './frames.mjs'
|
|
12
|
+
import { MARKER_NAME } from './marker.mjs'
|
|
13
|
+
import { ORIGIN_NAME } from './origin.mjs'
|
|
14
|
+
import { ARCHIVE_MARKER_RE } from './archive.mjs'
|
|
15
|
+
import { parseSyncConflictName } from './util.mjs'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 会话库根目录(~/.dsh/sessions,经 Junction 即同步面)。
|
|
19
|
+
*/
|
|
20
|
+
export function sessionsRoot() {
|
|
21
|
+
return join(homedir(), '.dsh', 'sessions')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 列出全部会话目录。
|
|
26
|
+
* @returns {Array<{bucket:string, dir:string, name:string}>}
|
|
27
|
+
*/
|
|
28
|
+
export function listSessionDirs() {
|
|
29
|
+
const root = sessionsRoot()
|
|
30
|
+
if (!existsSync(root)) return []
|
|
31
|
+
const out = []
|
|
32
|
+
for (const bucket of readdirSync(root)) {
|
|
33
|
+
const bucketDir = join(root, bucket)
|
|
34
|
+
let sessionDirs
|
|
35
|
+
try {
|
|
36
|
+
sessionDirs = readdirSync(bucketDir, { withFileTypes: true })
|
|
37
|
+
} catch {
|
|
38
|
+
continue
|
|
39
|
+
}
|
|
40
|
+
for (const ent of sessionDirs) {
|
|
41
|
+
if (!ent.isDirectory()) continue
|
|
42
|
+
out.push({ bucket, dir: join(bucketDir, ent.name), name: ent.name })
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 按会话 id(完整或前缀)定位目录。
|
|
50
|
+
* @param {string} query 例如 "session-55d2ae62-…" 或 "55d2ae62"
|
|
51
|
+
*/
|
|
52
|
+
export function findSessionDirs(query) {
|
|
53
|
+
const q = String(query).trim()
|
|
54
|
+
if (q === '') return []
|
|
55
|
+
const all = listSessionDirs()
|
|
56
|
+
const exact = all.filter((s) => s.name === q)
|
|
57
|
+
if (exact.length > 0) return exact
|
|
58
|
+
return all.filter((s) => s.name.includes(q))
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 会话目录内容盘点。
|
|
63
|
+
* @param {string} dir
|
|
64
|
+
* @returns {{
|
|
65
|
+
* canonical: Array<{name:string,path:string,version:number}>,
|
|
66
|
+
* logConflicts: Array<{name:string,path:string,version:number,shortId?:string,date?:string,time?:string}>,
|
|
67
|
+
* markerConflicts: string[],
|
|
68
|
+
* archiveConflicts: string[],
|
|
69
|
+
* other: string[],
|
|
70
|
+
* }}
|
|
71
|
+
*/
|
|
72
|
+
export function inventorySessionDir(dir) {
|
|
73
|
+
let names
|
|
74
|
+
try {
|
|
75
|
+
names = readdirSync(dir)
|
|
76
|
+
} catch {
|
|
77
|
+
return { canonical: [], logConflicts: [], markerConflicts: [], archiveConflicts: [], other: [] }
|
|
78
|
+
}
|
|
79
|
+
const canonical = []
|
|
80
|
+
const logConflicts = []
|
|
81
|
+
const markerConflicts = []
|
|
82
|
+
const archiveConflicts = []
|
|
83
|
+
const other = []
|
|
84
|
+
for (const name of names) {
|
|
85
|
+
const path = join(dir, name)
|
|
86
|
+
const parsed = parseLogFilename(name)
|
|
87
|
+
if (parsed.kind === 'canonical') {
|
|
88
|
+
canonical.push({ name, path, version: parsed.version })
|
|
89
|
+
continue
|
|
90
|
+
}
|
|
91
|
+
if (parsed.kind === 'conflict') {
|
|
92
|
+
logConflicts.push({ name, path, version: parsed.version, shortId: parsed.shortId, date: parsed.date, time: parsed.time })
|
|
93
|
+
continue
|
|
94
|
+
}
|
|
95
|
+
// 创建归属记录本体/冲突副本:纯元数据,不是争抢痕迹(core/marker.mjs 的
|
|
96
|
+
// MARKER_CONFLICT_RE 同样排除了 origin),整段跳过,不做噪音。
|
|
97
|
+
if (name === ORIGIN_NAME || /^\.dsh-xlock-origin\.json\.sync-conflict-/.test(name)) continue
|
|
98
|
+
// 归档标记(core/archive.mjs,新旧两个文件名 + 冲突副本):xlock 自己的
|
|
99
|
+
// 标记,不再是"外来标记"。本体存在即正常,不计入摘要;只有 Syncthing 冲突
|
|
100
|
+
// 副本(两台机并发改归档状态的痕迹)单列一桶,供 status/audit 提示看一眼。
|
|
101
|
+
if (ARCHIVE_MARKER_RE.test(name)) {
|
|
102
|
+
if (name.includes('.sync-conflict-')) archiveConflicts.push(name)
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
if (/^\.dsh-xlock/.test(name) && /\.sync-conflict-/.test(name)) {
|
|
106
|
+
markerConflicts.push(name)
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
if (name === MARKER_NAME) continue
|
|
110
|
+
other.push(name)
|
|
111
|
+
}
|
|
112
|
+
return { canonical, logConflicts, markerConflicts, archiveConflicts, other }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 副本设备短 ID → 机器名(包内 machines.json 映射;未知原样返回)。
|
|
117
|
+
* @param {string|undefined} shortId
|
|
118
|
+
* @param {{devices?:Record<string,string>}} registry
|
|
119
|
+
* @returns {{name:string, known:boolean}}
|
|
120
|
+
*/
|
|
121
|
+
export function machineName(shortId, registry) {
|
|
122
|
+
if (!shortId) return { name: '(unknown)', known: false }
|
|
123
|
+
const devices = registry?.devices || {}
|
|
124
|
+
const name = devices[shortId]
|
|
125
|
+
return name ? { name, known: true } : { name: shortId, known: false }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export { parseSyncConflictName }
|
package/core/uistate.mjs
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 会话锁/归档状态的只读查询与显式解锁(core/uistate.mjs)
|
|
3
|
+
*
|
|
4
|
+
* 供宿主半的 webServer 路由(client UI)使用,也可单测。刻意只依赖 core 里
|
|
5
|
+
* 已有的纯函数 + node:fs,不碰 Cordis 服务,方便在 test/run.mjs 里独立验证。
|
|
6
|
+
*
|
|
7
|
+
* 数据源全是本机磁盘上的会话目录标记:锁标记(core/marker.mjs)、归档标记
|
|
8
|
+
* (core/archive.mjs)、创建归属(core/origin.mjs)。Syncthing minute 级延迟
|
|
9
|
+
* 依旧存在——这里读到的是"本机此刻看见的那一面",不是跨机强一致状态。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { existsSync, unlinkSync } from 'node:fs'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { markerStatus, listMarkerConflicts, MARKER_NAME } from './marker.mjs'
|
|
15
|
+
import { readArchiveMarker } from './archive.mjs'
|
|
16
|
+
import { inferOrigin } from './origin.mjs'
|
|
17
|
+
import { findSessionDirs } from './sessionfs.mjs'
|
|
18
|
+
import { describeActivity } from './live.mjs'
|
|
19
|
+
|
|
20
|
+
/** 标记损坏按 fail-safe 对待:和异机持有一样不许接管,只是多带一个 corrupt 字段。 */
|
|
21
|
+
function lockStateOf(status) {
|
|
22
|
+
if (status.corrupt || status.foreign || status.conflicts.length > 0) return 'held-foreign'
|
|
23
|
+
if (status.state === 'held') return 'held-self'
|
|
24
|
+
if (status.state === 'released') return 'released'
|
|
25
|
+
return 'unmarked'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 查一个会话的锁 + 归档 + 活跃度状态。
|
|
30
|
+
*
|
|
31
|
+
* @param {string} sessionId
|
|
32
|
+
* @param {{identity?:object, registry?:object, now?:number, activeMs?:number}} env
|
|
33
|
+
* @returns {object|null} 找不到会话目录返回 null
|
|
34
|
+
*/
|
|
35
|
+
export function getSessionLockState(sessionId, env = {}) {
|
|
36
|
+
const dirs = findSessionDirs(String(sessionId || '').trim())
|
|
37
|
+
// 精确名优先;includes 兜底是为了兼容历史前缀查询,但绝不放宽解锁(见 reset)。
|
|
38
|
+
const hit = dirs.find((d) => d.name === String(sessionId)) || dirs[0]
|
|
39
|
+
if (!hit) return null
|
|
40
|
+
|
|
41
|
+
const identity = env.identity || {}
|
|
42
|
+
const status = markerStatus(hit.dir, identity)
|
|
43
|
+
const origin = inferOrigin(hit.dir, {
|
|
44
|
+
identity,
|
|
45
|
+
registry: env.registry || {},
|
|
46
|
+
bucket: hit.bucket,
|
|
47
|
+
})
|
|
48
|
+
const archive = readArchiveMarker(hit.dir)
|
|
49
|
+
const lockState = lockStateOf(status)
|
|
50
|
+
// 只有异机持有时才去读日志——本机会话的平台状态点已经足够,读日志是白花钱。
|
|
51
|
+
const activity = lockState === 'held-foreign'
|
|
52
|
+
? describeActivity(hit.dir, { now: env.now, activeMs: env.activeMs })
|
|
53
|
+
: null
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
sessionId: hit.name,
|
|
57
|
+
lockState,
|
|
58
|
+
host: status.holder?.host || (origin.known ? origin.host : null),
|
|
59
|
+
machineId: status.holder?.machineId || origin.machineId || null,
|
|
60
|
+
pid: status.holder?.pid ?? null,
|
|
61
|
+
corrupt: status.corrupt === true,
|
|
62
|
+
markerConflicts: status.conflicts.length,
|
|
63
|
+
createdRemote: origin.local === false && origin.source !== 'unknown',
|
|
64
|
+
createdHost: origin.source === 'unknown' ? null : origin.host,
|
|
65
|
+
originSource: origin.source,
|
|
66
|
+
archived: typeof archive.archived === 'boolean' ? archive.archived : null,
|
|
67
|
+
archiveSource: archive.source,
|
|
68
|
+
/** 异机持有时才非 null:`{activity,lastWriteAt,freshMs,openTurn}`(core/live.mjs)。 */
|
|
69
|
+
activity,
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 列出本机可见的全部会话状态。 */
|
|
74
|
+
export function listSessionLockStates(env = {}) {
|
|
75
|
+
const dirs = findSessionDirs('session-')
|
|
76
|
+
const out = []
|
|
77
|
+
for (const dir of dirs) {
|
|
78
|
+
const state = getSessionLockState(dir.name, env)
|
|
79
|
+
if (state) out.push(state)
|
|
80
|
+
}
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 磁盘上的全量会话 id(去重、排序)。
|
|
86
|
+
*
|
|
87
|
+
* 给浏览器半做**集合变化检测**:平台只在连接建立时拉一次列表,之后靠事件增量维护;
|
|
88
|
+
* 异机删掉一条会话时本机不会产生 session/disposed,那行会一直挂着。宿主半扫盘能
|
|
89
|
+
* 看见「少了一条」,客户端比对集合变了就让平台重拉权威基线。
|
|
90
|
+
*
|
|
91
|
+
* 用磁盘目录而不是 `sessionPersistence.list`:本模块刻意只依赖 core 纯函数,
|
|
92
|
+
* 而目录面就是持久化的真身(list 也只是在读它)。
|
|
93
|
+
*
|
|
94
|
+
* @returns {string[]}
|
|
95
|
+
*/
|
|
96
|
+
export function listSessionIds() {
|
|
97
|
+
const ids = new Set()
|
|
98
|
+
for (const dir of findSessionDirs('session-')) {
|
|
99
|
+
if (typeof dir.name === 'string' && dir.name.startsWith('session-')) ids.add(dir.name)
|
|
100
|
+
}
|
|
101
|
+
return [...ids].sort()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 显式解锁:删除粘锁标记 + 它的 sync-conflict 副本(与 cli/xlock.mjs cmdReset 同语义)。
|
|
106
|
+
*
|
|
107
|
+
* 安全约束:
|
|
108
|
+
* - 只接受**精确会话名**,不接受前缀 / 路径 / 目录穿越——前缀命中多个目录时
|
|
109
|
+
* 宁可拒绝,也不盲删一堆标记;
|
|
110
|
+
* - 只删会话目录内固定文件名的标记,绝不按请求里的任意路径删文件;
|
|
111
|
+
* - 归档标记(.dsh-xlock-archive.json / 旧名)一概不碰——解锁与归档无因果关系。
|
|
112
|
+
*
|
|
113
|
+
* @param {string} sessionId
|
|
114
|
+
* @param {{sessionsDir?:string}} env
|
|
115
|
+
* @returns {{ok:boolean, sessionId:string, removed:string[], error?:string}}
|
|
116
|
+
*/
|
|
117
|
+
export function resetSessionLock(sessionId, env = {}) {
|
|
118
|
+
const raw = String(sessionId || '').trim()
|
|
119
|
+
if (raw === '') return { ok: false, sessionId: raw, removed: [], error: 'sessionId required' }
|
|
120
|
+
const dirs = findSessionDirs(raw)
|
|
121
|
+
const hit = dirs.find((d) => d.name === raw)
|
|
122
|
+
if (!hit) {
|
|
123
|
+
return {
|
|
124
|
+
ok: false,
|
|
125
|
+
sessionId: raw,
|
|
126
|
+
removed: [],
|
|
127
|
+
error: dirs.length > 0 ? 'sessionId must be exact (prefix matched multiple sessions)' : 'session not found',
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const removed = []
|
|
131
|
+
const marker = join(hit.dir, MARKER_NAME)
|
|
132
|
+
if (existsSync(marker)) {
|
|
133
|
+
unlinkSync(marker)
|
|
134
|
+
removed.push(MARKER_NAME)
|
|
135
|
+
}
|
|
136
|
+
for (const name of listMarkerConflicts(hit.dir)) {
|
|
137
|
+
unlinkSync(join(hit.dir, name))
|
|
138
|
+
removed.push(name)
|
|
139
|
+
}
|
|
140
|
+
return { ok: true, sessionId: hit.name, removed }
|
|
141
|
+
}
|