@240xu/dsh-message-ops 0.23.0 → 0.47.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.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 写互斥(0.40.3,srv-audit D7/D8)。
3
+ *
4
+ * 两类写共用一把**按会话**的锁,再加一把按日志路径的细锁:
5
+ * - `withSessionLock(sessionId)`:commit / restore / 回收站移动 / purge 全部串行。
6
+ * 此前回收站模块完全无锁:并发双 delete 会「两次都 archive → 失败方回滚 unarchive
7
+ * 掉成功方的墓碑」并留下 ghost 条目;delete 与 revert 并发会让日志写入丢失
8
+ * (宿主持有 fd,目录被搬走)。
9
+ * - `withWriteLock(logPath)`:磁盘字节级串行(同会话不同路径理论上不该有,留着无害)。
10
+ *
11
+ * 顺序固定:先 session 后 log。所有调用方必须遵守,否则会死锁。
12
+ */
13
+ const sessionChains = new Map()
14
+ const logChains = new Map()
15
+
16
+ function chained(map, key, task) {
17
+ const prev = map.get(key) ?? Promise.resolve()
18
+ const run = prev.then(task, task)
19
+ const tail = run.then(
20
+ () => {},
21
+ () => {},
22
+ )
23
+ map.set(key, tail)
24
+ tail.finally(() => {
25
+ if (map.get(key) === tail) map.delete(key)
26
+ })
27
+ return run
28
+ }
29
+
30
+ /**
31
+ * 按会话串行(commit/restore/回收站全部写操作)。
32
+ * @param {string} sessionId 会话 id(两种拼写视为不同键;调用方传 pickSessionDir 得到的规范 id)
33
+ * @param {() => Promise<any>} task 临界区
34
+ * @returns {Promise<any>} task 的结果
35
+ */
36
+ export function withSessionLock(sessionId, task) {
37
+ return chained(sessionChains, 'sid:' + String(sessionId), task)
38
+ }
39
+
40
+ /**
41
+ * 按日志路径串行(磁盘字节写入)。
42
+ * @param {string} logPath 会话日志路径
43
+ * @param {() => Promise<any>} task 临界区
44
+ * @returns {Promise<any>} task 的结果
45
+ */
46
+ export function withWriteLock(logPath, task) {
47
+ return chained(logChains, 'log:' + String(logPath), task)
48
+ }