feat(seo): 사이트맵 재생성 진행상황 + 실시간/폴링 UI

관리자 "전체 재생성"을 큐(Full 모드)로 던지고 진행상황을 SEO 탭에서 확인한다.
Reverb ON 이면 방송 채널 구독으로 실시간 갱신, OFF 면 상태 API 폴링으로 폴백한다.

- SitemapProgress 진행상황 스토어(queued→running→writing→completed/failed,
 캐시 TTL 3600, 방송 스로틀) + SitemapManager.getStatus 확장(progress + realtime_enabled)
- GET /api/admin/seo/sitemap/status(core.settings.read) 신규
- 관리자 재생성을 항상 Full 모드로 큐잉 + 진행률 기록, Job 최종 실패 시 progress=failed 고정
- core.admin.seo.sitemap 방송 채널 인증(core.settings.read)
- SEO 탭 진행상황 UI(상태 배지/단계/누적 URL/실시간·폴링 안내) + 폴링 분기
- 재생성 중 누적 URL 표기(replaceAllForContributor 삽입 건수 반환 — count 쿼리 없이 스트림 누적)
- ja 언어팩 진행상황 UI 번역 동기화
This commit is contained in:
HeuJung committed 2026-07-18 18:22:16 +09:00
1 parent 1629684156
commit face022073
29 files changed
+1145 -83

No files matched your search

