From 8e0ea60eaceaa580b615f46cb57d472bd94c9774 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:33:48 +0900 Subject: [PATCH] =?UTF-8?q?perf(tech-log):=20MOCK=20=EC=86=8C=EC=8A=A4?= =?UTF-8?q?=EC=99=80=20Studio=20gateway=EB=A5=BC=20=EC=B2=AB=20=EC=82=AC?= =?UTF-8?q?=EC=9A=A9=20=EB=95=8C=20=EB=B0=9B=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 런타임 문서가 MOCK·HTTP를 고르므로 두 소스가 모든 빌드에 들어간다. 기능 입력 조립(create-tech-log-feature-input.ts)이 MOCK 공개 콘텐츠, MOCK·HTTP Studio gateway를 정적으로 가져와, 운영(HTTP) 공개 화면을 여는 사람도 그 코드를 초기 JS로 받았다. MOCK이 쓰는 content-format은 마크다운 파서(micromark·mdast·unified)까지 끌고 왔다. 초기 JS는 main 에서 300,869 B(gzip)로 예산 204,800 B를 넘는다(FE-GATE-012). 고른 방법 - 포트는 이미 모두 Promise를 돌려준다. deferAsyncPort가 포트를 먼저 만들고 첫 호출에서 구현 모듈을 동적 import해 넘긴다. 호출하는 쪽과 feature input의 모양(publicContent, createStudioApplication)은 그대로다. - 포트 키 목록은 `Record`로 적어, 포트에 메서드가 늘거나 줄면 타입 검사가 실패한다. - 구현 받기에 실패하면 잊고 다음 호출에서 다시 받는다. - MOCK 공개 콘텐츠는 첫 조회 때 받는다. HTTP 공개 gateway는 공개 첫 화면의 데이터 요청에 쓰이므로 그대로 둔다. - Studio gateway 셋(MOCK이면 Studio state 하나를 나눠 씀)은 묶음 하나로 받는다(mock-studio-gateways.ts, http-studio-gateways.ts). createStudioApplication은 Studio가 마운트될 때 불리므로 그때 바로 받기 시작한다(startNow). 첫 조회 때 받으면 화면 청크 → 조회 → gateway 청크 → 요청으로 한 번 더 기다린다. 버린 대안 - createStudioApplication을 async로 바꾸기: StudioProvider와 시험 15곳이 함께 바뀐다. 포트가 이미 비동기라 필요 없다. - 공개 HTTP gateway도 지연 로드: 첫 화면 데이터 요청 앞에 청크 왕복이 하나 생긴다. 위험·한계 - MOCK 빌드(로컬·e2e·visual)는 첫 공개 조회와 첫 Studio 조회 앞에 청크를 한 번 받는다. - 포트 메서드가 동기 값을 돌려주게 바뀌면 이 방식은 맞지 않는다. 타입 제약(모든 멤버가 Promise를 돌려줌)이 그때 컴파일에서 막는다. 검증 - desktop CI env 빌드: 초기 JS 300,869 → 232,337 B(Studio 셸 지연을 포함한 측정, 다음 커밋). 빠진 모듈 179개 중 npm(마크다운 파서) 약 88 KB, mock 23 KB, static 11 KB(모듈 단독 gzip 합). - tests/features/tech-log/deferred-async-port.test.ts: 한 번만 받기, 동시 첫 호출, 실패 뒤 다시 받기, 키·freeze, gateway 셋의 state 공유, startNow. --- .../adapters/create-tech-log-feature-input.ts | 72 +++++---- .../tech-log/adapters/deferred-async-port.ts | 39 +++++ .../adapters/deferred-tech-log-ports.ts | 137 ++++++++++++++++++ .../adapters/http/http-studio-gateways.ts | 33 +++++ .../adapters/mock/mock-studio-gateways.ts | 21 +++ .../tech-log/deferred-async-port.test.ts | 112 ++++++++++++++ 6 files changed, 375 insertions(+), 39 deletions(-) create mode 100644 src/features/tech-log/adapters/deferred-async-port.ts create mode 100644 src/features/tech-log/adapters/deferred-tech-log-ports.ts create mode 100644 src/features/tech-log/adapters/http/http-studio-gateways.ts create mode 100644 src/features/tech-log/adapters/mock/mock-studio-gateways.ts create mode 100644 tests/features/tech-log/deferred-async-port.test.ts diff --git a/src/features/tech-log/adapters/create-tech-log-feature-input.ts b/src/features/tech-log/adapters/create-tech-log-feature-input.ts index dd19d1a..e2a6232 100644 --- a/src/features/tech-log/adapters/create-tech-log-feature-input.ts +++ b/src/features/tech-log/adapters/create-tech-log-feature-input.ts @@ -6,17 +6,12 @@ import type { Asset } from "../contracts/studio/contract.ts"; import { createTechLogStudioApplication } from "../application/studio-application.ts"; import type { InstalledHttpOperationExecutor } from "../../../adapters/http/index.ts"; import { createTechLogHttpBinding } from "./http/tech-log-http-binding.ts"; -import { createAssetUploadTransport } from "./http/asset-upload-transport.ts"; -import { createHttpStudioAssetGateway } from "./http/http-studio-asset-gateway.ts"; -import { createHttpStudioGateway } from "./http/http-studio-gateway.ts"; import type { CsrfTokenProvider } from "./http/studio-session-csrf.ts"; -import { createMockStudioAssetGateway } from "./mock/mock-studio-asset-gateway.ts"; -import { createMockManagementGateway } from "./mock/mock-management-gateway.ts"; -import { createMockStudioState } from "./mock/mock-state.ts"; -import { createMockStudioGateway } from "./mock/mock-studio-gateway.ts"; -import { createHttpManagementGateway } from "./http/http-management-gateway.ts"; import { createHttpPublicContentGateway } from "./http/http-public-content-gateway.ts"; -import { publicContentQueries } from "./static/public-query.ts"; +import { + deferPublicContentQueries, + deferStudioGateways, +} from "./deferred-tech-log-ports.ts"; /** * The HTTP gateway builds no headers of its own — `Idempotency-Key` comes @@ -55,26 +50,18 @@ export function createTechLogFeatureInstalledInput( const mockAssets = new Map(); const http = createTechLogHttpBinding(context.http); - - const createStudioAssetGateway = () => - context.studioSource === "MOCK" - ? createMockStudioAssetGateway(mockAssets) - : createHttpStudioAssetGateway({ - http, - csrf: context.csrf, - upload: createAssetUploadTransport({ - baseUrl: context.apiBaseUrl, - timeoutMs: context.requestTimeoutMs, - }), - }); - - // The public read source switches independently of Studio: the two are // different services, and the combination that matters today is an authoring // backend that is live while the public read API is not. + // + // FE-GATE-012. Both sources ship in every build (the runtime document picks + // one), so the MOCK content is loaded on its first query instead of riding + // the initial JavaScript of a production page that reads HTTP. const publicContent = context.publicSource === "MOCK" - ? publicContentQueries + ? deferPublicContentQueries( + async () => (await import("./static/public-query.ts")).publicContentQueries, + ) : createHttpPublicContentGateway({ http }); // MOCK: one in-memory Studio state per application, shared by the document @@ -82,21 +69,28 @@ export function createTechLogFeatureInstalledInput( // also takes it out of the document list. Management used to be HTTP even // here, and a MOCK build (local development, the e2e and visual builds) // asked an API that is not there for its topics and projects. - const createStudioApplication = () => { - if (context.studioSource === "MOCK") { - const state = createMockStudioState(); - return createTechLogStudioApplication({ - studio: createMockStudioGateway({ assets: mockAssets, state }), - assets: createStudioAssetGateway(), - management: createMockManagementGateway({ studioState: state }), - }); - } - return createTechLogStudioApplication({ - studio: createHttpStudioGateway({ http }), - assets: createStudioAssetGateway(), - management: createHttpManagementGateway({ http }), - }); - }; + // + // FE-GATE-012. Studio's gateways, MOCK or HTTP, are a chunk of their own. + // StudioProvider calls this when Studio mounts, so the chunk starts loading + // then, next to the page chunk, rather than on the first query. Each call + // still gets its own set (and, for MOCK, its own state). + const createStudioApplication = () => + createTechLogStudioApplication( + deferStudioGateways( + async () => + context.studioSource === "MOCK" + ? (await import("./mock/mock-studio-gateways.ts")).createMockStudioGateways( + mockAssets, + ) + : (await import("./http/http-studio-gateways.ts")).createHttpStudioGateways({ + http, + csrf: context.csrf, + apiBaseUrl: context.apiBaseUrl, + requestTimeoutMs: context.requestTimeoutMs, + }), + { startNow: true }, + ), + ); const input: TechLogFeatureInput = Object.freeze({ publicContent, diff --git a/src/features/tech-log/adapters/deferred-async-port.ts b/src/features/tech-log/adapters/deferred-async-port.ts new file mode 100644 index 0000000..23213d0 --- /dev/null +++ b/src/features/tech-log/adapters/deferred-async-port.ts @@ -0,0 +1,39 @@ +type AsyncMethods = { + readonly [Key in keyof Port]: (...args: never[]) => Promise; +}; + +/** + * 모든 멤버가 Promise 를 돌려주는 포트를, 구현 모듈을 받기 전에 만든다. + * + * 부팅 그래프가 MOCK gateway·정적 공개 콘텐츠·Studio gateway 를 정적으로 가져와, 운영 + * 공개 화면을 여는 사람도 그 코드를 전부 초기 JS 로 받았다(FE-GATE-012). 포트는 이미 + * 비동기라, 첫 호출에서 구현을 받고 넘겨 주면 호출하는 쪽은 바뀌지 않는다. + * + * - `methods` 는 포트의 키 전부다. 타입이 빠진 키와 남는 키를 막는다. + * - 구현은 한 번만 받는다. 받기에 실패하면 잊고 다음 호출에서 다시 받는다 — 청크를 한 번 + * 못 받았다고 그 세션 내내 실패하지 않는다. + */ +export function deferAsyncPort>( + load: () => Promise, + methods: Readonly>, +): Port { + let loaded: Promise | undefined; + const target = (): Promise => { + loaded ??= load().catch((error: unknown) => { + loaded = undefined; + throw error; + }); + return loaded; + }; + const port: Record Promise> = {}; + for (const name of Object.keys(methods)) { + port[name] = async (...args: unknown[]) => { + const implementation = await target(); + const method = implementation[name as keyof Port] as unknown as ( + ...methodArgs: unknown[] + ) => Promise; + return method.apply(implementation, args); + }; + } + return Object.freeze(port) as unknown as Port; +} diff --git a/src/features/tech-log/adapters/deferred-tech-log-ports.ts b/src/features/tech-log/adapters/deferred-tech-log-ports.ts new file mode 100644 index 0000000..c104ffd --- /dev/null +++ b/src/features/tech-log/adapters/deferred-tech-log-ports.ts @@ -0,0 +1,137 @@ +import type { PublicContentQueries } from "../application/ports/public-content-queries.ts"; +import type { ManagementGateway } from "../application/ports/management-gateway.ts"; +import type { StudioAssetGateway } from "../application/ports/studio-asset-gateway.ts"; +import type { StudioGateway } from "../application/ports/studio-gateway.ts"; +import { deferAsyncPort } from "./deferred-async-port.ts"; + +/* + 포트마다 키 전부다. `Record` 라 포트에 메서드가 늘거나 줄면 타입 검사가 + 여기서 실패한다. +*/ +const PUBLIC_CONTENT_QUERY_METHODS = Object.freeze({ + listRecords: true, + getRecord: true, + getProject: true, + getRelease: true, + getProjectRecords: true, + getProjectDecisions: true, + getProjectActivity: true, + listTopics: true, + listContacts: true, + getTopicDetail: true, + getHome: true, + listProjects: true, + listReleases: true, + listCatalog: true, + getLatestEntries: true, + getHomeFocusItems: true, + searchPublicContent: true, +} as const satisfies Record); + +const STUDIO_GATEWAY_METHODS = Object.freeze({ + getDashboard: true, + listDocuments: true, + createDocument: true, + getDocument: true, + saveDocument: true, + validateDocument: true, + createPreview: true, + getCurrentPreview: true, + publishDocument: true, + unpublishPublication: true, + listPublications: true, + getPublicationSnapshot: true, + getCatalog: true, +} as const satisfies Record); + +const STUDIO_ASSET_GATEWAY_METHODS = Object.freeze({ + listAssets: true, + uploadAsset: true, + getAsset: true, + updateAssetMetadata: true, + deleteAsset: true, +} as const satisfies Record); + +const MANAGEMENT_GATEWAY_METHODS = Object.freeze({ + listTopics: true, + createTopic: true, + updateTopic: true, + deleteTopic: true, + listTopicVariants: true, + createTopicVariant: true, + updateTopicVariant: true, + deleteTopicVariant: true, + listProjects: true, + listQuestions: true, + listProjectDecisions: true, + getProject: true, + createProject: true, + updateProject: true, + deleteProject: true, + publishProject: true, + unpublishProject: true, + listProjectActivities: true, + createProjectActivity: true, + updateProjectActivity: true, + deleteProjectActivity: true, + getHomeFocus: true, + updateHomeFocus: true, + listReleases: true, + getRelease: true, + createRelease: true, + updateRelease: true, + deleteRelease: true, + publishRelease: true, + archiveRelease: true, + deleteDocument: true, + deleteDecision: true, +} as const satisfies Record); + +export function deferPublicContentQueries( + load: () => Promise, +): PublicContentQueries { + return deferAsyncPort(load, PUBLIC_CONTENT_QUERY_METHODS); +} + +export type StudioGateways = Readonly<{ + studio: StudioGateway; + assets: StudioAssetGateway; + management: ManagementGateway; +}>; + +/** + * Studio gateway 셋을 한 번에 받는다. 셋이 같은 구현 묶음(MOCK 이면 같은 Studio state)을 + * 써야 해서, 묶음 하나를 받고 각 포트가 그 안의 자기 gateway 로 넘긴다. + * + * `startNow` 면 첫 호출을 기다리지 않고 바로 받기 시작한다. Studio 가 마운트될 때 만들어지므로, + * 첫 조회 때 받으면 화면 청크 → 조회 → gateway 청크 → 요청으로 한 번 더 기다린다. 미리 받다 + * 실패해도 여기서 삼키고, 첫 호출이 다시 받는다. + */ +export function deferStudioGateways( + load: () => Promise, + { startNow = false }: Readonly<{ startNow?: boolean }> = {}, +): StudioGateways { + let loaded: Promise | undefined; + const gateways = (): Promise => { + loaded ??= load().catch((error: unknown) => { + loaded = undefined; + throw error; + }); + return loaded; + }; + if (startNow) void gateways().catch(() => undefined); + return Object.freeze({ + studio: deferAsyncPort( + async () => (await gateways()).studio, + STUDIO_GATEWAY_METHODS, + ), + assets: deferAsyncPort( + async () => (await gateways()).assets, + STUDIO_ASSET_GATEWAY_METHODS, + ), + management: deferAsyncPort( + async () => (await gateways()).management, + MANAGEMENT_GATEWAY_METHODS, + ), + }); +} diff --git a/src/features/tech-log/adapters/http/http-studio-gateways.ts b/src/features/tech-log/adapters/http/http-studio-gateways.ts new file mode 100644 index 0000000..a13a3ad --- /dev/null +++ b/src/features/tech-log/adapters/http/http-studio-gateways.ts @@ -0,0 +1,33 @@ +import { createAssetUploadTransport } from "./asset-upload-transport.ts"; +import { createHttpManagementGateway } from "./http-management-gateway.ts"; +import { createHttpStudioAssetGateway } from "./http-studio-asset-gateway.ts"; +import { createHttpStudioGateway } from "./http-studio-gateway.ts"; +import type { CsrfTokenProvider } from "./studio-session-csrf.ts"; +import type { TechLogHttpBinding } from "./tech-log-http-binding.ts"; + +export type HttpStudioGatewaysContext = Readonly<{ + http: TechLogHttpBinding; + csrf: CsrfTokenProvider; + apiBaseUrl: string; + requestTimeoutMs: number; +}>; + +/** + * HTTP Studio 의 gateway 셋. Studio 에 들어갈 때 받는 청크다 + * (`create-tech-log-feature-input.ts`). 공개 화면은 이 코드를 쓰지 않는다. + */ +export function createHttpStudioGateways(context: HttpStudioGatewaysContext) { + const { http } = context; + return Object.freeze({ + studio: createHttpStudioGateway({ http }), + assets: createHttpStudioAssetGateway({ + http, + csrf: context.csrf, + upload: createAssetUploadTransport({ + baseUrl: context.apiBaseUrl, + timeoutMs: context.requestTimeoutMs, + }), + }), + management: createHttpManagementGateway({ http }), + }); +} diff --git a/src/features/tech-log/adapters/mock/mock-studio-gateways.ts b/src/features/tech-log/adapters/mock/mock-studio-gateways.ts new file mode 100644 index 0000000..d138366 --- /dev/null +++ b/src/features/tech-log/adapters/mock/mock-studio-gateways.ts @@ -0,0 +1,21 @@ +import type { Asset } from "../../contracts/studio/contract.ts"; +import { createMockManagementGateway } from "./mock-management-gateway.ts"; +import { createMockStudioAssetGateway } from "./mock-studio-asset-gateway.ts"; +import { createMockStudioState } from "./mock-state.ts"; +import { createMockStudioGateway } from "./mock-studio-gateway.ts"; + +/** + * MOCK Studio 의 gateway 셋. Studio 에 들어갈 때 받는 청크다 + * (`create-tech-log-feature-input.ts`). + * + * 문서 gateway 와 관리 gateway 는 Studio state 하나를 나눠 쓴다 — 관리 화면에서 작업본을 + * 지우면 문서 목록에서도 빠진다. Asset 저장소는 앱 하나에 하나라 호출하는 쪽이 넘긴다. + */ +export function createMockStudioGateways(assets: Map) { + const state = createMockStudioState(); + return Object.freeze({ + studio: createMockStudioGateway({ assets, state }), + assets: createMockStudioAssetGateway(assets), + management: createMockManagementGateway({ studioState: state }), + }); +} diff --git a/tests/features/tech-log/deferred-async-port.test.ts b/tests/features/tech-log/deferred-async-port.test.ts new file mode 100644 index 0000000..09b8b95 --- /dev/null +++ b/tests/features/tech-log/deferred-async-port.test.ts @@ -0,0 +1,112 @@ +import assert from "node:assert/strict"; +import { test } from "vitest"; + +import { deferAsyncPort } from "../../../src/features/tech-log/adapters/deferred-async-port.ts"; +import { deferStudioGateways } from "../../../src/features/tech-log/adapters/deferred-tech-log-ports.ts"; +import { createMockStudioGateways } from "../../../src/features/tech-log/adapters/mock/mock-studio-gateways.ts"; +import { FIXTURE_IDS } from "../../../src/features/tech-log/adapters/mock/fixtures.ts"; +import type { Asset } from "../../../src/features/tech-log/contracts/studio/contract.ts"; + +type Greeter = Readonly<{ + greet(name: string): Promise; + count(): Promise; +}>; + +function greeterImplementation(): Greeter { + let calls = 0; + return { + async greet(name) { + calls += 1; + return `hello ${name}`; + }, + async count() { + return calls; + }, + }; +} + +const GREETER_METHODS = { greet: true, count: true } as const; + +test("구현을 첫 호출에서 한 번만 받고 모든 메서드가 같은 구현을 쓴다", async () => { + let loads = 0; + const port = deferAsyncPort(async () => { + loads += 1; + return greeterImplementation(); + }, GREETER_METHODS); + + assert.equal(loads, 0, "만들기만 해서는 구현을 받지 않는다"); + assert.equal(await port.greet("a"), "hello a"); + assert.equal(await port.greet("b"), "hello b"); + assert.equal(await port.count(), 2); + assert.equal(loads, 1); +}); + +test("동시에 들어온 첫 호출들도 구현을 한 번만 받는다", async () => { + let loads = 0; + const port = deferAsyncPort(async () => { + loads += 1; + await Promise.resolve(); + return greeterImplementation(); + }, GREETER_METHODS); + + await Promise.all([port.greet("a"), port.greet("b"), port.count()]); + assert.equal(loads, 1); +}); + +test("구현을 받지 못하면 그 호출은 실패하고 다음 호출에서 다시 받는다", async () => { + let loads = 0; + const port = deferAsyncPort(async () => { + loads += 1; + if (loads === 1) throw new TypeError("Failed to fetch dynamically imported module"); + return greeterImplementation(); + }, GREETER_METHODS); + + await assert.rejects(port.greet("a"), /dynamically imported module/u); + assert.equal(await port.greet("b"), "hello b"); + assert.equal(loads, 2); +}); + +test("포트는 선언한 메서드만 가진 얼린 객체다", () => { + const port = deferAsyncPort(async () => greeterImplementation(), GREETER_METHODS); + + assert.deepEqual(Object.keys(port).sort(), ["count", "greet"]); + assert.equal(Object.isFrozen(port), true); +}); + +test("Studio gateway 셋은 구현 묶음 하나를 같이 쓴다", async () => { + let loads = 0; + const assets = new Map(); + const gateways = deferStudioGateways(async () => { + loads += 1; + return createMockStudioGateways(assets); + }); + + assert.equal(loads, 0); + const draft = (await gateways.studio.getDocument(FIXTURE_IDS.conflictCase)).document; + await gateways.management.deleteDocument("CASE", draft.id, draft.version, { + idempotencyKey: "deferred-shared-state", + }); + // 관리 gateway 로 지운 작업본이 같은 묶음의 문서 gateway 에서도 사라진다. + await assert.rejects(gateways.studio.getDocument(FIXTURE_IDS.conflictCase)); + await gateways.assets.listAssets({}); + assert.equal(loads, 1); +}); + +test("startNow 면 만들 때 받기 시작하고, 그때의 실패는 첫 호출이 다시 받는다", async () => { + let loads = 0; + const assets = new Map(); + const gateways = deferStudioGateways( + async () => { + loads += 1; + if (loads === 1) throw new TypeError("Failed to fetch dynamically imported module"); + return createMockStudioGateways(assets); + }, + { startNow: true }, + ); + + assert.equal(loads, 1, "만들자마자 받기 시작한다"); + // 미리 받기의 실패가 처리된 뒤 첫 호출이 들어온다. + await new Promise((resolve) => setTimeout(resolve, 0)); + await gateways.studio.getDashboard(); + assert.equal(loads, 2); +});