fix(core,admin_basic): 정적 게시 재게시 누락 3건 수정 + 관리자 수동 복구 UI + sudo core:update 소유권 정합
- 템플릿 update 는 레이아웃 변경 여부와 무관하게 캐시 버전을 올리고(실패 복원 뒤에도), 자산 주소 방식 전환 3경로도 bump 한다 - config:cache 가 컨테이너 인스턴스를 덮어 이후 terminating 재게시가 사라지던 결함을 복원 헬퍼로 차단 - custom/ 변경 감지와 게시가 같은 열거자(재귀·크기 포함)를 쓰고, 서명은 호스트별로 저장 - 캐시 버전·서명 키를 만료시키지 않는다(기본 TTL 24h 로 매일 전체 재생성되던 문제) - 관리자 > 환경설정 > 일반 「초기 화면 정적 파일」 카드: 상태 조회 + 지금 다시 만들기(확인 모달), 대시보드 알림 버튼 연결, CLI 와 같은 statusReport 소비 - sudo core:update 경로의 root 소유 잔존(설정 디렉토리·임시 폴더·로그·업그레이드 마이그레이션 산출물) 상속·정합화, ext-static 명령 root 경고와 sudo -u 힌트 - 안내·문서·트러블슈팅 4건·audit 룰 ext-cache-version-raw-read·ja 언어팩 동기
This commit is contained in:
1 parent
d263f74cae
commit
de18159986
105 files changed
+4055
-208
No files matched your search
@@ -1371,44 +1371,17 @@ class CoreUpdateCommand extends Command
|
||||
* - `root_web_symmetric` : root 실행 + 웹서버 계정이 root 로 추정됨 (root 서비스 구성).
|
||||
* - `root_web_unknown` : root 실행 + 웹서버 계정 추정 실패 (스냅샷/추정 불가).
|
||||
*
|
||||
* 웹서버 계정은 `FilePermissionHelper::inferWebServerOwnership()` 이 storage/bootstrap
|
||||
* 쓰기 영역 소유자로 추정한다.
|
||||
* 판정은 `FilePermissionHelper::describeWebServerAccount()` 가 소유한다 — 정적 게시 상태·게시
|
||||
* 명령(`ext-static:*`)의 root 경고와 같은 4분기를 공유하기 위해 옮겼다(#651 C1). 이 메서드는
|
||||
* 그 결과를 종전 반환 형태(`[모드, 계정명]`)로 바꿔 주는 위임만 한다.
|
||||
*
|
||||
* @return array{0: string, 1: string|null} [모드, 웹서버 계정명 또는 null]
|
||||
*/
|
||||
private function classifyResumeExecutionContext(): array
|
||||
{
|
||||
if (! function_exists('posix_geteuid') || ! function_exists('posix_getpwuid')) {
|
||||
return ['non_root', null];
|
||||
}
|
||||
$account = FilePermissionHelper::describeWebServerAccount();
|
||||
|
||||
// root(sudo) 실행이 아니면 일반 SSH 사용자 = 파일 소유자 → 권한 분기 안내 불필요.
|
||||
// (공유 호스팅에서 웹서버·PHP·실행 유저가 같은 경우도 여기서 non_root 로 처리됨.)
|
||||
if (posix_geteuid() !== 0) {
|
||||
return ['non_root', null];
|
||||
}
|
||||
|
||||
[$owner] = FilePermissionHelper::inferWebServerOwnership();
|
||||
|
||||
// 추정 실패 (스냅샷 불가) — 계정명 미상 경고 경로.
|
||||
if ($owner === false) {
|
||||
return ['root_web_unknown', null];
|
||||
}
|
||||
|
||||
// 웹서버 계정이 root 로 추정됨 — root 로 서비스하는 구성이라 재실행도 root 로 무해.
|
||||
if ($owner === 0) {
|
||||
return ['root_web_symmetric', null];
|
||||
}
|
||||
|
||||
$entry = posix_getpwuid($owner);
|
||||
$name = $entry['name'] ?? null;
|
||||
|
||||
// uid 는 나왔지만 이름 해석 실패 — 미상 경로로 처리 (uid 노출은 오히려 혼란).
|
||||
if ($name === null) {
|
||||
return ['root_web_unknown', null];
|
||||
}
|
||||
|
||||
return ['root_web_known', $name];
|
||||
return [$account['mode'], $account['name']];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -38,6 +38,14 @@ class PublishExtensionStaticCacheCommand extends Command
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
// root 로 실행 중이면 경고만 하고 **계속 진행**한다 — 명시적 명령은 운영자 책임이고, 중단 가드는
|
||||
// 두지 않는다(#651 D3). 게시가 만드는 캐시 락 샤드·병합 번들이 root 소유로 남으면 이후 웹 요청의
|
||||
// 캐시 쓰기가 Permission denied 로 죽으므로(전면 500 실사례) 웹 계정 실행 형태를 함께 적는다.
|
||||
if (StatusExtensionStaticCacheCommand::isRootProcess()) {
|
||||
$this->warn('root 로 실행 중입니다 — 이 계정으로 게시하면 캐시 폴더·병합 번들이 root 소유가 되어 이후 웹 요청이 실패할 수 있습니다.');
|
||||
$this->warn('웹 계정으로 실행하세요: '.StatusExtensionStaticCacheCommand::publishCommandHint());
|
||||
}
|
||||
|
||||
$published = $service->publishCurrent(force: (bool) $this->option('force'));
|
||||
|
||||
if (! $published) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -13,7 +14,10 @@ use Illuminate\Support\Facades\File;
|
||||
* 운영 환경에서 실패를 확인할 방법이 사실상 없었다(`/dev` 대시보드는 `app.debug` 가 필요한데
|
||||
* 게시는 프로덕션 전용이다). 이 커맨드가 그 통로다.
|
||||
*
|
||||
* 출력: 현재 버전 / 게시 여부 / manifest 파일 수 / 게시 트리 쓰기 가능성 /
|
||||
* 판정은 `ExtensionStaticCacheService::statusReport()` 가 소유한다 — 관리자 화면의
|
||||
* 「초기 화면 정적 파일」 카드와 같은 값을 소비하며, 이 커맨드는 문구·조치 힌트만 담당한다.
|
||||
*
|
||||
* 출력: 실행 계정 / 현재 버전 / 게시 여부 / manifest 파일 수 / 게시 트리 쓰기 가능성 /
|
||||
* 최근 실패 마커 / 잔존 버전 목록.
|
||||
*
|
||||
* 종료 코드: 이상이 하나라도 있으면 비-0. 비-0 은 "커맨드 실행 실패" 가 아니라
|
||||
@@ -41,23 +45,30 @@ class StatusExtensionStaticCacheCommand extends Command
|
||||
{
|
||||
$problems = [];
|
||||
|
||||
$enabled = $service->isEnabled();
|
||||
$version = ExtensionStaticCacheService::getExtensionCacheVersion();
|
||||
$report = $service->statusReport();
|
||||
$base = $service->baseDir();
|
||||
$versionDir = $service->versionDir($version);
|
||||
$published = $service->isPublished($version);
|
||||
$publishHint = self::publishCommandHint();
|
||||
|
||||
$this->line('');
|
||||
$this->line('<options=bold>부트스트랩 리소스 정적 게시 상태</>');
|
||||
$this->line('');
|
||||
|
||||
$this->line(' 실행 계정 : '.ExtensionStaticCacheService::currentProcessUser());
|
||||
$this->line(' kill-switch : '.($enabled ? '활성 (게시함)' : '<comment>비활성 (게시 안 함)</comment>'));
|
||||
$this->line(' 현재 캐시 버전 : '.$version);
|
||||
$this->line(' 실행 계정 : '.$report['process_user']);
|
||||
|
||||
// root 로 실행 중이면 여기서 게시하지 말라고 먼저 알린다 — 캐시 락 샤드·병합 번들이 root
|
||||
// 소유로 남아 이후 웹 요청의 캐시 쓰기가 Permission denied 로 죽는다(전면 500 실사례).
|
||||
// 중단하지는 않는다 — 상태 점검은 읽기 전용이다. (#651 C1)
|
||||
if (self::isRootProcess()) {
|
||||
$this->line(' <comment>root 로 실행 중 — 이 계정으로 게시하면 캐시 폴더가 root 소유가 될 수 있습니다. '
|
||||
.'웹 계정으로 실행하세요: '.$publishHint.'</comment>');
|
||||
}
|
||||
|
||||
$this->line(' kill-switch : '.($report['enabled'] ? '활성 (게시함)' : '<comment>비활성 (게시 안 함)</comment>'));
|
||||
$this->line(' 현재 캐시 버전 : '.$report['version']);
|
||||
$this->line(' 게시 루트 : '.$base);
|
||||
|
||||
// kill-switch 가 꺼져 있으면 미게시는 정상이다 — 이상으로 세지 않는다.
|
||||
if (! $enabled) {
|
||||
if (! $report['enabled']) {
|
||||
$this->line('');
|
||||
$this->comment('kill-switch 가 꺼져 있어 게시 상태는 점검하지 않습니다 (core.static_cache.enabled).');
|
||||
|
||||
@@ -65,9 +76,7 @@ class StatusExtensionStaticCacheCommand extends Command
|
||||
}
|
||||
|
||||
// 1) 게시 트리 쓰기 가능성 — 제보 본건(P1/P2)의 직접 지표
|
||||
$writable = File::isDirectory($base) ? is_writable($base) : $this->parentIsWritable($base);
|
||||
|
||||
if ($writable) {
|
||||
if ($report['tree_writable']) {
|
||||
$this->line(' 트리 쓰기 : 가능');
|
||||
} else {
|
||||
$this->line(' 트리 쓰기 : <error>불가</error>');
|
||||
@@ -81,28 +90,27 @@ class StatusExtensionStaticCacheCommand extends Command
|
||||
}
|
||||
|
||||
// 2) 현재 버전 게시 여부
|
||||
if ($published) {
|
||||
$manifest = json_decode((string) @file_get_contents($versionDir.'/manifest.json'), true);
|
||||
$fileCount = is_array($manifest) ? count($manifest['files'] ?? []) : 0;
|
||||
|
||||
if ($report['published']) {
|
||||
$this->line(' 게시 상태 : 완료');
|
||||
$this->line(' manifest 파일 : '.$fileCount.'건');
|
||||
$this->line(' 게시 시각 : '.(is_array($manifest) ? ($manifest['published_at'] ?? '?') : '?'));
|
||||
$this->line(' manifest 파일 : '.$report['files'].'건');
|
||||
$this->line(' 게시 시각 : '.($report['published_at'] ?? '?'));
|
||||
|
||||
if ($fileCount === 0) {
|
||||
if ($report['files'] === 0) {
|
||||
$problems[] = 'manifest 에 기록된 파일이 0건입니다 — 게시가 비어 있습니다.';
|
||||
}
|
||||
} else {
|
||||
$this->line(' 게시 상태 : <comment>미게시</comment>');
|
||||
$problems[] = sprintf(
|
||||
'현재 버전(%d)이 게시되지 않았습니다. 다음 웹 렌더의 자가 치유가 시도하며, '
|
||||
.'즉시 게시하려면 `php artisan ext-static:publish` 를 실행하세요.',
|
||||
$version
|
||||
.'즉시 게시하려면 웹 계정으로 `%s` 를 실행하거나 관리자 > 환경설정 > 일반 의 '
|
||||
.'「지금 다시 만들기」를 사용하세요.',
|
||||
$report['version'],
|
||||
$publishHint
|
||||
);
|
||||
}
|
||||
|
||||
// 3) 최근 실패 마커 — 원인별로 조치가 다르다
|
||||
$marker = ExtensionStaticCacheService::failureMarker();
|
||||
$marker = $report['failure'];
|
||||
|
||||
if ($marker !== null) {
|
||||
$this->line('');
|
||||
@@ -117,7 +125,7 @@ class StatusExtensionStaticCacheCommand extends Command
|
||||
}
|
||||
|
||||
// 4) 잔존 버전 목록 — 누적은 삭제 실패(소유권 불일치)의 지표다
|
||||
$versions = $this->publishedVersions($base);
|
||||
$versions = $report['retained_versions'];
|
||||
|
||||
$this->line('');
|
||||
$this->line(' 잔존 버전 : '.($versions === [] ? '(없음)' : implode(', ', $versions)));
|
||||
@@ -148,16 +156,35 @@ class StatusExtensionStaticCacheCommand extends Command
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 루트가 아직 없을 때, 만들 수 있는지(부모 쓰기 가능) 판정합니다.
|
||||
* 수동 게시 명령을 웹 계정 실행 형태로 안내합니다 — `ext-static:publish` 와 공유.
|
||||
*
|
||||
* @param string $base 게시 루트 절대 경로
|
||||
* @return bool 생성 가능 여부
|
||||
* root 가 아니면 명령만 그대로다(일반 SSH 사용자 = 파일 소유자 / 공유 호스팅 대칭 구성 / posix
|
||||
* 미지원). root 이면 웹서버 계정을 식별해 `sudo -u {계정}` 을 붙이고, 식별하지 못하면
|
||||
* placeholder 와 확인 방법을 함께 적는다 — 판정은 `FilePermissionHelper::describeWebServerAccount()`
|
||||
* 가 소유한다(`core:update` 재실행 안내와 같은 4분기).
|
||||
*
|
||||
* @return string 안내 명령 문자열
|
||||
*/
|
||||
private function parentIsWritable(string $base): bool
|
||||
public static function publishCommandHint(): string
|
||||
{
|
||||
$parent = dirname($base);
|
||||
$command = 'php artisan ext-static:publish';
|
||||
$account = FilePermissionHelper::describeWebServerAccount();
|
||||
|
||||
return File::isDirectory($parent) && is_writable($parent);
|
||||
return match ($account['mode']) {
|
||||
'root_web_known' => 'sudo -u '.$account['name'].' '.$command,
|
||||
'root_web_unknown' => 'sudo -u <웹서버계정> '.$command.' (웹서버 계정은 storage 디렉토리 소유자로 확인)',
|
||||
default => $command,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 프로세스가 root(euid 0)로 실행 중인지 판정합니다 — 안내 분기 전용.
|
||||
*
|
||||
* @return bool root 실행 여부
|
||||
*/
|
||||
public static function isRootProcess(): bool
|
||||
{
|
||||
return FilePermissionHelper::describeWebServerAccount()['mode'] !== 'non_root';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -172,37 +199,11 @@ class StatusExtensionStaticCacheCommand extends Command
|
||||
{
|
||||
return match ($reason) {
|
||||
'parent_not_writable' => '게시 트리 권한 문제입니다. CLI 계정과 웹 계정이 그룹을 공유하고 '
|
||||
.'`public/build` 가 그룹 쓰기(g+w)인지 확인하세요.',
|
||||
.'`public/build` 가 그룹 쓰기(g+w)인지 확인하세요. 수동 게시는 웹 계정으로: '
|
||||
.self::publishCommandHint(),
|
||||
'write_failed' => '쓰기 도중 실패했습니다. 디스크 여유 공간과 quota 를 확인하세요.',
|
||||
'lock_unavailable' => '캐시 락을 얻지 못했습니다. 캐시 저장소(파일 캐시 디렉토리 권한 등)를 확인하세요.',
|
||||
default => '상세 메시지를 확인하세요.',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 루트에 남아 있는 버전 디렉토리 목록을 반환합니다 (오름차순).
|
||||
*
|
||||
* @param string $base 게시 루트 절대 경로
|
||||
* @return array<int, int> 버전 목록
|
||||
*/
|
||||
private function publishedVersions(string $base): array
|
||||
{
|
||||
if (! File::isDirectory($base)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$versions = [];
|
||||
|
||||
foreach (File::directories($base) as $dir) {
|
||||
$name = basename($dir);
|
||||
|
||||
if (ctype_digit($name)) {
|
||||
$versions[] = (int) $name;
|
||||
}
|
||||
}
|
||||
|
||||
sort($versions);
|
||||
|
||||
return $versions;
|
||||
}
|
||||
}
|
||||
@@ -822,6 +822,31 @@ class ExtensionPendingHelper
|
||||
return $basePath.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.$identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 업데이트용 임시 디렉토리(다운로드·추출)를 부모 소유권까지 정합화해 확보합니다.
|
||||
*
|
||||
* 세 매니저(모듈·플러그인·템플릿)가 같은 경로 규약(`storage/app/temp/{type}_update_{uid}`)을 쓰므로
|
||||
* 확보 절차도 한 곳에 둔다 — 복사본은 서로 다른 하드닝을 갖고 갈라진다.
|
||||
*
|
||||
* @param string $tempDir 임시 디렉토리 절대 경로
|
||||
*/
|
||||
public static function ensureUpdateTempDirectory(string $tempDir): void
|
||||
{
|
||||
// 부모(`storage/app/temp`)는 최초 1회만 만들어지고 자식만 삭제된다 — sudo 코어 업데이트의
|
||||
// 번들 확장 업데이트가 그 최초 생성자면 부모가 root 소유로 굳어, 이후 관리자 화면(웹 계정)의
|
||||
// 확장 업데이트가 임시 폴더를 만들지 못한다 (#651 F14). 부모는 소유권 상속·그룹 쓰기까지
|
||||
// 정합화하는 프리미티브로 확보하고, 자식은 만든 뒤 부모 소유권을 상속시킨다.
|
||||
// 확보 실패는 종전 동작(`ensureDirectoryExists` 의 예외 흐름)으로 폴백해 계약을 바꾸지 않는다.
|
||||
if (! FilePermissionHelper::ensureWritableDirectory(dirname($tempDir))) {
|
||||
File::ensureDirectoryExists($tempDir);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
File::ensureDirectoryExists($tempDir);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($tempDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 업데이트 스테이징용 타임스탬프 디렉토리를 생성합니다.
|
||||
*
|
||||
|
||||
@@ -566,6 +566,73 @@ class FilePermissionHelper
|
||||
return [$baseOwner, $baseGroup, 'base_path (대칭 구성)'];
|
||||
}
|
||||
|
||||
/** 테스트 전용 — `describeWebServerAccount()` 판정 오버라이드 (null = 실판정) */
|
||||
private static ?array $webServerAccountForTesting = null;
|
||||
|
||||
/**
|
||||
* 테스트 전용 — 실행 환경 판정을 강제합니다 (posix 부재 환경에서 root 분기를 재현하기 위해).
|
||||
*
|
||||
* @param array{mode: string, name: string|null}|null $account 강제할 판정 (null 로 실판정 복귀)
|
||||
*/
|
||||
public static function fakeWebServerAccountForTesting(?array $account): void
|
||||
{
|
||||
self::$webServerAccountForTesting = $account;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 프로세스 기준으로 "웹서버 계정" 안내에 필요한 실행 환경을 분류합니다.
|
||||
*
|
||||
* root(sudo) 로 artisan 을 실행하면 그 명령이 만드는 캐시 샤드·번들·임시 파일이 root 소유로 남아
|
||||
* 이후 웹 프로세스의 쓰기가 실패한다. 그래서 root 실행을 감지한 명령은 "웹서버 계정으로 실행"
|
||||
* 을 안내해야 하는데, 그 판정을 명령마다 다시 쓰면 한 곳만 어긋나도 서로 다른 안내가 나간다.
|
||||
* `core:update` 의 재실행 안내가 처음 세운 4분기를 그대로 옮겨 공유한다 — 동작 불변.
|
||||
*
|
||||
* 반환 모드:
|
||||
* - `non_root` : posix 미지원(Windows 등) 또는 현재 유효 사용자가 root 가 아님
|
||||
* (일반 SSH 사용자 = 파일 소유자, 공유 호스팅 대칭 구성 포함).
|
||||
* - `root_web_known` : root 실행 + 웹서버 계정 식별 성공 + 실행 사용자(root)와 다름.
|
||||
* - `root_web_symmetric` : root 실행 + 웹서버 계정이 root 로 추정됨 (root 서비스 구성).
|
||||
* - `root_web_unknown` : root 실행 + 웹서버 계정 추정 실패 (스냅샷/추정 불가).
|
||||
*
|
||||
* 웹서버 계정은 `inferWebServerOwnership()` 이 storage/bootstrap 쓰기 영역 소유자로 추정한다.
|
||||
*
|
||||
* @return array{mode: string, name: string|null} 모드와 웹서버 계정명(`root_web_known` 일 때만)
|
||||
*/
|
||||
public static function describeWebServerAccount(): array
|
||||
{
|
||||
if (self::$webServerAccountForTesting !== null) {
|
||||
return self::$webServerAccountForTesting;
|
||||
}
|
||||
|
||||
if (! function_exists('posix_geteuid') || ! function_exists('posix_getpwuid')) {
|
||||
return ['mode' => 'non_root', 'name' => null];
|
||||
}
|
||||
|
||||
if (posix_geteuid() !== 0) {
|
||||
return ['mode' => 'non_root', 'name' => null];
|
||||
}
|
||||
|
||||
[$owner] = static::inferWebServerOwnership();
|
||||
|
||||
if ($owner === false) {
|
||||
return ['mode' => 'root_web_unknown', 'name' => null];
|
||||
}
|
||||
|
||||
if ($owner === 0) {
|
||||
return ['mode' => 'root_web_symmetric', 'name' => null];
|
||||
}
|
||||
|
||||
$entry = posix_getpwuid($owner);
|
||||
$name = $entry['name'] ?? null;
|
||||
|
||||
// uid 는 나왔지만 이름 해석 실패 — 미상 경로로 처리 (uid 노출은 오히려 혼란).
|
||||
if ($name === null) {
|
||||
return ['mode' => 'root_web_unknown', 'name' => null];
|
||||
}
|
||||
|
||||
return ['mode' => 'root_web_known', 'name' => $name];
|
||||
}
|
||||
|
||||
/**
|
||||
* 경로와 그 하위 항목의 소유자·그룹을 재귀적으로 복원합니다.
|
||||
*
|
||||
|
||||
@@ -357,9 +357,13 @@ class SettingsMigrator
|
||||
return false;
|
||||
}
|
||||
|
||||
// 디렉토리 확인 및 생성
|
||||
// 디렉토리 확인 및 생성 — 파일(`writeJsonFile`)과 대칭으로 디렉토리도 부모 소유권을 상속한다.
|
||||
// sudo 코어 업데이트의 업그레이드 스텝이 이 디렉토리를 root 로 만들면 `storage/app/{modules,
|
||||
// plugins}` 는 restore_ownership 의도적 제외 경로라 코어 업데이트로도 되돌려지지 않고, 이후
|
||||
// 웹 프로세스의 그 모듈 설정 저장이 영구 실패한다 (#651 F13).
|
||||
if (! File::isDirectory($settingsDir)) {
|
||||
File::makeDirectory($settingsDir, 0755, true);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($settingsDir);
|
||||
}
|
||||
|
||||
// 카테고리 파일 생성
|
||||
|
||||
@@ -27,6 +27,7 @@ use App\Extension\Helpers\ExtensionPendingHelper;
|
||||
use App\Extension\Helpers\ExtensionRoleSyncHelper;
|
||||
use App\Extension\Helpers\ExtensionStatusGuard;
|
||||
use App\Extension\Helpers\ExtensionUpgradeGuardHelper;
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
@@ -1829,9 +1830,11 @@ class ModuleManager implements ModuleManagerInterface
|
||||
return;
|
||||
}
|
||||
|
||||
// 디렉토리 생성
|
||||
// 디렉토리 생성 — sudo 코어 업데이트(번들 확장 업데이트 프롬프트) 경로에서 root 로 만들어지면
|
||||
// `storage/app/modules` 는 restore_ownership 제외 경로라 되돌려지지 않는다 → 부모 소유권 상속 (#651 F13)
|
||||
if (! File::isDirectory($settingsDir)) {
|
||||
File::makeDirectory($settingsDir, 0755, true);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($settingsDir);
|
||||
}
|
||||
|
||||
// 카테고리별로 설정 파일 생성
|
||||
@@ -1846,6 +1849,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
|
||||
$jsonContent = json_encode($categoryData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||
File::put($filePath, $jsonContent);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($filePath);
|
||||
$createdFiles[] = $category.'.json';
|
||||
}
|
||||
|
||||
@@ -4140,7 +4144,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
$tempDir = storage_path('app/temp/module_update_'.uniqid());
|
||||
|
||||
try {
|
||||
File::ensureDirectoryExists($tempDir);
|
||||
ExtensionPendingHelper::ensureUpdateTempDirectory($tempDir);
|
||||
|
||||
// GitHub에서 다운로드 및 추출 (코어와 동일한 폴백 체인)
|
||||
$extractedDir = $this->extensionManager->downloadAndExtractFromGitHub(
|
||||
|
||||
@@ -27,6 +27,7 @@ use App\Extension\Helpers\ExtensionPendingHelper;
|
||||
use App\Extension\Helpers\ExtensionRoleSyncHelper;
|
||||
use App\Extension\Helpers\ExtensionStatusGuard;
|
||||
use App\Extension\Helpers\ExtensionUpgradeGuardHelper;
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
@@ -2637,14 +2638,17 @@ class PluginManager implements PluginManagerInterface
|
||||
return;
|
||||
}
|
||||
|
||||
// 디렉토리 생성
|
||||
// 디렉토리 생성 — sudo 코어 업데이트 경로에서 root 로 만들어지면 `storage/app/plugins` 는
|
||||
// restore_ownership 제외 경로라 되돌려지지 않는다 → 부모 소유권 상속 (#651 F13)
|
||||
if (! File::isDirectory($settingsDir)) {
|
||||
File::makeDirectory($settingsDir, 0755, true);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($settingsDir);
|
||||
}
|
||||
|
||||
// 기본값 저장
|
||||
$content = json_encode($defaults, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||
File::put($settingsPath, $content);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($settingsPath);
|
||||
|
||||
Log::info('플러그인 기본 설정 파일 생성 완료', [
|
||||
'plugin' => $identifier,
|
||||
@@ -4369,7 +4373,7 @@ class PluginManager implements PluginManagerInterface
|
||||
$tempDir = storage_path('app/temp/plugin_update_'.uniqid());
|
||||
|
||||
try {
|
||||
File::ensureDirectoryExists($tempDir);
|
||||
ExtensionPendingHelper::ensureUpdateTempDirectory($tempDir);
|
||||
|
||||
// GitHub에서 다운로드 및 추출 (코어와 동일한 폴백 체인)
|
||||
$extractedDir = $this->extensionManager->downloadAndExtractFromGitHub(
|
||||
|
||||
@@ -2854,7 +2854,7 @@ class TemplateManager implements TemplateManagerInterface
|
||||
$tempDir = storage_path('app/temp/template_update_'.uniqid());
|
||||
|
||||
try {
|
||||
File::ensureDirectoryExists($tempDir);
|
||||
ExtensionPendingHelper::ensureUpdateTempDirectory($tempDir);
|
||||
|
||||
// GitHub에서 다운로드 및 추출 (코어와 동일한 폴백 체인)
|
||||
$extractedDir = $this->extensionManager->downloadAndExtractFromGitHub(
|
||||
@@ -3183,11 +3183,14 @@ class TemplateManager implements TemplateManagerInterface
|
||||
|
||||
$this->clearAllTemplateLanguageCaches();
|
||||
$this->clearAllTemplateRoutesCaches();
|
||||
// refreshTemplateLayouts() 내부에서 변경 시 incrementExtensionCacheVersion() 호출됨
|
||||
// 비활성 템플릿이라 refreshTemplateLayouts()를 건너뛴 경우에만 여기서 증가
|
||||
if ($previousStatus !== ExtensionStatus::Active->value) {
|
||||
$this->incrementExtensionCacheVersion();
|
||||
}
|
||||
// 모듈(`updateModule`)·플러그인(`updatePlugin`)과 동형으로 **무조건** 올린다 —
|
||||
// lang/routes/components/dist 만 바뀐 릴리스도 정적 게시본(#122)을 갱신해야 한다.
|
||||
// 종전에는 활성 템플릿이면 `refreshTemplateLayouts()` 의 조건부 bump(레이아웃
|
||||
// 변경 건수 > 0)에 위임했는데, 그 조건은 게시 입력 중 레이아웃 축만 보므로
|
||||
// 레이아웃이 그대로인 릴리스는 게시본이 immutable 로 stale 하게 남았다(#651 F1).
|
||||
// `refreshTemplateLayouts()` 내부의 조건부 bump 는 단독 호출처(refresh-layout)가
|
||||
// 있어 그대로 두며, 이중 bump 는 put 1회 비용이고 terminating 게시는 1회로 병합된다.
|
||||
$this->incrementExtensionCacheVersion();
|
||||
self::invalidateTemplateStatusCache();
|
||||
|
||||
// 훅 발행: 템플릿 업데이트 완료 (Artisan 직접 호출 시에도 리스너 트리거)
|
||||
@@ -3237,6 +3240,15 @@ class TemplateManager implements TemplateManagerInterface
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// 실패 경로도 bump 한다 — 백업 복원이 실패했거나 부분 반영된 디스크가 남을 수
|
||||
// 있어, 게시본을 새 버전으로 다시 굽는 쪽이 옛 게시본을 그대로 두는 쪽보다
|
||||
// 안전하다(#651 F2). 원래 예외를 가리지 않도록 bump 실패는 삼킨다.
|
||||
try {
|
||||
$this->incrementExtensionCacheVersion();
|
||||
} catch (\Throwable) {
|
||||
// 원래 예외(아래 throw)가 진짜 원인이다 — bump 실패는 로그(트레이트)로 충분
|
||||
}
|
||||
|
||||
throw new \RuntimeException(
|
||||
__('templates.errors.update_failed', [
|
||||
'template' => $identifier,
|
||||
|
||||
@@ -21,6 +21,27 @@ trait ClearsTemplateCaches
|
||||
*/
|
||||
private static string $extensionCacheVersionKey = 'ext.cache_version';
|
||||
|
||||
/**
|
||||
* 확장 캐시 버전·custom 서명 키의 저장 TTL (초) — 10년.
|
||||
*
|
||||
* 이 키들은 **만료로 재생성되어서는 안 된다.** 버전 키가 만료되면 다음 독자가
|
||||
* `regenerateExtensionCacheVersion()` 으로 새 `time()` 을 만들고, 그것은 정적 게시본
|
||||
* (`public/build/ext/{v}/`, 실측 715파일·40MB) **전체 재생성** + 병합 번들 재병합 + 전
|
||||
* 방문자의 자산 URL 변경이다. TTL 을 넘기지 않으면 `AbstractCacheDriver::put()` 이
|
||||
* `cache.default_ttl`(기본 86400) 을 적용해 그 재생성이 **매일** 우발적으로 일어났다(#651 F11).
|
||||
*
|
||||
* 영구 저장의 두 후보를 쓰지 않는 이유:
|
||||
* - `forever()` 는 `CacheInterface` 밖이다 — 인터페이스 확장은 확장 공개 표면 변경이라
|
||||
* 번들 확장 전수의 `g7_version` 동기화 의무를 낳는다.
|
||||
* - `put(…, 0)` 은 Laravel `Repository::put` 이 `seconds <= 0` 을 **forget** 으로 처리해
|
||||
* 키를 지운다. 파일 스토어는 만료를 `9999999999` 로 캡하므로 큰 TTL 은 안전하다.
|
||||
*
|
||||
* 트레이트 안에서는 `self::` 로 읽지 않는다 — 트레이트 정적 메서드를 트레이트 이름으로 직접
|
||||
* 부르는 호출(테스트·레거시)에서 `self` 가 트레이트 자신으로 해석되어 "Cannot access trait
|
||||
* constant directly" 가 난다. 트레이트를 조합한 코어 서비스 클래스 경유로 읽는다.
|
||||
*/
|
||||
public const PERSISTENT_TTL_SECONDS = 315360000;
|
||||
|
||||
/**
|
||||
* 프로세스 1회 메모이즈된 확장 좌표 캐시 스토어 이름 (write/read 스토어 일관성).
|
||||
* `extensionCacheStore()` 가 최초 1회 채우며, 테스트는 `resetExtensionCacheStoreMemo()`
|
||||
@@ -39,7 +60,7 @@ trait ClearsTemplateCaches
|
||||
{
|
||||
try {
|
||||
$newVersion = time();
|
||||
self::resolveExtensionCache()->put(self::$extensionCacheVersionKey, $newVersion);
|
||||
self::resolveExtensionCache()->put(self::$extensionCacheVersionKey, $newVersion, ExtensionStaticCacheService::PERSISTENT_TTL_SECONDS);
|
||||
|
||||
Log::info('확장 기능 캐시 버전 증가', [
|
||||
'new_version' => $newVersion,
|
||||
@@ -91,6 +112,9 @@ trait ClearsTemplateCaches
|
||||
* 대신 동일 로직을 직접 수행한다. 저장 실패 시에도 0 으로 붕괴하지 않도록
|
||||
* 생성한 `time()` 값을 반환한다(다음 요청이 다시 생성·저장 시도).
|
||||
*
|
||||
* 키는 `PERSISTENT_TTL_SECONDS` 로 저장되므로 만료로 이 경로에 오지 않는다 — 키 부재는
|
||||
* `php artisan cache:clear` 또는 캐시 스토어 소실 때만이다.
|
||||
*
|
||||
* @return int 새로 생성된 유효 캐시 버전 (타임스탬프)
|
||||
*/
|
||||
private static function regenerateExtensionCacheVersion(): int
|
||||
@@ -98,7 +122,7 @@ trait ClearsTemplateCaches
|
||||
$newVersion = time();
|
||||
|
||||
try {
|
||||
self::resolveExtensionCache()->put(self::$extensionCacheVersionKey, $newVersion);
|
||||
self::resolveExtensionCache()->put(self::$extensionCacheVersionKey, $newVersion, ExtensionStaticCacheService::PERSISTENT_TTL_SECONDS);
|
||||
|
||||
Log::info('확장 기능 캐시 버전 재생성 (키 부재/무효)', [
|
||||
'new_version' => $newVersion,
|
||||
@@ -182,6 +206,21 @@ trait ClearsTemplateCaches
|
||||
return new CoreCacheDriver(self::extensionCacheStore());
|
||||
}
|
||||
|
||||
/**
|
||||
* custom 자산 변경 서명(`ext.custom_signature`)용 캐시 드라이버를 반환합니다.
|
||||
*
|
||||
* 버전 키와 **같은 고정 스토어·같은 코어 네임스페이스**를 쓴다. 서명이 버전 키와 다른
|
||||
* 스토어에 저장되면(`app(CacheInterface::class)` 재바인딩 등) "첫 관측은 기록만" 규칙이
|
||||
* 스토어마다 따로 성립해 실제 변경 1회를 조용히 삼킨다(#651 F8). 서명을 쓰는 뷰 컴포저와
|
||||
* 지우는 관리 API 가 같은 통로를 써야 하므로 트레이트가 공급한다.
|
||||
*
|
||||
* @return CacheInterface 코어 네임스페이스 캐시 드라이버
|
||||
*/
|
||||
protected static function customSignatureCache(): CacheInterface
|
||||
{
|
||||
return new CoreCacheDriver(self::extensionCacheStore());
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 좌표 키(`ext.cache_version`)의 고정 캐시 스토어 이름을 반환합니다.
|
||||
*
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\LayoutRepositoryInterface;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
@@ -120,7 +121,10 @@ trait InvalidatesLayoutCache
|
||||
// 받는다. 레이아웃 저장 경로(LayoutService::clearPublicServingCache)는 이미 두 키를
|
||||
// 지우므로 정합을 맞춘다.
|
||||
if ($templateIdentifier) {
|
||||
$cacheVersion = (int) $cache->get('ext.cache_version', 0);
|
||||
// 트레이트 게터 경유 — 이 트레이트만 조합한 클래스가 있을 수 있어 `self::` 가 아니라
|
||||
// `ClearsTemplateCaches` 를 조합한 서비스 클래스를 통해 부른다(트레이트 정적 직접 호출은
|
||||
// PHP 8.1+ E_DEPRECATED). 원시 키 읽기는 `cache:clear` 직후 0 을 돌려주어 실제 키를 못 지운다.
|
||||
$cacheVersion = ExtensionStaticCacheService::getExtensionCacheVersion();
|
||||
$cache->forget("layout.{$templateIdentifier}.{$layout->name}.v{$cacheVersion}");
|
||||
$cache->forget("layout.{$templateIdentifier}.{$layout->name}.v{$cacheVersion}.meta");
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use App\Extension\Helpers\EditorSpecAssembler;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use App\Services\PermissionService;
|
||||
use App\Services\TemplateService;
|
||||
use App\Support\AssetUrl;
|
||||
@@ -88,8 +88,10 @@ class AdminTemplateAssetController extends AdminBaseController
|
||||
);
|
||||
}
|
||||
|
||||
$extensionCacheVersion = (int) app(CacheInterface::class)->get('ext.cache_version', 0);
|
||||
$version = $extensionCacheVersion > 0 ? $extensionCacheVersion : null;
|
||||
// 확장 캐시 버전은 트레이트 게터로만 읽는다 — 원시 키 읽기는 `cache:clear` 직후 0 을
|
||||
// 돌려주어 버전 없는 URL 을 만들고, 컨테이너 바인딩은 확장 네임스페이스로 누수될 수 있다.
|
||||
// 게터는 키 부재 시 재생성하므로 항상 유효 버전이다 (`AssetUrl::staticExtBase` 와 동형).
|
||||
$version = ExtensionStaticCacheService::getExtensionCacheVersion();
|
||||
|
||||
return $this->success(
|
||||
__('templates.messages.editor_assets_retrieved'),
|
||||
@@ -228,7 +230,7 @@ class AdminTemplateAssetController extends AdminBaseController
|
||||
// 바인딩은 확장 컨텍스트로 누수될 수 있어(메모리 feedback_core_cache_no_container_binding)
|
||||
// 코어 캐시 store 를 빗나갈 수 있다.
|
||||
$cache = new CoreCacheDriver;
|
||||
$cacheVersion = (int) $cache->get('ext.cache_version', 0);
|
||||
$cacheVersion = ExtensionStaticCacheService::getExtensionCacheVersion();
|
||||
// 캐시 키 — 템플릿 + 확장 캐시 버전 + 파일 mtime(빌드 변경 즉시 무효화).
|
||||
$mtime = (int) @filemtime($cssPath);
|
||||
$cacheKey = "template.editor_css.{$identifier}.v{$cacheVersion}.m{$mtime}";
|
||||
|
||||
@@ -13,6 +13,7 @@ use App\Http\Requests\Settings\UpdateSettingRequest;
|
||||
use App\Http\Resources\SettingsResource;
|
||||
use App\Services\DriverConnectionTester;
|
||||
use App\Services\DriverRegistryService;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use App\Services\OutboundProxyTester;
|
||||
use App\Services\SettingsService;
|
||||
use App\Support\EnvPriority;
|
||||
@@ -32,7 +33,8 @@ class SettingsController extends AdminBaseController
|
||||
private SettingsService $settingsService,
|
||||
private DriverConnectionTester $driverConnectionTester,
|
||||
private DriverRegistryService $driverRegistryService,
|
||||
private OutboundProxyTester $outboundProxyTester
|
||||
private OutboundProxyTester $outboundProxyTester,
|
||||
private ExtensionStaticCacheService $staticCacheService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
@@ -190,6 +192,39 @@ class SettingsController extends AdminBaseController
|
||||
return $this->success('common.success', TrustedProxyDiagnostic::forRequest(request()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 초기 화면 정적 파일(부트스트랩 리소스 정적 게시) 상태를 조회합니다 (#651).
|
||||
*
|
||||
* CLI `ext-static:status` 와 **같은 판정**(`ExtensionStaticCacheService::statusReport`)을 돌려준다.
|
||||
* 읽기 전용이며 입력이 없어 FormRequest 를 두지 않는다 (`trustedProxy` 와 동형).
|
||||
*
|
||||
* @return JsonResponse 상태 보고서 JSON 응답
|
||||
*/
|
||||
public function staticCacheStatus(): JsonResponse
|
||||
{
|
||||
return $this->success('settings.static_cache_status_loaded', $this->staticCacheService->statusReport());
|
||||
}
|
||||
|
||||
/**
|
||||
* 초기 화면 정적 파일을 지금 다시 만듭니다 (관리자 수동 복구, #651).
|
||||
*
|
||||
* 캐시 버전을 올리고 현재 버전을 강제 재게시한다. 게시 실패·게시가 쓰이지 않는 환경은
|
||||
* 요청 처리 실패가 아니라 **진단 결과**라 HTTP 200 으로 돌려주고 성공 여부는 페이로드
|
||||
* (`republished`)가 말한다 — 연결 테스트·드라이버 테스트와 같은 규약. 사이트는 어느 경우에도
|
||||
* API 폴백으로 정상이다.
|
||||
*
|
||||
* @return JsonResponse 재게시 결과 + 상태 보고서 JSON 응답
|
||||
*/
|
||||
public function republishStaticCache(): JsonResponse
|
||||
{
|
||||
$result = $this->staticCacheService->republish();
|
||||
|
||||
return $this->success(
|
||||
($result['republished'] ?? false) ? 'settings.static_cache_republished' : 'settings.static_cache_republish_failed',
|
||||
$result
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 캐시를 정리합니다.
|
||||
*
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
namespace App\Http\View\Composers\Traits;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -53,7 +53,7 @@ trait CollectsCustomAssets
|
||||
// 한 번을 더 해야 반영된다 — 원인을 알 수 없는 한 박자 지연으로만 나타난다.
|
||||
// 새 버전으로 다시 해석한다. 게시본은 아직 없으므로 URL 은 API 형태로 떨어지고,
|
||||
// 그 응답은 디스크의 최신 내용을 그대로 준다. 다음 요청부터 정적 경로가 된다.
|
||||
if ($this->syncCustomAssetCacheVersion($assets, $templateIdentifier)) {
|
||||
if ($this->syncCustomAssetCacheVersion($templateIdentifier)) {
|
||||
CustomAssets::flushCache();
|
||||
$assets = $this->resolveCustomAssets($templateIdentifier);
|
||||
}
|
||||
@@ -114,30 +114,29 @@ trait CollectsCustomAssets
|
||||
* 쓰기 뒤 이 키 하나를 `forget` 하는 것에 의존하므로(같은 키를 보는 두 소비자),
|
||||
* 키를 쪼개면 그 소비자가 일부만 지우게 되어 같은 결함군이 재생산된다.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $assets 수집된 서술자 목록
|
||||
* 서명 재료는 **게시와 같은 열거자**(`CustomAssets::publishableFiles`) — 활성 모듈·플러그인과
|
||||
* 이 렌더의 템플릿의 `custom/**` 전체(하위 디렉토리·글꼴·이미지 포함)의 경로·수정 시각·
|
||||
* 크기다. 종전에는 로드 목록(최상위 css/js)의 mtime 만 봤는데, 게시는 재귀 복사라
|
||||
* 글꼴만 교체한 변경이 영영 감지되지 않았다(#651 F7). 크기를 함께 넣는 이유는 mtime 해상도
|
||||
* (1초·일부 파일시스템 2초) 안의 재작성과 mtime 보존 복사(rsync -t)를 잡기 위해서다.
|
||||
*
|
||||
* 스코프 키에는 **호스트명**을 붙인다. 다중 웹서버가 캐시를 공유하면 같은 파일이라도 서버마다
|
||||
* 배포 시각(mtime)이 달라, 하나의 자리를 서버들이 번갈아 덮어쓰며 요청마다 "변경" 으로
|
||||
* 읽혀 전체 재게시가 왕복한다(#651 F9). 서버별로 기억하면 각 서버는 자기 파일만 대조한다.
|
||||
*
|
||||
* @param string|null $scope 렌더 스코프 (활성 템플릿 식별자)
|
||||
* @return bool 확장 캐시 버전을 올렸으면 true
|
||||
*/
|
||||
private function syncCustomAssetCacheVersion(array $assets, ?string $scope = null): bool
|
||||
private function syncCustomAssetCacheVersion(?string $scope = null): bool
|
||||
{
|
||||
try {
|
||||
$parts = [];
|
||||
$signature = $this->customAssetSignature($scope);
|
||||
|
||||
foreach ($assets as $asset) {
|
||||
// 파일 출처만 본다 — 외부 URL·훅이 더한 항목은 파일 서명이 없다
|
||||
if (($asset['source'] ?? null) !== 'file') {
|
||||
continue;
|
||||
}
|
||||
$scopeKey = ($scope ?? '').'@'.(gethostname() ?: 'host');
|
||||
|
||||
$parts[] = ($asset['id'] ?? '').'@'.($asset['version'] ?? '');
|
||||
}
|
||||
|
||||
sort($parts, SORT_STRING);
|
||||
$signature = $parts === [] ? 'empty' : md5(implode('|', $parts));
|
||||
|
||||
$scopeKey = $scope ?? '';
|
||||
|
||||
$cache = app(CacheInterface::class);
|
||||
// 버전 키와 같은 고정 스토어·코어 네임스페이스 — 컨테이너 바인딩을 거치면 재바인딩
|
||||
// 컨텍스트에서 다른 네임스페이스에 저장되어 첫 관측 규칙이 실제 변경을 삼킨다.
|
||||
$cache = self::customSignatureCache();
|
||||
|
||||
// 구 배포본이 남긴 스칼라 값은 맵이 아니다 — 어느 스코프의 것인지 알 수 없으므로
|
||||
// 서명으로 쓰지 않고 미관측으로 취급한다(첫 관측은 기록만 하니 헛된 bump 가 없다).
|
||||
@@ -151,7 +150,9 @@ trait CollectsCustomAssets
|
||||
}
|
||||
|
||||
$storedMap[$scopeKey] = $signature;
|
||||
$cache->put(CustomAssets::SIGNATURE_CACHE_KEY, $storedMap);
|
||||
// 버전 키와 같은 영구 TTL — 기본 TTL 로 만료되면 그 경계의 첫 관측이 "기록만" 이라
|
||||
// 실제 변경 1회를 놓친다.
|
||||
$cache->put(CustomAssets::SIGNATURE_CACHE_KEY, $storedMap, ExtensionStaticCacheService::PERSISTENT_TTL_SECONDS);
|
||||
|
||||
if ($stored === null) {
|
||||
return false;
|
||||
@@ -174,6 +175,44 @@ trait CollectsCustomAssets
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 렌더 스코프의 custom 파일 서명을 만듭니다.
|
||||
*
|
||||
* 재료 = 활성 모듈 → 활성 플러그인 → 렌더 템플릿 순으로 `publishableFiles()` 전체의
|
||||
* `{type}/{id}/{relative}@{mtime}@{size}`. 정렬 뒤 md5. 파일이 하나도 없으면 `empty`.
|
||||
*
|
||||
* @param string|null $scope 렌더 스코프 (활성 템플릿 식별자)
|
||||
* @return string 서명
|
||||
*/
|
||||
private function customAssetSignature(?string $scope): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
$targets = [];
|
||||
|
||||
foreach ($this->activeExtensionIdentifiers('modules') as $identifier) {
|
||||
$targets[] = ['modules', $identifier];
|
||||
}
|
||||
|
||||
foreach ($this->activeExtensionIdentifiers('plugins') as $identifier) {
|
||||
$targets[] = ['plugins', $identifier];
|
||||
}
|
||||
|
||||
if (! empty($scope)) {
|
||||
$targets[] = ['templates', $scope];
|
||||
}
|
||||
|
||||
foreach ($targets as [$type, $identifier]) {
|
||||
foreach (CustomAssets::publishableFiles($type, $identifier) as $file) {
|
||||
$parts[] = $type.'/'.$identifier.'/'.$file['relative'].'@'.$file['mtime'].'@'.$file['size'];
|
||||
}
|
||||
}
|
||||
|
||||
sort($parts, SORT_STRING);
|
||||
|
||||
return $parts === [] ? 'empty' : md5(implode('|', $parts));
|
||||
}
|
||||
|
||||
/**
|
||||
* 이번 요청이 사용자 추가 에셋을 끄도록 요구했는지 판정합니다.
|
||||
*
|
||||
|
||||
@@ -91,6 +91,13 @@ class StaticPublishFailureAlertListener implements HookListenerInterface
|
||||
? TimezoneHelper::toUserCarbon(Carbon::parse($marker['at']))?->diffForHumans()
|
||||
: null,
|
||||
'read' => false,
|
||||
// 알림에서 바로 복구한다 (#651 D11) — 운영자가 결함을 처음 만나는 곳이 알림이므로 그 자리에서
|
||||
// 끝나야 한다. 대시보드 렌더러는 `recover_endpoint` 가 있는 알림에 버튼을 그리고 POST 한다
|
||||
// (기존 재호환 알림과 같은 배선). 성공 문구는 재호환 알림의 기본 문구가 이 알림에는 맞지
|
||||
// 않으므로 리스너가 함께 싣는다.
|
||||
'recover_endpoint' => '/api/admin/settings/static-cache/republish',
|
||||
'recover_label' => __('extensions.alerts.static_publish_recover_label'),
|
||||
'recover_success_message' => __('extensions.alerts.static_publish_recovered'),
|
||||
];
|
||||
|
||||
return $alerts;
|
||||
|
||||
@@ -2215,6 +2215,12 @@ class CoreUpdateService
|
||||
storage_path('framework/cache'),
|
||||
base_path('bootstrap/cache'),
|
||||
storage_path('app/ext-bundles'),
|
||||
// 확장 업데이트의 다운로드·추출 임시 폴더. 부모 `storage/app/temp` 가 sudo 업데이트에서 root 로
|
||||
// 최초 생성되면 이후 관리자 화면의 확장 업데이트가 임시 폴더를 만들지 못한다 (#651 F14).
|
||||
storage_path('app/temp'),
|
||||
// `restore_ownership` 은 `storage/logs` 를 포함하지만 그 복원은 흐름 **중간**(Step 11)이라,
|
||||
// 그 뒤에 만들어지는 daily 롤오버·신규 로그 파일은 root 로 남는다 (#651 F15).
|
||||
storage_path('logs'),
|
||||
];
|
||||
|
||||
foreach ($targets as $dir) {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Exceptions\CustomAssetOperationException;
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
@@ -279,7 +279,9 @@ class CustomAssetService
|
||||
CustomAssets::flushCache();
|
||||
|
||||
try {
|
||||
app(CacheInterface::class)->forget(CustomAssets::SIGNATURE_CACHE_KEY);
|
||||
// 서명을 쓰는 뷰 컴포저와 **같은 통로**(고정 스토어·코어 네임스페이스)로 지운다 —
|
||||
// 다른 통로로 지우면 그쪽 서명이 남아 다음 렌더가 같은 변경을 한 번 더 bump 한다.
|
||||
self::customSignatureCache()->forget(CustomAssets::SIGNATURE_CACHE_KEY);
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('사용자 추가 에셋 서명 캐시 삭제 실패', ['error' => $e->getMessage()]);
|
||||
}
|
||||
@@ -385,8 +387,24 @@ class CustomAssetService
|
||||
return;
|
||||
}
|
||||
|
||||
if (! @mkdir($directory, 0755, true) && ! is_dir($directory)) {
|
||||
throw new CustomAssetOperationException('custom_assets.errors.directory_failed', ['path' => $directory]);
|
||||
// 확보는 코어 공통 프리미티브가 맡는다 — 소유권 상속·그룹 쓰기까지 정합화하고, 실패는 예외가 아니라
|
||||
// 사유로 올라온다. `custom/` 은 지연 생성이라 `deploy:deploy 0755` 로 배포된 확장 디렉토리에서
|
||||
// 첫 저장이 여기서 실패하는데, 경로만 적으면 운영자가 무엇을 고쳐야 하는지 알 수 없다(#651 D6).
|
||||
// 사유·소유자·권한·실행 계정·조치 예시를 함께 싣는다 (정적 게시 프리플라이트와 같은 식).
|
||||
if (FilePermissionHelper::ensureWritableDirectory($directory, 0775, $failure)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$failedPath = (string) ($failure['path'] ?? $directory);
|
||||
$reason = (string) ($failure['reason'] ?? 'create_failed');
|
||||
|
||||
throw new CustomAssetOperationException('custom_assets.errors.directory_failed', [
|
||||
'path' => $directory,
|
||||
'reason' => __('custom_assets.errors.reason.'.$reason),
|
||||
'owner' => (string) (@fileowner($failedPath) ?: 'unknown'),
|
||||
'perms' => file_exists($failedPath) ? substr(sprintf('%o', @fileperms($failedPath)), -4) : 'absent',
|
||||
'process_user' => ExtensionStaticCacheService::currentProcessUser(),
|
||||
'hint' => __('custom_assets.errors.directory_failed_hint', ['path' => $failedPath]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -531,6 +531,166 @@ class ExtensionStaticCacheService
|
||||
return (bool) config('core.static_cache.enabled', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 지금 이 설치에서 게시가 의미 있는지 판정합니다 — kill-switch 켜짐 + 프로덕션.
|
||||
*
|
||||
* `publishCurrent()` 자체에는 환경 게이트가 없다(명시적 `ext-static:publish` 가 어느 환경에서든
|
||||
* 돌 수 있어야 하므로). 환경 판정은 자가 치유(`AssetUrl::staticExtBase`)와 terminating 예약
|
||||
* (`schedulePublishOnTerminate`)에만 있었는데, 관리자 화면의 수동 복구는 두 판정을 **한 값**으로
|
||||
* 보여 줘야 하므로 여기서 묶는다. 비프로덕션은 blade 가 정적 URL 을 방출하지 않아 게시해도
|
||||
* 아무도 참조하지 않는다.
|
||||
*
|
||||
* @return bool 게시가 실제로 쓰이는 환경이면 true
|
||||
*/
|
||||
public function isPublishable(): bool
|
||||
{
|
||||
return $this->isEnabled() && app()->environment('production');
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 상태 보고서 — CLI(`ext-static:status`)·관리자 API·화면이 **같은 판정**을 소비한다.
|
||||
*
|
||||
* 판정을 소비처마다 다시 쓰면 한 곳만 어긋나도 서로 다른 답을 내놓는다(`TrustedProxyDiagnostic`
|
||||
* 이 CLI·대시보드·API 에 같은 판정을 공급하는 것과 같은 패턴). 문구·힌트는 소비처가 정한다.
|
||||
*
|
||||
* @return array{
|
||||
* enabled: bool,
|
||||
* publishable: bool,
|
||||
* environment: string,
|
||||
* version: int,
|
||||
* published: bool,
|
||||
* files: int,
|
||||
* published_at: string|null,
|
||||
* tree_writable: bool,
|
||||
* process_user: string,
|
||||
* failure: array{version:int, at:string, reason:string, count:int, message:string}|null,
|
||||
* retained_versions: array<int, int>
|
||||
* } 상태 보고서
|
||||
*/
|
||||
public function statusReport(): array
|
||||
{
|
||||
$version = self::getExtensionCacheVersion();
|
||||
$base = $this->baseDir();
|
||||
|
||||
unset($this->publishedMemo[$version]);
|
||||
$published = $this->isPublished($version);
|
||||
|
||||
$files = 0;
|
||||
$publishedAt = null;
|
||||
|
||||
if ($published) {
|
||||
$manifest = json_decode((string) @file_get_contents($this->versionDir($version).DIRECTORY_SEPARATOR.self::MANIFEST_FILE), true);
|
||||
|
||||
if (is_array($manifest)) {
|
||||
$files = count($manifest['files'] ?? []);
|
||||
$publishedAt = is_string($manifest['published_at'] ?? null) ? $manifest['published_at'] : null;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'enabled' => $this->isEnabled(),
|
||||
'publishable' => $this->isPublishable(),
|
||||
'environment' => (string) app()->environment(),
|
||||
'version' => $version,
|
||||
'published' => $published,
|
||||
'files' => $files,
|
||||
'published_at' => $publishedAt,
|
||||
'tree_writable' => $this->isPublishTreeWritable($base),
|
||||
'process_user' => self::currentProcessUser(),
|
||||
'failure' => self::failureMarker(),
|
||||
'retained_versions' => $this->publishedVersions($base),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 수동 복구 — 캐시 버전을 올리고 현재 버전을 **강제** 재게시합니다.
|
||||
*
|
||||
* 자동 경로(수명주기 bump → terminating 게시 · blade 자가 치유)가 놓친 갱신을 운영자가 즉시
|
||||
* 되돌리는 통로다. 캐시 버전이 만료로 재생성되지 않으므로(`PERSISTENT_TTL_SECONDS`) 재게시
|
||||
* 누락은 무기한 stale 이 되는데, 이 복구가 그 안전망이다.
|
||||
*
|
||||
* - 게시가 쓰이지 않는 환경(kill-switch 꺼짐 / 비프로덕션)이면 bump 하지 않고 사유만 돌려준다.
|
||||
* - `force: true` 가 필수다 — 직전 게시와 같은 초면 버전이 같아 manifest 존재로 skip 되어
|
||||
* 아무것도 다시 만들지 않는다.
|
||||
* - 게시 실패는 예외가 아니라 결과다(`republished=false` + 실패 마커). 사이트는 API 폴백으로 정상.
|
||||
* - 715파일·40MB 복사 + 번들 재병합이 웹 요청 안에서 돈다 — 게시 락 TTL(300초)만큼 실행 시간을
|
||||
* 확보하고, 클라이언트가 끊어도 게시는 끝낸다(중간에 죽으면 `.tmp` 만 남고 다음 GC 가 치운다).
|
||||
*
|
||||
* @return array<string, mixed> `republished`·`version_changed`·`previous_version` + `statusReport()`
|
||||
*/
|
||||
public function republish(): array
|
||||
{
|
||||
$previous = self::getExtensionCacheVersion();
|
||||
|
||||
if (! $this->isPublishable()) {
|
||||
return [
|
||||
'republished' => false,
|
||||
'version_changed' => false,
|
||||
'previous_version' => $previous,
|
||||
'reason' => $this->isEnabled() ? 'not_production' : 'disabled',
|
||||
] + $this->statusReport();
|
||||
}
|
||||
|
||||
@set_time_limit(300);
|
||||
@ignore_user_abort(true);
|
||||
|
||||
$this->incrementExtensionCacheVersion();
|
||||
|
||||
$republished = $this->publishCurrent(force: true);
|
||||
$current = self::getExtensionCacheVersion();
|
||||
|
||||
return [
|
||||
'republished' => $republished,
|
||||
'version_changed' => $current !== $previous,
|
||||
'previous_version' => $previous,
|
||||
'reason' => $republished ? null : (self::failureMarker()['reason'] ?? 'publish_failed'),
|
||||
] + $this->statusReport();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 트리에 쓸 수 있는지(없으면 만들 수 있는지) 판정합니다.
|
||||
*
|
||||
* @param string $base 게시 루트 절대 경로
|
||||
* @return bool 쓰기 가능 여부
|
||||
*/
|
||||
private function isPublishTreeWritable(string $base): bool
|
||||
{
|
||||
if (File::isDirectory($base)) {
|
||||
return is_writable($base);
|
||||
}
|
||||
|
||||
$parent = dirname($base);
|
||||
|
||||
return File::isDirectory($parent) && is_writable($parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 루트에 남아 있는 버전 디렉토리 목록을 반환합니다 (오름차순).
|
||||
*
|
||||
* @param string $base 게시 루트 절대 경로
|
||||
* @return array<int, int> 버전 목록
|
||||
*/
|
||||
private function publishedVersions(string $base): array
|
||||
{
|
||||
if (! File::isDirectory($base)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$versions = [];
|
||||
|
||||
foreach (File::directories($base) as $dir) {
|
||||
$name = basename($dir);
|
||||
|
||||
if (ctype_digit($name)) {
|
||||
$versions[] = (int) $name;
|
||||
}
|
||||
}
|
||||
|
||||
sort($versions);
|
||||
|
||||
return $versions;
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 버전의 게시를 실제 수행합니다 (tmp 쓰기 → rename → manifest → GC).
|
||||
*
|
||||
@@ -556,6 +716,10 @@ class ExtensionStaticCacheService
|
||||
File::deleteDirectory($tmp);
|
||||
$this->makeDirectory($tmp);
|
||||
|
||||
// custom 열거 메모를 비우고 디스크를 다시 읽는다 — 게시는 요청 뒤(terminating)나 장수 프로세스에서
|
||||
// 돌 수 있어, 앉아 있는 메모가 이미 지워진 파일을 가리키면 복사가 실패해 게시 전체가 중단된다.
|
||||
CustomAssets::flushCache();
|
||||
|
||||
$files = [];
|
||||
|
||||
$this->writeHtaccess($tmp, $files);
|
||||
@@ -909,17 +1073,48 @@ class ExtensionStaticCacheService
|
||||
// URL 은 **public 아래 실제 파일일 때만** 200 이 되므로, 문서가 안내하는
|
||||
// "폰트·이미지를 custom/ 에 두고 상대 경로로 참조" 를 성립시키는 방법은 게시뿐이다.
|
||||
//
|
||||
// 갱신 축은 확장 자산과 동일하다 — 운영자가 파일을 고치면 `CustomAssets` 가
|
||||
// 갱신 축은 확장 자산과 동일하다 — 운영자가 파일을 고치면 `CollectsCustomAssets` 가
|
||||
// 그것을 감지해 `ext.cache_version` 을 올리고, 그 단일 지점이 재게시까지 예약한다.
|
||||
$this->publishDistAssets(
|
||||
base_path("templates/{$identifier}/".CustomAssets::DIRECTORY),
|
||||
// 게시 집합은 감지와 **같은 열거자**(`CustomAssets::publishableFiles`)가 정한다.
|
||||
$this->publishCustomAssets(
|
||||
'templates',
|
||||
$identifier,
|
||||
$templateDir.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.CustomAssets::DIRECTORY,
|
||||
$files,
|
||||
$tmp,
|
||||
excludeCustom: false
|
||||
$tmp
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 하나의 운영자 소유 디렉토리(`custom/`)를 게시합니다.
|
||||
*
|
||||
* 파일 집합은 `CustomAssets::publishableFiles()` 가 정한다 — 변경 감지(`CollectsCustomAssets`)
|
||||
* 와 같은 열거자다. 게시와 감지가 서로 다른 코드로 범위를 정하면 어긋나고, 그 어긋남은
|
||||
* "글꼴을 바꿨는데 반영되지 않는다" 로만 나타난다(#651 F7).
|
||||
*
|
||||
* @param string $extensionType `templates` | `modules` | `plugins`
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $targetDir 게시 대상 절대 경로 (`…/assets/custom`)
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
* @param string $tmp tmp 루트 (상대 경로 계산용)
|
||||
*/
|
||||
private function publishCustomAssets(
|
||||
string $extensionType,
|
||||
string $identifier,
|
||||
string $targetDir,
|
||||
array &$files,
|
||||
string $tmp
|
||||
): void {
|
||||
foreach (CustomAssets::publishableFiles($extensionType, $identifier) as $file) {
|
||||
$this->copyFile(
|
||||
$file['absolute'],
|
||||
$targetDir.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $file['relative']),
|
||||
$files,
|
||||
$tmp
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 dist 디렉토리를 재귀 복사합니다 (허용 확장자만, 소스맵 제외).
|
||||
*
|
||||
@@ -927,7 +1122,8 @@ class ExtensionStaticCacheService
|
||||
* @param string $targetDir 게시 대상 절대 경로
|
||||
* @param array<string> $files 기록된 상대 경로 누적 (참조)
|
||||
* @param string $tmp tmp 루트 (상대 경로 계산용)
|
||||
* @param bool $excludeCustom 원본 안의 `custom/` 하위를 건너뛸지 (dist 원본에서만 참)
|
||||
* @param bool $excludeCustom 원본 안의 `custom/` 하위를 건너뛸지 (dist 원본은 참 — `custom/` 은
|
||||
* `publishCustomAssets()` 가 공유 열거자로 따로 게시한다)
|
||||
*/
|
||||
private function publishDistAssets(
|
||||
string $sourceDir,
|
||||
@@ -1064,13 +1260,13 @@ class ExtensionStaticCacheService
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->publishDistAssets(
|
||||
base_path("{$root}/{$identifier}/".CustomAssets::DIRECTORY),
|
||||
$this->publishCustomAssets(
|
||||
$root,
|
||||
$identifier,
|
||||
$tmp.DIRECTORY_SEPARATOR.$root.DIRECTORY_SEPARATOR.$identifier
|
||||
.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.CustomAssets::DIRECTORY,
|
||||
$files,
|
||||
$tmp,
|
||||
excludeCustom: false
|
||||
$tmp
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1135,7 +1135,9 @@ class LayoutService
|
||||
}
|
||||
|
||||
$identifier = $template->identifier;
|
||||
$cacheVersion = (int) $this->cache->get('ext.cache_version', 0);
|
||||
// 원시 키 읽기는 `cache:clear` 직후 0 을 돌려주어 `.v0` 키를 지우고 실제 키는 남긴다 —
|
||||
// 트레이트 게터는 부재 시 재생성하므로 실제 서빙 키와 같은 버전을 본다.
|
||||
$cacheVersion = self::getExtensionCacheVersion();
|
||||
|
||||
// PublicLayoutController::serve() 가 일반 응답과 편집 모드(`with_source_meta=1`) 응답을
|
||||
// 별도 캐시 키로 저장한다 (`.meta` 접미사). 본 PR Phase 3 S5a-1 에서 편집 모드 응답 캐시
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\AttachmentRepositoryInterface;
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Http\Resources\AttachmentResource;
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use App\Support\ConfigCacheHelper;
|
||||
@@ -28,6 +29,10 @@ use Illuminate\Validation\ValidationException;
|
||||
*/
|
||||
class SettingsService
|
||||
{
|
||||
// 자산 URL 방식 변경 시 확장 캐시 버전 bump 용. 주입된 `$this->cache` 로 직접 put 하지
|
||||
// 않는다 — 트레이트가 고정 `CoreCacheDriver` + 메모이즈 스토어를 쓰는 이유가 그 안에 있다.
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
public function __construct(
|
||||
private ConfigRepositoryInterface $configRepository,
|
||||
private AttachmentRepositoryInterface $attachmentRepository,
|
||||
@@ -706,6 +711,7 @@ class SettingsService
|
||||
// CLI(`g7:asset-url-mode`)와 동일한 처리 (계획서 §알려진 한계).
|
||||
if ($assetUrlModeChanged) {
|
||||
$this->clearSeoCacheForAssetUrlMode();
|
||||
$this->bumpExtensionCacheForAssetUrlMode();
|
||||
}
|
||||
|
||||
// drivers 탭은 queue/broadcasting/cache 등 long-running worker에 영향
|
||||
@@ -1090,6 +1096,7 @@ class SettingsService
|
||||
|
||||
if ($assetUrlModeChanged) {
|
||||
$this->clearSeoCacheForAssetUrlMode();
|
||||
$this->bumpExtensionCacheForAssetUrlMode();
|
||||
}
|
||||
|
||||
if (str_starts_with($key, 'drivers.') || $key === 'drivers') {
|
||||
@@ -1126,17 +1133,42 @@ class SettingsService
|
||||
*/
|
||||
public function restoreSettings(string $backupPath): bool
|
||||
{
|
||||
// 자산 URL 방식은 복원 **전**에 읽어 둔다 — 복원 뒤에는 이전 값을 알 수 없어
|
||||
// 변경 여부를 판별할 수 없다 (saveSettings/setSetting 과 같은 사유).
|
||||
$previousAssetUrlMode = $this->configRepository->get('general.asset_url_mode');
|
||||
|
||||
$result = $this->configRepository->restore($backupPath);
|
||||
|
||||
if ($result) {
|
||||
// 복원도 설정 전체를 갈아엎는 쓰기다 — 캐시만 비우고 미러를 두면
|
||||
// 같은 프로세스가 복원 전 값을 계속 읽는다 (저장 경로와 동일 결함, 공개이슈 #109).
|
||||
$this->invalidateSettingsCache();
|
||||
|
||||
// 복원으로 자산 URL 방식이 바뀌었으면 두 저장 경로와 동일하게 처리한다 —
|
||||
// SEO 프리렌더와 병합 번들 CSS 양쪽에 구워진 URL 형태가 어긋난다.
|
||||
if ($this->configRepository->get('general.asset_url_mode') !== $previousAssetUrlMode) {
|
||||
$this->clearSeoCacheForAssetUrlMode();
|
||||
$this->bumpExtensionCacheForAssetUrlMode();
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 자산 URL 방식이 바뀌었을 때 확장 캐시 버전을 올립니다 (정적 게시본 재생성).
|
||||
*
|
||||
* 병합 번들 CSS 는 내부 `url()` 참조가 그 시점의 자산 URL **형태**(확장자 / `?file=`)로
|
||||
* 본문에 구워진다(`ExtensionBundleService` 의 `AssetCssUrlRewriter`). 디스크 번들과 정적
|
||||
* 게시본은 캐시 버전으로 키드되어 있어, 버전이 오르지 않으면 모드를 바꿔도 옛 형태의
|
||||
* URL 이 남고 그 참조(글꼴·이미지)가 서버에서 404 가 된다(#651 F5). bump 단일 지점이
|
||||
* 번들 재병합과 정적 재게시를 함께 예약한다.
|
||||
*/
|
||||
private function bumpExtensionCacheForAssetUrlMode(): void
|
||||
{
|
||||
$this->incrementExtensionCacheVersion();
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 메일을 발송합니다.
|
||||
*
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -52,7 +53,7 @@ class ConfigCacheHelper
|
||||
}
|
||||
|
||||
try {
|
||||
Artisan::call('config:cache');
|
||||
self::withPreservedContainer(static fn () => Artisan::call('config:cache'));
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('config 캐시 재생성 실패 (config:clear 로 stale 은 제거됨 — 다음 요청은 비캐시 부팅)', [
|
||||
'error' => $e->getMessage(),
|
||||
@@ -60,6 +61,30 @@ class ConfigCacheHelper
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 콜백 실행 뒤 전역 컨테이너 인스턴스를 원래 앱으로 되돌립니다.
|
||||
*
|
||||
* `config:cache` 는 신선한 설정을 얻기 위해 **새 Application 을 부팅**하는데, `Application` 생성자가
|
||||
* `Container::setInstance()` 를 호출하므로 그 순간부터 `app()` 헬퍼가 실행 중인 앱이 아니라 그
|
||||
* 일회용 앱을 가리킨다(파사드는 별도 참조라 그대로다). 같은 프로세스에서 그 뒤에 등록되는
|
||||
* `app()->terminating()` 콜백은 종료되지 않는 앱에 걸려 **영원히 실행되지 않는다** — 설정 저장
|
||||
* 뒤의 확장 캐시 버전 bump 가 예약한 정적 재게시가 그렇게 조용히 사라졌다(#651 F5 실측: 버전은
|
||||
* 올랐는데 게시는 다음 렌더의 자가 치유까지 미뤄짐). 예외도 로그도 없고, 자가 치유가 한 렌더
|
||||
* 뒤에 덮어 주므로 "한 박자 늦게 반영" 으로만 나타난다.
|
||||
*
|
||||
* @param callable $callback 전역 인스턴스를 바꿔 놓을 수 있는 작업
|
||||
*/
|
||||
public static function withPreservedContainer(callable $callback): void
|
||||
{
|
||||
$app = Container::getInstance();
|
||||
|
||||
try {
|
||||
$callback();
|
||||
} finally {
|
||||
Container::setInstance($app);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* config 캐시만 제거합니다 (재생성 없음).
|
||||
*
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Support;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\AllowedTemplateFileType;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -53,6 +54,14 @@ class CustomAssets
|
||||
/** 요청 스코프 메모이즈 (같은 요청에서 같은 확장을 여러 번 묻는 경로 대비) */
|
||||
private static array $cache = [];
|
||||
|
||||
/**
|
||||
* 게시 대상 파일 열거 결과의 요청 스코프 메모이즈 (키 형식은 `$cache` 와 같다 — `{type}|{id}`).
|
||||
*
|
||||
* 서술자 메모(`$cache`)와 자리를 나눈다 — 서술자는 **로드 목록**(최상위 css/js), 이것은
|
||||
* **게시·변경 감지 집합**(하위 디렉토리 포함 전 허용 확장자)이라 의미가 다르다.
|
||||
*/
|
||||
private static array $fileCache = [];
|
||||
|
||||
/**
|
||||
* 확장 하나의 사용자 추가 에셋 목록을 돌려줍니다.
|
||||
*
|
||||
@@ -87,6 +96,110 @@ class CustomAssets
|
||||
public static function flushCache(): void
|
||||
{
|
||||
self::$cache = [];
|
||||
self::$fileCache = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 하나의 `custom/` 아래 **게시 대상 파일 전체**를 열거합니다.
|
||||
*
|
||||
* 정적 게시(`ExtensionStaticCacheService`)와 변경 감지(`CollectsCustomAssets`)가 **같은
|
||||
* 열거자**를 쓴다. 종전에는 게시가 `custom/**` 를 재귀로 복사하고 감지는 최상위 css/js 의
|
||||
* mtime 만 서명해 범위가 어긋났다 — 문서가 권장하는 `url('./fonts/x.woff2')` 의 글꼴만
|
||||
* 교체하면 게시본이 영영 갱신되지 않았다(#651 F7). 감지 범위와 게시 범위를 한 코드가
|
||||
* 정의해야 다시 어긋나지 않는다.
|
||||
*
|
||||
* 규약 스캔의 **로드 목록**(`forExtension()` — 최상위 css/js) 과는 별개다. 글꼴·이미지는
|
||||
* CSS 가 상대 경로로 참조하는 대상이지 그 자체로 로드할 것이 아니므로 로드 목록은 그대로다.
|
||||
*
|
||||
* 허용 확장자는 종전 게시와 동일하게 `AllowedTemplateFileType::allowedExtensions()`(환경
|
||||
* 무관 게터)에서 소스맵(`map`)을 뺀 목록이다 — 배포 금지 정책(`*.map` gitignore)과 같다.
|
||||
*
|
||||
* @param string $extensionType `templates` | `modules` | `plugins`
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return array<int, array{relative: string, absolute: string, mtime: int, size: int}> 상대 경로 오름차순
|
||||
*/
|
||||
public static function publishableFiles(string $extensionType, string $identifier): array
|
||||
{
|
||||
$cacheKey = $extensionType.'|'.$identifier;
|
||||
|
||||
if (array_key_exists($cacheKey, self::$fileCache)) {
|
||||
return self::$fileCache[$cacheKey];
|
||||
}
|
||||
|
||||
return self::$fileCache[$cacheKey] = self::enumeratePublishableFiles($extensionType, $identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* `publishableFiles()` 의 실제 열거 (메모 없음).
|
||||
*
|
||||
* @param string $extensionType 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return array<int, array{relative: string, absolute: string, mtime: int, size: int}> 상대 경로 오름차순
|
||||
*/
|
||||
private static function enumeratePublishableFiles(string $extensionType, string $identifier): array
|
||||
{
|
||||
$directory = self::directory($extensionType, $identifier);
|
||||
|
||||
if ($directory === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$realRoot = realpath($directory);
|
||||
|
||||
if ($realRoot === false || ! is_dir($realRoot)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$allowed = array_diff(AllowedTemplateFileType::allowedExtensions(), ['map']);
|
||||
|
||||
try {
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($realRoot, \FilesystemIterator::SKIP_DOTS)
|
||||
);
|
||||
} catch (\UnexpectedValueException $e) {
|
||||
Log::warning('사용자 추가 에셋 디렉토리를 열 수 없습니다.', [
|
||||
'identifier' => $identifier,
|
||||
'directory' => $realRoot,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$files = [];
|
||||
|
||||
/** @var \SplFileInfo $file */
|
||||
foreach ($iterator as $file) {
|
||||
if (! $file->isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$extension = strtolower($file->getExtension());
|
||||
|
||||
if (! in_array($extension, $allowed, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 컨테인먼트 검증 — 심볼릭 링크 등으로 custom 밖을 가리키는 실경로 차단 (게시와 동일)
|
||||
$realFile = $file->getRealPath();
|
||||
|
||||
if ($realFile === false || ! str_starts_with($realFile, $realRoot.DIRECTORY_SEPARATOR)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$relative = str_replace('\\', '/', substr($realFile, strlen($realRoot) + 1));
|
||||
|
||||
$files[$relative] = [
|
||||
'relative' => $relative,
|
||||
'absolute' => $realFile,
|
||||
'mtime' => (int) (@$file->getMTime() ?: 0),
|
||||
'size' => (int) (@$file->getSize() ?: 0),
|
||||
];
|
||||
}
|
||||
|
||||
ksort($files, SORT_STRING);
|
||||
|
||||
return array_values($files);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user