Files
Gnuboard7/app/Repositories/SeoCacheStatRepository.php
T
HeuJung 21f666e4b5 feat(seo): 사이트맵 스트리밍 생성 + SEO 캐시 설정 정합화
대용량 사이트에서 사이트맵 생성이 메모리 부족으로 반복 실패하던 문제(공개 )의
1단계로, 전체 URL을 메모리에 적재하던 구조를 스트리밍 분할 생성으로 교체한다.

사이트맵 스트리밍 코어:
- SitemapWriter — 자식 파일 1개 분량만 버퍼링하고 임계 도달 시 flush.
 StorageInterface가 append를 제공하지 않아(put이 전체 덮어쓰기) 택한 구조이며,
 최대 메모리가 "자식 파일 1개 크기"로 유계가 된다. URL 수(50,000)와
 바이트(45MB) 두 임계로 분할해 sitemaps.org 프로토콜을 지킨다.
- 커밋은 _tmp 전량 기록 → live 재배치 → manifest 마지막 기록 순. manifest 존재가
 커밋 완료 신호다. 기존 manifest를 먼저 지우지 않아 스왑 중 봇에게 503이 나가지 않는다.
- SitemapFileStore — 읽기측 + 파일 경로 SSoT. SitemapXmlRenderer — escape 단일 출처.

데이터 접근 계층 정리:
- contributor 3종이 쿼리를 직접 조립하던 것을 Repository 위임으로 전환.
 MySQL 버퍼드 쿼리에서 cursor는 결과셋 전체를 적재하므로 lazyById를 쓴다.
- SeoCacheStatsService → SeoCacheStatRepository 신설 (집계 4쿼리 → 1쿼리).
- audit 룰 service-direct-data-access의 사각 2건 수정 — 확장 디렉토리 정규식이
 상대경로를 매칭하지 못해 *Contributor처럼 접미사 없는 클래스가 전부 미검출이었다.

SEO 캐시 설정 정합화:
- SEO 설정의 캐시 3키가 cache 카테고리 형제 키에 항상 져서 운영자 입력이 조용히
 무시되고 있었다(설정을 cache 카테고리로 이관하며 SEO 탭 옛 칸을 미제거).
 고급 탭을 기준값으로 두되 SEO 탭에 지정이 있으면 오버라이드하도록 SeoCacheSettings
 단일 출처로 정리. "지정 여부"는 null로 판정하므로 기본값을 비웠다.
- 기존 설치는 Upgrade_7_1_0이 이행 — 옛 기본값과 같으면 미설정으로 비우고, 다르면
 운영자 의도로 보아 보존한다.

코어 버전 bump와 루트 CHANGELOG는 계획서 결정(D20)에 따라 마감 단계에서 일괄 수행한다.
2026-07-17 19:59:40 +09:00

136 lines
4.4 KiB
PHP

<?php
namespace App\Repositories;
use App\Contracts\Repositories\SeoCacheStatRepositoryInterface;
use App\Models\SeoCacheStat;
use Carbon\Carbon;
use Illuminate\Contracts\Database\Query\Expression;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
/**
* SEO 캐시 통계 Repository
*
* SEO 캐시 히트/미스 통계의 데이터 접근 계층을 담당합니다.
*/
class SeoCacheStatRepository implements SeoCacheStatRepositoryInterface
{
/**
* 그룹 집계에 허용된 컬럼 목록
*
* @var array<int, string>
*/
private const GROUPABLE_COLUMNS = ['layout_name', 'module_identifier'];
/**
* 캐시 통계 레코드를 기록합니다.
*
* @param array<string, mixed> $attributes 기록할 속성
*/
public function record(array $attributes): void
{
SeoCacheStat::create($attributes);
}
/**
* 전체 캐시 통계를 집계합니다.
*
* @param Carbon|null $since 집계 시작 시점 (null 이면 전체 기간)
* @return array{total: int, hits: int, misses: int, avg_response_time_ms: float|null} 집계 결과
*/
public function aggregate(?Carbon $since = null): array
{
$row = $this->baseQuery($since)
->select($this->aggregateSelects())
->first();
return [
'total' => (int) ($row->total ?? 0),
'hits' => (int) ($row->hits ?? 0),
'misses' => (int) ($row->misses ?? 0),
'avg_response_time_ms' => $row?->avg_response_time_ms !== null
? (float) $row->avg_response_time_ms
: null,
];
}
/**
* 지정한 컬럼으로 그룹화하여 캐시 통계를 집계합니다.
*
* @param string $groupBy 그룹 기준 컬럼 (layout_name | module_identifier)
* @param Carbon|null $since 집계 시작 시점 (null 이면 전체 기간)
* @return array<int, array{group: string|null, total: int, hits: int, misses: int, avg_response_time_ms: float|null}> 그룹별 집계 결과
*
* @throws \InvalidArgumentException 허용되지 않은 그룹 컬럼인 경우
*/
public function aggregateGrouped(string $groupBy, ?Carbon $since = null): array
{
if (! in_array($groupBy, self::GROUPABLE_COLUMNS, true)) {
throw new \InvalidArgumentException(
__('exceptions.seo.sitemap_stat_group_column_unsupported', ['column' => $groupBy])
);
}
return $this->baseQuery($since)
->select(array_merge([$groupBy], $this->aggregateSelects()))
->groupBy($groupBy)
->get()
->map(fn ($row): array => [
'group' => $row->{$groupBy},
'total' => (int) $row->total,
'hits' => (int) $row->hits,
'misses' => (int) $row->misses,
'avg_response_time_ms' => $row->avg_response_time_ms !== null
? (float) $row->avg_response_time_ms
: null,
])
->all();
}
/**
* 기준 시점보다 오래된 통계 레코드를 삭제합니다.
*
* @param Carbon $cutoff 기준 시점
* @return int 삭제된 레코드 수
*/
public function deleteOlderThan(Carbon $cutoff): int
{
return SeoCacheStat::where('created_at', '<', $cutoff)->delete();
}
/**
* 기간 필터가 적용된 기본 쿼리를 반환합니다.
*
* @param Carbon|null $since 집계 시작 시점
* @return Builder 쿼리 빌더
*/
private function baseQuery(?Carbon $since): Builder
{
$query = SeoCacheStat::query();
if ($since) {
$query->since($since);
}
return $query;
}
/**
* 집계 select 절을 반환합니다.
*
* hit/miss 는 단일 순회로 집계하기 위해 조건부 합계를 사용합니다.
*
* @return array<int, Expression> select 표현식 배열
*/
private function aggregateSelects(): array
{
return [
DB::raw('COUNT(*) as total'),
DB::raw("SUM(CASE WHEN type = 'hit' THEN 1 ELSE 0 END) as hits"),
DB::raw("SUM(CASE WHEN type = 'miss' THEN 1 ELSE 0 END) as misses"),
DB::raw("AVG(CASE WHEN type = 'miss' AND response_time_ms IS NOT NULL THEN response_time_ms ELSE NULL END) as avg_response_time_ms"),
];
}
}