feat(core,engine): 부트스트랩 리소스 정적 게시(bake) 및 폴백 체계 도입

공개 제보 https://github.com/gnuboard/g7/issues/122 대응 — 초기 부트스트랩
리소스(다국어 병합·컴포넌트 정의·라우트·확장 번들·템플릿 dist)를 캐시 버전
디렉토리(public/build/ext/{v}/)에 실파일로 게시해 웹서버가 rewrite 전에 직접
서빙한다. 부트 임계 경로의 PHP 왕복을 제거하고(실측 TTFB 131~144ms → 1~7ms),
미게시·부분게시·GC 직후에는 fetch·태그·번들 3계층이 종전 API 로 즉시 폴백한다.

- 게시: 원자적 tmp→rename→manifest(존재=완료), 캐시 락 단일 실행, 인라인 GC
 (현재+직전 1개), incrementExtensionCacheVersion 단일 지점 terminating 트리거
 + blade 자가 치유 + 설치기 태스크(best_effort) + 일일 cleanup 스케줄,
 sudo 업데이트 대비 소유권 정상화(normalizeOwnership)·prune/백업 제외
- 프론트(engine-v1.61.0): blade 주입 cache_version 1급 시드(이중 부트 로드 제거),
 fetchStaticFirst 즉시 폴백, ComponentRegistry 버전 키드 매니페스트,
 ModuleAssetLoader 번들 정적→레거시 폴백, asset-url-recovery staticToLegacy 역변환
- 폴백 API 품질: lang/components/routes ETag+304 + 환경 분기 Cache-Control,
 열화 라우트 스냅샷 공개 캐시 금지(서버측 캐시 회피와 대칭), 게시 .htaccess
 mod_deflate + nginx gzip 스니펫(압축 전송량 회귀 방지)
- SEO 정합: 봇 HTML 은 GC 대상 정적 URL 미사용(allowStatic:false), props $switch
 봇측 해석 구현(engine-v1.56.0 패리티), 패리티 룰 expression-dialect 그룹 신설,
 상주 allow 헤더 제거로 잠금 복원, _comment* 접두 주석 키 분류
- 검증: 전 수정 red→green 4단계, Playwright 라이브 21건, Chrome MCP 24축+M1~M3,
 봇 curl 3축, 캐시 저장소(file/redis/database) 축 판정, 히스토리·공개이슈·커밋
 이력 전수 재조사 반영
- 코어 7.0.10, engine-v1.61.0. kill-switch: G7_STATIC_CACHE=false
This commit is contained in:
HeuJung committed 2026-08-25 17:02:53 +09:00
1 parent 56836a2b66
commit 5ba7a83597
73 files changed
+4219 -98

No files matched your search

