Files
DongHyeonka ac98facd16
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / merge / static checks (pull_request) Canceled after 42s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / self-tests and removal drills (pull_request) Canceled after 0s
fix(cross-context-invalidation): 듣기 전에 localStorage를 읽어 pulse를 잃지 않는다
문제: Chromium은 탭의 첫 localStorage 읽기에서 그 탭의 캐시를 채우며
변경 observer를 새로 건다(Blink CachedStorageArea::EnsureLoaded). 이때
이미 도착했지만 아직 처리하지 않은 다른 탭의 변경 알림은 버려진다.
storage fallback의 pulse는 쓰자마자 지우므로 채운 캐시에도 흔적이 없어,
받는 탭은 그 무효화를 영영 받지 못한다. browser-capabilities 시험
「falls back to native localStorage events」가 runner run 371과 desktop
부하 20회 중 1회에서 이렇게 실패했다(받은 deliveries []). 받는 page가
바쁠 때 그 page의 첫 읽기(발행 직후의 snapshot, 또는 앱 부트의 설정
읽기)가 쌓인 알림보다 먼저 돌았다. 제품에서도 탭의 다른 코드가 처음
읽는 순간 같은 창이 열린다.

고친 방법: host가 잡은 localStorage를 storage 리스너를 걸기 전에 한 번
읽는다(getItem). 그 뒤의 읽기는 캐시를 다시 채우지 않으므로 observer가
바뀌지 않는다. 읽기가 거절되는 host에서도 리스너는 그대로 건다.
버린 대안:
- 시험만 고치기(발행 전에 받는 page에서 한 번 읽기): 제품의 같은 창을
  남긴다.
- poll 시한 늘리기: 늦는 것이 아니라 잃는 것이라 소용없다.

위험·한계: 런타임을 만들 때 그 origin의 localStorage 전체를 renderer로
한 번 읽는다(Chromium sync GetAll). 앱이 이미 localStorage를 쓰면 추가
비용이 없다. storage service가 다시 연결될 때(ResetConnection)의 손실은
다루지 않는다. 받는 page가 바쁜 동안 다른 탭의 cookie 변경을 보는 것은
Chromium뿐이라, 새 브라우저 시험은 Chromium에서만 받는 page를 붙잡는다.
새 시험은 앱 없는 같은 origin 빈 문서에서 돈다. 앱 부트가 먼저 읽어
받는 탭을 채우면 캐시 채우기를 빼도 통과하기 때문이다.

검증(desktop, scripts/verify.sh exec, 트리 ddda30a3):
- node scripts/run-vitest.ts run tests/unit/cross-tab-invalidation.test.ts
  21 통과
- playwright cross-context-invalidation.spec.ts --repeat-each 5,
  3엔진: 45 통과
- 변이(캐시 채우기 호출 제거, 트리 2f460282): 새 단위 시험 실패,
  새 브라우저 시험 chromium 5/5 실패, 나머지 40 통과
- 고치기 전 탐침(main f3de258d): 받는 page가 막힌 사이 발행하고 같은
  작업에서 첫 읽기 → chromium 5/5 실패, firefox·webkit 10/10 통과.
  리스너 전에 한 번 읽게 한 대조는 15/15 통과

Refs: runner run 371 merge / browser tests
2026-11-19 12:05:54 +09:00

429 lines
13 KiB
TypeScript

