@deepseek-ai/dsh-session-persistence-jsonl 0.2.2-alpha.3 → 0.2.2-rc.2

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.
Files changed (41) hide show
  1. package/lib/types/catalog-migration.d.ts.map +1 -0
  2. package/lib/types/catalog-migration.js.map +1 -0
  3. package/lib/types/format.d.ts.map +1 -0
  4. package/lib/types/format.js.map +1 -0
  5. package/lib/types/generation.d.ts.map +1 -0
  6. package/lib/types/generation.js.map +1 -0
  7. package/lib/types/index.d.ts.map +1 -0
  8. package/lib/types/index.js.map +1 -0
  9. package/lib/types/lease.d.ts.map +1 -0
  10. package/lib/types/lease.js.map +1 -0
  11. package/lib/types/migration-verifier.d.ts.map +1 -0
  12. package/lib/types/migration-verifier.js.map +1 -0
  13. package/lib/types/storage.d.ts.map +1 -0
  14. package/lib/types/storage.js.map +1 -0
  15. package/lib/types/testing/generation.d.ts.map +1 -0
  16. package/lib/types/testing/generation.js.map +1 -0
  17. package/lib/types/win32.d.ts.map +1 -0
  18. package/lib/types/win32.js.map +1 -0
  19. package/lib/types/worker.d.ts.map +1 -0
  20. package/lib/types/worker.js.map +1 -0
  21. package/lib/types/zstd-private-decoder.d.ts.map +1 -0
  22. package/lib/types/zstd-private-decoder.js.map +1 -0
  23. package/lib/types/zstd-public-decoder.d.ts.map +1 -0
  24. package/lib/types/zstd-public-decoder.js.map +1 -0
  25. package/lib/types/zstd.d.ts.map +1 -0
  26. package/lib/types/zstd.js.map +1 -0
  27. package/lib/worker.cjs +300 -103
  28. package/package.json +17 -14
  29. package/src/catalog-migration.ts +92 -0
  30. package/src/format.ts +538 -0
  31. package/src/generation.ts +1059 -0
  32. package/src/index.ts +1839 -0
  33. package/src/lease.ts +135 -0
  34. package/src/migration-verifier.ts +198 -0
  35. package/src/storage.ts +571 -0
  36. package/src/testing/generation.ts +16 -0
  37. package/src/win32.ts +208 -0
  38. package/src/worker.ts +56 -0
  39. package/src/zstd-private-decoder.ts +178 -0
  40. package/src/zstd-public-decoder.ts +40 -0
  41. package/src/zstd.ts +156 -0
