fix(core): 공개 템플릿 config 캐시 무효화 누락과 확장 캐시 삭제 경로 동종 결함 정비

공개 config.json 의 고정 캐시 키(template.config.{identifier})가 어떤 갱신
경로에서도 forget 되지 않아 template:update/cache-clear/비활성화/삭제 후에도
최대 1시간(TTL) 이전 manifest 로 응답되던 결함(공개 )을 수정한다.

- TemplateManager::clearTemplateCache 공개화 — config/components_manifest(두
 변종)/현재 버전 routes·language 키 능동 forget, updateTemplate cleanup 호출
- forgetLayoutCacheKeys 가 편집기용 .with_source_meta 변종까지 삭제
- ext.cache_version 쓰기를 incrementExtensionCacheVersion 단일 지점으로 통일
- module/plugin:cache-clear 의 유령 키 forget 을 실재 캐시(레이아웃 서빙/해석
 캐시, 상태 키, 미들웨어 인덱스, 버전 bump) 무효화로 교체
- 공개 routes/language/layout API 의 ?v 생략 폴백을 0 → 현재 버전으로 교정
This commit is contained in:
HeuJung committed 2026-08-17 13:22:48 +09:00
1 parent 09a700e4c7
commit e819db9d42
27 files changed
+891 -247

No files matched your search

