Files
Gnuboard7/tests/Playwright/specs/smoke/bootstrap-request-dedup.spec.ts
T
HeuJung 5ba7a83597 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
2026-08-25 17:02:53 +09:00

121 lines
4.9 KiB
TypeScript

/**
* 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);
});
});