package/src/win32.ts ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Windows durable namespace helpers for the JSONL backend.
3
+ *
4
+ * POSIX publishes a newly-created log by creating a directory entry and then
5
+ * fsyncing the parent directory. Windows does not expose that parent-directory
6
+ * fsync contract through Node, so the Windows path uses the native durable
7
+ * namespace primitive instead: create a staging object in the target directory
8
+ * and publish it with `MoveFileExW(..., MOVEFILE_WRITE_THROUGH)` without
9
+ * replacement or cross-volume copy fallback.
10
+ *
11
+ * @module dsh-session-persistence-jsonl/win32
12
+ */
13
+
14
+ import { createHash } from 'node:crypto'
15
+ import { mkdtemp, rm, stat } from 'node:fs/promises'
16
+ import { join, parse, resolve, toNamespacedPath } from 'node:path'
17
+
18
+ type MoveFileExW = (existing: string, replacement: string, flags: number) => number
19
+ type CreateSemaphoreW = (security: null, initial: number, maximum: number, name: string) => number
20
+ type WaitForSingleObject = (handle: number, milliseconds: number) => number
21
+ type ReleaseSemaphore = (handle: number, count: number, previous: null) => number
22
+ type CloseHandle = (handle: number) => number
23
+ type GetLastError = () => number
24
+
25
+ interface Win32Bindings {
26
+ moveFileExW: MoveFileExW
27
+ createSemaphoreW: CreateSemaphoreW
28
+ waitForSingleObject: WaitForSingleObject
29
+ releaseSemaphore: ReleaseSemaphore
30
+ closeHandle: CloseHandle
31
+ getLastError: GetLastError
32
+ }
33
+
34
+ interface Win32ErrnoException extends NodeJS.ErrnoException {
35
+ win32Code: number
36
+ dest: string
37
+ }
38
+
39
+ const MOVEFILE_WRITE_THROUGH = 0x00000008
40
+ const WAIT_OBJECT_0 = 0
41
+ const WAIT_TIMEOUT = 0x00000102
42
+ const ERROR_FILE_NOT_FOUND = 2
43
+ const ERROR_PATH_NOT_FOUND = 3
44
+ const ERROR_ACCESS_DENIED = 5
45
+ const ERROR_NOT_SAME_DEVICE = 17
46
+ const ERROR_SHARING_VIOLATION = 32
47
+ const ERROR_FILE_EXISTS = 80
48
+ const ERROR_INVALID_NAME = 123
49
+ const ERROR_ALREADY_EXISTS = 183
50
+
51
+ let bindings: Win32Bindings | undefined
52
+
53
+ /** Load the small Win32 API lazily so non-Windows processes never load Koffi. */
54
+ async function win32(): Promise<Win32Bindings> {
55
+ if (bindings !== undefined) return bindings
56
+ const koffi = (await import('koffi')).default
57
+ const kernel32 = koffi.load('kernel32.dll')
58
+ bindings = {
59
+ moveFileExW: kernel32.func('__stdcall', 'MoveFileExW', 'int', ['str16', 'str16', 'uint']) as MoveFileExW,
60
+ createSemaphoreW: kernel32.func('__stdcall', 'CreateSemaphoreW', 'intptr', ['void*', 'int', 'int', 'str16']) as CreateSemaphoreW,
61
+ waitForSingleObject: kernel32.func('__stdcall', 'WaitForSingleObject', 'uint', ['intptr', 'uint']) as WaitForSingleObject,
62
+ releaseSemaphore: kernel32.func('__stdcall', 'ReleaseSemaphore', 'int', ['intptr', 'int', 'void*']) as ReleaseSemaphore,
63
+ closeHandle: kernel32.func('__stdcall', 'CloseHandle', 'int', ['intptr']) as CloseHandle,
64
+ getLastError: kernel32.func('__stdcall', 'GetLastError', 'uint', []) as GetLastError,
65
+ }
66
+ return bindings
67
+ }
68
+
69
+ function errnoCode(win32Code: number): string {
70
+ switch (win32Code) {
71
+ case ERROR_FILE_NOT_FOUND:
72
+ case ERROR_PATH_NOT_FOUND:
73
+ return 'ENOENT'
74
+ case ERROR_ACCESS_DENIED:
75
+ return 'EACCES'
76
+ case ERROR_NOT_SAME_DEVICE:
77
+ return 'EXDEV'
78
+ case ERROR_SHARING_VIOLATION:
79
+ return 'EBUSY'
80
+ case ERROR_FILE_EXISTS:
81
+ case ERROR_ALREADY_EXISTS:
82
+ return 'EEXIST'
83
+ case ERROR_INVALID_NAME:
84
+ return 'EINVAL'
85
+ default:
86
+ return 'EIO'
87
+ }
88
+ }
89
+
90
+ function win32Error(syscall: string, win32Code: number, path: string, dest: string): Win32ErrnoException {
91
+ const code = errnoCode(win32Code)
92
+ const error = new Error(`${syscall} ${code} (Win32 ${win32Code}): ${path} -> ${dest}`) as Win32ErrnoException
93
+ error.code = code
94
+ error.errno = win32Code
95
+ error.syscall = syscall
96
+ error.path = path
97
+ error.dest = dest
98
+ error.win32Code = win32Code
99
+ return error
100
+ }
101
+
102
+ function isENOENT(error: unknown): boolean {
103
+ return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
104
+ }
105
+
106
+ function isEEXIST(error: unknown): boolean {
107
+ return (error as NodeJS.ErrnoException | null)?.code === 'EEXIST'
108
+ }
109
+
110
+ async function assertDirectory(path: string): Promise<boolean> {
111
+ try {
112
+ // A bare drive root is already short, and Node rejects its extended-length
113
+ // spelling as EISDIR. Descendants retain the namespace for long-path probes.
114
+ const probe = path === parse(path).root ? path : toNamespacedPath(path)
115
+ const info = await stat(probe)
116
+ if (info.isDirectory()) return true
117
+ const error = new Error(`path exists but is not a directory: ${path}`) as NodeJS.ErrnoException
118
+ error.code = 'ENOTDIR'
119
+ error.path = path
120
+ throw error
121
+ } catch (error) {
122
+ if (isENOENT(error)) return false
123
+ throw error
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Publish `existing` at `replacement` with Windows write-through rename
129
+ * semantics. The destination must not already exist; the move must stay within
130
+ * the volume (no copy fallback flag is set).
131
+ * @param existing - the synced staging path to move.
132
+ * @param replacement - the final path, which must not already exist.
133
+ */
134
+ export async function publishNewFileWin32(existing: string, replacement: string): Promise<void> {
135
+ const api = await win32()
136
+ const ok = api.moveFileExW(toNamespacedPath(existing), toNamespacedPath(replacement), MOVEFILE_WRITE_THROUGH)
137
+ if (ok === 0) throw win32Error('MoveFileExW', api.getLastError(), existing, replacement)
138
+ }
139
+
140
+ /**
141
+ * Acquire the session write lock as a named kernel semaphore (count 1) whose
142
+ * name is derived from the canonical lock path. A kernel object never touches
143
+ * the filesystem, so readers, searches, and directory removal proceed freely
144
+ * while the lock is held; a second acquirer's zero-timeout wait times out
145
+ * (`EBUSY`); and when the last handle closes — including on any process
146
+ * death — the object is destroyed, so a successor's create starts fresh.
147
+ * @param path - the lock file path the name is derived from (case-folded:
148
+ * Windows paths are case-insensitive).
149
+ * @returns the open semaphore handle, released via {@link releaseLockHandleWin32}.
150
+ */
151
+ export async function acquireLockHandleWin32(path: string): Promise<number> {
152
+ const api = await win32()
153
+ const name = `Local\\dsh-session-lock-${createHash('sha256').update(resolve(path).toLowerCase()).digest('hex')}`
154
+ const handle = api.createSemaphoreW(null, 1, 1, name)
155
+ if (handle === 0) throw win32Error('CreateSemaphoreW', api.getLastError(), path, name)
156
+ const wait = api.waitForSingleObject(handle, 0)
157
+ if (wait === WAIT_OBJECT_0) return handle
158
+ api.closeHandle(handle)
159
+ if (wait === WAIT_TIMEOUT) throw win32Error('WaitForSingleObject', ERROR_SHARING_VIOLATION, path, name)
160
+ throw win32Error('WaitForSingleObject', api.getLastError(), path, name)
161
+ }
162
+
163
+ /**
164
+ * Release a lock from {@link acquireLockHandleWin32}: restore the semaphore
165
+ * count and close the handle (the object dies with its last handle).
166
+ * @param handle - the open semaphore handle.
167
+ */
168
+ export async function releaseLockHandleWin32(handle: number): Promise<void> {
169
+ const api = await win32()
170
+ const released = api.releaseSemaphore(handle, 1, null)
171
+ const closed = api.closeHandle(handle)
172
+ if (released === 0 || closed === 0) throw win32Error('ReleaseSemaphore', api.getLastError(), `handle:${handle}`, `handle:${handle}`)
173
+ }
174
+
175
+ /**
176
+ * Create `target` and its missing ancestors with durable Windows namespace
177
+ * publication. Each missing directory is first created as a random staging
178
+ * sibling, then moved to its final name with `MOVEFILE_WRITE_THROUGH`; races
179
+ * with another creator are accepted only after verifying the winner is a
180
+ * directory.
181
+ * @param target - the absolute directory path to create durably when absent.
182
+ */
183
+ export async function ensureDurableDirectoryWin32(target: string): Promise<void> {
184
+ const absolute = resolve(target)
185
+ const root = parse(absolute).root
186
+ await assertDirectory(root)
187
+
188
+ const segments = absolute.slice(root.length).split(/[\\/]+/).filter(part => part.length > 0)
189
+ let current = root
190
+ for (const segment of segments) {
191
+ const next = join(current, segment)
192
+ if (!await assertDirectory(next)) await createLeafDirectoryWin32(current, next)
193
+ current = next
194
+ }
195
+ }
196
+
197
+ async function createLeafDirectoryWin32(parent: string, target: string): Promise<void> {
198
+ // Keep the staging component independent of the target basename so a legal
199
+ // 255-byte target component does not make mkdtemp's sibling name too long.
200
+ const staging = await mkdtemp(toNamespacedPath(join(parent, '.dsh-mkdir-')))
201
+ try {
202
+ await publishNewFileWin32(staging, target)
203
+ } catch (error) {
204
+ await rm(staging, { recursive: true, force: true })
205
+ if (isEEXIST(error) && await assertDirectory(target)) return
206
+ throw error
207
+ }
208
+ }
package/src/worker.ts ADDED
@@ -0,0 +1,56 @@
1
+ /** Worker entry for current-generation physical and logical verification. */
2
+
3
+ import { parentPort, workerData } from 'node:worker_threads'
4
+ import { verifyJsonlCurrentGeneration } from './generation.ts'
5
+ import type { JsonlExpectedPrefix } from './generation.ts'
6
+ import type { JsonlCompression } from './format.ts'
7
+
8
+ interface VerificationRequest {
9
+ readonly path: string
10
+ readonly compression: JsonlCompression
11
+ readonly expectedId: string
12
+ readonly expectedEventCount: number
13
+ readonly expectedPrefix?: JsonlExpectedPrefix
14
+ }
15
+
16
+ function parseRequest(value: unknown): VerificationRequest {
17
+ if (typeof value !== 'object' || value === null) throw new Error('migration verifier request must be an object')
18
+ const request = value as Partial<VerificationRequest>
19
+ if (typeof request.path !== 'string'
20
+ || request.compression !== 'none' && request.compression !== 'zstd'
21
+ || typeof request.expectedId !== 'string'
22
+ || !Number.isSafeInteger(request.expectedEventCount)
23
+ || (request.expectedEventCount as number) < 0
24
+ || request.expectedPrefix !== undefined
25
+ && (!Number.isSafeInteger(request.expectedPrefix.bytes)
26
+ || request.expectedPrefix.bytes < 0
27
+ || !/^[0-9a-f]{64}$/.test(request.expectedPrefix.digest))) {
28
+ throw new Error('migration verifier request is malformed')
29
+ }
30
+ return request as VerificationRequest
31
+ }
32
+
33
+ if (parentPort === null) throw new Error('migration verifier requires a parent port')
34
+ const port = parentPort
35
+
36
+ const request = parseRequest(workerData)
37
+
38
+ async function verify(): Promise<void> {
39
+ try {
40
+ const result = await verifyJsonlCurrentGeneration(
41
+ request.path,
42
+ request.compression,
43
+ request.expectedId,
44
+ request.expectedEventCount,
45
+ request.expectedPrefix,
46
+ )
47
+ port.postMessage({ ok: true, result })
48
+ } catch (error: unknown) {
49
+ const failure = error instanceof Error ? error : new Error(String(error))
50
+ port.postMessage({ ok: false, message: failure.message, stack: failure.stack })
51
+ } finally {
52
+ port.close()
53
+ }
54
+ }
55
+
56
+ void verify()
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Node-private synchronous Zstandard frame decoder optimization.
3
+ * @module dsh-session-persistence-jsonl/zstd-private-decoder
4
+ */
5
+
6
+ import { constants as bufferConstants } from 'node:buffer'
7
+ import { createZstdDecompress } from 'node:zlib'
8
+ import type { ZstdFrameDecoder, ZstdFrameRange } from './zstd.ts'
9
+
10
+ const DECODE_CHUNK_SIZE = 1024 * 1024
11
+
12
+ interface NodeZstdPrivateHandle {
13
+ writeSync(
14
+ flushFlag: number,
15
+ input: Buffer,
16
+ inputOffset: number,
17
+ inputLength: number,
18
+ output: Buffer,
19
+ outputOffset: number,
20
+ outputLength: number,
21
+ ): void
22
+ }
23
+
24
+ type NodeZstdPrivateWriteState = Uint32Array & { 0: number; 1: number }
25
+
26
+ interface NodeZstdPrivateState {
27
+ [key: symbol]: unknown
28
+ _handle: NodeZstdPrivateHandle | null
29
+ _writeState: NodeZstdPrivateWriteState
30
+ _defaultFlushFlag: number
31
+ }
32
+
33
+ type NodeZstdPrivateStream = ReturnType<typeof createZstdDecompress> & NodeZstdPrivateState
34
+
35
+ /** Return the stream with its observed private Node contract, or reject that optimization. */
36
+ function privateZstdStream(
37
+ stream: ReturnType<typeof createZstdDecompress>,
38
+ ): { stream: NodeZstdPrivateStream; errorKey: symbol } | undefined {
39
+ const candidate = stream as unknown as Partial<NodeZstdPrivateState>
40
+ const handle = candidate._handle
41
+ const errorKey = Reflect.ownKeys(stream).find((key): key is symbol => (
42
+ typeof key === 'symbol' && key.description === 'kError'
43
+ ))
44
+ /* v8 ignore next -- one test runtime exposes one Node-private shape; the Node 24/26 matrix checks compatibility. */
45
+ if (
46
+ typeof handle !== 'object' || handle === null
47
+ || typeof (handle as { writeSync?: unknown }).writeSync !== 'function'
48
+ || !(candidate._writeState instanceof Uint32Array)
49
+ || candidate._writeState.length < 2
50
+ || typeof candidate._defaultFlushFlag !== 'number'
51
+ || errorKey === undefined
52
+ || candidate[errorKey] !== null
53
+ ) return undefined
54
+ return { stream: stream as NodeZstdPrivateStream, errorKey }
55
+ }
56
+
57
+ /**
58
+ * Synchronous multi-frame decoder backed by one Node Zstd stream handle. Node
59
+ * exposes synchronous decoding only as a one-shot API, so this adapter uses
60
+ * the stream's private handle contract to reuse its native context and output
61
+ * chunks across frames.
62
+ */
63
+ export class NodePrivateZstdFrameDecoder implements ZstdFrameDecoder {
64
+ private readonly output = Buffer.allocUnsafe(DECODE_CHUNK_SIZE)
65
+ private decoderError?: Error
66
+ private started = false
67
+ private closed = false
68
+
69
+ private constructor(
70
+ private readonly stream: NodeZstdPrivateStream,
71
+ private readonly errorKey: symbol,
72
+ ) {
73
+ this.stream.on('error', (error: Error) => {
74
+ this.decoderError ??= error
75
+ })
76
+ }
77
+
78
+ /**
79
+ * Create the optimized decoder when this Node release exposes the expected
80
+ * private stream shape.
81
+ * @returns a shared decoder, or `undefined` when callers must use the public fallback.
82
+ */
83
+ static create(): NodePrivateZstdFrameDecoder | undefined {
84
+ const stream = createZstdDecompress({ chunkSize: DECODE_CHUNK_SIZE })
85
+ const privateAccess = privateZstdStream(stream)
86
+ /* v8 ignore next -- reached only when a supported Node release changes its private stream shape. */
87
+ if (privateAccess !== undefined) {
88
+ return new NodePrivateZstdFrameDecoder(privateAccess.stream, privateAccess.errorKey)
89
+ }
90
+ /* v8 ignore next -- the active Node runtime passed the private-shape probe above. */
91
+ stream.close()
92
+ /* v8 ignore next -- the active Node runtime passed the private-shape probe above. */
93
+ return undefined
94
+ }
95
+
96
+ /** @inheritdoc */
97
+ public *decode(source: Buffer, frames: readonly ZstdFrameRange[]): Generator<Buffer, void, void> {
98
+ if (this.started) throw new Error('Zstandard frame decoder was already started')
99
+ if (this.closed) throw new Error('cannot start a closed Zstandard frame decoder')
100
+ this.started = true
101
+ try {
102
+ for (const frame of frames) {
103
+ try {
104
+ yield this.decodeFrame(source.subarray(frame.start, frame.end))
105
+ } catch (error) {
106
+ throw new Error(`corrupt Zstandard session log: frame at byte ${frame.start} failed validation`, {
107
+ cause: error,
108
+ })
109
+ }
110
+ }
111
+ } finally {
112
+ this.close()
113
+ }
114
+ }
115
+
116
+ /** Decode one frame; its returned scratch view remains valid until the next call. */
117
+ private decodeFrame(input: Buffer): Buffer {
118
+ const handle = this.stream._handle
119
+ /* v8 ignore next -- decode() rejects closed instances before entering this private frame operation. */
120
+ if (this.closed || handle === null) throw new Error('cannot decode with a closed Zstandard frame decoder')
121
+
122
+ let inputOffset = 0
123
+ let inputRemaining = input.length
124
+ let outputBytes = 0
125
+ const fullChunks: Buffer[] = []
126
+ for (;;) {
127
+ handle.writeSync(
128
+ this.stream._defaultFlushFlag,
129
+ input,
130
+ inputOffset,
131
+ inputRemaining,
132
+ this.output,
133
+ 0,
134
+ this.output.length,
135
+ )
136
+ if (this.decoderError !== undefined) throw this.decoderError
137
+ const internalError = this.stream[this.errorKey]
138
+ if (internalError !== null) {
139
+ if (internalError instanceof Error) throw internalError
140
+ throw new Error('Zstandard decoder exposed a non-Error internal failure')
141
+ }
142
+
143
+ const outputAfter = this.stream._writeState[0]
144
+ const inputAfter = this.stream._writeState[1]
145
+ const consumed = inputRemaining - inputAfter
146
+ const produced = this.output.length - outputAfter
147
+ if (produced > 0) {
148
+ outputBytes += produced
149
+ /* v8 ignore next -- Buffer cannot materialize a frame beyond its own process-wide maximum length. */
150
+ if (outputBytes > bufferConstants.MAX_LENGTH) {
151
+ throw new Error(`Zstandard frame output exceeds ${bufferConstants.MAX_LENGTH} bytes`)
152
+ }
153
+ }
154
+
155
+ if (outputAfter !== 0) {
156
+ /* v8 ignore next -- structurally scanned ranges contain exactly one complete frame and no trailing bytes. */
157
+ if (inputAfter !== 0) throw new Error('Zstandard frame decoder left trailing input')
158
+ const finalChunk = this.output.subarray(0, produced)
159
+ if (fullChunks.length === 0) return finalChunk
160
+ if (produced > 0) fullChunks.push(Buffer.from(finalChunk))
161
+ const onlyChunk = fullChunks[0] as Buffer
162
+ return fullChunks.length === 1
163
+ ? onlyChunk
164
+ : Buffer.concat(fullChunks, outputBytes)
165
+ }
166
+ fullChunks.push(Buffer.from(this.output))
167
+ inputOffset += consumed
168
+ inputRemaining = inputAfter
169
+ }
170
+ }
171
+
172
+ /** @inheritdoc */
173
+ close(): void {
174
+ if (this.closed) return
175
+ this.closed = true
176
+ this.stream.close()
177
+ }
178
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Public-API synchronous Zstandard frame decoder fallback.
3
+ * @module dsh-session-persistence-jsonl/zstd-public-decoder
4
+ */
5
+
6
+ import { zstdDecompressSync } from 'node:zlib'
7
+ import type { ZstdFrameDecoder, ZstdFrameRange } from './zstd.ts'
8
+
9
+ /** Multi-frame adapter built exclusively from Node's supported one-shot API. */
10
+ export class PublicZstdFrameDecoder implements ZstdFrameDecoder {
11
+ private started = false
12
+ private closed = false
13
+
14
+ /** @inheritdoc */
15
+ public *decode(source: Buffer, frames: readonly ZstdFrameRange[]): Generator<Buffer, void, void> {
16
+ if (this.started) throw new Error('Zstandard frame decoder was already started')
17
+ if (this.closed) throw new Error('cannot start a closed Zstandard frame decoder')
18
+ this.started = true
19
+ try {
20
+ for (const { start, end } of frames) {
21
+ let decoded: Buffer
22
+ try {
23
+ decoded = zstdDecompressSync(source.subarray(start, end))
24
+ } catch (error) {
25
+ throw new Error(`corrupt Zstandard session log: frame at byte ${start} failed validation`, {
26
+ cause: error,
27
+ })
28
+ }
29
+ yield decoded
30
+ }
31
+ } finally {
32
+ this.close()
33
+ }
34
+ }
35
+
36
+ /** @inheritdoc */
37
+ close(): void {
38
+ this.closed = true
39
+ }
40
+ }
package/src/zstd.ts ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Zstandard frame primitives for the JSONL persistence backend. The backend
3
+ * owns a concatenated-frame container so it can append and recover batches
4
+ * without exposing compression mechanics through the persistence seam.
5
+ * @module dsh-session-persistence-jsonl/zstd
6
+ */
7
+
8
+ import {
9
+ constants, zstdCompress, zstdDecompress, type ZstdOptions,
10
+ } from 'node:zlib'
11
+ import { promisify } from 'node:util'
12
+ import { NodePrivateZstdFrameDecoder } from './zstd-private-decoder.ts'
13
+ import { PublicZstdFrameDecoder } from './zstd-public-decoder.ts'
14
+
15
+ const ZSTD_MAGIC = 0xFD2FB528
16
+ const zstdCompressAsync = promisify(zstdCompress)
17
+ const zstdDecompressAsync = promisify(zstdDecompress)
18
+ const CHECKSUM_OPTIONS: ZstdOptions = {
19
+ params: { [constants.ZSTD_c_checksumFlag]: 1 },
20
+ }
21
+ const INCOMPLETE_FRAME_OPTIONS: ZstdOptions = {
22
+ finishFlush: constants.ZSTD_e_flush,
23
+ }
24
+
25
+ /** Byte range occupied by one structurally complete Zstandard frame. */
26
+ export interface ZstdFrameRange {
27
+ /** Inclusive frame start. */
28
+ start: number
29
+ /** Exclusive frame end. */
30
+ end: number
31
+ }
32
+
33
+ /** Structural scan result for a concatenated Zstandard stream. */
34
+ export interface ZstdFrameScan {
35
+ /** Complete frames in file order. */
36
+ frames: ZstdFrameRange[]
37
+ /** Start of an incomplete final frame, when EOF interrupts one. */
38
+ tornStart?: number
39
+ }
40
+
41
+ /**
42
+ * Locate complete frames without decompressing their blocks. Invalid complete
43
+ * structure rejects; EOF inside the final frame returns its start for repair.
44
+ * @param buffer - complete bytes currently present in the session artifact.
45
+ * @param maxFrames - optional complete-frame limit for metadata-only readers.
46
+ * @returns complete frame ranges and an optional incomplete-final-frame start.
47
+ */
48
+ export function scanZstdFrames(buffer: Buffer, maxFrames = Number.POSITIVE_INFINITY): ZstdFrameScan {
49
+ const frames: ZstdFrameRange[] = []
50
+ let offset = 0
51
+
52
+ while (offset < buffer.length) {
53
+ const start = offset
54
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
55
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) {
56
+ throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${offset}`)
57
+ }
58
+ offset += 4
59
+
60
+ if (offset === buffer.length) return { frames, tornStart: start }
61
+ const descriptor = buffer.readUInt8(offset)
62
+ offset += 1
63
+ if ((descriptor & 0x18) !== 0) {
64
+ throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${offset - 1}`)
65
+ }
66
+
67
+ const contentSizeFlag = descriptor >>> 6
68
+ const singleSegment = (descriptor & 0x20) !== 0
69
+ const checksum = (descriptor & 0x04) !== 0
70
+ const dictionaryFlag = descriptor & 0x03
71
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
72
+ const contentSizeBytes = contentSizeFlag === 0
73
+ ? (singleSegment ? 1 : 0)
74
+ : 1 << contentSizeFlag
75
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
76
+ if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start }
77
+ offset += remainingHeaderBytes
78
+
79
+ for (;;) {
80
+ if (buffer.length - offset < 3) return { frames, tornStart: start }
81
+ const blockHeader = buffer.readUIntLE(offset, 3)
82
+ offset += 3
83
+ const lastBlock = (blockHeader & 1) !== 0
84
+ const blockType = (blockHeader >>> 1) & 0x03
85
+ const blockSize = blockHeader >>> 3
86
+ if (blockType === 0x03) {
87
+ throw new Error(`corrupt Zstandard session log: reserved block type at byte ${offset - 3}`)
88
+ }
89
+ const payloadBytes = blockType === 0x01 ? 1 : blockSize
90
+ if (buffer.length - offset < payloadBytes) return { frames, tornStart: start }
91
+ offset += payloadBytes
92
+ if (lastBlock) break
93
+ }
94
+
95
+ if (checksum) {
96
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
97
+ offset += 4
98
+ }
99
+ frames.push({ start, end: offset })
100
+ if (frames.length === maxFrames) return { frames }
101
+ }
102
+
103
+ return { frames }
104
+ }
105
+
106
+ /**
107
+ * Compress one independently decodable, checksummed Zstandard frame.
108
+ * @param input - JSONL bytes for a header or durable event batch.
109
+ * @returns the complete encoded frame.
110
+ */
111
+ export async function compressZstdFrame(input: Buffer | string): Promise<Buffer> {
112
+ return zstdCompressAsync(input, CHECKSUM_OPTIONS)
113
+ }
114
+
115
+ /**
116
+ * Decompress one complete frame and validate its checksum.
117
+ * @param input - one structurally complete Zstandard frame.
118
+ * @returns the frame plaintext.
119
+ */
120
+ export async function decompressZstdFrame(input: Buffer): Promise<Buffer> {
121
+ return zstdDecompressAsync(input)
122
+ }
123
+
124
+ /** Common lifecycle for interchangeable synchronous multi-frame decoders. */
125
+ export interface ZstdFrameDecoder {
126
+ /**
127
+ * Decode and checksum complete frames in source order. Each yielded buffer
128
+ * remains valid only until the iterator advances to the next frame.
129
+ * @param source - concatenated Zstandard frame bytes.
130
+ * @param frames - structurally complete ranges within `source`.
131
+ * @returns one plaintext buffer per frame.
132
+ */
133
+ decode(source: Buffer, frames: readonly ZstdFrameRange[]): Generator<Buffer, void, void>
134
+ /** Release decoder-owned resources; repeated calls are harmless. */
135
+ close(): void
136
+ }
137
+
138
+ /**
139
+ * Select the shared private decoder when the running Node 24/26 shape is
140
+ * compatible, otherwise preserve correctness with the public one-shot API.
141
+ * @returns a synchronous decoder with an implementation-independent lifecycle.
142
+ */
143
+ export function createZstdFrameDecoder(): ZstdFrameDecoder {
144
+ return NodePrivateZstdFrameDecoder.create() ?? new PublicZstdFrameDecoder()
145
+ }
146
+
147
+ /**
148
+ * Recover available plaintext from a structurally incomplete final frame.
149
+ * `ZSTD_e_flush` deliberately suppresses final-frame and checksum completion;
150
+ * callers must establish the torn frame boundary before using this helper.
151
+ * @param input - available bytes from a known incomplete Zstandard frame.
152
+ * @returns plaintext produced from the available input.
153
+ */
154
+ export async function decompressZstdPrefix(input: Buffer): Promise<Buffer> {
155
+ return zstdDecompressAsync(input, INCOMPLETE_FRAME_OPTIONS)
156
+ }