Files
Gnuboard7/tests/Feature/Api/Public/PublicComponentsCachingTest.php
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

184 lines
6.4 KiB
PHP

<?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'));
}
}