Files
Gnuboard7/app/Repositories/IdentityVerificationLogRepository.php
T
HeuJung 2ae1972a3b perf(core): 대용량 목록 상한 총 건수·커서 계약 신설 및 요청당 반복 실행 비용 정리
공개 이슈 gnuboard/g7 이 지목한 병목은 "같은 일을 반복 실행한다" 축이다.
응답·행의 무게를 다룬 · 과 겹치지 않는다.

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

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

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

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

총 건수가 잘린 목록에서 순번을 역산하면 0 과 음수가 나온다. 지어내지 않고 null 을
돌려주며, 그 원칙을 last_page 와 동일하게 적용했다.
2026-08-06 11:13:51 +09:00

243 lines
9.2 KiB
PHP

<?php
namespace App\Repositories;
use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface;
use App\Enums\IdentityVerificationStatus;
use App\Helpers\TimezoneHelper;
use App\Models\IdentityPolicy;
use App\Models\IdentityVerificationLog;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Support\Query\PaginationLimits;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
/**
* identity_verification_logs Repository 구현체.
*
* @since 7.0.0-beta.4
*/
class IdentityVerificationLogRepository implements IdentityVerificationLogRepositoryInterface
{
use PaginatesWithDeferredJoin;
/**
* 검증 로그를 생성합니다.
*
* @param array $attributes 생성 속성
* @return IdentityVerificationLog 생성된 로그
*/
public function create(array $attributes): IdentityVerificationLog
{
return IdentityVerificationLog::create($attributes);
}
/**
* ID로 검증 로그를 조회합니다.
*
* @param string $id 로그 ID
* @return IdentityVerificationLog|null 조회된 로그 또는 null
*/
public function findById(string $id): ?IdentityVerificationLog
{
return IdentityVerificationLog::find($id);
}
/**
* ID로 검증 로그를 업데이트합니다.
*
* @param string $id 로그 ID
* @param array $attributes 업데이트 속성
* @return bool 업데이트 성공 여부
*/
public function updateById(string $id, array $attributes): bool
{
return IdentityVerificationLog::whereKey($id)->update($attributes) > 0;
}
/**
* 최근에 검증 완료된 로그를 조회합니다.
*
* @param string $purpose 본인인증 목적
* @param int|null $userId 사용자 ID (null 가능)
* @param string|null $targetHash 대상 해시 (null 가능)
* @param int $withinMinutes 조회 범위 (분)
* @return IdentityVerificationLog|null 가장 최근 검증 로그 또는 null
*/
public function findRecentVerified(
string $purpose,
?int $userId,
?string $targetHash,
int $withinMinutes,
): ?IdentityVerificationLog {
$query = IdentityVerificationLog::query()
->where('purpose', $purpose)
->where('status', IdentityVerificationStatus::Verified->value)
->where('verified_at', '>=', Carbon::now()->subMinutes(max(0, $withinMinutes)));
if ($userId !== null) {
$query->where('user_id', $userId);
} elseif ($targetHash !== null) {
$query->where('target_hash', $targetHash);
} else {
return null;
}
return $query->orderByDesc('verified_at')->first();
}
/**
* 미소비된 검증 토큰으로 로그를 조회합니다.
*
* @param string $token 검증 토큰
* @param string $purpose 본인인증 목적
* @return IdentityVerificationLog|null 조회된 로그 또는 null
*/
public function findVerifiedForToken(string $token, string $purpose): ?IdentityVerificationLog
{
return IdentityVerificationLog::query()
->where('verification_token', $token)
->where('purpose', $purpose)
->where('status', IdentityVerificationStatus::Verified->value)
->whereNull('consumed_at')
->first();
}
/**
* 만료 시각이 지난 챌린지를 일괄 만료 처리합니다.
*
* @return int 만료 처리된 행 수
*/
public function expirePastDue(): int
{
return IdentityVerificationLog::query()
->whereIn('status', [
IdentityVerificationStatus::Requested->value,
IdentityVerificationStatus::Sent->value,
])
->where('expires_at', '<', Carbon::now())
->update(['status' => IdentityVerificationStatus::Expired->value]);
}
/**
* 지정된 일수 이전의 로그를 일괄 삭제합니다.
*
* @param int $days 보존 일수
* @return int 삭제된 행 수
*/
public function purgeOlderThan(int $days): int
{
return IdentityVerificationLog::query()
->where('created_at', '<', Carbon::now()->subDays(max(1, $days)))
->delete();
}
/**
* 필터 기반 검증 로그 페이지네이션 결과를 반환합니다.
*
* @param array $filters 검색 필터
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator 페이지네이터
*/
public function search(array $filters, int $perPage = 20)
{
$query = IdentityVerificationLog::query();
// 단일값 + 다중값 — 다중값(*s) 우선, 없으면 단일값 fallback (외부 링크 호환)
$columnMap = [
'provider_id' => 'provider_ids',
'purpose' => 'purposes',
'status' => 'statuses',
'channel' => 'channels',
'origin_type' => 'origin_types',
];
foreach ($columnMap as $singleKey => $multiKey) {
$multi = $filters[$multiKey] ?? null;
if (is_array($multi) && $multi !== []) {
$query->whereIn($singleKey, $multi);
} elseif (! empty($filters[$singleKey])) {
$query->where($singleKey, $filters[$singleKey]);
}
}
// source_type / source_identifier — identity_policies 의 source 컨텍스트로 이력 필터링.
// 직접 컬럼이 아니라 origin_policy_key ∈ (해당 source 의 정책 키 목록) 으로 매칭한다.
if (! empty($filters['source_type'])) {
$query->whereIn('origin_policy_key', function ($q) use ($filters) {
$q->select('key')
->from((new IdentityPolicy)->getTable())
->where('source_type', $filters['source_type']);
if (! empty($filters['source_identifier'])) {
$q->where('source_identifier', $filters['source_identifier']);
}
});
}
if (! empty($filters['user_id'])) {
$query->where('user_id', (int) $filters['user_id']);
}
if (! empty($filters['target_hash'])) {
$query->where('target_hash', $filters['target_hash']);
}
// search + search_type: auto/user_id/target_hash/ip_address/policy_key 통합 검색.
// auto: 입력이 모두 숫자이면 user_id, 그 외(64자 hex 등)는 target_hash 로 라우팅.
if (! empty($filters['search'])) {
$term = (string) $filters['search'];
$type = $filters['search_type'] ?? 'auto';
if ($type === 'user_id' || ($type === 'auto' && ctype_digit($term))) {
$query->where('user_id', (int) $term);
} elseif ($type === 'ip_address') {
$query->where('ip_address', $term);
} elseif ($type === 'policy_key') {
$query->where('origin_policy_key', 'like', $term.'%');
} else {
$query->where('target_hash', $term);
}
}
// 기간 필터는 사이트 타임존 기준으로 해석한다 — created_at 은 UTC 로 저장되고
// 화면은 사이트 타임존으로 보여주므로, 입력 문자열을 그대로 비교하면 하루가 어긋난다.
// 종료값은 시각 없이 날짜만 오는 경우(`<input type="date">`) 그날 끝까지 포함한다.
if (! empty($filters['date_from'])) {
$query->where('created_at', '>=', TimezoneHelper::fromSiteDateTime($filters['date_from']));
}
if (! empty($filters['date_to'])) {
$query->where('created_at', '<=', TimezoneHelper::fromSiteRangeEnd($filters['date_to']));
}
$sortBy = in_array($filters['sort_by'] ?? null, ['created_at', 'attempts'], true)
? $filters['sort_by']
: 'created_at';
$sortOrder = ($filters['sort_order'] ?? 'desc') === 'asc' ? 'asc' : 'desc';
// 본인인증 로그는 계속 쌓이는 이력이라 뒤쪽 페이지에서 OFFSET 비용이 커진다.
// 응답이 요청/응답 payload 를 그대로 노출하므로 컬럼은 좁히지 않고 지연 조인만 적용한다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: [['column' => $sortBy, 'direction' => $sortOrder]],
perPage: $perPage,
// 로그 테이블은 계속 쌓이기만 한다. 총 건수는 상한까지만 세고 "다음" 이동은
// per_page + 1 실측으로 끝까지 열어 둔다 (계산 불가는 마지막 페이지 번호 하나뿐).
resultCap: PaginationLimits::resultCap('admin.identity_logs'),
);
}
/**
* 비회원 검증 로그에 사용자 ID 를 채워넣습니다.
*
* @param string $id 로그 ID
* @param int $userId 사용자 ID
* @return bool 성공 여부 (이미 user_id 가 있으면 false)
*/
public function backfillUserId(string $id, int $userId): bool
{
return IdentityVerificationLog::whereKey($id)
->whereNull('user_id')
->update(['user_id' => $userId]) > 0;
}
}