Merge lane/T: object id grammar at every write, SW start telemetry wiring test (05-10, 06-05)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-28 00:59:08 +09:00
co-authored by Claude Opus 5.5
5 changed files with 261 additions and 8 deletions
+13 -5
View File
@@ -106,14 +106,22 @@ type은 facade 밖으로 노출하지 않는다.
SSOT다. 문서와 catalog가 다르면 gate가 검사하는 catalog를 우선 고치고 이 표도
같이 갱신한다.
Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·2·6만 갖고 있다.
Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6과 2의 시작 실패
이벤트만 갖고 있다.
1. `src/features/installed-runtime-capabilities.ts`의 `SERVICE_WORKER`를
`ACTIVE`로 바꾼다. `scripts/build-frontend.ts`가 worker 빌드를 추가로 돈다.
2. 관측: `createRuntimeComposition`이 텔레메트리 포트를 optional host에 넘긴다.
시작 결과가 `FAILED`나 `INCOMPATIBLE`이면 `service-worker.start.failed`가 1건
남는다(`src/bootstrap/optional-runtime-host.ts`). 업데이트 설치 실패와 page
controller의 `observe`는 아직 어디에도 연결되지 않는다.
2. 관측: `createRuntimeComposition`이 텔레메트리 포트를 optional host에 넘긴다
(`src/bootstrap/create-runtime-composition.ts`). 시작 결과가 `FAILED`나
`INCOMPATIBLE`이면 `service-worker.start.failed`가 1건 남는다
(`src/bootstrap/optional-runtime-host.ts`). 실제 composition에서 첫 설치가
실패하면 이벤트가 1건 나가는 것은
`tests/component/runtime-composition-service-worker-telemetry.test.ts`가
확인한다. 템플릿이 연결하지 않은 것은 셋이다. 업데이트 설치 실패
(`watchForUpdates`, `src/adapters/service-worker/service-worker-page-controller.ts`)는
이벤트를 남기지 않는다. page controller의 `observe`는 composition이 넘기지
않는다. `OptionalRuntimeHost.health()`는 `src` 안에서 읽는 코드가 없다.
필요하면 다운스트림이 `createRuntimeComposition`에서 연결한다.
3. blockers: 저장하지 않은 편집이 있는 탭이 활성화를 거절하게
`createOptionalRuntimeHost`에 `blockers`를 넘긴다. 템플릿은 넘기지 않는다.
4. 활성화 UI: `ServiceWorkerRuntimeHost.onUpdateWaiting`을 구독하고, 사용자가
+15 -2
View File
@@ -131,7 +131,9 @@ export function assertOpfsRuntimePolicy(policy: OpfsRuntimePolicy): void {
* 05-10. Stored prepared objects, journal rows and physical paths all use the
* opaque id grammar, so a policy may narrow it but never widen it: a wider
* policy let BEGIN through and failed every put at its last step. Ids just
* outside the grammar catch the usual widenings when the policy is resolved.
* outside the grammar catch the usual widenings when the policy is resolved;
* writes also check the grammar itself (isWritableObjectId), so a widening no
* sample finds is refused at BEGIN instead.
*/
const OBJECT_IDS_OUTSIDE_GRAMMAR = Object.freeze([
"",
@@ -141,6 +143,9 @@ const OBJECT_IDS_OUTSIDE_GRAMMAR = Object.freeze([
"object.12345",
"object/12345",
"object~12345",
"object:12345",
"object@12345",
"objekt_\u00e4\u00f6\u00fc12",
]);
function widensObjectIdGrammar(
@@ -159,6 +164,14 @@ export function isOpaqueObjectId(value: string): boolean {
return OPAQUE_OBJECT_ID.test(value);
}
/** 05-10. The policy may narrow the id grammar for writes, never widen it. */
export function isWritableObjectId(
policy: OpfsRuntimePolicy,
objectId: string,
): boolean {
return OPAQUE_OBJECT_ID.test(objectId) && policy.isObjectIdAllowed(objectId);
}
export function validateObjectWriteInput(
input: Readonly<{
scope: OpfsStorageScope;
@@ -179,7 +192,7 @@ export function validateObjectWriteInput(
return (
isValidOpfsStorageScope(input.scope) &&
input.scope.namespace === input.storagePolicy.namespace &&
policy.isObjectIdAllowed(input.objectId) &&
isWritableObjectId(policy, input.objectId) &&
policy.isMediaTypeAllowed(input.mediaType) &&
(input.expectedGeneration === null ||
(Number.isSafeInteger(input.expectedGeneration) &&
@@ -14,6 +14,7 @@ import { createAbortableOperation } from "../../platform/abortable-operation.ts"
import {
resolveOpfsRuntimePolicy,
isValidOpfsStorageScope,
isWritableObjectId,
type OpfsRuntimePolicy,
} from "./opfs-policy.ts";
import { isPreparedObject, stableJson } from "./opfs-prepared-object.ts";
@@ -328,7 +329,7 @@ export function createOpfsWorkerRuntime(
if (
!SAFE_TRANSACTION_ID.test(request.transactionId) ||
!isValidOpfsStorageScope(request.scope) ||
!dependencies.policy.isObjectIdAllowed(request.objectId) ||
!isWritableObjectId(dependencies.policy, request.objectId) ||
!Number.isSafeInteger(request.generation) ||
request.generation < 1 ||
!isPhysicalGenerationId(request.physicalGenerationId) ||
@@ -0,0 +1,169 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts";
/**
* 06-05. The optional host reports a Service Worker that did not start, but
* only if the composition hands it the application's telemetry port. This
* test runs the real composition with an ACTIVE selection and a first install
* that fails, and records what reaches the telemetry adapter.
*/
const emitted = vi.hoisted(
() => [] as Array<readonly [string, Record<string, unknown>]>,
);
vi.mock("../../src/features/installed-runtime-capabilities.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-runtime-capabilities.ts")>();
return {
INSTALLED_RUNTIME_CAPABILITIES: Object.freeze({
...original.INSTALLED_RUNTIME_CAPABILITIES,
serviceWorker: Object.freeze({
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: Object.freeze(["PWA_STATIC_ASSETS"]),
}),
}),
};
});
vi.mock("../../src/adapters/telemetry/index.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/adapters/telemetry/index.ts")>();
return {
...original,
createTelemetryAdapter: (
options: Parameters<typeof original.createTelemetryAdapter>[0],
) => {
const adapter = original.createTelemetryAdapter(options);
return Object.freeze({
...adapter,
emit(eventName: string, attributes: Record<string, unknown>) {
emitted.push([eventName, attributes]);
adapter.emit(eventName as never, attributes);
},
});
},
};
});
const origin = "http://localhost";
const runtimeConfig = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 2,
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "1",
API_CONTRACT_VERSION: "1",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
};
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
releaseId: "local-release",
builtAt: "2026-07-26T00:00:00.000Z",
routeChunks: {
"route-home": "assets/home.js",
"route-examples-ui": "assets/ui.js",
"route-examples-states": "assets/states.js",
"route-examples-auth": "assets/auth.js",
"route-not-found": "assets/not-found.js",
},
};
async function fetcher(input: RequestInfo | URL): Promise<Response> {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.href
: input.url;
return Response.json(
url.includes("release-manifest") ? releaseManifest : runtimeConfig,
);
}
/** A first install whose worker turns `redundant` (install event rejected). */
function failingInstallContainer(): ServiceWorkerContainer {
const register = vi.fn(
async (scriptURL: string | URL, options?: RegistrationOptions) => {
const installing = {
scriptURL: new URL(scriptURL, origin).href,
state: "installing",
addEventListener(type: string, listener: () => void) {
if (type !== "statechange") return;
queueMicrotask(() => {
installing.state = "redundant";
listener();
});
},
removeEventListener() {},
};
return {
scope: new URL(options?.scope ?? "/", origin).href,
installing,
waiting: null,
active: null,
addEventListener() {},
removeEventListener() {},
update: vi.fn(async () => {}),
} as unknown as ServiceWorkerRegistration;
},
);
return {
controller: null,
register,
getRegistration: vi.fn(async () => undefined),
getRegistrations: vi.fn(async () => []),
addEventListener() {},
removeEventListener() {},
} as unknown as ServiceWorkerContainer;
}
describe("06-05 runtime composition reports a Service Worker install failure", () => {
afterEach(() => {
emitted.length = 0;
});
it("emits exactly one service-worker.start.failed through the application telemetry port", async () => {
const container = failingInstallContainer();
const composition = await createRuntimeComposition({
fetcher,
host: {
location: { origin },
navigator: { serviceWorker: container },
},
});
try {
await composition.optional.startAfterMount();
expect(container.register).toHaveBeenCalledTimes(1);
expect(composition.optional.health().serviceWorker).toBe("DEGRADED");
expect(
emitted.filter(([eventName]) => eventName.startsWith("service-worker.")),
).toEqual([
[
"service-worker.start.failed",
{ error_kind: "INSTALL_FAILED", build_id: "local-build" },
],
]);
} finally {
await composition.dispose();
}
});
});
+62
View File
@@ -2453,6 +2453,68 @@ describe("05-10 the object id grammar is the prepared-object grammar", () => {
}),
).toThrow(TypeError);
});
it.each([
["a colon", /^[A-Za-z0-9_:-]{8,128}$/u],
["an at sign", /^[A-Za-z0-9_@-]{8,128}$/u],
["Unicode letters", /^[\p{L}0-9_-]{8,128}$/u],
])("rejects a policy that also allows %s when it is resolved", (_, grammar) => {
expect(() =>
resolveOpfsRuntimePolicy({
...runtimePolicy,
isObjectIdAllowed: (objectId) => grammar.test(objectId),
}),
).toThrow(TypeError);
});
// A predicate can widen the grammar in ways no sample finds. The grammar
// still applies at BEGIN_PUT, so such an id never reaches FINISH_PUT.
const widenedId = "object:tenant@12345";
const widenedPolicy = (): typeof runtimePolicy => ({
...runtimePolicy,
isObjectIdAllowed: (objectId) =>
objectId === widenedId || runtimePolicy.isObjectIdAllowed(objectId),
});
it("refuses an id outside the grammar at BEGIN_PUT even if the policy allows it", async () => {
const runtime = createOpfsWorkerRuntime({
root: new MemoryDirectory() as unknown as FileSystemDirectoryHandle,
crypto: globalThis.crypto,
policy: widenedPolicy(),
leaseManager: immediateLeases({ count: 0 }),
dedicatedWorker: true,
supportsSynchronousAccessHandles: false,
});
expectFailureCode(
await runtime.handleRequest({
...beginRequest("request_begin_1234", "transaction_12345678", scopeA),
objectId: widenedId,
} as OpfsWorkerRequest),
"INVALID_INPUT",
);
});
it("fails such a put as invalid input before it writes, never as corrupt data", async () => {
const { tab, root } = sharedRootTabs(widenedPolicy());
const adapter = tab("a");
expect(
await adapter.objects.put({
objectId: widenedId,
expectedGeneration: null,
mediaType: "application/octet-stream",
source: oneByteSource(),
}),
).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
expect(root.children.size).toBe(0);
expect(await adapter.objects.put({
objectId: "object_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: oneByteSource(),
})).toMatchObject({ ok: true });
});
});
describe("05-14 a read that outlives its generation", () => {