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

148 lines
5.1 KiB
PHP

<?php
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;
/**
* Sitemap 재생성 / 상태 조회 서비스.
*
* 큐 잡(GenerateSitemapJob)과 관리자 수동 트리거(SeoCacheController)에서 공통으로 사용합니다.
* 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 을 기록합니다.
*
* @return array{success: bool, status: string, message?: string, data?: array<string, mixed>}
* status: 'updated' | 'disabled' | 'failed'
*/
public function regenerate(): array
{
$enabled = (bool) g7_core_settings('seo.sitemap_enabled', true);
if (! $enabled) {
return [
'success' => false,
'status' => 'disabled',
'message' => 'Sitemap 생성이 비활성화되어 있습니다.',
];
}
HookManager::doAction('core.seo.sitemap.before_regenerate');
try {
$meta = $this->generator->generateToWriter($this->makeWriter());
// 고급 탭(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 = [
'success' => true,
'status' => 'updated',
'message' => 'Sitemap 생성이 완료되었습니다.',
'data' => [
'last_updated_at' => $lastUpdatedAt,
'size_bytes' => $meta['size_bytes'],
'url_count' => $meta['url_count'],
'child_count' => $meta['child_count'],
'ttl' => $ttl,
],
];
HookManager::doAction('core.seo.sitemap.after_regenerate', $result);
return $result;
} catch (\Throwable $e) {
Log::error('[SEO] Sitemap regeneration failed', [
'error' => $e->getMessage(),
]);
$result = [
'success' => false,
'status' => 'failed',
'message' => 'Sitemap 생성에 실패했습니다: '.$e->getMessage(),
];
HookManager::doAction('core.seo.sitemap.after_regenerate_failed', $result);
return $result;
}
}
/**
* 현재 sitemap 의 메타데이터를 반환합니다.
*
* @return array{last_updated_at: ?string}
*/
public function getStatus(): array
{
$lastUpdatedAt = (string) g7_core_settings('seo.sitemap_last_updated_at', '');
return [
'last_updated_at' => $lastUpdatedAt !== '' ? $lastUpdatedAt : null,
];
}
/**
* 설정값을 반영한 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 을 기록합니다.
*
* @param string $iso8601 ISO8601 형식 타임스탬프
*/
private function updateLastUpdatedAt(string $iso8601): void
{
try {
$current = $this->configRepository->getCategory('seo');
$current['sitemap_last_updated_at'] = $iso8601;
$this->configRepository->saveCategory('seo', $current);
} catch (\Throwable $e) {
Log::warning('Sitemap last_updated_at 갱신 실패', ['error' => $e->getMessage()]);
}
}
}