Files
tech-log-frontend/tests/unit/realtime/sse-parser-reference.ts
T
DongHyeonka c80320dfc7 chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
2026-11-12 08:28:54 +09:00

365 lines
10 KiB
TypeScript

// The round-2 SSE parser (decode each chunk, then re-encode every segment to
// count its bytes), kept only as the oracle for the differential test.
import type { RealtimeResult } from "../../../src/application/ports/realtime/shared.ts";
import {
realtimeFailure,
realtimeSuccess,
} from "../../../src/adapters/realtime/result.ts";
export const SSE_PARSER_CEILINGS = Object.freeze({
maxLineBytes: 64 * 1_024,
maxEventBytes: 64 * 1_024,
maxIncompleteBufferBytes: 128 * 1_024,
maxChunkBytes: 256 * 1_024,
maxItemsPerChunk: 256,
maxRetryMs: 60_000,
});
const LINE_BREAK = /[\r\n]/gu;
const NO_ITEMS: readonly SseParserItem[] = Object.freeze([]);
const COMMENT_ITEMS: readonly SseParserItem[] = Object.freeze([
Object.freeze({ kind: "COMMENT" as const }),
]);
export type SseParserLimits = Readonly<{
maxLineBytes: number;
maxEventBytes: number;
maxIncompleteBufferBytes: number;
maxChunkBytes: number;
maxItemsPerChunk: number;
maxRetryMs: number;
}>;
export type ParsedSseEvent = Readonly<{
kind: "EVENT";
eventType: string;
data: string;
/**
* Standard SSE last-event-ID state. Consumers that require cursor-after-
* effect must additionally require `hasExplicitId` and commit independently.
*/
id: string | null;
hasExplicitId: boolean;
}>;
export type SseParserItem =
| ParsedSseEvent
| Readonly<{ kind: "COMMENT" }>
| Readonly<{ kind: "RETRY"; retryMs: number }>;
export type SseParserFinish = Readonly<{
items: readonly SseParserItem[];
incompleteEventDiscarded: boolean;
}>;
export type IncrementalSseParser = Readonly<{
/**
* Returns at most `maxItemsPerChunk` items. Text past that cap is kept and
* must be taken with `drain()` until it returns no items; pushing or
* finishing before then fails with QUEUE_OVERFLOW.
*/
push(chunk: Uint8Array): RealtimeResult<readonly SseParserItem[]>;
drain(): RealtimeResult<readonly SseParserItem[]>;
finish(): RealtimeResult<SseParserFinish>;
}>;
export function createIncrementalSseParser(
limits: Partial<SseParserLimits> = {},
): IncrementalSseParser {
const resolved = resolveLimits(limits);
// ignoreBOM: false makes the decoder strip the one leading BOM the
// stream grammar allows; a second one is ordinary text.
const decoder = new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: false,
});
const encoder = new TextEncoder();
let state: "OPEN" | "FAILED" | "FINISHED" = "OPEN";
let pendingCarriageReturn = false;
let line = "";
let lineBytes = 0;
let undrained = "";
let blockBytes = 0;
let dataLines: string[] = [];
let eventType = "";
let lastEventId: string | null = null;
let hasExplicitId = false;
function push(
chunk: Uint8Array,
): RealtimeResult<readonly SseParserItem[]> {
if (state !== "OPEN") {
return realtimeFailure("CLOSED", "DECODE");
}
if (!(chunk instanceof Uint8Array)) {
return fail("MALFORMED_EVENT");
}
if (chunk.byteLength > resolved.maxChunkBytes) {
return fail("EVENT_TOO_LARGE");
}
if (undrained.length > 0) return fail("QUEUE_OVERFLOW");
let text: string;
try {
text = decoder.decode(chunk, { stream: true });
} catch {
return fail("MALFORMED_EVENT");
}
return consumeText(text);
}
function drain(): RealtimeResult<readonly SseParserItem[]> {
if (state !== "OPEN") {
return realtimeFailure("CLOSED", "DECODE");
}
const text = undrained;
undrained = "";
return consumeText(text);
}
function finish(): RealtimeResult<SseParserFinish> {
if (state !== "OPEN") {
return realtimeFailure("CLOSED", "DECODE");
}
if (undrained.length > 0) return fail("QUEUE_OVERFLOW");
let tail: string;
try {
tail = decoder.decode();
} catch {
return fail("MALFORMED_EVENT");
}
const consumed = consumeText(tail);
if (!consumed.ok) return consumed;
const items = [...consumed.value];
if (pendingCarriageReturn) {
pendingCarriageReturn = false;
const processed = processLine(1);
if (!processed.ok) return processed;
items.push(...processed.value);
}
if (
undrained.length > 0 ||
items.length > resolved.maxItemsPerChunk
) {
return fail("QUEUE_OVERFLOW");
}
const incompleteEventDiscarded =
lineBytes > 0 ||
blockBytes > 0 ||
dataLines.length > 0 ||
eventType.length > 0 ||
hasExplicitId;
clearBlock();
line = "";
lineBytes = 0;
state = "FINISHED";
return success(
Object.freeze({
items: Object.freeze(items),
incompleteEventDiscarded,
}),
);
}
/**
* Works a line at a time: find the next CR/LF, append the text before it
* and count its UTF-8 bytes once. Byte counts only grow within a line, so
* checking the limits per segment fails exactly where a per-character check
* would. Stops at `maxItemsPerChunk` items and keeps the rest for `drain()`.
*/
function consumeText(
text: string,
): RealtimeResult<readonly SseParserItem[]> {
const items: SseParserItem[] = [];
let index = 0;
while (index < text.length) {
if (items.length >= resolved.maxItemsPerChunk) {
undrained = text.slice(index);
break;
}
if (pendingCarriageReturn) {
pendingCarriageReturn = false;
const lineFeed = text.charCodeAt(index) === 0x0a;
const processed = processLine(lineFeed ? 2 : 1);
if (!processed.ok) return processed;
items.push(...processed.value);
if (lineFeed) index += 1;
continue;
}
LINE_BREAK.lastIndex = index;
const lineBreak = LINE_BREAK.exec(text)?.index ?? text.length;
if (lineBreak > index) {
const segment = text.slice(index, lineBreak);
line += segment;
lineBytes += encoder.encode(segment).byteLength;
if (
lineBytes > resolved.maxLineBytes ||
lineBytes + blockBytes > resolved.maxIncompleteBufferBytes
) {
return fail("EVENT_TOO_LARGE");
}
}
if (lineBreak === text.length) break;
index = lineBreak + 1;
if (text.charCodeAt(lineBreak) === 0x0d) {
pendingCarriageReturn = true;
continue;
}
const processed = processLine(1);
if (!processed.ok) return processed;
items.push(...processed.value);
}
return success(Object.freeze(items));
}
function processLine(
terminatorBytes: number,
): RealtimeResult<readonly SseParserItem[]> {
const currentLine = line;
const currentLineBytes = lineBytes;
line = "";
lineBytes = 0;
if (currentLine.length === 0) {
const items: SseParserItem[] = [];
if (dataLines.length > 0) {
items.push(
Object.freeze({
kind: "EVENT",
eventType: eventType.length > 0 ? eventType : "message",
data: dataLines.join("\n"),
id: lastEventId,
hasExplicitId,
}),
);
}
clearBlock();
return success(Object.freeze(items));
}
if (currentLine.startsWith(":")) return success(COMMENT_ITEMS);
blockBytes += currentLineBytes + terminatorBytes;
if (blockBytes > resolved.maxEventBytes) {
return fail("EVENT_TOO_LARGE");
}
if (blockBytes > resolved.maxIncompleteBufferBytes) {
return fail("EVENT_TOO_LARGE");
}
const separator = currentLine.indexOf(":");
const field =
separator === -1
? currentLine
: currentLine.slice(0, separator);
let value =
separator === -1 ? "" : currentLine.slice(separator + 1);
if (value.startsWith(" ")) value = value.slice(1);
if (field === "data") {
dataLines.push(value);
return success(NO_ITEMS);
}
if (field === "event") {
eventType = value;
return success(NO_ITEMS);
}
if (field === "id") {
if (!value.includes("\0")) {
lastEventId = value;
hasExplicitId = true;
}
return success(NO_ITEMS);
}
if (field === "retry" && /^\d+$/u.test(value)) {
const retryMs = Number(value);
if (
Number.isSafeInteger(retryMs) &&
retryMs <= resolved.maxRetryMs
) {
return success(
Object.freeze([
Object.freeze({ kind: "RETRY" as const, retryMs }),
]),
);
}
}
return success(NO_ITEMS);
}
function clearBlock(): void {
blockBytes = 0;
dataLines = [];
eventType = "";
hasExplicitId = false;
}
function fail(
kind:
| "EVENT_TOO_LARGE"
| "MALFORMED_EVENT"
| "QUEUE_OVERFLOW",
): RealtimeResult<never> {
state = "FAILED";
line = "";
lineBytes = 0;
undrained = "";
clearBlock();
return realtimeFailure(kind, "DECODE");
}
return Object.freeze({ push, drain, finish });
}
function resolveLimits(
input: Partial<SseParserLimits>,
): SseParserLimits {
const limits = {
maxLineBytes:
input.maxLineBytes ?? SSE_PARSER_CEILINGS.maxLineBytes,
maxEventBytes:
input.maxEventBytes ?? SSE_PARSER_CEILINGS.maxEventBytes,
maxIncompleteBufferBytes:
input.maxIncompleteBufferBytes ??
SSE_PARSER_CEILINGS.maxIncompleteBufferBytes,
maxChunkBytes:
input.maxChunkBytes ?? SSE_PARSER_CEILINGS.maxChunkBytes,
maxItemsPerChunk:
input.maxItemsPerChunk ??
SSE_PARSER_CEILINGS.maxItemsPerChunk,
maxRetryMs: input.maxRetryMs ?? SSE_PARSER_CEILINGS.maxRetryMs,
};
if (
!positiveInteger(limits.maxLineBytes) ||
limits.maxLineBytes > SSE_PARSER_CEILINGS.maxLineBytes ||
!positiveInteger(limits.maxEventBytes) ||
limits.maxEventBytes > SSE_PARSER_CEILINGS.maxEventBytes ||
!positiveInteger(limits.maxIncompleteBufferBytes) ||
limits.maxIncompleteBufferBytes >
SSE_PARSER_CEILINGS.maxIncompleteBufferBytes ||
limits.maxIncompleteBufferBytes < limits.maxEventBytes ||
!positiveInteger(limits.maxChunkBytes) ||
limits.maxChunkBytes > SSE_PARSER_CEILINGS.maxChunkBytes ||
limits.maxChunkBytes < limits.maxEventBytes ||
!positiveInteger(limits.maxItemsPerChunk) ||
limits.maxItemsPerChunk >
SSE_PARSER_CEILINGS.maxItemsPerChunk ||
!positiveInteger(limits.maxRetryMs) ||
limits.maxRetryMs > SSE_PARSER_CEILINGS.maxRetryMs
) {
throw new TypeError("Invalid SSE parser limits.");
}
return Object.freeze(limits);
}
function success<Value>(value: Value): RealtimeResult<Value> {
return realtimeSuccess(value);
}
function positiveInteger(value: number): boolean {
return Number.isSafeInteger(value) && value > 0;
}