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

@@ -911,4 +911,71 @@ class LayoutServingTest extends TestCase
// 메시지도 raw UTF-8 (레이아웃 제공 성공 메시지)
$this->assertMatchesRegularExpression('/[가-힣]/u', $body);
}
/**
* 프로덕션에서 레이아웃 응답은 공개 캐시 헤더를 유지한다 (#122 작업 D — successWithCache 환경 분기 동반 효과)
*
* @effects fallback_api_serves_etag_304
*/
public function test_layout_has_public_cache_headers_in_production(): void
{
app()['env'] = 'production';
$template = Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$layout = TemplateLayout::create([
'template_id' => $template->id,
'name' => 'dashboard',
'content' => ['meta' => [], 'data_sources' => [], 'components' => []],
]);
$response = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
$response->assertStatus(200);
$this->assertNotNull($response->headers->get('ETag'));
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringContainsString('public', $cacheControl);
$this->assertStringContainsString('max-age=3600', $cacheControl);
}
/**
* 개발 환경에서 레이아웃 응답은 no-cache (dev 레이아웃 반영성 — #122 작업 D 환경 분기)
*
* @effects fallback_api_no_cache_in_dev
*/
public function test_layout_no_cache_in_development(): void
{
app()['env'] = 'local';
$template = Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$layout = TemplateLayout::create([
'template_id' => $template->id,
'name' => 'dashboard',
'content' => ['meta' => [], 'data_sources' => [], 'components' => []],
]);
$response = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
$response->assertStatus(200);
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringContainsString('no-cache', $cacheControl);
$this->assertStringNotContainsString('max-age=3600', $cacheControl);
}
}
@@ -0,0 +1,183 @@
<?php
namespace Tests\Feature\Api\Public;
use App\Enums\ExtensionStatus;
use App\Models\Module;
use App\Models\Plugin;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* 모듈/플러그인 components.json 서빙의 폴백 API 캐시 계약 (#122 작업 C).
*
* `cachedJsonResponse` 가 ETag/304 조건부 캐시와 환경 분기(prod: public
* max-age / dev: no-cache)를 적용하는지 검증한다. 정적 게시본(fast path)
* 미스 시 이 API 가 폴백 경로이므로, 폴백 품질이 곧 미게시 상태의 부트 성능이다.
*/
class PublicComponentsCachingTest extends TestCase
{
use RefreshDatabase;
private string $moduleIdentifier;
private string $pluginIdentifier;
protected function setUp(): void
{
parent::setUp();
$this->moduleIdentifier = 'test-module'.uniqid();
$this->pluginIdentifier = 'test-plugin'.uniqid();
Module::factory()->create([
'identifier' => $this->moduleIdentifier,
'status' => ExtensionStatus::Active->value,
]);
Plugin::factory()->create([
'identifier' => $this->pluginIdentifier,
'status' => ExtensionStatus::Active->value,
]);
mkdir(base_path("modules/{$this->moduleIdentifier}"), 0755, true);
file_put_contents(
base_path("modules/{$this->moduleIdentifier}/components.json"),
json_encode(['composite' => ['TestWidget' => ['path' => 'components/TestWidget.tsx']]])
);
mkdir(base_path("plugins/{$this->pluginIdentifier}"), 0755, true);
file_put_contents(
base_path("plugins/{$this->pluginIdentifier}/components.json"),
json_encode(['composite' => ['TestPanel' => ['path' => 'components/TestPanel.tsx']]])
);
}
protected function tearDown(): void
{
foreach ([
base_path("modules/{$this->moduleIdentifier}"),
base_path("plugins/{$this->pluginIdentifier}"),
] as $dir) {
if (file_exists($dir)) {
array_map('unlink', glob($dir.'/*') ?: []);
rmdir($dir);
}
}
parent::tearDown();
}
/**
* 프로덕션: 200 응답에 ETag + public max-age + Vary 부착
*/
public function test_module_components_has_etag_and_cache_headers_in_production(): void
{
app()['env'] = 'production';
$response = $this->getJson("/api/modules/{$this->moduleIdentifier}/components.json");
$response->assertStatus(200);
$this->assertNotNull($response->headers->get('ETag'));
$cacheControl = $response->headers->get('Cache-Control');
$this->assertStringContainsString('public', $cacheControl);
$this->assertStringContainsString('max-age=3600', $cacheControl);
$this->assertStringContainsString('Accept-Encoding', (string) $response->headers->get('Vary'));
}
/**
* 프로덕션: If-None-Match 일치 시 304 (본문 미전송)
*
* @effects fallback_api_serves_etag_304
*/
public function test_module_components_returns_304_with_matching_etag(): void
{
app()['env'] = 'production';
$first = $this->getJson("/api/modules/{$this->moduleIdentifier}/components.json");
$etag = $first->headers->get('ETag');
$this->assertNotNull($etag);
$second = $this->getJson(
"/api/modules/{$this->moduleIdentifier}/components.json",
['If-None-Match' => $etag]
);
$second->assertStatus(304);
$this->assertSame('', $second->getContent());
$this->assertSame($etag, $second->headers->get('ETag'));
$this->assertStringContainsString('max-age=3600', (string) $second->headers->get('Cache-Control'));
}
/**
* 개발: no-cache (파일 수정 즉시 반영 — 브라우저 1h 캐시 비대칭 해소 F10)
*/
public function test_module_components_no_cache_in_development(): void
{
app()['env'] = 'local';
$response = $this->getJson("/api/modules/{$this->moduleIdentifier}/components.json");
$response->assertStatus(200);
$this->assertStringContainsString('no-cache', (string) $response->headers->get('Cache-Control'));
$this->assertStringNotContainsString('max-age=3600', (string) $response->headers->get('Cache-Control'));
}
/**
* 플러그인도 동일 계약 (200 헤더 + 304)
*/
public function test_plugin_components_caching_contract(): void
{
app()['env'] = 'production';
$first = $this->getJson("/api/plugins/{$this->pluginIdentifier}/components.json");
$first->assertStatus(200);
$etag = $first->headers->get('ETag');
$this->assertNotNull($etag);
$this->assertStringContainsString('max-age=3600', (string) $first->headers->get('Cache-Control'));
$second = $this->getJson(
"/api/plugins/{$this->pluginIdentifier}/components.json",
['If-None-Match' => $etag]
);
$second->assertStatus(304);
}
/**
* 플러그인도 개발 환경에서는 no-cache (모듈과 동일 축 — 한쪽만 잠그면 비대칭이 남는다)
*/
public function test_plugin_components_no_cache_in_development(): void
{
app()['env'] = 'local';
$response = $this->getJson("/api/plugins/{$this->pluginIdentifier}/components.json");
$response->assertStatus(200);
$this->assertStringContainsString('no-cache', (string) $response->headers->get('Cache-Control'));
$this->assertStringNotContainsString('max-age=3600', (string) $response->headers->get('Cache-Control'));
}
/**
* 내용 변경 시 ETag 불일치 → 200 재전송 (ETag 는 내용 해시)
*/
public function test_etag_changes_when_content_changes(): void
{
app()['env'] = 'production';
$first = $this->getJson("/api/modules/{$this->moduleIdentifier}/components.json");
$etag = $first->headers->get('ETag');
file_put_contents(
base_path("modules/{$this->moduleIdentifier}/components.json"),
json_encode(['composite' => ['Changed' => ['path' => 'components/Changed.tsx']]])
);
$second = $this->getJson(
"/api/modules/{$this->moduleIdentifier}/components.json",
['If-None-Match' => (string) $etag]
);
$second->assertStatus(200);
$this->assertNotSame($etag, $second->headers->get('ETag'));
}
}
@@ -49,6 +49,7 @@ class CoreScheduleRegistrationTest extends TestCase
'queue:prune-batches' => '15 4 * * *',
'notification:cleanup' => '20 4 * * *',
'ext-bundles:cleanup' => '25 4 * * *',
'ext-static:cleanup' => '28 4 * * *',
'seo:prune-stats' => '30 4 * * *',
'schedules:prune-history' => '35 4 * * *',
'identity:prune-logs' => '40 4 * * *',
@@ -0,0 +1,45 @@
<?php
namespace Tests\Feature\Http;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Tests\TestCase;
/**
* 정적 게시본 미스(`.json`)는 SPA catch-all 에 매칭되지 않는다 (#122 / 공개 #47 상호작용).
*
* catch-all 의 확장자 제외 lookahead(`(?!.*\.(js|css|…))`)는 끝 앵커가 없어 부분일치로
* 동작한다 — `.json` 은 `.js` 를 부분 문자열로 포함하므로 함께 제외된다. 덕분에 정적
* 게시본(`/build/ext/{v}/**.json`) 미스는 `template.dependencies` + `seo` 미들웨어와
* blade 풀 렌더를 거치지 않고 즉시 404 가 된다 (미스 비용 < API 폴백).
*
* 이 테스트는 그 성질을 계약으로 잠근다 — 훗날 lookahead 에 끝 앵커(`$`)를 붙이는
* "정리" 가 들어오면 정적 미스가 SPA 풀 렌더 경유로 조용히 비싸진다.
*/
class BuildPathCatchAllExclusionTest extends TestCase
{
/**
* 정적 게시 트리 미스는 유저 catch-all 에 매칭되지 않는다.
*
* @effects static_miss_skips_spa_catch_all
*/
public function test_build_경로는_유저_catch_all_에_매칭되지_않는다(): void
{
$this->expectException(NotFoundHttpException::class);
app('router')->getRoutes()->match(
Request::create('/build/ext/1787637589/templates/sirsoft-basic/lang/ko.json', 'GET')
);
}
/**
* 일반 SPA 경로는 여전히 catch-all 에 매칭된다 (과잉 제외 방지 가드).
*/
public function test_일반_경로는_여전히_유저_catch_all_에_매칭된다(): void
{
$route = app('router')->getRoutes()->match(Request::create('/some-page', 'GET'));
$this->assertContains('GET', $route->methods());
}
}
@@ -0,0 +1,427 @@
<?php
namespace Tests\Feature\Services;
use App\Contracts\Repositories\TemplateRepositoryInterface;
use App\Enums\ExtensionStatus;
use App\Models\Template;
use App\Services\ExtensionBundleService;
use App\Services\ExtensionStaticCacheService;
use App\Services\LanguagePackService;
use App\Services\TemplateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* 부트스트랩 리소스 정적 게시(bake) 서비스 테스트 (#122 S1).
*
* 게시 트리 형상(병합 결과 = 폴백 API 페이로드), 원자성(tmp → rename → manifest
* 마지막), 멱등(skip), 비활성 산출물 부재, 경로 검증 거부, GC 보존 정책,
* kill-switch, terminating 트리거 환경 게이트를 검증한다.
*/
class ExtensionStaticCacheServiceTest extends TestCase
{
use RefreshDatabase;
private const VERSION = 987654321;
/** 테스트 전용 public 루트 (실 게시 트리 격리) */
private string $isolatedPublicPath;
protected function setUp(): void
{
parent::setUp();
// 실 게시 트리(public/build/ext) 격리.
//
// GC 케이스가 "삭제 3건 / VERSION+300 만 잔존" 을 단언하므로 이 테스트는
// base 디렉토리가 비어 있는 상태에서 출발해야 한다. 그런데 `baseDir()` 은
// `public_path()` 기준이라, base 를 비우는 것이 곧 **운영 중 사이트의 게시본을
// 지우는 것**이 된다 (테스트 1건 실행만으로 전량 소실 — 자가 치유가 복구하기
// 전까지 구 HTML 이 참조하는 자산이 404 → 폴백). 그래서 base 를 비우는 대신
// public 루트 자체를 테스트 전용 임시 경로로 돌린다.
$this->isolatedPublicPath = storage_path('framework/testing/public-'.getmypid());
File::ensureDirectoryExists($this->isolatedPublicPath);
$this->app->usePublicPath($this->isolatedPublicPath);
// 결정적 버전 시드 (getExtensionCacheVersion 폴백 재생성 방지)
Cache::put('g7:core:ext.cache_version', self::VERSION);
// 이전 실행이 비정상 종료로 남긴 게시 락 잔존물 정리 (결정적 실행 보장)
Cache::lock('ext-static.publish.'.self::VERSION, 300)->forceRelease();
Cache::lock('ext-static.publish.'.(self::VERSION + 1), 300)->forceRelease();
ExtensionStaticCacheService::resetPublishScheduleForTesting();
$this->cleanBaseDir();
}
protected function tearDown(): void
{
$this->cleanBaseDir();
File::deleteDirectory($this->isolatedPublicPath);
ExtensionStaticCacheService::resetPublishScheduleForTesting();
parent::tearDown();
}
private function cleanBaseDir(): void
{
File::deleteDirectory(public_path('build/ext'));
}
private function service(): ExtensionStaticCacheService
{
return app(ExtensionStaticCacheService::class);
}
private function createActiveTemplate(string $identifier = 'sirsoft-admin_basic', string $type = 'admin'): Template
{
return Template::create([
'identifier' => $identifier,
'vendor' => explode('-', $identifier)[0],
'name' => ['ko' => '테스트 템플릿', 'en' => 'Test Template'],
'version' => '1.0.0',
'type' => $type,
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트', 'en' => 'Test'],
]);
}
/**
* 활성 템플릿 0개(설치 직전)여도 예외 없이 빈 게시가 성립한다.
*
* @scenario publish_state=unpublished, environment=production, trigger=manual_command
*/
public function test_publishes_empty_tree_when_no_active_templates(): void
{
$service = $this->service();
$this->assertTrue($service->publishCurrent());
$this->assertTrue($service->isPublished(self::VERSION));
$this->assertFileExists($service->versionDir(self::VERSION).'/manifest.json');
$this->assertFileExists($service->versionDir(self::VERSION).'/.htaccess');
}
/**
* lang 게시물은 폴백 API(serveLanguage)와 동일 페이로드다 (canonical 비교).
*
* @effects published_lang_matches_api_payload
*/
public function test_published_lang_matches_api_payload(): void
{
$this->createActiveTemplate();
$service = $this->service();
$this->assertTrue($service->publishCurrent());
$publishedPath = $service->versionDir(self::VERSION).'/templates/sirsoft-admin_basic/lang/ko.json';
$this->assertFileExists($publishedPath);
$apiResponse = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json');
$apiResponse->assertStatus(200);
$this->assertSame(
json_decode((string) $apiResponse->getContent(), true),
json_decode((string) file_get_contents($publishedPath), true),
'정적 게시본과 폴백 API 의 lang 페이로드가 canonical 동일해야 한다'
);
}
/**
* routes 게시물은 성공 봉투({"success":true,...,"data":...})를 포함한다 —
* 프론트 소비 코드(result.success / result.data) 무변경 보장.
*
* @effects published_routes_has_success_envelope
*/
public function test_published_routes_has_success_envelope(): void
{
$this->createActiveTemplate();
$service = $this->service();
$this->assertTrue($service->publishCurrent());
$publishedPath = $service->versionDir(self::VERSION).'/templates/sirsoft-admin_basic/routes.json';
$this->assertFileExists($publishedPath);
$published = json_decode((string) file_get_contents($publishedPath), true);
$this->assertTrue($published['success']);
$this->assertArrayHasKey('data', $published);
// 폴백 API 의 data 와 동일해야 한다
$apiResponse = $this->getJson('/api/templates/sirsoft-admin_basic/routes.json');
$apiResponse->assertStatus(200);
$this->assertSame($apiResponse->json('data'), $published['data']);
}
/**
* components.json 사본과 dist 에셋이 게시되고 `*.map` 은 제외된다.
*
* @effects published_tree_excludes_sourcemaps
*/
public function test_publishes_components_and_dist_assets_excluding_sourcemaps(): void
{
$this->createActiveTemplate();
$service = $this->service();
$this->assertTrue($service->publishCurrent());
$templateDir = $service->versionDir(self::VERSION).'/templates/sirsoft-admin_basic';
// components.json 사본 (실번들 파일이 존재)
$this->assertFileExists($templateDir.'/components.json');
$this->assertSame(
json_decode((string) file_get_contents(base_path('templates/sirsoft-admin_basic/components.json')), true),
json_decode((string) file_get_contents($templateDir.'/components.json'), true)
);
// dist 에셋 사본 존재 + 소스맵 부재
$this->assertDirectoryExists($templateDir.'/assets');
$maps = glob($templateDir.'/assets/*/*.map') ?: [];
$this->assertSame([], $maps, '소스맵은 게시 대상이 아니다');
}
/**
* 비활성 템플릿 산출물은 게시 트리에 부재한다 (활성 게이트의 정적 등가물).
*
* @effects published_tree_excludes_inactive_extensions
*/
public function test_inactive_template_is_absent_from_published_tree(): void
{
$this->createActiveTemplate();
Template::create([
'identifier' => 'sirsoft-basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '비활성', 'en' => 'Inactive'],
'version' => '1.0.0',
'type' => 'user',
'status' => ExtensionStatus::Inactive->value,
'description' => ['ko' => '비활성', 'en' => 'Inactive'],
]);
$service = $this->service();
$this->assertTrue($service->publishCurrent());
$this->assertDirectoryExists($service->versionDir(self::VERSION).'/templates/sirsoft-admin_basic');
$this->assertDirectoryDoesNotExist($service->versionDir(self::VERSION).'/templates/sirsoft-basic');
}
/**
* 식별자 패턴 불일치(경로 세그먼트 위험) 템플릿은 게시에서 거부된다.
*
* @effects identifier_outside_pattern_rejected
*/
public function test_rejects_identifier_outside_whitelist_pattern(): void
{
$this->createActiveTemplate();
// vendor-name 패턴을 벗어나는 식별자 (DB 직접 생성으로 우회 가정)
Template::create([
'identifier' => 'UPPER..traversal',
'vendor' => 'upper',
'name' => ['ko' => '위험', 'en' => 'Danger'],
'version' => '1.0.0',
'type' => 'user',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '위험', 'en' => 'Danger'],
]);
$service = $this->service();
$this->assertTrue($service->publishCurrent());
$templatesDir = $service->versionDir(self::VERSION).'/templates';
$this->assertDirectoryExists($templatesDir.'/sirsoft-admin_basic');
$entries = array_map('basename', File::directories($templatesDir));
$this->assertSame(['sirsoft-admin_basic'], $entries, '패턴 불일치 식별자는 트리에 없어야 한다');
}
/**
* 멱등 — 게시 완료 상태에서 재호출은 skip (기존 게시물 유지), force 는 재게시.
*
* @scenario publish_state=published, environment=production, trigger=manual_command
*
* @effects publish_is_idempotent_until_forced
*/
public function test_publish_is_idempotent_and_force_republishes(): void
{
$service = $this->service();
$this->assertTrue($service->publishCurrent());
// 게시 후 심은 마커가 skip 재호출에서 살아남으면 재게시가 없었다는 증거
$marker = $service->versionDir(self::VERSION).'/idempotency-marker';
File::put($marker, 'x');
$this->assertTrue($service->publishCurrent());
$this->assertFileExists($marker);
// force 재게시는 디렉토리를 새로 만든다 → 마커 소실
$this->assertTrue($service->publishCurrent(force: true));
$this->assertFileDoesNotExist($marker);
$this->assertTrue($service->isPublished(self::VERSION));
}
/**
* 쓰기 단계 실패 시 예외를 삼키고 false + tmp 잔존물 정리 + manifest 부재.
*
* @scenario publish_state=partial, environment=production, trigger=lifecycle
*
* @effects write_failure_cleans_tmp_and_falls_back
*/
public function test_write_failure_cleans_tmp_and_returns_false(): void
{
$this->createActiveTemplate();
// 병합 SSoT 가 예외를 던지는 상황 시뮬레이션
$mock = $this->partialMock(TemplateService::class, function ($mock) {
$mock->shouldReceive('getLanguageDataWithModules')
->andThrow(new \RuntimeException('disk full'));
});
$service = new ExtensionStaticCacheService(
$mock,
app(TemplateRepositoryInterface::class),
app(ExtensionBundleService::class),
app(LanguagePackService::class),
);
$this->assertFalse($service->publishCurrent());
$this->assertFalse($service->isPublished(self::VERSION));
$base = $service->baseDir();
$tmpDirs = File::isDirectory($base)
? array_filter(File::directories($base), fn ($d) => str_ends_with($d, '.tmp'))
: [];
$this->assertSame([], array_values($tmpDirs), 'tmp 잔존물은 정리되어야 한다');
}
/**
* GC — 현재 버전 + 직전 1개 보존, 그 외 삭제 (tmp 잔존물 포함).
*
* @effects cleanup_keeps_current_and_previous_versions
*/
public function test_cleanup_keeps_current_and_previous_only(): void
{
$service = $this->service();
$this->assertTrue($service->publishCurrent());
// 과거 버전 3개 + 고아 tmp 시뮬레이션
foreach ([100, 200, 300] as $old) {
File::ensureDirectoryExists($service->versionDir($old));
File::put($service->versionDir($old).'/manifest.json', '{}');
}
File::ensureDirectoryExists($service->baseDir().'/400.tmp');
$deleted = $service->cleanup();
// 보존: 현재(VERSION) + 직전(300). 삭제: 100, 200, 400.tmp
$this->assertSame(3, $deleted);
$this->assertDirectoryExists($service->versionDir(self::VERSION));
$this->assertDirectoryExists($service->versionDir(300));
$this->assertDirectoryDoesNotExist($service->versionDir(200));
$this->assertDirectoryDoesNotExist($service->versionDir(100));
$this->assertDirectoryDoesNotExist($service->baseDir().'/400.tmp');
}
/**
* kill-switch(core.static_cache.enabled=false) — 게시 자체가 중단된다.
*
* @scenario publish_state=unpublished, environment=production, trigger=kill_switch
*
* @effects kill_switch_disables_publish_and_gate
*/
public function test_kill_switch_disables_publishing(): void
{
config(['core.static_cache.enabled' => false]);
$service = $this->service();
$this->assertFalse($service->publishCurrent());
$this->assertDirectoryDoesNotExist($service->baseDir());
}
/**
* terminating 트리거 — 비프로덕션(testing)에서는 예약되지 않는다.
*
* @scenario publish_state=unpublished, environment=dev, trigger=lifecycle
*
* @effects terminating_publish_gated_to_production
*/
public function test_terminating_publish_not_scheduled_outside_production(): void
{
ExtensionStaticCacheService::schedulePublishOnTerminate();
$this->app->terminate();
$this->assertDirectoryDoesNotExist($this->service()->baseDir());
}
/**
* terminating 트리거 — 프로덕션에서는 종료 시점의 현재 버전으로 게시된다.
*
* @scenario publish_state=unpublished, environment=production, trigger=lifecycle
*
* @effects terminating_publish_uses_final_version_after_burst
*/
public function test_terminating_publish_runs_in_production(): void
{
app()['env'] = 'production';
ExtensionStaticCacheService::schedulePublishOnTerminate();
// 예약 후 버전이 한 번 더 bump 되어도 실행 시점의 최종 버전으로 게시 (자연 병합)
Cache::put('g7:core:ext.cache_version', self::VERSION + 1);
$this->app->terminate();
$this->assertTrue($this->service()->isPublished(self::VERSION + 1));
$this->assertFalse($this->service()->isPublished(self::VERSION));
}
/**
* terminating 게시 예약 플래그는 콜백 실행 시점에 리셋된다.
*
* 요청마다 앱 인스턴스를 새로 만드는 장수 프로세스(Octane 류)에서는 static 플래그만
* 프로세스에 살아남는다 — 리셋이 없으면 2번째 이후 bump 는 새 앱에 콜백이 등록되지
* 않은 채 플래그만 true 라 그 워커에서 영구 미게시가 되고, `AssetUrl` 자가 치유도
* 같은 플래그를 쓰므로 복구 경로가 없다. FPM(요청=프로세스)에서는 무영향.
*
* @scenario publish_state=published, environment=production, trigger=lifecycle
*
* @effects terminating_schedule_rearms_after_execution
*/
public function test_terminating_publish_rearms_after_callback_execution(): void
{
app()['env'] = 'production';
ExtensionStaticCacheService::schedulePublishOnTerminate();
$this->app->terminate();
$property = new \ReflectionProperty(ExtensionStaticCacheService::class, 'publishScheduled');
$this->assertFalse($property->getValue(), '콜백 실행 후 플래그가 리셋되어 재예약 가능해야 한다');
}
/**
* 게시 `.htaccess` 는 불변 캐시와 함께 mod_deflate 압축을 선언한다.
*
* 정적 서빙은 Laravel 압축 미들웨어(GzipEncodeResponse)를 우회하므로, Apache 에서는
* 게시 디렉토리가 스스로 압축을 선언해야 종전 API 대비 전송량 회귀가 없다
* (실측: lang/ko.json 524,915B 비압축 전송). nginx 는 규정 문서의 gzip 스니펫이 담당한다.
*
* @scenario publish_state=published, environment=production, trigger=manual_command
*
* @effects published_htaccess_declares_compression
*/
public function test_published_htaccess_declares_compression(): void
{
$service = $this->service();
$this->assertTrue($service->publishCurrent());
$htaccess = File::get($service->versionDir(self::VERSION).'/.htaccess');
$this->assertStringContainsString('mod_deflate.c', $htaccess);
$this->assertStringContainsString('application/json', $htaccess);
}
}
@@ -5,6 +5,7 @@ namespace Tests\Feature\Template;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Models\Template;
use App\Services\TemplateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
@@ -165,6 +166,151 @@ class PublicTemplateControllerTest extends TestCase
$this->assertEquals($response1->json('data'), $response2->json('data'));
}
/**
* `?v` 명시 요청은 조건부 캐시 헤더를 받는다 (#122 작업 D)
*
* 버전 키드 URL 은 bump 시 URL 자체가 바뀌므로 1h 공개 캐시가 안전하다.
*/
public function test_versioned_routes_request_has_conditional_cache_headers(): void
{
app()['env'] = 'production';
Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$response = $this->getJson('/api/templates/sirsoft-admin_basic/routes.json?v=1234');
$response->assertStatus(200)->assertJson(['success' => true]);
$this->assertNotNull($response->headers->get('ETag'));
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringContainsString('public', $cacheControl);
$this->assertStringContainsString('max-age=3600', $cacheControl);
$this->assertStringContainsString('Accept-Encoding', (string) $response->headers->get('Vary'));
}
/**
* `?v` 명시 요청의 If-None-Match 일치 시 304 (#122 작업 D)
*/
public function test_versioned_routes_request_returns_304_with_matching_etag(): void
{
app()['env'] = 'production';
Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$first = $this->getJson('/api/templates/sirsoft-admin_basic/routes.json?v=1234');
$etag = $first->headers->get('ETag');
$this->assertNotNull($etag);
$second = $this->getJson(
'/api/templates/sirsoft-admin_basic/routes.json?v=1234',
['If-None-Match' => $etag]
);
$second->assertStatus(304);
$this->assertSame('', $second->getContent());
}
/**
* 무버전 요청은 종전대로 공개 캐시 헤더가 없다 (#122 작업 D — 핸드셰이크 신선도 보존)
*/
public function test_unversioned_routes_request_has_no_public_cache_headers(): void
{
app()['env'] = 'production';
Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$response = $this->getJson('/api/templates/sirsoft-admin_basic/routes.json');
$response->assertStatus(200);
$this->assertNull($response->headers->get('ETag'));
$this->assertStringNotContainsString('max-age=3600', (string) $response->headers->get('Cache-Control'));
}
/**
* 개발 환경에서 `?v` 요청도 no-cache (dev 파일 수정 즉시 반영 — #122 작업 D 환경 분기)
*/
public function test_versioned_routes_request_no_cache_in_development(): void
{
app()['env'] = 'local';
Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$response = $this->getJson('/api/templates/sirsoft-admin_basic/routes.json?v=1234');
$response->assertStatus(200);
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringContainsString('no-cache', $cacheControl);
$this->assertStringNotContainsString('max-age=3600', $cacheControl);
}
/**
* 열화 라우트 스냅샷은 `?v` 요청이어도 공개 캐시 헤더를 받지 않는다 (#493 대칭, #122 작업 D)
*
* 서버측 캐시 회피(#493)만으로는 부족하다 — 같은 `?v` URL 에 `public, max-age` 가
* 붙으면 브라우저/CDN 계층이 열화 응답을 1시간 박제하고, 버전은 이미 올라간 뒤라
* 스스로 회복되지 않는다. 정적 게시 경로(publishTemplate)의 열화 제외와 동일 규율.
*
* @effects degraded_snapshot_gets_no_public_cache
*/
public function test_degraded_routes_snapshot_has_no_public_cache_headers(): void
{
app()['env'] = 'production';
Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
// proxy partial — 실제 인스턴스를 감싸 미지정 메서드는 실구현으로 위임
// (makePartial 은 생성자를 건너뛰어 typed property 미초기화 오류가 난다)
$service = \Mockery::mock(app(TemplateService::class));
$service->shouldReceive('lastRouteMergeWasDegraded')->andReturn(true);
$this->app->instance(TemplateService::class, $service);
$response = $this->getJson('/api/templates/sirsoft-admin_basic/routes.json?v=1234');
$response->assertStatus(200)->assertJson(['success' => true]);
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringNotContainsString('public', $cacheControl);
$this->assertStringNotContainsString('max-age=3600', $cacheControl);
}
/**
* config.json 서빙이 캐시를 생성하고 installed manifest 버전을 반환하는지 테스트 (#588, 공개 #119)
*
@@ -5,6 +5,7 @@ namespace Tests\Feature\Template;
use App\Enums\ExtensionStatus;
use App\Models\Template;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Tests\TestCase;
class TemplateAssetServingTest extends TestCase
@@ -12,7 +13,9 @@ class TemplateAssetServingTest extends TestCase
use RefreshDatabase;
private Template $activeTemplate;
private string $testTemplatePath;
private string $testIdentifier;
protected function setUp(): void
@@ -30,7 +33,7 @@ class TemplateAssetServingTest extends TestCase
// 테스트용 템플릿 디렉토리 생성
$this->testTemplatePath = base_path("templates/{$this->testIdentifier}/dist");
if (!file_exists($this->testTemplatePath)) {
if (! file_exists($this->testTemplatePath)) {
mkdir($this->testTemplatePath, 0755, true);
}
}
@@ -66,11 +69,11 @@ class TemplateAssetServingTest extends TestCase
*/
private function deleteDirectory(string $dir): bool
{
if (!file_exists($dir)) {
if (! file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
if (! is_dir($dir)) {
return unlink($dir);
}
@@ -79,7 +82,7 @@ class TemplateAssetServingTest extends TestCase
continue;
}
if (!$this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
if (! $this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
return false;
}
}
@@ -455,7 +458,7 @@ class TemplateAssetServingTest extends TestCase
// Assert
$response->assertStatus(200);
// baseResponse를 통해 실제 응답 타입 확인
$this->assertTrue($response->baseResponse instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse, '200 response should be a file response');
$this->assertTrue($response->baseResponse instanceof BinaryFileResponse, '200 response should be a file response');
$this->assertNotNull($response->headers->get('ETag'), 'New ETag should be provided');
}
@@ -534,7 +537,8 @@ class TemplateAssetServingTest extends TestCase
*/
public function test_serves_components_json(): void
{
// Arrange
// Arrange — public max-age 는 프로덕션 정책 (dev 는 no-cache 환경 분기, #122 작업 C)
app()['env'] = 'production';
$componentsPath = base_path("templates/{$this->testIdentifier}/components.json");
file_put_contents($componentsPath, json_encode([
'Button' => ['path' => 'components/Button.jsx'],
@@ -555,6 +559,56 @@ class TemplateAssetServingTest extends TestCase
$this->assertStringContainsString('max-age=3600', $cacheControl);
}
/**
* components.json If-None-Match 일치 시 304 (조건부 캐시 — #122 작업 C)
*/
public function test_components_json_returns_304_with_matching_etag(): void
{
// Arrange
app()['env'] = 'production';
$componentsPath = base_path("templates/{$this->testIdentifier}/components.json");
file_put_contents($componentsPath, json_encode([
'Button' => ['path' => 'components/Button.jsx'],
]));
// Act
$first = $this->get($this->templateUrl('components.json'));
$etag = $first->headers->get('ETag');
$second = $this->get($this->templateUrl('components.json'), ['If-None-Match' => (string) $etag]);
// Assert
$this->assertNotNull($etag);
$second->assertStatus(304);
$this->assertSame('', $second->getContent());
}
/**
* 개발 환경에서 components.json 은 no-cache (파일 수정 즉시 반영 — F10)
*
* @scenario publish_state=unpublished, environment=dev, trigger=self_heal
*
* @effects fallback_api_no_cache_in_dev
*/
public function test_components_json_no_cache_in_development(): void
{
// Arrange
app()['env'] = 'local';
$componentsPath = base_path("templates/{$this->testIdentifier}/components.json");
file_put_contents($componentsPath, json_encode([
'Button' => ['path' => 'components/Button.jsx'],
]));
// Act
$response = $this->get($this->templateUrl('components.json'));
// Assert
$response->assertStatus(200);
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringContainsString('no-cache', $cacheControl);
$this->assertStringNotContainsString('max-age=3600', $cacheControl);
}
/**
* 비활성화 템플릿의 components.json 접근 시 404 반환
*/
@@ -155,6 +155,9 @@ class TemplateLanguageServingTest extends TestCase
*/
public function test_cache_control_header_is_set(): void
{
// public max-age 는 프로덕션 정책 (dev 는 no-cache 환경 분기, #122 작업 C)
app()['env'] = 'production';
$response = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json');
$response->assertStatus(200);
@@ -166,6 +169,44 @@ class TemplateLanguageServingTest extends TestCase
$this->assertStringContainsString('public', $cacheControl);
}
/**
* lang If-None-Match 일치 시 304 (조건부 캐시 — #122 작업 C)
*/
public function test_language_returns_304_with_matching_etag(): void
{
app()['env'] = 'production';
$first = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json');
$first->assertStatus(200);
$etag = $first->headers->get('ETag');
$this->assertNotNull($etag);
$second = $this->getJson(
'/api/templates/sirsoft-admin_basic/lang/ko.json',
['If-None-Match' => $etag]
);
$second->assertStatus(304);
$this->assertSame('', $second->getContent());
}
/**
* 개발 환경에서 lang 은 no-cache (파일 수정 즉시 반영 — F10)
*
* @scenario publish_state=unpublished, environment=dev, trigger=manual_command
*/
public function test_language_no_cache_in_development(): void
{
app()['env'] = 'local';
$response = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json');
$response->assertStatus(200);
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringContainsString('no-cache', $cacheControl);
$this->assertStringNotContainsString('max-age=3600', $cacheControl);
}
/**
* 잘못된 로케일 형식 요청 시 404 반환
*/
@@ -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);
});
});
+19 -1
View File
@@ -56,6 +56,9 @@ class SeoNodeKeyParityTest extends TestCase
'id',
'key',
'comment',
// `_comment` 는 접두사 계열이다 — 저장소 관례상 `_comment_id`·`_comment_hidden` 등
// 문맥 이름을 붙인 변형이 통용된다(전수 8종). 정확일치로만 등록하면 새 변형마다
// 이 테스트가 red 가 되므로 isCommentKey() 가 접두사로 판정한다.
'_comment',
// 설치 시점에 인라인 확장되므로 SEO 렌더 시에는 남지 않는다
'partial',
@@ -110,7 +113,7 @@ class SeoNodeKeyParityTest extends TestCase
}
foreach ($this->collectNodeKeys($decoded) as $key) {
if (! in_array($key, $known, true)) {
if (! in_array($key, $known, true) && ! $this->isCommentKey($key)) {
$unknown[$key][] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $file);
}
}
@@ -124,6 +127,21 @@ class SeoNodeKeyParityTest extends TestCase
));
}
/**
* `_comment` 접두사 주석 키인지 판정합니다.
*
* 저장소 관례상 주석 키는 `_comment` 단독 외에 `_comment_id` 처럼 설명 대상을
* 접미사로 붙인 변형이 통용된다. React(DynamicRenderer)와 SEO(ComponentHtmlMapper)
* 모두 알 수 없는 최상위 키를 무시하므로 렌더 패리티에 영향이 없다.
*
* @param string $key 노드 최상위 키
* @return bool 주석 키 여부
*/
private function isCommentKey(string $key): bool
{
return str_starts_with($key, '_comment');
}
/**
* 문서 루트가 곧 노드인 partial 파일도 실제로 스캔됩니다.
*
@@ -0,0 +1,78 @@
<?php
namespace Tests\Unit\Seo;
use App\Seo\SeoRenderer;
use App\Services\ExtensionStaticCacheService;
use App\Support\AssetUrl;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* SEO 봇 HTML 의 템플릿 CSS URL 은 정적 게시(bake) 경로를 우회해야 한다 (#122).
*
* 봇 HTML 은 SeoCacheManager(`seo.page.*` — 키에 cache_version 미포함, TTL 수시간)에
* 캐시되는데, 정적 게시 디렉토리는 GC 가 현재+직전 1개만 보존한다. 캐시된 HTML 이
* GC 된 `/build/ext/{v}/…` 를 참조하면 봇 화면의 CSS 가 404 이고, SEO HTML 에는
* asset-url-recovery 파샬이 포함되지 않아 자가 복구 경로도 없다. 따라서 SEO 렌더는
* 항상 무버전 API URL(정적 게이트 우회 = 종전 동작)을 사용한다.
*/
class SeoRendererStaticAssetBypassTest extends TestCase
{
private const VERSION = 424242;
/** 테스트 전용 public 루트 (실 게시 트리 격리) */
private string $isolatedPublicPath;
protected function setUp(): void
{
parent::setUp();
// 실 게시 트리(public/build/ext) 오염 방지 (ExtensionStaticCacheServiceTest 와 동일 근거)
$this->isolatedPublicPath = storage_path('framework/testing/public-seobypass-'.getmypid());
File::ensureDirectoryExists($this->isolatedPublicPath);
$this->app->usePublicPath($this->isolatedPublicPath);
}
protected function tearDown(): void
{
File::deleteDirectory($this->isolatedPublicPath);
AssetUrl::resetStaticExtBaseMemo();
ExtensionStaticCacheService::resetPublishScheduleForTesting();
parent::tearDown();
}
/**
* 정적 게이트가 열린 상태에서도 SEO CSS URL 은 `/build/ext/` 를 참조하지 않는다.
*
* @effects seo_html_never_references_gc_target_static_path
*/
public function test_seo_css_url_은_정적_게시_경로를_우회한다(): void
{
Cache::put('g7:core:ext.cache_version', self::VERSION);
app()['env'] = 'production';
$dir = public_path('build/ext/'.self::VERSION);
File::ensureDirectoryExists($dir.'/templates/sirsoft-basic/assets/css');
File::put($dir.'/manifest.json', '{}');
File::put($dir.'/templates/sirsoft-basic/assets/css/components.css', 'x');
AssetUrl::resetStaticExtBaseMemo();
// 전제 고정 — 블레이드 경로(기본값)는 정적 게이트를 통과하는 상태다.
// 이 단언이 깨지면 아래 우회 단언은 게이트 미통과로 인한 공허한 통과가 된다.
$this->assertSame(
'/build/ext/'.self::VERSION.'/templates/sirsoft-basic/assets/css/components.css',
AssetUrl::templateAsset('sirsoft-basic', 'css/components.css')
);
$method = new \ReflectionMethod(SeoRenderer::class, 'getTemplateCssUrls');
$urls = $method->invoke(app(SeoRenderer::class), 'sirsoft-basic');
$this->assertNotEmpty($urls);
foreach ($urls as $url) {
$this->assertStringNotContainsString('/build/ext/', $url);
}
}
}
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace Tests\Unit\Seo;
use App\Seo\ComponentHtmlMapper;
use App\Seo\ExpressionEvaluator;
use Tests\TestCase;
/**
* props 값의 `$switch`/`$cases` 객체 해석이 React 렌더러와 같은지 감시합니다.
*
* 배경 (engine-v1.56.0 패리티):
* React `DataBindingEngine.resolveObject` 는 `{ "$switch": "{{expr}}", "$cases": {...},
* "$default": ... }` 형태의 props 값을 선언적 분기로 해석한다 (일반 경로 + 반복 경로).
* 봇(SEO) 렌더러가 이를 모르면 그 prop 은 배열이라는 이유로 **속성 자체가 조용히
* 사라진다** — 예외도 경고도 없다. 레이아웃 최상위 `computed` 의 `$switch` 는
* `SeoRenderer::resolveComputedSwitch` 가 별도로 처리하며, 이 테스트는 **노드 props
* 값** 축을 고정한다.
*
* 범위: props(속성) 축. 노드 `text` 키는 React 도 문자열만 해석하므로 대상이 아니다.
*
* @see ComponentHtmlMapper::buildAttributes()
*/
class SeoSwitchValueParityTest extends TestCase
{
private ComponentHtmlMapper $mapper;
private ExpressionEvaluator $evaluator;
protected function setUp(): void
{
parent::setUp();
$this->mapper = new ComponentHtmlMapper;
$this->evaluator = new ExpressionEvaluator;
$this->mapper->setComponentMap([
'Div' => ['tag' => 'div'],
'Li' => ['tag' => 'li'],
]);
$this->mapper->setTextProps(['text']);
$this->mapper->setAllowedAttrs(['class', 'id']);
$this->mapper->setAttrMap(['className' => 'class']);
}
/**
* 컴포넌트 배열을 렌더링합니다.
*
* @param array $components 컴포넌트 정의 배열
* @param array $context 데이터 컨텍스트
* @return string 렌더링된 HTML
*/
private function render(array $components, array $context = []): string
{
return $this->mapper->render($components, $context, $this->evaluator);
}
/**
* 일반 경로 — props 의 $switch 객체가 case 값으로 해석됩니다.
*
* @effects switch_prop_values_resolved_in_bot_render
*/
public function test_general_path_switch_prop_resolves_to_case_value(): void
{
$html = $this->render([
[
'name' => 'Div',
'props' => [
'className' => [
'$switch' => '{{tab}}',
'$cases' => ['products' => 'text-red', 'contents' => 'text-blue'],
'$default' => 'text-gray',
],
],
'text' => 'x',
],
], ['tab' => 'products']);
$this->assertStringContainsString('class="text-red"', $html);
}
/**
* 반복 경로 — 항목 변수를 참조하는 $switch 키가 항목마다 해석됩니다.
*
* @effects switch_prop_values_resolved_in_bot_render
*/
public function test_iteration_path_switch_key_resolves_per_item(): void
{
$html = $this->render([
[
'name' => 'Li',
'iteration' => [
'data' => '{{rows}}',
'item_var' => 'row',
],
'props' => [
'className' => [
'$switch' => '{{row.kind}}',
'$cases' => ['a' => 'kind-a', 'b' => 'kind-b'],
],
],
'text' => '{{row.kind}}',
],
], ['rows' => [['kind' => 'a'], ['kind' => 'b']]]);
$this->assertStringContainsString('class="kind-a"', $html);
$this->assertStringContainsString('class="kind-b"', $html);
}
/**
* 매칭 실패 시 $default 로 폴백합니다.
*
* @effects switch_prop_values_resolved_in_bot_render
*/
public function test_switch_falls_back_to_default_when_no_case_matches(): void
{
$html = $this->render([
[
'name' => 'Div',
'props' => [
'className' => [
'$switch' => '{{tab}}',
'$cases' => ['products' => 'text-red'],
'$default' => 'text-gray',
],
],
'text' => 'x',
],
], ['tab' => 'unknown']);
$this->assertStringContainsString('class="text-gray"', $html);
}
/**
* 매칭 실패 + $default 부재 → 속성이 방출되지 않습니다 (React undefined 와 동일).
*/
public function test_switch_without_match_or_default_emits_no_attribute(): void
{
$html = $this->render([
[
'name' => 'Div',
'props' => [
'className' => [
'$switch' => '{{tab}}',
'$cases' => ['products' => 'text-red'],
],
],
'text' => 'x',
],
], ['tab' => 'unknown']);
$this->assertStringNotContainsString('class=', $html);
$this->assertStringContainsString('x', $html);
}
/**
* case 값의 `{{}}` 바인딩도 해석됩니다 (React 중첩 표현식 지원과 동일).
*
* @effects switch_prop_values_resolved_in_bot_render
*/
public function test_switch_case_value_bindings_are_resolved(): void
{
$html = $this->render([
[
'name' => 'Div',
'props' => [
'className' => [
'$switch' => '{{tab}}',
'$cases' => ['products' => 'badge-{{level}}'],
],
],
'text' => 'x',
],
], ['tab' => 'products', 'level' => 'gold']);
$this->assertStringContainsString('class="badge-gold"', $html);
}
}
@@ -1293,6 +1293,48 @@ MD;
}
}
/**
* `applyUpdate(prune:true)` 가 `public` 타깃을 정리할 때 정적 게시본
* (`public/build/ext`)을 orphan 으로 삭제하지 않고 보존합니다 (#122).
*
* 게시본은 릴리즈 소스에 없는 로컬 파생물이라 excludes(`build/ext`) 미등록 시
* prune 이 삭제해, 업데이트 완료까지 정적 fast path 가 불필요하게 끊긴다.
*/
public function test_apply_update_prune_preserves_static_publish_dir(): void
{
[$source, $fakeBase, $restore] = $this->prepareApplyUpdateEnv(['public']);
// prepareApplyUpdateEnv 가 excludes 를 비우므로 실제 기본값(config/app.php)을 재주입 —
// 이 테스트의 검증 대상이 바로 excludes 의 `build/ext` 항목이다
config(['app.update.excludes' => ['node_modules', '.git', 'bootstrap/cache', 'build/ext']]);
try {
// source(릴리즈): public/build/core 는 추적 배포 산출물이라 항상 존재,
// build/ext 는 로컬 파생물이라 릴리즈 소스에 없다
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'build'.DIRECTORY_SEPARATOR.'core');
File::put($source.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'index.php', "<?php // core\n");
File::put(
$source.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'build'.DIRECTORY_SEPARATOR.'core'.DIRECTORY_SEPARATOR.'template-engine.min.js',
'// bundle'
);
// 활성(mine): 정적 게시본 + manifest
$publishDir = $fakeBase.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'build'
.DIRECTORY_SEPARATOR.'ext'.DIRECTORY_SEPARATOR.'1234';
File::ensureDirectoryExists($publishDir);
File::put($publishDir.DIRECTORY_SEPARATOR.'manifest.json', '{}');
$this->service->applyUpdate($source, null, prune: true, applyList: null);
$this->assertFileExists(
$publishDir.DIRECTORY_SEPARATOR.'manifest.json',
'prune 업데이트가 정적 게시본(public/build/ext)을 orphan 삭제하면 안 된다',
);
} finally {
$restore();
}
}
/**
* end-to-end 회귀 (#43): `applyUpdate(prune:true)` 가 `public` 타깃을 정리할 때
* `public/storage` symlink 를 orphan 으로 삭제하지 않고 보존합니다.
+214
View File
@@ -2,7 +2,10 @@
namespace Tests\Unit\Support;
use App\Services\ExtensionStaticCacheService;
use App\Support\AssetUrl;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
@@ -14,9 +17,25 @@ use Tests\TestCase;
*/
class AssetUrlTest extends TestCase
{
/** 테스트 전용 public 루트 (실 게시 트리 격리) */
private string $isolatedPublicPath;
protected function setUp(): void
{
parent::setUp();
// 실 게시 트리(public/build/ext) 격리 — cleanupStaticFixture 가 base 를 통째로
// 지우므로, 격리 없이는 단위 테스트 1회 실행이 운영 중 사이트의 게시본을 전량
// 삭제한다 (ExtensionStaticCacheServiceTest 의 격리와 동일 근거).
$this->isolatedPublicPath = storage_path('framework/testing/public-asseturl-'.getmypid());
File::ensureDirectoryExists($this->isolatedPublicPath);
$this->app->usePublicPath($this->isolatedPublicPath);
}
protected function tearDown(): void
{
AssetUrl::forceMode(null);
File::deleteDirectory($this->isolatedPublicPath);
parent::tearDown();
}
@@ -172,4 +191,199 @@ class AssetUrlTest extends TestCase
$this->assertSame(AssetUrl::MODE_EXTENSION, AssetUrl::mode());
}
// ── 정적 게시(bake) 게이트 (#122 S2) ─────────────────────────────────
/**
* 정적 게이트용 게시 픽스처를 만든다.
*
* @param int $version 버전
* @param array<string> $files 버전 디렉토리 내 상대 경로 목록
*/
private function publishFixture(int $version, array $files = []): void
{
$dir = public_path('build/ext/'.$version);
File::ensureDirectoryExists($dir);
File::put($dir.'/manifest.json', '{}');
foreach ($files as $relative) {
File::ensureDirectoryExists(dirname($dir.'/'.$relative));
File::put($dir.'/'.$relative, 'x');
}
}
private function cleanupStaticFixture(): void
{
File::deleteDirectory(public_path('build/ext'));
AssetUrl::resetStaticExtBaseMemo();
ExtensionStaticCacheService::resetPublishScheduleForTesting();
}
/**
* 정적 게이트 3조건 — 프로덕션 + enabled + 게시 완료(manifest) 를 전부
* 통과해야만 base 가 반환된다.
*
* @scenario publish_state=unpublished, environment=production, trigger=self_heal
*
* @effects static_gate_requires_manifest, kill_switch_disables_publish_and_gate
*/
public function test_정적_게이트는_프로덕션_활성_게시완료_3조건이다(): void
{
try {
Cache::put('g7:core:ext.cache_version', 424242);
// 비프로덕션(testing) → null
AssetUrl::resetStaticExtBaseMemo();
$this->publishFixture(424242);
$this->assertNull(AssetUrl::staticExtBase());
// 프로덕션 + 게시 완료 → base
app()['env'] = 'production';
AssetUrl::resetStaticExtBaseMemo();
$this->assertSame('/build/ext/424242', AssetUrl::staticExtBase());
// kill-switch off → null
config(['core.static_cache.enabled' => false]);
AssetUrl::resetStaticExtBaseMemo();
$this->assertNull(AssetUrl::staticExtBase());
config(['core.static_cache.enabled' => true]);
// manifest 부재(미게시) → null
File::delete(public_path('build/ext/424242/manifest.json'));
AssetUrl::resetStaticExtBaseMemo();
$this->assertNull(AssetUrl::staticExtBase());
} finally {
$this->cleanupStaticFixture();
}
}
/**
* 태그 계층 파일 단위 게이트 — manifest 는 있어도 그 자산의 실파일이 없으면
* 그 자산만 종전 API URL 로 방출된다 (나머지는 정적 URL).
*
* @scenario publish_state=partial, environment=production, trigger=manual_command
*
* @effects tag_layer_checks_individual_file_existence
*/
public function test_태그_계층은_개별_파일_존재까지_확인한다(): void
{
try {
Cache::put('g7:core:ext.cache_version', 424242);
app()['env'] = 'production';
$this->publishFixture(424242, [
'templates/sirsoft-basic/assets/css/components.css',
'bundles/modules.js',
]);
AssetUrl::resetStaticExtBaseMemo();
// 존재하는 파일 → 정적 URL (버전 디렉토리 경로, `?v` 불요)
$this->assertSame(
'/build/ext/424242/templates/sirsoft-basic/assets/css/components.css',
AssetUrl::templateAsset('sirsoft-basic', 'css/components.css', 424242)
);
$this->assertSame(
'/build/ext/424242/bundles/modules.js',
AssetUrl::extensionBundle('modules', 'js', 424242)
);
// 부재 파일 → 종전 API URL 그대로 (바이트 동일)
$this->assertSame(
'/api/templates/assets/sirsoft-basic/js/components.iife.js?v=424242',
AssetUrl::templateAsset('sirsoft-basic', 'js/components.iife.js', 424242)
);
$this->assertSame(
'/api/plugins/bundle.css?v=424242',
AssetUrl::extensionBundle('plugins', 'css', 424242)
);
} finally {
$this->cleanupStaticFixture();
}
}
/**
* 현재 게시 버전과 다른 `$version` 을 요구하는 호출은 정적 분기를 타지 않는다.
*
* 정적 경로는 항상 현재 게시본을 가리키므로, 다른 버전을 명시한 호출에 현재본을
* 돌려주면 "요청 버전이 URL 에 반영된다" 는 시그니처 계약이 조용히 깨진다.
* (현 호출부는 전부 현재 버전을 넘기므로 실동작 불변 — 미래 호출부 방어)
*/
public function test_요청_버전이_현재_게시_버전과_다르면_정적_분기를_건너뛴다(): void
{
try {
Cache::put('g7:core:ext.cache_version', 424242);
app()['env'] = 'production';
$this->publishFixture(424242, [
'templates/sirsoft-basic/assets/css/components.css',
]);
AssetUrl::resetStaticExtBaseMemo();
// 현재 버전 요청 → 정적
$this->assertSame(
'/build/ext/424242/templates/sirsoft-basic/assets/css/components.css',
AssetUrl::templateAsset('sirsoft-basic', 'css/components.css', 424242)
);
// 다른 버전 요청 → 종전 API URL (요청 버전 유지)
$this->assertSame(
'/api/templates/assets/sirsoft-basic/css/components.css?v=111111',
AssetUrl::templateAsset('sirsoft-basic', 'css/components.css', 111111)
);
} finally {
$this->cleanupStaticFixture();
}
}
/**
* 정적 게이트의 버전 조회는 PHP deprecation 을 발생시키지 않아야 한다.
*
* 트레이트 정적 메서드 직접 호출(`ClearsTemplateCaches::getExtensionCacheVersion()`)은
* PHP 8.1+ E_DEPRECATED 다 — blade 게이트는 매 프로덕션 요청마다 실행되므로
* 트레이트를 사용하는 클래스 경유로 호출해야 한다.
*
* @effects static_gate_requires_manifest
*/
public function test_정적_게이트는_deprecation_없이_동작한다(): void
{
try {
Cache::put('g7:core:ext.cache_version', 424242);
app()['env'] = 'production';
$this->publishFixture(424242);
AssetUrl::resetStaticExtBaseMemo();
$deprecations = [];
set_error_handler(static function (int $errno, string $errstr) use (&$deprecations): bool {
$deprecations[] = "[{$errno}] {$errstr}";
return true;
}, E_DEPRECATED | E_USER_DEPRECATED);
try {
AssetUrl::staticExtBase();
} finally {
restore_error_handler();
}
$this->assertSame([], $deprecations);
} finally {
$this->cleanupStaticFixture();
}
}
/**
* base null(게이트 미통과) 이면 기존 URL 과 바이트 동일해야 한다 (호출부 무변경 계약).
*
* @scenario publish_state=unpublished, environment=dev, trigger=kill_switch
*/
public function test_게이트_미통과시_종전_ur_l_바이트_동일(): void
{
AssetUrl::resetStaticExtBaseMemo();
AssetUrl::forceMode(AssetUrl::MODE_EXTENSION);
$this->assertSame(
'/api/templates/assets/sirsoft-basic/css/components.css?v=7',
AssetUrl::templateAsset('sirsoft-basic', 'css/components.css', 7)
);
$this->assertSame('/api/modules/bundle.js?v=7', AssetUrl::extensionBundle('modules', 'js', 7));
}
}
+90
View File
@@ -0,0 +1,90 @@
feature: ext-static-cache
description: |
부트스트랩 리소스 정적 게시(bake) — 공개 #122.
초기 부트스트랩 리소스(다국어 병합·컴포넌트 정의·라우트·확장 번들·템플릿 dist
에셋)를 캐시 버전 디렉토리(`public/build/ext/{v}/`)에 실파일로 게시해 웹서버가
rewrite 전에 직접 서빙한다. 병합 입력이 바뀌는 수명주기 이벤트마다
`incrementExtensionCacheVersion()` 단일 지점의 terminating 예약으로 재게시되고,
누락 시 blade 렌더의 자가 치유가 보충한다. 미게시/부분게시/GC 직후에는 프론트
fetch 계층(fetchStaticFirst)과 태그 계층(asset-url-recovery 파샬)이 종전 API 로
폴백한다.
핵심 동작:
- 게시 원자성: {v}.tmp 쓰기 → rename → manifest 마지막 기록 (manifest 존재 = 완료)
- 서빙 게이트 3조건: 프로덕션 + core.static_cache.enabled + 게시 완료
- 태그 계층은 개별 파일 file_exists 까지 확인 후 정적 URL 방출
- blade 주입 cache_version 시드로 stale localStorage 이중 로드 제거 (작업 A)
- components.json `?v` 부착 + 버전 키드 manifestCache (작업 B)
- 폴백 API 품질: ETag/304 + 환경 분기 (작업 C·D)
axes:
publish_state: [published, unpublished, partial]
environment: [production, dev]
trigger: [lifecycle, self_heal, manual_command, kill_switch]
exclusions:
- { environment: dev, publish_state: published, reason: "dev 는 staticBase 미주입 — 게시 상태와 무관하게 전 리소스 API 직행" }
- { environment: dev, publish_state: partial, reason: "동일 — dev 는 정적 경로 자체가 없다" }
- { trigger: kill_switch, publish_state: published, reason: "kill-switch off 는 게이트에서 base 자체를 차단 — 게시 상태 무관" }
- { trigger: kill_switch, publish_state: partial, reason: "동일" }
effects:
- published_lang_matches_api_payload
- published_routes_has_success_envelope
- published_tree_excludes_inactive_extensions
- published_tree_excludes_sourcemaps
- identifier_outside_pattern_rejected
- publish_is_idempotent_until_forced
- write_failure_cleans_tmp_and_falls_back
- cleanup_keeps_current_and_previous_versions
- kill_switch_disables_publish_and_gate
- terminating_publish_gated_to_production
- terminating_publish_uses_final_version_after_burst
- static_gate_requires_manifest
- tag_layer_checks_individual_file_existence
- static_first_fetch_falls_back_to_api_on_miss
- fallback_is_observable_via_console_warn
- static_asset_tag_recovers_to_api_url
- no_duplicate_boot_requests
- versioned_boot_urls
- handshake_reload_preserved_on_version_mismatch
- manifest_cache_keys_are_version_scoped
- fallback_api_serves_etag_304
- fallback_api_no_cache_in_dev
- degraded_snapshot_gets_no_public_cache
- seo_html_never_references_gc_target_static_path
- static_miss_skips_spa_catch_all
- terminating_schedule_rearms_after_execution
- published_htaccess_declares_compression
- bundle_script_static_miss_falls_back_to_api
test_files:
- tests/Feature/Services/ExtensionStaticCacheServiceTest.php
- tests/Feature/Api/Public/PublicComponentsCachingTest.php
- tests/Feature/Template/PublicTemplateControllerTest.php
- tests/Feature/Template/TemplateAssetServingTest.php
- tests/Feature/Template/TemplateLanguageServingTest.php
- tests/Feature/Api/Public/LayoutServingTest.php
- tests/Feature/Http/BuildPathCatchAllExclusionTest.php
- tests/Unit/Support/AssetUrlTest.php
- tests/Unit/Seo/SeoRendererStaticAssetBypassTest.php
- resources/js/core/__tests__/TemplateApp.cacheVersionSeed.test.ts
- resources/js/core/support/__tests__/fetchStaticFirst.test.ts
- resources/js/core/support/__tests__/assetUrlRecovery.test.ts
- resources/js/core/template-engine/__tests__/ComponentRegistry.manifestVersion.test.ts
- resources/js/core/modules/__tests__/ModuleAssetLoader.test.ts
- tests/Playwright/specs/smoke/bootstrap-request-dedup.spec.ts
- tests/Playwright/specs/smoke/static-cache-fallback.spec.ts
notes: |
리소스 5종(lang/components/routes/번들/dist)은 축이 아니라 effects 로 커버한다 —
게시·게이트·폴백은 리소스 무관 공통 메커니즘이고, 리소스별 형상 차이는
published_* effects (payload/봉투/소스맵 제외) 가 각각 단언한다.
environment=dev 축은 PHPUnit(환경 분기 케이스)과 AssetUrl 게이트 단위가 담당한다 —
E2E 대상 사이트(g7_2.dev)는 production 이라 dev 축을 브라우저로 실측할 수 없다.
trigger=lifecycle 의 실기기 검증(확장 비활성/활성 → 재게시 → 새 staticBase)은
Chrome MCP 매트릭스 T10a~T10d 가 수행한다 (원상 복구 의무 포함).
publish_state=partial 은 태그 계층(개별 file_exists 게이트)과 fetch 계층
(fetchStaticFirst 404 폴백) 양쪽에서 단위/브라우저로 커버된다.