perf(core): 대용량 목록 상한 총 건수·커서 계약 신설 및 요청당 반복 실행 비용 정리

공개 이슈 gnuboard/g7 이 지목한 병목은 "같은 일을 반복 실행한다" 축이다.
응답·행의 무게를 다룬 · 과 겹치지 않는다.

공통 계약 — 총 건수 상한과 페이지 이동 범위는 별개 결정이다. 묶으면 필요 없이
기능이 깎인다. 총 건수만 상한을 받고(파생 테이블 COUNT), "다음" 이동은
per_page + 1 실측으로 끝까지 열어 둔다. 계산이 불가능해지는 것은 마지막 페이지
번호 하나뿐이며 그 사실은 last_page: null 이 알린다. 최신순처럼 실제 컬럼으로
정렬하는 목록은 커서로 전환해 깊이와 무관하게 일정 속도로 이동한다. 관련도순은
계산값 정렬이라 커서 키로 쓸 수 없어 offset 을 유지한다.

계약의 입구는 표준 paginate 와 같은 폭이어야 한다. 관계·쿼리 빌더를 받지 못하면
그 좁은 만큼이 그대로 운영 500 이 되고, 실제로 관리자 알림 목록에서 그렇게 터졌다.
응답 조립도 컬렉션마다 손으로 하면 형태가 늘어나는 순간 없는 값을 부르거나 새
필드를 흘리므로, 형태 판정을 paginationMeta 한 곳에 모았다. 표준 paginate
응답은 필드 단위로 이전과 동일하다.

요청당 반복 비용 — 훅 구독마다 남기던 로그 400줄, 요청당 스무 번 넘던 설정 파일
재읽기, 이미 캐시된 목록의 DB 재조회를 없앴다. 권한 판정은 요청 스코프 메모를 두어
화면 요소마다 나가던 조회를 한 번으로 줄였고, 크로스 요청 캐시는 두지 않아 권한
변경이 종전처럼 다음 요청에 반영된다.

검색 질의는 활성 엔진이 만든다. 저장소가 구체 엔진을 지목하면 플러그인이 등록한
엔진은 호출될 기회 자체를 잃고 오류 없이 다른 방식으로 동작한다. 해석기를 두어
활성 엔진에 위임하고, 전문검색이 없는 DBMS 의 부분일치 폴백도 드라이버명 하드코딩
대신 선언형 config 로 옮겼다.

총 건수가 잘린 목록에서 순번을 역산하면 0 과 음수가 나온다. 지어내지 않고 null 을
돌려주며, 그 원칙을 last_page 와 동일하게 적용했다.
This commit is contained in:
HeuJung committed 2026-08-06 11:13:51 +09:00
1 parent 97ab99b7cd
commit 2ae1972a3b
101 files changed
+6160 -322

No files matched your search

