perf(core): 레이아웃 목록 응답에서 편집 대상 아닌 본문 제외
레이아웃 코드 편집 화면이 목록을 부를 때 모든 레이아웃의 본문(content)까지 함께 내려받고 있었다. 레이아웃이 많은 템플릿에서는 목록을 여는 것만으로 수십 MB 가 브라우저에 쌓여 화면이 크게 느려졌고, 디버그 모드에서는 탭이 메모리 부족으로 종료됐다. 목록 화면은 본문을 쓰지 않고 선택한 파일 하나만 편집한다. 목록 전용 Resource 를 두어 이름·설명·크기·수정일만 싣고, 본문은 상세 조회에서만 읽는다. 크기는 목록에서 표시하므로 저장소가 길이만 계산해 돌려준다.
This commit is contained in:
1 parent
953616552f
commit
19789433df
9 files changed
+496
-11
No files matched your search
@@ -6,6 +6,7 @@ use App\Enums\LayoutSourceType;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\TemplateLayoutVersion;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Collection as SupportCollection;
|
||||
|
||||
interface LayoutRepositoryInterface
|
||||
{
|
||||
@@ -17,6 +18,17 @@ interface LayoutRepositoryInterface
|
||||
*/
|
||||
public function getByTemplateId(int $templateId): Collection;
|
||||
|
||||
/**
|
||||
* 목록 표시용 경량 레이아웃 행 조회
|
||||
*
|
||||
* 본문(`content`)을 반환에 포함하지 않는다 — 설명·크기 등 본문 파생값만 계산해 담는다.
|
||||
* 편집 대상 본문은 상세 조회가 제공한다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection<int, array> 목록 행 배열 컬렉션
|
||||
*/
|
||||
public function getListByTemplateId(int $templateId): SupportCollection;
|
||||
|
||||
/**
|
||||
* 특정 레이아웃 조회 (템플릿 ID와 이름으로)
|
||||
*
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Exceptions\ConcurrentModificationException;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Requests\Layout\StoreLayoutPreviewRequest;
|
||||
use App\Http\Requests\Layout\UpdateLayoutContentRequest;
|
||||
use App\Http\Resources\LayoutListResource;
|
||||
use App\Http\Resources\LayoutResource;
|
||||
use App\Http\Resources\LayoutVersionResource;
|
||||
use App\Services\LayoutPreviewService;
|
||||
@@ -38,15 +39,19 @@ class LayoutController extends AdminBaseController
|
||||
return $this->notFound('common.not_found');
|
||||
}
|
||||
|
||||
$layouts = $this->layoutService->getLayoutsByTemplateId($template->id);
|
||||
// 목록은 본문(`content`)을 담지 않는 경량 조회를 쓴다 — 파일 목록 화면은 이름·설명·
|
||||
// 크기·수정일만 표시하고, 편집 대상 본문은 상세 엔드포인트가 따로 제공한다.
|
||||
// 종전에는 목록·상세가 같은 Resource 를 공용해 102개 레이아웃의 본문이 전부 실렸고
|
||||
// (응답 18.30MB 중 content 17.41MB), 디버그 모드에서 렌더러가 메모리 한계를 넘었다.
|
||||
$layouts = $this->layoutService->getLayoutListByTemplateId($template->id);
|
||||
|
||||
// 레이아웃 이름 → 라우트 path 매핑 — 코드 편집기가 파일 선택 시 ?route= URL
|
||||
// 동기화 / 위지윅에서 넘어온 ?route= 로 해당 파일 복원에 사용한다.
|
||||
$routePathMap = $this->templateService->getLayoutRoutePathMap($templateName);
|
||||
|
||||
$collection = LayoutResource::collection($layouts);
|
||||
$collection = LayoutListResource::collection($layouts);
|
||||
$collection->collection->transform(
|
||||
fn (LayoutResource $resource) => $resource->withRoutePathMap($routePathMap)
|
||||
fn (LayoutListResource $resource) => $resource->withRoutePathMap($routePathMap)
|
||||
);
|
||||
|
||||
return $this->success('common.success', $collection);
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 레이아웃 **목록** 전용 리소스
|
||||
*
|
||||
* 코드 편집 화면의 파일 목록은 행마다 이름·설명·라우트·크기·수정일·업데이트 표시만 쓴다.
|
||||
* 편집 대상 본문은 선택 시 상세 엔드포인트(`current_layout`)가 따로 받아온다.
|
||||
*
|
||||
* 종전에는 목록·상세가 {@see LayoutResource} 하나를 공용해 목록 응답에도 각 레이아웃의
|
||||
* `content`(본문 전체) · `components` · `data_sources` · `metadata` 가 실렸다.
|
||||
* 실측(sirsoft-admin_basic): 응답 18.30MB 중 `content` 가 17.41MB(95%). 화면은 102개 중
|
||||
* 1개 본문만 필요한데 101개를 더 받아 전역 상태에 상주시켰고, 디버그 모드에서는 그 상태를
|
||||
* 추적하다 렌더러가 메모리 한계를 넘었다.
|
||||
*
|
||||
* 본문에서 파생되는 값(`description` · `size`)은 조회 계층이 미리 계산해 넘긴다 —
|
||||
* 이 리소스는 본문을 보지 않는다.
|
||||
*
|
||||
* @since 7.0.6
|
||||
*/
|
||||
class LayoutListResource extends BaseApiResource
|
||||
{
|
||||
/** @var array<string, string|null> 레이아웃 이름 → 라우트 path 매핑 */
|
||||
private array $routePathMap = [];
|
||||
|
||||
/**
|
||||
* 라우트 path 매핑을 주입합니다.
|
||||
*
|
||||
* @param array<string, string|null> $routePathMap 레이아웃 이름 → 라우트 path
|
||||
* @return $this
|
||||
*/
|
||||
public function withRoutePathMap(array $routePathMap): self
|
||||
{
|
||||
$this->routePathMap = $routePathMap;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 행을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request 요청 객체
|
||||
* @return array 목록 행 데이터
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$name = $this->getValue('name');
|
||||
$size = (int) $this->getValue('size', 0);
|
||||
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'template_id' => $this->getValue('template_id'),
|
||||
'name' => $name,
|
||||
'description' => $this->getValue('description') ?: $name,
|
||||
|
||||
// 이 레이아웃을 사용하는 라우트의 path (routes.json 기준). 파일 선택 시 ?route=
|
||||
// 동기화 / 위지윅에서 넘어온 ?route= 로 해당 파일 복원에 사용.
|
||||
'route_path' => $this->routePathMap[$name] ?? null,
|
||||
|
||||
'size' => $size,
|
||||
'size_formatted' => $this->formatFileSize($size),
|
||||
'has_update' => false,
|
||||
|
||||
// 낙관적 잠금 — 편집 진입 후 저장 요청에 expected_lock_version 으로 전달
|
||||
'lock_version' => (int) $this->getValue('lock_version', 0),
|
||||
|
||||
// 상세 응답(LayoutResource)의 formatTimestamps() 와 같은 규약 — 사용자 timezone
|
||||
// 기준 문자열이다. 원시 ISO 를 그대로 내보내면 목록의 수정일 표기만 형식이 달라진다.
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->toCarbon($this->getValue('created_at'))),
|
||||
'updated_at' => $this->formatDateTimeStringForUser($this->toCarbon($this->getValue('updated_at'))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 값을 Carbon 인스턴스로 변환합니다.
|
||||
*
|
||||
* 경량 조회는 배열 행을 넘기므로 값이 Carbon 일 수도, 문자열일 수도, null 일 수도 있다.
|
||||
*
|
||||
* @param mixed $value 변환할 값
|
||||
* @return Carbon|null 변환된 Carbon 또는 null
|
||||
*/
|
||||
private function toCarbon(mixed $value): ?Carbon
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $value instanceof Carbon ? $value : Carbon::parse($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 크기를 사람이 읽는 단위로 변환합니다.
|
||||
*
|
||||
* @param int $bytes 바이트 수
|
||||
* @return string 변환된 크기 문자열
|
||||
*/
|
||||
private function formatFileSize(int $bytes): string
|
||||
{
|
||||
if ($bytes < 1024) {
|
||||
return $bytes.' B';
|
||||
}
|
||||
|
||||
if ($bytes < 1048576) {
|
||||
return round($bytes / 1024, 1).' KB';
|
||||
}
|
||||
|
||||
return round($bytes / 1048576, 1).' MB';
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,13 @@ use App\Enums\LayoutSourceType;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\TemplateLayoutVersion;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Collection as SupportCollection;
|
||||
|
||||
class LayoutRepository implements LayoutRepositoryInterface
|
||||
{
|
||||
/** @var int 목록 조회 시 본문을 흘려 읽는 청크 크기 */
|
||||
private const LIST_CHUNK_SIZE = 25;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃 조회
|
||||
*
|
||||
@@ -23,6 +27,55 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 표시용 경량 레이아웃 행을 조회합니다.
|
||||
*
|
||||
* 목록 화면은 이름·설명·크기·수정일만 쓰고 본문은 상세 엔드포인트가 따로 제공한다.
|
||||
* 그런데 `getByTemplateId()` 로 전체 컬럼을 읽으면 `content`(레이아웃 본문)까지 전부
|
||||
* 메모리에 올라간다 — sirsoft-admin_basic 기준 102행 합계 17MB 이상이다.
|
||||
*
|
||||
* 여기서는 chunk 로 흘려 읽으며 본문에서 파생되는 값(설명·크기)만 뽑고 본문 자체는
|
||||
* 즉시 버린다. 결과적으로 반환 컬렉션에 본문이 남지 않고, PHP 피크 메모리도 청크
|
||||
* 단위로 묶인다.
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @return Collection<int, array> 목록 행 배열 (id, template_id, name, description, size, lock_version, created_at, updated_at)
|
||||
*/
|
||||
public function getListByTemplateId(int $templateId): SupportCollection
|
||||
{
|
||||
$rows = collect();
|
||||
|
||||
// 순회 커서는 기본키다 — `chunkById` 는 `where id > lastId` 로 다음 페이지를 잡으므로
|
||||
// 여기에 `orderBy('name')` 을 함께 걸면 정렬 순서와 커서 기준이 어긋나 행이 조용히
|
||||
// 누락된다(실측: 102행 중 58행만 반환). 표시 정렬은 순회를 마친 뒤에 적용한다.
|
||||
TemplateLayout::query()
|
||||
->where('template_id', $templateId)
|
||||
->select(['id', 'template_id', 'name', 'content', 'lock_version', 'created_at', 'updated_at'])
|
||||
->chunkById(self::LIST_CHUNK_SIZE, function (Collection $chunk) use ($rows) {
|
||||
foreach ($chunk as $layout) {
|
||||
$content = $layout->content;
|
||||
$contentJson = is_array($content)
|
||||
? json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
|
||||
: '{}';
|
||||
|
||||
$rows->push([
|
||||
'id' => $layout->id,
|
||||
'template_id' => $layout->template_id,
|
||||
'name' => $layout->name,
|
||||
// 본문에서 파생 — 이 값만 남기고 본문은 버린다
|
||||
'description' => $content['meta']['description'] ?? null,
|
||||
'size' => strlen($contentJson),
|
||||
'lock_version' => $layout->lock_version,
|
||||
'created_at' => $layout->created_at,
|
||||
'updated_at' => $layout->updated_at,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
// 표시 정렬은 순회와 분리 — 커서 기준(id)과 섞으면 행이 누락된다
|
||||
return $rows->sortBy('name', SORT_STRING)->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 레이아웃 조회 (템플릿 ID와 이름으로)
|
||||
*
|
||||
|
||||
@@ -1350,6 +1350,28 @@ class LayoutService
|
||||
return $layouts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 표시용 경량 레이아웃 행을 조회합니다.
|
||||
*
|
||||
* 본문을 반환에 담지 않으므로 파일 목록 화면이 편집 대상이 아닌 레이아웃의 본문까지
|
||||
* 내려받는 일이 없다. 편집 대상 본문은 {@see getLayoutByName()} 이 제공한다.
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @return \Illuminate\Support\Collection<int, array> 목록 행 배열 컬렉션
|
||||
*/
|
||||
public function getLayoutListByTemplateId(int $templateId)
|
||||
{
|
||||
// Before 훅 - 레이아웃 목록 조회 전
|
||||
HookManager::doAction('core.layout.before_index', $templateId);
|
||||
|
||||
$rows = $this->layoutRepository->getListByTemplateId($templateId);
|
||||
|
||||
// After 훅 - 레이아웃 목록 조회 후
|
||||
HookManager::doAction('core.layout.after_index', $rows, $templateId);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 레이아웃 조회 (이름으로)
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user