@kabxx/dsh-session-move 0.1.1 → 0.1.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.
package/src/zstd-frame.js CHANGED
@@ -19,66 +19,102 @@ import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib'
19
19
  const ZSTD_MAGIC = 0xFD2FB528
20
20
  const CHECKSUM_OPTIONS = { params: { [constants.ZSTD_c_checksumFlag]: 1 } }
21
21
 
22
- /**
23
- * Locate complete frames without decompressing their blocks.
24
- * @param buffer - complete bytes currently present in the session artifact.
25
- * @returns complete frame ranges and an optional incomplete-final-frame start.
26
- */
27
- export function scanFrames(buffer) {
28
- const frames = []
29
- let offset = 0
22
+ const FRAME_MAGIC_BYTES = 4
30
23
 
31
- while (offset < buffer.length) {
32
- const start = offset
33
- if (buffer.length - offset < 4) return { frames, tornStart: start }
34
- if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) {
35
- throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${offset}`)
36
- }
37
- offset += 4
24
+ /** Scan compressed frame boundaries with fixed scratch space and no body decompression. */
25
+ export function createFrameScanner() {
26
+ const scratch = Buffer.allocUnsafe(4)
27
+ let phase = 'magic'
28
+ let remaining = FRAME_MAGIC_BYTES
29
+ let offset = 0
30
+ let start = 0
31
+ let checksum
32
+ let lastBlock
38
33
 
39
- if (offset === buffer.length) return { frames, tornStart: start }
40
- const descriptor = buffer.readUInt8(offset)
41
- offset += 1
42
- if ((descriptor & 0x18) !== 0) {
43
- throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${offset - 1}`)
44
- }
34
+ function nextPhase(name, bytes) {
35
+ phase = name
36
+ remaining = bytes
37
+ }
45
38
 
46
- const contentSizeFlag = descriptor >>> 6
47
- const singleSegment = (descriptor & 0x20) !== 0
48
- const checksum = (descriptor & 0x04) !== 0
49
- const dictionaryFlag = descriptor & 0x03
50
- const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
51
- const contentSizeBytes = contentSizeFlag === 0
52
- ? (singleSegment ? 1 : 0)
53
- : 1 << contentSizeFlag
54
- const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
55
- if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start }
56
- offset += remainingHeaderBytes
39
+ function completeFrame(onFrame) {
40
+ const end = offset
41
+ nextPhase('magic', FRAME_MAGIC_BYTES)
42
+ onFrame?.({ start, end })
43
+ start = end
44
+ }
57
45
 