@@ -2,6 +2,7 @@
namespace Tests\Feature\Api\Public;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Models\Template;
use App\Models\TemplateLayout;
@@ -210,9 +211,13 @@ class LayoutServingTest extends TestCase
],
]);
// PublicLayoutController 는 CacheInterface + 버전 키 ("layout.{id}.{name}.v{v}") 사용
$cache = app(\App\Contracts\Extension\CacheInterface::class);
$cacheKey = "layout.{$template->identifier}.{$layout->name}.v0";
// PublicLayoutController 는 CacheInterface + 버전 키 ("layout.{id}.{name}.v{v}") 사용.
// `?v` 생략 시 현재 확장 캐시 버전으로 폴백하므로 (#588 — `.v0` 사각 키 방지)
// 버전을 시드해 결정적 키로 검증한다
Cache::put('g7:core:ext.cache_version', 1234);
$cache = app(CacheInterface::class);
$cacheKey = "layout.{$template->identifier}.{$layout->name}.v1234";
$cache->forget($cacheKey);
// Act: 첫 번째 요청 (캐시 미스, DB 조회)
@@ -4,10 +4,17 @@ namespace Tests\Feature\Console\Commands\Module;
use App\Enums\ExtensionOwnerType;
use App\Enums\ExtensionStatus;
use App\Enums\LayoutSourceType;
use App\Extension\Cache\CoreCacheDriver;
use App\Extension\ExtensionMiddlewareRegistry;
use App\Extension\ModuleManager;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Models\Module;
use App\Models\Permission;
use App\Models\Template;
use App\Models\TemplateLayout;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\Helpers\ProtectsExtensionDirectories;
use Tests\TestCase;
@@ -163,24 +170,97 @@ class ModuleArtisanCommandsTest extends TestCase
/**
* module:cache-clear 커맨드가 모든 캐시를 삭제하는지 테스트
*
* 실재하는 상태 키(ext.modules.*_identifiers)가 소멸하고 캐시 버전이 bump 되는지
* 검증한다 (#588 — 기존 forget 대상은 writer 없는 유령 키였다).
*/
public function test_cache_clear_command_clears_all_caches(): void
{
$coreCache = new CoreCacheDriver(config('cache.default', 'array'));
$coreCache->put('ext.modules.active_identifiers', ['stale-module'], 3600);
$coreCache->put('ext.modules.installed_identifiers', ['stale-module'], 3600);
// 실제 writer(ExtensionMiddlewareRegistry::buildIndex)와 동형으로 태그 포함
// remember — flush() 는 taggable 스토어에서 태그 인덱스 기반으로 삭제한다
$coreCache->remember('extension.middleware_index', fn () => [['stale' => true]], 3600, [ExtensionMiddlewareRegistry::CACHE_TAG]);
Cache::put('g7:core:ext.cache_version', 1000);
$this->artisan('module:cache-clear')
->expectsOutput(__('modules.commands.cache_clear.clearing_all'))
->assertExitCode(0);
$this->assertNull(
$coreCache->get('ext.modules.active_identifiers'),
'module:cache-clear 후 활성 모듈 상태 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$coreCache->get('ext.modules.installed_identifiers'),
'module:cache-clear 후 설치 모듈 상태 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$coreCache->get('extension.middleware_index'),
'module:cache-clear 후 확장 미들웨어 인덱스 캐시(extension.middleware_index)가 삭제되어야 합니다.'
);
$this->assertGreaterThan(
1000,
ClearsTemplateCaches::getExtensionCacheVersion(),
'module:cache-clear 후 확장 캐시 버전이 bump 되어야 합니다.'
);
}
/**
* module:cache-clear 커맨드가 특정 모듈의 캐시만 삭제하는지 테스트
*
* 해석 캐시(layout_resolver.{templateId}.{name})는 버전 접미사 없는 고정 키로
* 레이아웃 row ID 를 저장하므로, 커맨드가 능동 삭제하지 않으면 TTL 동안
* 이전 해석 결과가 유지된다 (#588 동종 보강).
*/
public function test_cache_clear_command_clears_single_module_cache(): void
{
$identifier = 'sirsoft-board';
// 모듈 소유 레이아웃 row — 해석 캐시 키 도출(getLayoutsByModule)의 원천
$template = Template::factory()->create([
'identifier' => 'cachetest-admin_basic',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
]);
TemplateLayout::create([
'template_id' => $template->id,
'name' => 'sirsoft-board.cache_probe',
'source_type' => LayoutSourceType::Module->value,
'source_identifier' => $identifier,
'content' => ['meta' => ['title' => 'probe'], 'components' => []],
]);
$coreCache = new CoreCacheDriver(config('cache.default', 'array'));
$coreCache->put('ext.modules.active_identifiers', ['stale-module'], 3600);
$coreCache->put("layout_resolver.{$template->id}.sirsoft-board.cache_probe", 12345, 3600);
// 실제 writer(ExtensionMiddlewareRegistry::buildIndex)와 동형으로 태그 포함
// remember — flush() 는 taggable 스토어에서 태그 인덱스 기반으로 삭제한다
$coreCache->remember('extension.middleware_index', fn () => [['stale' => true]], 3600, [ExtensionMiddlewareRegistry::CACHE_TAG]);
Cache::put('g7:core:ext.cache_version', 1000);
$this->artisan('module:cache-clear', ['identifier' => $identifier])
->expectsOutput(__('modules.commands.cache_clear.clearing_single', ['module' => $identifier]))
->assertExitCode(0);
$this->assertNull(
$coreCache->get('ext.modules.active_identifiers'),
'module:cache-clear(단일) 후 모듈 상태 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$coreCache->get("layout_resolver.{$template->id}.sirsoft-board.cache_probe"),
'module:cache-clear(단일) 후 해당 모듈 레이아웃의 해석 캐시(layout_resolver.*)가 삭제되어야 합니다.'
);
$this->assertNull(
$coreCache->get('extension.middleware_index'),
'module:cache-clear(단일) 후 확장 미들웨어 인덱스 캐시(extension.middleware_index)가 삭제되어야 합니다.'
);
$this->assertGreaterThan(
1000,
ClearsTemplateCaches::getExtensionCacheVersion(),
'module:cache-clear(단일) 후 확장 캐시 버전이 bump 되어야 합니다.'
);
}
/**
@@ -4,9 +4,13 @@ namespace Tests\Feature\Console\Commands\Plugin;
use App\Enums\ExtensionOwnerType;
use App\Enums\ExtensionStatus;
use App\Extension\Cache\CoreCacheDriver;
use App\Extension\ExtensionMiddlewareRegistry;
use App\Extension\PluginManager;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Models\Permission;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Tests\Helpers\ProtectsExtensionDirectories;
use Tests\TestCase;
@@ -183,12 +187,41 @@ class PluginArtisanCommandsTest extends TestCase
/**
* plugin:cache-clear 커맨드가 모든 캐시를 삭제하는지 테스트
*
* 실재하는 상태 키(ext.plugins.*_identifiers)가 소멸하고 캐시 버전이 bump 되는지
* 검증한다 (#588 — 기존 forget 대상은 writer 없는 유령 키였다).
*/
public function test_cache_clear_command_clears_all_caches(): void
{
$coreCache = new CoreCacheDriver(config('cache.default', 'array'));
$coreCache->put('ext.plugins.active_identifiers', ['stale-plugin'], 3600);
$coreCache->put('ext.plugins.installed_identifiers', ['stale-plugin'], 3600);
// 실제 writer(ExtensionMiddlewareRegistry::buildIndex)와 동형으로 태그 포함
// remember — flush() 는 taggable 스토어에서 태그 인덱스 기반으로 삭제한다
$coreCache->remember('extension.middleware_index', fn () => [['stale' => true]], 3600, [ExtensionMiddlewareRegistry::CACHE_TAG]);
Cache::put('g7:core:ext.cache_version', 1000);
$this->artisan('plugin:cache-clear')
->expectsOutput(__('plugins.commands.cache_clear.clearing_all'))
->assertExitCode(0);
$this->assertNull(
$coreCache->get('ext.plugins.active_identifiers'),
'plugin:cache-clear 후 활성 플러그인 상태 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$coreCache->get('ext.plugins.installed_identifiers'),
'plugin:cache-clear 후 설치 플러그인 상태 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$coreCache->get('extension.middleware_index'),
'plugin:cache-clear 후 확장 미들웨어 인덱스 캐시(extension.middleware_index)가 삭제되어야 합니다.'
);
$this->assertGreaterThan(
1000,
ClearsTemplateCaches::getExtensionCacheVersion(),
'plugin:cache-clear 후 확장 캐시 버전이 bump 되어야 합니다.'
);
}
/**
@@ -198,9 +231,30 @@ class PluginArtisanCommandsTest extends TestCase
{
$identifier = 'sirsoft-daum_postcode';
$coreCache = new CoreCacheDriver(config('cache.default', 'array'));
$coreCache->put('ext.plugins.active_identifiers', ['stale-plugin'], 3600);
// 실제 writer(ExtensionMiddlewareRegistry::buildIndex)와 동형으로 태그 포함
// remember — flush() 는 taggable 스토어에서 태그 인덱스 기반으로 삭제한다
$coreCache->remember('extension.middleware_index', fn () => [['stale' => true]], 3600, [ExtensionMiddlewareRegistry::CACHE_TAG]);
Cache::put('g7:core:ext.cache_version', 1000);
$this->artisan('plugin:cache-clear', ['identifier' => $identifier])
->expectsOutput(__('plugins.commands.cache_clear.clearing_single', ['plugin' => $identifier]))
->assertExitCode(0);
$this->assertNull(
$coreCache->get('ext.plugins.active_identifiers'),
'plugin:cache-clear(단일) 후 플러그인 상태 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$coreCache->get('extension.middleware_index'),
'plugin:cache-clear(단일) 후 확장 미들웨어 인덱스 캐시(extension.middleware_index)가 삭제되어야 합니다.'
);
$this->assertGreaterThan(
1000,
ClearsTemplateCaches::getExtensionCacheVersion(),
'plugin:cache-clear(단일) 후 확장 캐시 버전이 bump 되어야 합니다.'
);
}
/**
@@ -3,6 +3,7 @@
namespace Tests\Feature\Console\Commands\Template;
use App\Enums\ExtensionStatus;
use App\Extension\Cache\CoreCacheDriver;
use App\Extension\TemplateManager;
use App\Models\Template;
use App\Models\TemplateLayout;
@@ -366,20 +367,41 @@ class TemplateArtisanCommandsTest extends TestCase
$this->artisan('template:list', ['--status' => 'inactive'])
->assertExitCode(0);
// cache-clear 커맨드 (특정 템플릿)
// cache-clear 커맨드 (특정 템플릿) — 공개 config 캐시 실소멸까지 검증 (#588, 공개 #119)
$coreCache = new CoreCacheDriver(config('cache.default', 'array'));
$coreCache->put("template.config.{$identifier}", [
'success' => true,
'data' => ['version' => '0.0.1-stale'],
], 3600);
$this->artisan('template:cache-clear', ['identifier' => $identifier])
->expectsOutput(__('templates.commands.cache_clear.clearing_single', ['template' => $identifier]))
->assertExitCode(0);
$this->assertNull(
$coreCache->get("template.config.{$identifier}"),
'template:cache-clear(단일) 후 공개 config 캐시가 삭제되어야 합니다.'
);
// 활성화하여 cache-clear 전체 테스트
$this->artisan('template:activate', ['identifier' => $identifier])
->assertExitCode(0);
// cache-clear 커맨드 (전체)
// cache-clear 커맨드 (전체) — 전체 모드도 config 캐시 실소멸 검증
$coreCache->put("template.config.{$identifier}", [
'success' => true,
'data' => ['version' => '0.0.1-stale'],
], 3600);
$this->artisan('template:cache-clear')
->expectsOutput(__('templates.commands.cache_clear.clearing_all'))
->assertExitCode(0);
$this->assertNull(
$coreCache->get("template.config.{$identifier}"),
'template:cache-clear(전체) 후 공개 config 캐시가 삭제되어야 합니다.'
);
// 비활성화
$this->artisan('template:deactivate', ['identifier' => $identifier])
->assertExitCode(0);
@@ -2,6 +2,7 @@
namespace Tests\Feature\Template;
use App\Contracts\Extension\CacheInterface;
use App\Models\Permission;
use App\Models\Role;
use App\Models\Template;
@@ -203,9 +204,13 @@ class PublicLayoutControllerTest extends TestCase
// 캐시 초기화 — CacheInterface 를 통해 코어 캐시 prefix 일관 사용
// (Laravel Cache facade 의 global `CACHE_PREFIX` 와 CoreCacheDriver 의
// `g7:core` prefix 가 합쳐진 실제 키와 동등하게 조회/삭제하기 위함)
$coreCache = app(\App\Contracts\Extension\CacheInterface::class);
$coreCache->forget("layout.{$template->identifier}.{$layout->name}.v0");
// `g7:core` prefix 가 합쳐진 실제 키와 동등하게 조회/삭제하기 위함).
// `?v` 생략 시 현재 확장 캐시 버전으로 폴백하므로 (#588 — `.v0` 사각 키 방지)
// 버전을 시드해 결정적 키로 검증한다
Cache::put('g7:core:ext.cache_version', 1234);
$coreCache = app(CacheInterface::class);
$coreCache->forget("layout.{$template->identifier}.{$layout->name}.v1234");
$coreCache->forget("template.{$template->id}.layout.{$layout->name}");
// Act: 첫 번째 요청 (캐시 생성)
@@ -214,7 +219,7 @@ class PublicLayoutControllerTest extends TestCase
// 캐시가 생성되었는지 CacheInterface 로 확인 (컨트롤러가 사용하는 동일 경로)
$this->assertTrue(
$coreCache->has("layout.{$template->identifier}.{$layout->name}.v0"),
$coreCache->has("layout.{$template->identifier}.{$layout->name}.v1234"),
'레이아웃 응답이 CoreCacheDriver(g7:core 접두사) 에 캐시되어야 함',
);
@@ -252,7 +257,7 @@ class PublicLayoutControllerTest extends TestCase
'content' => ['meta' => ['title' => 'Dashboard'], 'data_sources' => [], 'components' => []],
]);
$coreCache = app(\App\Contracts\Extension\CacheInterface::class);
$coreCache = app(CacheInterface::class);
$version = 1781151505;
$nonce = 7;
// 편집 모드(.meta) — `core.templates.layouts.edit` 권한 보유 사용자로 인증.
@@ -2,6 +2,7 @@
namespace Tests\Feature\Template;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Models\Template;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -141,9 +142,12 @@ class PublicTemplateControllerTest extends TestCase
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
// 캐시 초기화 (CacheInterface 사용 — v{version} 접미사 포함, 기본 v=0)
$cache = app(\App\Contracts\Extension\CacheInterface::class);
$cacheKey = "template.routes.{$template->identifier}.v0";
// `?v` 생략 시 현재 확장 캐시 버전으로 폴백하므로 (#588 — `.v0` 사각 키 방지)
// 버전을 시드해 결정적 키로 검증한다 (getExtensionCacheVersion 은 0 을 반환하지 않음)
Cache::put('g7:core:ext.cache_version', 1234);
$cache = app(CacheInterface::class);
$cacheKey = "template.routes.{$template->identifier}.v1234";
$cache->forget($cacheKey);
// Act: 첫 번째 요청 (캐시 생성)
@@ -160,4 +164,98 @@ class PublicTemplateControllerTest extends TestCase
// 두 응답의 데이터가 동일한지 확인
$this->assertEquals($response1->json('data'), $response2->json('data'));
}
/**
* config.json 서빙이 캐시를 생성하고 installed manifest 버전을 반환하는지 테스트 (#588, 공개 #119)
*
* @scenario cache_state=cold,template_type=admin
*
* @effects serve_config_caches_manifest_and_embeds_cache_version
*/
public function test_serve_config_caches_manifest_and_returns_version(): void
{
// Arrange: 활성화된 템플릿 생성 (실제 번들 파일을 읽는 경량 픽스처)
$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'],
]);
$cache = app(CacheInterface::class);
$cacheKey = "template.config.{$template->identifier}";
$cache->forget($cacheKey);
// Act
$response = $this->getJson("/api/templates/{$template->identifier}/config.json");
// Assert: 성공 + installed template.json 의 실제 version 반환
$response->assertStatus(200)->assertJson(['success' => true]);
$manifest = json_decode(
file_get_contents(base_path("templates/{$template->identifier}/template.json")),
true
);
$this->assertSame($manifest['version'], $response->json('data.version'));
// cache_version 은 캐시 read 후 현재값이 주입되는 유효 정수
$this->assertIsInt($response->json('data.cache_version'));
$this->assertGreaterThan(0, $response->json('data.cache_version'));
// 서버 캐시 키가 생성됨
$this->assertNotNull($cache->get($cacheKey), 'config 조회 후 서버 캐시가 생성되어야 합니다.');
}
/**
* config.json 캐시 삭제 후 최신 manifest 가 반환되는지 테스트 (#588, 공개 #119)
*
* 캐시 히트 증명(변조본 서빙) → forget → 실제 파일 버전 복귀 체인.
* 라이브 재현(sentinel 주입 → cache-clear 무효 → 직접 forget 으로만 해소)의 자동화판.
*
* @scenario cache_state=warm_stale,template_type=admin
*
* @effects serve_config_returns_installed_manifest_after_invalidation
*/
public function test_serve_config_returns_fresh_manifest_after_cache_cleared(): void
{
// Arrange
$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'],
]);
$cache = app(CacheInterface::class);
$cacheKey = "template.config.{$template->identifier}";
// 캐시에 변조된 manifest 심기 (파일 무수정 — stale 상태 재현)
$cache->put($cacheKey, [
'success' => true,
'data' => ['version' => '9.9.9-stale-sentinel'],
], 3600);
// Act & Assert 1: 캐시 히트 경로 증명 — 변조본이 그대로 서빙됨
$stale = $this->getJson("/api/templates/{$template->identifier}/config.json");
$stale->assertStatus(200);
$this->assertSame('9.9.9-stale-sentinel', $stale->json('data.version'));
// Act & Assert 2: forget 후 실제 파일 버전 복귀
$cache->forget($cacheKey);
$fresh = $this->getJson("/api/templates/{$template->identifier}/config.json");
$fresh->assertStatus(200);
$manifest = json_decode(
file_get_contents(base_path("templates/{$template->identifier}/template.json")),
true
);
$this->assertSame($manifest['version'], $fresh->json('data.version'));
}
}
@@ -284,6 +284,196 @@ class TemplateCacheManagementTest extends TestCase
}
}
/**
* template:cache-clear 커맨드가 공개 config 캐시를 삭제하는지 테스트 (#588, 공개 #119)
*
* `template.config.{identifier}` 는 버전 접미사 없는 고정 키라 캐시 버전 bump 로
* 무효화되지 않는다 — 커맨드가 능동 forget 하지 않으면 TTL(1시간) 동안
* 이전 manifest 가 계속 서빙된다.
*
* @scenario cache_state=warm_stale,lifecycle_trigger=cache_clear_command_single,template_type=admin
*
* @effects cache_clear_command_forgets_template_config_key
*/
public function test_template_cache_clear_command_forgets_public_config_cache(): void
{
// Arrange
$this->templateManager->installTemplate('sirsoft-admin_basic');
$this->coreCache()->put('template.config.sirsoft-admin_basic', [
'success' => true,
'data' => ['version' => '0.0.1-stale'],
], 3600);
// Act
$this->artisan('template:cache-clear', ['identifier' => 'sirsoft-admin_basic'])
->assertExitCode(0);
// Assert
$this->assertNull(
$this->coreCache()->get('template.config.sirsoft-admin_basic'),
'template:cache-clear 후 공개 config 캐시(template.config.{identifier})가 삭제되어야 합니다.'
);
}
/**
* template:cache-clear 전체 모드가 공개 config 캐시를 삭제하는지 테스트 (#588, 공개 #119)
*
* @scenario cache_state=warm_stale,lifecycle_trigger=cache_clear_command_all,template_type=admin
*
* @effects cache_clear_command_forgets_template_config_key
*/
public function test_template_cache_clear_all_forgets_public_config_cache(): void
{
// Arrange
$this->templateManager->installTemplate('sirsoft-admin_basic');
$this->coreCache()->put('template.config.sirsoft-admin_basic', [
'success' => true,
'data' => ['version' => '0.0.1-stale'],
], 3600);
// Act (무인자 = 전체 모드)
$this->artisan('template:cache-clear')
->assertExitCode(0);
// Assert
$this->assertNull(
$this->coreCache()->get('template.config.sirsoft-admin_basic'),
'template:cache-clear 전체 모드 후 공개 config 캐시가 삭제되어야 합니다.'
);
}
/**
* clearTemplateCache() 가 config + components_manifest 고정 키를 삭제하는지 테스트 (#588)
*
* components_manifest 는 숫자 id / identifier 두 변종 키가 실재한다
* (ComponentExists 는 int|string 을 수용). 템플릿 업데이트로 components.json 이
* 변해도 이 키가 남으면 최대 1시간 구 매니페스트로 레이아웃을 검증한다.
*
* @scenario cache_state=warm_stale,lifecycle_trigger=template_update,template_type=admin
*
* @effects template_update_invalidates_public_config_cache,clear_template_cache_forgets_components_manifest_variants
*/
public function test_clear_template_cache_forgets_config_and_components_manifest(): void
{
// Arrange
$this->templateManager->installTemplate('sirsoft-admin_basic');
$template = Template::where('identifier', 'sirsoft-admin_basic')->first();
$this->coreCache()->put('template.config.sirsoft-admin_basic', [
'success' => true,
'data' => ['version' => '0.0.1-stale'],
], 3600);
$this->coreCache()->put("template.{$template->id}.components_manifest", ['components' => []], 3600);
$this->coreCache()->put('template.sirsoft-admin_basic.components_manifest', ['components' => []], 3600);
// Act — 라이프사이클(update/deactivate/uninstall/cache-clear)이 공유하는 무효화 단일 지점
$this->templateManager->clearTemplateCache('sirsoft-admin_basic');
// Assert
$this->assertNull(
$this->coreCache()->get('template.config.sirsoft-admin_basic'),
'clearTemplateCache() 후 공개 config 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$this->coreCache()->get("template.{$template->id}.components_manifest"),
'clearTemplateCache() 후 숫자 id 변종 components_manifest 캐시가 삭제되어야 합니다.'
);
$this->assertNull(
$this->coreCache()->get('template.sirsoft-admin_basic.components_manifest'),
'clearTemplateCache() 후 identifier 변종 components_manifest 캐시가 삭제되어야 합니다.'
);
}
/**
* 비활성화/삭제 라이프사이클이 공개 config 캐시를 삭제하는지 테스트 (#588, 공개 #119)
*
* 활성 시절 warm 된 config 캐시가 남으면 비활성/삭제된 템플릿의 manifest 를
* 최대 1시간 200 으로 계속 서빙한다 (캐시 히트가 상태 검사보다 먼저).
*
* @scenario cache_state=warm_stale,lifecycle_trigger=deactivate,template_type=admin
*
* @effects deactivate_uninstall_invalidate_public_config_cache
*/
public function test_template_deactivate_and_uninstall_invalidate_public_config_cache(): void
{
// Arrange
$this->templateManager->installTemplate('sirsoft-admin_basic');
$this->templateManager->activateTemplate('sirsoft-admin_basic');
$warmConfig = function (): void {
$this->coreCache()->put('template.config.sirsoft-admin_basic', [
'success' => true,
'data' => ['version' => '0.0.1-stale'],
], 3600);
};
// Act & Assert — 비활성화 경로
$warmConfig();
$this->templateManager->deactivateTemplate('sirsoft-admin_basic');
$this->assertNull(
$this->coreCache()->get('template.config.sirsoft-admin_basic'),
'비활성화 후 공개 config 캐시가 삭제되어야 합니다.'
);
// Act & Assert — 삭제 경로
$warmConfig();
$this->templateManager->uninstallTemplate('sirsoft-admin_basic');
$this->assertNull(
$this->coreCache()->get('template.config.sirsoft-admin_basic'),
'삭제 후 공개 config 캐시가 삭제되어야 합니다.'
);
}
/**
* 비활성화 시 편집기용 `.with_source_meta` 변종 레이아웃 캐시도 삭제되는지 테스트 (#588)
*
* LayoutService 는 편집기 병합 응답을 `.with_source_meta` 접미사 키로 별도 캐싱한다.
* 라이프사이클 무효화(forgetLayoutCacheKeys)가 접미사 없는 키만 지우면
* activate/deactivate/uninstall/refresh 후에도 편집기용 병합 캐시가 잔존한다.
*
* @scenario cache_state=warm_stale,lifecycle_trigger=uninstall,template_type=admin
*
* @effects with_source_meta_layout_cache_variants_forgotten
*/
public function test_deactivate_template_clears_with_source_meta_layout_caches(): void
{
// Arrange
$this->templateManager->installTemplate('sirsoft-admin_basic');
$this->templateManager->activateTemplate('sirsoft-admin_basic');
$template = Template::where('identifier', 'sirsoft-admin_basic')->first();
$layouts = TemplateLayout::where('template_id', $template->id)->get();
$this->assertGreaterThan(0, $layouts->count());
$warmedKeys = [];
foreach ($layouts as $layout) {
$key = "template.{$template->id}.layout.{$layout->name}.with_source_meta";
$this->coreCache()->put($key, ['test' => 'meta'], 3600);
$warmedKeys[] = $key;
// 소스 해시 변종 (LayoutService::getMergedLayoutCacheKey 와 동형 — 접미사는 해시 뒤)
if ($layout->source_type && $layout->source_identifier) {
$sourceHash = md5($layout->source_type->value.$layout->source_identifier);
$hashKey = "template.{$template->id}.layout.{$layout->name}.{$sourceHash}.with_source_meta";
$this->coreCache()->put($hashKey, ['test' => 'meta'], 3600);
$warmedKeys[] = $hashKey;
}
}
// Act
$this->templateManager->deactivateTemplate('sirsoft-admin_basic');
// Assert
foreach ($warmedKeys as $key) {
$this->assertNull(
$this->coreCache()->get($key),
"비활성화 후 편집기용 병합 캐시({$key})가 삭제되어야 합니다."
);
}
}
/**
* 테스트용 레이아웃 JSON 파일 생성
*/
@@ -2,6 +2,7 @@
namespace Tests\Feature\Template;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Models\Template;
use App\Services\TemplateService;
@@ -129,9 +130,12 @@ class TemplateLanguageServingTest extends TestCase
*/
public function test_language_file_is_cached(): void
{
// PublicBaseController::cached() 는 CacheInterface + v{version} 접미사 (기본 v=0)
$cache = app(\App\Contracts\Extension\CacheInterface::class);
$cacheKey = 'template.language.sirsoft-admin_basic.ko.v0';
// `?v` 생략 시 현재 확장 캐시 버전으로 폴백하므로 (#588 — `.v0` 사각 키 방지)
// 버전을 시드해 결정적 키로 검증한다
Cache::put('g7:core:ext.cache_version', 1234);
$cache = app(CacheInterface::class);
$cacheKey = 'template.language.sirsoft-admin_basic.ko.v1234';
$cache->forget($cacheKey);
// 첫 번째 요청
@@ -179,4 +183,4 @@ class TemplateLanguageServingTest extends TestCase
$response = $this->getJson('/api/templates/sirsoft-admin_basic/lang/KO.json');
$response->assertStatus(404);
}
}
}
@@ -16,7 +16,11 @@ use Tests\TestCase;
* 새 CacheInterface 를 통해 캐시를 삭제하는지 검증.
*
* 실제 명령어 실행은 모듈 manager / plugin manager 의존성이 크므로,
* 명령어가 사용하는 키 형식과 forget 동작을 키 차원에서 검증합니다.
* CacheInterface 의 다건 put/forget 왕복 동작을 키 차원에서 검증합니다.
*
* 주의: 아래 키 문자열은 이관 당시의 픽스처다. 현행 커맨드는 유령 키 forget 을
* 제거하고 상태 키 무효화 + 레이아웃 캐시 + 버전 bump 로 동작한다 (#588) —
* 커맨드의 실동작 검증은 {Module,Plugin,Template}ArtisanCommandsTest 가 담당한다.
*/
class ArtisanCacheClearTest extends TestCase
{
@@ -38,9 +42,7 @@ class ArtisanCacheClearTest extends TestCase
}
/**
* G-1-1: module:cache-clear 명령어 — 모듈 관련 캐시 삭제 검증.
*
* ClearModuleCacheCommand::clearModuleCache() 가 사용하는 키 패턴을 검증.
* G-1-1: 모듈 키 픽스처 다건 put→forget 왕복 (드라이버 동작 검증 — 커맨드 미호출).
*/
#[Test]
public function g_1_1_module_cache_clear_removes_per_module_keys(): void
@@ -58,7 +60,7 @@ class ArtisanCacheClearTest extends TestCase
$this->cache->put($k, 'data');
}
// 명령어 핸들러 시뮬레이션 — CacheInterface.forget 호출
// CacheInterface.forget 다건 호출 (드라이버 동작 검증)
foreach ($keys as $k) {
$this->cache->forget($k);
}
@@ -69,7 +71,7 @@ class ArtisanCacheClearTest extends TestCase
}
/**
* G-1-2: plugin:cache-clear 명령어 — 플러그인 캐시 삭제.
* G-1-2: 플러그인 키 픽스처 다건 put→forget 왕복 (드라이버 동작 검증 — 커맨드 미호출).
*/
#[Test]
public function g_1_2_plugin_cache_clear_removes_per_plugin_keys(): void
@@ -96,7 +98,7 @@ class ArtisanCacheClearTest extends TestCase
}
/**
* G-1-3: template:cache-clear 명령어 — 템플릿 + 레이아웃 + routes + 다국어 캐시 삭제.
* G-1-3: 템플릿/레이아웃 키 픽스처 다건 put→forget 왕복 (드라이버 동작 검증 — 커맨드 미호출).
*/
#[Test]
public function g_1_3_template_cache_clear_removes_template_layout_routes(): void
@@ -127,7 +129,7 @@ class ArtisanCacheClearTest extends TestCase
}
/**
* G-1-4: 인수 없이 호출 시 모든 모듈 캐시 + 전역 키 삭제.
* G-1-4: 전역 + 개별 키 혼합 다건 put→forget 왕복 (드라이버 동작 검증 — 커맨드 미호출).
*/
#[Test]
public function g_1_4_clear_without_args_clears_all(): void
@@ -143,7 +145,7 @@ class ArtisanCacheClearTest extends TestCase
$this->cache->put("module.info.{$id}", 'data');
}
// 명령어 시뮬레이션 — 전역 + 개별 모두 삭제
// 전역 + 개별 모두 forget (드라이버 동작 검증)
$globalKeys = ['modules.all', 'modules.active', 'modules.installed'];
foreach ($globalKeys as $k) {
$this->cache->forget($k);
@@ -0,0 +1,86 @@
<?php
namespace Tests\Unit\Extension;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 템플릿 업데이트 성공 cleanup 의 config 캐시 무효화 구조 테스트 (#588, 공개 #119)
*
* `template.config.{identifier}` 는 버전 접미사 없는 고정 키라 캐시 버전 bump 로
* 무효화되지 않는다. updateTemplate() 성공 cleanup 이 clearTemplateCache() 를
* 직접 호출하지 않으면, 비활성 업데이트·레이아웃 무변경 업데이트 경로에서 공개
* config.json 이 TTL(1시간) 동안 이전 manifest 를 계속 서빙한다.
*
* 실제 updateTemplate() 통합 실행은 업데이트 소스(_pending/신버전) 픽스처가 필요해
* 비용이 크므로, clearTemplateCache() 의 키 삭제는 TemplateCacheManagementTest 가
* 동작으로 검증하고 본 테스트는 호출 존재를 소스 구조로 고정한다
* (선례: ExtensionUpdateStatusCacheSymmetryTest).
*/
class TemplateUpdateConfigCacheInvalidationTest extends TestCase
{
/**
* @scenario cache_state=warm_current,lifecycle_trigger=template_update,template_type=user
*
* @effects template_update_invalidates_public_config_cache
*/
#[Test]
public function update_template_cleanup_calls_clear_template_cache(): void
{
$body = $this->methodSource(
base_path('app/Extension/TemplateManager.php'),
'updateTemplate'
);
$this->assertStringContainsString(
'$this->clearTemplateCache(',
$body,
'updateTemplate() 성공 cleanup 이 clearTemplateCache() 를 호출해야 합니다 — '
.'누락 시 공개 config.json 이 캐시 TTL 동안 이전 manifest 로 응답됩니다.'
);
}
/**
* 대상 메서드 본문을 주석 제거 후 반환합니다.
*
* 주석을 남겨 두면 설명 문장에 들어 있는 호출 표기가 검사를 통과시킨다.
*
* @param string $path 대상 파일 절대 경로
* @param string $method 대상 메서드명
* @return string 주석이 제거된 메서드 본문
*/
private function methodSource(string $path, string $method): string
{
$this->assertFileExists($path);
$stripped = '';
foreach (token_get_all(file_get_contents($path)) as $token) {
if (is_array($token) && in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) {
continue;
}
$stripped .= is_array($token) ? $token[1] : $token;
}
$start = strpos($stripped, "public function {$method}(");
$this->assertNotFalse($start, "{$path} 에서 {$method}() 메서드를 찾지 못했습니다.");
// 중괄호 균형으로 메서드 본문 끝을 찾는다
$open = strpos($stripped, '{', $start);
$depth = 0;
$length = strlen($stripped);
for ($i = $open; $i < $length; $i++) {
if ($stripped[$i] === '{') {
$depth++;
} elseif ($stripped[$i] === '}') {
$depth--;
if ($depth === 0) {
return substr($stripped, $open, $i - $open + 1);
}
}
}
$this->fail("{$path} 의 {$method}() 본문 끝을 찾지 못했습니다.");
}
}
@@ -0,0 +1,33 @@
# audit:allow test-scenario-coverage reason: axes 30 cross product(pairwise) 중 동작 분기가 실재하는 조합만 docblock 매핑. cache_state=cold 는 라이프사이클 트리거와 직교(캐시가 없으면 forget 은 무조건 no-op 멱등)라 트리거 조합 확장이 형식적이고, template_type 은 무효화 경로가 타입 무관 단일 코드(clearTemplateCache)라 admin 대표 + 구조 테스트의 user 로 충분. effects 7건은 전수 매핑됨.
feature: template_public_config_cache_invalidation
description: |
공개 템플릿 설정(config.json) 서빙 캐시 `template.config.{identifier}` 는 버전
접미사 없는 고정 키라 캐시 버전 bump 로 무효화되지 않는다. 템플릿 라이프사이클
(cache-clear 커맨드 단일/전체, update, deactivate, uninstall) 전 경로가
`TemplateManager::clearTemplateCache()` 단일 지점을 경유해 이 키(+ components_manifest
두 변종, 현재 버전 routes/language 키, `.with_source_meta` 편집기 변종)를 능동
삭제함을 고정한다 (#588, 공개 #119).
coverage_strategy: pairwise
axes:
cache_state: [cold, warm_current, warm_stale]
lifecycle_trigger: [cache_clear_command_single, cache_clear_command_all, template_update, deactivate, uninstall]
template_type: [admin, user]
effects:
- cache_clear_command_forgets_template_config_key
- template_update_invalidates_public_config_cache
- deactivate_uninstall_invalidate_public_config_cache
- serve_config_caches_manifest_and_embeds_cache_version
- serve_config_returns_installed_manifest_after_invalidation
- clear_template_cache_forgets_components_manifest_variants
- with_source_meta_layout_cache_variants_forgotten
test_files:
- tests/Feature/Template/TemplateCacheManagementTest.php
- tests/Feature/Template/PublicTemplateControllerTest.php
- tests/Feature/Console/Commands/Template/TemplateArtisanCommandsTest.php
- tests/Unit/Extension/TemplateUpdateConfigCacheInvalidationTest.php