dsh-lpipe-memory 0.0.0-stage → 0.1.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/src/writer.mjs ADDED
@@ -0,0 +1,155 @@
1
+ // 写入:一条事件一行,追加进当天的帧文件;同时维护偏移表、meta 与全局游标。
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
3
+ import { dirname } from 'node:path'
4
+
5
+ import { GENESIS, seal } from './chain.mjs'
6
+ import { FORMAT_VERSION } from './compact.mjs'
7
+ import { dayOf } from './day.mjs'
8
+ import { compressFrame, FRAME_BYTES } from './frames.mjs'
9
+ import { dayFile, framesFile, idxFile, memoryRoot, metaFile, sessionDir, stateFile } from './paths.mjs'
10
+
11
+ function readJson(file, fallback) {
12
+ try {
13
+ return JSON.parse(readFileSync(file, 'utf8'))
14
+ } catch {
15
+ return fallback
16
+ }
17
+ }
18
+
19
+ function readLines(file) {
20
+ if (!existsSync(file)) return []
21
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean)
22
+ }
23
+
24
+ function writeJson(file, value) {
25
+ mkdirSync(dirname(file), { recursive: true })
26
+ writeFileSync(file, JSON.stringify(value, null, 2) + '\n', 'utf8')
27
+ }
28
+
29
+ /** 一天的写入端:攒够一帧就压缩追加,行偏移顺手记进 .idx。 */
30
+ class DaySink {
31
+ constructor(root, sessionId, day) {
32
+ this.file = dayFile(root, sessionId, day)
33
+ this.framesPath = framesFile(root, sessionId, day)
34
+ this.idxPath = idxFile(root, sessionId, day)
35
+ mkdirSync(dirname(this.file), { recursive: true })
36
+ this.position = existsSync(this.file) ? statSync(this.file).size : 0
37
+ const lastFrame = readLines(this.framesPath).pop()
38
+ this.frameNo = lastFrame ? JSON.parse(lastFrame).n + 1 : 0
39
+ this.pending = []
40
+ this.pendingRows = []
41
+ this.pendingBytes = 0
42
+ }
43
+
44
+ push(seq, line) {
45
+ const offset = this.pendingBytes
46
+ this.pending.push(line + '\n')
47
+ this.pendingRows.push({ s: seq, f: this.frameNo, o: offset, l: Buffer.byteLength(line) })
48
+ this.pendingBytes += Buffer.byteLength(line) + 1
49
+ if (this.pendingBytes >= FRAME_BYTES) this.flush()
50
+ }
51
+
52
+ flush() {
53
+ if (this.pending.length === 0) return
54
+ const packed = compressFrame(this.pending.join(''))
55
+ appendFileSync(this.file, packed)
56
+ appendFileSync(this.framesPath, JSON.stringify({ n: this.frameNo, at: this.position, len: packed.length }) + '\n')
57
+ appendFileSync(this.idxPath, this.pendingRows.map((entry) => JSON.stringify(entry)).join('\n') + '\n')
58
+ this.position += packed.length
59
+ this.frameNo += 1
60
+ this.pending = []
61
+ this.pendingRows = []
62
+ this.pendingBytes = 0
63
+ }
64
+ }
65
+
66
+ export class MemoryWriter {
67
+ constructor({ root = memoryRoot(), now = () => Date.now() } = {}) {
68
+ this.root = root
69
+ this.now = now
70
+ this.sinks = new Map()
71
+ this.meta = new Map()
72
+ this.state = readJson(stateFile(root), { version: FORMAT_VERSION, seq: -1, hash: GENESIS, day: null, sessions: {} })
73
+ }
74
+
75
+ /** 该会话已经写到的事件序号,用来做幂等去重。 */
76
+ lastEventSeq(sessionId) {
77
+ return this.state.sessions[sessionId]?.lastEventSeq ?? -1
78
+ }
79
+
80
+ /**
81
+ * 写入一条投影好的记录。
82
+ * `eventSeq` 是会话内的事件序号:同一条重复投递会被直接跳过,返回 null。
83
+ */
84
+ append({ sessionId, eventSeq, at, kind, turn = null, step = null, payload = {} }) {
85
+ if (!sessionId) throw new TypeError('append 需要 sessionId')
86
+ if (Number.isFinite(eventSeq) && eventSeq <= this.lastEventSeq(sessionId)) return null
87
+ const when = Number.isFinite(at) ? at : this.now()
88
+ const day = dayOf(when)
89
+ const key = `${sessionId}|${day}`
90
+ if (!this.sinks.has(key)) this.sinks.set(key, new DaySink(this.root, sessionId, day))
91
+
92
+ const seq = this.state.seq + 1
93
+ const row = seal({ seq, day, at: when, session: sessionId, turn, step, kind, ...payload }, this.state.hash)
94
+ this.sinks.get(key).push(seq, JSON.stringify(row))
95
+
96
+ const session = this.state.sessions[sessionId] ?? { firstSeq: seq, lastSeq: seq, rows: 0, lastAt: when }
97
+ session.firstSeq = Math.min(session.firstSeq ?? seq, seq)
98
+ session.lastSeq = seq
99
+ session.rows = (session.rows ?? 0) + 1
100
+ session.lastAt = when
101
+ if (Number.isFinite(eventSeq)) session.lastEventSeq = eventSeq
102
+ this.state.sessions[sessionId] = session
103
+ this.state.seq = seq
104
+ this.state.hash = row.hash
105
+ this.state.day = day
106
+ this.#noteDay(sessionId, day, when)
107
+ return row
108
+ }
109
+
110
+ #noteDay(sessionId, day, at) {
111
+ const meta = this.meta.get(sessionId) ?? readJson(metaFile(this.root, sessionId), null) ?? {
112
+ id: sessionId,
113
+ title: '',
114
+ startedAt: at,
115
+ lastAt: at,
116
+ rows: 0,
117
+ days: [],
118
+ }
119
+ const entry = meta.days.find((item) => item.day === day)
120
+ if (entry) entry.rows += 1
121
+ else meta.days.push({ day, rows: 1 })
122
+ meta.rows += 1
123
+ meta.startedAt = Math.min(meta.startedAt ?? at, at)
124
+ meta.lastAt = Math.max(meta.lastAt ?? at, at)
125
+ this.meta.set(sessionId, meta)
126
+ }
127
+
128
+ /** 会话标题由宿主另外告知,写进 meta.json 当目录用。 */
129
+ setTitle(sessionId, title) {
130
+ if (!sessionId || !title) return
131
+ const meta = this.meta.get(sessionId) ?? readJson(metaFile(this.root, sessionId), null)
132
+ if (!meta) return
133
+ meta.title = String(title)
134
+ this.meta.set(sessionId, meta)
135
+ }
136
+
137
+ /** 把攒着的行压成帧,并落 state / meta。 */
138
+ flush() {
139
+ for (const sink of this.sinks.values()) sink.flush()
140
+ writeJson(stateFile(this.root), this.state)
141
+ for (const [sessionId, meta] of this.meta) {
142
+ mkdirSync(sessionDir(this.root, sessionId), { recursive: true })
143
+ writeJson(metaFile(this.root, sessionId), meta)
144
+ }
145
+ }
146
+
147
+ close() {
148
+ this.flush()
149
+ this.sinks.clear()
150
+ }
151
+
152
+ snapshot() {
153
+ return { seq: this.state.seq, hash: this.state.hash, day: this.state.day, sessions: { ...this.state.sessions } }
154
+ }
155
+ }