Files
tech-log-frontend/tests/unit/realtime/event-consumer.test.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

402 lines
12 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import type {
RealtimeAcceptDisposition,
RealtimeRecoveryCheckpoint,
} from "../../../src/application/ports/realtime/event-authority.ts";
import type {
RealtimeResult,
} from "../../../src/application/ports/realtime/shared.ts";
import {
createRealtimeEventConsumer,
} from "../../../src/adapters/realtime/event-consumer.ts";
import type {
RealtimeEventCodec,
ValidatedRealtimeEventDto,
} from "../../../src/adapters/realtime/event-codec.ts";
import {
realtimeFailure,
realtimeSuccess,
} from "../../../src/adapters/realtime/result.ts";
import {
createRealtimeStreamCoordinator,
type RealtimeStreamCoordinator,
} from "../../../src/adapters/realtime/stream-coordinator.ts";
import {
createFetchSseConnection,
} from "../../../src/adapters/realtime/sse/fetch-sse-connection.ts";
import {
STREAM_ID,
TEST_MAPPERS,
createTestRealtimeCodec,
createTestRealtimeRegistry,
realtimeEventJson,
} from "./fixture.ts";
function setup(
recoveryMode:
| "CURSOR"
| "SNAPSHOT_ONLY"
| "SESSION_REBUILD",
resumeCursor: string | null,
) {
const dto = {
envelope: {
recoveryMode,
resumeCursor,
streamId: "REFERENCE_STREAM",
},
} as ValidatedRealtimeEventDto;
const codec: RealtimeEventCodec = {
decode: vi.fn(() => realtimeSuccess(dto)),
};
const accept = vi.fn<
(
event: ValidatedRealtimeEventDto,
signal?: AbortSignal,
) => Promise<RealtimeResult<RealtimeAcceptDisposition>>
>(() =>
Promise.resolve(
realtimeSuccess({
outcome: "DROPPED" as const,
reason: "DUPLICATE_EVENT" as const,
}),
),
);
const consumer = createRealtimeEventConsumer({
codec,
coordinator: {
accept,
} as Pick<RealtimeStreamCoordinator, "accept">,
});
return { consumer, accept, codec };
}
describe("realtime transport event consumer", () => {
it("requires exact equality between SSE id and CURSOR envelope", async () => {
const matching = setup("CURSOR", "cursor.0001");
await expect(
matching.consumer.consume("{}", {
kind: "SSE_DIRECT_CURSOR",
eventId: "cursor.0001",
}),
).resolves.toMatchObject({ ok: true });
expect(matching.accept).toHaveBeenCalledTimes(1);
const advanced = setup("CURSOR", "cursor.0002");
await expect(
advanced.consumer.consume("{}", {
kind: "SSE_DIRECT_CURSOR",
eventId: "cursor.0001",
}),
).resolves.toEqual(
realtimeFailure("PROTOCOL_MISMATCH", "RECEIVE"),
);
expect(advanced.accept).not.toHaveBeenCalled();
});
it("forbids SSE id semantics for non-CURSOR recovery", async () => {
const runtime = setup("SNAPSHOT_ONLY", null);
await expect(
runtime.consumer.consume("{}", {
kind: "SSE_NO_CURSOR",
}),
).resolves.toMatchObject({ ok: true });
await expect(
runtime.consumer.consume("{}", {
kind: "SSE_DIRECT_CURSOR",
eventId: "cursor.0001",
}),
).resolves.toEqual(
realtimeFailure("PROTOCOL_MISMATCH", "RECEIVE"),
);
});
it("serializes an encapsulated WebSocket envelope through the codec", async () => {
const runtime = setup("SESSION_REBUILD", null);
await expect(
runtime.consumer.consumeEncapsulated(
Object.freeze({ protocol: "REALTIME_EVENT_V1" }),
),
).resolves.toMatchObject({ ok: true });
expect(runtime.codec.decode).toHaveBeenCalledWith(
'{"protocol":"REALTIME_EVENT_V1"}',
);
});
it("projects common dispositions into the canonical transport outcome", async () => {
const runtime = setup("SNAPSHOT_ONLY", null);
await expect(
runtime.consumer.consumeForTransport("{}", {
kind: "SSE_NO_CURSOR",
}),
).resolves.toEqual({
ok: true,
value: { kind: "CONTINUE" },
});
const checkpoint = Object.freeze({
recoveryMode: "SNAPSHOT_ONLY" as const,
streamEpoch: "stream-epoch.0001",
lastAppliedSequence: "0",
resumeCursor: null,
}) as RealtimeRecoveryCheckpoint;
runtime.accept.mockResolvedValueOnce(
realtimeSuccess({
outcome: "RECOVERED",
reason: "INITIALIZE",
resumeState: checkpoint,
}),
);
await expect(
runtime.consumer.consumeForTransport("{}", {
kind: "SSE_NO_CURSOR",
}),
).resolves.toEqual({
ok: true,
value: {
kind: "RECOVERY_COMMITTED",
streamId: "REFERENCE_STREAM",
checkpoint,
},
});
runtime.accept.mockResolvedValueOnce(
realtimeSuccess({
outcome: "DROPPED",
reason: "RECOVERY_IN_PROGRESS",
}),
);
await expect(
runtime.consumer.consumeForTransport("{}", {
kind: "SSE_NO_CURSOR",
}),
).resolves.toEqual(
realtimeFailure("PROTOCOL_MISMATCH", "RECEIVE"),
);
runtime.accept.mockResolvedValueOnce(
realtimeSuccess({
outcome: "DROPPED",
reason: "SCOPE_FENCED",
}),
);
await expect(
runtime.consumer.consumeForTransport("{}", {
kind: "SSE_NO_CURSOR",
}),
).resolves.toEqual(
realtimeFailure("SCOPE_FENCED", "RECEIVE"),
);
});
it("threads transport cancellation into the common authority", async () => {
const runtime = setup("SNAPSHOT_ONLY", null);
const active = new AbortController();
await runtime.consumer.consume(
"{}",
{ kind: "SSE_NO_CURSOR" },
active.signal,
);
expect(runtime.accept).toHaveBeenLastCalledWith(
expect.anything(),
active.signal,
);
const aborted = new AbortController();
aborted.abort();
await expect(
runtime.consumer.consume(
"{}",
{ kind: "SSE_NO_CURSOR" },
aborted.signal,
),
).resolves.toEqual(
realtimeFailure("ABORTED", "RECEIVE"),
);
expect(runtime.accept).toHaveBeenCalledTimes(1);
});
});
describe("SSE transport, consumer and stream coordinator together", () => {
it("keeps reading after a SNAPSHOT_ONLY recovery that needs no transport barrier", async () => {
const registry = createTestRealtimeRegistry({
recovery: {
mode: "SNAPSHOT_ONLY",
snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
checkpointCodecId: "ReferenceRealtimeCheckpoint",
barrier: "NONE",
},
delivery: "INVALIDATION_HINT",
stateBearing: false,
});
const snapshots = ["0", "3"];
const recoveries: string[] = [];
const apply = vi.fn(async () => realtimeSuccess(undefined));
const coordinator = createRealtimeStreamCoordinator({
registry,
mappers: TEST_MAPPERS,
authority: {
effects: { apply },
recovery: {
async recover(request) {
recoveries.push(request.reason);
const sequence = snapshots.shift() ?? "0";
return realtimeSuccess({
kind: "SNAPSHOT_RESET",
checkpoint: {
recoveryMode: "SNAPSHOT_ONLY",
streamEpoch: "stream-epoch-0001",
lastAppliedSequence: sequence,
resumeCursor: null,
snapshotRevision: `snapshot-revision-${sequence}`,
},
});
},
},
},
scope: {
generation: 7,
scopeBinding: "scope-binding-0001",
isCurrent: () => true,
},
now: () => 10_000,
});
const consumer = createRealtimeEventConsumer({
codec: createTestRealtimeCodec(registry),
coordinator,
});
await expect(
coordinator.recover(STREAM_ID, "INITIALIZE"),
).resolves.toMatchObject({ ok: true });
const frame = (sequence: string) =>
`data: ${realtimeEventJson({
eventId: `event-0000000${sequence}`,
sequence,
recoveryMode: "SNAPSHOT_ONLY",
resumeCursor: null,
})}\n\n`;
const body = [frame("1"), frame("3"), frame("4")].join("");
const connection = createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "SNAPSHOT_ONLY",
fetcher: async () =>
new Response(body, {
status: 200,
headers: { "Content-Type": "text/event-stream" },
}),
});
// Sequence 3 is a gap: the coordinator recovers to snapshot 3, and the
// stream must keep reading so sequence 4 still applies.
const closed = await connection.read({
resumeCursor: null,
onEvent: (event, signal) =>
consumer.consumeForTransport(
event.data,
{ kind: "SSE_NO_CURSOR" },
signal,
),
});
expect(closed).toMatchObject({ ok: true, value: { kind: "EOF" } });
expect(recoveries).toEqual(["INITIALIZE", "SEQUENCE_GAP"]);
expect(apply).toHaveBeenCalledTimes(2);
expect(coordinator.getResumeState(STREAM_ID)).toMatchObject({
lastAppliedSequence: "4",
});
expect(coordinator.inspect(STREAM_ID).awaitingTransportBarrier).toBe(
false,
);
});
it("ends on an unregistered event type as a registry mismatch and leaves freshness UNKNOWN", async () => {
const registry = createTestRealtimeRegistry({
recovery: {
mode: "SNAPSHOT_ONLY",
snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
checkpointCodecId: "ReferenceRealtimeCheckpoint",
barrier: "NONE",
},
delivery: "INVALIDATION_HINT",
stateBearing: false,
});
const apply = vi.fn(async () => realtimeSuccess(undefined));
const coordinator = createRealtimeStreamCoordinator({
registry,
mappers: TEST_MAPPERS,
authority: {
effects: { apply },
recovery: {
recover: async () =>
realtimeSuccess({
kind: "SNAPSHOT_RESET",
checkpoint: {
recoveryMode: "SNAPSHOT_ONLY",
streamEpoch: "stream-epoch-0001",
lastAppliedSequence: "0",
resumeCursor: null,
snapshotRevision: "snapshot-revision-0",
},
}),
},
},
scope: {
generation: 7,
scopeBinding: "scope-binding-0001",
isCurrent: () => true,
},
now: () => 10_000,
});
const consumer = createRealtimeEventConsumer({
codec: createTestRealtimeCodec(registry),
coordinator,
});
await expect(
coordinator.recover(STREAM_ID, "INITIALIZE"),
).resolves.toMatchObject({ ok: true });
// A newer backend added an event type this bundle does not know.
const frame = (sequence: string, eventType?: string) =>
`data: ${realtimeEventJson({
eventId: `event-0000000${sequence}`,
sequence,
recoveryMode: "SNAPSHOT_ONLY",
resumeCursor: null,
...(eventType === undefined ? {} : { eventType }),
})}\n\n`;
const body = frame("1") + frame("2", "ADDED_BY_NEWER_BACKEND");
const connection = createFetchSseConnection({
endpoint: "https://app.example.test/events",
applicationOrigin: "https://app.example.test",
recoveryMode: "SNAPSHOT_ONLY",
fetcher: async () =>
new Response(body, {
status: 200,
headers: { "Content-Type": "text/event-stream" },
}),
});
const closed = await connection.read({
resumeCursor: null,
onEvent: (event, signal) =>
consumer.consumeForTransport(
event.data,
{ kind: "SSE_NO_CURSOR" },
signal,
),
});
expect(apply).toHaveBeenCalledOnce();
expect(closed).toEqual(
realtimeFailure("PROTOCOL_MISMATCH", "REGISTRY", false),
);
expect(coordinator.inspect(STREAM_ID).freshness).toBe("UNKNOWN");
});
});