fix(core,ecommerce): Windows 확장 업데이트 파일 잠금 해소 + 통화 삭제 영속화

Windows 는 하위 트리에 열린 핸들이 하나라도 있으면 디렉토리 rename 을 막는다.
잠금 프로세스를 찾아 종료하던 기존 대응은 디렉토리 핸들을 감지하지 못했고
사용 중인 편집기를 예고 없이 죽였다. rename 이 막히면 파일 단위 연산으로
폴백해 어떤 프로세스도 건드리지 않고 교체를 끝낸다. 커밋 전 점검에서
pint.json 이 코어 업데이트 대상에 빠져 있던 것도 함께 등재했다.

이커머스는 기본 제공 통화 삭제가 저장 응답에서 즉시 부활했다. 항목 단위
보충 병합이 "소실" 과 "의도적 삭제" 를 구분하지 못한 탓이라, 삭제 의도를
서버가 도출해 저장본에 기록하고 병합이 그 기록을 존중하게 했다. 그 통화로
결제된 과거 주문의 표기가 흔들리지 않도록 소수 자릿수 해석도 스냅샷 우선으로
바꿨다 — 금액은 원래 스냅샷 환율을 써 안전했으나 자릿수만 현재 설정을 봤다.
This commit is contained in:
HeuJung committed 2026-08-12 10:10:01 +09:00
1 parent 5ae34002f3
commit c77ddee03b
39 files changed
+1886 -138

No files matched your search

