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
package/core/live.mjs
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 会话活跃度探测(core/live.mjs)
|
|
3
|
+
*
|
|
4
|
+
* 回答一个问题:**另一台机器此刻真的在写这条会话,还是只留下了锁标记?**
|
|
5
|
+
*
|
|
6
|
+
* 平台没有跨机运行状态协议:`sessionController.list` 的 `running` 只认本进程的 live
|
|
7
|
+
* Agent,冷行一律 false。所以只能从本机就能看到的两个客观事实推导——锁标记为 held
|
|
8
|
+
* 且持有方不是本机,再看会话日志还新不新。纯读取,不碰任何会话文件。
|
|
9
|
+
*
|
|
10
|
+
* 两种状态必须长得不一样:
|
|
11
|
+
* writing 对端真在写(日志新鲜,或最后一轮 turn 还没收尾)
|
|
12
|
+
* silent 标记还在但日志早停了(残锁,崩溃/未 close 留下的)
|
|
13
|
+
*
|
|
14
|
+
* 注意:**不做新鲜度截断**。残锁恰恰是最需要人看见并解锁的情况,早期实现把超过
|
|
15
|
+
* 15 分钟的标记整个丢弃,等于把最该暴露的状态藏起来。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { closeSync, fstatSync, openSync, readdirSync, readSync, statSync } from 'node:fs'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
import { zstdDecompressSync } from 'node:zlib'
|
|
21
|
+
|
|
22
|
+
/** 会话目录里代表「日志正在增长」的文件名(jsonl / jsonl.zstd 两代格式)。 */
|
|
23
|
+
export const SESSION_LOG_NAMES = ['session.v4.jsonl.zstd', 'session.jsonl.zstd', 'session.v4.jsonl', 'session.jsonl']
|
|
24
|
+
|
|
25
|
+
/** Syncthing 接收中的临时文件前缀 / 冲突副本标记。 */
|
|
26
|
+
const SYNCTHING_TMP_PREFIX = '~syncthing~'
|
|
27
|
+
const SYNCTHING_CONFLICT_MARK = '.sync-conflict-'
|
|
28
|
+
|
|
29
|
+
/** zstd 帧魔数:会话日志是多帧拼接,解尾帧要先找到帧边界。 */
|
|
30
|
+
const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
|
|
31
|
+
|
|
32
|
+
/** 只看日志尾巴的字节数。够了:一次 turn 的收尾/开启总在最后几帧里。 */
|
|
33
|
+
const TAIL_BYTES = 262144
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 会话目录里「对端最近一次写」的时间(毫秒);没有可判读的文件返回 null。
|
|
37
|
+
*
|
|
38
|
+
* 为什么不能只看正式日志的 mtime:跨机同步走 Syncthing,它是「先写
|
|
39
|
+
* `~syncthing~<name>.tmp`,整份收完再 rename 盖住正式文件」。对端每隔几秒就追加
|
|
40
|
+
* 一段 zstd,本地这份就得整份重传一次 —— 日志越大,正式文件的 mtime 落后越久
|
|
41
|
+
* (实测 1.2 MB 的日志能落后好几分钟)。只盯正式文件会把「正在传输」误判成
|
|
42
|
+
* 「已停止」。所以把正在接收的临时文件、以及 `.sync-conflict-*` 副本也算作证据。
|
|
43
|
+
*
|
|
44
|
+
* @param {string} dir
|
|
45
|
+
* @returns {number|null}
|
|
46
|
+
*/
|
|
47
|
+
export function sessionLogMtime(dir) {
|
|
48
|
+
let names
|
|
49
|
+
try {
|
|
50
|
+
names = readdirSync(dir)
|
|
51
|
+
} catch {
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
let best = null
|
|
55
|
+
for (const name of names) {
|
|
56
|
+
const isLog = SESSION_LOG_NAMES.includes(name)
|
|
57
|
+
const isIncoming = name.startsWith(SYNCTHING_TMP_PREFIX) && SESSION_LOG_NAMES.some((log) => name.includes(log))
|
|
58
|
+
const isConflict = name.includes(SYNCTHING_CONFLICT_MARK) && SESSION_LOG_NAMES.some((log) => name.includes(log))
|
|
59
|
+
if (!isLog && !isIncoming && !isConflict) continue
|
|
60
|
+
try {
|
|
61
|
+
const info = statSync(join(dir, name))
|
|
62
|
+
if (!info.isFile()) continue
|
|
63
|
+
if (best === null || info.mtimeMs > best) best = info.mtimeMs
|
|
64
|
+
} catch {
|
|
65
|
+
/* 正在被 rename 覆盖,下次再看 */
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return best
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 读日志**尾部**,判断最后一轮是否还没收尾(`turn/start` 之后没有 `turn/end`)。
|
|
73
|
+
*
|
|
74
|
+
* 光看 mtime 判不出「在跑但在等」——对端跑一个长工具调用可以几分钟不写日志,那段
|
|
75
|
+
* 静默会被误判成「已停止」。反过来,日志停在那里但 turn 没闭合,就说明它还在轮次
|
|
76
|
+
* 中间。返回 `true`(未收尾)/ `false`(已收尾)/ `null`(读不到或格式不认识)。
|
|
77
|
+
*
|
|
78
|
+
* @param {string} sessionDir
|
|
79
|
+
* @returns {boolean|null}
|
|
80
|
+
*/
|
|
81
|
+
export function tailHasOpenTurn(sessionDir) {
|
|
82
|
+
if (!sessionDir) return null
|
|
83
|
+
let file = null
|
|
84
|
+
for (const name of SESSION_LOG_NAMES) {
|
|
85
|
+
const candidate = join(sessionDir, name)
|
|
86
|
+
try {
|
|
87
|
+
if (statSync(candidate).isFile()) {
|
|
88
|
+
file = candidate
|
|
89
|
+
break
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
/* 试下一个候选名 */
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (file === null) return null
|
|
96
|
+
let fd = null
|
|
97
|
+
try {
|
|
98
|
+
fd = openSync(file, 'r')
|
|
99
|
+
const size = fstatSync(fd).size
|
|
100
|
+
if (size <= 0) return null
|
|
101
|
+
const take = Math.min(size, TAIL_BYTES)
|
|
102
|
+
const buffer = Buffer.alloc(take)
|
|
103
|
+
readSync(fd, buffer, 0, take, size - take)
|
|
104
|
+
let text
|
|
105
|
+
if (file.endsWith('.jsonl.zstd')) {
|
|
106
|
+
// 多帧 zstd:从块内第一个帧边界解到末尾,拼起来再按行解析。
|
|
107
|
+
const starts = []
|
|
108
|
+
for (let at = buffer.indexOf(ZSTD_MAGIC); at !== -1; at = buffer.indexOf(ZSTD_MAGIC, at + 4)) starts.push(at)
|
|
109
|
+
if (starts.length === 0) return null
|
|
110
|
+
const parts = []
|
|
111
|
+
for (let i = 0; i < starts.length; i += 1) {
|
|
112
|
+
const end = i + 1 < starts.length ? starts[i + 1] : buffer.length
|
|
113
|
+
try {
|
|
114
|
+
parts.push(zstdDecompressSync(buffer.subarray(starts[i], end)))
|
|
115
|
+
} catch {
|
|
116
|
+
break // 最后一帧可能被截断(正在写),前面解出来的够用
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (parts.length === 0) return null
|
|
120
|
+
text = Buffer.concat(parts).toString('utf8')
|
|
121
|
+
} else {
|
|
122
|
+
text = buffer.toString('utf8')
|
|
123
|
+
}
|
|
124
|
+
let open = null
|
|
125
|
+
for (const line of text.split('\n')) {
|
|
126
|
+
if (line.length === 0) continue
|
|
127
|
+
let event
|
|
128
|
+
try {
|
|
129
|
+
event = JSON.parse(line)
|
|
130
|
+
} catch {
|
|
131
|
+
continue // 尾部可能被截断成半行
|
|
132
|
+
}
|
|
133
|
+
if (event?.type === 'turn/start') open = true
|
|
134
|
+
else if (event?.type === 'turn/end') open = false
|
|
135
|
+
}
|
|
136
|
+
return open
|
|
137
|
+
} catch {
|
|
138
|
+
return null
|
|
139
|
+
} finally {
|
|
140
|
+
if (fd !== null) {
|
|
141
|
+
try {
|
|
142
|
+
closeSync(fd)
|
|
143
|
+
} catch {
|
|
144
|
+
/* 关不掉不影响判断 */
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 判一条会话目录的活跃度。
|
|
152
|
+
*
|
|
153
|
+
* @param {string} sessionDir
|
|
154
|
+
* @param {{now?:number, activeMs?:number}} [opts]
|
|
155
|
+
* @returns {{activity:'writing'|'silent', lastWriteAt:number|null, freshMs:number|null, openTurn:boolean}}
|
|
156
|
+
*/
|
|
157
|
+
export function describeActivity(sessionDir, opts = {}) {
|
|
158
|
+
const now = Number.isFinite(opts.now) ? opts.now : Date.now()
|
|
159
|
+
const activeMs = Number.isFinite(opts.activeMs) && opts.activeMs >= 0 ? opts.activeMs : 180000
|
|
160
|
+
const lastWriteAt = sessionLogMtime(sessionDir)
|
|
161
|
+
if (lastWriteAt === null) {
|
|
162
|
+
return { activity: 'silent', lastWriteAt: null, freshMs: null, openTurn: false }
|
|
163
|
+
}
|
|
164
|
+
const freshMs = Math.max(0, now - lastWriteAt)
|
|
165
|
+
// 只在新旧之间那一带才需要读日志尾巴(贵),新鲜的直接判 writing。
|
|
166
|
+
const openTurn = freshMs <= activeMs ? false : tailHasOpenTurn(sessionDir) === true
|
|
167
|
+
return {
|
|
168
|
+
activity: freshMs <= activeMs || openTurn ? 'writing' : 'silent',
|
|
169
|
+
lastWriteAt,
|
|
170
|
+
freshMs,
|
|
171
|
+
openTurn,
|
|
172
|
+
}
|
|
173
|
+
}
|
package/core/marker.mjs
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 粘性懒加载锁标记。
|
|
3
|
+
*
|
|
4
|
+
* 标记:<session-dir>/.dsh-xlock.json
|
|
5
|
+
* { v:1, machineId, host, pid, sessionId, state:'held'|'released' }
|
|
6
|
+
*
|
|
7
|
+
* 状态机(终稿):
|
|
8
|
+
* - 无标记 → `fs.openSync(p,'wx')` 独占原子创建 held(创建即互斥原语);
|
|
9
|
+
* - held+本机 → 放行(崩溃残留自愈路径);
|
|
10
|
+
* - held+异机 / 标记损坏 / 标记出现 sync-conflict 副本 → 拦截
|
|
11
|
+
* (抛 name='SessionAlreadyOwnedError' 的 Error,控制器映射为
|
|
12
|
+
* session/writer-held,message 携带持有主机名与 reset 指引直达 UI);
|
|
13
|
+
* - released(任意机)→ 原子翻转 held 放行;
|
|
14
|
+
* - 释放:close → 原子改写 released(不删除;分钟级同步延迟下
|
|
15
|
+
* released 态让对机立刻可接管,也不留"幽灵 held");
|
|
16
|
+
* - 崩溃:无 close → held 残留 → 异机持续被拦(有意 fail-safe)。
|
|
17
|
+
*
|
|
18
|
+
* 无决策用时间戳:跨机时钟不可信,状态只由显式翻转推进。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, writeSync, fsyncSync } from 'node:fs'
|
|
22
|
+
import { join } from 'node:path'
|
|
23
|
+
import { atomicWriteText, readJsonSafe } from './util.mjs'
|
|
24
|
+
|
|
25
|
+
export const MARKER_NAME = '.dsh-xlock.json'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* marker 文件名 + 任意 sync-conflict 变体(Syncthing 冲突副本)。
|
|
29
|
+
*
|
|
30
|
+
* 必须排除 `.dsh-xlock-origin*` 与 `.dsh-xlock-archive*`:创建归属记录
|
|
31
|
+
* (core/origin.mjs)和归档标记(core/archive.mjs)都住在同一目录,它们的
|
|
32
|
+
* 冲突副本只是"两台机都写过"的痕迹,不是争抢,不该把会话挡住
|
|
33
|
+
* ((?!-origin|-archive) 这一处就是防线)。
|
|
34
|
+
*/
|
|
35
|
+
const MARKER_CONFLICT_RE = /^\.dsh-xlock(?!-origin|-archive).*\.sync-conflict-\d{8}-\d{6}-[A-Za-z0-9]+\.\w+$/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 跨机/异常拦截错误。name 固定为 SessionAlreadyOwnedError,
|
|
39
|
+
* dsh-api-session-controller/src/agent.ts:199 按 name 捕获并映射
|
|
40
|
+
* RemoteError('session/writer-held', message) —— message 直达 UI。
|
|
41
|
+
*/
|
|
42
|
+
export class XlockHeldError extends Error {
|
|
43
|
+
/**
|
|
44
|
+
* @param {string} sessionId
|
|
45
|
+
* @param {string} message 完整提示(含持有方与逃生门指引)
|
|
46
|
+
*/
|
|
47
|
+
constructor(sessionId, message) {
|
|
48
|
+
super(message)
|
|
49
|
+
this.name = 'SessionAlreadyOwnedError'
|
|
50
|
+
this.sessionId = sessionId
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 会话目录内的标记绝对路径。
|
|
56
|
+
* @param {string} sessionDir
|
|
57
|
+
*/
|
|
58
|
+
export function markerPath(sessionDir) {
|
|
59
|
+
return join(sessionDir, MARKER_NAME)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 读取标记。
|
|
64
|
+
* @returns {{state:'missing'}|{state:'corrupt'}|{state:'ok',data:any}}
|
|
65
|
+
*/
|
|
66
|
+
export function readMarker(sessionDir) {
|
|
67
|
+
const path = markerPath(sessionDir)
|
|
68
|
+
if (!existsSync(path)) return { state: 'missing' }
|
|
69
|
+
const data = readJsonSafe(path, undefined)
|
|
70
|
+
if (!data || typeof data !== 'object' || (data.state !== 'held' && data.state !== 'released')) {
|
|
71
|
+
return { state: 'corrupt' }
|
|
72
|
+
}
|
|
73
|
+
return { state: 'ok', data }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 扫描会话目录中的标记冲突副本(.dsh-xlock*.sync-conflict-*.json)。
|
|
78
|
+
* 存在即视为"异机持锁痕迹"——fail-safe 拦截。
|
|
79
|
+
* @param {string} sessionDir
|
|
80
|
+
* @returns {string[]}
|
|
81
|
+
*/
|
|
82
|
+
export function listMarkerConflicts(sessionDir) {
|
|
83
|
+
let names
|
|
84
|
+
try {
|
|
85
|
+
names = readdirSync(sessionDir)
|
|
86
|
+
} catch {
|
|
87
|
+
return []
|
|
88
|
+
}
|
|
89
|
+
return names.filter((name) => MARKER_CONFLICT_RE.test(name))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 以 wx 独占创建 held 标记(无则创建;已存在返回 false)。
|
|
94
|
+
* @returns {boolean} 是否由本次调用创建
|
|
95
|
+
*/
|
|
96
|
+
export function createHeldMarker(sessionDir, identity, sessionId) {
|
|
97
|
+
const path = markerPath(sessionDir)
|
|
98
|
+
const payload = JSON.stringify({
|
|
99
|
+
v: 1,
|
|
100
|
+
machineId: identity.uuid,
|
|
101
|
+
host: identity.host,
|
|
102
|
+
pid: process.pid,
|
|
103
|
+
sessionId,
|
|
104
|
+
state: 'held',
|
|
105
|
+
})
|
|
106
|
+
let fd
|
|
107
|
+
try {
|
|
108
|
+
fd = openSync(path, 'wx')
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error?.code === 'EEXIST') return false
|
|
111
|
+
if (error?.code === 'ENOENT') {
|
|
112
|
+
mkdirSync(sessionDir, { recursive: true })
|
|
113
|
+
fd = openSync(path, 'wx')
|
|
114
|
+
} else {
|
|
115
|
+
throw error
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
writeSync(fd, `${payload}\n`, 0, 'utf8')
|
|
120
|
+
fsyncSync(fd)
|
|
121
|
+
} finally {
|
|
122
|
+
closeSync(fd)
|
|
123
|
+
}
|
|
124
|
+
return true
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 原子写完整标记内容(temp+rename)。
|
|
129
|
+
*/
|
|
130
|
+
function writeMarker(sessionDir, data) {
|
|
131
|
+
atomicWriteText(markerPath(sessionDir), `${JSON.stringify(data)}\n`)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 取得本机持锁(幂等):
|
|
136
|
+
* - missing → wx 创建;
|
|
137
|
+
* - released → 翻转 held(机器字段换成自己);
|
|
138
|
+
* - held+本机 → 保持;
|
|
139
|
+
* - held+异机 / corrupt / 存在标记冲突副本 → 抛 XlockHeldError。
|
|
140
|
+
* @param {string} sessionDir
|
|
141
|
+
* @param {{uuid:string,host:string}} identity
|
|
142
|
+
* @param {string} sessionId
|
|
143
|
+
*/
|
|
144
|
+
export function acquireMarker(sessionDir, identity, sessionId) {
|
|
145
|
+
const conflicts = listMarkerConflicts(sessionDir)
|
|
146
|
+
if (conflicts.length > 0) {
|
|
147
|
+
throw new XlockHeldError(
|
|
148
|
+
sessionId,
|
|
149
|
+
`session "${sessionId}" lock marker has sync-conflict copies (${conflicts.join(', ')}) — ` +
|
|
150
|
+
`two machines contested this session; use the xlock tool: reset then audit before resuming`,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
const marker = readMarker(sessionDir)
|
|
154
|
+
if (marker.state === 'corrupt') {
|
|
155
|
+
throw new XlockHeldError(
|
|
156
|
+
sessionId,
|
|
157
|
+
`session "${sessionId}" lock marker is corrupt (fail-safe) — use the xlock tool (action "reset") to clear it`,
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
if (marker.state === 'ok' && marker.data.state === 'held' && marker.data.machineId !== identity.uuid) {
|
|
161
|
+
throw new XlockHeldError(
|
|
162
|
+
sessionId,
|
|
163
|
+
`session "${sessionId}" is locked on host "${marker.data.host || 'unknown'}" ` +
|
|
164
|
+
`(sticky lock marker; the owning machine crashed or still runs). ` +
|
|
165
|
+
`To take over: confirm the owning machine has stopped writing, then run the xlock tool ` +
|
|
166
|
+
`(action "reset", session "${sessionId}") — or delete the marker file directly`,
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
if (marker.state === 'ok' && marker.data.state === 'held') return // 本机已持
|
|
170
|
+
if (marker.state === 'missing') {
|
|
171
|
+
if (createHeldMarker(sessionDir, identity, sessionId)) return
|
|
172
|
+
// wx 输了:另一进程/同步刚创建 → 重读再判(绝不盲写覆盖)。
|
|
173
|
+
return acquireMarker(sessionDir, identity, sessionId)
|
|
174
|
+
}
|
|
175
|
+
// released(任意机)→ 原子翻转 held。
|
|
176
|
+
writeMarker(sessionDir, {
|
|
177
|
+
v: 1,
|
|
178
|
+
machineId: identity.uuid,
|
|
179
|
+
host: identity.host,
|
|
180
|
+
pid: process.pid,
|
|
181
|
+
sessionId,
|
|
182
|
+
state: 'held',
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 释放锁:held → released(原子改写,不删除)。
|
|
188
|
+
* 任何失败都吞掉(close 语义优先:绝不因标记写失败破坏 close)。
|
|
189
|
+
* @returns {boolean} 是否成功落为 released
|
|
190
|
+
*/
|
|
191
|
+
export function releaseMarker(sessionDir, identity) {
|
|
192
|
+
try {
|
|
193
|
+
const marker = readMarker(sessionDir)
|
|
194
|
+
if (marker.state !== 'ok') return marker.state === 'missing'
|
|
195
|
+
if (marker.data.state === 'released') return true
|
|
196
|
+
// 异机持有 → 不翻转:本进程从未持有该标记,盲翻会让异机的锁失明
|
|
197
|
+
// (跨机陈旧 close 的防护——identity 缺省时保持旧行为,供测试夹具使用)。
|
|
198
|
+
if (identity && marker.data.machineId && marker.data.machineId !== identity.uuid) return false
|
|
199
|
+
writeMarker(sessionDir, { ...marker.data, state: 'released', pid: 0 })
|
|
200
|
+
return true
|
|
201
|
+
} catch {
|
|
202
|
+
return false
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 便捷判断(供 status/audit):标记是否正被异机持有。
|
|
208
|
+
* @returns {{foreign:boolean, holder?:{host?:string,machineId?:string}, conflicts:string[], corrupt:boolean}}
|
|
209
|
+
*/
|
|
210
|
+
export function markerStatus(sessionDir, identity) {
|
|
211
|
+
const conflicts = listMarkerConflicts(sessionDir)
|
|
212
|
+
const marker = readMarker(sessionDir)
|
|
213
|
+
if (marker.state === 'missing') {
|
|
214
|
+
return { foreign: conflicts.length > 0, conflicts, corrupt: false }
|
|
215
|
+
}
|
|
216
|
+
if (marker.state === 'corrupt') {
|
|
217
|
+
return { foreign: true, conflicts, corrupt: true }
|
|
218
|
+
}
|
|
219
|
+
const held = marker.data.state === 'held'
|
|
220
|
+
const foreign = held && marker.data.machineId !== identity.uuid
|
|
221
|
+
return {
|
|
222
|
+
foreign,
|
|
223
|
+
conflicts,
|
|
224
|
+
corrupt: false,
|
|
225
|
+
state: marker.data.state,
|
|
226
|
+
holder: { host: marker.data.host, machineId: marker.data.machineId, pid: marker.data.pid },
|
|
227
|
+
heldByLocal: held && !foreign,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 测试/CLI 用:标记文件是否存在。 */
|
|
232
|
+
export function markerExists(sessionDir) {
|
|
233
|
+
return existsSync(markerPath(sessionDir))
|
|
234
|
+
}
|
package/core/origin.mjs
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 会话创建归属判定。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不能复用 `.dsh-xlock.json`(粘锁标记):
|
|
5
|
+
* 标记记的是【当前/最后持有者】—— acquireMarker 在 released 态会把
|
|
6
|
+
* machineId/host/pid 整组改写成自己(core/marker.mjs)。一台机器打开
|
|
7
|
+
* 别人创建的会话,标记就变成它,归属从此不可考。
|
|
8
|
+
*
|
|
9
|
+
* 三层证据(强 → 弱):
|
|
10
|
+
* L1 创建记录(权威):`<session-dir>/.dsh-xlock-origin.json`,只在
|
|
11
|
+
* sessionPersistence.create() 那一刻由创建方写入,wx 独占、只写一次,
|
|
12
|
+
* 此后任何机器都不改写。文件名不以 `.jsonl`/`.jsonl.zstd` 结尾,
|
|
13
|
+
* 不会被 dsh-session-persistence-jsonl 的 legacy-layout 检测误判。
|
|
14
|
+
* L2 目录桶推断(历史回填):DSH 的会话桶名 = 创建时 cwd 的 projectKey()。
|
|
15
|
+
* 桶名不可逆,但可正向算:拿 registry 里登记过的 cwd 逐个算 projectKey()
|
|
16
|
+
* 比对桶名,命中即得机器。这样 feature 上线前的历史会话也能判。
|
|
17
|
+
* L3 未知:都没有就报 unknown,绝不猜。
|
|
18
|
+
*
|
|
19
|
+
* 同步面注意:origin 记录在会话目录内(跨机同步),registry 在包目录内
|
|
20
|
+
* (同样跨机共享),两边都可能出现 Syncthing 冲突副本 —— 都要处理。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, writeSync } from 'node:fs'
|
|
24
|
+
import { basename, dirname, join } from 'node:path'
|
|
25
|
+
import { readJsonSafe } from './util.mjs'
|
|
26
|
+
|
|
27
|
+
/** 创建记录的固定文件名(只写一次,永不改写)。 */
|
|
28
|
+
export const ORIGIN_NAME = '.dsh-xlock-origin.json'
|
|
29
|
+
|
|
30
|
+
/** 创建记录可能出现的 Syncthing 冲突副本。 */
|
|
31
|
+
const ORIGIN_CONFLICT_RE = /^\.dsh-xlock-origin\.json\.sync-conflict-\d{8}-\d{6}-[A-Za-z0-9]+\.\w+$/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 复刻 dsh-session-persistence-jsonl 的 projectKey():
|
|
35
|
+
* `/`、`\`、`:` 折叠成一个 `-`,保留 `[A-Za-z0-9._-]`,其余转 `~XXXX`,
|
|
36
|
+
* 结果 `--${readable.slice(0,251)}--`。桶名由它生成,所以正向比对必须逐字一致。
|
|
37
|
+
* @param {string} cwd
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
export function projectKey(cwd) {
|
|
41
|
+
const text = String(cwd)
|
|
42
|
+
if (text.length === 0) throw new Error('cannot encode an empty project path')
|
|
43
|
+
let readable = ''
|
|
44
|
+
let separatorRun = false
|
|
45
|
+
for (let i = 0; i < text.length; i++) {
|
|
46
|
+
const code = text.charCodeAt(i)
|
|
47
|
+
const ch = String.fromCharCode(code)
|
|
48
|
+
if (ch === '/' || ch === '\\' || ch === ':') {
|
|
49
|
+
if (!separatorRun) readable += '-'
|
|
50
|
+
separatorRun = true
|
|
51
|
+
} else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
|
|
52
|
+
readable += ch
|
|
53
|
+
separatorRun = false
|
|
54
|
+
} else {
|
|
55
|
+
readable += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
|
|
56
|
+
separatorRun = false
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return `--${(readable.replace(/^-+/, '') || 'root').slice(0, 251)}--`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 创建记录文件路径。
|
|
64
|
+
* @param {string} sessionDir
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export function originPath(sessionDir) {
|
|
68
|
+
return join(sessionDir, ORIGIN_NAME)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 读取创建记录。
|
|
73
|
+
* @param {string} sessionDir
|
|
74
|
+
* @returns {{state:'missing'}|{state:'corrupt'}|{state:'ok',data:any}}
|
|
75
|
+
*/
|
|
76
|
+
export function readOrigin(sessionDir) {
|
|
77
|
+
const path = originPath(sessionDir)
|
|
78
|
+
if (!existsSync(path)) return { state: 'missing' }
|
|
79
|
+
const data = readJsonSafe(path, undefined)
|
|
80
|
+
if (!data || typeof data !== 'object' || typeof data.machineId !== 'string' || data.machineId.length < 8) {
|
|
81
|
+
return { state: 'corrupt' }
|
|
82
|
+
}
|
|
83
|
+
return { state: 'ok', data }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 列出创建记录的冲突副本(有副本说明两台机器都写过,仍然只是"痕迹"不算争抢)。
|
|
88
|
+
* @param {string} sessionDir
|
|
89
|
+
* @returns {string[]}
|
|
90
|
+
*/
|
|
91
|
+
export function listOriginConflicts(sessionDir) {
|
|
92
|
+
let names
|
|
93
|
+
try {
|
|
94
|
+
names = readdirSync(sessionDir)
|
|
95
|
+
} catch {
|
|
96
|
+
return []
|
|
97
|
+
}
|
|
98
|
+
return names.filter((name) => ORIGIN_CONFLICT_RE.test(name))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 写创建记录(wx 独占,只写一次)。已存在 / 目录未物化 → 返回 false。
|
|
103
|
+
* @param {string} sessionDir
|
|
104
|
+
* @param {{uuid:string,host:string}} identity
|
|
105
|
+
* @param {string} sessionId
|
|
106
|
+
* @param {string|undefined} cwd
|
|
107
|
+
* @returns {boolean} 是否由本次调用写入
|
|
108
|
+
*/
|
|
109
|
+
export function writeOriginOnce(sessionDir, identity, sessionId, cwd) {
|
|
110
|
+
const path = originPath(sessionDir)
|
|
111
|
+
const payload = JSON.stringify(
|
|
112
|
+
{
|
|
113
|
+
v: 1,
|
|
114
|
+
machineId: identity.uuid,
|
|
115
|
+
host: identity.host,
|
|
116
|
+
sessionId,
|
|
117
|
+
cwd: typeof cwd === 'string' ? cwd : null,
|
|
118
|
+
createdAt: new Date().toISOString(),
|
|
119
|
+
},
|
|
120
|
+
null,
|
|
121
|
+
2,
|
|
122
|
+
)
|
|
123
|
+
let fd
|
|
124
|
+
try {
|
|
125
|
+
fd = openSync(path, 'wx')
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error?.code === 'EEXIST') return false
|
|
128
|
+
if (error?.code === 'ENOENT') {
|
|
129
|
+
try {
|
|
130
|
+
mkdirSync(sessionDir, { recursive: true })
|
|
131
|
+
fd = openSync(path, 'wx')
|
|
132
|
+
} catch {
|
|
133
|
+
return false
|
|
134
|
+
}
|
|
135
|
+
} else {
|
|
136
|
+
return false
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
writeSync(fd, `${payload}\n`)
|
|
141
|
+
fsyncSync(fd)
|
|
142
|
+
return true
|
|
143
|
+
} catch {
|
|
144
|
+
return false
|
|
145
|
+
} finally {
|
|
146
|
+
try {
|
|
147
|
+
closeSync(fd)
|
|
148
|
+
} catch {
|
|
149
|
+
/* 已关闭 */
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 由桶名反查机器:拿 registry 里每个已知机器的 cwds 逐个算 projectKey 比对。
|
|
156
|
+
* @param {string} bucket 例如 "--D-_Dev-ws-dsh--"
|
|
157
|
+
* @param {object} registry loadMachines() 结果
|
|
158
|
+
* @returns {{machineId:string, host:string}|undefined}
|
|
159
|
+
*/
|
|
160
|
+
export function machineByBucket(bucket, registry) {
|
|
161
|
+
const machines = registry?.machines || {}
|
|
162
|
+
for (const [machineId, entry] of Object.entries(machines)) {
|
|
163
|
+
const cwds = Array.isArray(entry?.cwds) ? entry.cwds : []
|
|
164
|
+
for (const cwd of cwds) {
|
|
165
|
+
if (typeof cwd !== 'string' || cwd === '') continue
|
|
166
|
+
let key
|
|
167
|
+
try {
|
|
168
|
+
key = projectKey(cwd)
|
|
169
|
+
} catch {
|
|
170
|
+
continue
|
|
171
|
+
}
|
|
172
|
+
if (key === bucket) return { machineId, host: typeof entry.host === 'string' ? entry.host : machineId }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return undefined
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* registry 里查机器显示名。
|
|
180
|
+
* @param {string|undefined} machineId
|
|
181
|
+
* @param {object} registry
|
|
182
|
+
* @returns {{host:string, known:boolean}}
|
|
183
|
+
*/
|
|
184
|
+
export function machineLabel(machineId, registry) {
|
|
185
|
+
if (!machineId) return { host: '(unknown)', known: false }
|
|
186
|
+
const entry = registry?.machines?.[machineId]
|
|
187
|
+
if (entry && typeof entry.host === 'string' && entry.host !== '') return { host: entry.host, known: true }
|
|
188
|
+
return { host: machineId, known: false }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 判一个会话目录的创建归属(三层证据)。
|
|
193
|
+
* @param {string} sessionDir 会话目录
|
|
194
|
+
* @param {{identity:{uuid:string,host:string}, registry?:object, bucket?:string}} env
|
|
195
|
+
* bucket = 会话桶目录名;不给则从 sessionDir 的父目录名取
|
|
196
|
+
* @returns {{
|
|
197
|
+
* machineId: string|undefined,
|
|
198
|
+
* host: string,
|
|
199
|
+
* known: boolean,
|
|
200
|
+
* source: 'record'|'bucket'|'unknown',
|
|
201
|
+
* local: boolean,
|
|
202
|
+
* conflicts: number,
|
|
203
|
+
* cwd: string|undefined,
|
|
204
|
+
* }}
|
|
205
|
+
*/
|
|
206
|
+
export function inferOrigin(sessionDir, env = {}) {
|
|
207
|
+
const registry = env.registry || {}
|
|
208
|
+
const identity = env.identity
|
|
209
|
+
const conflicts = listOriginConflicts(sessionDir).length
|
|
210
|
+
|
|
211
|
+
const record = readOrigin(sessionDir)
|
|
212
|
+
if (record.state === 'ok') {
|
|
213
|
+
const machineId = record.data.machineId
|
|
214
|
+
const label = machineLabel(machineId, registry)
|
|
215
|
+
// 记录自带 host 作为兜底(另一台机器还没把 registry 同步过来时也能显示名字)
|
|
216
|
+
const host = label.known ? label.host : typeof record.data.host === 'string' ? record.data.host : machineId
|
|
217
|
+
return {
|
|
218
|
+
machineId,
|
|
219
|
+
host,
|
|
220
|
+
known: label.known || typeof record.data.host === 'string',
|
|
221
|
+
source: 'record',
|
|
222
|
+
local: Boolean(identity && identity.uuid === machineId),
|
|
223
|
+
conflicts,
|
|
224
|
+
cwd: typeof record.data.cwd === 'string' ? record.data.cwd : undefined,
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const bucket =
|
|
229
|
+
typeof env.bucket === 'string' && env.bucket !== ''
|
|
230
|
+
? env.bucket
|
|
231
|
+
: basename(dirname(sessionDir)) // 会话目录的父目录就是桶名
|
|
232
|
+
if (bucket && bucket !== '.' && bucket !== '') {
|
|
233
|
+
const hit = machineByBucket(bucket, registry)
|
|
234
|
+
if (hit) {
|
|
235
|
+
const label = machineLabel(hit.machineId, registry)
|
|
236
|
+
return {
|
|
237
|
+
machineId: hit.machineId,
|
|
238
|
+
host: label.host,
|
|
239
|
+
known: label.known,
|
|
240
|
+
source: 'bucket',
|
|
241
|
+
local: Boolean(identity && identity.uuid === hit.machineId),
|
|
242
|
+
conflicts,
|
|
243
|
+
cwd: undefined,
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return {
|
|
249
|
+
machineId: undefined,
|
|
250
|
+
host: '(unknown)',
|
|
251
|
+
known: false,
|
|
252
|
+
source: 'unknown',
|
|
253
|
+
local: false,
|
|
254
|
+
conflicts,
|
|
255
|
+
cwd: undefined,
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* 归属来源的中文标签(报告用)。
|
|
261
|
+
* @param {'record'|'bucket'|'unknown'} source
|
|
262
|
+
*/
|
|
263
|
+
export function originSourceLabel(source) {
|
|
264
|
+
if (source === 'record') return '创建记录'
|
|
265
|
+
if (source === 'bucket') return '目录桶推断'
|
|
266
|
+
return '未知'
|
|
267
|
+
}
|