Repository navigation
Expand file tree
/
Copy pathpayload-codec.ts
More file actions
186 lines (185 loc) · 5.29 KB
/
Copy pathpayload-codec.ts
File metadata and controls
186 lines (185 loc) · 5.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import { createHash } from "node:crypto";
import { gzipSync, gunzipSync } from "node:zlib";
import { z } from "zod";
export const payloadHash = (data: string | Uint8Array) =>
createHash("sha256").update(data).digest("hex");
const hash = z.string().regex(/^[a-f0-9]{64}$/);
const pointer = z
.object({ kind: z.enum(["data", "index"]), sha256: hash })
.strict();
const indexSchema = z
.object({
type: z.literal("knowledge_book_payload_index"),
version: z.literal(1),
children: z.array(pointer).min(1).max(128),
})
.strict();
const rootSchema = z
.object({
type: z.literal("knowledge_book_payload_root"),
version: z.literal(1),
rawSha256: hash,
rawSize: z.number().int().positive(),
tree: pointer,
})
.strict();
export type PayloadKind = "data" | "index" | "root";
export type PayloadPointer = { kind: "data" | "index"; sha256: string };
export type EncodedObject = {
kind: PayloadKind;
sha256: string;
bytes: Buffer;
rawSize: number;
storedSha256: string;
children: PayloadPointer[];
};
export const payloadObjectLimit = 1024 * 1024;
/** Intern raw quoted tokens, preserving whitespace, escapes, field order and UTF-8 bytes. */
export function encodeBookPayload(raw: string) {
JSON.parse(raw);
const objects = new Map<string, EncodedObject>();
const add = (
kind: PayloadKind,
body: Buffer,
children: PayloadPointer[] = [],
) => {
if (!body.length || body.length > payloadObjectLimit)
throw new Error("Invalid payload chunk size");
const sha256 = payloadHash(body),
bytes = gzipSync(body);
objects.set(`${kind}:${sha256}`, {
kind,
sha256,
bytes,
rawSize: body.length,
storedSha256: payloadHash(bytes),
children,
});
return { kind, sha256 } as PayloadPointer;
};
const pieces: PayloadPointer[] = [];
const append = (text: string) => {
const bytes = Buffer.from(text);
for (let i = 0; i < bytes.length; i += payloadObjectLimit)
pieces.push(add("data", bytes.subarray(i, i + payloadObjectLimit)));
};
let start = 0;
for (let i = 0; i < raw.length; i++) {
if (raw[i] !== '"') continue;
const tokenStart = i++;
while (i < raw.length) {
if (raw[i] === "\\") i += 2;
else if (raw[i++] === '"') break;
}
const token = raw.slice(tokenStart, i);
if (Buffer.byteLength(token) >= 1024) {
append(raw.slice(start, tokenStart));
append(token);
start = i;
}
i--;
}
append(raw.slice(start));
let level = pieces;
while (level.length > 1) {
const next: PayloadPointer[] = [];
for (let i = 0; i < level.length; i += 128) {
const children = level.slice(i, i + 128);
next.push(
add(
"index",
Buffer.from(
JSON.stringify({
type: "knowledge_book_payload_index",
version: 1,
children,
}),
),
children,
),
);
}
level = next;
}
const rawSha256 = payloadHash(raw),
rawSize = Buffer.byteLength(raw);
const tree = level[0]!;
const root = add(
"root",
Buffer.from(
JSON.stringify({
type: "knowledge_book_payload_root",
version: 1,
rawSha256,
rawSize,
tree,
}),
),
[tree],
);
return {
objects: [...objects.values()],
rootSha256: root.sha256,
rawSha256,
rawSize,
};
}
export function decodePayloadObject(
bytes: Uint8Array,
rawSize: number,
sha256: string,
storedSha256: string,
) {
if (
payloadHash(bytes) !== storedSha256 ||
rawSize <= 0 ||
rawSize > payloadObjectLimit
)
throw new Error("Invalid stored payload");
const raw = gunzipSync(bytes, { maxOutputLength: payloadObjectLimit });
if (raw.length !== rawSize || payloadHash(raw) !== sha256)
throw new Error("Invalid raw payload");
return raw;
}
export async function decodeBookPayload(
rootSha256: string,
rawSha256: string,
rawSize: number,
load: (kind: PayloadKind, sha256: string) => Promise<Buffer>,
) {
const root = rootSchema.parse(
JSON.parse((await load("root", rootSha256)).toString("utf8")),
);
if (root.rawSha256 !== rawSha256 || root.rawSize !== rawSize)
throw new Error("Payload root mismatch");
const parts: Buffer[] = [];
let size = 0;
const walk = async (p: PayloadPointer, depth: number) => {
if (depth > 16) throw new Error("Payload index exceeds depth limit");
const raw = await load(p.kind, p.sha256);
if (p.kind === "data") {
size += raw.length;
if (size > rawSize) throw new Error("Payload exceeds recorded size");
parts.push(raw);
} else
for (const child of indexSchema.parse(JSON.parse(raw.toString("utf8")))
.children)
await walk(child, depth + 1);
};
await walk(root.tree, 0);
const raw = Buffer.concat(parts);
if (raw.length !== rawSize || payloadHash(raw) !== rawSha256)
throw new Error("Reconstructed payload mismatch");
const text = new TextDecoder("utf-8", { fatal: true }).decode(raw);
JSON.parse(text);
return text;
}
export function payloadObjectChildren(
kind: PayloadKind,
raw: Buffer,
): PayloadPointer[] {
if (kind === "data") return [];
if (kind === "root")
return [rootSchema.parse(JSON.parse(raw.toString("utf8"))).tree];
return indexSchema.parse(JSON.parse(raw.toString("utf8"))).children;
}