Files
Gnuboard7/app/Seo/SeoCacheManager.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

242 lines
5.9 KiB
PHP

<?php
namespace App\Seo;
use App\Contracts\Extension\CacheInterface;
use App\Seo\Contracts\SeoCacheManagerInterface;
use Illuminate\Support\Facades\Log;
class SeoCacheManager implements SeoCacheManagerInterface
{
/**
* 캐시 키 프리픽스 (드라이버 접두사 `g7:core:` 다음에 붙음)
*/
private const CACHE_PREFIX = 'seo.page.';
/**
* 캐시된 URL 인덱스 키
*/
private const INDEX_KEY = 'seo.cached_urls';
public function __construct(private readonly CacheInterface $cache) {}
/**
* {@inheritdoc}
*/
public function get(string $url, string $locale): ?string
{
if (! $this->isEnabled()) {
return null;
}
$key = $this->buildKey($url, $locale);
return $this->cache->get($key);
}
/**
* {@inheritdoc}
*/
public function put(string $url, string $locale, string $html): void
{
if (! $this->isEnabled()) {
return;
}
$key = $this->buildKey($url, $locale);
$ttl = $this->getCacheTtl();
$this->cache->put($key, $html, $ttl);
// URL 인덱스 업데이트
$this->addToIndex($url, $locale, $key);
}
/**
* {@inheritdoc}
*/
public function invalidateByUrl(string $urlPattern): int
{
$count = 0;
$index = $this->getIndex();
foreach ($index as $entry) {
if ($this->matchesPattern($entry['url'], $urlPattern)) {
$this->cache->forget($entry['key']);
$count++;
}
}
if ($count > 0) {
$this->rebuildIndex();
}
return $count;
}
/**
* {@inheritdoc}
*/
public function invalidateByLayout(string $layoutName): int
{
$count = 0;
$index = $this->getIndex();
foreach ($index as $entry) {
if (($entry['layout'] ?? '') === $layoutName) {
$this->cache->forget($entry['key']);
$count++;
}
}
if ($count > 0) {
$this->rebuildIndex();
}
return $count;
}
/**
* {@inheritdoc}
*/
public function clearAll(): void
{
$index = $this->getIndex();
foreach ($index as $entry) {
$this->cache->forget($entry['key']);
}
$this->cache->forget(self::INDEX_KEY);
Log::info('[SEO] All cache cleared', ['count' => count($index)]);
}
/**
* {@inheritdoc}
*/
public function getCachedUrls(): array
{
return array_map(fn ($entry) => $entry['url'], $this->getIndex());
}
/**
* 캐시 키 빌드 (URL + 로케일)
*
* @param string $url URL
* @param string $locale 로케일
* @return string 캐시 키
*/
private function buildKey(string $url, string $locale): string
{
return self::CACHE_PREFIX.md5($url.'|'.$locale);
}
/**
* 캐시 활성화 여부 확인 — 고급 탭 값을 쓰되 SEO 탭에 별도 지정이 있으면 그것이 우선 (D19).
*/
private function isEnabled(): bool
{
return SeoCacheSettings::pageCacheEnabled();
}
/**
* 캐시 TTL (초) — 고급 탭 값을 쓰되 SEO 탭에 별도 지정이 있으면 그것이 우선 (D19).
*/
private function getCacheTtl(): int
{
return SeoCacheSettings::pageCacheTtl();
}
/**
* URL 인덱스에 항목을 추가합니다.
*
* @param string $url URL
* @param string $locale 로케일
* @param string $key 캐시 키
*/
private function addToIndex(string $url, string $locale, string $key): void
{
$index = $this->getIndex();
$index[$key] = [
'url' => $url,
'locale' => $locale,
'key' => $key,
'cached_at' => now()->toIso8601String(),
];
$this->cache->put(self::INDEX_KEY, $index, 86400 * 30); // 30일
}
/**
* 캐시 인덱스를 조회합니다.
*/
private function getIndex(): array
{
return $this->cache->get(self::INDEX_KEY, []);
}
/**
* 유효한 캐시만 남겨 인덱스를 재구성합니다.
*/
private function rebuildIndex(): void
{
$index = $this->getIndex();
$validIndex = [];
foreach ($index as $key => $entry) {
if ($this->cache->has($entry['key'])) {
$validIndex[$key] = $entry;
}
}
$this->cache->put(self::INDEX_KEY, $validIndex, 86400 * 30);
}
/**
* URL이 패턴에 매칭되는지 확인합니다.
*
* @param string $url URL
* @param string $pattern 패턴 (와일드카드 * 지원)
*/
private function matchesPattern(string $url, string $pattern): bool
{
// 와일드카드를 정규식으로 변환
$regex = str_replace(['*', '/'], ['.*', '\/'], $pattern);
return (bool) preg_match('/^'.$regex.'$/', $url);
}
/**
* 캐시 저장 시 레이아웃 정보를 함께 저장합니다.
*
* @param string $url URL
* @param string $locale 로케일
* @param string $html HTML
* @param string $layoutName 레이아웃명
*/
public function putWithLayout(string $url, string $locale, string $html, string $layoutName): void
{
if (! $this->isEnabled()) {
return;
}
$key = $this->buildKey($url, $locale);
$ttl = $this->getCacheTtl();
$this->cache->put($key, $html, $ttl);
// 레이아웃 정보 포함하여 인덱스 업데이트
$index = $this->getIndex();
$index[$key] = [
'url' => $url,
'locale' => $locale,
'key' => $key,
'layout' => $layoutName,
'cached_at' => now()->toIso8601String(),
];
$this->cache->put(self::INDEX_KEY, $index, 86400 * 30);
}
}