feat(core,engine): 부트스트랩 리소스 정적 게시(bake) 및 폴백 체계 도입
공개 제보 https://github.com/gnuboard/g7/issues/122 대응 — 초기 부트스트랩 리소스(다국어 병합·컴포넌트 정의·라우트·확장 번들·템플릿 dist)를 캐시 버전 디렉토리(public/build/ext/{v}/)에 실파일로 게시해 웹서버가 rewrite 전에 직접 서빙한다. 부트 임계 경로의 PHP 왕복을 제거하고(실측 TTFB 131~144ms → 1~7ms), 미게시·부분게시·GC 직후에는 fetch·태그·번들 3계층이 종전 API 로 즉시 폴백한다. - 게시: 원자적 tmp→rename→manifest(존재=완료), 캐시 락 단일 실행, 인라인 GC (현재+직전 1개), incrementExtensionCacheVersion 단일 지점 terminating 트리거 + blade 자가 치유 + 설치기 태스크(best_effort) + 일일 cleanup 스케줄, sudo 업데이트 대비 소유권 정상화(normalizeOwnership)·prune/백업 제외 - 프론트(engine-v1.61.0): blade 주입 cache_version 1급 시드(이중 부트 로드 제거), fetchStaticFirst 즉시 폴백, ComponentRegistry 버전 키드 매니페스트, ModuleAssetLoader 번들 정적→레거시 폴백, asset-url-recovery staticToLegacy 역변환 - 폴백 API 품질: lang/components/routes ETag+304 + 환경 분기 Cache-Control, 열화 라우트 스냅샷 공개 캐시 금지(서버측 캐시 회피와 대칭), 게시 .htaccess mod_deflate + nginx gzip 스니펫(압축 전송량 회귀 방지) - SEO 정합: 봇 HTML 은 GC 대상 정적 URL 미사용(allowStatic:false), props $switch 봇측 해석 구현(engine-v1.56.0 패리티), 패리티 룰 expression-dialect 그룹 신설, 상주 allow 헤더 제거로 잠금 복원, _comment* 접두 주석 키 분류 - 검증: 전 수정 red→green 4단계, Playwright 라이브 21건, Chrome MCP 24축+M1~M3, 봇 curl 3축, 캐시 저장소(file/redis/database) 축 판정, 히스토리·공개이슈·커밋 이력 전수 재조사 반영 - 코어 7.0.10, engine-v1.61.0. kill-switch: G7_STATIC_CACHE=false
This commit is contained in:
1 parent
56836a2b66
commit
5ba7a83597
73 files changed
+4219
-98
No files matched your search
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 오래된 부트스트랩 리소스 정적 게시 디렉토리를 정리하는 커맨드
|
||||
*
|
||||
* 게시 디렉토리(`public/build/ext/{version}/`)는 캐시 스토어 밖 파일시스템이라
|
||||
* version bump 가 구버전 디렉토리를 지우지 않는다. 게시 성공 직후 인라인 GC 가
|
||||
* 돌지만, 게시가 오래 없거나 실패한 환경의 잔존물을 이 커맨드가 회수한다.
|
||||
* (`CleanupExtensionBundlesCommand` 파일 산출물 GC 패턴 미러, #122)
|
||||
*/
|
||||
class CleanupExtensionStaticCacheCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'ext-static:cleanup';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '오래된 부트스트랩 리소스 정적 게시 디렉토리(구 version)를 삭제합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @param ExtensionStaticCacheService $service 정적 게시 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(ExtensionStaticCacheService $service): int
|
||||
{
|
||||
$deleted = $service->cleanup();
|
||||
|
||||
$this->info("오래된 정적 게시 디렉토리 {$deleted}건이 삭제되었습니다.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 부트스트랩 리소스 정적 게시(bake)를 수동 수행하는 커맨드
|
||||
*
|
||||
* 수명주기 이벤트(terminating 트리거)와 blade 자가 치유가 정상 경로지만,
|
||||
* 배포 직후 워밍이나 수동 복구가 필요할 때 이 커맨드로 즉시 게시한다.
|
||||
* 설치기 완료 단계에서도 호출된다 (#122).
|
||||
*/
|
||||
class PublishExtensionStaticCacheCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'ext-static:publish {--force : 게시 완료 상태여도 강제 재게시}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '부트스트랩 리소스(다국어·컴포넌트·라우트·번들·템플릿 에셋)를 정적 파일로 게시합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @param ExtensionStaticCacheService $service 정적 게시 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(ExtensionStaticCacheService $service): int
|
||||
{
|
||||
if (! $service->isEnabled()) {
|
||||
$this->warn('정적 게시가 비활성화되어 있습니다 (G7_STATIC_CACHE=false). 게시를 건너뜁니다.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$published = $service->publishCurrent(force: (bool) $this->option('force'));
|
||||
|
||||
if (! $published) {
|
||||
$this->error('정적 게시에 실패했습니다. 로그를 확인하세요 — 사이트는 API 폴백으로 정상 동작합니다.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info('부트스트랩 리소스 정적 게시가 완료되었습니다.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
/**
|
||||
* 부트스트랩 리소스 정적 게시(bake) 실패 예외.
|
||||
*
|
||||
* 사용자 대면 예외가 아니다 — `ExtensionStaticCacheService::publishVersion()` 의
|
||||
* 자체 catch 가 즉시 삼켜 Log::warning 진단으로만 남기고, 사이트는 API 폴백으로
|
||||
* 정상 동작한다. 따라서 메시지는 다국어 키가 아니라 운영자 로그용 진단 문자열이다.
|
||||
*/
|
||||
class StaticCachePublishException extends \RuntimeException {}
|
||||
@@ -4,6 +4,7 @@ namespace App\Extension\Traits;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
@@ -48,6 +49,12 @@ trait ClearsTemplateCaches
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
// 부트스트랩 리소스 정적 게시(bake) 예약 — 모든 bump 호출부(수명주기 전체)가
|
||||
// 이 단일 지점을 경유하므로 재게시 트리거 누락이 구조적으로 불가능하다 (#122).
|
||||
// terminating 시점에 프로세스당 1회, 실행 시점의 최종 버전으로 게시된다
|
||||
// (연속 bump 자연 병합). 실패해도 사이트는 API 폴백으로 정상.
|
||||
ExtensionStaticCacheService::schedulePublishOnTerminate();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -210,17 +210,37 @@ abstract class BaseApiController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 응답을 반환합니다 (캐싱 헤더 포함).
|
||||
* JSON 응답을 반환합니다 (조건부 캐싱 헤더 포함).
|
||||
*
|
||||
* ETag 기반 조건부 캐시(If-None-Match → 304)와 환경별 Cache-Control 분기를
|
||||
* 적용한다 — 프로덕션은 `public, max-age`, 그 외 환경은 `no-cache`(파일 수정
|
||||
* 즉시 반영 — `fileResponse` 의 환경 분기와 동일 사상).
|
||||
*
|
||||
* @param mixed $data JSON으로 변환할 데이터
|
||||
* @param int $maxAge 캐시 유지 시간 (초, 기본: 1시간)
|
||||
* @param int $status HTTP 상태 코드
|
||||
* @return JsonResponse JSON 응답
|
||||
* @return JsonResponse|Response JSON 응답 또는 304 응답
|
||||
*/
|
||||
protected function cachedJsonResponse(mixed $data, int $maxAge = 3600, int $status = 200): JsonResponse
|
||||
protected function cachedJsonResponse(mixed $data, int $maxAge = 3600, int $status = 200): JsonResponse|Response
|
||||
{
|
||||
$etag = $this->generateETag($data);
|
||||
|
||||
$cacheControl = app()->environment('production')
|
||||
? "public, max-age={$maxAge}"
|
||||
: 'no-cache';
|
||||
|
||||
if ($status === 200 && $this->isNotModified($etag)) {
|
||||
$response = $this->notModifiedResponse($etag, $maxAge);
|
||||
$response->headers->set('Cache-Control', $cacheControl);
|
||||
$response->headers->set('Vary', 'Accept-Encoding');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
return response()->json($data, $status, [
|
||||
'Cache-Control' => "public, max-age={$maxAge}",
|
||||
'Cache-Control' => $cacheControl,
|
||||
'ETag' => $etag,
|
||||
'Vary' => 'Accept-Encoding',
|
||||
], ResponseHelper::JSON_ENCODE_OPTIONS);
|
||||
}
|
||||
|
||||
@@ -283,9 +303,18 @@ abstract class BaseApiController extends Controller
|
||||
): JsonResponse|Response {
|
||||
$etag = $this->generateETag($data);
|
||||
|
||||
// 환경별 캐싱 정책 — 프로덕션 외 환경은 no-cache 로 파일/데이터 수정 즉시 반영
|
||||
// (`fileResponse`/`cachedJsonResponse` 와 동일 사상, #122 작업 D)
|
||||
$cacheControl = app()->environment('production')
|
||||
? "public, max-age={$maxAge}"
|
||||
: 'no-cache';
|
||||
|
||||
// 304 Not Modified 처리
|
||||
if ($this->isNotModified($etag)) {
|
||||
return $this->notModifiedResponse($etag, $maxAge);
|
||||
$response = $this->notModifiedResponse($etag, $maxAge);
|
||||
$response->headers->set('Cache-Control', $cacheControl);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
@@ -294,7 +323,7 @@ abstract class BaseApiController extends Controller
|
||||
'data' => $data,
|
||||
], 200, [], ResponseHelper::JSON_ENCODE_OPTIONS)
|
||||
->header('ETag', $etag)
|
||||
->header('Cache-Control', "public, max-age={$maxAge}")
|
||||
->header('Cache-Control', $cacheControl)
|
||||
->header('Vary', 'Accept-Encoding, Accept-Language');
|
||||
}
|
||||
}
|
||||
@@ -140,9 +140,9 @@ class PublicModuleController extends PublicBaseController
|
||||
* 폴백한다(무손실 보존 디그레이드).
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return JsonResponse 컴포넌트 정의 응답
|
||||
* @return JsonResponse|Response 컴포넌트 정의 응답 (If-None-Match 일치 시 304)
|
||||
*/
|
||||
public function serveComponents(string $identifier): JsonResponse
|
||||
public function serveComponents(string $identifier): JsonResponse|Response
|
||||
{
|
||||
$this->logApiUsage('modules.components', ['identifier' => $identifier]);
|
||||
|
||||
|
||||
@@ -139,9 +139,9 @@ class PublicPluginController extends PublicBaseController
|
||||
* 폴백한다(무손실 보존 디그레이드).
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return JsonResponse 컴포넌트 정의 응답
|
||||
* @return JsonResponse|Response 컴포넌트 정의 응답 (If-None-Match 일치 시 304)
|
||||
*/
|
||||
public function serveComponents(string $identifier): JsonResponse
|
||||
public function serveComponents(string $identifier): JsonResponse|Response
|
||||
{
|
||||
$this->logApiUsage('plugins.components', ['identifier' => $identifier]);
|
||||
|
||||
|
||||
@@ -35,9 +35,9 @@ class PublicTemplateController extends PublicBaseController
|
||||
* 템플릿 라우트 정보 조회 (활성화된 모듈의 routes 포함)
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자 (vendor-name 형식)
|
||||
* @return JsonResponse 라우트 정보 응답
|
||||
* @return JsonResponse|Response 라우트 정보 응답 (`?v` 명시 + If-None-Match 일치 시 304)
|
||||
*/
|
||||
public function getRoutes(string $identifier): JsonResponse
|
||||
public function getRoutes(string $identifier): JsonResponse|Response
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.routes', ['identifier' => $identifier]);
|
||||
@@ -101,6 +101,15 @@ class PublicTemplateController extends PublicBaseController
|
||||
return $this->error(__('templates.errors.invalid_cache_data'), 500);
|
||||
}
|
||||
|
||||
// 버전 키드 URL(`?v` 명시)은 bump 시 URL 자체가 바뀌므로 조건부 공개 캐시가 안전하다.
|
||||
// 무버전 요청(핸드셰이크 폴백 등)은 종전대로 캐시 헤더 없이 신선 응답 (#122 작업 D).
|
||||
// 열화 스냅샷은 공개 캐시 금지 — 서버측 캐시 회피(#493)와 동일 규율로, 같은 `?v`
|
||||
// URL 에 public max-age 가 붙으면 브라우저/CDN 이 열화 응답을 1시간 박제한다
|
||||
// (버전은 이미 올라간 뒤라 스스로 회복되지 않음. 정적 게시의 열화 제외와 대칭).
|
||||
if ($rawVersion !== null && ! $this->templateService->lastRouteMergeWasDegraded()) {
|
||||
return $this->successWithCache('templates.messages.routes_retrieved', $routesData['data'], 3600);
|
||||
}
|
||||
|
||||
return $this->success(
|
||||
__('templates.messages.routes_retrieved'),
|
||||
$routesData['data']
|
||||
@@ -145,9 +154,9 @@ class PublicTemplateController extends PublicBaseController
|
||||
* 컴포넌트 정의 파일 서빙
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return JsonResponse 컴포넌트 정의 응답
|
||||
* @return JsonResponse|Response 컴포넌트 정의 응답 (If-None-Match 일치 시 304)
|
||||
*/
|
||||
public function serveComponents(string $identifier): JsonResponse
|
||||
public function serveComponents(string $identifier): JsonResponse|Response
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.components', ['identifier' => $identifier]);
|
||||
@@ -244,9 +253,9 @@ class PublicTemplateController extends PublicBaseController
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param string $locale 로케일 (ko, en 등)
|
||||
* @return JsonResponse 다국어 데이터 응답
|
||||
* @return JsonResponse|Response 다국어 데이터 응답 (If-None-Match 일치 시 304)
|
||||
*/
|
||||
public function serveLanguage(string $identifier, string $locale): JsonResponse
|
||||
public function serveLanguage(string $identifier, string $locale): JsonResponse|Response
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.language', [
|
||||
|
||||
@@ -1457,6 +1457,9 @@ class ComponentHtmlMapper
|
||||
// 표현식 해석: 문자열/숫자는 evaluate, 배열/객체는 evaluateRaw
|
||||
$resolved = $evaluator->evaluateRaw($value, $context);
|
||||
$data[$key] = $resolved;
|
||||
} elseif ($this->isSwitchDefinition($value)) {
|
||||
// $switch 선언적 분기 (React resolveObject 와 동일 위치에서 해석)
|
||||
$data[$key] = $this->resolveSwitchValue($value, $context, $evaluator);
|
||||
} elseif (is_array($value)) {
|
||||
// 중첩 객체 (예: socialLinks): 재귀적으로 해석
|
||||
$data[$key] = $this->resolveAllPropsRecursive($value, $context, $evaluator);
|
||||
@@ -1482,6 +1485,8 @@ class ComponentHtmlMapper
|
||||
foreach ($values as $k => $v) {
|
||||
if (is_string($v) && str_contains($v, '{{')) {
|
||||
$result[$k] = $evaluator->evaluateRaw($v, $context);
|
||||
} elseif ($this->isSwitchDefinition($v)) {
|
||||
$result[$k] = $this->resolveSwitchValue($v, $context, $evaluator);
|
||||
} elseif (is_array($v)) {
|
||||
$result[$k] = $this->resolveAllPropsRecursive($v, $context, $evaluator);
|
||||
} else {
|
||||
@@ -1492,6 +1497,71 @@ class ComponentHtmlMapper
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 값이 `$switch` 선언적 분기 객체인지 판정합니다.
|
||||
*
|
||||
* React `DataBindingEngine.isSwitchExpression` 과 동일 — `$switch` 와 `$cases`
|
||||
* 키를 모두 가진 객체(연관 배열)만 해당한다.
|
||||
*
|
||||
* @param mixed $value 판정 대상 값
|
||||
* @return bool $switch 정의 여부
|
||||
*/
|
||||
private function isSwitchDefinition(mixed $value): bool
|
||||
{
|
||||
return is_array($value)
|
||||
&& array_key_exists('$switch', $value)
|
||||
&& array_key_exists('$cases', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* `$switch` 선언적 분기 객체를 해석합니다.
|
||||
*
|
||||
* React `DataBindingEngine.resolveSwitch` 와 동일 의미론 (engine-v1.56.0 패리티):
|
||||
* ① `$switch` 키 표현식을 평가해 문자열 키로 정규화(trim, 실패 시 빈 문자열)
|
||||
* ② `$cases` 에서 키 일치 값 선택, 없으면 `$default`, 그것도 없으면 null(React undefined)
|
||||
* ③ 결과가 `{{}}` 포함 문자열이면 재해석, 객체면 재귀 해석(중첩 $switch 포함)
|
||||
*
|
||||
* 레이아웃 최상위 `computed` 의 $switch 는 `SeoRenderer::resolveComputedSwitch` 가
|
||||
* 별도 처리한다 — 이 메서드는 노드 props 값 축 담당.
|
||||
*
|
||||
* @param array $definition $switch 정의 { "$switch", "$cases", "$default"? }
|
||||
* @param array $context 데이터 컨텍스트
|
||||
* @param ExpressionEvaluator $evaluator 표현식 평가기
|
||||
* @return mixed 해석된 값 (매칭·기본값 모두 없으면 null)
|
||||
*/
|
||||
private function resolveSwitchValue(array $definition, array $context, ExpressionEvaluator $evaluator): mixed
|
||||
{
|
||||
try {
|
||||
$keyValue = trim((string) $evaluator->evaluate((string) ($definition['$switch'] ?? ''), $context));
|
||||
} catch (\Throwable) {
|
||||
$keyValue = '';
|
||||
}
|
||||
|
||||
$cases = is_array($definition['$cases'] ?? null) ? $definition['$cases'] : [];
|
||||
|
||||
if ($keyValue !== '' && array_key_exists($keyValue, $cases)) {
|
||||
$result = $cases[$keyValue];
|
||||
} elseif (array_key_exists('$default', $definition)) {
|
||||
$result = $definition['$default'];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_string($result)) {
|
||||
return str_contains($result, '{{') ? $evaluator->evaluate($result, $context) : $result;
|
||||
}
|
||||
|
||||
if ($this->isSwitchDefinition($result)) {
|
||||
return $this->resolveSwitchValue($result, $context, $evaluator);
|
||||
}
|
||||
|
||||
if (is_array($result)) {
|
||||
return $this->resolveAllPropsRecursive($result, $context, $evaluator);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {field|alt_field} 패턴에서 아이템 값을 해석합니다.
|
||||
*
|
||||
@@ -1688,6 +1758,12 @@ class ComponentHtmlMapper
|
||||
continue;
|
||||
}
|
||||
|
||||
// $switch 선언적 분기 객체 (engine-v1.56.0 React 패리티) — 해석하지 않으면
|
||||
// 배열이라는 이유로 속성이 조용히 사라진다 (예외·경고 없음)
|
||||
if ($this->isSwitchDefinition($value)) {
|
||||
$value = $this->resolveSwitchValue($value, $context, $evaluator);
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$evaluated = $evaluator->evaluate($value, $context);
|
||||
if ($evaluated !== '') {
|
||||
|
||||
+11
-1
@@ -730,7 +730,12 @@ class SeoRenderer implements SeoRendererInterface
|
||||
foreach ($cssPaths as $cssPath) {
|
||||
// dist/ 접두사 제거 (서빙 경로에서는 dist가 자동 추가됨)
|
||||
$servePath = preg_replace('#^dist/#', '', $cssPath);
|
||||
$urls[] = AssetUrl::templateAsset($templateIdentifier, $servePath);
|
||||
|
||||
// 정적 게시본(bake) 경로 금지 — 이 URL 은 SeoCacheManager(`seo.page.*`,
|
||||
// 키에 cache_version 미포함)에 캐시된 HTML 에 박제되는데, 정적 디렉토리는
|
||||
// GC 가 현재+직전 1개만 보존해 캐시 수명 안에 404 가 될 수 있다. SEO HTML 은
|
||||
// asset-url-recovery 파샬도 없어 자가 복구가 불가하므로 무버전 API URL 고정.
|
||||
$urls[] = AssetUrl::templateAsset($templateIdentifier, $servePath, allowStatic: false);
|
||||
}
|
||||
|
||||
return $urls;
|
||||
@@ -954,6 +959,11 @@ class SeoRenderer implements SeoRendererInterface
|
||||
* 프론트엔드 TemplateApp이 레이아웃 레벨 initLocal/initGlobal을 상태에 적용하는 것과
|
||||
* 동일하게, 각 값의 {{}} 표현식을 해석해 반환합니다.
|
||||
*
|
||||
* **데이터소스 레벨 `initLocal` 옵션은 의도적으로 처리하지 않는다** (2026-08-25 확정) —
|
||||
* 그 옵션을 쓰는 화면(장바구니·주문서·프로필 수정·게시판 작성 폼 등)은 인증·인터랙션
|
||||
* 화면이라 봇 렌더 가치가 없다. 봇 노출이 필요한 상태 시드는 레이아웃 최상위
|
||||
* `initLocal`/`state` 를 사용한다 (docs/backend/seo-system.md 지원 노드 키 표 참조).
|
||||
*
|
||||
* @param mixed $block 초기 상태 블록 (키 → 값)
|
||||
* @param array $context 현재 컨텍스트 (route, query 등 포함)
|
||||
* @return array 평가된 초기 상태
|
||||
|
||||
@@ -0,0 +1,603 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Exceptions\StaticCachePublishException;
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Models\Template;
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 부트스트랩 리소스 정적 게시(bake) 서비스.
|
||||
*
|
||||
* 병합 결과물(다국어·컴포넌트 정의·라우트·확장 번들·템플릿 dist 에셋)을
|
||||
* 캐시 버전 디렉토리(`public/build/ext/{v}/`)에 실파일로 게시해 웹서버가
|
||||
* rewrite 전에 직접 서빙하게 한다 (#122). 병합 로직은 새로 만들지 않고
|
||||
* 전부 기존 SSoT(TemplateService/ExtensionBundleService)를 호출한다.
|
||||
*
|
||||
* 원자성: `{v}.tmp/` 에 전부 쓴 뒤 디렉토리 rename → `{v}/`, manifest.json 은
|
||||
* rename 후 마지막에 기록한다. manifest 존재 = 게시 완료(부분 게시 참조 방지).
|
||||
*
|
||||
* 실패 정책: 쓰기 실패는 예외를 삼키고 Log::warning + tmp 정리 — 사이트는
|
||||
* API 폴백으로 정상 유지된다(fail-open 이 아니라 "정적 fast path 미적용" 상태).
|
||||
*/
|
||||
class ExtensionStaticCacheService
|
||||
{
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
/** 게시 완료 마커 파일명 */
|
||||
private const MANIFEST_FILE = 'manifest.json';
|
||||
|
||||
/** 게시 락 이름 접두사 */
|
||||
private const LOCK_PREFIX = 'ext-static.publish.';
|
||||
|
||||
/** 확장 식별자 패턴 (vendor-name) — 경로 세그먼트 화이트리스트 */
|
||||
private const IDENTIFIER_PATTERN = '/^[a-z0-9]+-[a-z0-9_]+$/';
|
||||
|
||||
/** 로케일 패턴 — 경로 세그먼트 화이트리스트 */
|
||||
private const LOCALE_PATTERN = '/^[a-z]{2}(?:[-_][A-Za-z0-9]{2,8})?$/';
|
||||
|
||||
/** terminating 게시 예약 플래그 (프로세스당 1회) */
|
||||
private static bool $publishScheduled = false;
|
||||
|
||||
/** isPublished 요청당 메모이즈 (version => 존재 여부) */
|
||||
private array $publishedMemo = [];
|
||||
|
||||
public function __construct(
|
||||
private TemplateService $templateService,
|
||||
private TemplateRepositoryInterface $templateRepository,
|
||||
private ExtensionBundleService $bundleService,
|
||||
private LanguagePackService $languagePackService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 현재 확장 캐시 버전 기준으로 게시합니다.
|
||||
*
|
||||
* 이미 게시 완료(manifest 존재) 상태면 skip(멱등). `Cache::lock` 으로 단일
|
||||
* 실행을 보장하며, 락 미획득 시 다른 프로세스가 게시 중인 것으로 보고 skip.
|
||||
*
|
||||
* @param bool $force 게시 완료 상태여도 강제 재게시
|
||||
* @return bool 게시 완료 상태로 끝났으면 true (skip 포함), 실패/비활성이면 false
|
||||
*/
|
||||
public function publishCurrent(bool $force = false): bool
|
||||
{
|
||||
if (! $this->isEnabled()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$version = self::getExtensionCacheVersion();
|
||||
|
||||
if (! $force && $this->isPublished($version)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$lock = Cache::lock(self::LOCK_PREFIX.$version, 300);
|
||||
|
||||
if (! $lock->get()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 락 대기 중 다른 프로세스가 완료했을 수 있다 (멱등 재확인)
|
||||
unset($this->publishedMemo[$version]);
|
||||
if (! $force && $this->isPublished($version)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->publishVersion($version);
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 해당 버전이 게시 완료 상태인지 확인합니다 (manifest 존재 = 완료).
|
||||
*
|
||||
* AssetUrl 게이트가 요청당 여러 번 호출하므로 메모이즈한다.
|
||||
*
|
||||
* @param int $version 확장 캐시 버전
|
||||
* @return bool 게시 완료 여부
|
||||
*/
|
||||
public function isPublished(int $version): bool
|
||||
{
|
||||
return $this->publishedMemo[$version] ??= is_file(
|
||||
$this->versionDir($version).DIRECTORY_SEPARATOR.self::MANIFEST_FILE
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 버전 + 직전 1개를 보존하고 나머지 게시 디렉토리를 삭제합니다.
|
||||
*
|
||||
* 직전 버전을 남기는 이유: 브라우저에 캐시된 직전 렌더 HTML 이 아직 구버전
|
||||
* 정적 URL 을 참조할 수 있다 (asset-url-recovery 파샬이 최후 방어).
|
||||
*
|
||||
* @return int 삭제된 디렉토리 수
|
||||
*/
|
||||
public function cleanup(): int
|
||||
{
|
||||
$base = $this->baseDir();
|
||||
|
||||
if (! File::isDirectory($base)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$current = self::getExtensionCacheVersion();
|
||||
$versions = [];
|
||||
$deleted = 0;
|
||||
|
||||
foreach (File::directories($base) as $dir) {
|
||||
$name = basename($dir);
|
||||
|
||||
// 미완료 tmp 잔존물은 무조건 제거 대상 (rename 전 실패 흔적)
|
||||
if (str_ends_with($name, '.tmp')) {
|
||||
File::deleteDirectory($dir);
|
||||
$deleted++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ctype_digit($name)) {
|
||||
$versions[(int) $name] = $dir;
|
||||
}
|
||||
}
|
||||
|
||||
// 현재 버전과, 현재를 제외한 최신 1개(직전) 보존
|
||||
$keep = [$current];
|
||||
$others = array_keys($versions);
|
||||
rsort($others);
|
||||
foreach ($others as $v) {
|
||||
if ($v !== $current) {
|
||||
$keep[] = $v;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($versions as $v => $dir) {
|
||||
if (! in_array($v, $keep, true)) {
|
||||
File::deleteDirectory($dir);
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 수명주기 이벤트에서 호출되는 terminating 게시 예약.
|
||||
*
|
||||
* `incrementExtensionCacheVersion()` 내부 단일 지점에서 호출된다.
|
||||
* 프로세스당 1회만 등록하며, 게시는 예약 시점이 아니라 **실행 시점의 현재
|
||||
* 버전**으로 수행되어 연속 bump(일괄 업데이트)를 자연 병합한다.
|
||||
*
|
||||
* 프로덕션 전용 — 비프로덕션은 blade 가 정적 URL 을 방출하지 않으므로
|
||||
* 게시 자체가 무의미하고(§2-2), testing 환경의 파일 쓰기 부수효과도 차단한다.
|
||||
*/
|
||||
public static function schedulePublishOnTerminate(): void
|
||||
{
|
||||
if (self::$publishScheduled || ! app()->environment('production')) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$publishScheduled = true;
|
||||
|
||||
app()->terminating(static function (): void {
|
||||
// 실행 시점에 재무장 가능 상태로 복귀 — 요청마다 앱 인스턴스를 새로 쓰는
|
||||
// 장수 프로세스(Octane 류)에서는 static 플래그만 살아남으므로, 리셋 없이는
|
||||
// 2번째 이후 bump 가 새 앱에 콜백을 등록하지 못한 채 영구 미게시가 된다
|
||||
// (자가 치유도 같은 플래그 공유). FPM(요청=프로세스)에서는 무영향.
|
||||
self::$publishScheduled = false;
|
||||
|
||||
try {
|
||||
app(self::class)->publishCurrent();
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('정적 게시 terminating 실행 실패 — 다음 렌더의 자가 치유가 재시도합니다', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 격리용 — terminating 예약 플래그를 초기화합니다.
|
||||
*/
|
||||
public static function resetPublishScheduleForTesting(): void
|
||||
{
|
||||
self::$publishScheduled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 루트 디렉토리 절대 경로를 반환합니다.
|
||||
*
|
||||
* @return string `public/build/ext` 절대 경로
|
||||
*/
|
||||
public function baseDir(): string
|
||||
{
|
||||
return public_path('build/ext');
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 디렉토리 절대 경로를 반환합니다.
|
||||
*
|
||||
* @param int $version 확장 캐시 버전
|
||||
* @return string 버전 디렉토리 절대 경로
|
||||
*/
|
||||
public function versionDir(int $version): string
|
||||
{
|
||||
return $this->baseDir().DIRECTORY_SEPARATOR.$version;
|
||||
}
|
||||
|
||||
/**
|
||||
* kill-switch 판정 (`core.static_cache.enabled`, .env `G7_STATIC_CACHE`).
|
||||
*
|
||||
* @return bool 정적 게시 활성 여부
|
||||
*/
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return (bool) config('core.static_cache.enabled', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 버전의 게시를 실제 수행합니다 (tmp 쓰기 → rename → manifest → GC).
|
||||
*
|
||||
* @param int $version 게시할 확장 캐시 버전
|
||||
* @return bool 성공 여부
|
||||
*/
|
||||
private function publishVersion(int $version): bool
|
||||
{
|
||||
$base = $this->baseDir();
|
||||
$tmp = $base.DIRECTORY_SEPARATOR.$version.'.tmp';
|
||||
$final = $this->versionDir($version);
|
||||
|
||||
try {
|
||||
File::deleteDirectory($tmp);
|
||||
File::ensureDirectoryExists($tmp, 0775);
|
||||
|
||||
$files = [];
|
||||
|
||||
$this->writeHtaccess($tmp, $files);
|
||||
|
||||
$locales = $this->publishableLocales();
|
||||
|
||||
foreach ($this->templateRepository->getActive() as $template) {
|
||||
$this->publishTemplate($tmp, $template, $locales, $files);
|
||||
}
|
||||
|
||||
$this->publishBundles($tmp, $version, $files);
|
||||
|
||||
// 원자적 스왑 — force 재게시 시 기존 디렉토리를 비켜낸 뒤 rename
|
||||
if (File::isDirectory($final)) {
|
||||
File::deleteDirectory($final);
|
||||
}
|
||||
|
||||
if (! @rename($tmp, $final)) {
|
||||
throw new StaticCachePublishException("Failed to rename publish directory: {$tmp} -> {$final}");
|
||||
}
|
||||
|
||||
// manifest 는 rename 후 마지막 기록 — 존재 = 게시 완료
|
||||
$this->writeManifest($final, $version, $files);
|
||||
unset($this->publishedMemo[$version]);
|
||||
|
||||
// sudo/root CLI 게시 대응 — terminating 게시는 코어 업데이트의
|
||||
// restoreOwnership **이후**(프로세스 종료 시)에 실행되므로, root 소유로
|
||||
// 남으면 이후 php-fpm 의 재게시·GC 가 영구 실패한다. 부모(public/build)
|
||||
// 소유권을 상속시킨다 (FilePermissionHelper::copyFile 의 sudo 대응 선례).
|
||||
$this->normalizeOwnership();
|
||||
|
||||
// 인라인 GC (현재 + 직전 1개 보존)
|
||||
$this->cleanup();
|
||||
|
||||
Log::info('부트스트랩 리소스 정적 게시 완료', [
|
||||
'version' => $version,
|
||||
'files' => count($files),
|
||||
]);
|
||||
|
||||
return true;
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('부트스트랩 리소스 정적 게시 실패 — API 폴백으로 동작합니다', [
|
||||
'version' => $version,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
File::deleteDirectory($tmp);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* root 로 실행된 CLI 게시의 산출물 소유권을 부모 디렉토리 기준으로 정상화합니다.
|
||||
*
|
||||
* root 가 아닌 프로세스는 chown 자체가 불가능하고 필요도 없다(자기 소유로 생성됨)
|
||||
* — 그 경우 즉시 no-op. 실패는 chownRecursive 가 경고 로그로 누적한다.
|
||||
* 게시 루트 전체(`build/ext`)를 대상으로 하므로 방금 게시된 버전 디렉토리와
|
||||
* 잔존 구버전이 함께 정상화된다.
|
||||
*/
|
||||
private function normalizeOwnership(): void
|
||||
{
|
||||
if (! function_exists('chown') || ! function_exists('posix_geteuid') || posix_geteuid() !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$parent = dirname($this->baseDir());
|
||||
$owner = @fileowner($parent);
|
||||
$group = @filegroup($parent);
|
||||
|
||||
if ($owner === false || $owner === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
FilePermissionHelper::chownRecursive($this->baseDir(), $owner, $group);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 템플릿 1개의 게시물(lang/components/routes/assets)을 기록합니다.
|
||||
*
|
||||
* @param string $tmp tmp 디렉토리 절대 경로
|
||||
* @param Template $template 활성 템플릿
|
||||
* @param array<string> $locales 게시 대상 로케일
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
*/
|
||||
private function publishTemplate(string $tmp, Template $template, array $locales, array &$files): void
|
||||
{
|
||||
$identifier = (string) $template->identifier;
|
||||
|
||||
if (! preg_match(self::IDENTIFIER_PATTERN, $identifier)) {
|
||||
Log::warning('정적 게시 제외 — 식별자 패턴 불일치', ['identifier' => $identifier]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$templateDir = $tmp.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$identifier;
|
||||
|
||||
// 1. lang 병합 결과 (코어→템플릿→모듈→플러그인→언어팩 훅) — 현 lang API 와 동일 형상(raw)
|
||||
foreach ($locales as $locale) {
|
||||
$result = $this->templateService->getLanguageDataWithModules($identifier, $locale);
|
||||
|
||||
if (! ($result['success'] ?? false) || ! is_array($result['data'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->writeJson(
|
||||
$templateDir.DIRECTORY_SEPARATOR.'lang'.DIRECTORY_SEPARATOR.$locale.'.json',
|
||||
$result['data'],
|
||||
$files,
|
||||
$tmp
|
||||
);
|
||||
}
|
||||
|
||||
// 2. components.json 사본 (raw)
|
||||
$componentsPath = base_path("templates/{$identifier}/components.json");
|
||||
if (is_file($componentsPath)) {
|
||||
$this->copyFile($componentsPath, $templateDir.DIRECTORY_SEPARATOR.'components.json', $files, $tmp);
|
||||
}
|
||||
|
||||
// 3. routes 병합 결과 — 프론트 소비 코드 무변경을 위한 성공 봉투 포함.
|
||||
// 열화 스냅샷(확장 업데이트 진행 중 등)은 게시하지 않는다 — 정적 파일은
|
||||
// 스스로 회복되지 않으므로 열화 상태가 다음 bump 까지 박제된다 (getRoutes 와 동일 규율)
|
||||
$routesResult = $this->templateService->getRoutesDataWithModules($identifier);
|
||||
|
||||
if (($routesResult['success'] ?? false) && ! $this->templateService->lastRouteMergeWasDegraded()) {
|
||||
$this->writeJson(
|
||||
$templateDir.DIRECTORY_SEPARATOR.'routes.json',
|
||||
['success' => true, 'message' => '', 'data' => $routesResult['data']],
|
||||
$files,
|
||||
$tmp
|
||||
);
|
||||
} elseif ($routesResult['success'] ?? false) {
|
||||
Log::warning('정적 게시에서 routes 제외 — 라우트 병합 열화 상태 (확장 업데이트 진행 중 추정)', [
|
||||
'template' => $identifier,
|
||||
]);
|
||||
}
|
||||
|
||||
// 4. dist 에셋 사본 (확장자 화이트리스트, *.map 제외)
|
||||
$this->publishDistAssets(
|
||||
base_path("templates/{$identifier}/dist"),
|
||||
$templateDir.DIRECTORY_SEPARATOR.'assets',
|
||||
$files,
|
||||
$tmp
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 dist 디렉토리를 재귀 복사합니다 (허용 확장자만, 소스맵 제외).
|
||||
*
|
||||
* @param string $sourceDir 원본 dist 절대 경로
|
||||
* @param string $targetDir 게시 대상 절대 경로
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
* @param string $tmp tmp 루트 (상대 경로 계산용)
|
||||
*/
|
||||
private function publishDistAssets(string $sourceDir, string $targetDir, array &$files, string $tmp): void
|
||||
{
|
||||
$realSource = realpath($sourceDir);
|
||||
|
||||
if ($realSource === false || ! is_dir($realSource)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 소스맵은 배포 금지 정책(`*.map` gitignore)과 동일하게 제외
|
||||
$allowed = array_diff(AllowedTemplateFileType::getAllowedExtensions(), ['map']);
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($realSource, \FilesystemIterator::SKIP_DOTS)
|
||||
);
|
||||
|
||||
/** @var \SplFileInfo $file */
|
||||
foreach ($iterator as $file) {
|
||||
if (! $file->isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$extension = strtolower($file->getExtension());
|
||||
if (! in_array($extension, $allowed, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 컨테인먼트 검증 — 심볼릭 링크 등으로 dist 밖을 가리키는 실경로 차단
|
||||
$realFile = $file->getRealPath();
|
||||
if ($realFile === false || ! str_starts_with($realFile, $realSource.DIRECTORY_SEPARATOR)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$relative = substr($realFile, strlen($realSource) + 1);
|
||||
$this->copyFile($realFile, $targetDir.DIRECTORY_SEPARATOR.$relative, $files, $tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 병합 번들 4종(modules/plugins × js/css)을 게시합니다.
|
||||
*
|
||||
* @param string $tmp tmp 디렉토리 절대 경로
|
||||
* @param int $version 확장 캐시 버전
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
*/
|
||||
private function publishBundles(string $tmp, int $version, array &$files): void
|
||||
{
|
||||
$map = ['module' => 'modules', 'plugin' => 'plugins'];
|
||||
|
||||
foreach ($map as $type => $plural) {
|
||||
foreach (['js', 'css'] as $kind) {
|
||||
$path = $this->bundleService->getBundleFilePath($type, $kind, $version);
|
||||
|
||||
if ($path === '' || ! is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->copyFile(
|
||||
$path,
|
||||
$tmp.DIRECTORY_SEPARATOR.'bundles'.DIRECTORY_SEPARATOR."{$plural}.{$kind}",
|
||||
$files,
|
||||
$tmp
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 대상 로케일을 열거합니다 — `/api/locales/active` 와 동일 소스
|
||||
* (언어팩이 추가한 로케일 포함).
|
||||
*
|
||||
* @return array<string> 로케일 목록 (패턴 검증 통과분)
|
||||
*/
|
||||
private function publishableLocales(): array
|
||||
{
|
||||
$locales = $this->languagePackService->getActiveLocales();
|
||||
|
||||
return array_values(array_filter(
|
||||
is_array($locales) ? $locales : [],
|
||||
static fn ($locale) => is_string($locale) && preg_match(self::LOCALE_PATTERN, $locale)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 파일을 API 와 동일 인코딩 옵션으로 기록합니다.
|
||||
*
|
||||
* @param string $absolutePath 기록 대상 절대 경로
|
||||
* @param mixed $data 직렬화할 데이터
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
* @param string $tmp tmp 루트 (상대 경로 계산용)
|
||||
*/
|
||||
private function writeJson(string $absolutePath, mixed $data, array &$files, string $tmp): void
|
||||
{
|
||||
File::ensureDirectoryExists(dirname($absolutePath), 0775);
|
||||
|
||||
$json = json_encode($data, ResponseHelper::JSON_ENCODE_OPTIONS);
|
||||
|
||||
if ($json === false) {
|
||||
throw new StaticCachePublishException("Failed to encode JSON payload: {$absolutePath}");
|
||||
}
|
||||
|
||||
if (File::put($absolutePath, $json) === false) {
|
||||
throw new StaticCachePublishException("Failed to write file: {$absolutePath}");
|
||||
}
|
||||
|
||||
$files[] = $this->relativePath($absolutePath, $tmp);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 1개를 복사합니다.
|
||||
*
|
||||
* @param string $source 원본 절대 경로
|
||||
* @param string $target 대상 절대 경로
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
* @param string $tmp tmp 루트 (상대 경로 계산용)
|
||||
*/
|
||||
private function copyFile(string $source, string $target, array &$files, string $tmp): void
|
||||
{
|
||||
File::ensureDirectoryExists(dirname($target), 0775);
|
||||
|
||||
if (! File::copy($source, $target)) {
|
||||
throw new StaticCachePublishException("Failed to copy file: {$source} -> {$target}");
|
||||
}
|
||||
|
||||
$files[] = $this->relativePath($target, $tmp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apache 용 불변 캐시 헤더 + 압축 .htaccess 를 기록합니다.
|
||||
*
|
||||
* 정적 서빙은 Laravel 압축 미들웨어(GzipEncodeResponse)를 우회하므로 압축을
|
||||
* 여기서 직접 선언한다 — 없으면 종전 API 대비 전송량 회귀다 (실측: lang/ko.json
|
||||
* 524,915B 비압축). nginx 는 서버 기본(ETag/Last-Modified) 재검증으로 충분하며
|
||||
* 권장 gzip/expires 스니펫은 규정 문서(§8)에 안내한다.
|
||||
*
|
||||
* @param string $tmp tmp 디렉토리 절대 경로
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
*/
|
||||
private function writeHtaccess(string $tmp, array &$files): void
|
||||
{
|
||||
$content = <<<'HTACCESS'
|
||||
<IfModule mod_headers.c>
|
||||
Header set Cache-Control "public, max-age=31536000, immutable"
|
||||
</IfModule>
|
||||
<IfModule mod_deflate.c>
|
||||
AddOutputFilterByType DEFLATE application/json application/javascript text/css image/svg+xml
|
||||
</IfModule>
|
||||
|
||||
HTACCESS;
|
||||
|
||||
if (File::put($tmp.DIRECTORY_SEPARATOR.'.htaccess', $content) === false) {
|
||||
throw new StaticCachePublishException('Failed to write .htaccess');
|
||||
}
|
||||
|
||||
$files[] = '.htaccess';
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 완료 마커(manifest.json)를 기록합니다.
|
||||
*
|
||||
* @param string $finalDir 최종 버전 디렉토리 절대 경로
|
||||
* @param int $version 확장 캐시 버전
|
||||
* @param array<string> $files 게시된 상대 경로 목록
|
||||
*/
|
||||
private function writeManifest(string $finalDir, int $version, array $files): void
|
||||
{
|
||||
$manifest = [
|
||||
'cache_version' => $version,
|
||||
'published_at' => now()->toIso8601String(),
|
||||
'files' => array_values($files),
|
||||
];
|
||||
|
||||
$json = json_encode($manifest, ResponseHelper::JSON_ENCODE_OPTIONS);
|
||||
|
||||
if ($json === false || File::put($finalDir.DIRECTORY_SEPARATOR.self::MANIFEST_FILE, $json) === false) {
|
||||
throw new StaticCachePublishException('Failed to write manifest');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* tmp 루트 기준 상대 경로를 반환합니다.
|
||||
*
|
||||
* @param string $absolutePath 절대 경로
|
||||
* @param string $tmp tmp 루트
|
||||
* @return string 상대 경로 (구분자 `/` 정규화)
|
||||
*/
|
||||
private function relativePath(string $absolutePath, string $tmp): string
|
||||
{
|
||||
return str_replace('\\', '/', substr($absolutePath, strlen($tmp) + 1));
|
||||
}
|
||||
}
|
||||
+147
-2
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use App\Support\Routing\DualExtensionRoute;
|
||||
|
||||
/**
|
||||
@@ -59,6 +60,23 @@ class AssetUrl
|
||||
*/
|
||||
private static ?string $modeOverride = null;
|
||||
|
||||
/**
|
||||
* 정적 게시(bake) 베이스 경로 메모 (요청당 1회 판정).
|
||||
*/
|
||||
private static ?string $staticExtBaseMemo = null;
|
||||
|
||||
/**
|
||||
* 정적 게시 베이스 판정 완료 여부.
|
||||
*/
|
||||
private static bool $staticExtBaseResolved = false;
|
||||
|
||||
/**
|
||||
* 태그 계층 파일 단위 게이트 메모 (상대 경로 => 존재 여부).
|
||||
*
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
private static array $staticFileMemo = [];
|
||||
|
||||
/**
|
||||
* 현재 자산 URL 모드를 반환합니다.
|
||||
*
|
||||
@@ -103,6 +121,105 @@ class AssetUrl
|
||||
self::$modeOverride = $mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정적 게시(bake) 베이스 경로를 반환합니다 (#122).
|
||||
*
|
||||
* 게이트 3조건 — ① 프로덕션 ② `core.static_cache.enabled` ③ 현재 버전 게시
|
||||
* 완료(manifest 존재) — 을 전부 통과할 때만 `/build/ext/{v}` 를 반환한다.
|
||||
* 아니면 null (종전 API URL 방출). 요청당 1회 판정 후 메모이즈한다.
|
||||
*
|
||||
* 자가 치유 — 프로덕션인데 현재 버전이 미게시면 terminating 게시를 예약한다.
|
||||
* 이번 응답은 종전 API URL 로 나가고(첫 방문자 1회만 종전 속도), 다음
|
||||
* 렌더부터 정적 fast path 가 적용된다.
|
||||
*
|
||||
* blade 렌더 경로에서 호출되므로 어떤 실패도 예외로 새 나가면 안 된다.
|
||||
*
|
||||
* @return string|null 정적 베이스 경로 또는 null
|
||||
*/
|
||||
public static function staticExtBase(): ?string
|
||||
{
|
||||
if (self::$staticExtBaseResolved) {
|
||||
return self::$staticExtBaseMemo;
|
||||
}
|
||||
|
||||
self::$staticExtBaseResolved = true;
|
||||
self::$staticExtBaseMemo = null;
|
||||
|
||||
try {
|
||||
if (! app()->environment('production')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! (bool) config('core.static_cache.enabled', true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 트레이트 정적 메서드 직접 호출(ClearsTemplateCaches::)은 PHP 8.1+ E_DEPRECATED
|
||||
// — 트레이트를 사용하는 클래스 경유로 호출한다 (게이트·게시자가 같은 static
|
||||
// 스토어 메모 슬롯을 공유하게 되는 부수 이점도 있다)
|
||||
$version = ExtensionStaticCacheService::getExtensionCacheVersion();
|
||||
|
||||
if (! app(ExtensionStaticCacheService::class)->isPublished($version)) {
|
||||
// 자가 치유 — 응답 종료 후 게시 시도 (실패해도 API 폴백으로 정상)
|
||||
ExtensionStaticCacheService::schedulePublishOnTerminate();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
self::$staticExtBaseMemo = '/build/ext/'.$version;
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return self::$staticExtBaseMemo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정적 게시 베이스 메모를 초기화합니다 (테스트 전용).
|
||||
*/
|
||||
public static function resetStaticExtBaseMemo(): void
|
||||
{
|
||||
self::$staticExtBaseResolved = false;
|
||||
self::$staticExtBaseMemo = null;
|
||||
self::$staticFileMemo = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 정적 게시본 내 파일 존재 여부를 확인합니다 (태그 계층 파일 단위 게이트).
|
||||
*
|
||||
* `<link>`/`<script>` 태그는 404 를 받아도 스스로 재시도하지 못하므로,
|
||||
* manifest 게이트에 더해 그 자산의 실파일 존재까지 확인한 뒤에만 정적 URL 을
|
||||
* 방출한다 (요청당 태그 대상 ~6개 파일, 메모이즈).
|
||||
*
|
||||
* @param string $relative 게시 트리 상대 경로
|
||||
* @return bool 파일 존재 여부
|
||||
*/
|
||||
private static function staticFileExists(string $relative): bool
|
||||
{
|
||||
$version = substr((string) self::$staticExtBaseMemo, strlen('/build/ext/'));
|
||||
|
||||
return self::$staticFileMemo[$relative] ??= is_file(
|
||||
public_path('build/ext/'.$version.'/'.$relative)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 태그 계층 자산의 정적 게시 URL 을 반환합니다 (파일 존재 확인 포함).
|
||||
*
|
||||
* @param string $relative 게시 트리 상대 경로
|
||||
* @return string|null 정적 URL 또는 null (게이트 미통과)
|
||||
*/
|
||||
private static function staticTagUrl(string $relative): ?string
|
||||
{
|
||||
$base = self::staticExtBase();
|
||||
|
||||
if ($base === null || ! self::staticFileExists($relative)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $base.'/'.$relative;
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 자산 URL 을 생성합니다.
|
||||
*
|
||||
@@ -112,11 +229,28 @@ class AssetUrl
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param string $path `dist/` 이하 파일 경로 (예: `js/components.iife.js`)
|
||||
* @param int|string|null $version 캐시 무효화 버전 (null 이면 미부착)
|
||||
* @param bool $allowStatic 정적 게시본(bake) 경로 허용 여부. 생성한 URL 이 정적
|
||||
* 게시 GC(현재+직전 1개 보존)보다 오래 사는 저장소에 박제되는
|
||||
* 호출부(SEO 페이지 캐시 등)는 false 로 종전 API URL 을 받는다
|
||||
* @return string 생성된 URL
|
||||
*/
|
||||
public static function templateAsset(string $identifier, string $path, int|string|null $version = null): string
|
||||
public static function templateAsset(string $identifier, string $path, int|string|null $version = null, bool $allowStatic = true): string
|
||||
{
|
||||
return self::asset('templates', $identifier, $path, $version);
|
||||
// 정적 게시본(bake) 우선 (#122) — 버전 디렉토리 경로라 `?v` 쿼리가 불필요하다.
|
||||
// 게이트(프로덕션·kill-switch·게시 완료·개별 파일 존재) 미통과 시 종전 URL 그대로.
|
||||
// `$version` 이 현재 게시 버전과 다르면 정적 분기를 건너뛴다 — 정적 경로는 항상
|
||||
// 현재 게시본이므로, 다른 버전을 명시한 호출에 현재본을 주면 "요청 버전이 URL 에
|
||||
// 반영된다" 는 시그니처 계약이 조용히 깨진다 (현 호출부는 전부 현재 버전 전달).
|
||||
$static = null;
|
||||
if ($allowStatic) {
|
||||
$base = self::staticExtBase();
|
||||
|
||||
if ($base !== null && ($version === null || $base === '/build/ext/'.$version)) {
|
||||
$static = self::staticTagUrl('templates/'.$identifier.'/assets/'.ltrim($path, '/'));
|
||||
}
|
||||
}
|
||||
|
||||
return $static ?? self::asset('templates', $identifier, $path, $version);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -178,6 +312,17 @@ class AssetUrl
|
||||
*/
|
||||
public static function extensionBundle(string $type, string $kind, int|string|null $version = null): string
|
||||
{
|
||||
// 정적 게시본(bake) 우선 (#122) — `bundles/{modules|plugins}.{js|css}` 사본.
|
||||
// `$version` 명시 호출이 현재 게시 버전과 다르면 건너뛴다 (templateAsset 과 동일 계약)
|
||||
$base = self::staticExtBase();
|
||||
$static = $base !== null && ($version === null || $base === '/build/ext/'.$version)
|
||||
? self::staticTagUrl("bundles/{$type}.{$kind}")
|
||||
: null;
|
||||
|
||||
if ($static !== null) {
|
||||
return $static;
|
||||
}
|
||||
|
||||
$base = self::isExtensionless()
|
||||
? "/api/{$type}/bundle/{$kind}"
|
||||
: "/api/{$type}/bundle.{$kind}";
|
||||
|
||||
Reference in new issue
Block a user