@@ -56,6 +56,7 @@ interface SitemapUrlRepositoryInterface
*
* @param string $contributor 기여자 식별자
* @param iterable<int, array{loc: string, resource_type?: string, resource_id?: mixed, lastmod?: mixed, changefreq?: ?string, priority?: ?float}> $entries URL 항목 스트림
* @return int 삽입된 행 수 (진행상황 누적 URL 표기용 — count 쿼리 없이 스트림 누적)
*/
public function replaceAllForContributor(string $contributor, iterable $entries): void;
public function replaceAllForContributor(string $contributor, iterable $entries): int;
}
@@ -2,12 +2,14 @@
namespace App\Http\Controllers\Api\Admin;
use App\Enums\SitemapGenerationMode;
use App\Http\Controllers\Api\Base\AdminBaseController;
use App\Http\Requests\Admin\SeoCacheClearRequest;
use App\Jobs\GenerateSitemapJob;
use App\Seo\Contracts\SeoCacheManagerInterface;
use App\Seo\SeoCacheStatsService;
use App\Seo\SitemapManager;
use App\Seo\SitemapProgress;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
@@ -21,7 +23,8 @@ class SeoCacheController extends AdminBaseController
public function __construct(
private SeoCacheStatsService $statsService,
private SeoCacheManagerInterface $cacheManager,
private SitemapManager $sitemapManager
private SitemapManager $sitemapManager,
private SitemapProgress $sitemapProgress
) {
parent::__construct();
}
@@ -111,12 +114,25 @@ class SeoCacheController extends AdminBaseController
return $this->error('seo.sitemap_disabled', 400);
}
GenerateSitemapJob::dispatch();
// 관리자 수동 재생성은 항상 전체(Full) — 현 생성 상태와 무관하게 전량 재생성 (D7)
GenerateSitemapJob::dispatch(SitemapGenerationMode::Full);
return $this->success('seo.sitemap_regenerate_dispatched', [
'status' => 'dispatched',
...$this->sitemapManager->getStatus(),
]);
// 큐 대기 중에도 UI 가 'queued' 를 표시하도록 즉시 기록
$this->sitemapProgress->start(SitemapGenerationMode::Full->value);
return $this->success('seo.sitemap_regenerate_dispatched', $this->sitemapManager->getStatus());
}
/**
* Sitemap 재생성 진행상황과 실시간 연결 가능 여부를 조회합니다.
*
* SEO 탭 진입 시 초기 로드용이며, 폴링(Reverb OFF)일 때 주기적으로 재조회됩니다.
*
* @return JsonResponse 진행상황(progress) + last_updated_at + realtime_enabled 를 포함한 JSON 응답
*/
public function sitemapStatus(): JsonResponse
{
return $this->success('messages.success', $this->sitemapManager->getStatus());
}
/**
+4
View File
@@ -4,6 +4,7 @@ namespace App\Jobs;
use App\Enums\SitemapGenerationMode;
use App\Seo\SitemapManager;
use App\Seo\SitemapProgress;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -108,6 +109,9 @@ class GenerateSitemapJob implements ShouldBeUnique, ShouldQueue
*/
public function failed(\Throwable $exception): void
{
// 잡 최종 실패(재시도 소진/타임아웃) 시 진행상황을 'failed' 로 고정 — 무한 running 방지
app(SitemapProgress::class)->fail($exception->getMessage());
Log::error('[SEO] Sitemap generation failed', [
'error' => $exception->getMessage(),
]);
+6 -1
View File
@@ -92,7 +92,7 @@ class SitemapUrlRepository implements SitemapUrlRepositoryInterface
/**
* {@inheritDoc}
*/
public function replaceAllForContributor(string $contributor, iterable $entries): void
public function replaceAllForContributor(string $contributor, iterable $entries): int
{
// 기여자 스코프 전량 제거 후 청크 삽입. 대용량(수백만) 삽입을 단일 트랜잭션으로
// 감싸면 락/메모리 부담이 크므로, 삭제 후 청크별 삽입으로 유계 메모리를 유지합니다.
@@ -100,6 +100,7 @@ class SitemapUrlRepository implements SitemapUrlRepositoryInterface
$now = now();
$batch = [];
$inserted = 0;
foreach ($entries as $entry) {
$batch[] = $this->toRow(
(string) ($entry['resource_type'] ?? 'unknown'),
@@ -113,13 +114,17 @@ class SitemapUrlRepository implements SitemapUrlRepositoryInterface
if (count($batch) >= self::INSERT_CHUNK) {
SitemapUrl::insert($batch);
$inserted += count($batch);
$batch = [];
}
}
if ($batch !== []) {
SitemapUrl::insert($batch);
$inserted += count($batch);
}
return $inserted;
}
/**
+1
View File
@@ -35,6 +35,7 @@ class SeoServiceProvider extends ServiceProvider
$this->app->singleton(SeoConfigMerger::class);
$this->app->singleton(SitemapFileStore::class);
$this->app->singleton(SitemapIndexer::class);
$this->app->singleton(SitemapProgress::class);
// Sitemap 파일 입출력은 비공개 디스크(local = storage/app/private, serve=false)를 사용합니다.
// public/storage 심볼릭 링크에 의존하지 않고 컨트롤러 스트리밍으로 서빙합니다.
+23 -3
View File
@@ -36,6 +36,7 @@ class SitemapManager
private ConfigRepositoryInterface $configRepository,
private StorageInterface $storage,
private SitemapUrlRepositoryInterface $repository,
private SitemapProgress $progress,
) {}
/**
@@ -70,6 +71,8 @@ class SitemapManager
$this->rebuildStore();
}
$this->progress->writing($this->repository->countVisible());
$meta = $this->generator->generateToWriterFromEntries(
$this->makeWriter(),
$this->streamStoreEntries(),
@@ -98,6 +101,8 @@ class SitemapManager
],
];
$this->progress->complete($meta);
HookManager::doAction('core.seo.sitemap.after_regenerate', $result);
return $result;
@@ -106,6 +111,8 @@ class SitemapManager
'error' => $e->getMessage(),
]);
$this->progress->fail($e->getMessage());
$result = [
'success' => false,
'status' => 'failed',
@@ -119,9 +126,13 @@ class SitemapManager
}
/**
* 현재 sitemap 의 메타데이터를 반환합니다.
* 현재 sitemap 의 메타데이터와 진행상황을 반환합니다.
*
* @return array{last_updated_at: ?string}
* realtime_enabled 는 설정 SSoT(drivers.websocket_enabled)와 실제 적용 config
* (broadcasting.default) 를 함께 확인해 판정합니다 — 프론트가 실시간(구독)/폴링을
* 분기하는 근거입니다.
*
* @return array{last_updated_at: ?string, progress: ?array<string, mixed>, realtime_enabled: bool}
*/
public function getStatus(): array
{
@@ -129,6 +140,9 @@ class SitemapManager
return [
'last_updated_at' => $lastUpdatedAt !== '' ? $lastUpdatedAt : null,
'progress' => $this->progress->get(),
'realtime_enabled' => (bool) g7_core_settings('drivers.websocket_enabled', false)
&& config('broadcasting.default') !== 'null',
];
}
@@ -139,9 +153,15 @@ class SitemapManager
*/
private function rebuildStore(): void
{
// 스트림 삽입 건수를 누적해 running 단계의 "누적 URL 수" 를 표기합니다(D4).
// countVisible() 같은 사전 count 쿼리 없이 삽입 결과만 합산하므로 1.4M 에서도 부담이 없습니다.
$total = 0;
foreach ($this->generator->getContributors() as $contributor) {
try {
$this->repository->replaceAllForContributor(
// 현재 기여자 진입 시점의 누적치(직전 기여자들까지)를 표시합니다.
$this->progress->phase($contributor->getIdentifier(), $total);
$total += $this->repository->replaceAllForContributor(
$contributor->getIdentifier(),
$this->generator->streamContributorEntries($contributor),
);
+210
View File
@@ -0,0 +1,210 @@
<?php
namespace App\Seo;
use App\Contracts\Extension\CacheInterface;
use App\Extension\HookManager;
/**
* Sitemap 재생성 진행상황 스토어.
*
* 재생성 잡/커맨드가 단계(phase)를 기록하면 캐시(seo.sitemap.progress)에 저장하고,
* Reverb 가 활성일 때는 관리자 채널로 방송해 SEO 탭이 실시간으로 갱신되게 합니다.
* Reverb OFF 시 방송은 HookManager 가 자동으로 건너뛰며(분기 불필요), 캐시는 항상
* 기록되므로 프론트가 폴링으로 폴백할 수 있습니다.
*
* 상태 전이: queued → running(기여자별) → writing → completed | failed
* (진행바는 퍼센트가 아닌 단계 기반 — 사전 count 쿼리가 1.4M 에서 부담이므로.)
*/
final class SitemapProgress
{
/**
* 진행상황 캐시 키
*/
public const KEY = 'seo.sitemap.progress';
/**
* 방송 채널명 (관리자 전용)
*/
public const CHANNEL = 'core.admin.seo.sitemap';
/**
* 방송 이벤트명 (클라이언트는 `.` 접두로 수신)
*/
public const EVENT = 'sitemap.progress.updated';
/**
* 진행상황 캐시 TTL (초) — 잡이 하드 kill 로 죽어도 이 시간 후 자동 만료(무한 running 방지)
*/
private const TTL = 3600;
/**
* URL 누적 방송 간격 — 같은 단계에서 urls 만 증가할 때 이 간격마다만 방송(방송 폭주 방지)
*/
private const BROADCAST_URL_INTERVAL = 5000;
/**
* 마지막으로 방송한 시점의 누적 URL 수
*/
private int $lastBroadcastUrls = 0;
public function __construct(private CacheInterface $cache) {}
/**
* 재생성 예약을 기록합니다(큐 대기 중에도 UI 가 'queued' 를 표시).
*
* @param string $mode 재생성 모드(full|auto|incremental)
*/
public function start(string $mode): void
{
$this->lastBroadcastUrls = 0;
$this->persist([
'status' => 'queued',
'mode' => $mode,
'started_at' => now()->toIso8601String(),
'finished_at' => null,
'phase' => null,
'urls' => 0,
'url_count' => null,
'child_count' => null,
'message' => null,
], broadcast: true);
}
/**
* 현재 처리 중인 기여자 단계를 기록합니다.
*
* 단계가 바뀌면 즉시 방송하고, 같은 단계에서 urls 만 증가하면 간격 스로틀을 적용합니다.
* 캐시는 폴링 정확도를 위해 항상 기록합니다.
*
* @param string $phase 단계 식별자(기여자 identifier)
* @param int|null $urls 누적 URL 수(선택)
*/
public function phase(string $phase, ?int $urls = null): void
{
$state = $this->current();
$phaseChanged = ($state['phase'] ?? null) !== $phase;
$state['status'] = 'running';
$state['phase'] = $phase;
if ($urls !== null) {
$state['urls'] = $urls;
}
$broadcast = $phaseChanged
|| ($urls !== null && ($urls - $this->lastBroadcastUrls) >= self::BROADCAST_URL_INTERVAL);
$this->persist($state, broadcast: $broadcast);
if ($broadcast) {
$this->lastBroadcastUrls = (int) ($state['urls'] ?? 0);
}
}
/**
* 파일 작성 단계를 기록합니다.
*
* @param int|null $urls 작성 대상 누적 URL 수(선택)
*/
public function writing(?int $urls = null): void
{
$state = $this->current();
$state['status'] = 'writing';
$state['phase'] = null;
if ($urls !== null) {
$state['urls'] = $urls;
}
$this->persist($state, broadcast: true);
}
/**
* 재생성 완료를 기록합니다.
*
* @param array<string, mixed> $meta 생성 메타(url_count, child_count 등)
*/
public function complete(array $meta): void
{
$state = $this->current();
$state['status'] = 'completed';
$state['phase'] = null;
$state['finished_at'] = now()->toIso8601String();
$state['url_count'] = $meta['url_count'] ?? null;
$state['child_count'] = $meta['child_count'] ?? null;
$state['urls'] = $meta['url_count'] ?? ($state['urls'] ?? 0);
$state['message'] = null;
$this->persist($state, broadcast: true);
}
/**
* 재생성 실패를 기록합니다(무한 running 방지).
*
* @param string $message 실패 메시지
*/
public function fail(string $message): void
{
$state = $this->current();
$state['status'] = 'failed';
$state['phase'] = null;
$state['finished_at'] = now()->toIso8601String();
$state['message'] = $message;
$this->persist($state, broadcast: true);
}
/**
* 현재 진행상황을 반환합니다(폴링/초기 로드용).
*
* @return array<string, mixed>|null 진행상황 또는 아직 실행 이력이 없으면 null
*/
public function get(): ?array
{
$state = $this->cache->get(self::KEY);
return is_array($state) ? $state : null;
}
/**
* 현재 진행상황을 반환하되, 없으면 기본 골격을 돌려줍니다(부분 갱신 병합용).
*
* @return array<string, mixed> 진행상황 골격
*/
private function current(): array
{
return $this->get() ?? [
'status' => 'idle',
'mode' => null,
'started_at' => null,
'finished_at' => null,
'phase' => null,
'urls' => 0,
'url_count' => null,
'child_count' => null,
'message' => null,
];
}
/**
* 진행상황을 캐시에 기록하고, 필요 시 관리자 채널로 방송합니다.
*
* 방송 payload 는 상태 API 응답의 `data` 형태(`progress` + `realtime_enabled`)와 동형입니다.
* websocket 데이터소스가 `target_source` 로 대상 소스를 통째로 교체하므로, 동형이어야
* 형제 필드(realtime_enabled)를 잃지 않고 UI 바인딩이 유지됩니다(D27).
*
* @param array<string, mixed> $state 진행상황 상태
* @param bool $broadcast 방송 여부(스로틀 판정 결과)
*/
private function persist(array $state, bool $broadcast): void
{
$this->cache->put(self::KEY, $state, self::TTL);
if ($broadcast) {
HookManager::broadcast(self::CHANNEL, self::EVENT, [
'realtime_enabled' => true,
'progress' => $state,
]);
}
}
}