import {
expect,
test,
type Page,
} from "../support/browser/strict-browser-test.ts";
const TOPIC = "sample-topic-alpha";
const TOPIC_VERSION = 1;
const STATE_KEY = "__crossContextInvalidationCapability";
const STORAGE_PULSE_KEY =
"ca-frontend:cache-invalidation:v1:pulse";
type BrowserTransportMode = "BROADCAST" | "STORAGE";
type BrowserDeliverySnapshot = Readonly<{
ordering: string;
sequence: number;
topic: string;
transport: string;
}>;
type BrowserRuntimeSnapshot = Readonly<{
status: string;
deliveries: readonly BrowserDeliverySnapshot[];
pulseRetained: boolean;
}>;
async function installRuntime(
page: Page,
mode: BrowserTransportMode,
cacheEpoch: string,
): Promise<string> {
return await page.evaluate(
async ({
currentCacheEpoch,
currentMode,
stateKey,
topic,
topicVersion,
}) => {
const modulePath =
"/src/adapters/cross-context-invalidation/index.ts";
const { createBrowserCrossContextInvalidationFromHost } =
(await import(
/* @vite-ignore */ modulePath
)) as typeof import("../../src/adapters/cross-context-invalidation/index.ts");
const host: Record<string, unknown> =
currentMode === "BROADCAST"
? (globalThis as unknown as Record<string, unknown>)
: {
crypto: globalThis.crypto,
localStorage: globalThis.localStorage,
addEventListener:
globalThis.addEventListener.bind(globalThis),
removeEventListener:
globalThis.removeEventListener.bind(globalThis),
};
const runtime = createBrowserCrossContextInvalidationFromHost({
host,
cacheEpoch: currentCacheEpoch,
topics: [{ topic, topicVersion }],
});
if (!runtime) {
throw new Error(
"Cross-context invalidation runtime is unavailable.",
);
}
const deliveries: BrowserDeliverySnapshot[] = [];
runtime.subscribe((delivery) => {
deliveries.push({
ordering: delivery.ordering,
sequence: delivery.event.sequence,
topic: delivery.event.topic,
transport: delivery.transport,
});
});
Reflect.set(globalThis, stateKey, { deliveries, runtime });
return runtime.getStatus();
},
{
currentCacheEpoch: cacheEpoch,
currentMode: mode,
stateKey: STATE_KEY,
topic: TOPIC,
topicVersion: TOPIC_VERSION,
},
);
}
async function publish(page: Page) {
return await page.evaluate(
({ stateKey, topic, topicVersion }) => {
const state = Reflect.get(globalThis, stateKey) as
| {
runtime: {
publish(input: {
topic: string;
topicVersion: number;
}): unknown;
};
}
| undefined;
if (!state) throw new Error("Capability runtime is not installed.");
return state.runtime.publish({ topic, topicVersion });
},
{
stateKey: STATE_KEY,
topic: TOPIC,
topicVersion: TOPIC_VERSION,
},
);
}
async function snapshot(page: Page): Promise<BrowserRuntimeSnapshot> {
return await page.evaluate(
({ pulseKey, stateKey }) => {
const state = Reflect.get(globalThis, stateKey) as
| {
deliveries: BrowserDeliverySnapshot[];
runtime: { getStatus(): string };
}
| undefined;
if (!state) throw new Error("Capability runtime is not installed.");
return {
status: state.runtime.getStatus(),
deliveries: structuredClone(state.deliveries),
pulseRetained: localStorage.getItem(pulseKey) !== null,
};
},
{ pulseKey: STORAGE_PULSE_KEY, stateKey: STATE_KEY },
);
}
async function closeRuntime(page: Page): Promise<string | null> {
return await page.evaluate((stateKey) => {
const state = Reflect.get(globalThis, stateKey) as
| { runtime: { close(): void; getStatus(): string } }
| undefined;
if (!state) return null;
state.runtime.close();
return state.runtime.getStatus();
}, STATE_KEY);
}
async function disposeRuntime(page: Page): Promise<void> {
await page.evaluate(
({ pulseKey, stateKey }) => {
const state = Reflect.get(globalThis, stateKey) as
| { runtime: { close(): void } }
| undefined;
state?.runtime.close();
localStorage.removeItem(pulseKey);
Reflect.deleteProperty(globalThis, stateKey);
},
{ pulseKey: STORAGE_PULSE_KEY, stateKey: STATE_KEY },
);
}
test("delivers invalidation through native BroadcastChannel and cleans the receiver", async ({
page,
}) => {
const secondPage = await page.context().newPage();
const cacheEpoch = `browser.primary.${Date.now()}`;
try {
await Promise.all([page.goto("/"), secondPage.goto("/")]);
await page.evaluate(
(pulseKey) => localStorage.removeItem(pulseKey),
STORAGE_PULSE_KEY,
);
const statuses = await Promise.all([
installRuntime(page, "BROADCAST", cacheEpoch),
installRuntime(secondPage, "BROADCAST", cacheEpoch),
]);
expect(statuses).toEqual([
"ACTIVE_BROADCAST",
"ACTIVE_BROADCAST",
]);
expect(await publish(page)).toEqual({
ok: true,
transport: "BROADCAST",
});
await expect
.poll(async () => (await snapshot(secondPage)).deliveries)
.toEqual([
{
ordering: "NEXT",
sequence: 1,
topic: TOPIC,
transport: "BROADCAST",
},
]);
expect((await snapshot(page)).deliveries).toEqual([]);
expect(await closeRuntime(secondPage)).toBe("CLOSED");
expect(await publish(page)).toEqual({
ok: true,
transport: "BROADCAST",
});
await page.waitForTimeout(100);
expect(await snapshot(secondPage)).toEqual({
status: "CLOSED",
deliveries: [
{
ordering: "NEXT",
sequence: 1,
topic: TOPIC,
transport: "BROADCAST",
},
],
pulseRetained: false,
});
} finally {
await Promise.allSettled([
disposeRuntime(page),
disposeRuntime(secondPage),
]);
await secondPage.close();
}
});
test("falls back to native localStorage events and removes the pulse during cleanup", async ({
page,
}) => {
const secondPage = await page.context().newPage();
const cacheEpoch = `browser.fallback.${Date.now()}`;
try {
await Promise.all([page.goto("/"), secondPage.goto("/")]);
await page.evaluate(
(pulseKey) => localStorage.removeItem(pulseKey),
STORAGE_PULSE_KEY,
);
const statuses = await Promise.all([
installRuntime(page, "STORAGE", cacheEpoch),
installRuntime(secondPage, "STORAGE", cacheEpoch),
]);
expect(statuses).toEqual([
"ACTIVE_STORAGE_FALLBACK",
"ACTIVE_STORAGE_FALLBACK",
]);
expect(await publish(page)).toEqual({
ok: true,
transport: "STORAGE",
});
await expect
.poll(async () => (await snapshot(secondPage)).deliveries)
.toEqual([
{
ordering: "NEXT",
sequence: 1,
topic: TOPIC,
transport: "STORAGE",
},
]);
expect(await snapshot(page)).toMatchObject({
deliveries: [],
pulseRetained: false,
});
expect(await snapshot(secondPage)).toMatchObject({
pulseRetained: false,
});
expect(await closeRuntime(secondPage)).toBe("CLOSED");
expect(await publish(page)).toEqual({
ok: true,
transport: "STORAGE",
});
await page.waitForTimeout(100);
expect(await snapshot(secondPage)).toEqual({
status: "CLOSED",
deliveries: [
{
ordering: "NEXT",
sequence: 1,
topic: TOPIC,
transport: "STORAGE",
},
],
pulseRetained: false,
});
} finally {
await Promise.allSettled([
disposeRuntime(page),
disposeRuntime(secondPage),
]);
await secondPage.close();
}
});
// 2026-11-19, runner run 371. Chromium loads a tab's localStorage cache on the
// tab's first read, and the load drops the change notifications from other
// tabs that have arrived but not run yet (Blink CachedStorageArea::EnsureLoaded).
// A pulse is removed as soon as it is written, so the test above lost it when
// the receiver was busy as the pulse arrived and the receiver's first read (the
// snapshot, or the app's boot reading a preference) ran before the queued
// notifications. Here the receiver stays busy until the publisher is done and
// then reads localStorage for the first time in the same task, as other code
// in the tab would. Only Chromium lets a busy page see another tab's cookie
// change, so only there does the receiver wait for the publisher's cookie; the
// other engines read at once and check the same delivery.
//
// Both pages are a blank same-origin document, not the app: the app's boot
// reads localStorage on its own schedule, and a read before the test's would
// prime the receiver whether or not the runtime does.
const BLANK_DOCUMENT_PATH = "/__cross-context-capability-blank";
async function gotoBlankDocument(target: Page): Promise<void> {
await target.route(`**${BLANK_DOCUMENT_PATH}`, (route) =>
route.fulfill({
contentType: "text/html",
body: '<!doctype html><link rel="icon" href="data:,"><title>cross-context capability</title>',
}),
);
await target.goto(BLANK_DOCUMENT_PATH);
}
test("keeps a pulse that reaches a busy receiver before other code first reads localStorage", async ({
page,
browserName,
}) => {
const secondPage = await page.context().newPage();
const cacheEpoch = `browser.busy.${Date.now()}`;
const signal = `cross-context-busy-${Date.now()}`;
try {
await Promise.all([
gotoBlankDocument(page),
gotoBlankDocument(secondPage),
]);
await page.evaluate(
(pulseKey) => localStorage.removeItem(pulseKey),
STORAGE_PULSE_KEY,
);
const statuses = await Promise.all([
installRuntime(page, "STORAGE", cacheEpoch),
installRuntime(secondPage, "STORAGE", cacheEpoch),
]);
expect(statuses).toEqual([
"ACTIVE_STORAGE_FALLBACK",
"ACTIVE_STORAGE_FALLBACK",
]);
// The publisher publishes as soon as the receiver says it is busy, then
// sets the cookie the busy receiver waits for.
await page.evaluate(
({ currentSignal, stateKey, topic, topicVersion }) => {
const state = Reflect.get(globalThis, stateKey) as {
runtime: {
publish(input: { topic: string; topicVersion: number }): unknown;
};
published?: Promise<unknown>;
};
const channel = new BroadcastChannel(currentSignal);
state.published = new Promise((resolve) => {
channel.addEventListener(
"message",
() => {
channel.close();
const result = state.runtime.publish({ topic, topicVersion });
document.cookie = `${currentSignal}=published; path=/`;
resolve(result);
},
{ once: true },
);
});
},
{
currentSignal: signal,
stateKey: STATE_KEY,
topic: TOPIC,
topicVersion: TOPIC_VERSION,
},
);
const firstRead = secondPage.evaluate(
({ currentSignal, holdBusy }) => {
const channel = new BroadcastChannel(currentSignal);
channel.postMessage("busy");
if (holdBusy) {
// The publisher's cookie ends the wait. The guard only turns a
// publisher that never answers into a message before the test
// timeout.
const guard = performance.now() + 20_000;
while (!document.cookie.includes(`${currentSignal}=published`)) {
if (performance.now() > guard) {
throw new Error(
"the publisher's cookie never reached the busy receiver",
);
}
}
}
channel.close();
return localStorage.getItem("cross-context-busy-receiver:other-code");
},
{ currentSignal: signal, holdBusy: browserName === "chromium" },
);
// Awaited together, so a receiver that gives up waiting fails the test
// with its own message instead of leaving the publisher's wait to time out.
const [published, read] = await Promise.all([
page.evaluate(
(stateKey) =>
(Reflect.get(globalThis, stateKey) as { published: Promise<unknown> })
.published,
STATE_KEY,
),
firstRead,
]);
expect(published).toEqual({ ok: true, transport: "STORAGE" });
expect(read).toBeNull();
await expect
.poll(async () => (await snapshot(secondPage)).deliveries)
.toEqual([
{
ordering: "NEXT",
sequence: 1,
topic: TOPIC,
transport: "STORAGE",
},
]);
} finally {
await Promise.allSettled([
disposeRuntime(page),
disposeRuntime(secondPage),
]);
await secondPage.close();
}
});