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:
1 parent
fcaacad8d1
commit
21f666e4b5
75 files changed
+4767
-951
No files matched your search
@@ -2,9 +2,9 @@
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use App\Seo\SitemapGenerator;
|
||||
use App\Seo\SitemapWriter;
|
||||
use App\Seo\TemplateRouteResolver;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
@@ -475,6 +475,180 @@ class SitemapGeneratorTest extends TestCase
|
||||
$this->assertEquals(1, substr_count($xml, '<url>'));
|
||||
}
|
||||
|
||||
// ─── renderUrlBlock / urlset 헤더·푸터 ──────────────────
|
||||
|
||||
/**
|
||||
* renderUrlBlock()이 단일 언어 <url> 블록을 생성하는지 확인합니다.
|
||||
*/
|
||||
public function test_render_url_block_single_locale(): void
|
||||
{
|
||||
$block = $this->generator->renderUrlBlock([
|
||||
'loc' => 'https://example.test/a',
|
||||
'changefreq' => 'daily',
|
||||
'priority' => 0.8,
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('<loc>https://example.test/a</loc>', $block);
|
||||
$this->assertStringContainsString('<changefreq>daily</changefreq>', $block);
|
||||
$this->assertStringContainsString('<priority>0.8</priority>', $block);
|
||||
$this->assertStringNotContainsString('xhtml:link', $block);
|
||||
$this->assertSame(1, substr_count($block, '<url>'));
|
||||
}
|
||||
|
||||
/**
|
||||
* renderUrlBlock()이 다국어에서 로케일별 블록과 hreflang을 생성하는지 확인합니다.
|
||||
*/
|
||||
public function test_render_url_block_multilingual(): void
|
||||
{
|
||||
config(['app.locale' => 'ko', 'app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$block = $this->generator->renderUrlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
$this->assertSame(2, substr_count($block, '<url>'));
|
||||
$this->assertStringContainsString('<loc>https://example.test/a</loc>', $block);
|
||||
$this->assertStringContainsString('<loc>https://example.test/a?locale=en</loc>', $block);
|
||||
$this->assertStringContainsString('hreflang="x-default"', $block);
|
||||
}
|
||||
|
||||
/**
|
||||
* XML 특수문자가 이스케이프되는지 확인합니다.
|
||||
*/
|
||||
public function test_render_url_block_escapes_xml_special_characters(): void
|
||||
{
|
||||
$block = $this->generator->renderUrlBlock(['loc' => 'https://example.test/a?x=1&y=2']);
|
||||
|
||||
$this->assertStringContainsString('<loc>https://example.test/a?x=1&y=2</loc>', $block);
|
||||
// 이스케이프되지 않은 원본 & 가 남아 있으면 XML 파싱이 깨집니다.
|
||||
$this->assertNotFalse(simplexml_load_string('<urlset>'.$block.'</urlset>'));
|
||||
}
|
||||
|
||||
/**
|
||||
* urlset 헤더/푸터가 로케일 수에 따라 분기되는지 확인합니다.
|
||||
*/
|
||||
public function test_urlset_header_switches_on_multilingual(): void
|
||||
{
|
||||
$this->assertStringNotContainsString('xmlns:xhtml', $this->generator->buildUrlsetHeader());
|
||||
$this->assertSame('</urlset>', $this->generator->buildUrlsetFooter());
|
||||
|
||||
config(['app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$this->assertStringContainsString('xmlns:xhtml', $this->generator->buildUrlsetHeader());
|
||||
}
|
||||
|
||||
// ─── generateToWriter ────────────────────────────────
|
||||
|
||||
/**
|
||||
* generateToWriter()가 기여자 URL을 writer 에 한 건씩 전달하고
|
||||
* 상대 url 을 절대 loc 으로 변환하는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_to_writer_streams_entries_without_cross_merge(): void
|
||||
{
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$contributorA = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorA->shouldReceive('getIdentifier')->andReturn('mod-a');
|
||||
$contributorA->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/a/1'],
|
||||
['url' => '/a/2'],
|
||||
]);
|
||||
|
||||
$contributorB = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorB->shouldReceive('getIdentifier')->andReturn('mod-b');
|
||||
$contributorB->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/b/1'],
|
||||
]);
|
||||
|
||||
$this->generator->registerContributor($contributorA);
|
||||
$this->generator->registerContributor($contributorB);
|
||||
|
||||
$writer = new SpySitemapWriter;
|
||||
$meta = $this->generator->generateToWriter($writer);
|
||||
|
||||
$this->assertTrue($writer->opened);
|
||||
$this->assertTrue($writer->closed);
|
||||
$this->assertTrue($writer->committed);
|
||||
$this->assertSame(['committed' => true], $meta);
|
||||
|
||||
$locs = array_column($writer->entries, 'loc');
|
||||
$this->assertContains(url('/a/1'), $locs);
|
||||
$this->assertContains(url('/a/2'), $locs);
|
||||
$this->assertContains(url('/b/1'), $locs);
|
||||
|
||||
// 'url' 키는 절대 loc 으로 변환되어 남지 않아야 합니다.
|
||||
foreach ($writer->entries as $entry) {
|
||||
$this->assertArrayNotHasKey('url', $entry);
|
||||
$this->assertArrayHasKey('loc', $entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 기여자를 하나씩 소진하여 writer 로 흘려보내는지 확인합니다 (전체 병합 부재 증명).
|
||||
*
|
||||
* 모든 기여자의 URL 을 배열로 모은 뒤 한 번에 쓰는 구현이라면, 두 번째 기여자의
|
||||
* getUrls() 가 호출되는 시점에 writer 는 아직 비어 있다. 이 테스트는 그 구현을 걸러낸다.
|
||||
*/
|
||||
public function test_generate_to_writer_drains_each_contributor_before_calling_the_next(): void
|
||||
{
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$writer = new SpySitemapWriter;
|
||||
|
||||
$contributorA = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorA->shouldReceive('getIdentifier')->andReturn('mod-a');
|
||||
$contributorA->shouldReceive('getUrls')->andReturn([['url' => '/a/1']]);
|
||||
|
||||
$locsSeenWhenBWasAsked = null;
|
||||
|
||||
$contributorB = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorB->shouldReceive('getIdentifier')->andReturn('mod-b');
|
||||
$contributorB->shouldReceive('getUrls')->andReturnUsing(
|
||||
function () use ($writer, &$locsSeenWhenBWasAsked): array {
|
||||
$locsSeenWhenBWasAsked = array_column($writer->entries, 'loc');
|
||||
|
||||
return [['url' => '/b/1']];
|
||||
}
|
||||
);
|
||||
|
||||
$this->generator->registerContributor($contributorA);
|
||||
$this->generator->registerContributor($contributorB);
|
||||
$this->generator->generateToWriter($writer);
|
||||
|
||||
$this->assertNotNull($locsSeenWhenBWasAsked, 'B 기여자가 호출되어야 합니다.');
|
||||
$this->assertContains(
|
||||
url('/a/1'),
|
||||
$locsSeenWhenBWasAsked,
|
||||
'B 를 호출하기 전에 A 의 URL 이 이미 writer 로 전달되어야 합니다 (전체 병합 금지).'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 기여자가 실패해도 다른 기여자의 URL 이 계속 기록되는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_to_writer_isolates_contributor_failure(): void
|
||||
{
|
||||
$failing = Mockery::mock(SitemapContributorInterface::class);
|
||||
$failing->shouldReceive('getIdentifier')->andReturn('failing-module');
|
||||
$failing->shouldReceive('getUrls')->andThrow(new \RuntimeException('DB connection failed'));
|
||||
|
||||
$working = Mockery::mock(SitemapContributorInterface::class);
|
||||
$working->shouldReceive('getIdentifier')->andReturn('working-module');
|
||||
$working->shouldReceive('getUrls')->andReturn([['url' => '/ok']]);
|
||||
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(fn (string $message, array $context) => str_contains($message, 'Sitemap contributor failed')
|
||||
&& $context['contributor'] === 'failing-module');
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($failing);
|
||||
$this->generator->registerContributor($working);
|
||||
|
||||
$writer = new SpySitemapWriter;
|
||||
$this->generator->generateToWriter($writer);
|
||||
|
||||
$this->assertContains(url('/ok'), array_column($writer->entries, 'loc'));
|
||||
}
|
||||
|
||||
// ─── 헬퍼 메서드 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -542,3 +716,76 @@ class SitemapGeneratorTest extends TestCase
|
||||
return $urls;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SitemapWriter 호출을 기록하는 테스트 더블.
|
||||
*
|
||||
* generateToWriter 가 URL 을 한 건씩 스트리밍하는지(전체 배열 병합 없음)와
|
||||
* open/close/commit 생명주기를 검증하기 위해 사용합니다.
|
||||
* 스토리지 없이 동작하도록 부모 생성자를 호출하지 않습니다.
|
||||
*/
|
||||
class SpySitemapWriter extends SitemapWriter
|
||||
{
|
||||
/**
|
||||
* open() 호출 여부
|
||||
*/
|
||||
public bool $opened = false;
|
||||
|
||||
/**
|
||||
* close() 호출 여부
|
||||
*/
|
||||
public bool $closed = false;
|
||||
|
||||
/**
|
||||
* commit() 호출 여부
|
||||
*/
|
||||
public bool $committed = false;
|
||||
|
||||
/**
|
||||
* addUrl() 로 전달된 URL 항목 목록
|
||||
*
|
||||
* @var array<int, array<string, mixed>>
|
||||
*/
|
||||
public array $entries = [];
|
||||
|
||||
/**
|
||||
* SpySitemapWriter 생성자 (의존성 없이 생성).
|
||||
*/
|
||||
public function __construct() {}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function open(): void
|
||||
{
|
||||
$this->opened = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function addUrl(array $entry): void
|
||||
{
|
||||
$this->entries[] = $entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function close(): array
|
||||
{
|
||||
$this->closed = true;
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function commit(): array
|
||||
{
|
||||
$this->committed = true;
|
||||
|
||||
return ['committed' => true];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user