dsh-config-sync-plugin 0.3.66 → 0.3.68

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,322 @@
1
+ // 会话日志(session.v*.jsonl.zstd)底层读写库
2
+ //
3
+ // 背景:这份文件是 append-only 的**多帧 zstd**。首帧是 header(一行 JSON),之后是事件行,
4
+ // 每行带连续 seq。实测 11MB 的日志里 6884 帧装了 10776 个事件 —— 写入侧会把多个事件压进同一帧,
5
+ // 所以「一帧一个事件」的假设不成立,读正文必须逐行解析。
6
+ //
7
+ // 切帧办法:
8
+ // A) 二分逐帧试解 —— 1 万帧 × 24 次试解,10MB 要 11 秒,太慢,不能进同步热路径。
9
+ // B) 扫描帧魔数 28 B5 2F FD 当候选,逐候选验证「切出来能解且解完是完整行」。
10
+ // 随机数据命中魔数概率约 1/2^32,12MB 期望 0.003 次,误判由验证兜掉。
11
+ // 每帧只解一次 = O(n) 原生解压。本库用 B:12MB 全解析约 640ms。
12
+ //
13
+ // 判定原则(append-only 的硬性质):
14
+ // 同源两份日志去掉首帧(首帧 cwd 会被归一成占位符,字节不同)后,短的那份必然是长的那份的
15
+ // **字节前缀**。于是只需一次 memcmp:
16
+ // identical / 一方是另一方前缀 → 同源,保留更长的那份,零风险
17
+ // 互不为前缀 → 可能分叉(也可能只是帧边界重压过),再用 seq 集合判断:
18
+ // 一方 seq 是另一方子集 → 仍是同源,取超集
19
+ // 两边各有对方没有的 seq → 真分叉,按 seq 求并集
20
+ //
21
+ // 导出的主要函数见各段注释。
22
+
23
+ import fs from 'node:fs';
24
+ import zlib from 'node:zlib';
25
+
26
+ const ZSTD_MAGIC = [0x28, 0xb5, 0x2f, 0xfd];
27
+
28
+ export function isFrameMagic(buf, i) {
29
+ return (
30
+ i + 4 <= buf.length &&
31
+ buf[i] === ZSTD_MAGIC[0] &&
32
+ buf[i + 1] === ZSTD_MAGIC[1] &&
33
+ buf[i + 2] === ZSTD_MAGIC[2] &&
34
+ buf[i + 3] === ZSTD_MAGIC[3]
35
+ );
36
+ }
37
+
38
+ /**
39
+ * 找第一帧(header)的结束偏移。
40
+ * 注意:不能靠「zstdDecompressSync(buf) 成功」来判断「整份只有一帧」—— Node 的
41
+ * zstdDecompressSync 遇到多帧缓冲会忽略后续帧并返回第一帧内容,据此返回 buf.length
42
+ * 会把 rest 判成空。所以这里只做「下一个魔数位置能切出完整行」的精确判定,判不出来就 -1。
43
+ */
44
+ export function firstFrameEnd(buf) {
45
+ if (!isFrameMagic(buf, 0)) return -1;
46
+ for (let i = 1; i + 4 <= buf.length; i++) {
47
+ if (!isFrameMagic(buf, i)) continue;
48
+ for (const plus of [0, 4, 8]) {
49
+ const e = i + plus;
50
+ if (e > buf.length) continue;
51
+ try {
52
+ const out = zlib.zstdDecompressSync(buf.subarray(0, e));
53
+ if (out.length > 0 && out[out.length - 1] === 0x0a) return e;
54
+ } catch {
55
+ /* 假帧头或 checksum 未计入,试下一个偏移 */
56
+ }
57
+ }
58
+ }
59
+ return -1;
60
+ }
61
+
62
+ /** 扫描候选帧头并验证,返回真实帧边界 */
63
+ export function splitFrames(buf) {
64
+ if (buf.length === 0) return [];
65
+ if (!isFrameMagic(buf, 0)) throw new Error('not a zstd frame stream (bad magic at byte 0)');
66
+
67
+ const cands = [0];
68
+ for (let i = 1; i + 4 <= buf.length; i++) {
69
+ if (buf[i] === 0x28 && buf[i + 1] === 0xb5 && buf[i + 2] === 0x2f && buf[i + 3] === 0xfd) cands.push(i);
70
+ }
71
+ cands.push(buf.length);
72
+
73
+ const frames = [];
74
+ let start = 0;
75
+ for (let k = 1; k < cands.length; k++) {
76
+ const end = cands[k];
77
+ if (end <= start) continue;
78
+ const slice = buf.subarray(start, end);
79
+ let ok = false;
80
+ let decoded = null;
81
+ try {
82
+ decoded = zlib.zstdDecompressSync(slice);
83
+ ok = decoded.length > 0 && decoded[decoded.length - 1] === 0x0a;
84
+ } catch {
85
+ ok = false;
86
+ }
87
+ const isLast = k === cands.length - 1;
88
+ if (ok) {
89
+ frames.push({ start, end, data: slice, decoded });
90
+ start = end;
91
+ continue;
92
+ }
93
+ if (isLast) {
94
+ // 末帧:可能带 4 字节 checksum 未计入,也可能就是尾巴不完整
95
+ let fixed = null;
96
+ for (const plus of [4, 8]) {
97
+ const e = end + plus;
98
+ if (e > buf.length) continue;
99
+ try {
100
+ const out = zlib.zstdDecompressSync(buf.subarray(start, e));
101
+ if (out.length > 0) {
102
+ fixed = { start, end: e, data: buf.subarray(start, e), decoded: out };
103
+ break;
104
+ }
105
+ } catch {
106
+ /* 继续 */
107
+ }
108
+ }
109
+ if (fixed) {
110
+ frames.push(fixed);
111
+ start = fixed.end;
112
+ } else if (decoded !== null) {
113
+ frames.push({ start, end, data: slice, decoded });
114
+ start = end;
115
+ } else {
116
+ frames.push({ start, end, data: slice, decoded: null });
117
+ start = end;
118
+ }
119
+ }
120
+ // 非末帧且解码失败:假帧头,继续累积到下一个候选
121
+ }
122
+ if (start < buf.length) {
123
+ let decoded = null;
124
+ try {
125
+ decoded = zlib.zstdDecompressSync(buf.subarray(start));
126
+ } catch {
127
+ decoded = null;
128
+ }
129
+ frames.push({ start, end: buf.length, data: buf.subarray(start), decoded });
130
+ }
131
+ return frames;
132
+ }
133
+
134
+ function frameText(frame) {
135
+ if (frame.decoded) return frame.decoded.toString('utf8');
136
+ return zlib.zstdDecompressSync(frame.data).toString('utf8');
137
+ }
138
+
139
+ /**
140
+ * 解析整份日志。
141
+ * 返回 { header, rows:[{ seq, text, frameIndex }], frames }
142
+ * rows[].text 是该事件的原始 JSON 行文本(merge 时逐行复用,保证内容不变)
143
+ */
144
+ export function parseLog(buf) {
145
+ const frames = splitFrames(buf);
146
+ if (frames.length === 0) return { header: null, rows: [], frames };
147
+
148
+ let header = null;
149
+ let rowStart = 0;
150
+ try {
151
+ const first = frameText(frames[0]);
152
+ const line = first.split('\n').find((l) => l.trim() !== '');
153
+ if (line) {
154
+ header = JSON.parse(line);
155
+ rowStart = 1;
156
+ }
157
+ } catch {
158
+ header = null;
159
+ rowStart = 0;
160
+ }
161
+
162
+ const rows = [];
163
+ for (let i = rowStart; i < frames.length; i++) {
164
+ let text = null;
165
+ try {
166
+ text = frameText(frames[i]);
167
+ } catch {
168
+ text = null;
169
+ }
170
+ if (text === null) {
171
+ rows.push({ seq: null, text: null, frameIndex: i });
172
+ continue;
173
+ }
174
+ for (const line of text.split('\n')) {
175
+ if (!line.trim()) continue;
176
+ let seq = null;
177
+ try {
178
+ const obj = JSON.parse(line);
179
+ if (typeof obj.seq === 'number') seq = obj.seq;
180
+ } catch {
181
+ seq = null;
182
+ }
183
+ rows.push({ seq, text: line, frameIndex: i });
184
+ }
185
+ }
186
+ return { header, rows, frames, headerText: header ? JSON.stringify(header) : null };
187
+ }
188
+
189
+ export function loadLog(path) {
190
+ const buf = fs.readFileSync(path);
191
+ const log = parseLog(buf);
192
+ log.path = path;
193
+ log.bytes = buf.length;
194
+ log.buf = buf;
195
+ return log;
196
+ }
197
+
198
+ /** 去掉首帧后的字节(跨机同源字节前缀判定用)。切不出首帧时返回 null。 */
199
+ export function restAfterHeader(buf) {
200
+ const e = firstFrameEnd(buf);
201
+ if (e <= 0) return null;
202
+ if (e >= buf.length) return Buffer.alloc(0);
203
+ return buf.subarray(e);
204
+ }
205
+
206
+ export function findGaps(rows) {
207
+ const gaps = [];
208
+ const seqs = [];
209
+ for (const r of rows) if (typeof r.seq === 'number') seqs.push(r.seq);
210
+ for (let i = 1; i < seqs.length; i++) {
211
+ if (seqs[i] !== seqs[i - 1] + 1) gaps.push({ at: i, expected: seqs[i - 1] + 1, got: seqs[i] });
212
+ }
213
+ return { gaps, seqs, first: seqs.length ? seqs[0] : null, tail: seqs.length ? seqs[seqs.length - 1] : null };
214
+ }
215
+
216
+ export function seqTailOf(log) {
217
+ for (let i = log.rows.length - 1; i >= 0; i--) {
218
+ if (typeof log.rows[i].seq === 'number') return log.rows[i].seq;
219
+ }
220
+ return null;
221
+ }
222
+
223
+ /** 分块 memcmp。返回 { relation, divergeAt, aLen, bLen } */
224
+ export function compareRaw(a, b) {
225
+ const n = Math.min(a.length, b.length);
226
+ const CHUNK = 1 << 16;
227
+ let i = 0;
228
+ while (i < n) {
229
+ const step = Math.min(CHUNK, n - i);
230
+ if (a.compare(b, i, i + step, i, i + step) !== 0) {
231
+ // 二分找第一个不同字节
232
+ let lo = i;
233
+ let hi = i + step - 1;
234
+ while (lo < hi) {
235
+ const mid = (lo + hi) >> 1;
236
+ if (a.compare(b, i, mid + 1, i, mid + 1) === 0) lo = mid + 1;
237
+ else hi = mid;
238
+ }
239
+ return { relation: 'fork', divergeAt: lo, aLen: a.length, bLen: b.length };
240
+ }
241
+ i += step;
242
+ }
243
+ if (a.length === b.length) return { relation: 'identical', aLen: a.length, bLen: b.length };
244
+ if (a.length < b.length) return { relation: 'a_is_prefix_of_b', aLen: a.length, bLen: b.length };
245
+ return { relation: 'b_is_prefix_of_a', aLen: a.length, bLen: b.length };
246
+ }
247
+
248
+ /** seq 集合关系:'equal'|'a_superset'|'b_superset'|'both_exclusive' */
249
+ export function compareSeqs(rowsA, rowsB) {
250
+ const sa = new Set(rowsA.map((r) => r.seq).filter((s) => typeof s === 'number'));
251
+ const sb = new Set(rowsB.map((r) => r.seq).filter((s) => typeof s === 'number'));
252
+ const onlyA = [];
253
+ const onlyB = [];
254
+ for (const x of sa) if (!sb.has(x)) onlyA.push(x);
255
+ for (const x of sb) if (!sa.has(x)) onlyB.push(x);
256
+ let relation;
257
+ if (onlyA.length === 0 && onlyB.length === 0) relation = 'equal';
258
+ else if (onlyB.length === 0) relation = 'a_superset';
259
+ else if (onlyA.length === 0) relation = 'b_superset';
260
+ else relation = 'both_exclusive';
261
+ return { relation, onlyA, onlyB, countA: sa.size, countB: sb.size };
262
+ }
263
+
264
+ /**
265
+ * 按 seq 求并集,重建一份可读日志。
266
+ *
267
+ * 关键:**逐事件重建**,不复用整帧。因为一帧可能装多个事件,若把「含 48,49,50 的帧」和
268
+ * 「含 50 的帧」都拼进去,输出里 seq 50 就出现两次,DSH 读到就是 expected 51 got 50。
269
+ * 所以这里把每个事件的原始行文本单独压成一帧,保证 seq 严格单调 +1。
270
+ */
271
+ export function mergeLogs(logA, logB, preferredHeader) {
272
+ const bySeq = new Map();
273
+ const conflicts = [];
274
+ let anon = 0;
275
+
276
+ const add = (log, tag) => {
277
+ for (const r of log.rows) {
278
+ if (r.text === null) continue;
279
+ if (typeof r.seq !== 'number') {
280
+ // 没有 seq 的行无法排序对账,只在没有同 seq 冲突时按出现顺序追加
281
+ bySeq.set(`anon${anon++}`, { key: null, text: r.text, tag });
282
+ continue;
283
+ }
284
+ const cur = bySeq.get(r.seq);
285
+ if (!cur) {
286
+ bySeq.set(r.seq, { key: r.seq, text: r.text, tag });
287
+ } else if (cur.text !== r.text) {
288
+ conflicts.push(r.seq);
289
+ }
290
+ }
291
+ };
292
+ add(logA, 'a');
293
+ add(logB, 'b');
294
+
295
+ const keys = [...bySeq.keys()];
296
+ const numeric = keys.filter((k) => typeof k === 'number').sort((x, y) => x - y);
297
+ const anonKeys = keys.filter((k) => typeof k !== 'number');
298
+
299
+ const holes = [];
300
+ for (let i = 1; i < numeric.length; i++) {
301
+ if (numeric[i] !== numeric[i - 1] + 1) {
302
+ holes.push({ after: numeric[i - 1], next: numeric[i], missing: numeric[i] - numeric[i - 1] - 1 });
303
+ }
304
+ }
305
+
306
+ const headerText = preferredHeader || (logA.header ? JSON.stringify(logA.header) : logB.header ? JSON.stringify(logB.header) : null);
307
+ const parts = [];
308
+ if (headerText) parts.push(zlib.zstdCompressSync(Buffer.from(headerText + '\n', 'utf8')));
309
+ for (const k of numeric) parts.push(zlib.zstdCompressSync(Buffer.from(bySeq.get(k).text + '\n', 'utf8')));
310
+ for (const k of anonKeys) parts.push(zlib.zstdCompressSync(Buffer.from(bySeq.get(k).text + '\n', 'utf8')));
311
+
312
+ return {
313
+ buffer: Buffer.concat(parts),
314
+ rows: numeric.length + anonKeys.length,
315
+ seqFirst: numeric.length ? numeric[0] : null,
316
+ seqTail: numeric.length ? numeric[numeric.length - 1] : null,
317
+ holes,
318
+ conflicts,
319
+ fromA: [...bySeq.values()].filter((v) => v.tag === 'a').length,
320
+ fromB: [...bySeq.values()].filter((v) => v.tag === 'b').length,
321
+ };
322
+ }