v7.0.0-beta.5 release

This commit is contained in:
HeuJung committed 2026-05-12 17:58:34 +09:00
1 parent 1db039ff34
commit eb467aca79
159 files changed
+7599 -218

No files matched your search

@@ -0,0 +1,106 @@
<?php
namespace App\Upgrades\Data\V7_0_0_beta_5\Appliers;
use App\Extension\Upgrade\SnapshotApplier;
use App\Extension\UpgradeContext;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* 7.0.0-beta.5 시점의 permissions 카탈로그 delta 적용기.
*
* 본 버전은 IDV 권한 식별자 rename 2건만 다룬다. added/removed 는 비어있다.
*
* rename 의 *단순 경로* (옛 row 만 존재 → 신 row 부재) 를 in-place UPDATE 로 처리한다.
* 신 row 충돌 경로 (양쪽 모두 존재) 는 IdentityPermissionPivotMerge DataMigration 이 담당.
*
* 멱등성:
* - added 는 updateOrInsert (재실행 안전)
* - removed 는 where(identifier)->delete (옛 row 없으면 silent skip)
* - renamed 는 신 row 존재 시 silent skip (Migration 에 위임)
*
* V-1 안전:
* - Illuminate\Support\Facades\DB / Schema 만 사용
* - app(*Service|*Manager|*Repository::class) 호출 없음
* - 다른 버전 namespace 참조 없음
* - Database\Seeders 참조 없음
*/
final class PermissionsApplier implements SnapshotApplier
{
public function __construct(private readonly string $jsonPath) {}
public function apply(UpgradeContext $context): void
{
if (! Schema::hasTable('permissions')) {
$context->logger->info('[7.0.0-beta.5] permissions 테이블 부재 — PermissionsApplier skip');
return;
}
$delta = json_decode(
file_get_contents($this->jsonPath),
true,
flags: JSON_THROW_ON_ERROR,
);
$now = now();
foreach ($delta['added'] ?? [] as $row) {
if (empty($row['identifier'])) {
continue;
}
DB::table('permissions')->updateOrInsert(
['identifier' => $row['identifier']],
[
'type' => $row['type'] ?? null,
'category' => $row['category'] ?? null,
'name' => isset($row['name']) ? json_encode($row['name']) : null,
'updated_at' => $now,
'created_at' => $now,
],
);
}
foreach ($delta['removed'] ?? [] as $identifier) {
DB::table('permissions')->where('identifier', $identifier)->delete();
}
$renameApplied = 0;
foreach ($delta['renamed'] ?? [] as $rename) {
$from = $rename['from'] ?? null;
$to = $rename['to'] ?? null;
if (! is_string($from) || ! is_string($to)) {
continue;
}
$oldRow = DB::table('permissions')->where('identifier', $from)->first();
$newRow = DB::table('permissions')->where('identifier', $to)->first();
if ($oldRow && ! $newRow) {
DB::table('permissions')
->where('id', $oldRow->id)
->update([
'identifier' => $to,
'updated_at' => $now,
]);
$context->logger->info(sprintf(
'[7.0.0-beta.5] permissions in-place rename — %s → %s (id=%d, 피벗 자동 보존)',
$from,
$to,
$oldRow->id,
));
$renameApplied++;
}
}
if ($renameApplied > 0) {
$context->logger->info(sprintf(
'[7.0.0-beta.5] PermissionsApplier 완료 — in-place rename %d건 (충돌 경로는 Migration 위임)',
$renameApplied,
));
}
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"version": "7.0.0-beta.5",
"files": [
{ "kind": "permissions", "file": "permissions.delta.json" }
]
}
@@ -0,0 +1,317 @@
<?php
namespace App\Upgrades\Data\V7_0_0_beta_5\Migrations;
use App\Extension\Helpers\FilePermissionHelper;
use App\Extension\Upgrade\DataMigration;
use App\Extension\UpgradeContext;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
/**
* 4개 도메인의 활성 확장 디렉토리 자동 복구 (modules/plugins/templates/language_packs).
*
* beta.4 의 `applyDiscoveredTopLevelPaths` 회귀 (#347) 로 인해 손실된 활성 확장 디렉토리를
* `_bundled/{identifier}` 기준으로 자동 복구한다.
*
* 흐름:
* 1. DB `status='active'` row 식별자 조회
* 2. 활성 디렉토리 존재 확인 → 있으면 skip
* 3. `_bundled/{identifier}` 존재 시 비파괴 복사 (removeOrphans:false)
* 4. `_bundled` 부재 시 (외부 확장) → 자동 복구 불가 안내 + DB row 단발성 비활성화
*
* 멱등성: 활성 디렉토리 존재 시 silent skip. 모든 보정은 비파괴.
*/
final class RecoverActiveExtensionDirs implements DataMigration
{
/**
* 도메인별 경로/컬럼 매핑.
*
* @var array<string, array{table:string, dir:string, sourceColumn:string}>
*/
private const DOMAIN_MAP = [
'modules' => [
'table' => 'modules',
'dir' => 'modules',
'sourceColumn' => 'github_url',
],
'plugins' => [
'table' => 'plugins',
'dir' => 'plugins',
'sourceColumn' => 'github_url',
],
'templates' => [
'table' => 'templates',
'dir' => 'templates',
'sourceColumn' => 'github_url',
],
'language_packs' => [
'table' => 'language_packs',
'dir' => 'lang-packs',
'sourceColumn' => 'source_url',
],
];
/**
* 외부 확장으로 판정된 row 의 `deactivated_reason` raw 값 (단발성 식별자).
*/
private const DEACTIVATION_REASON_DIR_LOST = 'extension_dir_lost_beta5';
public function name(): string
{
return 'RecoverActiveExtensionDirs';
}
public function run(UpgradeContext $context): void
{
$context->logger->info('[7.0.0-beta.5] 활성 확장 디렉토리 정합성 검증 시작');
$totalRestored = 0;
$totalSkipped = 0;
$externalLost = [];
foreach (self::DOMAIN_MAP as $domain => $cfg) {
$stats = $this->recoverDomain($context, $domain, $cfg);
$totalRestored += $stats['restored'];
$totalSkipped += $stats['skipped'];
$externalLost = array_merge($externalLost, $stats['external_lost']);
}
$context->logger->info(sprintf(
'[7.0.0-beta.5] 활성 확장 디렉토리 복구 완료 — 복원 %d 건, 정상 %d 건, 외부 확장 손실 %d 건',
$totalRestored,
$totalSkipped,
count($externalLost),
));
if (count($externalLost) > 0) {
$context->logger->warning(sprintf(
'[7.0.0-beta.5] 외부 확장 %d개 자동 복구 불가 — 운영자 수동 처리 필요. 상세는 위 개별 항목 로그 참조.',
count($externalLost),
));
}
}
/**
* @param array{table:string, dir:string, sourceColumn:string} $cfg
* @return array{restored:int, skipped:int, external_lost:array<int, string>}
*/
private function recoverDomain(UpgradeContext $context, string $domain, array $cfg): array
{
$stats = ['restored' => 0, 'skipped' => 0, 'external_lost' => []];
if (! Schema::hasTable($cfg['table'])) {
$context->logger->info(sprintf('[7.0.0-beta.5] %s 테이블 부재 — 도메인 skip', $cfg['table']));
return $stats;
}
$sourceColumnExists = Schema::hasColumn($cfg['table'], $cfg['sourceColumn']);
$rows = DB::table($cfg['table'])
->where('status', 'active')
->get(['identifier', 'version', $sourceColumnExists ? $cfg['sourceColumn'] : DB::raw("NULL as {$cfg['sourceColumn']}")]);
foreach ($rows as $row) {
$identifier = $row->identifier;
$activePath = base_path($cfg['dir'].DIRECTORY_SEPARATOR.$identifier);
if (File::isDirectory($activePath) && ! $this->isEmptyDirectory($activePath)) {
$stats['skipped']++;
continue;
}
$bundledPath = base_path($cfg['dir'].DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.$identifier);
if (File::isDirectory($bundledPath) && ! $this->isEmptyDirectory($bundledPath)) {
$this->restoreFromBundled($context, $domain, $identifier, $bundledPath, $activePath);
$stats['restored']++;
} else {
$this->handleExternalExtensionLoss($context, $domain, $cfg, $row, $sourceColumnExists);
$stats['external_lost'][] = $identifier;
}
}
return $stats;
}
private function restoreFromBundled(
UpgradeContext $context,
string $domain,
string $identifier,
string $bundledPath,
string $activePath,
): void {
try {
File::ensureDirectoryExists(dirname($activePath));
FilePermissionHelper::copyDirectory($bundledPath, $activePath, null, [], removeOrphans: false);
$ownerInfo = $this->describeOwnership($activePath);
$context->logger->info(sprintf(
'[7.0.0-beta.5] %s/%s 활성 디렉토리 복원 완료 — %s → %s (%s)',
$domain,
$identifier,
$bundledPath,
$activePath,
$ownerInfo,
));
} catch (\Throwable $e) {
$context->logger->warning(sprintf(
'[7.0.0-beta.5] %s/%s 활성 디렉토리 복원 실패 — %s: %s',
$domain,
$identifier,
$activePath,
$e->getMessage(),
));
}
}
/**
* @param array{table:string, dir:string, sourceColumn:string} $cfg
*/
private function handleExternalExtensionLoss(
UpgradeContext $context,
string $domain,
array $cfg,
object $row,
bool $sourceColumnExists,
): void {
$identifier = $row->identifier;
$version = $row->version ?? '?';
$sourceColumn = $cfg['sourceColumn'];
$sourceUrl = $sourceColumnExists ? ($row->{$sourceColumn} ?? null) : null;
if (is_string($sourceUrl) && $sourceUrl !== '') {
$command = $this->describeReinstallCommand($domain, $identifier);
$context->logger->warning(sprintf(
"[7.0.0-beta.5] ⚠ 외부 %s 자동 복구 불가 — %s/%s @ %s\n %s: %s\n 수동 재설치: %s",
$this->describeDomainSingular($domain),
$cfg['dir'],
$identifier,
$version,
$sourceColumn,
$sourceUrl,
$command,
));
} else {
$context->logger->warning(sprintf(
"[7.0.0-beta.5] ⚠ 외부 %s 자동 복구 불가 — %s/%s @ %s\n 외부 source 정보 부재 (%s 미저장)\n 운영자가 원본 소스로 직접 재설치 필요",
$this->describeDomainSingular($domain),
$cfg['dir'],
$identifier,
$version,
$sourceColumn,
));
}
$this->markDeactivatedIfSupported($context, $cfg['table'], $identifier);
}
private function markDeactivatedIfSupported(UpgradeContext $context, string $table, string $identifier): void
{
$hasReason = Schema::hasColumn($table, 'deactivated_reason');
$hasAt = Schema::hasColumn($table, 'deactivated_at');
if (! $hasReason || ! $hasAt) {
$context->logger->info(sprintf(
'[7.0.0-beta.5] %s.deactivated_* 컬럼 부재 — %s DB row 비활성화 skip (stdout 안내만 적용)',
$table,
$identifier,
));
return;
}
try {
DB::table($table)
->where('identifier', $identifier)
->update([
'status' => 'inactive',
'deactivated_reason' => self::DEACTIVATION_REASON_DIR_LOST,
'deactivated_at' => now(),
]);
$context->logger->info(sprintf(
'[7.0.0-beta.5] %s/%s DB row 단발성 비활성화 — deactivated_reason=%s',
$table,
$identifier,
self::DEACTIVATION_REASON_DIR_LOST,
));
} catch (\Throwable $e) {
$context->logger->warning(sprintf(
'[7.0.0-beta.5] %s/%s DB row 비활성화 실패 — %s',
$table,
$identifier,
$e->getMessage(),
));
}
}
private function describeDomainSingular(string $domain): string
{
return match ($domain) {
'modules' => '모듈',
'plugins' => '플러그인',
'templates' => '템플릿',
'language_packs' => '언어팩',
default => $domain,
};
}
private function describeReinstallCommand(string $domain, string $identifier): string
{
return match ($domain) {
'modules' => sprintf('php artisan module:install %s --source=github', $identifier),
'plugins' => sprintf('php artisan plugin:install %s --source=github', $identifier),
'templates' => sprintf('php artisan template:install %s --source=github', $identifier),
'language_packs' => sprintf('php artisan language-pack:install %s --source=url', $identifier),
default => sprintf('php artisan %s:install %s', $domain, $identifier),
};
}
private function describeOwnership(string $path): string
{
if (! File::isDirectory($path)) {
return 'unknown';
}
$owner = function_exists('fileowner') ? @fileowner($path) : null;
$group = function_exists('filegroup') ? @filegroup($path) : null;
$perms = function_exists('fileperms') ? @fileperms($path) : null;
$permsOctal = $perms !== false && $perms !== null ? sprintf('%04o', $perms & 0777) : '?';
$ownerName = '?';
if ($owner !== false && $owner !== null && function_exists('posix_getpwuid')) {
$info = @posix_getpwuid($owner);
$ownerName = is_array($info) && isset($info['name']) ? $info['name'] : (string) $owner;
} elseif ($owner !== false && $owner !== null) {
$ownerName = (string) $owner;
}
$groupName = '?';
if ($group !== false && $group !== null && function_exists('posix_getgrgid')) {
$info = @posix_getgrgid($group);
$groupName = is_array($info) && isset($info['name']) ? $info['name'] : (string) $group;
} elseif ($group !== false && $group !== null) {
$groupName = (string) $group;
}
return sprintf('owner=%s group=%s perms=%s', $ownerName, $groupName, $permsOctal);
}
private function isEmptyDirectory(string $path): bool
{
if (! File::isDirectory($path)) {
return true;
}
$entries = @scandir($path);
if ($entries === false) {
return true;
}
return count(array_diff($entries, ['.', '..'])) === 0;
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Upgrades\Data\V7_0_0_beta_5\Migrations;
use App\Extension\Upgrade\DataMigration;
use App\Extension\UpgradeContext;
use Illuminate\Support\Facades\File;
/**
* `{modules,plugins,templates,lang-packs}/_pending/{.gitignore,.gitkeep}` 부재 시 재생성.
*
* `applyDiscoveredTopLevelPaths` 결함이 부모 디렉토리 통째로 복사하며 release zip 의
* `_pending` stub 만 남기는 상황 (부재한 `.gitignore`/`.gitkeep` 가 활성에서 손실되는 회귀)
* 의 사후 보정.
*
* 멱등성: stub 파일 존재 시 skip.
*/
final class RecoverPendingStubFiles implements DataMigration
{
/**
* 디렉토리별 `_pending` stub 보정 대상 (디렉토리명).
*
* @var array<int, string>
*/
private const PENDING_STUB_DIRS = ['modules', 'plugins', 'templates', 'lang-packs'];
public function name(): string
{
return 'RecoverPendingStubFiles';
}
public function run(UpgradeContext $context): void
{
$gitignoreContent = "*\n!.gitignore\n!.gitkeep\n";
$restored = 0;
$skipped = 0;
foreach (self::PENDING_STUB_DIRS as $domainDir) {
$pendingPath = base_path($domainDir.DIRECTORY_SEPARATOR.'_pending');
if (! File::isDirectory($pendingPath)) {
try {
File::ensureDirectoryExists($pendingPath);
$context->logger->info(sprintf('[7.0.0-beta.5] %s/_pending 디렉토리 생성', $domainDir));
} catch (\Throwable $e) {
$context->logger->warning(sprintf(
'[7.0.0-beta.5] %s/_pending 디렉토리 생성 실패 — %s',
$domainDir,
$e->getMessage(),
));
continue;
}
}
foreach ([['.gitignore', $gitignoreContent], ['.gitkeep', '']] as [$stubName, $stubContent]) {
$stubPath = $pendingPath.DIRECTORY_SEPARATOR.$stubName;
if (File::exists($stubPath)) {
$skipped++;
continue;
}
try {
File::put($stubPath, $stubContent);
$restored++;
} catch (\Throwable $e) {
$context->logger->warning(sprintf(
'[7.0.0-beta.5] %s/_pending/%s 작성 실패 — %s',
$domainDir,
$stubName,
$e->getMessage(),
));
}
}
}
$context->logger->info(sprintf(
'[7.0.0-beta.5] _pending stub 보정 — 신규 작성 %d 건, 기존 보존 %d 건',
$restored,
$skipped,
));
}
}
@@ -0,0 +1,121 @@
<?php
namespace App\Upgrades\Data\V7_0_0_beta_5\Migrations;
use App\Extension\Helpers\FilePermissionHelper;
use App\Extension\Upgrade\DataMigration;
use App\Extension\UpgradeContext;
use FilesystemIterator;
use Illuminate\Support\Facades\File;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
/**
* beta.4 의 `recoverLangPacksBundled` 와 동등한 fallback 을 한 번 더 멱등 실행.
*
* beta.4 step 이 이미 보정한 환경에서는 silent skip. beta.4 spawn 자식이 정상 실행되지
* 못한 환경(예: in-process fallback 실패)에서 누락이 남아있다면 본 step 이 추가 보정.
*
* 비표준 ZIP 구조 탐색을 위해 `FilesystemIterator` 기반 무제한 깊이 재귀 탐색을 사용한다
* (beta.4 의 4단계 깊이 제약을 회피).
*
* 멱등성: `lang-packs/_bundled` 가 비어있지 않으면 silent skip.
*/
final class VerifyBundledLangPacksFallback implements DataMigration
{
public function name(): string
{
return 'VerifyBundledLangPacksFallback';
}
public function run(UpgradeContext $context): void
{
$activeBundled = base_path('lang-packs/_bundled');
if (File::isDirectory($activeBundled) && count(File::directories($activeBundled)) > 0) {
$context->logger->info('[7.0.0-beta.5] lang-packs/_bundled 정상 — fallback skip');
return;
}
$context->logger->warning('[7.0.0-beta.5] lang-packs/_bundled 누락 감지 — fallback 탐색 시작');
$pendingSource = $this->locatePendingLangPacksSourceDeep($context);
if ($pendingSource === null) {
$context->logger->warning(
'[7.0.0-beta.5] _pending 의 lang-packs/_bundled 소스 미발견 — 수동 복구 필요. '
.'`php artisan core:update --force` 재실행으로 자동 발견 폴백 트리거.'
);
return;
}
try {
File::ensureDirectoryExists($activeBundled);
FilePermissionHelper::copyDirectory($pendingSource, $activeBundled, null, [], removeOrphans: false);
$count = count(File::directories($activeBundled));
$context->logger->info(sprintf(
'[7.0.0-beta.5] lang-packs/_bundled fallback 복원 완료 — %d 개 패키지 ({%s} → {%s})',
$count,
$pendingSource,
$activeBundled,
));
} catch (\Throwable $e) {
$context->logger->warning('[7.0.0-beta.5] lang-packs/_bundled fallback 복원 실패 — '.$e->getMessage());
}
}
/**
* _pending 디렉토리에서 `lang-packs/_bundled` 소스를 무제한 깊이로 재귀 탐색.
*
* `FilesystemIterator` 기반으로 깊이 제한 없이 첫 매치를 반환한다 (가장 얕은 매치 우선).
*/
private function locatePendingLangPacksSourceDeep(UpgradeContext $context): ?string
{
$pendingPath = config('app.update.pending_path');
if (! is_string($pendingPath) || $pendingPath === '' || ! File::isDirectory($pendingPath)) {
return null;
}
try {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($pendingPath, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
);
} catch (\Throwable $e) {
$context->logger->warning('[7.0.0-beta.5] _pending 재귀 탐색 실패 — '.$e->getMessage());
return null;
}
$matches = [];
foreach ($iterator as $entry) {
if (! $entry->isDir()) {
continue;
}
$path = $entry->getPathname();
// basename 이 '_bundled' 이고 부모 basename 이 'lang-packs' 인 경로만 매치
if (basename($path) !== '_bundled') {
continue;
}
if (basename(dirname($path)) !== 'lang-packs') {
continue;
}
if (count(File::directories($path)) === 0) {
continue;
}
$matches[] = $path;
}
if (count($matches) === 0) {
return null;
}
// 가장 짧은 경로 (가장 얕은 매치) 우선 선택
usort($matches, fn (string $a, string $b): int => strlen($a) <=> strlen($b));
$picked = $matches[0];
$context->logger->info('[7.0.0-beta.5] lang-packs 소스 발견: '.$picked);
return $picked;
}
}
@@ -0,0 +1,107 @@
<?php
namespace App\Upgrades\Data\V7_0_0_beta_5\Migrations;
use App\Extension\Upgrade\DataMigration;
use App\Extension\UpgradeContext;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* 본인인증(IDV) 관리자 권한 키 마이그레이션의 *충돌 경로* 처리.
*
* PermissionsApplier 가 처리하는 *단순 경로* (옛 row 만 존재) 와 본 Migration 의
* *충돌 경로* (양쪽 row 모두 존재) 가 함께 동작하여 메시지 템플릿 패턴과 일관되도록
* 프로바이더/정책 권한도 read / update 로 분리한다. 기존 `manage` 키는 `update` 로 변경.
*
* 흐름 (충돌 경로만):
* 1. 옛 권한과 신 권한 양쪽에 부여된 role 식별 (중복 피벗 회피)
* 2. 옛 권한에만 부여된 role 은 피벗을 신 권한으로 이동 (granted_at/by/scope_type 그대로)
* 3. 양쪽 부여된 role 은 옛 피벗만 삭제 (신 피벗 보존)
* 4. 옛 권한 row 삭제
*
* 멱등성: 옛 키 또는 신 키 부재 시 silent skip. 두 번 호출해도 무해.
*/
final class IdentityPermissionPivotMerge implements DataMigration
{
private const RENAMES = [
'core.admin.identity.manage' => 'core.admin.identity.providers.update',
'core.admin.identity.policies.manage' => 'core.admin.identity.policies.update',
];
public function name(): string
{
return 'IdentityPermissionPivotMerge';
}
public function run(UpgradeContext $context): void
{
if (! Schema::hasTable('permissions') || ! Schema::hasTable('role_permissions')) {
$context->logger->info('[7.0.0-beta.5] permissions/role_permissions 테이블 부재 — IdentityPermissionPivotMerge skip');
return;
}
$totalProcessed = 0;
foreach (self::RENAMES as $oldIdentifier => $newIdentifier) {
$oldRow = DB::table('permissions')->where('identifier', $oldIdentifier)->first();
$newRow = DB::table('permissions')->where('identifier', $newIdentifier)->first();
// 신 row 부재 경로는 PermissionsApplier 가 in-place rename 으로 이미 처리 → skip
// 옛 row 부재는 처리할 대상 없음 → skip
if (! $oldRow || ! $newRow) {
continue;
}
$this->mergePermissionPivots(
$context,
(int) $oldRow->id,
(int) $newRow->id,
$oldIdentifier,
$newIdentifier,
);
$totalProcessed++;
}
$context->logger->info(sprintf(
'[7.0.0-beta.5] IDV 권한 키 충돌 경로 병합 완료 — 총 %d건 처리',
$totalProcessed,
));
}
private function mergePermissionPivots(
UpgradeContext $context,
int $oldPermissionId,
int $newPermissionId,
string $oldIdentifier,
string $newIdentifier,
): void {
$rolesWithNew = DB::table('role_permissions')
->where('permission_id', $newPermissionId)
->pluck('role_id')
->all();
$movedCount = DB::table('role_permissions')
->where('permission_id', $oldPermissionId)
->whereNotIn('role_id', $rolesWithNew)
->update(['permission_id' => $newPermissionId]);
$duplicateDeleted = DB::table('role_permissions')
->where('permission_id', $oldPermissionId)
->delete();
DB::table('permissions')
->where('id', $oldPermissionId)
->delete();
$context->logger->info(sprintf(
'[7.0.0-beta.5] IDV 권한 키 병합 — %s(id=%d) → %s(id=%d) — 피벗 이동 %d건, 중복 정리 %d건, 옛 row 삭제',
$oldIdentifier,
$oldPermissionId,
$newIdentifier,
$newPermissionId,
$movedCount,
$duplicateDeleted,
));
}
}
@@ -0,0 +1,73 @@
<?php
namespace App\Upgrades\Data\V7_0_0_beta_5\Migrations;
use App\Extension\Upgrade\DataMigration;
use App\Extension\UpgradeContext;
/**
* `public/storage` symlink 손상 자동 복구 (단발성).
*
* beta.4 → beta.5 업그레이드 시점의 백업/복원은 부모 beta.4 메모리의 `FilePermissionHelper`
* 를 사용하므로 symlink 보존 분기 (beta.5+ 도입) 가 미적용 → 롤백 발생 시 `public/storage`
* symlink 가 일반 디렉토리로 변질되는 결함이 잔존한다. 본 step 이 단발성 자동 복구
* (rename 보존 + symlink 재생성) 로 보완한다.
*
* 안전 가드 (false positive 차단):
* 1. `is_link($publicStorage)` 가 true → 이미 정상 symlink, silent skip (멱등)
* 2. `! is_dir($publicStorage) || ! is_dir($storageSource)` → Laravel storage:link
* 컨벤션을 따르지 않는 환경, skip
* 3. rename 으로 `.broken.{timestamp}` 백업 후 symlink 재생성 — `rm -rf` 미사용
* 4. symlink 생성 실패 (Windows 권한 부족 등) → rename 백업을 원위치로 복원
*/
final class RecoverPublicStorageSymlink implements DataMigration
{
public function name(): string
{
return 'RecoverPublicStorageSymlink';
}
public function run(UpgradeContext $context): void
{
$publicStorage = public_path('storage');
$storageSource = storage_path('app/public');
// 1) 정상 symlink → skip (멱등)
if (is_link($publicStorage)) {
return;
}
// 2) public/storage 가 일반 디렉토리이면서 Laravel storage:link source 가 존재할 때만
// 손상 후보로 판정 — 운영자가 Laravel 표준을 따르고 있다는 강한 신호.
// 둘 중 하나라도 부재하면 운영자 의도적 구성으로 간주하여 skip.
if (! is_dir($publicStorage) || ! is_dir($storageSource)) {
return;
}
// 3) 안전 보존 — rm -rf 대신 rename 으로 백업 후 symlink 재생성.
// false positive (운영자가 의도적으로 일반 디렉토리 사용) 시에도 데이터 손실 없음.
$backup = $publicStorage.'.broken.'.date('YmdHis');
if (! @rename($publicStorage, $backup)) {
$context->logger->warning('[7.0.0-beta.5] public/storage rename 실패 — 자동 복구 skip', [
'path' => $publicStorage,
]);
return;
}
if (! @symlink($storageSource, $publicStorage)) {
// symlink 생성 실패 (Windows SeCreateSymbolicLink 권한 부족 등) → rename 원복
@rename($backup, $publicStorage);
$context->logger->warning('[7.0.0-beta.5] public/storage symlink 재생성 실패 — rename 원복', [
'target' => $storageSource,
]);
return;
}
$context->logger->info('[7.0.0-beta.5] public/storage symlink 자동 복구 완료 — 백업 디렉토리 검증 후 수동 삭제 권장', [
'backup' => $backup,
'target' => $storageSource,
]);
}
}
@@ -0,0 +1,14 @@
{
"added": [],
"removed": [],
"renamed": [
{
"from": "core.admin.identity.manage",
"to": "core.admin.identity.providers.update"
},
{
"from": "core.admin.identity.policies.manage",
"to": "core.admin.identity.policies.update"
}
]
}