feat(core): 정적 게시 수명주기 보완 — 빌드 파괴·권한·무결성

https://github.com/gnuboard/g7/issues/122 제보자의 추가 지적 2건(빌드가 게시본을
지움 / CLI 최초 게시 후 웹 재생성 불가)에 대응하고, 같은 근본 원인을 공유하는
결함을 전수조사로 함께 고친다.

- 빌드가 자기 산출물만 교체한다: 루트 vite `emptyOutDir: false`
 기본값 true 는 폴백 없는 코어 3번들과 배달된 immutable URL 의 게시본을 함께 지웠다
- 게시 트리 권한을 웹이 이어받는다: 병합 전 프리플라이트 + 부모 그룹 상속·g+w
 종전 소유권 정상화는 root 축만 덮어 비-root CLI 계정은 무방비였다
- 갱신 → 생성 → 완전성 확인을 한 묶음으로: 기록 바이트 대조, .old 원자 스왑,
 rename 일시 거부 재시도, 프론트 JSON 파싱 검증
- 실패를 억제하고 기록한다: 버전 한정 실패 마커 + 사유별 대시보드 알림
 + ext-static:status 점검 커맨드
- 파생: catch-all 제외 목록을 에셋 화이트리스트 합집합에서 파생(mjs·webp·otf 누락),
 번들 디스크 쓰기 fail-soft·빈 번들 503, 활성 디렉토리 prune 회피
This commit is contained in:
HeuJung committed 2026-08-28 08:02:22 +09:00
1 parent fe973f40af
commit b4ed33aa44
52 files changed
+3495 -147

No files matched your search