@@ -0,0 +1,120 @@
/**
* Smoke: stale 캐시버전 재방문의 부트 이중 로드 제거 (#122 작업 A·B)
*
* localStorage `g7_cache_version` 이 stale 이면 첫 burst 가 구버전 `?v` 로 나가고,
* config 핸드셰이크가 routes 재로드 + lang(ko·en, `_=` 버스터) 재다운로드를 유발해
* ~500KB 중복 / 부트 ~1.3s 연장이 발생했다. blade 주입 cache_version 시드가
* 이를 제거했음을 실브라우저에서 잠근다.
*
* @scenario publish_state=published, environment=production, trigger=lifecycle
* @effects no_duplicate_boot_requests, versioned_boot_urls
*/
import { test, expect, type Page } from '@playwright/test';
/**
* 부트 리소스 URL 판별 — 정적 게시 경로와 API 경로(이중 모드 포함)를 모두 흡수한다.
*
* 확장자 형태만 매칭하면 정적 게시가 켜진 사이트에서 카운터가 0 이 되어
* 테스트가 조용히 무의미해진다 (network-resilience.spec.ts 의 suffixedPath 확장).
*/
function bootResourceMatchers(pathname: string): { routes: boolean; lang: string | null; components: boolean } {
const routes =
/^\/build\/ext\/\d+\/templates\/[^/]+\/routes\.json$/.test(pathname) ||
/^\/api\/templates\/[^/]+\/routes(\.json)?$/.test(pathname);
const staticLang = pathname.match(/^\/build\/ext\/\d+\/templates\/[^/]+\/lang\/([a-z-]+)\.json$/);
const apiLang = pathname.match(/^\/api\/templates\/[^/]+\/lang\/([a-z-]+)(\.json)?$/);
const lang = staticLang?.[1] ?? apiLang?.[1] ?? null;
const components =
/^\/build\/ext\/\d+\/templates\/[^/]+\/components\.json$/.test(pathname) ||
/^\/api\/templates\/[^/]+\/components(\.json)?$/.test(pathname);
return { routes, lang, components };
}
/** 페이지의 부트 리소스 요청을 수집한다 */
function collectBootRequests(page: Page) {
const routesUrls: string[] = [];
const langUrls = new Map<string, string[]>();
const componentUrls: string[] = [];
const busterUrls: string[] = [];
page.on('request', (request) => {
const url = new URL(request.url());
const { routes, lang, components } = bootResourceMatchers(url.pathname);
if (routes) routesUrls.push(request.url());
if (lang) langUrls.set(lang, [...(langUrls.get(lang) ?? []), request.url()]);
if (components) componentUrls.push(request.url());
if (/[?&]_=\d+/.test(url.search)) busterUrls.push(request.url());
});
return { routesUrls, langUrls, componentUrls, busterUrls };
}
test.describe('부트 이중 로드 제거 (#122)', () => {
test('@smoke stale localStorage 재방문 — routes 1회·lang 로케일당 1회·`_=` 0건·버전드 URL', async ({ page }) => {
// stale 캐시버전 시드 (재방문자 시뮬레이션 — 종전엔 이중 로드 트리거)
await page.addInitScript(() => {
try {
window.localStorage.setItem('g7_cache_version', '1');
} catch {
/* localStorage 불가 환경은 시드 없이 진행 */
}
});
const collected = collectBootRequests(page);
await page.goto('/');
await page.waitForFunction(
() => (document.querySelector('#app')?.childElementCount ?? 0) > 0,
{ timeout: 30_000 }
);
await page.waitForLoadState('networkidle', { timeout: 30_000 });
// routes 는 정확히 1회 (핸드셰이크 재로드 부재)
expect(collected.routesUrls, `routes 요청: ${collected.routesUrls.join(', ')}`).toHaveLength(1);
// lang 은 로케일당 1회
for (const [locale, urls] of collected.langUrls) {
expect(urls, `lang/${locale} 요청: ${urls.join(', ')}`).toHaveLength(1);
}
// `_=` 캐시 버스터 재로드 0건
expect(collected.busterUrls, `버스터 요청: ${collected.busterUrls.join(', ')}`).toHaveLength(0);
// 부트 리소스 URL 은 버전 기반 (정적 경로 `/build/ext/{v}/` 또는 `?v=`)
const bootUrls = [...collected.routesUrls, ...collected.componentUrls];
for (const url of bootUrls) {
expect(
/\/build\/ext\/\d+\//.test(url) || /[?&]v=\d+/.test(url),
`버전 없는 부트 URL: ${url}`
).toBe(true);
}
// localStorage 는 서버 버전으로 치유된다
const healed = await page.evaluate(() => ({
stored: window.localStorage.getItem('g7_cache_version'),
injected: (window as any).G7Config?.cache_version,
}));
expect(healed.stored).toBe(String(healed.injected));
});
test('@smoke 치유 후 재로드 — 요청 구성이 동일하고 이중 로드가 없다', async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle', { timeout: 30_000 });
const collected = collectBootRequests(page);
await page.reload();
await page.waitForFunction(
() => (document.querySelector('#app')?.childElementCount ?? 0) > 0,
{ timeout: 30_000 }
);
await page.waitForLoadState('networkidle', { timeout: 30_000 });
expect(collected.routesUrls.length).toBeLessThanOrEqual(1);
expect(collected.busterUrls).toHaveLength(0);
});
});
@@ -71,6 +71,20 @@ async function bodyText(page: Page): Promise<string> {
return page.evaluate(() => document.body.innerText.trim().replace(/\n+/g, ' | '));
}
/**
* 정적 게시(bake, #122) fast path 강제 미스.
*
* 정적 게시가 완료된 프로덕션 사이트에서는 routes/components/lang/번들이
* `/build/ext/{v}/…` 를 먼저 타므로, `/api/**` 패턴 인터셉트가 한 건도 걸리지
* 않은 채 이 스펙 전체가 무력화된다 (suffixedPath 3형태 밖의 4번째 URL 형태).
* 이 스펙의 검증 대상은 **API 폴백 경로의 복원력**이므로 정적 요청을 404 로
* 강제해 앱 자체 폴백(fetchStaticFirst / staticToLegacy)이 API 계층으로
* 내려보내게 한다. 미게시 사이트에서는 `/build/ext/**` 요청이 없어 무해하다.
*/
test.beforeEach(async ({ page }) => {
await page.route('**/build/ext/**', (route) => route.fulfill({ status: 404, body: '' }));
});
test.describe('네트워크 복원력 — 요청 1건의 일시 실패 (#463)', () => {
// 각 경로의 첫 요청 1건을 취소해도 재시도로 복구되어 앱이 정상 렌더돼야 한다.
const SINGLE_ABORT_PATHS: Array<{ name: string; pattern: string | ((url: URL) => boolean) }> = [
@@ -220,6 +234,19 @@ test.describe('네트워크 복원력 — 번들이 끝내 부재할 때 (#463)'
},
);
// 게시(bake) 사이트에서는 blade 가 이 번들을 정적 URL 로 방출하고, 그 1회가
// MAX_ATTEMPTS 예산의 첫 슬롯을 소비한다 (L2 — 예산 신설 금지, staticToLegacy 는
// 남은 예산으로 API 형태에 합류). 정적 시도를 따로 세어 총 예산으로 단언한다.
let staticAttempts = 0;
await page.route(
(url) => /\/build\/ext\/.*components\.iife\.js/.test(url.pathname),
(route) => {
staticAttempts += 1;
return route.fulfill({ status: 404, body: '' });
},
);
await page.goto('/');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await page.waitForFunction(
@@ -234,8 +261,9 @@ test.describe('네트워크 복원력 — 번들이 끝내 부재할 때 (#463)'
expect(text).toMatch(FALLBACK_UI);
await expect(page.locator('#app button')).toBeVisible();
// 재시도 3시도 (초기 1 + 재시도 2)
expect(attempts).toBe(3);
// 총 3시도 (초기 1 + 재시도 2) — 게시 사이트는 정적 1 + API 2, 미게시는 API 3.
// 합산 정확값으로 잠가 과잉 재시도(예산 신설) 회귀를 양쪽 세계에서 차단한다.
expect(attempts + staticAttempts).toBe(3);
});
/**
@@ -0,0 +1,112 @@
/**
* Smoke: 정적 게시(bake) fast path + API 폴백 (#122 S2·S3)
*
* 정적 게시가 켜진 프로덕션 사이트에서 ① 부트 리소스가 `/build/ext/{v}/…` 로
* 수신되고 ② 정적 응답을 브라우저단에서 404 로 강제해도 legacy API 폴백으로
* 화면이 정상 렌더됨을 잠근다. 서버 파일 조작이 없으므로 원복이 불필요하다.
*
* env 가드 — 대상 사이트가 정적 게시 미적용(비프로덕션/kill-switch/미게시)이면
* staticBase 미주입으로 skip 된다 (첫 방문이 자가 치유를 예약하므로 워밍 1회 수행).
*
* @scenario publish_state=partial, environment=production, trigger=self_heal
* @effects static_first_fetch_falls_back_to_api_on_miss, fallback_is_observable_via_console_warn
*/
import { test, expect, type Page } from '@playwright/test';
/** 대상 사이트의 staticBase 주입 여부 (자가 치유 워밍 포함) */
async function probeStaticBase(page: Page): Promise<string | null> {
await page.goto('/');
await page.waitForLoadState('networkidle', { timeout: 30_000 });
let base = await page.evaluate(() => (window as any).G7Config?.staticBase ?? null);
if (!base) {
// 미게시 상태였다면 방금 렌더가 terminating 게시를 예약했다 — 1회 재방문
await page.waitForTimeout(3_000);
await page.reload();
await page.waitForLoadState('networkidle', { timeout: 30_000 });
base = await page.evaluate(() => (window as any).G7Config?.staticBase ?? null);
}
return typeof base === 'string' ? base : null;
}
test.describe('정적 게시 fast path + 폴백 (#122)', () => {
/**
* @scenario publish_state=published, environment=production, trigger=self_heal
* @effects versioned_boot_urls
*/
test('@smoke 정적 URL 로 부트 리소스를 수신한다 (static-first)', async ({ page }) => {
const staticUrls: string[] = [];
page.on('request', (request) => {
if (new URL(request.url()).pathname.startsWith('/build/ext/')) {
staticUrls.push(request.url());
}
});
const base = await probeStaticBase(page);
test.skip(base === null, '대상 사이트에 정적 게시 미적용 (staticBase 미주입)');
await page.reload();
await page.waitForFunction(
() => (document.querySelector('#app')?.childElementCount ?? 0) > 0,
{ timeout: 30_000 }
);
await page.waitForLoadState('networkidle', { timeout: 30_000 });
// 정적 게시 경로에서 부트 리소스를 실제로 받는다
expect(staticUrls.length, `정적 경로 수신: ${staticUrls.join(', ')}`).toBeGreaterThan(0);
expect(staticUrls.some((u) => /\/templates\/[^/]+\/routes\.json/.test(u))).toBe(true);
});
test('@smoke 정적 응답을 404 로 강제해도 legacy API 폴백으로 화면이 정상 렌더된다', async ({ page }) => {
const base = await probeStaticBase(page);
test.skip(base === null, '대상 사이트에 정적 게시 미적용 (staticBase 미주입)');
const warns: string[] = [];
page.on('console', (message) => {
if (message.type() === 'warning') warns.push(message.text());
});
let aborted = 0;
const apiFallbacks: string[] = [];
// 정적 fetch 리소스(routes/lang/components)만 404 강제 — 태그 자산(CSS/JS)은
// 파일 게이트가 이미 통과시킨 실파일이므로 건드리지 않는다 (렌더 자체를 위한 것)
await page.route(
(url) => /\/build\/ext\/\d+\/templates\/[^/]+\/(routes|components|lang\/[a-z-]+)\.json$/.test(url.pathname),
(route) => {
aborted += 1;
return route.fulfill({ status: 404, body: 'forced miss' });
}
);
page.on('request', (request) => {
const path = new URL(request.url()).pathname;
if (/^\/api\/templates\/[^/]+\/(routes|components|lang\/[a-z-]+)(\.json)?$/.test(path)) {
apiFallbacks.push(request.url());
}
});
await page.reload();
await page.waitForFunction(
() => (document.querySelector('#app')?.childElementCount ?? 0) > 0,
{ timeout: 30_000 }
);
await page.waitForLoadState('networkidle', { timeout: 30_000 });
// 정적 미스가 실제로 발생했고
expect(aborted).toBeGreaterThan(0);
// legacy API 폴백이 그 자리를 메웠으며
expect(apiFallbacks.length, `API 폴백: ${apiFallbacks.join(', ')}`).toBeGreaterThan(0);
// 화면은 전면 에러 없이 정상이다
const text = await page.evaluate(() => document.body.innerText.trim());
expect(text).not.toMatch(/초기화 실패|페이지 로딩 실패/);
expect(text.length).toBeGreaterThan(20);
// 폴백은 조용하지 않다 — console warn 으로 관측 가능
expect(warns.some((w) => w.includes('fetchStaticFirst')), `warns: ${warns.join(' | ')}`).toBe(true);
});
});