+354 -61
View File
@@ -141,11 +141,22 @@ class ExtensionPendingHelper
// Windows에서 deleteDirectory 직후 같은 이름으로 rename이 실패하는
// 타이밍 이슈를 회피하기 위해 rename→rename→delete 패턴을 사용합니다.
// 임시 디렉토리를 _pending/ 하위에 생성하여 오토로드 오염 방지
//
// Windows 잠금 대응: 디렉토리 rename 은 하위 트리에 열린 핸들(파일 워처의
// 디렉토리 핸들, IDE/Node 프로세스가 열어 둔 파일 등)이 하나라도 있으면
// 실패한다. 잠금 프로세스의 식별·종료는 신뢰할 수 없으므로(디렉토리 핸들은
// Restart Manager 로 감지 불가), rename 이 차단되면 파일 단위 연산으로
// 폴백한다 — 파일 생성/덮어쓰기/읽기는 디렉토리 핸들 잠금의 영향을 받지
// 않아 어떤 프로세스도 종료하지 않고 교체를 완료할 수 있다.
$basePath = dirname($targetPath);
$pendingPath = $basePath.DIRECTORY_SEPARATOR.'_pending';
File::ensureDirectoryExists($pendingPath, 0775);
$identifier = basename($targetPath);
// 이전 실패 실행이 남긴 교체용 임시 디렉토리 정리 (best-effort)
self::cleanupSwapLeftovers($pendingPath, $identifier);
$tempPath = $pendingPath.DIRECTORY_SEPARATOR.$identifier.'_updating_'.uniqid();
$oldPath = $pendingPath.DIRECTORY_SEPARATOR.$identifier.'_old_'.uniqid();
@@ -161,40 +172,77 @@ class ExtensionPendingHelper
// 기존 → _old 이동 (rename, Windows NTFS 타이밍 이슈 대응 재시도)
if (! self::retryMoveDirectory($targetPath, $oldPath)) {
// 파일 잠금 감지 및 해제 시도
if (self::tryReleaseLocks($targetPath, $onProgress)) {
// 잠금 해제 후 재시도
if (! self::retryMoveDirectory($targetPath, $oldPath)) {
File::deleteDirectory($tempPath);
throw new \RuntimeException(
"Failed to move existing directory: {$targetPath} → {$oldPath}"
);
}
} else {
File::deleteDirectory($tempPath);
throw new \RuntimeException(
"Failed to move existing directory: {$targetPath} → {$oldPath}"
);
// 활성 디렉토리 rename 차단 (하위 트리에 열린 핸들 존재)
// → 파일 단위 제자리 동기화로 폴백. 덮어쓰기는 잠금의 영향을 받지 않는다.
$onProgress?->__invoke(null, '디렉토리 이동이 차단되어 파일 단위 제자리 교체로 전환합니다...');
Log::info('확장 교체: 활성 디렉토리 rename 차단 — 제자리 동기화 폴백', [
'target' => $targetPath,
]);
try {
self::syncDirectoryContents($tempPath, $targetPath, $onProgress);
} finally {
self::bestEffortDeleteDirectory($tempPath);
}
self::refreshRuntimeCaches();
return;
}
// 임시 → 활성 이동 (rename, Windows NTFS 타이밍 이슈 대응 재시도)
if (! self::retryMoveDirectory($tempPath, $targetPath)) {
// 롤백: _old를 원래 위치로 복원
File::moveDirectory($oldPath, $targetPath);
throw new \RuntimeException(
"Failed to move directory: {$tempPath} → {$targetPath}"
);
// 방금 복사한 스테이징 트리를 파일 워처가 이미 열어 rename 이 차단된 경우
// → 파일 단위 복사로 폴백. 소스에는 읽기 접근만 필요해 잠금과 무관하게 성공한다.
$onProgress?->__invoke(null, '디렉토리 이동이 차단되어 파일 단위 복사로 전환합니다...');
Log::info('확장 교체: 스테이징 rename 차단 — 파일 단위 복사 폴백', [
'staging' => $tempPath,
'target' => $targetPath,
]);
try {
self::copyDirectoryWithProgress($tempPath, $targetPath, $tempPath, $onProgress);
} catch (\Exception $e) {
// 복사 실패: 부분 복사본 제거 후 _old 를 원래 위치로 복원
self::bestEffortDeleteDirectory($targetPath);
if (! self::retryMoveDirectory($oldPath, $targetPath)) {
try {
self::syncDirectoryContents($oldPath, $targetPath, $onProgress);
} catch (\Throwable $restoreError) {
Log::error('확장 교체 롤백 실패 — 백업 복원이 필요합니다', [
'target' => $targetPath,
'old' => $oldPath,
'error' => $restoreError->getMessage(),
]);
}
}
throw new \RuntimeException(
"Failed to move directory: {$tempPath} → {$targetPath}",
0,
$e
);
}
self::bestEffortDeleteDirectory($tempPath);
}
// 교체 완료 후 _old 삭제 (실패해도 무해)
File::deleteDirectory($oldPath);
// 교체 완료 후 _old 삭제 (실패해도 무해 — 다음 교체 시작 시 잔존물 정리가 재시도)
self::bestEffortDeleteDirectory($oldPath);
// 원자적 rename 은 inode 단위로 교체되므로 PHP realpath/stat 캐시가
// 이전 디렉토리의 파일 존재 여부를 기준으로 판단할 수 있다. 직후 Composer
// PSR-4 autoload 가 신규 파일(beta.1 에 없던 Seeder/Model)을 file_exists 로
// 탐색할 때 false 반환 → "Class not found" fatal 로 업그레이드 스텝이 실패.
// clearstatcache(true) 로 전체 stat 캐시를 비워 신규 파일이 즉시 보이도록 한다.
self::refreshRuntimeCaches();
}
/**
* 교체 완료 후 PHP 런타임 캐시를 갱신합니다.
*
* 원자적 rename 은 inode 단위로 교체되므로 PHP realpath/stat 캐시가
* 이전 디렉토리의 파일 존재 여부를 기준으로 판단할 수 있다. 직후 Composer
* PSR-4 autoload 가 신규 파일(beta.1 에 없던 Seeder/Model)을 file_exists 로
* 탐색할 때 false 반환 → "Class not found" fatal 로 업그레이드 스텝이 실패.
* clearstatcache(true) 로 전체 stat 캐시를 비워 신규 파일이 즉시 보이도록 한다.
*/
private static function refreshRuntimeCaches(): void
{
clearstatcache(true);
// opcache 가 활성화된 프로덕션에서는 활성 디렉토리 하위의 이전 컴파일 바이트코드가
@@ -237,41 +285,6 @@ class ExtensionPendingHelper
]);
}
/**
* 파일 잠금을 감지하고 해제를 시도합니다.
*
* Windows에서 다른 프로세스(IDE 등)가 파일 핸들을 보유하고 있을 때,
* 해당 프로세스를 감지하고 종료하여 디렉토리 이동이 가능하도록 합니다.
* 프로그레스바와 별개로 STDERR에 직접 출력하여 메시지가 덮어씌워지지 않습니다.
*
* @param string $directoryPath 잠금 해제할 디렉토리 경로
* @param \Closure|null $onProgress 진행 콜백
* @return bool 잠금 해제 성공 여부
*/
private static function tryReleaseLocks(string $directoryPath, ?\Closure $onProgress = null): bool
{
if (! FileHandleHelper::isWindows()) {
return false;
}
// 프로그레스바에 의해 메시지가 덮어씌워지지 않도록 STDERR에 직접 출력
$stderr = fopen('php://stderr', 'w');
$outputCallback = function (string $message) use ($stderr) {
if ($stderr) {
fwrite($stderr, $message.PHP_EOL);
}
Log::info($message, ['context' => 'file_lock_release']);
};
$result = FileHandleHelper::releaseLocks($directoryPath, $outputCallback);
if ($stderr) {
fclose($stderr);
}
return $result;
}
/**
* 디렉토리 이동을 재시도합니다 (Windows NTFS 타이밍 이슈 대응).
*
@@ -333,6 +346,282 @@ class ExtensionPendingHelper
}
}
/**
* 새 버전 콘텐츠를 활성 디렉토리에 파일 단위로 제자리 동기화합니다.
*
* 디렉토리 rename 이 외부 프로세스의 핸들 잠금으로 차단될 때 사용하는 폴백입니다.
* 디렉토리 inode 를 건드리지 않고 파일 생성/덮어쓰기/삭제만 수행하므로
* 디렉토리 핸들 잠금(파일 워처 등)의 영향을 받지 않습니다.
*
* (1) 새 버전 파일 전체를 덮어쓰기 → (2) 새 버전에 없는 잔존 파일 제거.
* (1) 실패는 예외로 전파해 호출자(매니저)가 백업 복원으로 수습하게 하고,
* (2) 실패는 로그만 남기고 진행합니다 (업데이트 전체 실패보다 잔존이 낫다).
*
* @param string $source 새 버전 콘텐츠 디렉토리
* @param string $dest 활성 디렉토리
* @param \Closure|null $onProgress 진행 콜백
*
* @throws \RuntimeException 새 버전 파일을 심지 못했을 때
*/
private static function syncDirectoryContents(string $source, string $dest, ?\Closure $onProgress = null): void
{
File::ensureDirectoryExists($dest, 0775);
$failed = [];
self::overlayDirectory($source, $dest, $source, $onProgress, $failed);
if (! empty($failed)) {
throw new \RuntimeException(
'Failed to replace files locked by another process: '
.implode(', ', array_slice($failed, 0, 5))
.(count($failed) > 5 ? ' (+'.(count($failed) - 5).' more)' : '')
);
}
$staleFailures = [];
self::removeStaleEntries($source, $dest, $staleFailures);
if (! empty($staleFailures)) {
Log::warning('확장 제자리 교체: 일부 잔존 파일을 삭제하지 못했습니다 (다음 교체 시 재시도)', [
'dest' => $dest,
'failed' => $staleFailures,
]);
}
}
/**
* 소스 디렉토리의 파일을 대상 디렉토리에 재귀적으로 덮어씁니다.
*
* @param string $source 소스 디렉토리
* @param string $dest 대상 디렉토리
* @param string $basePath 상대 경로 계산 기준
* @param \Closure|null $onProgress 진행 콜백
* @param array $failed 교체 실패한 상대 경로 수집 (참조)
*/
private static function overlayDirectory(
string $source,
string $dest,
string $basePath,
?\Closure $onProgress,
array &$failed
): void {
File::ensureDirectoryExists($dest, 0775);
$items = new \FilesystemIterator($source, \FilesystemIterator::SKIP_DOTS);
foreach ($items as $item) {
if ($item->isDir() && in_array($item->getBasename(), self::EXCLUDED_DIRECTORIES, true)) {
continue;
}
$target = $dest.DIRECTORY_SEPARATOR.$item->getBasename();
$relativePath = ltrim(str_replace($basePath, '', $item->getPathname()), '/\\');
if ($item->isDir()) {
if (is_file($target) && ! self::deleteFileWithFallback($target)) {
// 파일 → 디렉토리로 바뀐 경로인데 기존 파일을 치우지 못함
$failed[] = $relativePath;
continue;
}
self::overlayDirectory($item->getPathname(), $target, $basePath, $onProgress, $failed);
} else {
if (is_dir($target)) {
// 디렉토리 → 파일로 바뀐 경로
File::deleteDirectory($target);
}
$onProgress?->__invoke(null, $relativePath);
if (! self::replaceFile($item->getPathname(), $target)) {
$failed[] = $relativePath;
}
}
}
}
/**
* 파일 하나를 덮어씁니다 (잠금 대응 단계적 폴백).
*
* Windows 의 일반적인 파일 열기 모드는 읽기/쓰기 공유를 허용하므로,
* 다른 프로세스가 열어 둔 파일이라도 내용 덮어쓰기는 대부분 성공합니다.
* 덮어쓰기가 막힌 경우에만 삭제 후 재생성 → 옆으로 치우기(rename) 순으로
* 시도합니다. FilePermissionHelper::copyFile() 은 복사 실패를 보고하지 않으므로
* (File::copy 반환값 무시) 이 경로에서는 네이티브 copy 반환값으로 판정합니다.
*
* @param string $source 소스 파일
* @param string $destination 대상 파일
* @return bool 교체 성공 여부
*/
private static function replaceFile(string $source, string $destination): bool
{
File::ensureDirectoryExists(dirname($destination));
$isExisting = is_file($destination);
$existingPerms = $isExisting ? @fileperms($destination) : null;
$existingOwner = $isExisting ? @fileowner($destination) : null;
$existingGroup = $isExisting ? @filegroup($destination) : null;
$restoreMeta = function () use ($destination, $isExisting, $existingPerms, $existingOwner, $existingGroup) {
if (! $isExisting) {
// 신규 파일: 부모 디렉토리의 소유자/그룹 상속 (sudo 실행 시 root 소유 방지)
FilePermissionHelper::inheritOwnershipFromParent($destination);
return;
}
if ($existingPerms !== false && $existingPerms !== null) {
@chmod($destination, $existingPerms);
}
if ($existingOwner !== false && $existingOwner !== null && function_exists('chown')) {
@chown($destination, $existingOwner);
}
if ($existingGroup !== false && $existingGroup !== null && function_exists('chgrp')) {
@chgrp($destination, $existingGroup);
}
};
// 1차: 그대로 덮어쓰기
if (@copy($source, $destination)) {
$restoreMeta();
return true;
}
// 2차: 읽기 전용 속성 해제 후 재시도
@chmod($destination, 0666);
if (@copy($source, $destination)) {
$restoreMeta();
return true;
}
// 3차: 삭제 후 재생성
if (@unlink($destination) && @copy($source, $destination)) {
$restoreMeta();
return true;
}
// 4차: 잠긴 파일을 옆으로 치우고(rename 은 덮어쓰기와 별개 권한) 새 파일 생성.
// 옆으로 치운 파일은 즉시 삭제를 시도하고, 실패해도 새 버전에 없는 파일이므로
// 다음 제자리 동기화의 잔존 파일 제거가 다시 삭제를 시도한다.
$aside = $destination.'.g7stale_'.uniqid();
if (@rename($destination, $aside)) {
@unlink($aside);
if (@copy($source, $destination)) {
$restoreMeta();
return true;
}
}
return false;
}
/**
* 파일 하나를 삭제합니다 (잠금 대응 단계적 폴백).
*
* @param string $path 삭제할 파일 경로
* @return bool 삭제(또는 옆으로 치우기) 성공 여부
*/
private static function deleteFileWithFallback(string $path): bool
{
if (@unlink($path)) {
return true;
}
@chmod($path, 0666);
if (@unlink($path)) {
return true;
}
// 삭제가 막힌 경우 옆으로 치워 원래 이름을 비운다
$aside = $path.'.g7stale_'.uniqid();
if (@rename($path, $aside)) {
@unlink($aside);
return true;
}
return false;
}
/**
* 대상 디렉토리에서 소스에 존재하지 않는 파일/디렉토리를 제거합니다.
*
* @param string $source 새 버전 콘텐츠 디렉토리
* @param string $dest 활성 디렉토리
* @param array $failures 삭제 실패 경로 수집 (참조)
*/
private static function removeStaleEntries(string $source, string $dest, array &$failures): void
{
if (! is_dir($dest)) {
return;
}
$items = new \FilesystemIterator($dest, \FilesystemIterator::SKIP_DOTS);
foreach ($items as $item) {
$counterpart = $source.DIRECTORY_SEPARATOR.$item->getBasename();
if ($item->isDir()) {
if (is_dir($counterpart)) {
self::removeStaleEntries($counterpart, $item->getPathname(), $failures);
} else {
File::deleteDirectory($item->getPathname());
if (is_dir($item->getPathname())) {
$failures[] = $item->getPathname();
}
}
} elseif (! is_file($counterpart)) {
if (! self::deleteFileWithFallback($item->getPathname())) {
$failures[] = $item->getPathname();
}
}
}
}
/**
* 이전 실패 실행이 남긴 교체용 임시 디렉토리를 정리합니다 (best-effort).
*
* 잠금으로 인해 삭제하지 못한 `_updating_`/`_old_` 디렉토리는 다음 교체 시작
* 시점(잠금이 풀린 뒤일 가능성이 높음)에 다시 삭제를 시도합니다.
* 호출자가 소유한 스테이징 디렉토리(`{identifier}_{Ymd_His}`)는 건드리지 않습니다.
*
* @param string $pendingPath _pending 디렉토리 경로
* @param string $identifier 확장 식별자
*/
private static function cleanupSwapLeftovers(string $pendingPath, string $identifier): void
{
foreach (['_updating_', '_old_'] as $marker) {
$pattern = $pendingPath.DIRECTORY_SEPARATOR.$identifier.$marker.'*';
foreach (glob($pattern) ?: [] as $leftover) {
if (is_dir($leftover)) {
self::bestEffortDeleteDirectory($leftover);
}
}
}
}
/**
* 디렉토리를 삭제하되, 실패해도 예외를 던지지 않습니다.
*
* 잠금으로 삭제하지 못한 디렉토리는 다음 교체 시작 시 잔존물 정리가 재시도합니다.
*
* @param string $path 삭제할 디렉토리 경로
*/
private static function bestEffortDeleteDirectory(string $path): void
{
if (! File::isDirectory($path)) {
return;
}
File::deleteDirectory($path);
if (File::isDirectory($path)) {
Log::info('디렉토리를 완전히 삭제하지 못했습니다 (다음 교체 시 잔존물 정리에서 재시도)', [
'path' => $path,
]);
}
}
/**
* 확장 디렉토리를 삭제합니다.
*
@@ -353,6 +642,7 @@ class ExtensionPendingHelper
*
* @param string $basePath 확장 타입의 기본 경로
* @param string $identifier 확장 식별자
* @return bool _pending 존재 여부
*/
public static function isPending(string $basePath, string $identifier): bool
{
@@ -364,6 +654,7 @@ class ExtensionPendingHelper
*
* @param string $basePath 확장 타입의 기본 경로
* @param string $identifier 확장 식별자
* @return bool _bundled 존재 여부
*/
public static function isBundled(string $basePath, string $identifier): bool
{
@@ -375,6 +666,7 @@ class ExtensionPendingHelper
*
* @param string $basePath 확장 타입의 기본 경로
* @param string $identifier 확장 식별자
* @return string _pending 절대 경로
*/
public static function getPendingPath(string $basePath, string $identifier): string
{
@@ -386,6 +678,7 @@ class ExtensionPendingHelper
*
* @param string $basePath 확장 타입의 기본 경로
* @param string $identifier 확장 식별자
* @return string _bundled 절대 경로
*/
public static function getBundledPath(string $basePath, string $identifier): string
{