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)에 따라 마감 단계에서 일괄 수행한다.
This commit is contained in:
HeuJung committed 2026-07-17 19:59:40 +09:00
1 parent fcaacad8d1
commit 21f666e4b5
75 files changed
+4767 -951

No files matched your search

@@ -0,0 +1,43 @@
<?php
namespace App\Contracts\Repositories;
use Carbon\Carbon;
/**
* SEO 캐시 통계 Repository 인터페이스
*/
interface SeoCacheStatRepositoryInterface
{
/**
* 캐시 통계 레코드를 기록합니다.
*
* @param array<string, mixed> $attributes 기록할 속성 (url, locale, layout_name, module_identifier, type, response_time_ms)
*/
public function record(array $attributes): void;
/**
* 전체 캐시 통계를 집계합니다.
*
* @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;
/**
* 지정한 컬럼으로 그룹화하여 캐시 통계를 집계합니다.
*
* @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}> 그룹별 집계 결과
*/
public function aggregateGrouped(string $groupBy, ?Carbon $since = null): array;
/**
* 기준 시점보다 오래된 통계 레코드를 삭제합니다.
*
* @param Carbon $cutoff 기준 시점
* @return int 삭제된 레코드 수
*/
public function deleteOlderThan(Carbon $cutoff): int;
}
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Public;
use App\Contracts\Extension\CacheInterface;
use App\Http\Controllers\Controller;
use App\Seo\SeoCacheSettings;
use App\Seo\SitemapGenerator;
use Illuminate\Http\Response;
@@ -22,6 +23,7 @@ class SitemapController extends Controller
*
* @param SitemapGenerator $generator Sitemap 생성기
* @param CacheInterface $cache 코어 캐시 드라이버
* @return Response Sitemap XML 응답
*/
public function index(SitemapGenerator $generator, CacheInterface $cache): Response
{
@@ -34,8 +36,8 @@ class SitemapController extends Controller
if (! $xml) {
$xml = $generator->generate();
$ttl = (int) g7_core_settings('cache.seo_sitemap_ttl', g7_core_settings('seo.sitemap_cache_ttl', 86400));
$cache->put('seo.sitemap', $xml, $ttl);
// 고급 탭(cache.seo_sitemap_ttl)이 메인, SEO 탭에 별도 지정이 있으면 그것이 우선 (D19)
$cache->put('seo.sitemap', $xml, SeoCacheSettings::sitemapCacheTtl());
}
return response($xml, 200, [
+5
View File
@@ -32,6 +32,7 @@ use App\Contracts\Repositories\PluginRepositoryInterface;
use App\Contracts\Repositories\RoleRepositoryInterface;
use App\Contracts\Repositories\ScheduleHistoryRepositoryInterface;
use App\Contracts\Repositories\ScheduleRepositoryInterface;
use App\Contracts\Repositories\SeoCacheStatRepositoryInterface;
use App\Contracts\Repositories\SystemConfigRepositoryInterface;
use App\Contracts\Repositories\TemplateCustomTranslationRepositoryInterface;
use App\Contracts\Repositories\TemplateLayoutAttachmentRepositoryInterface;
@@ -79,6 +80,7 @@ use App\Repositories\PluginRepository;
use App\Repositories\RoleRepository;
use App\Repositories\ScheduleHistoryRepository;
use App\Repositories\ScheduleRepository;
use App\Repositories\SeoCacheStatRepository;
use App\Repositories\SystemConfigRepository;
use App\Repositories\TemplateCustomTranslationRepository;
use App\Repositories\TemplateLayoutAttachmentRepository;
@@ -216,6 +218,9 @@ class CoreServiceProvider extends ServiceProvider
$this->app->bind(NotificationRepositoryInterface::class, NotificationRepository::class);
$this->app->bind(NotificationTemplateRepositoryInterface::class, NotificationTemplateRepository::class);
// SEO Repository 바인딩
$this->app->bind(SeoCacheStatRepositoryInterface::class, SeoCacheStatRepository::class);
// IdentityVerification Repository 바인딩
$this->app->bind(IdentityVerificationLogRepositoryInterface::class, IdentityVerificationLogRepository::class);
$this->app->bind(IdentityPolicyRepositoryInterface::class, IdentityPolicyRepository::class);
+135
View File
@@ -0,0 +1,135 @@
<?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"),
];
}
}
+4 -4
View File
@@ -133,19 +133,19 @@ class SeoCacheManager implements SeoCacheManagerInterface
}
/**
* 캐시 활성화 여부 확인
* 캐시 활성화 여부 확인 — 고급 탭 값을 쓰되 SEO 탭에 별도 지정이 있으면 그것이 우선 (D19).
*/
private function isEnabled(): bool
{
return (bool) g7_core_settings('cache.seo_enabled', g7_core_settings('seo.cache_enabled', true));
return SeoCacheSettings::pageCacheEnabled();
}
/**
* 캐시 TTL (초) — g7_core_settings('cache.seo_ttl') 우선.
* 캐시 TTL (초) — 고급 탭 값을 쓰되 SEO 탭에 별도 지정이 있으면 그것이 우선 (D19).
*/
private function getCacheTtl(): int
{
return (int) g7_core_settings('cache.seo_ttl', g7_core_settings('seo.cache_ttl', 7200));
return SeoCacheSettings::pageCacheTtl();
}
/**
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Seo;
/**
* SEO 캐시 설정 해석기 (D19 우선순위 규칙의 단일 출처)
*
* 캐시 설정은 두 곳에서 지정할 수 있다:
*
* - 고급 탭 (`cache.*`) — 모든 캐시 설정의 메인(기준값)
* - SEO 탭 (`seo.*`) — 해당 영역에 별도 지정이 있으면 그것이 오버라이드
*
* "별도 지정" 판정은 **null 여부**로 한다 — SEO 탭 값이 null(미설정)이면 고급 탭 값을 따르고,
* 값이 있으면(false / 0 포함) 그 값이 이긴다. `Config::get` 은 키가 존재하면 값이 null 이어도
* 기본값으로 대체하지 않으므로 null 이 "미설정" 신호로 그대로 전달된다.
*
* 이 규칙이 호출처마다 흩어지면 도메인별로 우선순위가 갈라진다(과거 결함의 원인).
* SEO 캐시 설정을 읽는 모든 지점은 이 클래스를 경유한다.
*/
final class SeoCacheSettings
{
/**
* SEO 페이지 캐시 사용 여부
*
* @return bool 캐시 사용 여부
*/
public static function pageCacheEnabled(): bool
{
return (bool) self::resolve('seo.cache_enabled', 'cache.seo_enabled', true);
}
/**
* SEO 페이지 캐시 유지 시간 (초)
*
* @return int 캐시 TTL
*/
public static function pageCacheTtl(): int
{
return (int) self::resolve('seo.cache_ttl', 'cache.seo_ttl', 7200);
}
/**
* Sitemap 캐시 유지 시간 (초)
*
* @return int 캐시 TTL
*/
public static function sitemapCacheTtl(): int
{
return (int) self::resolve('seo.sitemap_cache_ttl', 'cache.seo_sitemap_ttl', 86400);
}
/**
* 오버라이드 → 메인 → 기본값 순으로 설정값을 해석합니다.
*
* @param string $overrideKey SEO 탭 키 (별도 지정 — null 이면 미설정)
* @param string $mainKey 고급 탭 키 (메인)
* @param mixed $fallback 둘 다 없을 때의 최종 기본값
* @return mixed 해석된 설정값
*/
private static function resolve(string $overrideKey, string $mainKey, mixed $fallback): mixed
{
return g7_core_settings($overrideKey) ?? g7_core_settings($mainKey, $fallback);
}
}
+115 -127
View File
@@ -2,26 +2,34 @@
namespace App\Seo;
use App\Models\SeoCacheStat;
use App\Contracts\Repositories\SeoCacheStatRepositoryInterface;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
/**
* SEO 캐시 통계 서비스
*
* 캐시 히트/미스를 기록하고 통계 데이터를 제공합니다.
* 데이터 접근은 Repository 인터페이스에 위임합니다.
*/
class SeoCacheStatsService
{
/**
* SeoCacheStatsService 생성자
*
* @param SeoCacheStatRepositoryInterface $statRepository SEO 캐시 통계 Repository
*/
public function __construct(
private readonly SeoCacheStatRepositoryInterface $statRepository,
) {}
/**
* 캐시 히트를 기록합니다.
*
* @param string $url 요청 URL
* @param string $locale 로케일
* @param string|null $layoutName 레이아웃명
* @param string|null $moduleIdentifier 모듈 식별자
* @return void
* @param string $url 요청 URL
* @param string $locale 로케일
* @param string|null $layoutName 레이아웃명
* @param string|null $moduleIdentifier 모듈 식별자
*/
public function recordHit(
string $url,
@@ -29,31 +37,23 @@ class SeoCacheStatsService
?string $layoutName = null,
?string $moduleIdentifier = null
): void {
try {
SeoCacheStat::create([
'url' => $url,
'locale' => $locale,
'layout_name' => $layoutName,
'module_identifier' => $moduleIdentifier,
'type' => 'hit',
]);
} catch (\Exception $e) {
Log::warning('[SEO] 캐시 히트 기록 실패', [
'url' => $url,
'error' => $e->getMessage(),
]);
}
$this->record([
'url' => $url,
'locale' => $locale,
'layout_name' => $layoutName,
'module_identifier' => $moduleIdentifier,
'type' => 'hit',
], '[SEO] 캐시 히트 기록 실패');
}
/**
* 캐시 미스를 기록합니다.
*
* @param string $url 요청 URL
* @param string $locale 로케일
* @param string|null $layoutName 레이아웃명
* @param string|null $moduleIdentifier 모듈 식별자
* @param int|null $responseTimeMs 렌더링 소요 시간 (ms)
* @return void
* @param string $url 요청 URL
* @param string $locale 로케일
* @param string|null $layoutName 레이아웃명
* @param string|null $moduleIdentifier 모듈 식별자
* @param int|null $responseTimeMs 렌더링 소요 시간 (ms)
*/
public function recordMiss(
string $url,
@@ -62,142 +62,72 @@ class SeoCacheStatsService
?string $moduleIdentifier = null,
?int $responseTimeMs = null
): void {
try {
SeoCacheStat::create([
'url' => $url,
'locale' => $locale,
'layout_name' => $layoutName,
'module_identifier' => $moduleIdentifier,
'type' => 'miss',
'response_time_ms' => $responseTimeMs,
]);
} catch (\Exception $e) {
Log::warning('[SEO] 캐시 미스 기록 실패', [
'url' => $url,
'error' => $e->getMessage(),
]);
}
$this->record([
'url' => $url,
'locale' => $locale,
'layout_name' => $layoutName,
'module_identifier' => $moduleIdentifier,
'type' => 'miss',
'response_time_ms' => $responseTimeMs,
], '[SEO] 캐시 미스 기록 실패');
}
/**
* 캐시 통계를 조회합니다.
*
* @param Carbon|null $since 조회 시작 시점 (null이면 전체 기간)
* @return array{total_entries: int, hits: int, misses: int, hit_rate: float, avg_response_time_ms: float|null}
* @param Carbon|null $since 조회 시작 시점 (null이면 전체 기간)
* @return array{total_entries: int, hits: int, misses: int, hit_rate: float, avg_response_time_ms: float|null} 캐시 통계
*/
public function getStats(?Carbon $since = null): array
{
$query = SeoCacheStat::query();
if ($since) {
$query->since($since);
}
$total = $query->count();
$hits = (clone $query)->hits()->count();
$misses = (clone $query)->misses()->count();
$avgResponseTime = (clone $query)->misses()
->whereNotNull('response_time_ms')
->avg('response_time_ms');
$stats = $this->statRepository->aggregate($since);
return [
'total_entries' => $total,
'hits' => $hits,
'misses' => $misses,
'hit_rate' => $total > 0 ? round(($hits / $total) * 100, 2) : 0.0,
'avg_response_time_ms' => $avgResponseTime !== null ? round((float) $avgResponseTime, 2) : null,
'total_entries' => $stats['total'],
'hits' => $stats['hits'],
'misses' => $stats['misses'],
'hit_rate' => $this->hitRate($stats['total'], $stats['hits']),
'avg_response_time_ms' => $this->roundOrNull($stats['avg_response_time_ms']),
];
}
/**
* 레이아웃별 캐시 통계를 조회합니다.
*
* @param Carbon|null $since 조회 시작 시점 (null이면 전체 기간)
* @return array<int, array{layout_name: string|null, total: int, hits: int, misses: int, hit_rate: float, avg_response_time_ms: float|null}>
* @param Carbon|null $since 조회 시작 시점 (null이면 전체 기간)
* @return array<int, array{layout_name: string|null, total: int, hits: int, misses: int, hit_rate: float, avg_response_time_ms: float|null}> 레이아웃별 캐시 통계
*/
public function getStatsByLayout(?Carbon $since = null): array
{
$query = SeoCacheStat::query()
->select(
'layout_name',
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")
)
->groupBy('layout_name');
if ($since) {
$query->where('created_at', '>=', $since);
}
return $query->get()->map(function ($row) {
$total = (int) $row->total;
$hits = (int) $row->hits;
return [
'layout_name' => $row->layout_name,
'total' => $total,
'hits' => $hits,
'misses' => (int) $row->misses,
'hit_rate' => $total > 0 ? round(($hits / $total) * 100, 2) : 0.0,
'avg_response_time_ms' => $row->avg_response_time_ms !== null
? round((float) $row->avg_response_time_ms, 2)
: null,
];
})->toArray();
return array_map(
fn (array $row): array => ['layout_name' => $row['group']] + $this->formatGroupRow($row),
$this->statRepository->aggregateGrouped('layout_name', $since),
);
}
/**
* 모듈별 캐시 통계를 조회합니다.
*
* @param Carbon|null $since 조회 시작 시점 (null이면 전체 기간)
* @return array<int, array{module_identifier: string|null, total: int, hits: int, misses: int, hit_rate: float, avg_response_time_ms: float|null}>
* @param Carbon|null $since 조회 시작 시점 (null이면 전체 기간)
* @return array<int, array{module_identifier: string|null, total: int, hits: int, misses: int, hit_rate: float, avg_response_time_ms: float|null}> 모듈별 캐시 통계
*/
public function getStatsByModule(?Carbon $since = null): array
{
$query = SeoCacheStat::query()
->select(
'module_identifier',
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")
)
->groupBy('module_identifier');
if ($since) {
$query->where('created_at', '>=', $since);
}
return $query->get()->map(function ($row) {
$total = (int) $row->total;
$hits = (int) $row->hits;
return [
'module_identifier' => $row->module_identifier,
'total' => $total,
'hits' => $hits,
'misses' => (int) $row->misses,
'hit_rate' => $total > 0 ? round(($hits / $total) * 100, 2) : 0.0,
'avg_response_time_ms' => $row->avg_response_time_ms !== null
? round((float) $row->avg_response_time_ms, 2)
: null,
];
})->toArray();
return array_map(
fn (array $row): array => ['module_identifier' => $row['group']] + $this->formatGroupRow($row),
$this->statRepository->aggregateGrouped('module_identifier', $since),
);
}
/**
* 오래된 통계 레코드를 삭제합니다.
*
* @param int $daysToKeep 보존 기간 (일, 기본값: 30)
* @param int $daysToKeep 보존 기간 (일, 기본값: 30)
* @return int 삭제된 레코드 수
*/
public function cleanup(int $daysToKeep = 30): int
{
$cutoff = Carbon::now()->subDays($daysToKeep);
$deleted = SeoCacheStat::where('created_at', '<', $cutoff)->delete();
$deleted = $this->statRepository->deleteOlderThan(Carbon::now()->subDays($daysToKeep));
Log::info('[SEO] 캐시 통계 정리 완료', [
'deleted' => $deleted,
@@ -206,4 +136,62 @@ class SeoCacheStatsService
return $deleted;
}
/**
* 통계 레코드를 기록하고, 실패해도 요청 흐름을 막지 않습니다.
*
* @param array<string, mixed> $attributes 기록할 속성
* @param string $failureMessage 실패 시 로그 메시지
*/
private function record(array $attributes, string $failureMessage): void
{
try {
$this->statRepository->record($attributes);
} catch (\Exception $e) {
Log::warning($failureMessage, [
'url' => $attributes['url'] ?? null,
'error' => $e->getMessage(),
]);
}
}
/**
* 그룹 집계 행을 응답 형식으로 변환합니다.
*
* @param array{total: int, hits: int, misses: int, avg_response_time_ms: float|null} $row 집계 행
* @return array{total: int, hits: int, misses: int, hit_rate: float, avg_response_time_ms: float|null} 변환된 행
*/
private function formatGroupRow(array $row): array
{
return [
'total' => $row['total'],
'hits' => $row['hits'],
'misses' => $row['misses'],
'hit_rate' => $this->hitRate($row['total'], $row['hits']),
'avg_response_time_ms' => $this->roundOrNull($row['avg_response_time_ms']),
];
}
/**
* 히트율(%)을 계산합니다.
*
* @param int $total 전체 건수
* @param int $hits 히트 건수
* @return float 히트율 (소수점 2자리)
*/
private function hitRate(int $total, int $hits): float
{
return $total > 0 ? round(($hits / $total) * 100, 2) : 0.0;
}
/**
* 값이 있으면 소수점 2자리로 반올림합니다.
*
* @param float|null $value 원본 값
* @return float|null 반올림된 값 (null 이면 null)
*/
private function roundOrNull(?float $value): ?float
{
return $value !== null ? round($value, 2) : null;
}
}
+11
View File
@@ -2,6 +2,8 @@
namespace App\Seo;
use App\Contracts\Extension\StorageInterface;
use App\Extension\Storage\CoreStorageDriver;
use App\Seo\Contracts\SeoCacheManagerInterface;
use App\Seo\Contracts\SeoRendererInterface;
use Illuminate\Support\ServiceProvider;
@@ -28,6 +30,15 @@ class SeoServiceProvider extends ServiceProvider
$this->app->singleton(SeoMetaResolver::class);
$this->app->singleton(SitemapGenerator::class);
$this->app->singleton(SeoConfigMerger::class);
$this->app->singleton(SitemapFileStore::class);
// Sitemap 파일 입출력은 비공개 디스크(local = storage/app/private, serve=false)를 사용합니다.
// public/storage 심볼릭 링크에 의존하지 않고 컨트롤러 스트리밍으로 서빙합니다.
foreach ([SitemapManager::class, SitemapFileStore::class] as $sitemapConsumer) {
$this->app->when($sitemapConsumer)
->needs(StorageInterface::class)
->give(fn () => new CoreStorageDriver('local'));
}
}
/**
+207
View File
@@ -0,0 +1,207 @@
<?php
namespace App\Seo;
use App\Contracts\Extension\StorageInterface;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Sitemap 파일 저장소 (읽기측)
*
* SitemapWriter 가 비공개 디스크에 커밋한 sitemap 인덱스/자식 파일을 조회하고
* 스트리밍 응답으로 반환합니다. public/storage 심볼릭 링크에 의존하지 않으며,
* 자식 파일(최대 50MB)을 메모리에 적재하지 않고 스트리밍합니다.
*
* 디스크 레이아웃(카테고리 cache 하위):
* sitemap/manifest.json 커밋 마커 + 자식 목록 메타
* sitemap/sitemap.xml sitemapindex
* sitemap/sitemap-{n}.xml 자식 sitemap (gzip 시 .xml.gz)
* sitemap/_tmp/ 생성 중 임시 디렉토리 (커밋 시 정리)
*/
class SitemapFileStore
{
/**
* StorageInterface 카테고리
*/
public const CATEGORY = 'cache';
/**
* 커밋된 sitemap 파일 디렉토리 (카테고리 하위 상대 경로)
*/
public const LIVE_DIR = 'sitemap';
/**
* 생성 중 임시 디렉토리 (카테고리 하위 상대 경로)
*/
public const TMP_DIR = 'sitemap/_tmp';
/**
* 커밋 마커 파일명
*/
public const MANIFEST_FILE = 'manifest.json';
/**
* sitemapindex 파일명
*/
public const INDEX_FILE = 'sitemap.xml';
/**
* SitemapFileStore 생성자
*
* @param StorageInterface $storage 비공개 디스크 스토리지 드라이버
*/
public function __construct(
private readonly StorageInterface $storage,
) {}
/**
* 자식 sitemap 파일명을 반환합니다.
*
* 파일명 규칙의 단일 출처이며, SitemapWriter(기록)와 web 라우트(서빙)가 공유합니다.
*
* @param int $n 자식 번호 (1부터)
* @param bool $gzip gzip 압축 여부
* @return string 자식 파일명 (예: sitemap-1.xml, sitemap-1.xml.gz)
*/
public static function childFilename(int $n, bool $gzip = false): string
{
return 'sitemap-'.$n.'.xml'.($gzip ? '.gz' : '');
}
/**
* 자식 sitemap 의 공개 절대 URL 을 반환합니다.
*
* sitemapindex 의 <loc> 값이며, web 라우트 `/sitemap-{n}.xml` 과 대응합니다.
*
* @param int $n 자식 번호 (1부터)
* @param bool $gzip gzip 압축 여부
* @return string 자식 sitemap 절대 URL
*/
public static function childUrl(int $n, bool $gzip = false): string
{
return url('/'.self::childFilename($n, $gzip));
}
/**
* 커밋된 sitemap 세트가 존재하는지 확인합니다.
*
* manifest.json 존재 = 커밋 완료 신호입니다.
*
* @return bool 서빙 가능한 세트 존재 여부
*/
public function exists(): bool
{
return $this->storage->exists(self::CATEGORY, self::LIVE_DIR.'/'.self::MANIFEST_FILE);
}
/**
* manifest 메타데이터를 반환합니다.
*
* @return array{generated_at?: string, url_count?: int, child_count?: int, size_bytes?: int, gzip?: bool, children?: array}|null
* manifest 배열 (없거나 손상 시 null)
*/
public function getManifest(): ?array
{
$raw = $this->storage->get(self::CATEGORY, self::LIVE_DIR.'/'.self::MANIFEST_FILE);
if ($raw === null || $raw === '') {
return null;
}
$decoded = json_decode($raw, true);
if (! is_array($decoded)) {
Log::warning('[SEO] Sitemap manifest 손상', ['path' => self::LIVE_DIR.'/'.self::MANIFEST_FILE]);
return null;
}
return $decoded;
}
/**
* sitemapindex 를 스트리밍 응답으로 반환합니다.
*
* @return StreamedResponse|null 인덱스 스트림 (세트가 없으면 null)
*/
public function indexResponse(): ?StreamedResponse
{
if (! $this->exists()) {
return null;
}
return $this->storage->response(
self::CATEGORY,
self::LIVE_DIR.'/'.self::INDEX_FILE,
self::INDEX_FILE,
['Content-Type' => 'application/xml'],
);
}
/**
* 자식 sitemap 을 스트리밍 응답으로 반환합니다.
*
* 실제 저장된 파일명은 manifest 에서 조회하므로, 생성 이후 gzip 설정이
* 바뀌어도 커밋된 세트를 그대로 서빙합니다.
*
* @param int $n 자식 번호 (1부터)
* @return StreamedResponse|null 자식 스트림 (없으면 null)
*/
public function childResponse(int $n): ?StreamedResponse
{
$filename = $this->childFile($n);
if ($filename === null) {
return null;
}
$headers = ['Content-Type' => 'application/xml'];
if (str_ends_with($filename, '.gz')) {
$headers['Content-Encoding'] = 'gzip';
}
return $this->storage->response(
self::CATEGORY,
self::LIVE_DIR.'/'.$filename,
$filename,
$headers,
);
}
/**
* 커밋된 sitemap 의 생성 시각을 반환합니다.
*
* @return string|null ISO8601 생성 시각 (세트가 없으면 null)
*/
public function lastGeneratedAt(): ?string
{
$manifest = $this->getManifest();
return $manifest['generated_at'] ?? null;
}
/**
* 자식 번호에 해당하는 실제 파일명을 반환합니다.
*
* @param int $n 자식 번호 (1부터)
* @return string|null 파일명 (존재하지 않으면 null)
*/
private function childFile(int $n): ?string
{
if ($n < 1) {
return null;
}
$manifest = $this->getManifest();
$children = $manifest['children'] ?? [];
$filename = $children[$n - 1]['file'] ?? null;
if (! is_string($filename) || $filename === '') {
return null;
}
if (! $this->storage->exists(self::CATEGORY, self::LIVE_DIR.'/'.$filename)) {
return null;
}
return $filename;
}
}
+107 -77
View File
@@ -40,9 +40,108 @@ class SitemapGenerator
$this->contributors[$contributor->getIdentifier()] = $contributor;
}
/**
* 수집한 URL을 SitemapWriter로 스트리밍하여 분할 sitemap 파일을 생성합니다.
*
* 기여자를 하나씩 순회하며 URL을 writer 에 한 건씩 넘기므로
* 전체 URL 배열을 메모리에 병합(array_merge)하지 않습니다.
*
* @param SitemapWriter $writer 분할 기록기
* @return array{generated_at: string, child_count: int, url_count: int, size_bytes: int, gzip: bool, children: array}
* 커밋된 sitemap 메타데이터
*/
public function generateToWriter(SitemapWriter $writer): array
{
$writer->open();
foreach ($this->collectStaticRoutes() as $entry) {
$writer->addUrl($entry);
}
foreach ($this->contributors as $contributor) {
try {
foreach ($this->drain($contributor) as $entry) {
$writer->addUrl($this->normalizeEntry($entry));
}
} catch (\Throwable $e) {
Log::warning('[SEO] Sitemap contributor failed', [
'contributor' => $contributor->getIdentifier(),
'error' => $e->getMessage(),
]);
}
}
$writer->close();
return $writer->commit();
}
/**
* 기여자로부터 URL 항목을 순회 가능한 형태로 가져옵니다.
*
* @param SitemapContributorInterface $contributor Sitemap 기여자
* @return iterable<array<string, mixed>> URL 항목 순회자
*/
private function drain(SitemapContributorInterface $contributor): iterable
{
return $contributor->getUrls();
}
/**
* 기여자 URL 항목의 'url' 키를 'loc'(절대 URL)으로 변환합니다.
*
* @param array<string, mixed> $entry URL 항목
* @return array<string, mixed> 변환된 URL 항목
*/
private function normalizeEntry(array $entry): array
{
if (isset($entry['url']) && ! isset($entry['loc'])) {
$entry['loc'] = url($entry['url']);
unset($entry['url']);
}
return $entry;
}
/**
* URL 항목 하나를 <url> 블록 XML로 렌더링합니다.
*
* XML 이스케이프의 단일 출처는 SitemapXmlRenderer 이며 이 메서드는 위임합니다.
*
* @param array{loc?: string, lastmod?: string, changefreq?: string, priority?: float} $entry URL 항목
* @return string <url> 블록 문자열
*/
public function renderUrlBlock(array $entry): string
{
return SitemapXmlRenderer::fromConfig()->urlBlock($entry);
}
/**
* urlset 여는 태그(XML 선언 포함)를 반환합니다.
*
* @return string urlset 헤더 문자열
*/
public function buildUrlsetHeader(): string
{
return SitemapXmlRenderer::fromConfig()->urlsetHeader();
}
/**
* urlset 닫는 태그를 반환합니다.
*
* @return string urlset 푸터 문자열
*/
public function buildUrlsetFooter(): string
{
return SitemapXmlRenderer::fromConfig()->urlsetFooter();
}
/**
* 전체 Sitemap URL을 수집하여 XML을 생성합니다.
*
* 전체 URL을 메모리에 적재하므로 소규모 사이트 / 하위호환 용도로만 사용합니다.
* 대용량은 generateToWriter() 를 사용합니다.
*
* @return string sitemap XML 문자열
*/
public function generate(): string
@@ -55,16 +154,11 @@ class SitemapGenerator
// 2. 기여자들의 동적 URL 수집
foreach ($this->contributors as $contributor) {
try {
$contributorUrls = $contributor->getUrls();
// 기여자 URL의 'url' 키를 'loc'(절대 URL)으로 변환
foreach ($contributorUrls as &$entry) {
if (isset($entry['url']) && ! isset($entry['loc'])) {
$entry['loc'] = url($entry['url']);
unset($entry['url']);
}
}
unset($entry);
$contributorUrls = array_map(
fn (array $entry): array => $this->normalizeEntry($entry),
$contributor->getUrls(),
);
$urls = array_merge($urls, $contributorUrls);
} catch (\Throwable $e) {
@@ -170,79 +264,15 @@ class SitemapGenerator
*/
private function buildXml(array $urls): string
{
$defaultLocale = config('app.locale');
$supportedLocales = config('app.supported_locales', [$defaultLocale]);
$isMultilingual = count($supportedLocales) > 1;
$renderer = SitemapXmlRenderer::fromConfig();
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
if ($isMultilingual) {
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'."\n";
$xml .= ' xmlns:xhtml="http://www.w3.org/1999/xhtml">'."\n";
} else {
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
}
$xml = $renderer->urlsetHeader();
foreach ($urls as $entry) {
$baseLoc = $entry['loc'];
if ($isMultilingual) {
// 각 로케일별 <url> 항목 생성
foreach ($supportedLocales as $locale) {
$localeLoc = $locale === $defaultLocale
? $baseLoc
: $baseLoc.'?locale='.$locale;
$xml .= ' <url>'."\n";
$xml .= ' <loc>'.htmlspecialchars($localeLoc, ENT_XML1, 'UTF-8').'</loc>'."\n";
if (! empty($entry['lastmod'])) {
$xml .= ' <lastmod>'.htmlspecialchars($entry['lastmod'], ENT_XML1, 'UTF-8').'</lastmod>'."\n";
}
if (! empty($entry['changefreq'])) {
$xml .= ' <changefreq>'.htmlspecialchars($entry['changefreq'], ENT_XML1, 'UTF-8').'</changefreq>'."\n";
}
if (isset($entry['priority'])) {
$xml .= ' <priority>'.number_format((float) $entry['priority'], 1).'</priority>'."\n";
}
// 모든 로케일의 hreflang alternate 링크
foreach ($supportedLocales as $altLocale) {
$altHref = $altLocale === $defaultLocale
? $baseLoc
: $baseLoc.'?locale='.$altLocale;
$xml .= ' <xhtml:link rel="alternate" hreflang="'.htmlspecialchars($altLocale, ENT_XML1, 'UTF-8').'" href="'.htmlspecialchars($altHref, ENT_XML1, 'UTF-8').'"/>'."\n";
}
// x-default = 기본 로케일 URL
$xml .= ' <xhtml:link rel="alternate" hreflang="x-default" href="'.htmlspecialchars($baseLoc, ENT_XML1, 'UTF-8').'"/>'."\n";
$xml .= ' </url>'."\n";
}
} else {
// 단일 언어: 기존 형식 유지
$xml .= ' <url>'."\n";
$xml .= ' <loc>'.htmlspecialchars($baseLoc, ENT_XML1, 'UTF-8').'</loc>'."\n";
if (! empty($entry['lastmod'])) {
$xml .= ' <lastmod>'.htmlspecialchars($entry['lastmod'], ENT_XML1, 'UTF-8').'</lastmod>'."\n";
}
if (! empty($entry['changefreq'])) {
$xml .= ' <changefreq>'.htmlspecialchars($entry['changefreq'], ENT_XML1, 'UTF-8').'</changefreq>'."\n";
}
if (isset($entry['priority'])) {
$xml .= ' <priority>'.number_format((float) $entry['priority'], 1).'</priority>'."\n";
}
$xml .= ' </url>'."\n";
}
$xml .= $renderer->urlBlock($entry);
}
$xml .= '</urlset>';
$xml .= $renderer->urlsetFooter();
return $xml;
}
+44 -9
View File
@@ -3,6 +3,7 @@
namespace App\Seo;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\StorageInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Extension\HookManager;
use Illuminate\Support\Facades\Log;
@@ -11,22 +12,34 @@ use Illuminate\Support\Facades\Log;
* Sitemap 재생성 / 상태 조회 서비스.
*
* 큐 잡(GenerateSitemapJob)과 관리자 수동 트리거(SeoCacheController)에서 공통으로 사용합니다.
* Sitemap XML 을 생성하여 캐시에 저장하고 마지막 업데이트 시각을
* settings 의 seo 카테고리(sitemap_last_updated_at)에 기록합니다.
* Sitemap 을 SitemapWriter 로 스트리밍 생성하여 비공개 디스크에 분할 파일로 커밋하고,
* 마지막 업데이트 시각을 settings 의 seo 카테고리(sitemap_last_updated_at)에 기록합니다.
* 캐시에는 XML 본문이 아니라 메타데이터만 저장합니다.
*/
class SitemapManager
{
/**
* Sitemap 메타데이터 캐시 키
*/
public const META_CACHE_KEY = 'seo.sitemap.meta';
/**
* 구 버전 Sitemap XML 본문 캐시 키 (디스크 서빙 전환으로 폐기 — 잔여분 정리용)
*/
private const LEGACY_XML_CACHE_KEY = 'seo.sitemap';
public function __construct(
private SitemapGenerator $generator,
private CacheInterface $cache,
private ConfigRepositoryInterface $configRepository,
private StorageInterface $storage,
) {}
/**
* Sitemap 을 즉시 생성하여 캐시에 저장하고 last_updated_at 을 기록합니다.
* Sitemap 을 즉시 생성하여 디스크에 커밋하고 last_updated_at 을 기록합니다.
*
* @return array{success: bool, status: string, message?: string, data?: array<string, mixed>}
* status: 'updated' | 'disabled' | 'failed'
* status: 'updated' | 'disabled' | 'failed'
*/
public function regenerate(): array
{
@@ -42,11 +55,16 @@ class SitemapManager
HookManager::doAction('core.seo.sitemap.before_regenerate');
try {
$xml = $this->generator->generate();
$ttl = (int) g7_core_settings('cache.seo_sitemap_ttl', g7_core_settings('seo.sitemap_cache_ttl', 86400));
$this->cache->put('seo.sitemap', $xml, $ttl);
$meta = $this->generator->generateToWriter($this->makeWriter());
$lastUpdatedAt = now()->toIso8601String();
// 고급 탭(cache.seo_sitemap_ttl)이 메인, SEO 탭에 별도 지정이 있으면 그것이 우선 (D19)
$ttl = SeoCacheSettings::sitemapCacheTtl();
// 디스크 서빙 전환 — 캐시에는 메타만 저장하고 구 XML 본문 캐시는 정리합니다.
$this->cache->forget(self::LEGACY_XML_CACHE_KEY);
$this->cache->put(self::META_CACHE_KEY, $meta, $ttl);
$lastUpdatedAt = $meta['generated_at'];
$this->updateLastUpdatedAt($lastUpdatedAt);
$result = [
@@ -55,7 +73,9 @@ class SitemapManager
'message' => 'Sitemap 생성이 완료되었습니다.',
'data' => [
'last_updated_at' => $lastUpdatedAt,
'size_bytes' => strlen($xml),
'size_bytes' => $meta['size_bytes'],
'url_count' => $meta['url_count'],
'child_count' => $meta['child_count'],
'ttl' => $ttl,
],
];
@@ -94,6 +114,21 @@ class SitemapManager
];
}
/**
* 설정값을 반영한 SitemapWriter 를 생성합니다.
*
* @return SitemapWriter 분할 기록기
*/
private function makeWriter(): SitemapWriter
{
return new SitemapWriter(
$this->storage,
SitemapXmlRenderer::fromConfig(),
(int) g7_core_settings('seo.sitemap_urls_per_file', SitemapWriter::HARD_URL_CAP),
(bool) g7_core_settings('seo.sitemap_gzip', false),
);
}
/**
* settings 의 seo 카테고리에 sitemap_last_updated_at 을 기록합니다.
*
+338
View File
@@ -0,0 +1,338 @@
<?php
namespace App\Seo;
use App\Contracts\Extension\StorageInterface;
use Illuminate\Support\Facades\Log;
/**
* Sitemap 파일 기록기 (스트리밍 분할 writer)
*
* URL 을 한 건씩 받아 자식 sitemap 파일로 분할 기록합니다.
* sitemaps.org 프로토콜(파일당 50,000 URL / 50MB)을 준수하며,
* 전체 URL 을 메모리에 적재하지 않습니다.
*
* StorageInterface 는 append 스트림을 제공하지 않고 put() 이 매 호출 파일 전체를
* 덮어쓰므로, 자식 파일 하나 분량만 메모리 버퍼에 쌓았다가 임계 도달 시 flush 합니다.
* 따라서 최대 메모리 사용량은 "자식 파일 1개 크기"로 제한됩니다.
*
* 커밋은 임시 디렉토리(_tmp)에 전량 기록한 뒤 live 로 재배치하고,
* manifest.json 을 마지막에 기록하는 방식으로 수행합니다(manifest = 커밋 마커).
*/
class SitemapWriter
{
/**
* 파일당 URL 수 상한 (sitemaps.org 프로토콜)
*/
public const HARD_URL_CAP = 50000;
/**
* 파일당 바이트 상한 (프로토콜 50MB 에 대한 안전 여유)
*/
public const MAX_FILE_BYTES = 45 * 1024 * 1024;
/**
* 현재 자식 파일 버퍼
*/
private string $buffer = '';
/**
* 현재 자식 파일에 기록된 <url> 블록 수
*/
private int $currentUrlCount = 0;
/**
* 현재 자식 파일 번호 (1부터)
*/
private int $childIndex = 0;
/**
* 현재 자식 파일이 열려 있는지 여부
*/
private bool $childOpen = false;
/**
* 현재 자식 파일의 최신 lastmod
*/
private ?string $childLastmod = null;
/**
* 기록된 자식 파일 목록
*
* @var array<int, array{file: string, loc: string, lastmod: ?string, url_count: int, size_bytes: int}>
*/
private array $children = [];
/**
* 전체 <url> 블록 수
*/
private int $totalUrls = 0;
/**
* 전체 자식 파일 바이트 합계
*/
private int $totalBytes = 0;
/**
* 파일당 URL 수 임계
*/
private readonly int $urlsPerFile;
/**
* SitemapWriter 생성자
*
* @param StorageInterface $storage 비공개 디스크 스토리지 드라이버
* @param SitemapXmlRenderer $renderer XML 조각 렌더러 (SitemapGenerator 와 공유)
* @param int $urlsPerFile 파일당 URL 수 (1 ~ HARD_URL_CAP 로 클램프)
* @param bool $gzip 자식 파일 gzip 압축 여부
*/
public function __construct(
private readonly StorageInterface $storage,
private readonly SitemapXmlRenderer $renderer,
int $urlsPerFile = self::HARD_URL_CAP,
private readonly bool $gzip = false,
) {
$this->urlsPerFile = max(1, min($urlsPerFile, self::HARD_URL_CAP));
}
/**
* 기록을 시작합니다 (임시 디렉토리 초기화 + 상태 리셋).
*/
public function open(): void
{
$this->purgeTmpDirectory();
$this->buffer = '';
$this->currentUrlCount = 0;
$this->childIndex = 0;
$this->childOpen = false;
$this->childLastmod = null;
$this->children = [];
$this->totalUrls = 0;
$this->totalBytes = 0;
}
/**
* URL 항목 하나를 기록합니다.
*
* 임계(URL 수 또는 바이트) 도달 시 현재 자식 파일을 flush 합니다.
*
* @param array{loc?: string, lastmod?: string, changefreq?: string, priority?: float} $entry URL 항목
*/
public function addUrl(array $entry): void
{
$block = $this->renderer->urlBlock($entry);
if ($block === '') {
return;
}
if (! $this->childOpen) {
$this->openNextChild();
}
$this->buffer .= $block;
$this->currentUrlCount += $this->renderer->urlBlockCount();
$this->totalUrls += $this->renderer->urlBlockCount();
$lastmod = $entry['lastmod'] ?? null;
if (is_string($lastmod) && $lastmod !== '' && ($this->childLastmod === null || $lastmod > $this->childLastmod)) {
$this->childLastmod = $lastmod;
}
// static:: 바인딩 — 하위 클래스가 임계값을 낮춰 바이트 분할 분기를 검증할 수 있게 한다
// (45MB 를 실제로 채우지 않고 같은 경로를 태우기 위함).
if ($this->currentUrlCount >= $this->urlsPerFile || strlen($this->buffer) >= static::MAX_FILE_BYTES) {
$this->flushChild();
}
}
/**
* 기록을 마감합니다 (마지막 자식 flush + sitemapindex 기록).
*
* @return array{child_count: int, url_count: int, size_bytes: int, children: array} 기록 메타데이터
*/
public function close(): array
{
// 자식이 하나도 없으면(URL 0건) 빈 urlset 자식 1개를 남겨 인덱스를 유효하게 유지합니다.
if ($this->childOpen || $this->children === []) {
if (! $this->childOpen) {
$this->openNextChild();
}
$this->flushChild();
}
$indexXml = $this->renderer->sitemapIndex($this->children);
$this->putOrFail(SitemapFileStore::TMP_DIR.'/'.SitemapFileStore::INDEX_FILE, $indexXml);
return [
'child_count' => count($this->children),
'url_count' => $this->totalUrls,
'size_bytes' => $this->totalBytes,
'children' => $this->children,
];
}
/**
* 임시 디렉토리의 세트를 live 로 커밋합니다.
*
* 순서: (1) 기존 live 파일 목록 확보 → (2) _tmp 파일을 live 로 재배치 →
* (3) manifest.json 기록(커밋 마커) → (4) 새 세트에 없는 stale 파일 삭제 → (5) _tmp 정리.
*
* @return array{generated_at: string, child_count: int, url_count: int, size_bytes: int, gzip: bool, children: array}
* 커밋된 sitemap 메타데이터
*
* @throws \RuntimeException 파일 기록 실패 시
*/
public function commit(): array
{
$staleFiles = $this->liveFilenames();
$newFiles = [SitemapFileStore::INDEX_FILE];
foreach ($this->children as $child) {
$newFiles[] = $child['file'];
}
foreach ($newFiles as $filename) {
$content = $this->storage->get(SitemapFileStore::CATEGORY, SitemapFileStore::TMP_DIR.'/'.$filename);
if ($content === null) {
throw new \RuntimeException(__('exceptions.seo.sitemap_temp_file_unreadable', ['file' => $filename]));
}
$this->putOrFail(SitemapFileStore::LIVE_DIR.'/'.$filename, $content);
unset($content);
}
$manifest = [
'generated_at' => now()->toIso8601String(),
'child_count' => count($this->children),
'url_count' => $this->totalUrls,
'size_bytes' => $this->totalBytes,
'gzip' => $this->gzip,
'urls_per_file' => $this->urlsPerFile,
'children' => $this->children,
];
// manifest 는 마지막에 기록 — 존재 = 커밋 완료 신호
$this->putOrFail(
SitemapFileStore::LIVE_DIR.'/'.SitemapFileStore::MANIFEST_FILE,
json_encode($manifest, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
);
$this->deleteStaleFiles($staleFiles, $newFiles);
$this->purgeTmpDirectory();
return $manifest;
}
/**
* 임시 디렉토리를 정리합니다.
*
* 정리 실패는 치명적이지 않습니다 — 임시 파일은 이름 기준으로 덮어쓰이고,
* 커밋은 children 목록에 있는 파일만 live 로 옮기므로 잔여 파일이 결과에 섞이지 않습니다.
* 따라서 예외를 전파하지 않고 경고만 남겨 sitemap 생성 자체가 중단되지 않도록 합니다.
*/
private function purgeTmpDirectory(): void
{
try {
$this->storage->deleteDirectory(SitemapFileStore::CATEGORY, SitemapFileStore::TMP_DIR);
} catch (\Throwable $e) {
Log::warning('[SEO] Sitemap 임시 디렉토리 정리 실패 (생성은 계속 진행)', [
'directory' => SitemapFileStore::TMP_DIR,
'error' => $e->getMessage(),
]);
}
}
/**
* 다음 자식 파일을 엽니다 (버퍼에 urlset 헤더 기록).
*/
private function openNextChild(): void
{
$this->childIndex++;
$this->buffer = $this->renderer->urlsetHeader();
$this->currentUrlCount = 0;
$this->childLastmod = null;
$this->childOpen = true;
}
/**
* 현재 자식 파일 버퍼를 임시 디렉토리에 기록하고 버퍼를 비웁니다.
*
* @throws \RuntimeException 파일 기록 실패 시
*/
private function flushChild(): void
{
$this->buffer .= $this->renderer->urlsetFooter();
$filename = SitemapFileStore::childFilename($this->childIndex, $this->gzip);
$content = $this->gzip ? gzencode($this->buffer, 6) : $this->buffer;
if ($content === false) {
throw new \RuntimeException(__('exceptions.seo.sitemap_gzip_failed', ['file' => $filename]));
}
$this->putOrFail(SitemapFileStore::TMP_DIR.'/'.$filename, $content);
$this->children[] = [
'file' => $filename,
'loc' => SitemapFileStore::childUrl($this->childIndex, $this->gzip),
'lastmod' => $this->childLastmod,
'url_count' => $this->currentUrlCount,
'size_bytes' => strlen($content),
];
$this->totalBytes += strlen($content);
$this->buffer = '';
$this->currentUrlCount = 0;
$this->childOpen = false;
}
/**
* live 디렉토리의 파일명 목록을 반환합니다.
*
* @return array<int, string> 파일명 배열 (디렉토리 제외)
*/
private function liveFilenames(): array
{
$paths = $this->storage->files(SitemapFileStore::CATEGORY, SitemapFileStore::LIVE_DIR);
return array_map(static fn (string $path): string => basename($path), $paths);
}
/**
* 새 세트에 포함되지 않은 이전 자식 파일을 삭제합니다.
*
* @param array<int, string> $staleFiles 커밋 전 live 파일명 목록
* @param array<int, string> $newFiles 새 세트 파일명 목록
*/
private function deleteStaleFiles(array $staleFiles, array $newFiles): void
{
$keep = array_merge($newFiles, [SitemapFileStore::MANIFEST_FILE]);
foreach ($staleFiles as $filename) {
if (in_array($filename, $keep, true)) {
continue;
}
$this->storage->delete(SitemapFileStore::CATEGORY, SitemapFileStore::LIVE_DIR.'/'.$filename);
}
}
/**
* 파일을 기록하고 실패 시 예외를 던집니다.
*
* @param string $path 카테고리 하위 상대 경로
* @param string $content 파일 내용
*
* @throws \RuntimeException 기록 실패 시
*/
private function putOrFail(string $path, string $content): void
{
if (! $this->storage->put(SitemapFileStore::CATEGORY, $path, $content)) {
Log::error('[SEO] Sitemap 파일 기록 실패', ['path' => $path]);
throw new \RuntimeException(__('exceptions.seo.sitemap_write_failed', ['path' => $path]));
}
}
}
+249
View File
@@ -0,0 +1,249 @@
<?php
namespace App\Seo;
/**
* Sitemap XML 조각 렌더러
*
* urlset 헤더/푸터, URL 단위 <url> 블록, sitemapindex 를 생성합니다.
* Sitemap XML 의 이스케이프 로직을 이 클래스 한 곳에서만 수행하며(단일 출처),
* SitemapGenerator(수집측)와 SitemapWriter(기록측)가 이 렌더러를 공유합니다.
*
* 다국어(supported_locales 2개 이상)면 URL 하나당 로케일별 <url> 블록을 생성하고
* 각 블록에 xhtml:link hreflang alternate 를 포함합니다.
*/
final class SitemapXmlRenderer
{
/**
* 다국어 여부 (지원 로케일 2개 이상)
*/
private readonly bool $multilingual;
/**
* SitemapXmlRenderer 생성자
*
* @param array<int, string> $supportedLocales 지원 로케일 목록
* @param string $defaultLocale 기본 로케일
*/
public function __construct(
private readonly array $supportedLocales,
private readonly string $defaultLocale,
) {
$this->multilingual = count($this->supportedLocales) > 1;
}
/**
* 애플리케이션 로케일 설정으로 렌더러를 생성합니다.
*
* @return self 설정 기반 렌더러 인스턴스
*/
public static function fromConfig(): self
{
$defaultLocale = (string) config('app.locale');
return new self(
(array) config('app.supported_locales', [$defaultLocale]),
$defaultLocale,
);
}
/**
* 다국어 모드 여부를 반환합니다.
*
* @return bool 지원 로케일이 2개 이상이면 true
*/
public function isMultilingual(): bool
{
return $this->multilingual;
}
/**
* URL 항목 하나가 생성하는 <url> 블록 개수를 반환합니다.
*
* 분할 임계(파일당 URL 수) 계산에 사용됩니다.
*
* @return int 다국어면 로케일 수, 단일 언어면 1
*/
public function urlBlockCount(): int
{
return $this->multilingual ? count($this->supportedLocales) : 1;
}
/**
* urlset 여는 태그(XML 선언 포함)를 반환합니다.
*
* @return string urlset 헤더 문자열
*/
public function urlsetHeader(): string
{
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
if ($this->multilingual) {
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'."\n";
$xml .= ' xmlns:xhtml="http://www.w3.org/1999/xhtml">'."\n";
} else {
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
}
return $xml;
}
/**
* urlset 닫는 태그를 반환합니다.
*
* @return string urlset 푸터 문자열
*/
public function urlsetFooter(): string
{
return '</urlset>';
}
/**
* URL 항목 하나를 <url> 블록으로 렌더링합니다.
*
* 다국어면 로케일 수만큼의 <url> 블록을 이어붙여 반환합니다.
*
* @param array{loc?: string, lastmod?: string, changefreq?: string, priority?: float} $entry URL 항목 (loc 은 절대 URL)
* @return string <url> 블록 문자열 (loc 이 없으면 빈 문자열)
*/
public function urlBlock(array $entry): string
{
$baseLoc = $entry['loc'] ?? '';
if ($baseLoc === '') {
return '';
}
if (! $this->multilingual) {
return $this->renderSingleUrl($baseLoc, $entry);
}
$xml = '';
foreach ($this->supportedLocales as $locale) {
$xml .= $this->renderLocalizedUrl($baseLoc, $entry, (string) $locale);
}
return $xml;
}
/**
* 자식 sitemap 목록을 sitemapindex XML 로 렌더링합니다.
*
* @param array<int, array{loc: string, lastmod?: ?string}> $children 자식 sitemap 목록
* @return string sitemapindex XML 문자열
*/
public function sitemapIndex(array $children): string
{
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
foreach ($children as $child) {
$xml .= ' <sitemap>'."\n";
$xml .= ' <loc>'.$this->escape($child['loc']).'</loc>'."\n";
if (! empty($child['lastmod'])) {
$xml .= ' <lastmod>'.$this->escape($child['lastmod']).'</lastmod>'."\n";
}
$xml .= ' </sitemap>'."\n";
}
$xml .= '</sitemapindex>';
return $xml;
}
/**
* 단일 언어 <url> 블록을 렌더링합니다.
*
* @param string $loc 절대 URL
* @param array $entry URL 항목
* @return string <url> 블록 문자열
*/
private function renderSingleUrl(string $loc, array $entry): string
{
$xml = ' <url>'."\n";
$xml .= ' <loc>'.$this->escape($loc).'</loc>'."\n";
$xml .= $this->renderMetaFields($entry);
$xml .= ' </url>'."\n";
return $xml;
}
/**
* 특정 로케일의 <url> 블록(hreflang alternate 포함)을 렌더링합니다.
*
* @param string $baseLoc 기본 로케일 절대 URL
* @param array $entry URL 항목
* @param string $locale 대상 로케일
* @return string <url> 블록 문자열
*/
private function renderLocalizedUrl(string $baseLoc, array $entry, string $locale): string
{
$xml = ' <url>'."\n";
$xml .= ' <loc>'.$this->escape($this->localizedLoc($baseLoc, $locale)).'</loc>'."\n";
$xml .= $this->renderMetaFields($entry);
// 모든 로케일의 hreflang alternate 링크
foreach ($this->supportedLocales as $altLocale) {
$altHref = $this->localizedLoc($baseLoc, (string) $altLocale);
$xml .= ' <xhtml:link rel="alternate" hreflang="'.$this->escape((string) $altLocale).'" href="'.$this->escape($altHref).'"/>'."\n";
}
// x-default = 기본 로케일 URL
$xml .= ' <xhtml:link rel="alternate" hreflang="x-default" href="'.$this->escape($baseLoc).'"/>'."\n";
$xml .= ' </url>'."\n";
return $xml;
}
/**
* lastmod / changefreq / priority 필드를 렌더링합니다.
*
* @param array $entry URL 항목
* @return string 메타 필드 문자열
*/
private function renderMetaFields(array $entry): string
{
$xml = '';
if (! empty($entry['lastmod'])) {
$xml .= ' <lastmod>'.$this->escape((string) $entry['lastmod']).'</lastmod>'."\n";
}
if (! empty($entry['changefreq'])) {
$xml .= ' <changefreq>'.$this->escape((string) $entry['changefreq']).'</changefreq>'."\n";
}
if (isset($entry['priority'])) {
$xml .= ' <priority>'.number_format((float) $entry['priority'], 1).'</priority>'."\n";
}
return $xml;
}
/**
* 로케일별 URL 을 생성합니다.
*
* @param string $baseLoc 기본 로케일 절대 URL
* @param string $locale 대상 로케일
* @return string 로케일 URL (기본 로케일이면 원본 그대로)
*/
private function localizedLoc(string $baseLoc, string $locale): string
{
return $locale === $this->defaultLocale
? $baseLoc
: $baseLoc.'?locale='.$locale;
}
/**
* XML 특수문자를 이스케이프합니다.
*
* @param string $value 원본 문자열
* @return string 이스케이프된 문자열
*/
private function escape(string $value): string
{
return htmlspecialchars($value, ENT_XML1, 'UTF-8');
}
}