58
- for (;;) {
59
- if (buffer.length - offset < 3) return { frames, tornStart: start }
60
- const blockHeader = buffer.readUIntLE(offset, 3)
61
- offset += 3
62
- const lastBlock = (blockHeader & 1) !== 0
63
- const blockType = (blockHeader >>> 1) & 0x03
64
- const blockSize = blockHeader >>> 3
65
- if (blockType === 0x03) {
66
- throw new Error(`corrupt Zstandard session log: reserved block type at byte ${offset - 3}`)
46
+ function advance(onFrame) {
47
+ switch (phase) {
48
+ case 'magic':
49
+ if (scratch.readUInt32LE(0) !== ZSTD_MAGIC) {
50
+ throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${start}`)
51
+ }
52
+ nextPhase('descriptor', 1)
53
+ break
54
+ case 'descriptor': {
55
+ const descriptor = scratch[0]
56
+ if ((descriptor & 0x18) !== 0) {
57
+ throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${offset - 1}`)
58
+ }
59
+ const contentSizeFlag = descriptor >>> 6
60
+ const singleSegment = (descriptor & 0x20) !== 0
61
+ checksum = (descriptor & 0x04) !== 0
62
+ const dictionaryFlag = descriptor & 0x03
63
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
64
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
65
+ nextPhase('frame-header', (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes)
66
+ break
67
+ }
68
+ case 'frame-header':
69
+ nextPhase('block-header', 3)
70
+ break
71
+ case 'block-header': {
72
+ const blockHeader = scratch.readUIntLE(0, 3)
73
+ lastBlock = (blockHeader & 1) !== 0
74
+ const blockType = (blockHeader >>> 1) & 0x03
75
+ if (blockType === 0x03) {
76
+ throw new Error(`corrupt Zstandard session log: reserved block type at byte ${offset - 3}`)
77
+ }
78
+ nextPhase('block', blockType === 0x01 ? 1 : blockHeader >>> 3)
79
+ break
67
80
  }
68
- const payloadBytes = blockType === 0x01 ? 1 : blockSize
69
- if (buffer.length - offset < payloadBytes) return { frames, tornStart: start }
70
- offset += payloadBytes
71
- if (lastBlock) break
81
+ case 'block':
82
+ if (!lastBlock) nextPhase('block-header', 3)
83
+ else if (checksum) nextPhase('checksum', 4)
84
+ else completeFrame(onFrame)
85
+ break
86
+ case 'checksum':
87
+ completeFrame(onFrame)
72
88
  }
89
+ }
73
90
 
74
- if (checksum) {
75
- if (buffer.length - offset < 4) return { frames, tornStart: start }
76
- offset += 4
77
- }
78
- frames.push({ start, end: offset })
91
+ return {
92
+ write(chunk, onFrame) {
93
+ let cursor = 0
94
+ while (cursor < chunk.length) {
95
+ const count = Math.min(remaining, chunk.length - cursor)
96
+ // Only descriptor and block metadata need to survive a chunk boundary.
97
+ if (phase === 'magic' || phase === 'descriptor' || phase === 'block-header') {
98
+ const fieldWidth = phase === 'magic' ? FRAME_MAGIC_BYTES : phase === 'descriptor' ? 1 : 3
99
+ chunk.copy(scratch, fieldWidth - remaining, cursor, cursor + count)
100
+ }
101
+ cursor += count
102
+ offset += count
103
+ remaining -= count
104
+ while (remaining === 0) advance(onFrame)
105
+ }
106
+ },
107
+ finish() { return offset === start ? undefined : start },
79
108
  }
109
+ }
80
110
 
81
- return { frames }
111
+ /** Locate complete frames in an in-memory artifact. */
112
+ export function scanFrames(buffer) {
113
+ const frames = []
114
+ const scanner = createFrameScanner()
115
+ scanner.write(buffer, (frame) => frames.push(frame))
116
+ const tornStart = scanner.finish()
117
+ return tornStart === undefined ? { frames } : { frames, tornStart }
82
118
  }
83
119
 
84
120
  /**
package/src/inbox.js DELETED
@@ -1,39 +0,0 @@
1
- import { fail } from './plan.js'
2
-
3
- export async function readMoveEvents(ctx, { id, oldCwd }) {
4
- let file
5
- try {
6
- file = await ctx.sessionPersistence.open(id, 'read')
7
- if (file.header.id !== id || file.header.cwd !== oldCwd) throw fail('changed')
8
- const { events } = await file.read()
9
- assertNoPendingInbox(ctx, file.header, events, file.inheritedEventCount)
10
- return events
11
- } catch (error) {
12
- if (error.code === 'busy' || error.code === 'changed') throw error
13
- throw fail('unsupported', error)
14
- } finally {
15
- await file?.close()
16
- }
17
- }
18
-
19
- /** Check the full durable inbox at the caller's quiescent, write-locked cut. */
20
- export function assertNoPendingInbox(ctx, header, events, inheritedEventCount) {
21
- let inbox
22
- try {
23
- if (!Array.isArray(events) || !Number.isSafeInteger(inheritedEventCount)
24
- || inheritedEventCount < 0 || inheritedEventCount > events.length) {
25
- throw new Error('Invalid session replay cut')
26
- }
27
- // An empty checkpoint forces DSH to replay from the origin instead of
28
- // taking a potentially stale cached inbox or opening a live agent.
29
- const restored = ctx.sessionProjections.restore({}, events, 0, header, inheritedEventCount)
30
- inbox = restored.snapshot.values.inbox
31
- if (!Array.isArray(inbox?.['next-turn']) || !Array.isArray(inbox['next-step'])) {
32
- throw new Error('DSH did not restore the standard inbox projection')
33
- }
34
- } catch (error) {
35
- throw fail('unsupported', error)
36
- }
37
-
38
- if (inbox['next-turn'].length || inbox['next-step'].length) throw fail('busy')
39
- }