+4 -10
View File
@@ -3,7 +3,6 @@
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
/**
* 활동 로그 컬렉션 리소스
@@ -36,15 +35,10 @@ class ActivityLogCollection extends BaseApiCollection
'data' => $this->mapWithRowNumber(function ($activityLog) {
return (new ActivityLogResource($activityLog))->toArray(request());
}),
'pagination' => $this->resource instanceof LengthAwarePaginator ? [
'current_page' => $this->resource->currentPage(),
'last_page' => $this->resource->lastPage(),
'per_page' => $this->resource->perPage(),
'total' => $this->resource->total(),
'from' => $this->resource->firstItem(),
'to' => $this->resource->lastItem(),
'has_more_pages' => $this->resource->hasMorePages(),
] : null,
// 메타를 손으로 조립하면 정확도 필드(total_relation·total_is_exact·result_cap)가
// 빠진다. 그러면 상한에 걸려 잘린 건수가 화면에서 정확한 값처럼 읽힌다
// (실측: 실제 88,792 건이 "10000건" 으로 표기). 표준 메타 한 곳만 쓴다.
...$this->paginationMeta(),
...($abilities ? ['abilities' => $abilities] : []),
];
}
@@ -36,15 +36,8 @@ class IdentityMessageDefinitionCollection extends BaseApiCollection
'data' => $this->mapWithRowNumber(function ($definition) use ($request) {
return (new IdentityMessageDefinitionResource($definition))->toArray($request);
}, $sortOrder),
'pagination' => [
'current_page' => $this->currentPage(),
'last_page' => $this->lastPage(),
'per_page' => $this->perPage(),
'total' => $this->total(),
'from' => $this->firstItem(),
'to' => $this->lastItem(),
'has_more_pages' => $this->hasMorePages(),
],
// 표준 메타를 쓴다 — 페이지 결과의 형태를 스스로 판정해 그 형태가 아는 값만 낸다.
...$this->paginationMeta(),
...($abilities ? ['abilities' => $abilities] : []),
];
}
+61 -10
View File
@@ -2,10 +2,14 @@
namespace App\Http\Resources;
use App\Contracts\Pagination\BoundedTotalAware;
use App\Helpers\PermissionHelper;
use App\Http\Resources\Traits\HasRowNumber;
use App\Support\Query\BoundedPage;
use Illuminate\Contracts\Pagination\LengthAwarePaginator as LengthAwarePaginatorContract;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Pagination\CursorPaginator;
/**
* API 컬렉션 리소스 기본 클래스
@@ -61,24 +65,71 @@ abstract class BaseApiCollection extends ResourceCollection
* 정확히 판정할 수 있도록 노출합니다. 전체 조회(get) 등 paginator 가 아닌
* 경우에는 빈 배열을 반환하므로 toArray 에서 array_merge 로 안전하게 합칠 수 있습니다.
*
* 페이지 결과는 세 형태 중 하나이며, 형태를 스스로 판정해 그 형태가 실제로 아는
* 값만 내보냅니다. 모르는 값을 0 이나 1 로 채우면 화면이 그것을 사실로 읽습니다.
*
* | 형태 | 예 | total | last_page | 추가 |
* |---|---|---|---|---|
* | 전체건수형 | `paginate()` | 정확 | 정확 | — |
* | 상한형 | {@see BoundedPage} | 정확 또는 하한 | 하한이면 null | `total_relation` `total_is_exact` `result_cap` |
* | 단순형 | `simplePaginate()` / `cursorPaginate()` | 없음 | 없음 | 커서면 `next_cursor` `prev_cursor` |
*
* 기존 필드는 하나도 제거하지 않으므로, 표준 `paginate()` 를 쓰는 기존 컬렉션의
* 응답은 이전과 완전히 동일합니다.
*
* @return array<string, mixed> ['pagination' => [...]] 또는 빈 배열
*/
protected function paginationMeta(): array
{
if (! method_exists($this->resource, 'currentPage')) {
$resource = $this->resource;
if ($resource instanceof CursorPaginator) {
return ['pagination' => $this->cursorPaginationMeta($resource)];
}
if (! method_exists($resource, 'currentPage')) {
return [];
}
$meta = [
'current_page' => $resource->currentPage(),
'per_page' => $resource->perPage(),
'from' => $resource->firstItem(),
'to' => $resource->lastItem(),
'has_more_pages' => $resource->hasMorePages(),
];
// 단순형(simplePaginate)은 총 건수를 아예 세지 않으므로 total/last_page 를 내보내지 않는다.
if ($resource instanceof LengthAwarePaginatorContract) {
$meta['last_page'] = $resource->lastPage();
$meta['total'] = $resource->total();
}
if ($resource instanceof BoundedTotalAware) {
$meta['total_relation'] = $resource->totalRelation()->value;
$meta['total_is_exact'] = $resource->totalRelation()->isExact();
$meta['result_cap'] = $resource->resultCap();
}
return ['pagination' => $meta];
}
/**
* 커서 페이지의 pagination 메타를 만듭니다.
*
* 커서 방식은 총 건수와 페이지 번호를 계산하지 않습니다. 대신 앞뒤 이동 커서를
* 그대로 실어 보내며, 화면은 이 값으로 이전/다음 버튼을 만듭니다.
*
* @param CursorPaginator $resource 커서 페이지 결과
* @return array<string, mixed> pagination 메타
*/
private function cursorPaginationMeta(CursorPaginator $resource): array
{
return [
'pagination' => [
'current_page' => $this->resource->currentPage(),
'last_page' => $this->resource->lastPage(),
'per_page' => $this->resource->perPage(),
'total' => $this->resource->total(),
'from' => $this->resource->firstItem(),
'to' => $this->resource->lastItem(),
'has_more_pages' => $this->resource->hasMorePages(),
],
'per_page' => $resource->perPage(),
'has_more_pages' => $resource->hasMorePages(),
'next_cursor' => $resource->nextCursor()?->encode(),
'prev_cursor' => $resource->previousCursor()?->encode(),
];
}
}
@@ -19,7 +19,7 @@ class NotificationDefinitionCollection extends BaseApiCollection
/**
* 컬렉션을 배열로 변환합니다.
*
* @param Request $request
* @param Request $request
* @return array
*/
public function toArray(Request $request): array
@@ -31,15 +31,8 @@ class NotificationDefinitionCollection extends BaseApiCollection
'data' => $this->mapWithRowNumber(function ($definition) use ($request) {
return (new NotificationDefinitionResource($definition))->toArray($request);
}, $sortOrder),
'pagination' => [
'current_page' => $this->currentPage(),
'last_page' => $this->lastPage(),
'per_page' => $this->perPage(),
'total' => $this->total(),
'from' => $this->firstItem(),
'to' => $this->lastItem(),
'has_more_pages' => $this->hasMorePages(),
],
// 표준 메타를 쓴다 — 페이지 결과의 형태를 스스로 판정해 그 형태가 아는 값만 낸다.
...$this->paginationMeta(),
...($abilities ? ['abilities' => $abilities] : []),
];
}
@@ -19,7 +19,7 @@ class NotificationLogCollection extends BaseApiCollection
/**
* 컬렉션을 배열로 변환합니다.
*
* @param Request $request
* @param Request $request
* @return array
*/
public function toArray(Request $request): array
@@ -31,15 +31,10 @@ class NotificationLogCollection extends BaseApiCollection
'data' => $this->mapWithRowNumber(function ($log) use ($request) {
return (new NotificationLogResource($log))->toArray($request);
}, $sortOrder),
'pagination' => [
'current_page' => $this->resource->currentPage(),
'last_page' => $this->resource->lastPage(),
'per_page' => $this->resource->perPage(),
'total' => $this->resource->total(),
'from' => $this->resource->firstItem(),
'to' => $this->resource->lastItem(),
'has_more_pages' => $this->resource->hasMorePages(),
],
// 표준 메타를 쓴다. 이 목록은 커서 요청이면 CursorPaginator 로, 그 외에는 상한형
// 페이지로 온다. 손으로 조립하면 커서 결과에 없는 total()/lastPage() 를 불러
// 그 요청만 500 이 되고, 상한형에서는 정확도 메타가 빠진다.
...$this->paginationMeta(),
...($abilities ? ['abilities' => $abilities] : []),
];
}
+12 -2
View File
@@ -2,6 +2,7 @@
namespace App\Http\Resources\Traits;
use App\Contracts\Pagination\BoundedTotalAware;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
@@ -57,7 +58,7 @@ trait HasRowNumber
* @param int $total 전체 항목 수
* @param int $perPage 페이지당 항목 수
* @param int $currentPage 현재 페이지 번호
* @return int 계산된 순번
* @return int|null 계산된 순번 (총 건수가 잘린 내림차순이면 null)
*/
protected function calculateRowNumber(
int $index,
@@ -65,13 +66,22 @@ trait HasRowNumber
int $total,
int $perPage,
int $currentPage
): int {
): ?int {
if ($sortOrder === 'asc') {
// 오름차순: 1, 2, 3, ... (페이지별 연속)
// 예: 2페이지 → ((2-1) * 10) + 0 + 1 = 11, 12, 13, ...
// offset 만으로 정해지므로 총 건수가 잘려도 그대로 정확하다.
return (($currentPage - 1) * $perPage) + $index + 1;
}
// 내림차순 순번은 "전체 몇 건 중 몇 번째" 라 총 건수를 알아야 나온다. 총 건수가
// 상한에 걸려 잘렸으면 그 값으로 역산한 순번은 첫 페이지부터 이미 틀리고, 상한을
// 넘어선 페이지에서는 0 과 음수까지 내려간다. 틀린 숫자를 내보내는 것보다
// 내보내지 않는 편이 낫으므로 `last_page` 와 같은 원칙으로 null 을 돌려준다.
if ($this->resource instanceof BoundedTotalAware && ! $this->resource->totalRelation()->isExact()) {
return null;
}
// 내림차순: total, total-1, ... (역순)
// 예: 총 30개, 2페이지 → 30 - ((2-1) * 10) - 0 = 20, 19, 18, ...
return $total - (($currentPage - 1) * $perPage) - $index;
@@ -5,14 +5,16 @@ namespace App\Http\Resources;
use App\Contracts\Repositories\NotificationDefinitionRepositoryInterface;
use Illuminate\Http\Request;
/**
* 알림함 컬렉션
*/
class UserNotificationCollection extends BaseApiCollection
{
/**
* 컬렉션을 배열로 변환합니다.
*
* @param Request $request
* @return array
* @param Request $request HTTP 요청
* @return array<string, mixed> 변환된 배열
*/
public function toArray(Request $request): array
{
@@ -29,15 +31,10 @@ class UserNotificationCollection extends BaseApiCollection
->withTypeLabelMap($typeLabelMap)
->toArray($request);
}, $sortOrder),
'pagination' => [
'current_page' => $this->resource->currentPage(),
'last_page' => $this->resource->lastPage(),
'per_page' => $this->resource->perPage(),
'total' => $this->resource->total(),
'from' => $this->resource->firstItem(),
'to' => $this->resource->lastItem(),
'has_more_pages' => $this->resource->hasMorePages(),
],
// 표준 메타를 쓴다. 손으로 조립하면 페이지 결과의 형태(전체건수형/상한형/단순형)를
// 구분하지 못해, 상한에 걸려 잘린 총 건수가 정확한 값처럼 나가고 마지막 페이지도
// 계산할 수 없는데 숫자가 채워진다.
...$this->paginationMeta(),
];
}
}