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:
1 parent
fe973f40af
commit
b4ed33aa44
52 files changed
+3495
-147
No files matched your search
@@ -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 회귀 가드) — 이름 하드코딩 아닌 선언 결과
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user