@@ -38,13 +38,23 @@ class ExtensionBundleServingTest extends TestCase
}
/**
* ExtensionBundleService 를 지정 경로를 반환하도록 mock 바인딩한다.
* 번들 서비스를 모킹합니다.
*
* `$memoryContent` / `$declaredCount` 는 빈 경로(`$returnPath === ''`)일 때의 분기를
* 정한다 — 디스크 캐시 실패(메모리 폴백)인지, 선언 0개(정상 빈 번들)인지,
* 선언은 있는데 결과가 0인지(장애)를 컨트롤러가 이 둘로 가른다.
*
* @param string $returnPath getBundleFilePath 반환값
* @param string $memoryContent buildBundleContent 반환값
* @param int $declaredCount countAssetDeclaringExtensions 반환값
*/
private function bindBundleService(string $returnPath): void
private function bindBundleService(string $returnPath, string $memoryContent = '', int $declaredCount = 0): void
{
$mock = Mockery::mock(ExtensionBundleService::class);
$mock->shouldReceive('getCurrentVersion')->andReturn(777);
$mock->shouldReceive('getBundleFilePath')->andReturn($returnPath);
$mock->shouldReceive('buildBundleContent')->andReturn($memoryContent);
$mock->shouldReceive('countAssetDeclaringExtensions')->andReturn($declaredCount);
$this->app->instance(ExtensionBundleService::class, $mock);
}
@@ -80,8 +90,8 @@ class ExtensionBundleServingTest extends TestCase
public function test_empty_bundle_returns_empty_ok_response(): void
{
// 활성 global 에셋이 없으면 서비스가 빈 경로 반환 → 컨트롤러 빈 200
$this->bindBundleService('');
// 에셋을 선언한 활성 확장이 0개 → 빈 번들이 정상이다 → 빈 200
$this->bindBundleService('', memoryContent: '', declaredCount: 0);
$response = $this->get('/api/modules/bundle.js?v=777');
@@ -91,6 +101,71 @@ class ExtensionBundleServingTest extends TestCase
$this->assertSame('', $response->getContent());
}
/**
* 디스크 캐시 실패는 500 이 아니라 메모리 병합 결과 200 이다 (E1 fail-soft).
*
* `ext-bundles` 디스크는 `throw => true` 라 권한 문제(uid 독점 0700 등)에서
* `UnableToWriteFile` 이 그대로 올라온다. 캐시는 최적화일 뿐이므로 그 실패가
* 모든 확장의 프론트엔드 JS/CSS 를 통째로 막으면 안 된다.
*
* @effects bundle_disk_write_failure_falls_back_to_memory
*/
public function test_disk_cache_failure_serves_memory_merged_result(): void
{
// 디스크 캐시 실패 → 경로는 빈 문자열, 그러나 병합 결과는 메모리에 있다
$this->bindBundleService('', memoryContent: '(function(){window.MEM=1})()', declaredCount: 2);
$response = $this->get('/api/modules/bundle.js?v=777');
$response->assertOk();
$this->assertStringStartsWith('text/javascript', $response->headers->get('Content-Type'));
$this->assertStringContainsString('window.MEM=1', $response->getContent());
// 캐시에 실패한 산출물이므로 immutable 로 박제하지 않는다
$this->assertStringContainsString('no-cache', (string) $response->headers->get('Cache-Control'));
}
/**
* 선언은 있는데 병합 결과가 비면 503 이다 (E2).
*
* 배포 중 `dist` 가 잠깐 비면 **모든 확장이 빠진 빈 번들**이 200 으로 나가고, 프론트는
* 404 도 오류도 받지 못한 채 한참 뒤 "Unknown action handler" 로 죽는다 — 그 시점에는
* 원인이 번들이라는 사실이 화면에도 로그에도 남아 있지 않다.
*
* @effects bundle_empty_with_declared_assets_returns_503
*/
public function test_empty_bundle_with_declared_assets_returns_503(): void
{
$this->bindBundleService('', memoryContent: '', declaredCount: 3);
$response = $this->get('/api/modules/bundle.js?v=777');
$response->assertStatus(503);
}
/**
* 플러그인 경로도 같은 판정을 쓴다 — 두 컨트롤러가 갈라지지 않는다 (장애 쪽).
*
* @effects bundle_decision_is_shared_across_extension_types
*/
public function test_plugin_bundle_returns_503_when_declared_but_empty(): void
{
$this->bindBundleService('', memoryContent: '', declaredCount: 1);
$this->get('/api/plugins/bundle.css?v=777')->assertStatus(503);
}
/**
* 플러그인 경로도 같은 판정을 쓴다 — 두 컨트롤러가 갈라지지 않는다 (정상 쪽).
*
* @effects bundle_decision_is_shared_across_extension_types
*/
public function test_plugin_bundle_returns_empty_ok_when_nothing_declared(): void
{
$this->bindBundleService('', memoryContent: '', declaredCount: 0);
$this->get('/api/plugins/bundle.css?v=777')->assertOk();
}
public function test_module_bundle_css_serves_with_css_content_type(): void
{
$path = $this->fixtureDir.'/module.777.css';
@@ -0,0 +1,168 @@
<?php
namespace Tests\Feature\Console;
use App\Console\Commands\Concerns\PrunesBuildOutput;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* 빌드 산출물 정리의 경로 범위 테스트 (#122 C1).
*
* `pruneBuildOutput()` 은 빌드 **전에** 실행된다. 웹이 서빙 중인 활성 디렉토리의 `dist/` 를
* 비우면 prune~빌드 완료 구간 전체가 서빙 공백이 되고, 빌드가 실패하면 빈 채로 남는다.
* 그래서 소스 디렉토리(`_bundled` / `_pending`)만 정리 대상이다.
*/
class BuildCommandPruneScopeTest extends TestCase
{
private string $root;
protected function setUp(): void
{
parent::setUp();
$this->root = storage_path('framework/testing/prune-scope');
File::deleteDirectory($this->root);
}
protected function tearDown(): void
{
File::deleteDirectory($this->root);
parent::tearDown();
}
/**
* 트레이트를 노출하는 테스트 더블 — 커맨드 전체를 띄우지 않고 판정만 검사한다.
*/
private function harness(): object
{
return new class
{
use PrunesBuildOutput;
/** @var array<int, string> */
public array $warnings = [];
/**
* 커맨드의 warn() 을 대체합니다.
*
* @param string $message 경고 문구
*/
public function warn($message, $verbosity = null): void
{
$this->warnings[] = (string) $message;
}
/**
* @param string $path 빌드 경로
* @return array<int, string> 삭제된 항목
*/
public function prune(string $path): array
{
return $this->pruneBuildOutput($path);
}
};
}
/**
* 산출물이 있는 dist 를 만듭니다.
*
* @param string $buildPath 확장 루트 경로
*/
private function seedDist(string $buildPath): void
{
File::ensureDirectoryExists($buildPath.'/dist/js');
File::put($buildPath.'/dist/js/components.iife.js', '(function(){})()');
File::ensureDirectoryExists($buildPath.'/dist/vendor/lib/1.0.0');
File::put($buildPath.'/dist/vendor/lib/1.0.0/lib.js', 'vendor');
}
/**
* `_bundled` 경로는 종전대로 정리한다 (동봉 vendor 는 보존).
*
* @effects prune_cleans_bundled_source_path
*/
public function test_bundled_path_is_pruned_but_vendor_preserved(): void
{
$path = $this->root.'/templates/_bundled/vendor-tpl';
$this->seedDist($path);
$harness = $this->harness();
$removed = $harness->prune($path);
$this->assertContains('js', $removed);
$this->assertDirectoryDoesNotExist($path.'/dist/js');
$this->assertDirectoryExists($path.'/dist/vendor', '동봉 vendor 가 삭제됐다');
$this->assertSame([], $harness->warnings);
}
/**
* `_pending` 경로도 소스 보관소다 — 정리 대상.
*
* @effects prune_cleans_pending_source_path
*/
public function test_pending_path_is_pruned(): void
{
$path = $this->root.'/modules/_pending/vendor-mod';
$this->seedDist($path);
$removed = $this->harness()->prune($path);
$this->assertContains('js', $removed);
}
/**
* 활성 디렉토리는 정리하지 않고 경고한다 — 서빙 공백 차단.
*
* @effects prune_skips_active_serving_path
*/
public function test_active_directory_is_not_pruned_and_warns(): void
{
$path = $this->root.'/templates/vendor-tpl';
$this->seedDist($path);
$harness = $this->harness();
$removed = $harness->prune($path);
$this->assertSame([], $removed);
$this->assertDirectoryExists(
$path.'/dist/js',
'활성 디렉토리의 산출물이 삭제됐다 — 빌드 완료까지 서빙이 끊긴다'
);
$this->assertNotEmpty($harness->warnings, '조용히 건너뛰면 stale 누적을 알 수 없다');
}
/**
* Windows 역슬래시 경로도 같은 판정을 받는다.
*
* @effects prune_scope_normalizes_path_separators
*/
public function test_backslash_paths_are_normalized(): void
{
// 백슬래시 리터럴을 소스에 직접 두지 않는다 — 도구 체인마다 이스케이프 해석이
// 달라 픽스처 자신이 조용히 다른 문자열을 검사하게 된다.
$sep = chr(92);
$path = $this->root.'/templates/_bundled/vendor-tpl';
$this->seedDist($path);
$windowsStyle = str_replace('/', $sep, $path);
$removed = $this->harness()->prune($windowsStyle);
$this->assertContains('js', $removed, '역슬래시 경로가 _bundled 로 인식되지 않았다');
}
/**
* dist 가 없으면 아무 일도 하지 않는다 (경고도 없다).
*
* @effects prune_is_noop_without_dist
*/
public function test_missing_dist_is_noop(): void
{
$harness = $this->harness();
$this->assertSame([], $harness->prune($this->root.'/templates/vendor-tpl'));
$this->assertSame([], $harness->warnings);
}
}
@@ -0,0 +1,192 @@
<?php
namespace Tests\Feature\Dashboard;
use App\Extension\HookManager;
use App\Listeners\StaticPublishFailureAlertListener;
use App\Services\ExtensionStaticCacheService;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
/**
* 정적 게시 실패의 운영자 도달 통로 테스트 (#122 O3).
*
* 게시 실패는 사이트를 멈추지 않는다 — API 폴백으로 넘어가 화면은 정상이고 서버 로그에만
* warning 이 쌓인다. 그래서 쓰기 불가 환경에서 정적 fast path 가 영구히 꺼진 채 운영되는
* 상태를 아무도 눈치채지 못했다(제보 본건). 이 테스트는 그 사실이 관리자 대시보드에
* 도달하는지, 그리고 **소음이 되지 않는지**(1회 실패는 알리지 않는다) 를 함께 잠근다.
*/
class StaticPublishAlertTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
Cache::forget('g7:core:ext.static.publish_failure');
}
protected function tearDown(): void
{
Cache::forget('g7:core:ext.static.publish_failure');
parent::tearDown();
}
private function listener(): StaticPublishFailureAlertListener
{
return new StaticPublishFailureAlertListener;
}
/**
* 실패 마커를 심습니다.
*
* @param int $count 연속 실패 횟수
* @param string $reason 사유 코드
*/
private function seedMarker(int $count, string $reason = 'parent_not_writable'): void
{
Cache::put('g7:core:ext.static.publish_failure', [
'version' => 123,
'at' => now()->toIso8601String(),
'reason' => $reason,
'count' => $count,
'message' => 'denied',
], 300);
}
/**
* 마커가 없으면 알림도 없다.
*
* @effects dashboard_has_no_alert_when_publishing_is_healthy
*/
public function test_no_alert_when_no_failure_marker(): void
{
$this->assertSame([], $this->listener()->addStaticPublishAlert([]));
}
/**
* 1회 실패는 알리지 않는다 — 배포 중 일시적 경합일 수 있고 자가 치유가 해소한다.
*
* @effects dashboard_alert_suppressed_below_threshold
*/
public function test_single_failure_does_not_alert(): void
{
$this->seedMarker(1);
$this->assertSame([], $this->listener()->addStaticPublishAlert([]));
}
/**
* 2회 연속 실패부터 대시보드 알림이 노출된다.
*
* @effects publish_failure_reaches_dashboard
*/
public function test_repeated_failure_surfaces_alert(): void
{
$this->seedMarker(2);
$alerts = $this->listener()->addStaticPublishAlert([]);
$this->assertCount(1, $alerts);
$this->assertSame('static_publish_failure', $alerts[0]['id']);
$this->assertSame('warning', $alerts[0]['type']);
$this->assertSame('static_publish_parent_not_writable', $alerts[0]['subtype']);
// 문구가 키 그대로 새어 나가지 않는지 — 번역 누락은 화면에 키 문자열을 노출한다.
$this->assertStringNotContainsString('extensions.alerts.', $alerts[0]['title']);
$this->assertStringNotContainsString('extensions.alerts.', $alerts[0]['message']);
$this->assertStringNotContainsString(':count', $alerts[0]['message']);
}
/**
* 사유별로 subtype 과 문구가 갈린다 — 조치할 곳이 다르기 때문이다.
*
* @effects publish_failure_alert_distinguishes_reason
*/
public function test_alert_distinguishes_failure_reason(): void
{
$messages = [];
foreach (['parent_not_writable', 'write_failed', 'lock_unavailable'] as $reason) {
$this->seedMarker(3, $reason);
$alerts = $this->listener()->addStaticPublishAlert([]);
$this->assertSame('static_publish_'.$reason, $alerts[0]['subtype']);
$this->assertStringNotContainsString('extensions.alerts.', $alerts[0]['message']);
$messages[$reason] = $alerts[0]['message'];
}
$this->assertCount(3, array_unique($messages), '사유별 문구가 구분되지 않는다');
}
/**
* 알 수 없는 사유도 일반 문구로 떨어진다 — 키 문자열이 화면에 노출되지 않는다.
*
* @effects publish_failure_alert_falls_back_for_unknown_reason
*/
public function test_unknown_reason_falls_back_to_generic_message(): void
{
$this->seedMarker(2, 'something_new');
$alerts = $this->listener()->addStaticPublishAlert([]);
$this->assertCount(1, $alerts);
$this->assertStringNotContainsString('extensions.alerts.', $alerts[0]['message']);
}
/**
* 기존 알림을 지우지 않고 덧붙인다 (필터 훅 계약).
*
* @effects publish_failure_alert_appends_to_existing
*/
public function test_alert_appends_without_dropping_existing(): void
{
$this->seedMarker(2);
$alerts = $this->listener()->addStaticPublishAlert([['id' => 'other']]);
$this->assertCount(2, $alerts);
$this->assertSame('other', $alerts[0]['id']);
}
/**
* 리스너가 `core.dashboard.alerts` 에 **실제로 등록**된다.
*
* 등록 실패는 예외도 로그도 남기지 않는다 — 알림이 그냥 안 뜰 뿐이라, 리스너 단위
* 테스트만으로는 배선 누락이 드러나지 않는다.
*
* @effects publish_failure_listener_is_registered_on_hook
*/
public function test_listener_is_wired_into_dashboard_alerts_hook(): void
{
$this->seedMarker(2);
$alerts = HookManager::applyFilters('core.dashboard.alerts', []);
$ids = array_column($alerts, 'id');
$this->assertContains(
'static_publish_failure',
$ids,
'리스너가 훅에 등록되지 않았다 — 알림이 조용히 뜨지 않는다'
);
}
/**
* 마커 접근자가 서비스의 기록과 같은 키를 본다 (키 오타 회귀 가드).
*
* @effects failure_marker_key_is_shared_between_writer_and_reader
*/
public function test_marker_accessor_reads_what_service_writes(): void
{
$this->seedMarker(4, 'write_failed');
$marker = ExtensionStaticCacheService::failureMarker();
$this->assertIsArray($marker);
$this->assertSame(4, $marker['count']);
$this->assertSame('write_failed', $marker['reason']);
}
}
@@ -0,0 +1,141 @@
<?php
namespace Tests\Feature\Extension;
use App\Extension\Helpers\ExtensionBackupHelper;
use App\Extension\Helpers\ExtensionPendingHelper;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* 확장 설치/업데이트 복사의 디렉토리 소유권 상속 테스트 (#122 P3).
*
* 파일은 `FilePermissionHelper::copyFile` 이 부모 소유권을 상속시키는데 **디렉토리는
* 그렇지 않았다.** sudo 로 실행된 설치/업데이트가 만든 디렉토리가 root 소유로 남으면
* 이후 웹 프로세스의 쓰기가 그 디렉토리에서 막힌다. 형제 구현
* `ExtensionBackupHelper::copyDirectoryWithProgress` 는 이미 같은 방어를 갖고 있었다
* (계층 불균형).
*
* 소유권 자체는 CI/개발 환경에서 단일 계정이라 값으로 단언할 수 없다 — 그래서 **복사
* 경로 세 곳 모두가 상속 호출을 갖는지**를 소스에서 검사하고, 복사 자체가 정상 동작하는지를
* 실제 파일시스템으로 확인한다. 한 경로만 고치면 나머지가 조용히 옛 동작으로 남기 때문이다.
*/
class ExtensionPendingOwnershipTest extends TestCase
{
private string $root;
protected function setUp(): void
{
parent::setUp();
$this->root = storage_path('framework/testing/pending-ownership');
File::deleteDirectory($this->root);
}
protected function tearDown(): void
{
File::deleteDirectory($this->root);
parent::tearDown();
}
/**
* 디렉토리를 만드는 복사 경로 전부가 부모 소유권을 상속시킨다.
*
* 대상 3곳: `copyDirectoryWithProgress`(rename 경로) / `syncDirectoryContents` ·
* `overlayDirectory`(제자리 동기화 폴백). 폴백만 빠뜨리면 파일 잠금으로 그 경로로
* 떨어진 교체에서만 소유권이 어긋나, Windows 잠금 상황에서만 재현되는 결함이 된다.
*
* @effects extension_copy_paths_inherit_directory_ownership
*/
public function test_every_directory_creating_copy_path_inherits_ownership(): void
{
$source = (new \ReflectionClass(ExtensionPendingHelper::class))->getFileName();
$content = (string) file_get_contents($source);
$methods = ['copyDirectoryWithProgress', 'syncDirectoryContents', 'overlayDirectory'];
foreach ($methods as $method) {
$body = $this->methodBody($content, $method);
$this->assertNotSame('', $body, "{$method} 을 소스에서 찾지 못했다 — 검사가 공허하다");
$this->assertStringContainsString(
'ensureDirectoryExists($dest',
$body,
"{$method} 이 디렉토리를 만들지 않는다 — 대상 목록이 낡았다"
);
$this->assertStringContainsString(
'FilePermissionHelper::inheritOwnershipFromParent($dest)',
$body,
"{$method} 이 디렉토리 소유권을 상속시키지 않는다 — sudo 설치 후 root 소유로 남는다"
);
}
}
/**
* 형제 구현(`ExtensionBackupHelper`)과 방어 수준이 같다 — 계층 불균형이 남지 않는다.
*
* @effects extension_copy_ownership_matches_sibling_helper
*/
public function test_matches_sibling_backup_helper_defense(): void
{
$sibling = (string) file_get_contents(
(new \ReflectionClass(ExtensionBackupHelper::class))->getFileName()
);
$this->assertStringContainsString(
'FilePermissionHelper::inheritOwnershipFromParent($dest)',
$sibling,
'기준으로 삼은 형제 구현이 바뀌었다 — 이 테스트의 전제를 다시 확인할 것'
);
}
/**
* 상속 호출을 추가한 뒤에도 실제 복사가 정상 동작한다 (회귀 가드).
*
* @effects extension_copy_still_produces_expected_tree
*/
public function test_copy_still_produces_expected_tree(): void
{
$source = $this->root.'/src';
$dest = $this->root.'/dest';
File::ensureDirectoryExists($source.'/nested/deep');
File::put($source.'/root.txt', 'a');
File::put($source.'/nested/deep/leaf.txt', 'b');
$method = new \ReflectionMethod(ExtensionPendingHelper::class, 'copyDirectoryWithProgress');
$method->setAccessible(true);
$method->invoke(null, $source, $dest, $source, null);
$this->assertFileExists($dest.'/root.txt');
$this->assertFileExists($dest.'/nested/deep/leaf.txt');
$this->assertSame('b', file_get_contents($dest.'/nested/deep/leaf.txt'));
}
/**
* 메서드 본문을 대략 잘라냅니다 (다음 메서드 선언 직전까지).
*
* @param string $content 파일 전문
* @param string $method 메서드명
* @return string 본문 (못 찾으면 빈 문자열)
*/
private function methodBody(string $content, string $method): string
{
$start = strpos($content, "function {$method}(");
if ($start === false) {
return '';
}
$rest = substr($content, $start);
$next = preg_match(
'/\n (?:public|protected|private)\s+(?:static\s+)?function\s/',
substr($rest, 1),
$m,
PREG_OFFSET_CAPTURE
);
return $next === 1 ? substr($rest, 0, $m[0][1] + 1) : $rest;
}
}
@@ -2,6 +2,7 @@
namespace Tests\Feature\Http;
use App\Support\StaticExtensionPattern;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Tests\TestCase;
@@ -42,4 +43,57 @@ class BuildPathCatchAllExclusionTest extends TestCase
$this->assertContains('GET', $route->methods());
}
/**
* 에셋 서빙이 허용하는 **모든** 확장자가 catch-all 에서 제외된다 (R1).
*
* 회귀 가드: 제외 목록이 라우트 파일에 손으로 적혀 있던 동안 `mjs` · `webp` · `otf`
* 세 가지가 빠져 있었다. 없는 `.mjs` 가 SPA 셸 HTML 200 을 받으면 브라우저는 그것을
* 스크립트로 파싱하다 죽는데, 응답이 성공이라 `onerror` 가 발화하지 않아 태그 복구기도
* 뜨지 않는다. `.json` 이 무사했던 것은 lookahead 에 끝 앵커가 없어 `.js` 에 부분일치한
* **우연**이었을 뿐이다. 이제 목록은 화이트리스트에서 파생되므로 우연에 기대지 않는다.
*
* @effects static_miss_returns_404_for_every_servable_extension
*/
public function test_모든_서빙_확장자가_catch_all_에서_제외된다(): void
{
$extensions = StaticExtensionPattern::servedExtensions();
$this->assertNotEmpty($extensions, '모집단이 비었다 — 검사가 공허하게 통과한다');
// 과거에 빠져 있던 세 가지가 모집단에 실제로 포함되는지 먼저 고정한다.
foreach (['mjs', 'webp', 'otf'] as $regressed) {
$this->assertContains($regressed, $extensions, "{$regressed} 가 모집단에서 빠졌다");
}
foreach ($extensions as $extension) {
$path = "/build/ext/1787637589/templates/sirsoft-basic/assets/missing.{$extension}";
try {
app('router')->getRoutes()->match(Request::create($path, 'GET'));
$this->fail(".{$extension} 미스가 SPA catch-all 에 매칭됐다 — HTML 200 이 나간다");
} catch (NotFoundHttpException) {
$this->addToAssertionCount(1);
}
}
}
/**
* admin catch-all 도 같은 제외 목록을 쓴다 — 두 목록이 갈라지지 않는다.
*
* @effects admin_catch_all_shares_static_exclusion
*/
public function test_admin_catch_all_도_같은_제외_목록을_쓴다(): void
{
foreach (StaticExtensionPattern::servedExtensions() as $extension) {
$path = "/admin/build/missing.{$extension}";
try {
app('router')->getRoutes()->match(Request::create($path, 'GET'));
$this->fail("admin: .{$extension} 미스가 catch-all 에 매칭됐다");
} catch (NotFoundHttpException) {
$this->addToAssertionCount(1);
}
}
}
}
@@ -13,9 +13,13 @@ use App\Services\ExtensionBundleService;
use App\Services\ExtensionStaticCacheService;
use App\Services\LanguagePackService;
use App\Services\TemplateService;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;
/**
@@ -57,6 +61,9 @@ class ExtensionStaticCacheServiceTest extends TestCase
Cache::lock('ext-static.publish.'.self::VERSION, 300)->forceRelease();
Cache::lock('ext-static.publish.'.(self::VERSION + 1), 300)->forceRelease();
// 실패 마커 격리 — 남아 있으면 백오프가 걸려 다음 테스트의 게시 예약이 조용히 스킵된다.
Cache::forget('g7:core:ext.static.publish_failure');
ExtensionStaticCacheService::resetPublishScheduleForTesting();
$this->cleanBaseDir();
}
@@ -95,10 +102,17 @@ class ExtensionStaticCacheServiceTest extends TestCase
}
$store = config('cache.default');
// 실패 마커까지 보여 준다 — 프리플라이트/쓰기 실패는 마커에 사유를 남기므로,
// 마커가 있으면 어느 분기였는지 즉시 알 수 있고 없으면 그 두 분기가 아니었다는 뜻이다.
// (마커 없이 false 면 kill-switch 또는 락 미획득이다.)
$marker = ExtensionStaticCacheService::failureMarker();
return sprintf(
'enabled=%s version=%d expected=%d lockFree=%s store=%s published=%s baseDir=%s',
'enabled=%s version=%d expected=%d lockFree=%s store=%s published=%s marker=%s baseDir=%s',
var_export($svc->isEnabled(), true), $v, self::VERSION, var_export($free, true),
$store, var_export($svc->isPublished($v), true), $svc->baseDir()
$store, var_export($svc->isPublished($v), true),
$marker === null ? 'none' : ($marker['reason'].':'.$marker['message']),
$svc->baseDir()
);
}
@@ -158,7 +172,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
/**
* 활성 템플릿 0개(설치 직전)여도 예외 없이 빈 게시가 성립한다.
*
* @scenario publish_state=unpublished, environment=production, trigger=manual_command, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=manual_command, process_user=web
*/
public function test_publishes_empty_tree_when_no_active_templates(): void
{
@@ -388,7 +402,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
/**
* 멱등 — 게시 완료 상태에서 재호출은 skip (기존 게시물 유지), force 는 재게시.
*
* @scenario publish_state=published, environment=production, trigger=manual_command, process_user=web
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=manual_command, process_user=web
*
* @effects publish_is_idempotent_until_forced
*/
@@ -413,7 +427,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
/**
* 쓰기 단계 실패 시 예외를 삼키고 false + tmp 잔존물 정리 + manifest 부재.
*
* @scenario publish_state=partial, environment=production, trigger=lifecycle, process_user=web
* @scenario publish_state=partial, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects write_failure_cleans_tmp_and_falls_back
*/
@@ -447,7 +461,204 @@ class ExtensionStaticCacheServiceTest extends TestCase
}
/**
* GC — 현재 버전 + 직전 1개 보존, 그 외 삭제 (tmp 잔존물 포함).
* 게시 루트를 만들 수 없으면 **병합을 시작하기 전에** 끊는다 (P2 프리플라이트).
*
* `public/build` 가 다른 계정 소유 + `g-w` 면 웹 프로세스는 `ext` 를 mkdir 조차 하지
* 못한다. 그 사실을 전 로케일 lang 병합 + 전 템플릿 dist 복사를 다 헛돈 뒤에 알게 되면
* 그 비용이 **모든 프로덕션 요청**에서 반복된다.
*
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=parent_denied, environment=production, trigger=lifecycle, process_user=web
*
* @effects parent_denied_short_circuits_before_merge
*/
public function test_unwritable_parent_short_circuits_before_merge(): void
{
$this->createActiveTemplate();
// 병합 SSoT 가 호출되면 실패 — 프리플라이트가 그 앞에서 끊어야 한다.
$mock = $this->partialMock(TemplateService::class, function ($mock) {
$mock->shouldReceive('getLanguageDataWithModules')
->never();
});
$service = new ExtensionStaticCacheService(
$mock,
app(TemplateRepositoryInterface::class),
app(ModuleRepositoryInterface::class),
app(PluginRepositoryInterface::class),
app(ExtensionBundleService::class),
app(LanguagePackService::class),
);
// 게시 루트도, 그 부모도 만들 수 없는 상태를 만든다 — public 루트를 파일로 막아
// 어떤 하위 디렉토리도 생성될 수 없게 한다 (Windows/Unix 공통으로 성립).
$blocked = $this->isolatedPublicPath.'/blocked-public';
File::put($blocked, 'not a directory');
$this->app->usePublicPath($blocked);
$this->assertFalse($service->publishCurrent());
$this->assertFalse($service->isPublished(self::VERSION));
$marker = ExtensionStaticCacheService::failureMarker();
$this->assertIsArray($marker, '프리플라이트 실패가 마커에 남지 않았다');
$this->assertSame('parent_not_writable', $marker['reason']);
}
/**
* 게시 루트 자체가 쓰기 불가면 같은 지점에서 끊긴다 (P1).
*
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=tree_denied, environment=production, trigger=lifecycle, process_user=web
*
* @effects parent_denied_short_circuits_before_merge
*/
public function test_unwritable_publish_tree_short_circuits(): void
{
$this->createActiveTemplate();
$service = $this->service();
// 게시 루트 자리에 파일을 놓아 디렉토리로 쓸 수 없게 만든다.
$base = $service->baseDir();
File::ensureDirectoryExists(dirname($base));
File::deleteDirectory($base);
File::put($base, 'not a directory');
$this->assertFalse($service->publishCurrent());
$this->assertFalse($service->isPublished(self::VERSION));
$marker = ExtensionStaticCacheService::failureMarker();
$this->assertIsArray($marker);
$this->assertSame('parent_not_writable', $marker['reason']);
@unlink($base);
}
/**
* 쓰기 실패는 실패 마커에 사유와 함께 기록된다 (O1 백오프의 근거).
*
* @scenario publish_state=partial, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects publish_failure_recorded_in_marker
*/
public function test_write_failure_records_failure_marker(): void
{
$this->createActiveTemplate();
Cache::forget('g7:core:ext.static.publish_failure');
$mock = $this->partialMock(TemplateService::class, function ($mock) {
$mock->shouldReceive('getLanguageDataWithModules')
->andThrow(new \RuntimeException('disk full'));
});
$service = new ExtensionStaticCacheService(
$mock,
app(TemplateRepositoryInterface::class),
app(ModuleRepositoryInterface::class),
app(PluginRepositoryInterface::class),
app(ExtensionBundleService::class),
app(LanguagePackService::class),
);
$this->assertFalse($service->publishCurrent());
$marker = ExtensionStaticCacheService::failureMarker();
$this->assertIsArray($marker, '실패 마커가 기록되지 않았다 — 진단 표면이 실패를 볼 수 없다');
$this->assertSame('write_failed', $marker['reason']);
$this->assertSame(self::VERSION, $marker['version']);
$this->assertSame(1, $marker['count']);
$this->assertStringContainsString('disk full', $marker['message']);
}
/**
* 게시 성공은 실패 마커를 제거한다 — 백오프가 영구 고착되지 않는다.
*
* @effects publish_success_clears_failure_marker
*/
public function test_successful_publish_clears_failure_marker(): void
{
Cache::put('g7:core:ext.static.publish_failure', [
'version' => self::VERSION,
'at' => now()->toIso8601String(),
'reason' => 'write_failed',
'count' => 3,
'message' => 'stale',
], 300);
$service = $this->service();
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
$this->assertNull(
ExtensionStaticCacheService::failureMarker(),
'성공했는데 실패 마커가 남아 있다 — 이후 예약이 영구 억제된다'
);
}
/**
* 신선한 실패 마커가 있으면 terminating 게시를 재예약하지 않는다 (O1 백오프).
*
* 쓰기 불가 환경에서 모든 프로덕션 요청이 전 로케일 병합 + 전 템플릿 dist 복사를
* 헛도는 것을 막는다.
*
* @effects publish_failure_backoff_suppresses_reschedule
*/
public function test_fresh_failure_marker_suppresses_publish_scheduling(): void
{
$this->app['env'] = 'production';
ExtensionStaticCacheService::resetPublishScheduleForTesting();
ExtensionStaticCacheService::fakeRootProcessForTesting(false);
Cache::put('g7:core:ext.static.publish_failure', [
'version' => self::VERSION,
'at' => now()->toIso8601String(),
'reason' => 'parent_not_writable',
'count' => 2,
'message' => 'denied',
], 300);
ExtensionStaticCacheService::schedulePublishOnTerminate();
$this->app->terminate();
$this->assertFalse(
$this->service()->isPublished(self::VERSION),
'실패 마커가 신선한데 게시가 재시도됐다 — 백오프가 걸리지 않는다'
);
}
/**
* 절단 쓰기는 예외로 잡히고 manifest 가 기록되지 않는다 (A1).
*
* `File::put()` 은 디스크 풀/quota 에서 **짧은 int** 를 돌려주며 성공한 것처럼 보인다.
* `=== false` 만 보면 절단 JSON 이 200 으로 서빙되고, 프론트는 `response.ok` 만 보므로
* 폴백하지 않은 채 `response.json()` 이 던져 부팅 전체가 실패한다.
*
* @scenario publish_state=partial, artifact_integrity=truncated, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects truncated_artifact_rejected_before_manifest
*/
public function test_truncated_write_is_rejected_before_manifest(): void
{
$this->createActiveTemplate();
// File::put 이 실제보다 짧은 바이트 수를 반환하는 상황 (디스크 풀/quota).
// partialMock 이라 ensureDirectoryExists 등 나머지 파일 연산은 그대로 동작한다.
File::partialMock()->shouldReceive('put')->andReturn(1);
$service = $this->service();
$this->assertFalse($service->publishCurrent());
$this->assertFalse(
$service->isPublished(self::VERSION),
'절단 산출물이 게시 완료로 표시됐다 — 손상 JSON 이 200 으로 서빙된다'
);
}
/**
* GC — 현재 버전 + 직전 1개 보존, 그 외 삭제.
*
* 갓 만들어진 `.tmp` 는 살아남는다 — 락은 버전별이라 다른 버전의 게시가 동시에
* 진행 중일 수 있고, 나이 무관 삭제는 그 순간 살아 있는 남의 tmp 를 파괴한다.
*
* @effects cleanup_keeps_current_and_previous_versions
*/
@@ -456,7 +667,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
$service = $this->service();
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
// 과거 버전 3개 + 고아 tmp 시뮬레이션
// 과거 버전 3개 + 진행 중으로 보이는 신규 tmp 시뮬레이션
foreach ([100, 200, 300] as $old) {
File::ensureDirectoryExists($service->versionDir($old));
File::put($service->versionDir($old).'/manifest.json', '{}');
@@ -465,19 +676,85 @@ class ExtensionStaticCacheServiceTest extends TestCase
$deleted = $service->cleanup();
// 보존: 현재(VERSION) + 직전(300). 삭제: 100, 200, 400.tmp
$this->assertSame(3, $deleted);
// 보존: 현재(VERSION) + 직전(300) + 신규 400.tmp. 삭제: 100, 200
$this->assertSame(2, $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');
$this->assertDirectoryExists(
$service->baseDir().'/400.tmp',
'진행 중일 수 있는 신규 tmp 는 보존되어야 한다'
);
}
/**
* GC — 나이 가드: 10분을 넘긴 `.tmp` / `.old` 만 삭제된다 (A4).
*
* @effects cleanup_removes_only_stale_work_directories
*/
public function test_cleanup_removes_only_stale_work_directories(): void
{
$service = $this->service();
$base = $service->baseDir();
File::ensureDirectoryExists($base);
$fresh = $base.'/500.tmp';
$staleTmp = $base.'/600.tmp';
$staleOld = $base.'/700.old';
foreach ([$fresh, $staleTmp, $staleOld] as $dir) {
File::ensureDirectoryExists($dir);
}
// 락 TTL(300초)의 2배가 기준 — 그보다 확실히 오래된 시각으로 되돌린다.
touch($staleTmp, time() - 3600);
touch($staleOld, time() - 3600);
clearstatcache();
$deleted = $service->cleanup();
$this->assertDirectoryExists($fresh, '신규 tmp 가 삭제되었다 — 진행 중 게시가 파괴된다');
$this->assertDirectoryDoesNotExist($staleTmp, '늙은 tmp 가 정리되지 않았다');
$this->assertDirectoryDoesNotExist($staleOld, '늙은 .old 가 정리되지 않았다');
$this->assertSame(2, $deleted);
}
/**
* GC — 현재 버전 디렉토리가 실존하지 않으면 실존 최신 2개를 보존한다 (D2).
*
* `cache:clear` 후 첫 호출자가 CLI 면 포인터만 새 버전으로 점프하고 산출물은 아직
* 없다. 그 상태에서 없는 버전을 보존 슬롯으로 쓰면 진짜 직전 버전이 삭제된다.
*
* @effects gc_preserves_previous_when_current_absent
*/
public function test_cleanup_preserves_two_newest_when_current_version_absent(): void
{
$service = $this->service();
$base = $service->baseDir();
File::ensureDirectoryExists($base);
// 현재 버전(VERSION) 디렉토리는 만들지 않는다 — 포인터만 앞선 상태.
foreach ([100, 200, 300] as $old) {
File::ensureDirectoryExists($service->versionDir($old));
File::put($service->versionDir($old).'/manifest.json', '{}');
}
$deleted = $service->cleanup();
$this->assertDirectoryExists($service->versionDir(300), '실존 최신이 보존되지 않았다');
$this->assertDirectoryExists(
$service->versionDir(200),
'진짜 직전 버전이 삭제됐다 — 없는 현재 버전이 보존 슬롯을 잡고 있다'
);
$this->assertDirectoryDoesNotExist($service->versionDir(100));
$this->assertSame(1, $deleted);
}
/**
* kill-switch(core.static_cache.enabled=false) — 게시 자체가 중단된다.
*
* @scenario publish_state=unpublished, environment=production, trigger=kill_switch, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=kill_switch, process_user=web
*
* @effects kill_switch_disables_publish_and_gate
*/
@@ -494,7 +771,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
/**
* terminating 트리거 — 비프로덕션(testing)에서는 예약되지 않는다.
*
* @scenario publish_state=unpublished, environment=dev, trigger=lifecycle, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=dev, trigger=lifecycle, process_user=web
*
* @effects terminating_publish_gated_to_production
*/
@@ -510,7 +787,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
/**
* terminating 트리거 — 프로덕션에서는 종료 시점의 현재 버전으로 게시된다.
*
* @scenario publish_state=unpublished, environment=production, trigger=lifecycle, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects terminating_publish_uses_final_version_after_burst
*/
@@ -538,7 +815,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
* (실사례: sudo 코어 업데이트 직후 전면 500). 게시는 다음 웹 렌더의
* 자가 치유(웹 계정)가 수행한다.
*
* @scenario publish_state=unpublished, environment=production, trigger=lifecycle, process_user=root_cli
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=root_cli
*
* @effects root_cli_defers_publish_to_web_self_heal
*/
@@ -565,7 +842,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
* 않은 채 플래그만 true 라 그 워커에서 영구 미게시가 되고, `AssetUrl` 자가 치유도
* 같은 플래그를 쓰므로 복구 경로가 없다. FPM(요청=프로세스)에서는 무영향.
*
* @scenario publish_state=published, environment=production, trigger=lifecycle, process_user=web
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects terminating_schedule_rearms_after_execution
*/
@@ -588,7 +865,7 @@ class ExtensionStaticCacheServiceTest extends TestCase
* 게시 디렉토리가 스스로 압축을 선언해야 종전 API 대비 전송량 회귀가 없다
* (실측: lang/ko.json 524,915B 비압축 전송). nginx 는 규정 문서의 gzip 스니펫이 담당한다.
*
* @scenario publish_state=published, environment=production, trigger=manual_command, process_user=web
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=manual_command, process_user=web
*
* @effects published_htaccess_declares_compression
*/
@@ -603,4 +880,442 @@ class ExtensionStaticCacheServiceTest extends TestCase
$this->assertStringContainsString('mod_deflate.c', $htaccess);
$this->assertStringContainsString('application/json', $htaccess);
}
/**
* manifest 기록이 실패하면 **이미 앉은 최종 디렉토리**를 정리한다 (A2).
*
* rename 이 이미 성공한 뒤라 `$tmp` 는 존재하지 않는다 — tmp 만 지우는 정리는 no-op 이고,
* manifest 없는 완성 디렉토리가 영구 잔존한다. 그 상태에서 `isPublished()` 는 영원히
* false 라 요청마다 트리를 지웠다 만들기를 반복하며, 실패는 로그에만 남는다.
*
* @scenario publish_state=partial, artifact_integrity=truncated, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects manifest_failure_cleans_final_directory
*/
public function test_manifest_failure_cleans_final_directory(): void
{
$this->createActiveTemplate();
$service = $this->service();
$final = $service->versionDir(self::VERSION);
$base = $service->baseDir();
// manifest 쓰기 **시점만** 실패시킨다 — 첫 파일 쓰기에서 던지면 rename 까지 가지
// 못해 이 경로(A2)가 아니라 tmp 정리 경로(P1)를 검사하게 된다.
$real = new Filesystem;
$fs = File::partialMock();
$fs->shouldReceive('put')
->withArgs(fn ($path) => str_ends_with(str_replace('\\', '/', (string) $path), '/manifest.json'))
->andReturn(false);
$fs->shouldReceive('put')
->andReturnUsing(fn ($path, $contents, $lock = false) => $real->put($path, $contents, $lock));
$this->assertFalse($service->publishCurrent());
$this->assertFalse($service->isPublished(self::VERSION));
$this->assertDirectoryDoesNotExist(
$final,
'manifest 없는 완성 디렉토리가 잔존했다 — isPublished 가 영원히 false 라 매 요청이 트리를 다시 만든다'
);
$leftovers = File::isDirectory($base) ? array_map('basename', File::directories($base)) : [];
$this->assertSame([], $leftovers, '게시 작업 디렉토리가 정리되지 않았다');
// 실패 지점이 manifest 였음을 고정한다 — 그보다 앞에서 끊겼다면 이 테스트는
// rename 이후 경로(A2)가 아니라 tmp 정리 경로를 검사한 셈이라 공허하다.
$marker = ExtensionStaticCacheService::failureMarker();
$this->assertIsArray($marker);
$this->assertSame('write_failed', $marker['reason']);
$this->assertStringContainsString('manifest.json', $marker['message']);
}
/**
* 재게시 중 `rename($tmp, $final)` 이 실패하면 비켜 둔 기존 버전이 복원된다 (A3).
*
* 실측 근거: Windows 재게시에서 이 경로가 실제로 발동했고(마커 상세
* `Failed to rename publish directory: …{v}.tmp -> …{v}`), 기존 게시본은 온전히
* 보존됐다. 복원이 없으면 이미 배달된 HTML 이 참조하는 CSS/JS/폰트가 전부 404 가
* 되고 폰트에는 복구기가 없다.
*
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=manual_command, process_user=web
*
* @effects rename_failure_restores_previous_published_version
*/
public function test_rename_failure_restores_previous_published_version(): void
{
$service = $this->service();
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
$final = $service->versionDir(self::VERSION);
$old = $final.'.old';
$base = $service->baseDir();
// 기존 게시본의 증거 — 복원되면 이 파일이 그대로 살아 있다.
File::put($final.'/previous-version-marker', 'v1');
// 새 트리를 앉힐 자리를 **비어 있지 않은 디렉토리**로 점유해 rename 을 실패시킨다.
// 점유 시점은 기존 버전을 `.old` 로 비켜낸 직후여야 하므로(그 전이면 기존 버전에
// 파일 하나가 늘 뿐이다), 스왑 판정 호출(`File::isDirectory($old)`)에 훅을 건다.
$fired = false;
$fs = File::partialMock();
$fs->shouldReceive('isDirectory')
->withArgs(fn ($path) => (string) $path === $old)
->andReturnUsing(function ($path) use (&$fired, $final) {
if (! $fired && ! is_dir($final)) {
$fired = true;
mkdir($final, 0775, true);
file_put_contents($final.DIRECTORY_SEPARATOR.'blocker', 'occupied');
}
return is_dir($path);
});
$fs->shouldReceive('isDirectory')->andReturnUsing(fn ($path) => is_dir($path));
$this->assertFalse($service->publishCurrent(force: true), '스왑 실패가 성공으로 보고됐다');
$this->assertTrue($fired, 'rename 실패를 유도하지 못했다 — 이 테스트는 공허 통과다');
$this->assertFileExists(
$final.'/previous-version-marker',
'스왑 실패 후 기존 게시본이 복원되지 않았다 — 배달된 HTML 의 자산이 전부 404 가 된다'
);
$this->assertFileExists($final.'/manifest.json');
$this->assertTrue($service->isPublished(self::VERSION));
$this->assertDirectoryDoesNotExist($old, '비켜 둔 디렉토리가 제자리로 돌아가지 않았다');
$leftovers = array_filter(
array_map('basename', File::directories($base)),
fn ($name) => str_ends_with($name, '.tmp')
);
$this->assertSame([], array_values($leftovers), 'tmp 잔존물이 정리되지 않았다');
$marker = ExtensionStaticCacheService::failureMarker();
$this->assertIsArray($marker);
$this->assertSame('write_failed', $marker['reason']);
$this->assertStringContainsString('Failed to rename publish directory', $marker['message']);
}
/**
* 디렉토리 rename 은 포기 전에 재시도한다 — 일시 거부를 게시 실패로 만들지 않는다.
*
* 실측 근거: 실패 순간 목적지는 **부재**였고 `.old` 스왑도 관여하지 않았는데
* `rename` 이 false 를 돌려줬으며, 상태를 바꾸지 않고 다시 호출하면 전부 성공했다
* (즉시 1건 / 200ms 후 3건). 재시도가 없으면 그 한 번이 그대로 게시 실패가 되어
* 실패 마커와 대시보드 알림까지 올라간다.
*
* 재시도 자체는 native `rename` 이라 주입할 수 없으므로, **끝내 실패하는** 경우의
* 소요 시간으로 재시도 발생을 관측한다 — 단발 호출이면 대기 없이 즉시 끝난다.
* 이 단언이 없으면 상수를 1 로 되돌려도 다른 케이스는 전부 통과한다.
*
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=manual_command, process_user=web
*
* @effects rename_failure_restores_previous_published_version
*/
public function test_directory_rename_is_retried_before_giving_up(): void
{
$service = $this->service();
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
$final = $service->versionDir(self::VERSION);
$old = $final.'.old';
// 위 A3 케이스와 같은 방식으로 자리를 **지속적으로** 점유해 rename 을 끝까지
// 실패시킨다 — 그래야 재시도가 전부 소진되고 그 대기가 소요 시간에 드러난다.
$fired = false;
$fs = File::partialMock();
$fs->shouldReceive('isDirectory')
->withArgs(fn ($path) => (string) $path === $old)
->andReturnUsing(function ($path) use (&$fired, $final) {
if (! $fired && ! is_dir($final)) {
$fired = true;
mkdir($final, 0775, true);
file_put_contents($final.DIRECTORY_SEPARATOR.'blocker', 'occupied');
}
return is_dir($path);
});
$fs->shouldReceive('isDirectory')->andReturnUsing(fn ($path) => is_dir($path));
$startedAt = microtime(true);
$this->assertFalse($service->publishCurrent(force: true));
$elapsed = microtime(true) - $startedAt;
$this->assertTrue($fired, 'rename 실패를 유도하지 못했다 — 이 테스트는 공허 통과다');
// 시도 3회 = 재시도 대기 2회. 롤백 rename 도 같은 헬퍼를 타므로 실제 대기는
// 이보다 길지만, 하한만 단언해 머신 속도에 좌우되지 않게 한다.
$this->assertGreaterThanOrEqual(
0.4,
$elapsed,
'rename 이 재시도 없이 즉시 포기했다 — 일시 거부가 그대로 게시 실패가 된다'
);
}
/**
* GC — 삭제에 실패한 디렉토리는 경고를 남기고 **삭제 카운트에서 제외**된다 (A5).
*
* 반환값을 검사하지 않으면 소유권 불일치로 삭제가 실패해도 "N개 삭제" 로 보고되어,
* 구버전·고아 tmp 가 무한 누적되는 동안 운영자에게는 정상으로 보인다.
*
* @effects cleanup_excludes_failed_deletions_from_count
*/
public function test_cleanup_excludes_failed_deletion_from_count(): void
{
$service = $this->service();
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
foreach ([100, 200, 300] as $old) {
File::ensureDirectoryExists($service->versionDir($old));
File::put($service->versionDir($old).'/manifest.json', '{}');
}
// 삭제 대상은 100·200 두 개. 그중 100 의 삭제만 실패시킨다.
$undeletable = $service->versionDir(100);
$real = new Filesystem;
Log::spy();
$fs = File::partialMock();
$fs->shouldReceive('deleteDirectory')
->withArgs(fn ($dir) => (string) $dir === $undeletable)
->andReturn(false);
$fs->shouldReceive('deleteDirectory')
->andReturnUsing(fn ($dir, $preserve = false) => $real->deleteDirectory($dir, $preserve));
$deleted = $service->cleanup();
$this->assertSame(1, $deleted, '삭제에 실패한 디렉토리가 삭제 건수에 집계됐다 — 잔존물 누적이 정상으로 보인다');
$this->assertDirectoryDoesNotExist($service->versionDir(200));
$this->assertDirectoryExists($service->versionDir(self::VERSION));
$this->assertDirectoryExists($service->versionDir(300));
Log::shouldHaveReceived('warning')->withArgs(
fn ($message, $context = []) => str_contains((string) $message, '정적 게시 디렉토리 삭제 실패')
);
}
/**
* 락 미획득(경합) — `Log::debug` 만 남고 실패 마커는 기록하지 않는다 (O2 a).
*
* 다른 프로세스가 게시 중인 것은 정상 상황이다. 마커를 남기면 정상적인 동시 요청
* 경합이 실패로 집계돼 진단 표면에 거짓 장애가 뜬다.
*
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects lock_contention_skips_without_failure_marker
*/
public function test_lock_contention_skips_without_failure_marker(): void
{
// 다른 프로세스가 이미 게시 중인 상태 — 같은 버전의 락을 선점한다.
$holder = Cache::lock('ext-static.publish.'.self::VERSION, 300);
$this->assertTrue($holder->get(), '테스트가 락을 선점하지 못했다 — 경합 상황을 만들 수 없다');
Log::spy();
try {
$service = $this->service();
$this->assertFalse($service->publishCurrent());
$this->assertFalse($service->isPublished(self::VERSION));
$this->assertNull(
ExtensionStaticCacheService::failureMarker(),
'정상 경합이 실패 마커로 집계됐다 — 진단 표면에 거짓 장애가 뜬다'
);
Log::shouldHaveReceived('debug')->withArgs(
fn ($message, $context = []) => str_contains((string) $message, '정적 게시 락 미획득')
);
} finally {
$holder->release();
}
}
/**
* 락 획득이 **예외를 던지면** 경고 + `lock_unavailable` 마커를 남긴다 (O2 b).
*
* 락을 제공하지 못하는 캐시 저장소(락 미지원 드라이버, 파일 캐시 디렉토리 권한
* 불일치)에서는 게시가 매 요청 조용히 스킵된다 — 사유가 마커에 남지 않으면 운영자가
* 그 사실을 알 방법이 로그뿐이다.
*
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects lock_provider_failure_recorded_in_marker
*/
public function test_lock_provider_failure_records_marker(): void
{
// 마커 스토어를 먼저 확정시킨다(프로세스 1회 메모이즈) — 아래에서 기본 스토어를
// 갈아끼워도 마커 기록/조회는 같은 스토어를 계속 쓴다.
$this->assertSame(self::VERSION, ExtensionStaticCacheService::getExtensionCacheVersion());
Cache::extend('g7-lockless', fn () => new class(new ArrayStore) extends Repository
{
public function lock($name, $seconds = 0, $owner = null)
{
throw new \BadMethodCallException('This cache store does not support locking.');
}
});
config([
'cache.stores.g7-lockless' => ['driver' => 'g7-lockless'],
'cache.default' => 'g7-lockless',
]);
Log::spy();
$service = $this->service();
$this->assertFalse($service->publishCurrent());
$this->assertFalse($service->isPublished(self::VERSION));
$marker = ExtensionStaticCacheService::failureMarker();
$this->assertIsArray($marker, '락 저장소 장애가 마커에 남지 않았다 — 진단 표면이 영구 침묵한다');
$this->assertSame('lock_unavailable', $marker['reason']);
$this->assertSame(self::VERSION, $marker['version']);
$this->assertStringContainsString('locking', $marker['message']);
Log::shouldHaveReceived('warning')->withArgs(
fn ($message, $context = []) => str_contains((string) $message, '정적 게시 락 획득 불가')
);
}
/**
* 게시 트리는 그룹 쓰기(`g+w`)로 정합화된다 (P2 후반).
*
* 제보 본건은 **비-root CLI 계정 ≠ 웹 계정** 이었다. CLI 최초 게시가 트리를
* `0755 deploy:deploy` 로 굳히면 이후 웹(php-fpm) 재게시가 영구 실패한다.
*
* POSIX 미지원 환경(Windows)에서는 권한 비트를 관측할 수 없다 — 그 경우에도 검사를
* 건너뛰지 않고 **계약 자체**(디렉토리 생성이 명시 chmod 를 거치는가, 정합화가 root
* 갈래와 항상-실행 갈래를 모두 갖는가)를 소스 수준에서 고정한다. 항상-실행 갈래가
* root 조건 안으로 들어가면 종전(비-root no-op) 동작으로 조용히 되돌아간다.
*
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=manual_command, process_user=web
*
* @effects published_tree_is_group_writable
*/
public function test_published_tree_is_group_writable(): void
{
$this->createActiveTemplate();
$service = $this->service();
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
$source = (string) file_get_contents(
(new \ReflectionClass(ExtensionStaticCacheService::class))->getFileName()
);
// ① 디렉토리 생성은 umask 를 무력화하는 명시 chmod 를 거친다.
$makeDirectory = $this->methodBody($source, 'makeDirectory');
$this->assertNotSame('', $makeDirectory, 'makeDirectory 를 소스에서 찾지 못했다 — 검사가 공허하다');
$this->assertStringContainsString(
'@chmod($dir, self::PUBLISH_DIR_MODE)',
$makeDirectory,
'ensureDirectoryExists 의 mode 는 umask 로 깎인다 — 명시 chmod 가 없으면 0755 로 굳는다'
);
$this->assertStringContainsString(
'FilePermissionHelper::inheritOwnershipFromParent($dir)',
$makeDirectory
);
// ② 정합화는 root 갈래와 항상-실행 갈래를 모두 갖는다.
$normalize = $this->methodBody($source, 'normalizeOwnership');
$this->assertNotSame('', $normalize, 'normalizeOwnership 을 소스에서 찾지 못했다 — 검사가 공허하다');
$this->assertStringContainsString('posix_geteuid() === 0', $normalize, 'root 갈래(sudo CLI 게시 대응)가 사라졌다');
$this->assertStringContainsString('FilePermissionHelper::chownRecursive(', $normalize);
// 들여쓰기 8칸 = 메서드 본문 최상위. root 조건 블록(12칸) 안으로 들어가면
// 비-root CLI 계정에서 종전처럼 no-op 이 된다.
$this->assertStringContainsString(
"\n FilePermissionHelper::inheritOwnershipFromParent(\$base);",
$normalize,
'소유권 상속이 root 갈래 안으로 들어갔다 — 비-root CLI 게시가 다시 무방비가 된다'
);
$this->assertStringContainsString(
"\n FilePermissionHelper::syncGroupWritabilityDetailed(\$base, force: true);",
$normalize,
'g+w 승격이 root 갈래 안으로 들어갔다 — 그룹을 공유하는 웹 계정이 재게시할 수 없다'
);
// ③ POSIX 환경에서는 실제 권한 비트까지 확인한다.
if (windows_os() || ! function_exists('posix_geteuid')) {
return;
}
clearstatcache();
$versionDir = $service->versionDir(self::VERSION);
$nested = $versionDir.'/templates/sirsoft-admin_basic';
foreach (array_filter([$service->baseDir(), $versionDir, is_dir($nested) ? $nested : null]) as $dir) {
$this->assertSame(
0020,
@fileperms($dir) & 0020,
"게시 트리에 그룹 쓰기 비트가 없다: {$dir} — 웹 계정의 재게시가 영구 실패한다"
);
}
}
/**
* 실패 마커의 백오프는 **같은 버전**만 억제한다.
*
* 버전이 오르면 그 버전은 아직 한 번도 시도된 적이 없다. 이전 버전의 마커로 막으면
* "캐시 버전 갱신 → 게시" 규율이 마커 TTL 창(최대 300초) 동안 도로 끊긴다.
*
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
*
* @effects publish_failure_backoff_is_scoped_to_version
*/
public function test_previous_version_failure_marker_does_not_suppress_new_version(): void
{
$this->app['env'] = 'production';
ExtensionStaticCacheService::resetPublishScheduleForTesting();
ExtensionStaticCacheService::fakeRootProcessForTesting(false);
// 이전 버전(VERSION)의 신선한 실패 마커
Cache::put('g7:core:ext.static.publish_failure', [
'version' => self::VERSION,
'at' => now()->toIso8601String(),
'reason' => 'parent_not_writable',
'count' => 2,
'message' => 'denied',
], 300);
// 버전 bump — 이 버전은 아직 한 번도 시도된 적이 없다.
Cache::put('g7:core:ext.cache_version', self::VERSION + 1);
ExtensionStaticCacheService::schedulePublishOnTerminate();
$this->assertTrue(
ExtensionStaticCacheService::isPublishScheduledForTesting(),
'이전 버전의 마커가 새 버전의 게시 예약을 막았다 — 버전 갱신 → 게시 규율이 TTL 창 동안 끊긴다'
);
$this->app->terminate();
$this->assertTrue($this->service()->isPublished(self::VERSION + 1));
}
/**
* 소스에서 메서드 본문을 잘라냅니다 (다음 메서드 선언 직전까지).
*
* @param string $content 파일 전체 내용
* @param string $method 메서드명
* @return string 본문 (찾지 못하면 빈 문자열)
*/
private function methodBody(string $content, string $method): string
{
$start = strpos($content, "function {$method}(");
if ($start === false) {
return '';
}
$rest = substr($content, $start);
$next = preg_match(
'/\n (?:public|protected|private)\s+(?:static\s+)?function\s/',
substr($rest, 1),
$m,
PREG_OFFSET_CAPTURE
);
return $next === 1 ? substr($rest, 0, $m[0][1] + 1) : $rest;
}
}
@@ -586,7 +586,7 @@ class TemplateAssetServingTest extends TestCase
/**
* 개발 환경에서 components.json 은 no-cache (파일 수정 즉시 반영 — F10)
*
* @scenario publish_state=unpublished, environment=dev, trigger=self_heal, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=dev, trigger=self_heal, process_user=web
*
* @effects fallback_api_no_cache_in_dev
*/
@@ -193,7 +193,7 @@ class TemplateLanguageServingTest extends TestCase
/**
* 개발 환경에서 lang 은 no-cache (파일 수정 즉시 반영 — F10)
*
* @scenario publish_state=unpublished, environment=dev, trigger=manual_command, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=dev, trigger=manual_command, process_user=web
*/
public function test_language_no_cache_in_development(): void
{
@@ -6,7 +6,7 @@
* ~500KB 중복 / 부트 ~1.3s 연장이 발생했다. blade 주입 cache_version 시드가
* 이를 제거했음을 실브라우저에서 잠근다.
*
* @scenario publish_state=published, environment=production, trigger=lifecycle, process_user=web
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=lifecycle, process_user=web
* @effects no_duplicate_boot_requests, versioned_boot_urls
*/
import { test, expect, type Page } from '@playwright/test';
@@ -8,7 +8,7 @@
* env 가드 — 대상 사이트가 정적 게시 미적용(비프로덕션/kill-switch/미게시)이면
* staticBase 미주입으로 skip 된다 (첫 방문이 자가 치유를 예약하므로 워밍 1회 수행).
*
* @scenario publish_state=partial, environment=production, trigger=self_heal, process_user=web
* @scenario publish_state=partial, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=self_heal, process_user=web
* @effects static_first_fetch_falls_back_to_api_on_miss, fallback_is_observable_via_console_warn
*/
import { test, expect, type Page } from '@playwright/test';
@@ -33,7 +33,7 @@ async function probeStaticBase(page: Page): Promise<string | null> {
test.describe('정적 게시 fast path + 폴백 (#122)', () => {
/**
* @scenario publish_state=published, environment=production, trigger=self_heal, process_user=web
* @scenario publish_state=published, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=self_heal, process_user=web
* @effects versioned_boot_urls
*/
test('@smoke 정적 URL 로 부트 리소스를 수신한다 (static-first)', async ({ page }) => {
@@ -109,4 +109,96 @@ test.describe('정적 게시 fast path + 폴백 (#122)', () => {
// 폴백은 조용하지 않다 — console warn 으로 관측 가능
expect(warns.some((w) => w.includes('fetchStaticFirst')), `warns: ${warns.join(' | ')}`).toBe(true);
});
/**
* 정적 응답이 **200 인데 본문이 손상**된 경우에도 폴백해 화면이 정상이어야 한다.
*
* 디스크 풀/quota 로 절단된 게시본은 웹서버가 정상 200 으로 서빙한다. `response.ok`
* 만 보던 종전 구현은 폴백하지 못한 채 `response.json()` 이 던져 부팅 전체가 실패했다 —
* 3층 폴백이 유일하게 개입하지 못하던 경로다.
*
* @scenario publish_state=partial, artifact_integrity=absent, filesystem_writable=writable, environment=production, trigger=self_heal, process_user=web
* @effects truncated_artifact_rejected_before_manifest, static_first_fetch_falls_back_to_api_on_miss
*/
test('@smoke 정적 200 + 손상 본문이어도 폴백으로 화면이 정상 렌더된다', 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 corrupted = 0;
const apiFallbacks: string[] = [];
// 404 가 아니라 **200 + 잘린 JSON** 을 돌려준다 — 종전 구현이 통과시키던 형태.
await page.route(
(url) => /\/build\/ext\/\d+\/templates\/[^/]+\/(routes|components|lang\/[a-z-]+)\.json$/.test(url.pathname),
(route) => {
corrupted += 1;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: '{"success":true,"data":{"messa',
});
}
);
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(corrupted).toBeGreaterThan(0);
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);
expect(
warns.some((w) => w.includes('malformed JSON')),
`warns: ${warns.join(' | ')}`
).toBe(true);
});
/**
* 정적 미스는 SPA 셸 HTML 이 아니라 404 를 받아야 한다 — 확장자 변종 포함.
*
* `mjs` · `webp` · `otf` 는 에셋 서빙이 허용하는데 catch-all 제외 목록에는 없었다.
* 없는 `.mjs` 가 `Content-Type: text/html` 인 200 을 받으면 브라우저는 그것을
* 스크립트로 파싱하다 죽는데, 응답이 성공이라 `onerror` 도 발화하지 않는다.
*
* @effects static_miss_returns_404_for_every_servable_extension
*/
test('@smoke 없는 정적 자산은 확장자 변종에서도 404 다 (HTML 200 아님)', async ({ page }) => {
const base = await probeStaticBase(page);
test.skip(base === null, '대상 사이트에 정적 게시 미적용 (staticBase 미주입)');
for (const extension of ['mjs', 'webp', 'otf', 'js', 'css', 'json']) {
const response = await page.request.get(
`${base}/templates/sirsoft-basic/assets/__missing__.${extension}`
);
const contentType = response.headers()['content-type'] ?? '';
// 계약은 **상태 코드**다. 404 응답의 본문이 HTML 인 것은 정상이며(라라벨 오류 페이지),
// 문제는 "없는 자산에 200 이 나가는 것" 이었다 — 200 이면 브라우저가 그 HTML 을
// 스크립트로 파싱하다 죽고, 응답이 성공이라 onerror 도 발화하지 않는다.
expect(
response.status(),
`.${extension} 가 ${response.status()} (content-type: ${contentType}) — SPA 셸 200 이 반환되면 스크립트 파싱이 죽는다`
).toBe(404);
}
});
});
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace Tests\Unit\Build;
use Tests\TestCase;
/**
* 빌드 산출물 디렉토리 계약 테스트 (#122 B1).
*
* vite 의 `build.emptyOutDir` 기본값은 `true` 다 — 산출물 디렉토리를 통째로 비운다.
* 그런데 그 디렉토리에는 vite 가 만들지 않는 **서빙 자산**이 함께 산다:
* `public/build/core/` 3번들(폴백 없는 동기 classic 스크립트), `public/build/ext/{v}/`
* 게시본(이미 배달된 HTML 의 immutable URL), 확장 `dist/vendor/`(동봉 제3자 자산).
* 소실은 예외도 서버 로그도 남기지 않고 브라우저 404 로만 나타난다.
*
* 픽스처 기반 정적 검사가 판정식을 잠그고, 이 테스트는 **저장소의 실제 상태**를
* 계약으로 고정한다 — git 추적 대상 vite config 전부가 `emptyOutDir` 을 명시 선언하고
* 그 값이 `false` 여야 한다.
*/
class ViteOutDirContractTest extends TestCase
{
/**
* 모든 git 추적 vite config 가 `emptyOutDir: false` 를 명시 선언한다.
*
* @effects vite_configs_declare_empty_outdir_false
*/
public function test_every_tracked_vite_config_declares_empty_outdir_false(): void
{
$configs = $this->trackedViteConfigs();
$this->assertNotEmpty($configs, 'vite config 를 하나도 찾지 못했다 — 이 계약 검사가 공허하다');
$this->assertContains(
'vite.config.js',
$configs,
'루트 vite config 가 목록에 없다 — 열거가 저장소 실제 상태를 반영하지 못한다'
);
foreach ($configs as $relative) {
$source = $this->stripComments((string) file_get_contents(base_path($relative)));
$this->assertMatchesRegularExpression(
'/\bemptyOutDir\s*:/',
$source,
"{$relative} 이 emptyOutDir 을 선언하지 않았다 — 기본값 true 로 산출물 디렉토리를 통째로 비운다"
);
preg_match_all('/\bemptyOutDir\s*:\s*([A-Za-z0-9_.]+)/', $source, $matches);
foreach ($matches[1] as $value) {
$this->assertSame(
'false',
$value,
"{$relative} 의 emptyOutDir 이 false 가 아니다 — 함께 사는 서빙 자산(코어 3번들 · 게시본 · 동봉 vendor)이 빌드마다 소실된다"
);
}
}
}
/**
* git 추적 대상 vite config 의 저장소 상대 경로 목록을 반환합니다.
*
* git 을 쓸 수 없는 환경에서는 추적 대상이 실제로 놓이는 위치(루트 · `_bundled`)를
* 직접 훑는다 — 활성 확장 디렉토리 사본(git 미추적)은 계약 대상이 아니다.
*
* @return array<int, string> 상대 경로 (구분자 `/`)
*/
private function trackedViteConfigs(): array
{
$output = [];
$status = 1;
@exec('git -C '.escapeshellarg(base_path()).' ls-files -- '.escapeshellarg('*vite.config*'), $output, $status);
if ($status === 0 && $output !== []) {
$tracked = array_values(array_filter(
array_map(fn ($line) => trim(str_replace('\\', '/', (string) $line)), $output),
fn ($line) => (bool) preg_match('#(^|/)vite\.config[^/]*\.(js|ts)$#', $line)
));
if ($tracked !== []) {
sort($tracked);
return $tracked;
}
}
$patterns = [
base_path('vite.config*.js'),
base_path('vite.config*.ts'),
base_path('modules/_bundled/*/vite.config*.js'),
base_path('modules/_bundled/*/vite.config*.ts'),
base_path('plugins/_bundled/*/vite.config*.js'),
base_path('plugins/_bundled/*/vite.config*.ts'),
base_path('templates/_bundled/*/vite.config*.js'),
base_path('templates/_bundled/*/vite.config*.ts'),
];
$found = [];
foreach ($patterns as $pattern) {
foreach (glob($pattern) ?: [] as $path) {
$found[] = ltrim(str_replace('\\', '/', substr($path, strlen(base_path()))), '/');
}
}
sort($found);
return $found;
}
/**
* 주석을 제거합니다 — 문서 주석 안의 예시 표기가 선언으로 오인되지 않게 한다.
*
* @param string $source 원본 소스
* @return string 주석이 제거된 소스
*/
private function stripComments(string $source): string
{
$withoutBlocks = preg_replace('#/\*.*?\*/#s', '', $source) ?? $source;
return preg_replace('#//[^\n]*#', '', $withoutBlocks) ?? $withoutBlocks;
}
}
@@ -7,6 +7,7 @@ use App\Enums\ExtensionStatus;
use App\Extension\Cache\PluginCacheDriver;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Models\Template;
use App\Services\ExtensionStaticCacheService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
@@ -285,4 +286,39 @@ class ClearsTemplateCachesTest extends TestCase
$this->assertGreaterThan(0, $newVersion);
$this->assertLessThanOrEqual(time(), $newVersion);
}
/**
* 버전 **재생성** 경로도 정적 게시를 예약한다 (D1).
*
* 회귀 가드: `incrementExtensionCacheVersion()` 에만 예약이 있고 재생성 경로에는
* 없었다. 그래서 `cache:clear` 후 첫 호출자가 CLI 면 포인터만 새 버전으로 점프하고
* 산출물은 옛 버전에 남았다 — "캐시 버전 갱신 → 게시" 단일 지점 규율의 유일한 구멍.
* 스케줄 GC 가 바로 그 첫 호출자라 매일 재현됐다.
*
* @effects regenerate_path_schedules_publish
*/
public function test_regenerate_path_schedules_static_publish(): void
{
$this->app['env'] = 'production';
ExtensionStaticCacheService::resetPublishScheduleForTesting();
ExtensionStaticCacheService::fakeRootProcessForTesting(false);
Cache::forget('g7:core:ext.static.publish_failure');
// 키 부재 → getExtensionCacheVersion 이 재생성 경로를 탄다.
Cache::forget('g7:core:ext.cache_version');
$this->assertFalse(
ExtensionStaticCacheService::isPublishScheduledForTesting(),
'사전 조건 오염 — 예약 플래그가 이미 서 있다'
);
ClearsTemplateCaches::getExtensionCacheVersion();
$this->assertTrue(
ExtensionStaticCacheService::isPublishScheduledForTesting(),
'재생성 경로가 게시를 예약하지 않았다 — 포인터만 점프하고 산출물이 옛 버전에 남는다'
);
ExtensionStaticCacheService::resetPublishScheduleForTesting();
}
}
@@ -100,11 +100,74 @@ class ExtensionBundleServiceTest extends TestCase
return $ext;
}
/**
* 에셋 **매니페스트 선언**(`getAssets()`)을 노출하는 가짜 확장 인스턴스를 만든다.
*
* 산출물 경로(`getBuiltAssetAbsolutePaths`)는 존재하지 않는 파일을 가리킨다 —
* "선언은 있는데 산출물이 없다"(dist 소실) 상태를 그대로 재현하기 위해서다.
*
* @param string $identifier 확장 식별자
* @param int $priority 로딩 우선순위
* @param array<string, mixed> $assets 매니페스트 assets 선언
* @param string $strategy 로딩 전략
*/
private function fakeExtensionWithAssets(string $identifier, int $priority, array $assets, string $strategy = 'global'): object
{
$ext = Mockery::mock();
$ext->shouldReceive('hasAssets')->andReturn($assets !== []);
$ext->shouldReceive('getIdentifier')->andReturn($identifier);
$ext->shouldReceive('getAssetLoadingConfig')->andReturn([
'strategy' => $strategy,
'priority' => $priority,
'dependencies' => [],
]);
$ext->shouldReceive('getAssets')->andReturn($assets);
$ext->shouldReceive('getBuiltAssetAbsolutePaths')->andReturn(
array_map(fn () => $this->fixtureDir.'/missing-'.$identifier.'.out', $assets)
);
return $ext;
}
private function service(): ExtensionBundleService
{
return new ExtensionBundleService($this->moduleManager, $this->pluginManager);
}
/**
* 선언 수는 **매니페스트 기준**이다 — 산출물 파일 존재 여부와 무관하다 (E2).
*
* 이 값이 "실제로 병합된 확장 수" 로 계산되면 dist 가 통째로 비어 있을 때
* `기대 0 = 결과 0` 이 되어 장애가 정상(빈 200)으로 위장된다. 실측 A/B: dist 를
* 비우면 수정 전 `modules/bundle/js` 가 빈 200, 수정 후 503 이다.
*
* @effects asset_declaration_count_reads_manifest_not_built_files
*/
public function test_counts_asset_declaring_extensions_from_manifest_not_built_output(): void
{
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-js' => $this->fakeExtensionWithAssets('ext-js', 10, ['js' => ['output' => 'dist/js/ext-js.iife.js']]),
'ext-both' => $this->fakeExtensionWithAssets('ext-both', 20, [
'js' => ['output' => 'dist/js/ext-both.iife.js'],
'css' => ['output' => 'dist/css/ext-both.css'],
]),
'ext-none' => $this->fakeExtensionWithAssets('ext-none', 30, []),
// 병합 대상 모집단과 같은 필터 — global 전략이 아니면 세지 않는다
'ext-layout' => $this->fakeExtensionWithAssets('ext-layout', 40, [
'js' => ['output' => 'dist/js/ext-layout.iife.js'],
], 'layout'),
]);
$service = $this->service();
$this->assertSame(2, $service->countAssetDeclaringExtensions('module', 'js'));
$this->assertSame(1, $service->countAssetDeclaringExtensions('module', 'css'));
// 산출물은 하나도 존재하지 않는다 → 병합 결과는 빈 문자열.
// "선언 > 0 && 결과 0" 이 곧 컨트롤러의 503 조건이다.
$this->assertSame('', $service->getBundleFilePath('module', 'js', 12345));
}
public function test_orders_global_assets_by_priority_ascending(): void
{
$a = $this->writeFixture('a.js', '(function(){})()');
@@ -324,6 +387,69 @@ class ExtensionBundleServiceTest extends TestCase
$this->assertFileExists($bundleDir.'/plugin.100.js');
}
/**
* clearBundles 는 **현재 버전을 보존**한다 (E3).
*
* 현재 버전까지 지우면 같은 순간 서빙 중인 웹 요청이 "존재함" 판정 직후
* `filemtime()` 에서 500 을 낸다(bump 직후 TOCTOU). `cleanupStaleBundles` 와
* 정책이 갈라져 있던 것이 원인이었다.
*
* @effects clear_bundles_preserves_current_version
*/
public function test_clear_bundles_preserves_current_version(): void
{
$bundleDir = storage_path('app/ext-bundles');
File::ensureDirectoryExists($bundleDir);
$current = $this->service()->getCurrentVersion();
File::put($bundleDir."/module.{$current}.js", 'current');
File::put($bundleDir.'/module.100.js', 'old');
$deleted = $this->service()->clearBundles('module');
$this->assertSame(1, $deleted);
$this->assertFileExists(
$bundleDir."/module.{$current}.js",
'현재 버전이 삭제됐다 — 서빙 중인 요청이 filemtime 에서 500 을 낸다'
);
$this->assertFileDoesNotExist($bundleDir.'/module.100.js');
}
/**
* GC 는 원자적 쓰기의 임시 파일(`*.tmp.{pid}`)도 정리한다 — 단 나이 가드를 지킨다 (E4).
*
* 종전에는 이 파일명이 번들 파일 패턴에 맞지 않아 GC 대상에서 통째로 빠졌고,
* rename 이 실패한 만큼 영구 잔존했다(실측 560개).
*
* @effects cleanup_removes_stale_atomic_write_temp_files
*/
public function test_cleanup_removes_stale_temp_bundle_files_only(): void
{
$bundleDir = storage_path('app/ext-bundles');
File::ensureDirectoryExists($bundleDir);
$fresh = $bundleDir.'/module.200.js.tmp.11111';
$stale = $bundleDir.'/module.200.js.tmp.22222';
File::put($fresh, 'writing now');
File::put($stale, 'orphan');
touch($stale, time() - 3600);
clearstatcache();
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
try {
$deleted = $this->service()->cleanupStaleBundles(200);
$this->assertFileExists($fresh, '진행 중인 쓰기의 임시 파일이 삭제됐다');
$this->assertFileDoesNotExist($stale, '고아 임시 파일이 정리되지 않았다 — 영구 누적된다');
$this->assertSame(1, $deleted);
} finally {
// 번들 디렉토리는 테스트 간 공유된다 — 남기면 형제 케이스의 삭제 건수가 틀어진다.
@unlink($fresh);
@unlink($stale);
}
}
public function test_plugin_bundle_orders_by_priority_gdpr_first_when_lowest(): void
{
// gdpr 가 priority 50 으로 최상단(제약 1 회귀 가드) — 이름 하드코딩 아닌 선언 결과
+3 -3
View File
@@ -223,7 +223,7 @@ class AssetUrlTest extends TestCase
* 정적 게이트 3조건 — 프로덕션 + enabled + 게시 완료(manifest) 를 전부
* 통과해야만 base 가 반환된다.
*
* @scenario publish_state=unpublished, environment=production, trigger=self_heal, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=self_heal, process_user=web
*
* @effects static_gate_requires_manifest, kill_switch_disables_publish_and_gate
*/
@@ -261,7 +261,7 @@ class AssetUrlTest extends TestCase
* 태그 계층 파일 단위 게이트 — manifest 는 있어도 그 자산의 실파일이 없으면
* 그 자산만 종전 API URL 로 방출된다 (나머지는 정적 URL).
*
* @scenario publish_state=partial, environment=production, trigger=manual_command, process_user=web
* @scenario publish_state=partial, artifact_integrity=intact, filesystem_writable=writable, environment=production, trigger=manual_command, process_user=web
*
* @effects tag_layer_checks_individual_file_existence
*/
@@ -373,7 +373,7 @@ class AssetUrlTest extends TestCase
/**
* base null(게이트 미통과) 이면 기존 URL 과 바이트 동일해야 한다 (호출부 무변경 계약).
*
* @scenario publish_state=unpublished, environment=dev, trigger=kill_switch, process_user=web
* @scenario publish_state=unpublished, artifact_integrity=intact, filesystem_writable=writable, environment=dev, trigger=kill_switch, process_user=web
*/
public function test_게이트_미통과시_종전_ur_l_바이트_동일(): void
{
+66
View File
@@ -27,6 +27,14 @@ axes:
# 7.0.10 업그레이드 실사례: root terminating 게시가 캐시 락 샤드를 root 소유로 남겨
# 웹 캐시 쓰기가 전면 500. 이 축이 없어 24축 매트릭스가 그 조합을 못 잡았다.
process_user: [web, root_cli]
# 산출물 무결성 축 — 200 인데 본문이 온전하지 않은 상태를 축으로 세운다.
# File::put 은 디스크 풀/quota 에서 짧은 int 를 돌려주며 성공한 것처럼 보이고,
# 절단된 JSON 은 웹서버가 정상 200 으로 서빙한다 — response.ok 만 보는 프론트가
# 폴백하지 못한 채 부팅 전체가 실패하던 유일한 사각이다 (#122 A1).
artifact_integrity: [intact, truncated, absent]
# 쓰기 가능성 축 — 제보 본건. CLI 계정과 웹 계정이 다르면 게시 트리 소유권이
# 최초 게시자에게 고정되어 이후 재게시가 영구 실패한다 (P1/P2).
filesystem_writable: [writable, parent_denied, tree_denied]
exclusions:
- { environment: dev, publish_state: published, reason: "dev 는 staticBase 미주입 — 게시 상태와 무관하게 전 리소스 API 직행" }
@@ -39,6 +47,44 @@ exclusions:
- { process_user: root_cli, trigger: manual_command, reason: "명시적 ext-static:publish 는 root 게이트 밖 (운영자 책임 — 규정 §6). 게시 로직 자체는 web 축 케이스가 검증" }
- { process_user: root_cli, publish_state: published, reason: "root 게이트는 게시 상태 판정 이전에 위치 — 상태와 직교, 대표 조합(unpublished×lifecycle)으로 고정" }
- { process_user: root_cli, publish_state: partial, reason: "동일 — 상태 직교" }
# --- artifact_integrity: 기본값 intact 외의 값은 대표 조합에 고정한다 ---
# 무결성은 "게시된 산출물을 소비할 때" 만 의미가 있다. 다른 축과 곱하면 조합만 늘고
# 검증 대상은 같아지므로, root_cli 축과 같은 방식으로 대표 조합에 못박는다.
- { artifact_integrity: truncated, environment: dev, reason: "dev 는 정적 경로가 없어 절단 산출물을 참조할 경로 자체가 없다" }
- { artifact_integrity: absent, environment: dev, reason: "동일" }
- { artifact_integrity: truncated, process_user: root_cli, reason: "무결성 판정은 소비 시점 — 게시 주체(uid)와 직교" }
- { artifact_integrity: absent, process_user: root_cli, reason: "동일" }
- { artifact_integrity: truncated, filesystem_writable: parent_denied, reason: "쓸 수 없으면 절단 산출물도 남지 않는다 — 두 실패 모드는 배타적" }
- { artifact_integrity: truncated, filesystem_writable: tree_denied, reason: "동일" }
- { artifact_integrity: absent, filesystem_writable: parent_denied, reason: "산출물 부재는 쓰기 불가의 결과 — 별도 조합으로 세지 않는다" }
- { artifact_integrity: absent, filesystem_writable: tree_denied, reason: "동일" }
- { artifact_integrity: truncated, publish_state: unpublished, reason: "미게시 상태에는 산출물 자체가 없다 — 판정 대상 부재" }
- { artifact_integrity: truncated, publish_state: published, reason: "절단은 manifest 기록 전에 예외로 차단된다 — published 로 확정될 수 없다" }
- { artifact_integrity: absent, publish_state: published, reason: "게시 완료(manifest 존재)와 산출물 부재는 동시에 성립하지 않는다" }
- { artifact_integrity: absent, publish_state: unpublished, reason: "미게시와 중복 — publish_state 축이 이미 표현한다" }
- { artifact_integrity: truncated, trigger: self_heal, reason: "대표 조합(partial×lifecycle)으로 고정 — 트리거와 직교" }
- { artifact_integrity: truncated, trigger: manual_command, reason: "동일" }
- { artifact_integrity: truncated, trigger: kill_switch, reason: "kill-switch 는 게시 자체를 막는 선행 게이트" }
- { artifact_integrity: absent, trigger: lifecycle, reason: "대표 조합(partial×self_heal)으로 고정 — 산출물 부재는 소비 시점 폴백이 대상이다" }
- { artifact_integrity: absent, trigger: manual_command, reason: "동일" }
- { artifact_integrity: absent, trigger: kill_switch, reason: "kill-switch 는 정적 경로 자체를 차단" }
# --- filesystem_writable: 기본값 writable 외의 값은 대표 조합에 고정한다 ---
# 쓰기 불가는 게시 시도 시점에만 의미가 있다(프리플라이트). 소비 축과 곱할 이유가 없다.
- { filesystem_writable: parent_denied, environment: dev, reason: "dev 는 게시 자체를 하지 않는다 (terminating 게이트가 프로덕션 한정)" }
- { filesystem_writable: tree_denied, environment: dev, reason: "동일" }
- { filesystem_writable: parent_denied, publish_state: published, reason: "부모 쓰기 불가면 게시가 성립한 적이 없다" }
- { filesystem_writable: tree_denied, publish_state: published, reason: "동일" }
- { filesystem_writable: parent_denied, publish_state: partial, reason: "프리플라이트가 병합 전에 끊으므로 부분 산출물이 생기지 않는다" }
- { filesystem_writable: tree_denied, publish_state: partial, reason: "동일" }
- { filesystem_writable: parent_denied, trigger: kill_switch, reason: "kill-switch 는 쓰기 판정 이전의 선행 게이트 — 권한 무관" }
- { filesystem_writable: tree_denied, trigger: kill_switch, reason: "동일" }
- { filesystem_writable: parent_denied, trigger: self_heal, reason: "대표 조합(unpublished×lifecycle)으로 고정 — 트리거와 직교" }
- { filesystem_writable: parent_denied, trigger: manual_command, reason: "동일" }
- { filesystem_writable: tree_denied, trigger: self_heal, reason: "동일" }
- { filesystem_writable: tree_denied, trigger: manual_command, reason: "동일" }
- { filesystem_writable: parent_denied, process_user: root_cli, reason: "root 게이트가 쓰기 판정 이전에 예약을 막는다 — uid 와 직교" }
- { filesystem_writable: tree_denied, process_user: root_cli, reason: "동일" }
effects:
- published_lang_matches_api_payload
@@ -70,6 +116,19 @@ effects:
- published_htaccess_declares_compression
- bundle_script_static_miss_falls_back_to_api
- root_cli_defers_publish_to_web_self_heal
- truncated_artifact_rejected_before_manifest
- parent_denied_short_circuits_before_merge
- regenerate_path_schedules_publish
- gc_preserves_previous_when_current_absent
- publish_failure_reaches_dashboard
- publish_failure_recorded_in_marker
- publish_success_clears_failure_marker
- publish_failure_backoff_suppresses_reschedule
- cleanup_removes_only_stale_work_directories
- static_miss_returns_404_for_every_servable_extension
- admin_catch_all_shares_static_exclusion
- prune_skips_active_serving_path
- extension_copy_paths_inherit_directory_ownership
test_files:
- tests/Feature/Services/ExtensionStaticCacheServiceTest.php
@@ -79,6 +138,13 @@ test_files:
- tests/Feature/Template/TemplateLanguageServingTest.php
- tests/Feature/Api/Public/LayoutServingTest.php
- tests/Feature/Http/BuildPathCatchAllExclusionTest.php
- tests/Feature/Api/Public/ExtensionBundleServingTest.php
- tests/Feature/Dashboard/StaticPublishAlertTest.php
- tests/Feature/Console/BuildCommandPruneScopeTest.php
- tests/Feature/Extension/ExtensionPendingOwnershipTest.php
- tests/Unit/Extension/ClearsTemplateCachesTest.php
- tests/Unit/Services/ExtensionBundleServiceTest.php
- tests/Unit/Build/ViteOutDirContractTest.php
- tests/Unit/Support/AssetUrlTest.php
- tests/Unit/Seo/SeoRendererStaticAssetBypassTest.php
- resources/js/core/__tests__/TemplateApp.cacheVersionSeed.test.ts