Publish reviewed operation framing protocol
of shared·codex-capacity-policy··Not checked
Version 105 · Files at version 106
2 files, 365 lines added, 0 removed.
--- /dev/null
+++ b/worker/project/operation-protocol.ts
@@ -0,0 +1,280 @@
1+import type { Entry } from "./project-types.ts"; 3+export const OPERATION_CHUNK_BYTES = 64 * 1024; 4+export const OPERATION_CHUNK_ENTRIES = 32; 5+export const OPERATION_MAX_BYTES = 4 * 1024 * 1024; 6+export const OPERATION_MAX_CHUNKS = 64; 8+export interface OperationHeads { 10+ readonly shared: number; 11+ readonly actorMine: number; 12+ readonly actorBase: number; 13+ readonly queueRevision: number; 16+export interface OperationQueueEffect { 17+ readonly kind: "enqueue"; 18+ readonly queueId: number; 19+ readonly actor: string; 20+ readonly entryIndex: number; 21+ readonly position: number; 24+export interface OperationLogSummary { 25+ readonly lines: number; 26+ readonly keys: number; 27+ readonly chars: number; 28+ readonly sharedVersion?: number; 29+ readonly lastPublish?: { readonly agent: string; readonly time: number }; 32+export interface ProjectOperation { 34+ readonly tenant: string; 35+ readonly project: string; 36+ readonly incarnation: string; 37+ readonly actor: string; 38+ readonly build: string; 39+ readonly executorIdentity: string; 40+ readonly rootDigest: string; 41+ readonly authorizationRevision: string; 42+ readonly policyRevision: string; 43+ readonly operationTime: number; 44+ readonly queuePolicy: { readonly policyRevision: string; readonly checkerReady: boolean }; 45+ readonly generation: number; 46+ readonly heads: OperationHeads; 47+ readonly message: string; 48+ readonly files: Readonly<Record<string, string | null>>; 51+export interface OperationFence { 52+ readonly tenant: string; 53+ readonly project: string; 54+ readonly incarnation: string; 55+ readonly actor: string; 56+ readonly build: string; 57+ readonly executorIdentity: string; 58+ readonly rootDigest: string; 59+ readonly authorizationRevision: string; 60+ readonly policyRevision: string; 61+ readonly generation: number; 62+ readonly heads: OperationHeads; 65+export interface OperationProjection { 66+ readonly sharedHead: number; 67+ readonly actorMineHead: number; 68+ readonly actorBaseHead: number; 69+ readonly queueRevision: number; 70+ readonly queueEffects: readonly OperationQueueEffect[]; 71+ readonly logSummary: OperationLogSummary; 74+export interface OperationReceipt { 76+ readonly tenant: string; 77+ readonly project: string; 78+ readonly incarnation: string; 79+ readonly actor: string; 80+ readonly build: string; 81+ readonly executorIdentity: string; 82+ readonly authorizationRevision: string; 83+ readonly policyRevision: string; 84+ readonly generation: number; 85+ readonly previousRootDigest: string; 86+ readonly nextRootDigest: string; 87+ readonly previousHeads: OperationHeads; 88+ readonly nextHeads: OperationHeads; 89+ readonly requestDigest: string; 90+ readonly outputDigest: string; 91+ readonly entryCount: number; 92+ readonly queueRevision: number; 93+ readonly queueEffects: readonly OperationQueueEffect[]; 94+ readonly status: "committed"; 97+export interface OperationChunk { 98+ readonly index: number; 99+ readonly firstEntry: number; 100+ readonly count: number; 101+ readonly bytes: number; 102+ readonly entries: readonly Entry[]; 103+ readonly text: string; 104+ readonly digest: string; 105+ readonly chain: string; 108+export function canonicalJson(value: unknown): string { 109+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; 110+ if (value && typeof value === "object") { 111+ const record = value as Record<string, unknown>; 112+ return `{${Object.keys(record) 114+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`) 117+ return JSON.stringify(value); 120+export function encodeEntries(entries: readonly Entry[]): string { 121+ return canonicalJson(entries); 124+export async function digestText(text: string): Promise<string> { 125+ const bytes = new TextEncoder().encode(text); 126+ const digest = await crypto.subtle.digest("SHA-256", bytes); 127+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); 130+export async function chainDigest( 137+ return digestText(canonicalJson({ previous, index, count, bytes, digest })); 140+export async function digestOperation(operation: ProjectOperation): Promise<string> { 141+ return digestText(canonicalJson(operation)); 144+function* jsonTokens(value: unknown, ancestors = new Set<object>()): Generator<string> { 145+ if (value === null || typeof value === "boolean") { 146+ yield String(value); 149+ if (typeof value === "number") { 150+ yield Number.isFinite(value) ? JSON.stringify(value) : "null"; 153+ if (typeof value === "string") { 155+ for (const point of value) { 156+ const code = point.charCodeAt(0); 157+ if (point === '"') yield '\\"'; 158+ else if (point === "\\") yield "\\\\"; 159+ else if (point === "\b") yield "\\b"; 160+ else if (point === "\f") yield "\\f"; 161+ else if (point === "\n") yield "\\n"; 162+ else if (point === "\r") yield "\\r"; 163+ else if (point === "\t") yield "\\t"; 164+ else if (code < 0x20 || (point.length === 1 && code >= 0xd800 && code <= 0xdfff)) 165+ yield `\\u${code.toString(16).padStart(4, "0")}`; 171+ if (Array.isArray(value)) { 172+ if (ancestors.has(value)) throw new TypeError("cannot serialize a cyclic entry"); 173+ ancestors.add(value); 175+ for (let index = 0; index < value.length; index++) { 176+ if (index) yield ","; 177+ yield* jsonTokens(value[index] ?? null, ancestors); 180+ ancestors.delete(value); 183+ if (value && typeof value === "object") { 184+ const record = value as Record<string, unknown>; 185+ if (ancestors.has(record)) throw new TypeError("cannot serialize a cyclic entry"); 186+ ancestors.add(record); 189+ for (const key in record) { 190+ if (!Object.hasOwn(record, key)) continue; 191+ const child = record[key]; 192+ if (child === undefined || typeof child === "function" || typeof child === "symbol") continue; 193+ if (!first) yield ","; 195+ yield* jsonTokens(key, ancestors); 197+ yield* jsonTokens(child, ancestors); 200+ ancestors.delete(record); 203+ if (value === undefined || typeof value === "function" || typeof value === "symbol") { 207+ throw new TypeError("entry contains an unsupported JSON value"); 210+export interface Utf8Frame { 211+ readonly text: string; 212+ readonly bytes: number; 215+export function* utf8JsonFrames(value: unknown): Generator<Utf8Frame> { 218+ for (const token of jsonTokens(value)) { 219+ for (const point of token) { 220+ const size = new TextEncoder().encode(point).byteLength; 221+ if (bytes + size > OPERATION_CHUNK_BYTES) { 222+ yield { text: frame, bytes }; 230+ if (frame || bytes === 0) yield { text: frame, bytes }; 233+export function measureUtf8Json(value: unknown): { bytes: number; frames: number } { 236+ for (const frame of utf8JsonFrames(value)) { 237+ bytes += frame.bytes; 240+ return { bytes, frames }; 244+ * Emits bounded JSON chunks for small entries. The store separately frames a 245+ * single large entry; this helper intentionally keeps its array contract. 247+export async function* chunkEntries(entries: Iterable<Entry>): AsyncGenerator<OperationChunk> { 251+ let batch: Entry[] = []; 253+ for (const entry of entries) { 254+ const text = canonicalJson(entry); 255+ const size = new TextEncoder().encode(text).byteLength; 256+ if (size + 2 > OPERATION_CHUNK_BYTES) throw new RangeError("one operation entry requires split UTF-8 framing"); 257+ const withComma = size + (batch.length ? 1 : 0); 258+ if (batch.length && (batch.length >= OPERATION_CHUNK_ENTRIES || batchBytes + withComma > OPERATION_CHUNK_BYTES)) { 259+ const chunkText = encodeEntries(batch); 260+ const bytes = new TextEncoder().encode(chunkText).byteLength; 261+ const digest = await digestText(chunkText); 262+ const chain = await chainDigest(previous, index, batch.length, bytes, digest); 263+ yield { index, firstEntry, count: batch.length, bytes, entries: batch, text: chunkText, digest, chain }; 265+ firstEntry += batch.length; 271+ batchBytes += size + (batch.length > 1 ? 1 : 0); 274+ const text = encodeEntries(batch); 275+ const bytes = new TextEncoder().encode(text).byteLength; 276+ const digest = await digestText(text); 277+ const chain = await chainDigest(previous, index, batch.length, bytes, digest); 278+ yield { index, firstEntry, count: batch.length, bytes, entries: batch, text, digest, chain }; --- /dev/null
+++ b/worker/project/test/operation-protocol.test.ts
@@ -0,0 +1,85 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 8+ type ProjectOperation, 10+} from "../operation-protocol.ts"; 11+import type { Entry } from "../project-types.ts"; 13+const operation: ProjectOperation = { 16+ project: "project-1", 17+ incarnation: "incarnation-1", 20+ executorIdentity: "trusted-local-executor", 21+ rootDigest: "root-0", 22+ authorizationRevision: "auth-1", 23+ policyRevision: "policy-1", 25+ queuePolicy: { policyRevision: "policy-1", checkerReady: false }, 27+ heads: { log: 0, shared: 0, actorMine: 0, actorBase: 0, queueRevision: 0 }, 28+ message: "record and publish", 29+ files: { "readme.txt": "updated\n" }, 32+test("canonical request binding ignores object property order and binds every request field", async () => { 35+ files: { "readme.txt": "updated\n" }, 36+ heads: { actorBase: 0, actorMine: 0, shared: 0, log: 0, queueRevision: 0 }, 38+ assert.equal(await digestOperation(operation), await digestOperation(reordered)); 40+ await digestOperation(operation), 41+ await digestOperation({ ...operation, authorizationRevision: "revoked" }), 44+ await digestOperation(operation), 45+ await digestOperation({ ...operation, files: { "readme.txt": "other\n" } }), 47+ assert.notEqual(await digestOperation(operation), await digestOperation({ ...operation, operationTime: 21 })); 49+ await digestOperation(operation), 50+ await digestOperation({ ...operation, queuePolicy: { ...operation.queuePolicy, checkerReady: true } }), 52+ assert.equal(canonicalJson({ z: 1, a: 2 }), '{"a":2,"z":1}'); 55+test("chunk generator preserves exact order with bounded entries and UTF-8 byte accounting", async () => { 56+ const entries: Entry[] = Array.from({ length: 70 }, (_, index) => ({ 58+ agent: `agent-${index}`, 62+ const chunks: OperationChunk[] = []; 63+ for await (const chunk of chunkEntries(entries)) chunks.push(chunk); 65+ chunks.flatMap((chunk) => chunk.entries), 68+ assert.ok(chunks.every((chunk, index) => chunk.index === index && chunk.count <= 32 && chunk.bytes <= 64 * 1024)); 70+ chunks.map((chunk) => chunk.firstEntry), 73+ assert.ok(chunks.every((chunk, index) => index === 0 || chunk.chain !== chunks[index - 1]!.chain)); 75+ const large: Entry = { type: "join", agent: "🙂".repeat(8_000), version: 0, time: 1 }; 76+ const utf8: OperationChunk[] = []; 77+ for await (const chunk of chunkEntries([large])) utf8.push(chunk); 78+ assert.ok(utf8[0]!.bytes > JSON.stringify(large).length); 79+ assert.ok(utf8[0]!.bytes <= 64 * 1024); 80+ const largeEntry: Entry = { type: "join", agent: `🙂\n"`.repeat(20_000), version: 0, time: 1 }; 81+ const frames = [...utf8JsonFrames(largeEntry)]; 82+ assert.ok(frames.length > 1); 83+ assert.ok(frames.every((frame) => frame.bytes <= 64 * 1024)); 84+ assert.deepEqual(JSON.parse(frames.map((frame) => frame.text).join("")), largeEntry);