fix(core,board,ecommerce,page,gdpr,ckeditor5,kginicis,admin_basic,basic): 목록 조회·검증 계층 정비 및 감사 지적 전건 처리
목록 조회 성능 축(깊은 OFFSET·정렬·색인)과 그 검증 계층에서 계획서 전수검수와 3회에 걸친 감사가 지적한 항목을 처리했다. 세부 경위는 의 각 회차 문서에 있다. 검증 계층 — 컨트롤러가 base Request 를 직접 주입받던 확장 13곳을 전용 FormRequest 로 옮겼다. 옮기면서 기존 동작 계약은 그대로 두었다: 상한 초과 limit 을 거부하지 않고 상한까지 반환하던 공개 API, per_page 를 범위로 조정하던 관리자 목록, 미지원 period 를 year 로 해석하던 인기글 목록 모두 종전과 같은 응답을 낸다. 상한/폴백을 rules 로 승격시키면 200 이던 응답이 422 가 되어 기존 링크가 깨지므로, 규칙은 타입만 닫고 클램프·폴백은 접근자가 맡는다. period 는 접근자가 닫힌 집합만 반환해 캐시 키 공간도 함께 닫힌다. ckeditor5 이미지 업로드만 ResponseHelper 봉투를 쓰지 않는다. 응답을 파싱하는 주체가 CDN 으로 로드되는 상위 CKEditor5 43.3.1 의 SimpleUploadAdapter 라 규약을 바꿀 수 없어, 각 응답 지점에 사유를 명시한 면제를 부착하고 근거를 API 문서에 남겼다. 하네스 — 룰 5개의 대상 경로 패턴이 매처와 맞지 않아 번들 확장 컨트롤러가 검사 대상에서 통째로 빠져 있었다. 패턴을 고치자 확장 위반 17건이 드러나 전건 처리했다. severity 오타가 요약 집계 양쪽에 안 잡혀 "0 error" 로 보고되던 문제도 런너 사전 검증으로 막았다. 정렬 게이트 대조 하네스는 관계 정렬 변형만 쓰는 저장소를 탐지하지 못한 채 통과시키고 있었다. 탐지·제외·인자 파싱을 함께 고치고 단위 테스트를 신설했다.
This commit is contained in:
1 parent
5f4a733b3b
commit
b10e89bef0
276 files changed
+12519
-1438
No files matched your search
@@ -71,19 +71,22 @@ class ListAxisRunner implements BenchmarkAxisRunner
|
||||
$notify("비움: {$table}");
|
||||
}
|
||||
|
||||
$columns = $this->existingColumns($table, (array) $profile->option('columns', ['*']));
|
||||
$order = $this->existingOrder($table, (array) $profile->option('order', [['id', 'desc']]));
|
||||
|
||||
if ($options->seed > 0) {
|
||||
$notify("시딩: {$table} ".number_format($options->seed).' 건');
|
||||
$this->seeder->seed(
|
||||
$table,
|
||||
$options->seed,
|
||||
(array) $profile->option('seed_overrides', []),
|
||||
fn (int $inserted, int $total) => $notify(sprintf(' 시딩 %s / %s', number_format($inserted), number_format($total)))
|
||||
fn (int $inserted, int $total) => $notify(sprintf(' 시딩 %s / %s', number_format($inserted), number_format($total))),
|
||||
// 정렬 기준 컬럼은 nullable 이어도 채운다 — 비워두면 합성 행이 전부 동률이 되어
|
||||
// 계측이 정렬 인덱스가 아니라 tie-break 경로를 잰다.
|
||||
array_column($order, 0),
|
||||
);
|
||||
}
|
||||
|
||||
$columns = $this->existingColumns($table, (array) $profile->option('columns', ['*']));
|
||||
$order = $this->existingOrder($table, (array) $profile->option('order', [['id', 'desc']]));
|
||||
|
||||
$rows = [];
|
||||
$notes = [];
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
|
||||
namespace App\Benchmark;
|
||||
|
||||
use App\Benchmark\DTO\BenchmarkProfile;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 목록 프로파일 선언에서 필요한 색인을 도출하고 스키마와 대조합니다.
|
||||
*
|
||||
* 배경: 지연 조인은 inner 가 키 컬럼만 읽게 만들지만, 그 inner 가 **인덱스 순서 그대로**
|
||||
* 끝나야 깊은 OFFSET 이 싸진다. 정렬을 덮는 인덱스가 없으면 inner 도 filesort 로 전체를
|
||||
* 훑으므로 개선 폭이 사라진다. 그런데 어떤 색인이 필요한지는 지금까지 테이블마다 사람이
|
||||
* 손으로 설계했고, 맞는지 검사하는 장치가 없었다.
|
||||
*
|
||||
* 필요한 정보는 이미 계측 프로파일에 선언돼 있다 — `filters` / `order` / `soft_delete` 를
|
||||
* 이으면 그대로 색인 레시피가 된다:
|
||||
*
|
||||
* (등치 필터 컬럼들 → soft_delete 면 deleted_at → 정렬 컬럼들 → 기본키)
|
||||
*
|
||||
* 이 클래스는 그 도출을 한 곳에 두어, 새 목록이 프로파일을 선언하는 순간 필요한 색인이
|
||||
* 자동으로 드러나게 한다. 색인 설계를 사람의 기억이 아니라 이미 있는 선언에 붙이는 것이라
|
||||
* 호출자가 추가로 선언할 것은 없다.
|
||||
*
|
||||
* 등치가 아닌 필터(`in` / `not in` / 범위)는 선행 컬럼에 넣지 않는다 — 선행 컬럼이 등치로
|
||||
* 고정되지 않으면 뒤따르는 정렬 컬럼을 인덱스 순서로 쓸 수 없기 때문이다. 이 판정을 틀리면
|
||||
* "색인이 있는데도 filesort" 라는, 눈으로는 구분되지 않는 상태를 정상으로 보고하게 된다.
|
||||
*/
|
||||
class ListIndexAdvisor
|
||||
{
|
||||
/** 선행 컬럼으로 쓸 수 있는 연산자 (등치만) */
|
||||
private const EQUALITY_OPERATORS = ['='];
|
||||
|
||||
/**
|
||||
* 프로파일이 요구하는 색인 선행 컬럼 목록을 도출합니다.
|
||||
*
|
||||
* @param array<string, mixed> $options 목록 프로파일 옵션
|
||||
* @return array<int, string> 선행 컬럼 순서 (등치 → deleted_at → 정렬 → 기본키)
|
||||
*/
|
||||
public function requiredColumns(array $options, string $keyName = 'id'): array
|
||||
{
|
||||
$leading = [];
|
||||
|
||||
foreach (($options['filters'] ?? []) as $column => $declared) {
|
||||
if (is_array($declared) && count($declared) === 2 && is_string($declared[0])) {
|
||||
// [연산자, 값] 형태 — 등치만 선행 컬럼 자격이 있다
|
||||
if (in_array(strtolower($declared[0]), self::EQUALITY_OPERATORS, true)) {
|
||||
$leading[] = (string) $column;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 값만 준 형태는 등가 비교
|
||||
$leading[] = (string) $column;
|
||||
}
|
||||
|
||||
if ($options['soft_delete'] ?? false) {
|
||||
$leading[] = 'deleted_at';
|
||||
}
|
||||
|
||||
foreach (($options['order'] ?? []) as $spec) {
|
||||
$column = is_array($spec) ? ($spec[0] ?? null) : $spec;
|
||||
|
||||
if (is_string($column) && $column !== '') {
|
||||
$leading[] = $column;
|
||||
}
|
||||
}
|
||||
|
||||
// 정렬 끝에 기본키가 없으면 동률 구간에서 filesort 가 남는다
|
||||
if (end($leading) !== $keyName) {
|
||||
$leading[] = $keyName;
|
||||
}
|
||||
|
||||
return array_values(array_unique($leading));
|
||||
}
|
||||
|
||||
/**
|
||||
* 도출한 색인이 실제 스키마에 있는지 대조합니다.
|
||||
*
|
||||
* @param array<string, mixed> $options 목록 프로파일 옵션
|
||||
* @return array{
|
||||
* table: string|null,
|
||||
* required: array<int, string>,
|
||||
* satisfied_by: string|null,
|
||||
* partial_by: string|null,
|
||||
* status: string
|
||||
* } status: satisfied | tiebreak_missing | missing | table_absent | not_applicable
|
||||
*/
|
||||
public function inspect(array $options, string $keyName = 'id'): array
|
||||
{
|
||||
$table = $options['table'] ?? null;
|
||||
$required = $this->requiredColumns($options, $keyName);
|
||||
|
||||
$result = [
|
||||
'table' => $table,
|
||||
'required' => $required,
|
||||
'satisfied_by' => null,
|
||||
'partial_by' => null,
|
||||
'status' => 'not_applicable',
|
||||
];
|
||||
|
||||
if (! is_string($table) || $table === '') {
|
||||
return $result;
|
||||
}
|
||||
|
||||
if (! Schema::hasTable($table)) {
|
||||
$result['status'] = 'table_absent';
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
// 기본키를 뺀 형태 — 색인은 있으나 tie-break 만 빠진 경우를 구분한다.
|
||||
// 이 둘은 처방이 다르다: 전자는 색인 신설, 후자는 기존 색인에 기본키를 덧붙이는 교체.
|
||||
$withoutKey = $required;
|
||||
if (end($withoutKey) === $keyName) {
|
||||
array_pop($withoutKey);
|
||||
}
|
||||
|
||||
foreach (Schema::getIndexes($table) as $index) {
|
||||
$columns = $index['columns'] ?? [];
|
||||
|
||||
if ($result['satisfied_by'] === null && $this->hasPrefix($columns, $required)) {
|
||||
$result['satisfied_by'] = $index['name'];
|
||||
}
|
||||
|
||||
if ($this->hasPrefix($columns, $withoutKey)) {
|
||||
// UNIQUE 색인은 값이 중복되지 않으므로 그 컬럼만으로 이미 전순서다.
|
||||
// 기본키를 덧붙일 필요가 없고, 붙여도 filesort 가 줄지 않는다.
|
||||
if ($result['satisfied_by'] === null && ($index['unique'] ?? false)) {
|
||||
$result['satisfied_by'] = $index['name'];
|
||||
}
|
||||
|
||||
if ($result['partial_by'] === null) {
|
||||
$result['partial_by'] = $index['name'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$result['status'] = match (true) {
|
||||
$result['satisfied_by'] !== null => 'satisfied',
|
||||
$result['partial_by'] !== null => 'tiebreak_missing',
|
||||
default => 'missing',
|
||||
};
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로파일에 선언된 면제 사유를 돌려줍니다.
|
||||
*
|
||||
* 행 수가 고정되거나 상한이 작아 색인이 불필요한 목록은 프로파일에 사유를 적어 면제한다.
|
||||
* 사유 없는 면제를 허용하지 않는 이유는, 면제가 쌓이면 검사 자체가 무의미해지는데
|
||||
* 사유가 없으면 나중에 그 판단이 여전히 옳은지 확인할 방법이 없기 때문이다.
|
||||
*
|
||||
* @param array<string, mixed> $options 목록 프로파일 옵션
|
||||
* @return string|null 면제 사유 (없으면 null)
|
||||
*/
|
||||
public function exemptionReason(array $options): ?string
|
||||
{
|
||||
$reason = $options['index_exempt'] ?? null;
|
||||
|
||||
return is_string($reason) && trim($reason) !== '' ? trim($reason) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로파일 목록을 한 번에 점검합니다.
|
||||
*
|
||||
* @param array<string, BenchmarkProfile> $profiles 목록 축 프로파일
|
||||
* @return array<int, array<string, mixed>> 프로파일별 점검 결과
|
||||
*/
|
||||
public function inspectAll(array $profiles): array
|
||||
{
|
||||
$rows = [];
|
||||
|
||||
foreach ($profiles as $key => $profile) {
|
||||
$options = $profile->options ?? [];
|
||||
|
||||
$rows[] = array_merge(
|
||||
['profile' => is_string($key) ? $key : $profile->qualifiedKey()],
|
||||
$this->inspect($options),
|
||||
['exemption' => $this->exemptionReason($options)]
|
||||
);
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 인덱스 컬럼이 요구 목록을 선행 프리픽스로 포함하는지 판정합니다.
|
||||
*
|
||||
* @param array<int, string> $columns 인덱스 컬럼 순서
|
||||
* @param array<int, string> $required 요구 선행 컬럼
|
||||
*/
|
||||
private function hasPrefix(array $columns, array $required): bool
|
||||
{
|
||||
if ($required === [] || count($columns) < count($required)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return array_slice(array_values($columns), 0, count($required)) === array_values($required);
|
||||
}
|
||||
}
|
||||
@@ -32,16 +32,18 @@ class SyntheticSeeder
|
||||
* @param int $count 시딩 건수
|
||||
* @param array<string, mixed> $overrides 컬럼별 고정값 (실제 조회 조건과 맞추기 위한 지정)
|
||||
* @param \Closure|null $onProgress 진행 콜백 (int $inserted, int $total)
|
||||
* @param array<int, string> $requiredColumns nullable 이어도 반드시 채울 컬럼 (계측이 정렬 기준으로 삼는 컬럼)
|
||||
*/
|
||||
public function seed(string $table, int $count, array $overrides = [], ?\Closure $onProgress = null): void
|
||||
public function seed(string $table, int $count, array $overrides = [], ?\Closure $onProgress = null, array $requiredColumns = []): void
|
||||
{
|
||||
$fillable = $this->fillableColumns($table);
|
||||
$required = $this->requiredColumnDefinitions($table, $requiredColumns, $fillable);
|
||||
|
||||
$chunk = [];
|
||||
$inserted = 0;
|
||||
|
||||
for ($i = 1; $i <= $count; $i++) {
|
||||
$chunk[] = $this->synthesizeRow($table, $fillable, $overrides, $i);
|
||||
$chunk[] = $this->synthesizeRow($table, array_merge($fillable, $required), $overrides, $i);
|
||||
|
||||
if (count($chunk) >= self::CHUNK_SIZE) {
|
||||
$this->insert($table, $chunk);
|
||||
@@ -94,6 +96,48 @@ class SyntheticSeeder
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 계측이 정렬 기준으로 삼는 컬럼의 정의를 반환합니다.
|
||||
*
|
||||
* `fillableColumns()` 는 "NOT NULL + 기본값 없음" 만 남기므로, Laravel 기본 `timestamps()`
|
||||
* 처럼 nullable 로 선언된 `created_at` 계열은 여기서 빠진다. 그런데 목록 프로파일 대부분이
|
||||
* `created_at` 으로 정렬하므로, 그대로 두면 합성 행이 전부 NULL 동률이 되어 계측이
|
||||
* 정렬 인덱스가 아니라 tie-break 경로를 재게 된다.
|
||||
*
|
||||
* @param string $table 대상 테이블
|
||||
* @param array<int, string> $names 반드시 채울 컬럼명 목록
|
||||
* @param array<int, array<string, mixed>> $already 이미 채우기로 한 컬럼 목록
|
||||
* @return array<int, array<string, mixed>> 추가로 채울 컬럼 정의 목록
|
||||
*/
|
||||
private function requiredColumnDefinitions(string $table, array $names, array $already): array
|
||||
{
|
||||
if ($names === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$covered = array_column($already, 'name');
|
||||
$columns = collect(Schema::getColumns($table))->keyBy('name');
|
||||
|
||||
$extra = [];
|
||||
|
||||
foreach (array_unique($names) as $name) {
|
||||
if (in_array($name, $covered, true) || ! $columns->has($name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$column = $columns->get($name);
|
||||
|
||||
// auto increment 키는 DB 가 채운다
|
||||
if ($column['auto_increment'] ?? false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$extra[] = $column;
|
||||
}
|
||||
|
||||
return $extra;
|
||||
}
|
||||
|
||||
/**
|
||||
* 합성 행 1건을 만듭니다.
|
||||
*
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use App\Search\SearchIndexMaintenanceManager;
|
||||
use App\Services\CoreUpdateService;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -109,6 +110,10 @@ trait BundledExtensionUpdatePrompt
|
||||
// 확장별 전략 오버라이드
|
||||
$strategies = $this->collectPerExtensionStrategies($updates, $globalStrategy, $force);
|
||||
|
||||
// 검색 인덱스 재생성 여부 — 인덱스 잠금·재색인 비용이 있어 운영 중인 사이트에서는
|
||||
// 기본값(아니오)을 유지하고 유지보수 시간에 별도로 수행하는 것이 안전하다.
|
||||
$rebuildSearchIndex = $this->askRebuildSearchIndex($force);
|
||||
|
||||
// 일괄 실행
|
||||
return $this->executeBulkUpdate(
|
||||
$moduleManager,
|
||||
@@ -116,6 +121,7 @@ trait BundledExtensionUpdatePrompt
|
||||
$templateManager,
|
||||
$updates,
|
||||
$strategies,
|
||||
$rebuildSearchIndex,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -200,8 +206,11 @@ trait BundledExtensionUpdatePrompt
|
||||
TemplateManager $templateManager,
|
||||
array $updates,
|
||||
array $strategies,
|
||||
bool $rebuildSearchIndex = false,
|
||||
): array {
|
||||
$manifest = $this->buildBundledUpdateManifest($updates, $strategies);
|
||||
// 운영자의 선택을 매니페스트에 실어 spawn 자식과 in-process fallback 이 같은 결정을 따르게 한다
|
||||
$manifest['rebuild_search_index'] = $rebuildSearchIndex;
|
||||
if ($this->bundledManifestIsEmpty($manifest)) {
|
||||
return ['success' => 0, 'failed' => 0, 'skipped' => 0, 'has_updates' => false];
|
||||
}
|
||||
@@ -228,6 +237,7 @@ trait BundledExtensionUpdatePrompt
|
||||
$templateManager,
|
||||
$updates,
|
||||
$strategies,
|
||||
$rebuildSearchIndex,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -385,6 +395,7 @@ trait BundledExtensionUpdatePrompt
|
||||
TemplateManager $templateManager,
|
||||
array $updates,
|
||||
array $strategies,
|
||||
bool $rebuildSearchIndex = false,
|
||||
): array {
|
||||
$success = 0;
|
||||
$failed = 0;
|
||||
@@ -452,6 +463,8 @@ trait BundledExtensionUpdatePrompt
|
||||
$this->newLine();
|
||||
$this->info("업데이트 완료: 성공 {$success}, 실패 {$failed}");
|
||||
|
||||
$this->runSearchIndexRebuildIfRequested($rebuildSearchIndex);
|
||||
|
||||
return [
|
||||
'success' => $success,
|
||||
'failed' => $failed,
|
||||
@@ -460,4 +473,60 @@ trait BundledExtensionUpdatePrompt
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검색 인덱스 재생성 여부를 운영자에게 확인합니다.
|
||||
*
|
||||
* 재생성은 인덱스 잠금 또는 전체 재색인을 유발하므로 기본값은 "아니오" 입니다.
|
||||
* `--force` (무인 실행) 시에도 묻지 않고 수행하지 않습니다 — 무인 실행이
|
||||
* 대용량 테이블을 잠그는 일이 없어야 합니다. 필요하면 `core:update
|
||||
* --rebuild-search-index` 로 명시하거나 이후 `search:index --repair` 를 실행합니다.
|
||||
*
|
||||
* @param bool $force 강제(무인) 실행 여부
|
||||
* @return bool 재생성 수행 여부
|
||||
*/
|
||||
private function askRebuildSearchIndex(bool $force): bool
|
||||
{
|
||||
// 커맨드가 옵션으로 이미 선택을 받았으면 그대로 따른다
|
||||
if ($this->hasOption('rebuild-search-index') && (bool) $this->option('rebuild-search-index')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($force) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$manager = app(SearchIndexMaintenanceManager::class);
|
||||
|
||||
// 점검을 제공하지 않는 엔진에서는 물을 것이 없다
|
||||
if (! $manager->hasMaintainer() || $manager->unavailableReason() !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->line(' '.__('search.index.rebuild_cost_warning'));
|
||||
|
||||
return $this->unifiedConfirm(__('search.index.rebuild_after_bulk_confirm'), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청이 있었으면 검색 인덱스를 재생성합니다.
|
||||
*
|
||||
* @param bool $requested 재생성 요청 여부
|
||||
* @return void
|
||||
*/
|
||||
private function runSearchIndexRebuildIfRequested(bool $requested): void
|
||||
{
|
||||
if (! $requested) {
|
||||
return;
|
||||
}
|
||||
|
||||
$report = app(SearchIndexMaintenanceManager::class)->repairStale();
|
||||
|
||||
$this->newLine();
|
||||
$this->info('검색 인덱스: '.$report->summary());
|
||||
|
||||
foreach ($report->failed as $identifier => $message) {
|
||||
$this->warn(' '.__('search.index.rebuild_failed_item', ['index' => $identifier, 'error' => $message]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,8 @@ class CoreUpdateCommand extends Command
|
||||
{--local : 로컬 코드베이스를 업데이트 소스로 사용 (GitHub 스킵)}
|
||||
{--source= : 수동 업데이트용 소스 디렉토리 경로 (GitHub 다운로드 대신 지정 디렉토리 사용)}
|
||||
{--zip= : 수동 업데이트용 ZIP 파일 경로 (GitHub 다운로드 대신 지정 ZIP 추출 사용)}
|
||||
{--vendor-mode=auto : vendor 설치 모드 (auto|composer|bundled)}';
|
||||
{--vendor-mode=auto : vendor 설치 모드 (auto|composer|bundled)}
|
||||
{--rebuild-search-index : 번들 확장 일괄 업데이트 후 색인이 누락된 검색 인덱스를 재생성 (인덱스가 잠기거나 재색인됩니다 — 운영 중에는 유지보수 시간에 수행하세요)}';
|
||||
|
||||
protected $description = '그누보드7 코어를 최신 버전으로 업데이트합니다';
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Console\Commands\Core;
|
||||
|
||||
use App\Extension\ExtensionManager;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use App\Search\SearchIndexMaintenanceManager;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -45,7 +47,8 @@ class ExecuteBundledUpdatesCommand extends Command
|
||||
|
||||
protected $signature = 'core:execute-bundled-updates
|
||||
{--manifest= : 업데이트 매니페스트 JSON 파일 경로 (필수)}
|
||||
{--force : 강제 업데이트 플래그 (확장 매니저 update 호출에 전달)}';
|
||||
{--force : 강제 업데이트 플래그 (확장 매니저 update 호출에 전달)}
|
||||
{--rebuild-search-index : 일괄 업데이트 후 검색 인덱스 재생성 (매니페스트의 선택보다 우선)}';
|
||||
|
||||
protected $description = '번들 확장 일괄 업데이트를 실행합니다 (CoreUpdateCommand 내부용 — fresh PHP 프로세스에서 호출)';
|
||||
|
||||
@@ -63,7 +66,7 @@ class ExecuteBundledUpdatesCommand extends Command
|
||||
// (Artisan::call 대신 직접 메서드 호출 — nested Artisan::call 이 outer 명령의
|
||||
// output buffer 를 덮어쓰는 Laravel 동작 회피)
|
||||
try {
|
||||
app(\App\Extension\ExtensionManager::class)->updateComposerAutoload();
|
||||
app(ExtensionManager::class)->updateComposerAutoload();
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('bundled update spawn 자식: updateComposerAutoload 호출 실패', [
|
||||
'error' => $e->getMessage(),
|
||||
@@ -77,6 +80,9 @@ class ExecuteBundledUpdatesCommand extends Command
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// 부모(core:update)가 운영자 선택을 매니페스트에 실어 보낸다 — 자식이 임의로 정하지 않는다
|
||||
$rebuildSearchIndex = (bool) $this->option('rebuild-search-index') || (bool) ($manifest['rebuild_search_index'] ?? false);
|
||||
|
||||
$modules = $manifest['modules'] ?? [];
|
||||
$plugins = $manifest['plugins'] ?? [];
|
||||
$templates = $manifest['templates'] ?? [];
|
||||
@@ -166,6 +172,17 @@ class ExecuteBundledUpdatesCommand extends Command
|
||||
$this->newLine();
|
||||
$this->info("업데이트 완료: 성공 {$success}, 실패 {$failed}");
|
||||
|
||||
// 검색 인덱스 재생성 — 운영자가 부모 단계에서 선택했을 때만 수행 (인덱스 잠금·재색인 비용)
|
||||
if ($rebuildSearchIndex) {
|
||||
$report = app(SearchIndexMaintenanceManager::class)->repairStale();
|
||||
$this->newLine();
|
||||
$this->info('검색 인덱스: '.$report->summary());
|
||||
|
||||
foreach ($report->failed as $identifier => $message) {
|
||||
$this->warn(' '.__('search.index.rebuild_failed_item', ['index' => $identifier, 'error' => $message]));
|
||||
}
|
||||
}
|
||||
|
||||
// 부모 프로세스가 결과를 복원할 수 있도록 표식 라인으로 페이로드 출력
|
||||
$this->line(self::RESULT_PREFIX.json_encode([
|
||||
'success' => $success,
|
||||
@@ -174,5 +191,4 @@ class ExecuteBundledUpdatesCommand extends Command
|
||||
|
||||
return $failed > 0 ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -116,7 +116,7 @@ class CheckModuleUpdatesCommand extends Command
|
||||
$updateCount = 0;
|
||||
|
||||
foreach ($result['details'] as $detail) {
|
||||
$isUpdate = $detail['update_available'] ?? false;
|
||||
$isUpdate = (bool) ($detail['update_available'] ?? true);
|
||||
if ($isUpdate) {
|
||||
$updateCount++;
|
||||
}
|
||||
@@ -143,7 +143,7 @@ class CheckModuleUpdatesCommand extends Command
|
||||
$this->table($headers, $tableData);
|
||||
$this->newLine();
|
||||
$this->info(__('modules.commands.check_updates.summary', [
|
||||
'total' => count($result['details']),
|
||||
'total' => $result['checked_count'] ?? count($result['details']),
|
||||
'updates' => $updateCount,
|
||||
]));
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Console\Commands\Traits\RebuildsSearchIndex;
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\ModuleManager;
|
||||
@@ -17,6 +18,7 @@ use Illuminate\Support\Facades\Validator;
|
||||
class InstallModuleCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
use RebuildsSearchIndex;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
@@ -24,7 +26,8 @@ class InstallModuleCommand extends Command
|
||||
protected $signature = 'module:install
|
||||
{identifier : 설치할 모듈 식별자}
|
||||
{--vendor-mode=auto : Vendor 설치 모드 (auto|composer|bundled)}
|
||||
{--force : 이미 설치된 경우에도 _bundled/_pending 원본으로 활성 디렉토리를 덮어쓰고 재설치 (불완전 설치 복구)}';
|
||||
{--force : 이미 설치된 경우에도 _bundled/_pending 원본으로 활성 디렉토리를 덮어쓰고 재설치 (불완전 설치 복구)}
|
||||
{--rebuild-search-index : 완료 후 색인이 누락된 검색 인덱스를 재생성 (인덱스가 잠기거나 재색인됩니다 — 운영 중에는 유지보수 시간에 수행하세요)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
@@ -114,6 +117,9 @@ class InstallModuleCommand extends Command
|
||||
|
||||
Log::info(__('modules.commands.install.success', ['module' => $identifier]));
|
||||
|
||||
// 검색 인덱스 재생성은 운영자가 선택했을 때만 수행한다 (인덱스 잠금·재색인 비용)
|
||||
$this->handleSearchIndexRebuild();
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Console\Commands\Traits\HasUnifiedConfirm;
|
||||
use App\Console\Commands\Traits\RebuildsSearchIndex;
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Extension\ModuleManager;
|
||||
@@ -16,6 +17,7 @@ class UpdateModuleCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
use HasUnifiedConfirm;
|
||||
use RebuildsSearchIndex;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
@@ -26,7 +28,8 @@ class UpdateModuleCommand extends Command
|
||||
{--vendor-mode=auto : Vendor 설치 모드 (auto|composer|bundled)}
|
||||
{--layout-strategy=overwrite : 레이아웃 전략 (overwrite|keep)}
|
||||
{--source=auto : 업데이트 소스 (auto|bundled|github) — bundled 는 _bundled 만 사용(GitHub 우회)}
|
||||
{--zip= : 외부 ZIP 파일 경로 (지정 시 GitHub/번들 우회 + 버전은 module.json 기준)}';
|
||||
{--zip= : 외부 ZIP 파일 경로 (지정 시 GitHub/번들 우회 + 버전은 module.json 기준)}
|
||||
{--rebuild-search-index : 완료 후 색인이 누락된 검색 인덱스를 재생성 (인덱스가 잠기거나 재색인됩니다 — 운영 중에는 유지보수 시간에 수행하세요)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
@@ -203,6 +206,9 @@ class UpdateModuleCommand extends Command
|
||||
'layout_strategy' => $layoutStrategy,
|
||||
]);
|
||||
|
||||
// 검색 인덱스 재생성은 운영자가 선택했을 때만 수행한다 (인덱스 잠금·재색인 비용)
|
||||
$this->handleSearchIndexRebuild();
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ class CheckPluginUpdatesCommand extends Command
|
||||
$updateCount = 0;
|
||||
|
||||
foreach ($result['details'] as $detail) {
|
||||
$isUpdate = $detail['update_available'] ?? false;
|
||||
$isUpdate = (bool) ($detail['update_available'] ?? true);
|
||||
if ($isUpdate) {
|
||||
$updateCount++;
|
||||
}
|
||||
@@ -143,7 +143,7 @@ class CheckPluginUpdatesCommand extends Command
|
||||
$this->table($headers, $tableData);
|
||||
$this->newLine();
|
||||
$this->info(__('plugins.commands.check_updates.summary', [
|
||||
'total' => count($result['details']),
|
||||
'total' => $result['checked_count'] ?? count($result['details']),
|
||||
'updates' => $updateCount,
|
||||
]));
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Console\Commands\Traits\RebuildsSearchIndex;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\PluginManager;
|
||||
@@ -16,6 +17,7 @@ use Illuminate\Support\Facades\Validator;
|
||||
class InstallPluginCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
use RebuildsSearchIndex;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
@@ -23,7 +25,8 @@ class InstallPluginCommand extends Command
|
||||
protected $signature = 'plugin:install
|
||||
{identifier : 설치할 플러그인 식별자}
|
||||
{--vendor-mode=auto : Vendor 설치 모드 (auto|composer|bundled)}
|
||||
{--force : 이미 설치된 경우에도 _bundled/_pending 원본으로 활성 디렉토리를 덮어쓰고 재설치 (불완전 설치 복구)}';
|
||||
{--force : 이미 설치된 경우에도 _bundled/_pending 원본으로 활성 디렉토리를 덮어쓰고 재설치 (불완전 설치 복구)}
|
||||
{--rebuild-search-index : 완료 후 색인이 누락된 검색 인덱스를 재생성 (인덱스가 잠기거나 재색인됩니다 — 운영 중에는 유지보수 시간에 수행하세요)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
@@ -111,6 +114,9 @@ class InstallPluginCommand extends Command
|
||||
|
||||
Log::info(__('plugins.commands.install.success', ['plugin' => $identifier]));
|
||||
|
||||
// 검색 인덱스 재생성은 운영자가 선택했을 때만 수행한다 (인덱스 잠금·재색인 비용)
|
||||
$this->handleSearchIndexRebuild();
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Console\Commands\Traits\HasUnifiedConfirm;
|
||||
use App\Console\Commands\Traits\RebuildsSearchIndex;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Extension\PluginManager;
|
||||
@@ -16,6 +17,7 @@ class UpdatePluginCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
use HasUnifiedConfirm;
|
||||
use RebuildsSearchIndex;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
@@ -26,7 +28,8 @@ class UpdatePluginCommand extends Command
|
||||
{--vendor-mode=auto : Vendor 설치 모드 (auto|composer|bundled)}
|
||||
{--layout-strategy=overwrite : 레이아웃 전략 (overwrite|keep)}
|
||||
{--source=auto : 업데이트 소스 (auto|bundled|github) — bundled 는 _bundled 만 사용(GitHub 우회)}
|
||||
{--zip= : 외부 ZIP 파일 경로 (지정 시 GitHub/번들 우회 + 버전은 plugin.json 기준)}';
|
||||
{--zip= : 외부 ZIP 파일 경로 (지정 시 GitHub/번들 우회 + 버전은 plugin.json 기준)}
|
||||
{--rebuild-search-index : 완료 후 색인이 누락된 검색 인덱스를 재생성 (인덱스가 잠기거나 재색인됩니다 — 운영 중에는 유지보수 시간에 수행하세요)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
@@ -202,6 +205,9 @@ class UpdatePluginCommand extends Command
|
||||
'layout_strategy' => $layoutStrategy,
|
||||
]);
|
||||
|
||||
// 검색 인덱스 재생성은 운영자가 선택했을 때만 수행한다 (인덱스 잠금·재색인 비용)
|
||||
$this->handleSearchIndexRebuild();
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Search;
|
||||
|
||||
use App\Console\Commands\Traits\HasUnifiedConfirm;
|
||||
use App\Enums\SearchIndexStatus;
|
||||
use App\Search\DTO\SearchIndexHealth;
|
||||
use App\Search\SearchIndexMaintenanceManager;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 검색 인덱스 점검·재생성 커맨드
|
||||
*
|
||||
* 인덱스는 있는데 내용이 색인되지 않아 검색이 조용히 0건을 돌려주는 상태를 검출하고,
|
||||
* 운영자가 선택하면 재생성합니다. 이 상태는 예외도 로그도 남기지 않으므로
|
||||
* "원래 검색이 안 되는 줄" 알고 지나가기 쉽습니다.
|
||||
*
|
||||
* 점검 방법은 **활성 Scout 엔진의 유지보수기**가 정합니다. 확장이 자체 검색 엔진을
|
||||
* 등록하면서 유지보수기를 함께 등록하면 이 커맨드가 그대로 그 엔진을 다룹니다
|
||||
* (`core.search.index_maintainers` 필터 훅).
|
||||
*
|
||||
* 사용 예시:
|
||||
* php artisan search:index # 활성 엔진의 인덱스 점검 (읽기 전용)
|
||||
* php artisan search:index --repair # 색인 누락 인덱스 재생성
|
||||
* php artisan search:index --filter=table=pages # 엔진별 필터 전달
|
||||
* php artisan search:index --json # 기계 판독용 출력
|
||||
*/
|
||||
class SearchIndexCommand extends Command
|
||||
{
|
||||
use HasUnifiedConfirm;
|
||||
|
||||
protected $signature = 'search:index
|
||||
{--repair : 색인이 누락된 인덱스를 재생성 (미지정 시 점검만)}
|
||||
{--filter=* : 엔진별 필터 (key=value 형태, 다중 지정 가능. FULLTEXT: table, index, samples)}
|
||||
{--json : 기계 판독용 JSON 출력}';
|
||||
|
||||
protected $description = '활성 검색 엔진의 인덱스가 실제로 내용을 색인하고 있는지 점검하고, 누락 시 재생성합니다';
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @param SearchIndexMaintenanceManager $manager 검색 인덱스 유지보수 진입점
|
||||
* @return int 종료 코드 (색인 누락 잔존 시 1)
|
||||
*/
|
||||
public function handle(SearchIndexMaintenanceManager $manager): int
|
||||
{
|
||||
$driver = $manager->driver();
|
||||
$filters = $this->parseFilters();
|
||||
|
||||
if (! $manager->hasMaintainer()) {
|
||||
$this->components->warn(__('search.index.no_maintainer', ['driver' => $driver]));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if (($reason = $manager->unavailableReason()) !== null) {
|
||||
$this->components->warn($reason);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$results = $manager->inspect($filters);
|
||||
|
||||
if ($results === []) {
|
||||
$this->components->warn(__('search.index.no_targets', ['driver' => $driver]));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$report = null;
|
||||
|
||||
if ($this->option('repair')) {
|
||||
$targets = array_values(array_filter($results, fn (SearchIndexHealth $h) => $h->needsRebuild()));
|
||||
|
||||
if ($targets !== [] && $this->confirmRebuild($targets)) {
|
||||
$report = $manager->repairStale($filters);
|
||||
$results = $manager->inspect($filters);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->line((string) json_encode([
|
||||
'driver' => $driver,
|
||||
'results' => array_map(fn (SearchIndexHealth $h) => $h->toArray(), $results),
|
||||
'repair' => $report?->toArray(),
|
||||
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
} else {
|
||||
$this->render($driver, $results, $report?->summary());
|
||||
}
|
||||
|
||||
$remaining = array_filter($results, fn (SearchIndexHealth $h) => $h->needsRebuild());
|
||||
|
||||
return ($remaining === [] && ($report === null || $report->failed === [])) ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* `--filter=key=value` 옵션을 연관 배열로 해석합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function parseFilters(): array
|
||||
{
|
||||
$filters = [];
|
||||
|
||||
foreach ((array) $this->option('filter') as $raw) {
|
||||
if (! is_string($raw) || ! str_contains($raw, '=')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$key, $value] = explode('=', $raw, 2);
|
||||
$key = trim($key);
|
||||
|
||||
if ($key !== '') {
|
||||
$filters[$key] = trim($value);
|
||||
}
|
||||
}
|
||||
|
||||
return $filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 재생성 대상을 보여 주고 진행 여부를 확인합니다.
|
||||
*
|
||||
* @param array<int, SearchIndexHealth> $targets 재생성 대상
|
||||
* @return bool 진행 여부
|
||||
*/
|
||||
private function confirmRebuild(array $targets): bool
|
||||
{
|
||||
$this->newLine();
|
||||
$this->components->info(__('search.index.rebuild_targets', ['count' => count($targets)]));
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$this->line(' - '.$target->identifier.' ('.$target->measurement.')');
|
||||
}
|
||||
|
||||
$this->components->warn(__('search.index.rebuild_cost_warning'));
|
||||
|
||||
if ($this->unifiedConfirm(__('search.index.rebuild_confirm'), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->components->info(__('search.index.rebuild_skipped'));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 판정 결과를 표로 출력합니다.
|
||||
*
|
||||
* @param string $driver 드라이버명
|
||||
* @param array<int, SearchIndexHealth> $results 판정 결과
|
||||
* @param string|null $repairSummary 재생성 요약 (수행했을 때만)
|
||||
* @return void
|
||||
*/
|
||||
private function render(string $driver, array $results, ?string $repairSummary): void
|
||||
{
|
||||
$rows = array_map(fn (SearchIndexHealth $health) => [
|
||||
$health->identifier,
|
||||
'<fg='.$health->status->consoleColor().'>'.$health->status->label().'</>',
|
||||
$health->measurement,
|
||||
], $results);
|
||||
|
||||
$this->newLine();
|
||||
$this->line(' '.__('search.index.driver_label', ['driver' => $driver]));
|
||||
$this->table([__('search.index.col.index'), __('search.index.col.status'), __('search.index.col.measurement')], $rows);
|
||||
|
||||
$counts = [];
|
||||
foreach (SearchIndexStatus::cases() as $case) {
|
||||
$counts[$case->value] = count(array_filter($results, fn (SearchIndexHealth $h) => $h->status === $case));
|
||||
}
|
||||
|
||||
$this->line(' '.__('search.index.counts', [
|
||||
'healthy' => $counts[SearchIndexStatus::Healthy->value],
|
||||
'degraded' => $counts[SearchIndexStatus::Degraded->value],
|
||||
'stale' => $counts[SearchIndexStatus::Stale->value],
|
||||
'skipped' => $counts[SearchIndexStatus::Skipped->value],
|
||||
'total' => count($results),
|
||||
]));
|
||||
|
||||
if ($repairSummary !== null) {
|
||||
$this->newLine();
|
||||
$this->components->info($repairSummary);
|
||||
}
|
||||
|
||||
if ($counts[SearchIndexStatus::Stale->value] > 0 && ! $this->option('repair')) {
|
||||
$this->newLine();
|
||||
$this->components->warn(__('search.index.stale_hint'));
|
||||
}
|
||||
|
||||
if ($counts[SearchIndexStatus::Degraded->value] > 0) {
|
||||
$this->line(' <comment>'.__('search.index.degraded_hint').'</comment>');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,7 +116,7 @@ class CheckTemplateUpdatesCommand extends Command
|
||||
$updateCount = 0;
|
||||
|
||||
foreach ($result['details'] as $detail) {
|
||||
$isUpdate = $detail['update_available'] ?? false;
|
||||
$isUpdate = (bool) ($detail['update_available'] ?? true);
|
||||
if ($isUpdate) {
|
||||
$updateCount++;
|
||||
}
|
||||
@@ -143,7 +143,7 @@ class CheckTemplateUpdatesCommand extends Command
|
||||
$this->table($headers, $tableData);
|
||||
$this->newLine();
|
||||
$this->info(__('templates.commands.check_updates.summary', [
|
||||
'total' => count($result['details']),
|
||||
'total' => $result['checked_count'] ?? count($result['details']),
|
||||
'updates' => $updateCount,
|
||||
]));
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Traits;
|
||||
|
||||
use App\Search\DTO\SearchIndexHealth;
|
||||
use App\Search\DTO\SearchIndexRepairReport;
|
||||
use App\Search\SearchIndexMaintenanceManager;
|
||||
|
||||
/**
|
||||
* 설치·업데이트 커맨드에 "검색 인덱스 재생성" 선택 옵션을 제공하는 트레이트.
|
||||
*
|
||||
* 재생성 비용은 엔진마다 다르지만(테이블 잠금 / 전체 재색인) 어느 쪽이든 운영 중인
|
||||
* 사이트에 영향을 줍니다. 그래서 **기본값은 재생성하지 않음**이고, 운영자가
|
||||
* `--rebuild-search-index` 로 명시했을 때만 수행합니다.
|
||||
*
|
||||
* 옵션을 주지 않아도 점검 결과는 안내합니다 — 색인이 누락되면 검색이 오류 없이 0건을
|
||||
* 돌려주므로, 알려주지 않으면 운영자가 알 방법이 없습니다.
|
||||
*/
|
||||
trait RebuildsSearchIndex
|
||||
{
|
||||
/**
|
||||
* 커맨드 `$signature` 에 붙일 옵션 정의.
|
||||
*
|
||||
* @return string 옵션 시그니처 조각
|
||||
*/
|
||||
public static function rebuildSearchIndexOption(): string
|
||||
{
|
||||
return '{--rebuild-search-index : 완료 후 색인이 누락된 검색 인덱스를 재생성 (인덱스가 잠기거나 재색인됩니다 — 운영 중에는 점검 결과만 확인하고 유지보수 시간에 수행하세요)}';
|
||||
}
|
||||
|
||||
/**
|
||||
* 작업 완료 후 검색 인덱스를 점검하고, 요청이 있었으면 재생성합니다.
|
||||
*
|
||||
* @param bool|null $requested 재생성 요청 여부 (null 이면 커맨드 옵션에서 읽음)
|
||||
* @return SearchIndexRepairReport|null 재생성 보고 (재생성을 하지 않았으면 null)
|
||||
*/
|
||||
protected function handleSearchIndexRebuild(?bool $requested = null): ?SearchIndexRepairReport
|
||||
{
|
||||
$manager = app(SearchIndexMaintenanceManager::class);
|
||||
|
||||
// 점검을 제공하지 않는 엔진에서는 조용히 넘어간다 (검색 자체는 정상 동작)
|
||||
if (! $manager->hasMaintainer() || $manager->unavailableReason() !== null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$requested ??= (bool) $this->option('rebuild-search-index');
|
||||
|
||||
if ($requested) {
|
||||
$report = $manager->repairStale();
|
||||
$this->reportRebuild($report);
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
$this->warnStale($manager->inspect());
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 재생성하지 않은 경우, 색인 누락 사실만 안내합니다.
|
||||
*
|
||||
* @param array<int, SearchIndexHealth> $results 점검 결과
|
||||
* @return void
|
||||
*/
|
||||
private function warnStale(array $results): void
|
||||
{
|
||||
$stale = array_values(array_filter($results, fn (SearchIndexHealth $h) => $h->needsRebuild()));
|
||||
|
||||
if ($stale === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->warn('⚠️ '.__('search.index.stale_after_update', ['count' => count($stale)]));
|
||||
|
||||
foreach ($stale as $health) {
|
||||
$this->line(' - '.$health->identifier);
|
||||
}
|
||||
|
||||
$this->line(' '.__('search.index.stale_hint'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 재생성 보고를 콘솔에 출력합니다.
|
||||
*
|
||||
* @param SearchIndexRepairReport $report 재생성 보고
|
||||
* @return void
|
||||
*/
|
||||
private function reportRebuild(SearchIndexRepairReport $report): void
|
||||
{
|
||||
$this->newLine();
|
||||
|
||||
if (! $report->didRebuild()) {
|
||||
$this->info('✅ '.$report->summary());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->info('✅ '.$report->summary());
|
||||
|
||||
foreach ($report->repaired as $identifier) {
|
||||
$this->line(' '.__('search.index.rebuilt_item', ['index' => $identifier]));
|
||||
}
|
||||
|
||||
foreach ($report->failed as $identifier => $message) {
|
||||
$this->error(' '.__('search.index.rebuild_failed_item', ['index' => $identifier, 'error' => $message]));
|
||||
}
|
||||
|
||||
foreach ($report->remaining as $identifier) {
|
||||
$this->warn(' '.__('search.index.still_stale_item', ['index' => $identifier]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 검색 인덱스 건강도 등급 (엔진 중립)
|
||||
*
|
||||
* 판정 방법은 엔진마다 다릅니다 — 각 `SearchIndexMaintainer` 구현이 자기 방식으로
|
||||
* 판정한 뒤 이 등급 중 하나로 답합니다. 코어는 등급만 보고 재생성 대상을 고릅니다.
|
||||
*/
|
||||
enum SearchIndexStatus: string
|
||||
{
|
||||
/** 정상 — 색인된 내용으로 검색이 성립한다 */
|
||||
case Healthy = 'healthy';
|
||||
|
||||
/** 부분 — 일부만 성립. 엔진 특성일 수 있어 자동 재생성 대상이 아니다 */
|
||||
case Degraded = 'degraded';
|
||||
|
||||
/** 색인 누락 — 검색이 성립하지 않는다. 재생성 대상 */
|
||||
case Stale = 'stale';
|
||||
|
||||
/** 판정 불가 — 표본·연결 부재 등 (사유를 함께 기록) */
|
||||
case Skipped = 'skipped';
|
||||
|
||||
/**
|
||||
* 사용자 친화 라벨을 반환합니다.
|
||||
*
|
||||
* @return string lang 키 해석 결과 (locale 자동 반영)
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return __('search.index.status.'.$this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 콘솔 출력용 색상명을 반환합니다.
|
||||
*
|
||||
* @return string Symfony 콘솔 색상명
|
||||
*/
|
||||
public function consoleColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Healthy => 'green',
|
||||
self::Degraded => 'yellow',
|
||||
self::Stale => 'red',
|
||||
self::Skipped => 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 케이스의 string 값 목록.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function allValues(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
@@ -3971,9 +3971,11 @@ class ModuleManager implements ModuleManagerInterface
|
||||
$moduleRecords = $this->moduleRepository->getAllKeyedByIdentifier();
|
||||
$details = [];
|
||||
$updatedCount = 0;
|
||||
$checkedCount = 0;
|
||||
|
||||
foreach ($moduleRecords as $identifier => $record) {
|
||||
$result = $this->checkModuleUpdate($identifier);
|
||||
$checkedCount++;
|
||||
|
||||
// DB 갱신
|
||||
$updateData = [
|
||||
@@ -3997,6 +3999,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
$updatedCount++;
|
||||
$details[] = [
|
||||
'identifier' => $identifier,
|
||||
'update_available' => true,
|
||||
'current_version' => $result['current_version'],
|
||||
'latest_version' => $result['latest_version'],
|
||||
'update_source' => $result['update_source'],
|
||||
@@ -4006,6 +4009,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
|
||||
return [
|
||||
'updated_count' => $updatedCount,
|
||||
'checked_count' => $checkedCount,
|
||||
'details' => $details,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -4153,9 +4153,11 @@ class PluginManager implements PluginManagerInterface
|
||||
$pluginRecords = $this->pluginRepository->getAllKeyedByIdentifier();
|
||||
$details = [];
|
||||
$updatedCount = 0;
|
||||
$checkedCount = 0;
|
||||
|
||||
foreach ($pluginRecords as $identifier => $record) {
|
||||
$result = $this->checkPluginUpdate($identifier);
|
||||
$checkedCount++;
|
||||
|
||||
// DB 갱신
|
||||
$updateData = [
|
||||
@@ -4179,6 +4181,7 @@ class PluginManager implements PluginManagerInterface
|
||||
$updatedCount++;
|
||||
$details[] = [
|
||||
'identifier' => $identifier,
|
||||
'update_available' => true,
|
||||
'current_version' => $result['current_version'],
|
||||
'latest_version' => $result['latest_version'],
|
||||
'update_source' => $result['update_source'],
|
||||
@@ -4188,6 +4191,7 @@ class PluginManager implements PluginManagerInterface
|
||||
|
||||
return [
|
||||
'updated_count' => $updatedCount,
|
||||
'checked_count' => $checkedCount,
|
||||
'details' => $details,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -2685,9 +2685,11 @@ class TemplateManager implements TemplateManagerInterface
|
||||
$templateRecords = $this->templateRepository->getAllKeyedByIdentifier();
|
||||
$details = [];
|
||||
$updatedCount = 0;
|
||||
$checkedCount = 0;
|
||||
|
||||
foreach ($templateRecords as $identifier => $record) {
|
||||
$result = $this->checkTemplateUpdate($identifier);
|
||||
$checkedCount++;
|
||||
|
||||
$updateData = [
|
||||
'update_available' => $result['update_available'],
|
||||
@@ -2711,6 +2713,7 @@ class TemplateManager implements TemplateManagerInterface
|
||||
$updatedCount++;
|
||||
$details[] = [
|
||||
'identifier' => $identifier,
|
||||
'update_available' => true,
|
||||
'current_version' => $result['current_version'],
|
||||
'latest_version' => $result['latest_version'],
|
||||
'update_source' => $result['update_source'],
|
||||
@@ -2720,6 +2723,7 @@ class TemplateManager implements TemplateManagerInterface
|
||||
|
||||
return [
|
||||
'updated_count' => $updatedCount,
|
||||
'checked_count' => $checkedCount,
|
||||
'details' => $details,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -335,6 +335,12 @@ class ResponseHelper
|
||||
/**
|
||||
* JSON Resource를 사용한 성공 응답을 생성합니다.
|
||||
*
|
||||
* `$resource->additional([...])` 로 실은 부가 데이터는 응답 최상위에 함께 나갑니다.
|
||||
* `JsonResource::resolve()` 는 리소스 본문만 돌려주므로, 그것만 쓰면 호출자가 실은
|
||||
* 부가 데이터가 조용히 사라집니다 — 예를 들어 확장 업데이트 응답의 `search_index`
|
||||
* (색인 누락 안내)가 사라지면 검색이 0건을 돌려주는 사실을 운영자가 알 방법이 없습니다.
|
||||
* `success`/`message`/`data` 키는 부가 데이터로 덮어쓰지 않습니다.
|
||||
*
|
||||
* @param string $messageKey 멤시지 키 (기본값: 'messages.success')
|
||||
* @param JsonResource|ResourceCollection|null $resource JSON 리소스
|
||||
* @param int $statusCode HTTP 상태 코드 (기본값: 200)
|
||||
@@ -351,11 +357,19 @@ class ResponseHelper
|
||||
): JsonResponse {
|
||||
$data = $resource ? $resource->resolve() : null;
|
||||
|
||||
return response()->json([
|
||||
$payload = [
|
||||
'success' => true,
|
||||
'message' => self::trans($messageKey, $messageParams, $domain),
|
||||
'data' => $data,
|
||||
], $statusCode, [], self::JSON_ENCODE_OPTIONS);
|
||||
];
|
||||
|
||||
$additional = $resource instanceof JsonResource ? (array) $resource->additional : [];
|
||||
|
||||
if ($additional !== []) {
|
||||
$payload += array_diff_key($additional, $payload);
|
||||
}
|
||||
|
||||
return response()->json($payload, $statusCode, [], self::JSON_ENCODE_OPTIONS);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -198,4 +198,31 @@ class TimezoneHelper
|
||||
|
||||
return Carbon::parse($normalized, static::getSiteTimezone())->utc();
|
||||
}
|
||||
|
||||
/**
|
||||
* 기간 필터의 **종료값**을 사이트 기본 타임존 기준으로 해석하여 UTC Carbon을 반환합니다.
|
||||
*
|
||||
* `<input type="date">` 는 시각 없이 'Y-m-d' 만 보낸다. 이 값을 그대로 datetime 비교에 쓰면
|
||||
* '00:00:00' 으로 해석되어 **종료일 당일이 통째로 빠진다**. 시각이 없는 입력만 그날 끝
|
||||
* (23:59:59)까지 확장하고, 시각이 함께 온 입력은 그 시각 그대로 둔다.
|
||||
*
|
||||
* 예: '2026-03-15' + Asia/Seoul → 2026-03-15 23:59:59 KST → 2026-03-15 14:59:59 UTC
|
||||
* '2026-03-15 09:30' + Asia/Seoul → 2026-03-15 00:30:00 UTC (확장하지 않음)
|
||||
*
|
||||
* @param string|null $dateTimeString Y-m-d 또는 Y-m-d\TH:i / Y-m-d H:i:s 형식
|
||||
* @return Carbon|null UTC Carbon 인스턴스
|
||||
*/
|
||||
public static function fromSiteRangeEnd(?string $dateTimeString): ?Carbon
|
||||
{
|
||||
if (! $dateTimeString) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalized = trim(str_replace('T', ' ', $dateTimeString));
|
||||
$dateOnly = preg_match('/^\d{4}-\d{2}-\d{2}$/', $normalized) === 1;
|
||||
|
||||
$parsed = Carbon::parse($normalized, static::getSiteTimezone());
|
||||
|
||||
return ($dateOnly ? $parsed->endOfDay() : $parsed)->utc();
|
||||
}
|
||||
}
|
||||
@@ -29,18 +29,22 @@ class MenuController extends AdminBaseController
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리용 메뉴 목록을 조회합니다.
|
||||
*
|
||||
* @param MenuListRequest $request 목록 필터·정렬 요청
|
||||
* @return JsonResponse 메뉴 컬렉션을 담은 JSON 응답
|
||||
*/
|
||||
public function index(MenuListRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = $request->validated();
|
||||
$user = Auth::user();
|
||||
|
||||
// 필터가 있으면 필터링된 메뉴 조회, 없으면 전체 조회
|
||||
if (isset($filters['is_active']) || ! empty($filters['filters'])) {
|
||||
$menus = $this->menuService->getFilteredMenusForManagement($filters, $user);
|
||||
} else {
|
||||
$menus = $this->menuService->getTopLevelMenusForManagement($user);
|
||||
}
|
||||
// 필터 유무와 무관하게 같은 경로로 조회한다. 예전에는 필터가 없으면 filters 를
|
||||
// 받지 않는 메서드로 분기했는데, 그 경로는 sort_by/sort_order 를 통째로 버려
|
||||
// "필터를 하나라도 걸어야 정렬이 먹는" 상태가 됐다 (#492 D-22).
|
||||
$menus = $this->menuService->getFilteredMenusForManagement($filters, $user);
|
||||
|
||||
return $this->successWithResource(
|
||||
'menu.fetch_success',
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Extension\Vendor\VendorMode;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Controllers\Concerns\InjectsExtensionLanguagePacks;
|
||||
use App\Http\Controllers\Concerns\OrchestratesCascadeInstall;
|
||||
use App\Http\Controllers\Concerns\RebuildsSearchIndexOnDemand;
|
||||
use App\Http\Requests\Extension\ChangelogRequest;
|
||||
use App\Http\Requests\Module\ActivateModuleRequest;
|
||||
use App\Http\Requests\Module\DeactivateModuleRequest;
|
||||
@@ -38,6 +39,7 @@ class ModuleController extends AdminBaseController
|
||||
{
|
||||
use InjectsExtensionLanguagePacks;
|
||||
use OrchestratesCascadeInstall;
|
||||
use RebuildsSearchIndexOnDemand;
|
||||
|
||||
public function __construct(
|
||||
private ModuleService $moduleService,
|
||||
@@ -531,25 +533,36 @@ class ModuleController extends AdminBaseController
|
||||
$force = (bool) ($validated['force'] ?? false);
|
||||
$result = $this->moduleService->updateModule($moduleName, $vendorMode, $layoutStrategy, $force);
|
||||
|
||||
// 검색 인덱스 재생성은 운영자가 체크했을 때만 수행한다 — 인덱스 잠금·재색인 비용이
|
||||
// 있어 운영 중인 사이트에서 업데이트만으로 발생해서는 안 된다.
|
||||
$searchIndex = $this->rebuildSearchIndexIfRequested(
|
||||
(bool) ($validated['rebuild_search_index'] ?? false)
|
||||
);
|
||||
|
||||
$moduleInfo = $result['module_info'] ?? null;
|
||||
|
||||
// 메시지 치환 파라미터를 반드시 전달한다 — 누락 시 ":module"/":version"
|
||||
// 플레이스홀더가 그대로 사용자에게 노출된다.
|
||||
$messageParams = [
|
||||
'module' => $moduleName,
|
||||
'version' => $result['to_version'] ?? ($moduleInfo['version'] ?? ''),
|
||||
'version' => (string) ($result['to_version'] ?? data_get($moduleInfo, 'version') ?? ''),
|
||||
];
|
||||
|
||||
if ($moduleInfo) {
|
||||
return $this->successWithResource(
|
||||
'modules.update_success',
|
||||
new ModuleResource($moduleInfo),
|
||||
(new ModuleResource($moduleInfo))->additional(['search_index' => $searchIndex]),
|
||||
200,
|
||||
$messageParams
|
||||
);
|
||||
}
|
||||
|
||||
return $this->success('modules.update_success', $result, 200, $messageParams);
|
||||
return $this->success(
|
||||
'modules.update_success',
|
||||
$result + ['search_index' => $searchIndex],
|
||||
200,
|
||||
$messageParams
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
// Service/Manager에서 이미 번역된 메시지를 errors에 포함하므로
|
||||
// 첫 번째 에러를 top-level message로 직접 사용 (이중 래핑 방지)
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Helpers\PermissionHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Controllers\Concerns\InjectsExtensionLanguagePacks;
|
||||
use App\Http\Controllers\Concerns\OrchestratesCascadeInstall;
|
||||
use App\Http\Controllers\Concerns\RebuildsSearchIndexOnDemand;
|
||||
use App\Http\Requests\Extension\ChangelogRequest;
|
||||
use App\Http\Requests\Plugin\ActivatePluginRequest;
|
||||
use App\Http\Requests\Plugin\DeactivatePluginRequest;
|
||||
@@ -39,6 +40,7 @@ class PluginController extends AdminBaseController
|
||||
{
|
||||
use InjectsExtensionLanguagePacks;
|
||||
use OrchestratesCascadeInstall;
|
||||
use RebuildsSearchIndexOnDemand;
|
||||
|
||||
public function __construct(
|
||||
private PluginService $pluginService,
|
||||
@@ -538,25 +540,35 @@ class PluginController extends AdminBaseController
|
||||
$force = (bool) ($validated['force'] ?? false);
|
||||
$result = $this->pluginService->updatePlugin($pluginName, $vendorMode, $layoutStrategy, $force);
|
||||
|
||||
// 검색 인덱스 재생성은 운영자가 체크했을 때만 수행한다 — 인덱스 잠금·재색인 비용이
|
||||
// 있어 운영 중인 사이트에서 업데이트만으로 발생해서는 안 된다.
|
||||
$searchIndex = $this->rebuildSearchIndexIfRequested(
|
||||
(bool) ($validated['rebuild_search_index'] ?? false)
|
||||
);
|
||||
|
||||
$pluginInfo = $result['plugin_info'] ?? null;
|
||||
|
||||
// 메시지 치환 파라미터를 반드시 전달한다 — 누락 시 ":plugin"/":version"
|
||||
// 플레이스홀더가 그대로 사용자에게 노출된다.
|
||||
// 성공 메시지는 ":plugin"/":version" 치환자를 쓰므로 값을 함께 넘긴다
|
||||
$messageParams = [
|
||||
'plugin' => $pluginName,
|
||||
'version' => $result['to_version'] ?? ($pluginInfo['version'] ?? ''),
|
||||
'version' => (string) ($result['to_version'] ?? data_get($pluginInfo, 'version') ?? ''),
|
||||
];
|
||||
|
||||
if ($pluginInfo) {
|
||||
return $this->successWithResource(
|
||||
'plugins.update_success',
|
||||
new PluginResource($pluginInfo),
|
||||
(new PluginResource($pluginInfo))->additional(['search_index' => $searchIndex]),
|
||||
200,
|
||||
$messageParams
|
||||
);
|
||||
}
|
||||
|
||||
return $this->success('plugins.update_success', $result, 200, $messageParams);
|
||||
return $this->success(
|
||||
'plugins.update_success',
|
||||
$result + ['search_index' => $searchIndex],
|
||||
200,
|
||||
$messageParams
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
// Service/Manager에서 이미 번역된 메시지를 errors에 포함하므로
|
||||
// 첫 번째 에러를 top-level message로 직접 사용 (이중 래핑 방지)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Concerns;
|
||||
|
||||
use App\Search\SearchIndexMaintenanceManager;
|
||||
|
||||
/**
|
||||
* 관리자 화면의 설치·업데이트 응답에 "검색 인덱스 재생성" 선택 결과를 싣는 트레이트.
|
||||
*
|
||||
* 재생성 비용은 엔진마다 다르지만(테이블 잠금 / 전체 재색인) 어느 쪽이든 운영 중인
|
||||
* 사이트에 영향을 줍니다. 그래서 **운영자가 화면에서 체크했을 때만** 수행하고,
|
||||
* 체크하지 않았을 때는 점검 결과만 실어 보내 화면이 "지금 색인이 누락된 인덱스가 있다"
|
||||
* 는 사실을 알릴 수 있게 합니다 — 색인이 비면 검색이 오류 없이 0건을 돌려주므로
|
||||
* 알려 주지 않으면 운영자가 알 방법이 없습니다.
|
||||
*/
|
||||
trait RebuildsSearchIndexOnDemand
|
||||
{
|
||||
/**
|
||||
* 요청이 있었으면 재생성하고, 없었으면 점검 결과만 반환합니다.
|
||||
*
|
||||
* @param bool $requested 재생성 요청 여부
|
||||
* @return array<string, mixed>|null 응답에 실을 페이로드 (점검 불가 엔진이면 null)
|
||||
*/
|
||||
protected function rebuildSearchIndexIfRequested(bool $requested): ?array
|
||||
{
|
||||
$manager = app(SearchIndexMaintenanceManager::class);
|
||||
|
||||
// 점검을 제공하지 않는 엔진에서는 실을 정보가 없다 (검색 자체는 정상 동작)
|
||||
if (! $manager->hasMaintainer() || $manager->unavailableReason() !== null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($requested) {
|
||||
return ['rebuilt' => true] + $manager->repairStale()->toArray();
|
||||
}
|
||||
|
||||
$stale = array_values(array_filter($manager->inspect(), fn ($health) => $health->needsRebuild()));
|
||||
|
||||
return [
|
||||
'rebuilt' => false,
|
||||
'driver' => $manager->driver(),
|
||||
'stale' => array_map(fn ($health) => $health->identifier, $stale),
|
||||
'stale_count' => count($stale),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pipeline\Pipeline;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Session\Middleware\StartSession;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
@@ -23,34 +25,16 @@ class StartApiSession
|
||||
/**
|
||||
* 요청을 처리합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param Closure $next 다음 미들웨어
|
||||
* @param Request $request HTTP 요청
|
||||
* @param Closure $next 다음 미들웨어
|
||||
* @return Response HTTP 응답
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
Log::info('[StartApiSession] 미들웨어 시작', ['url' => $request->url()]);
|
||||
|
||||
return (new Pipeline(app()))
|
||||
->send($request)
|
||||
->through($this->sessionPipeline())
|
||||
->then(function ($request) use ($next) {
|
||||
Log::info('[StartApiSession] 세션 파이프라인 완료', [
|
||||
'hasSession' => $request->hasSession(),
|
||||
'sessionStarted' => $request->hasSession() ? $request->session()->isStarted() : false,
|
||||
'sessionId' => $request->hasSession() ? $request->session()->getId() : null,
|
||||
]);
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
Log::info('[StartApiSession] 컨트롤러 응답 후', [
|
||||
'status' => $response->getStatusCode(),
|
||||
'cookies' => collect($response->headers->getCookies())->map(fn($c) => $c->getName())->all(),
|
||||
'webGuardCheck' => \Illuminate\Support\Facades\Auth::guard('web')->check(),
|
||||
]);
|
||||
|
||||
return $response;
|
||||
});
|
||||
->then(fn ($request) => $next($request));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,9 +47,9 @@ class StartApiSession
|
||||
protected function sessionPipeline(): array
|
||||
{
|
||||
return [
|
||||
\Illuminate\Cookie\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
EncryptCookies::class,
|
||||
AddQueuedCookiesToResponse::class,
|
||||
StartSession::class,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Requests\ActivityLog;
|
||||
|
||||
use App\Enums\ActivityLogType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -33,7 +34,7 @@ class ActivityLogIndexRequest extends FormRequest
|
||||
'log_type' => ['nullable', 'array'],
|
||||
'log_type.*' => ['string', Rule::in(ActivityLogType::values())],
|
||||
'action' => ['nullable', 'string', 'max:100'],
|
||||
'user_id' => ['nullable', 'integer', Rule::exists('users', 'id')],
|
||||
'user_id' => ['nullable', 'integer', Rule::exists(User::class, 'id')],
|
||||
'loggable_type' => ['nullable', 'string', 'max:255'],
|
||||
'search' => ['nullable', 'string', 'max:255'],
|
||||
'search_type' => ['nullable', 'string', Rule::in(['all', 'action', 'description', 'ip_address'])],
|
||||
@@ -41,6 +42,9 @@ class ActivityLogIndexRequest extends FormRequest
|
||||
'date_from' => ['nullable', 'date'],
|
||||
'date_to' => ['nullable', 'date', 'after_or_equal:date_from'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
// 게이트는 화면이 제공하는 정렬만 연다. ActivityLogRepository::SORTABLE_COLUMNS 는
|
||||
// 이보다 넓게(id·user_id 포함) 두어, 확장이 이 규칙을 훅으로 넓혔을 때 저장소가
|
||||
// 조용히 기본 정렬로 되돌리지 않도록 한다 (service-repository.md "정렬 컬럼 화이트리스트").
|
||||
'sort_by' => ['nullable', 'string', Rule::in(['created_at', 'action', 'log_type'])],
|
||||
'sort_order' => ['nullable', 'string', Rule::in(['asc', 'desc'])],
|
||||
];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Requests\Module;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -28,7 +29,7 @@ class PerformModuleUpdateRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -37,6 +38,8 @@ class PerformModuleUpdateRequest extends FormRequest
|
||||
'vendor_mode' => ['nullable', 'string', 'in:auto,composer,bundled'],
|
||||
// 코어 버전 비호환 강제 우회 플래그
|
||||
'force' => ['nullable', 'boolean'],
|
||||
// 업데이트 후 검색 인덱스 재생성 여부 — 인덱스 잠금·재색인 비용이 있어 기본은 미수행
|
||||
'rebuild_search_index' => ['nullable', 'boolean'],
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('core.module.perform_update_validation_rules', $rules, $this);
|
||||
|
||||
@@ -36,7 +36,9 @@ class NotificationLogIndexRequest extends FormRequest
|
||||
'extension_type' => ['nullable', 'string', 'in:core,module,plugin'],
|
||||
'status' => ['nullable', 'string', Rule::enum(NotificationLogStatus::class)],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'sort_by' => ['nullable', 'string', 'in:id,channel,notification_type,status,sent_at,created_at'],
|
||||
// 허용 집합은 NotificationLogRepository::SORTABLE_COLUMNS 와 동일해야 한다.
|
||||
// 게이트가 더 좁으면 화면 정렬 셀렉트가 제공하는 옵션(수신자명순/제목순)이 422 로 막힌다.
|
||||
'sort_by' => ['nullable', 'string', 'in:id,channel,notification_type,status,sent_at,created_at,recipient_name,subject'],
|
||||
'sort_order' => ['nullable', 'string', 'in:asc,desc'],
|
||||
];
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Requests\Plugin;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -28,7 +29,7 @@ class PerformPluginUpdateRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -37,6 +38,8 @@ class PerformPluginUpdateRequest extends FormRequest
|
||||
'vendor_mode' => ['nullable', 'string', 'in:auto,composer,bundled'],
|
||||
// 코어 버전 비호환 강제 우회 플래그 (위험 인지 후 사용자 명시 필요)
|
||||
'force' => ['nullable', 'boolean'],
|
||||
// 업데이트 후 검색 인덱스 재생성 여부 — 인덱스 잠금·재색인 비용이 있어 기본은 미수행
|
||||
'rebuild_search_index' => ['nullable', 'boolean'],
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('core.plugin.perform_update_validation_rules', $rules, $this);
|
||||
|
||||
@@ -304,10 +304,7 @@ class LanguagePackServiceProvider extends ServiceProvider
|
||||
$syncFor = function (string $scope, string $identifier, ?array $info, string $relativeBase) use ($registrar) {
|
||||
$vendor = $this->resolveVendor($identifier, $info);
|
||||
$version = (string) ($info['version'] ?? '1.0.0');
|
||||
$langDir = $relativeBase.'/'.$identifier.'/lang';
|
||||
if (! File::isDirectory(base_path($langDir))) {
|
||||
$langDir = $relativeBase.'/'.$identifier.'/resources/lang';
|
||||
}
|
||||
$langDir = $this->resolveExtensionLangDir($scope, $identifier, $relativeBase);
|
||||
$registrar->syncFromExtension($scope, $identifier, $vendor, $version, $langDir);
|
||||
};
|
||||
|
||||
@@ -359,6 +356,38 @@ class LanguagePackServiceProvider extends ServiceProvider
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 백엔드 다국어 디렉토리를 반환합니다.
|
||||
*
|
||||
* **런타임이 실제로 로드하는 경로와 같아야 한다** (`TranslationServiceProvider`).
|
||||
* 모듈은 `src/lang`, 플러그인은 `lang` 이며, 코어의 확장 설치 검증
|
||||
* (`ValidatesTranslationPath`)도 같은 규칙을 강제한다. 여기서 다른 경로를 잡으면
|
||||
* 언어팩에 등록된 키와 화면에 나오는 문구의 출처가 어긋난다.
|
||||
*
|
||||
* 존재하지 않으면 관례 경로들을 순서대로 확인해 실제 있는 디렉토리를 돌려준다
|
||||
* (제3자 확장이 다른 배치를 쓰는 경우 대비).
|
||||
*
|
||||
* @param string $scope 확장 스코프 (module|plugin|template)
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $relativeBase base_path 기준 상위 디렉토리 (modules|plugins|templates)
|
||||
* @return string base_path 기준 상대 lang 디렉토리
|
||||
*/
|
||||
private function resolveExtensionLangDir(string $scope, string $identifier, string $relativeBase): string
|
||||
{
|
||||
$primary = $scope === 'module' ? 'src/lang' : 'lang';
|
||||
$candidates = array_unique([$primary, 'lang', 'src/lang', 'resources/lang']);
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
$dir = $relativeBase.'/'.$identifier.'/'.$candidate;
|
||||
|
||||
if (File::isDirectory(base_path($dir))) {
|
||||
return $dir;
|
||||
}
|
||||
}
|
||||
|
||||
return $relativeBase.'/'.$identifier.'/'.$primary;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 manifest 또는 identifier 로부터 vendor 를 추출합니다.
|
||||
*
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Repositories\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Database\Query\Expression;
|
||||
use Illuminate\Contracts\Pagination\Paginator as PaginatorContract;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Pagination\Paginator;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -27,7 +29,10 @@ use Illuminate\Support\Collection;
|
||||
*
|
||||
* 호출 계약:
|
||||
* - `$query` 에는 **필터/where 만** 적용한다 (`orderBy`/`with`/`select` 미적용)
|
||||
* - `whereHas` 는 결과 집합을 결정하므로 그대로 둔다 — `with` 만 inner 에서 제거된다
|
||||
* - `whereHas` 는 결과 집합을 결정하므로 그대로 둔다 — 제거되는 것은 `with`(eager load) 뿐이다
|
||||
* - 관계는 **반드시 `$relations` 인자로** 넘긴다. `setEagerLoads([])` 는 inner 뿐 아니라
|
||||
* **outer 에도** 적용되므로, `$query->with()` 만 하고 인자를 생략하면 관계가 로드되지 않는다.
|
||||
* 이 실패는 예외도 쿼리 오류도 내지 않고 응답에서 관계 필드만 사라진다
|
||||
* - 정렬은 닫힌 집합이어야 한다 (ResolvesSortSpec 참조). 인덱스 없는 컬럼 정렬은 inner 도
|
||||
* 전체 스캔하므로 개선 폭이 보장되지 않는다
|
||||
* - 키 컬럼은 정렬 마지막에 자동으로 덧붙는다 (동률 시 페이지 경계가 흔들리는 것을 방지)
|
||||
@@ -180,8 +185,12 @@ trait PaginatesWithDeferredJoin
|
||||
/**
|
||||
* 정렬 스펙을 쿼리에 적용합니다.
|
||||
*
|
||||
* 컬럼이 상관 서브쿼리(Builder)면 `orderBy()` 가 서브 select 로 전개한다. 서브쿼리는
|
||||
* 원 행의 키에 상관되므로 inner/outer 어느 쪽에 적용해도 같은 순서를 만든다 —
|
||||
* outer 에서는 이번 페이지 건수만큼만 실행된다.
|
||||
*
|
||||
* @param Builder $query 대상 쿼리
|
||||
* @param array<int, array{column: string, direction: string}> $sort 정렬 스펙
|
||||
* @param array<int, array{column: string|Builder|Expression, direction: string}> $sort 정렬 스펙
|
||||
*/
|
||||
private function applySortSpec(Builder $query, array $sort): void
|
||||
{
|
||||
@@ -196,9 +205,13 @@ trait PaginatesWithDeferredJoin
|
||||
* 정렬 컬럼에 중복이 많으면(상태/조회수/평점 등) 동률 행의 순서가 실행마다 달라져 페이지
|
||||
* 경계에서 행이 중복되거나 누락된다. inner 와 outer 가 같은 순서를 갖도록 하는 전제이기도 하다.
|
||||
*
|
||||
* @param array<int, array{column: string, direction: string}> $sort 정렬 스펙
|
||||
* 정렬 컬럼은 문자열 외에 **상관 서브쿼리(Builder)** 나 Expression 도 올 수 있다
|
||||
* (관계 테이블 컬럼 기준 정렬 — `SortsByRelatedColumn`). 이 경우 키 컬럼일 수 없으므로
|
||||
* 전순서 보장을 위해 키 컬럼이 항상 덧붙는다.
|
||||
*
|
||||
* @param array<int, array{column: string|Builder|Expression, direction: string}> $sort 정렬 스펙
|
||||
* @param string $keyName 키 컬럼명
|
||||
* @return array<int, array{column: string, direction: string}> 키 컬럼이 보장된 정렬 스펙
|
||||
* @return array<int, array{column: string|Builder|Expression, direction: string}> 키 컬럼이 보장된 정렬 스펙
|
||||
*/
|
||||
private function normalizeSortSpecForKey(array $sort, string $keyName): array
|
||||
{
|
||||
@@ -207,7 +220,7 @@ trait PaginatesWithDeferredJoin
|
||||
foreach ($sort as $spec) {
|
||||
$column = $spec['column'] ?? null;
|
||||
|
||||
if (! is_string($column) || $column === '') {
|
||||
if (is_string($column) ? $column === '' : ! ($column instanceof Builder || $column instanceof QueryBuilder || $column instanceof Expression)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -219,6 +232,10 @@ trait PaginatesWithDeferredJoin
|
||||
|
||||
foreach ($normalized as $spec) {
|
||||
// 이미 키 컬럼으로 정렬한다면 그것으로 전순서가 성립한다
|
||||
if (! is_string($spec['column'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($spec['column'] === $keyName || str_ends_with($spec['column'], '.'.$keyName)) {
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repositories\Concerns;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* 관계 테이블 컬럼 기준 정렬 Trait
|
||||
*
|
||||
* 목록의 정렬 기준이 원 테이블에 없고 관계 테이블에 있는 경우가 있다.
|
||||
* (예: 주문 목록의 "발송일" — `shipped_at` 은 주문이 아니라 배송 테이블에 있고, 한 주문에
|
||||
* 배송 행이 여러 건일 수 있다.)
|
||||
*
|
||||
* 이때 화면이 정렬 옵션을 제공하는데 백엔드가 그 컬럼을 모르면 422 로 조용히 실패하거나,
|
||||
* 임시로 조인을 붙이면 다음 두 문제가 생긴다.
|
||||
*
|
||||
* 1. `JOIN` + `GROUP BY` 로 집계하면 1:N 조인이 원 행을 부풀려 총 건수와 페이지 경계가 깨진다
|
||||
* 2. inner 쿼리(지연 조인)에 집계를 붙이면 건너뛸 행 전체에 대해 집계가 돌아 OFFSET 이
|
||||
* 깊어질수록 비용이 그대로 누적된다 — 지연 조인을 도입한 이유가 사라진다
|
||||
*
|
||||
* 본 Trait 은 **상관 서브쿼리 정렬**로 두 문제를 함께 피한다. 원 행 수를 바꾸지 않으므로
|
||||
* 총 건수·페이지 경계가 그대로 유지되고, `(외래키, 정렬컬럼)` 복합 인덱스가 있으면 각 행당
|
||||
* 인덱스 첫 항목 한 건만 읽는다.
|
||||
*
|
||||
* 방향과 집계를 분리해 지정하지 않는 이유: 서브쿼리를 정렬 방향과 같은 방향으로 정렬해
|
||||
* 한 건만 취하면 `desc` 는 자연히 최댓값(가장 늦은 발송), `asc` 는 최솟값(가장 이른 발송)이
|
||||
* 된다. 운영자가 "최근 발송순" 을 골랐을 때 기대하는 값과 일치한다.
|
||||
*
|
||||
* 사용 계약:
|
||||
* - 정렬 키 → 관계 스펙 맵을 리포지토리 상수(`RELATED_SORTABLE_COLUMNS`)로 선언한다
|
||||
* - 그 키들은 FormRequest 의 `sort_by` 허용 목록에도 함께 들어가야 한다
|
||||
* (게이트 ⊆ 저장소 불변식 — `SortWhitelistGateParityTest` 가 검사한다)
|
||||
* - 정렬 대상 관계 테이블에는 `(외래키, 정렬컬럼)` 복합 인덱스를 반드시 둔다
|
||||
*
|
||||
* @see ResolvesSortSpec 원 테이블 컬럼 정렬 해석 (본 Trait 과 함께 사용)
|
||||
* @see PaginatesWithDeferredJoin 서브쿼리 정렬 스펙을 그대로 받는다
|
||||
*/
|
||||
trait SortsByRelatedColumn
|
||||
{
|
||||
/**
|
||||
* 관계 테이블 컬럼 정렬을 포함해 정렬 스펙을 해석합니다.
|
||||
*
|
||||
* 요청 정렬 키가 `$relatedMap` 에 있으면 상관 서브쿼리 스펙을, 그렇지 않으면
|
||||
* `ResolvesSortSpec::resolveSortSpec()` 의 일반 컬럼 스펙을 돌려준다.
|
||||
*
|
||||
* @param array $filters 요청 유래 필터 배열
|
||||
* @param array<int, string> $allowedColumns 원 테이블 허용 정렬 컬럼
|
||||
* @param array<string, array{model: class-string<Model>, foreign_key: string, column: string}> $relatedMap 정렬 키 → 관계 스펙
|
||||
* @param Model $parent 정렬 대상 원 모델 (상관 조건의 좌변)
|
||||
* @param string $defaultColumn 기본 정렬 컬럼
|
||||
* @param string $defaultDirection 기본 정렬 방향
|
||||
* @param string $columnKey 정렬 컬럼이 담긴 필터 키
|
||||
* @param string $directionKey 정렬 방향이 담긴 필터 키
|
||||
* @return array<int, array{column: string|Builder, direction: string}> 정렬 스펙 배열
|
||||
*/
|
||||
protected function resolveSortSpecWithRelated(
|
||||
array $filters,
|
||||
array $allowedColumns,
|
||||
array $relatedMap,
|
||||
Model $parent,
|
||||
string $defaultColumn,
|
||||
string $defaultDirection = 'desc',
|
||||
string $columnKey = 'sort_by',
|
||||
string $directionKey = 'sort_order',
|
||||
): array {
|
||||
$requested = $filters[$columnKey] ?? null;
|
||||
$requested = is_string($requested) ? trim($requested) : '';
|
||||
|
||||
if ($requested === '' || ! isset($relatedMap[$requested])) {
|
||||
return $this->resolveSortSpec(
|
||||
$filters,
|
||||
$allowedColumns,
|
||||
$defaultColumn,
|
||||
$defaultDirection,
|
||||
columnKey: $columnKey,
|
||||
directionKey: $directionKey,
|
||||
);
|
||||
}
|
||||
|
||||
$direction = $this->normalizeSortDirection($filters[$directionKey] ?? null, $defaultDirection);
|
||||
|
||||
return [[
|
||||
'column' => $this->relatedSortSubquery($relatedMap[$requested], $parent, $direction),
|
||||
'direction' => $direction,
|
||||
]];
|
||||
}
|
||||
|
||||
/**
|
||||
* 관계 테이블에서 정렬 기준값 한 건을 뽑는 상관 서브쿼리를 만듭니다.
|
||||
*
|
||||
* 정렬 방향과 같은 방향으로 관계 행을 정렬해 첫 건만 취한다 —
|
||||
* `desc` 면 가장 늦은 값, `asc` 면 가장 이른 값이 기준이 된다.
|
||||
*
|
||||
* @param array{model: class-string<Model>, foreign_key: string, column: string} $spec 관계 스펙
|
||||
* @param Model $parent 원 모델
|
||||
* @param string $direction 정렬 방향 (asc|desc)
|
||||
* @return Builder 상관 서브쿼리
|
||||
*/
|
||||
protected function relatedSortSubquery(array $spec, Model $parent, string $direction): Builder
|
||||
{
|
||||
/** @var Model $related */
|
||||
$related = new $spec['model'];
|
||||
|
||||
return $related->newQuery()
|
||||
->select($related->qualifyColumn($spec['column']))
|
||||
->whereColumn($related->qualifyColumn($spec['foreign_key']), $parent->qualifyColumn($parent->getKeyName()))
|
||||
->orderBy($related->qualifyColumn($spec['column']), $direction)
|
||||
->limit(1);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface;
|
||||
use App\Enums\IdentityVerificationStatus;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
@@ -195,12 +196,15 @@ class IdentityVerificationLogRepository implements IdentityVerificationLogReposi
|
||||
}
|
||||
}
|
||||
|
||||
// 기간 필터는 사이트 타임존 기준으로 해석한다 — created_at 은 UTC 로 저장되고
|
||||
// 화면은 사이트 타임존으로 보여주므로, 입력 문자열을 그대로 비교하면 하루가 어긋난다.
|
||||
// 종료값은 시각 없이 날짜만 오는 경우(`<input type="date">`) 그날 끝까지 포함한다.
|
||||
if (! empty($filters['date_from'])) {
|
||||
$query->where('created_at', '>=', $filters['date_from']);
|
||||
$query->where('created_at', '>=', TimezoneHelper::fromSiteDateTime($filters['date_from']));
|
||||
}
|
||||
|
||||
if (! empty($filters['date_to'])) {
|
||||
$query->where('created_at', '<=', $filters['date_to']);
|
||||
$query->where('created_at', '<=', TimezoneHelper::fromSiteRangeEnd($filters['date_to']));
|
||||
}
|
||||
|
||||
$sortBy = in_array($filters['sort_by'] ?? null, ['created_at', 'attempts'], true)
|
||||
|
||||
@@ -195,7 +195,9 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
|
||||
return $query
|
||||
->orderBy('scope')
|
||||
->orderBy('target_identifier')
|
||||
->orderBy('locale');
|
||||
->orderBy('locale')
|
||||
// 전순서 보장 — 위 세 컬럼 조합이 유니크하더라도 정렬 계약을 키로 닫아 둔다
|
||||
->orderBy('id');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -21,6 +21,13 @@ class MenuRepository implements MenuRepositoryInterface
|
||||
/** 허용 정렬 컬럼 (MenuListRequest 와 동일 집합) */
|
||||
private const SORTABLE_COLUMNS = ['created_at', 'name', 'slug', 'order'];
|
||||
|
||||
/**
|
||||
* 다국어 JSON 컬럼 목록 (검색·정렬 시 로케일 경로로 풀어야 하는 컬럼)
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const TRANSLATABLE_COLUMNS = ['name'];
|
||||
|
||||
/**
|
||||
* 모든 메뉴를 조회합니다.
|
||||
*
|
||||
@@ -434,19 +441,19 @@ class MenuRepository implements MenuRepositoryInterface
|
||||
$query->where(function ($q) use ($searchableFields, $value, $operator) {
|
||||
foreach ($searchableFields as $searchField) {
|
||||
$q->orWhere(function ($subQ) use ($searchField, $value, $operator) {
|
||||
$this->applyFilterOperator($subQ, $searchField, $value, $operator);
|
||||
$this->applySearchableField($subQ, $searchField, $value, $operator);
|
||||
});
|
||||
}
|
||||
});
|
||||
} elseif (in_array($field, $searchableFields)) {
|
||||
$this->applyFilterOperator($query, $field, $value, $operator);
|
||||
$this->applySearchableField($query, $field, $value, $operator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 정렬 (허용 컬럼 화이트리스트로 해석)
|
||||
foreach ($this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'order', 'asc') as $sort) {
|
||||
$query->orderBy($sort['column'], $sort['direction']);
|
||||
$query->orderBy($this->qualifySortColumn($sort['column']), $sort['direction']);
|
||||
}
|
||||
|
||||
// 자식 메뉴도 동일한 조건 적용하여 로드
|
||||
@@ -475,6 +482,69 @@ class MenuRepository implements MenuRepositoryInterface
|
||||
* @param string $value 검색 값
|
||||
* @param string $operator 연산자 (like, eq, starts_with, ends_with)
|
||||
*/
|
||||
/**
|
||||
* 검색 대상 필드에 조건을 적용합니다. (다국어 JSON 컬럼 인지)
|
||||
*
|
||||
* `name` 은 다국어 JSON 컬럼이다. JSON 은 유니코드 이스케이프(`\uXXXX`)로 저장되므로
|
||||
* 컬럼 전체에 LIKE 를 걸면 한글·일본어 검색어가 **절대 매칭되지 않는다**
|
||||
* (저장된 바이트는 `{"ko":"대시보드"}` 이다).
|
||||
* 지원 로케일별 JSON 경로(`name->ko`)로 나눠 검색한다 — 저장소 공통 관례다.
|
||||
*
|
||||
* @param Builder $query 쿼리 빌더
|
||||
* @param string $field 필드명
|
||||
* @param string $value 검색 값
|
||||
* @param string $operator 연산자 (like, eq, starts_with, ends_with)
|
||||
*/
|
||||
private function applySearchableField($query, string $field, string $value, string $operator): void
|
||||
{
|
||||
if (! in_array($field, self::TRANSLATABLE_COLUMNS, true)) {
|
||||
$this->applyFilterOperator($query, $field, $value, $operator);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$query->where(function ($q) use ($field, $value, $operator) {
|
||||
foreach ($this->translatableLocales() as $locale) {
|
||||
$q->orWhere(function ($subQ) use ($field, $locale, $value, $operator) {
|
||||
$this->applyFilterOperator($subQ, "{$field}->{$locale}", $value, $operator);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 정렬 컬럼이 다국어 JSON 컬럼이면 현재 로케일 경로로 바꿉니다.
|
||||
*
|
||||
* JSON 원문으로 정렬하면 `{"ko":"\uXXXX...` 문자열 순서가 되어 사람이 읽는 순서와
|
||||
* 무관해진다. 화면에 보이는 값(현재 로케일)으로 정렬해야 목록 순서가 납득 가능해진다.
|
||||
*
|
||||
* @param string $column 정렬 컬럼
|
||||
* @return string 실제 정렬에 쓸 컬럼 표현
|
||||
*/
|
||||
private function qualifySortColumn(string $column): string
|
||||
{
|
||||
if (! in_array($column, self::TRANSLATABLE_COLUMNS, true)) {
|
||||
return $column;
|
||||
}
|
||||
|
||||
return $column.'->'.app()->getLocale();
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 필드가 값을 가질 수 있는 로케일 목록을 반환합니다.
|
||||
*
|
||||
* 다국어 JSON 필드의 언어 집합은 `translatable_locales` 다 — 번역 파일이 없어도
|
||||
* 데이터는 저장될 수 있으므로 UI 표시 언어(`supported_locales`)보다 넓다.
|
||||
*
|
||||
* @return array<int, string> 로케일 코드 목록
|
||||
*/
|
||||
private function translatableLocales(): array
|
||||
{
|
||||
$locales = config('app.translatable_locales', config('app.supported_locales', []));
|
||||
|
||||
return empty($locales) ? [app()->getLocale()] : array_values($locales);
|
||||
}
|
||||
|
||||
private function applyFilterOperator($query, string $field, string $value, string $operator): void
|
||||
{
|
||||
switch ($operator) {
|
||||
|
||||
@@ -33,6 +33,7 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
'channel',
|
||||
'notification_type',
|
||||
'recipient_name',
|
||||
'subject',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -30,7 +30,9 @@ class NotificationRepository implements NotificationRepositoryInterface
|
||||
// audit:allow repository-paginate-column-pruning reason: 사용자 1명에 종속된 알림함 —
|
||||
// $user->notifications() 로 이미 좁혀지고, 목록이 표시하는 본문 자체가 data(JSON) 라
|
||||
// 걷어낼 넓은 컬럼이 없다
|
||||
return $query->orderBy('created_at', 'desc')->paginate($perPage);
|
||||
// 정렬 마지막의 기본키는 전순서 보장용이다 — created_at 동률에서 페이지 경계가
|
||||
// 흔들려 인접 페이지가 같은 알림을 중복 노출하고 다른 알림을 누락하는 것을 막는다.
|
||||
return $query->orderBy('created_at', 'desc')->orderBy('id', 'desc')->paginate($perPage);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -215,8 +215,12 @@ class RoleRepository implements RoleRepositoryInterface
|
||||
}
|
||||
|
||||
// 정렬 (코어/확장 소유 역할 먼저, 그 다음 사용자 생성 역할)
|
||||
// 정렬 마지막의 기본키는 전순서 보장용이다. 시더가 일괄 생성한 역할은 created_at 이
|
||||
// 한 타임스탬프에 몰려 있어(실측: 한 값에 최대 10행) 키가 없으면 동률 구간의 순서가
|
||||
// 페이지마다 달라지고, 인접 페이지가 같은 역할을 중복 노출하면서 다른 역할을 누락한다.
|
||||
$query->orderByRaw('CASE WHEN extension_type IS NOT NULL THEN 0 ELSE 1 END')
|
||||
->orderBy('created_at', 'desc');
|
||||
->orderBy('created_at', 'desc')
|
||||
->orderBy('id', 'desc');
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 역할 정의 테이블 — 행 수가 운영상 고정(수십 건)이고 넓은 컬럼이 없다
|
||||
return $query->paginate($perPage);
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Contracts\Repositories\ScheduleHistoryRepositoryInterface;
|
||||
use App\Models\ScheduleHistory;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
@@ -68,7 +69,11 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
|
||||
*/
|
||||
public function getPaginatedByScheduleId(int $scheduleId, array $filters = []): LengthAwarePaginator
|
||||
{
|
||||
$query = ScheduleHistory::with('triggeredBy')
|
||||
// 관계는 쿼리에 미리 붙이지 않는다 — 지연 조인 트레이트가 inner/outer 양쪽에서
|
||||
// setEagerLoads([]) 로 지우므로, 여기서 with() 하면 outer 에서도 사라져
|
||||
// ScheduleHistoryResource 의 whenLoaded('triggeredBy') 가 항상 비게 된다.
|
||||
// 로드는 relations: 인자로 넘긴다.
|
||||
$query = ScheduleHistory::query()
|
||||
->where('schedule_id', $scheduleId);
|
||||
|
||||
// 상태 필터
|
||||
@@ -81,13 +86,15 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
|
||||
$query->where('trigger_type', $filters['trigger_type']);
|
||||
}
|
||||
|
||||
// 날짜 필터
|
||||
// 기간 필터 — whereDate 는 컬럼에 DATE() 를 씌워 인덱스를 못 쓰게 만든다.
|
||||
// 같은 결과를 내는 범위 조건으로 바꿔 started_at 인덱스를 살린다
|
||||
// (종료일은 그날 23:59:59.999999 까지 포함해야 whereDate 와 동일한 경계를 갖는다).
|
||||
if (! empty($filters['started_from'])) {
|
||||
$query->whereDate('started_at', '>=', $filters['started_from']);
|
||||
$query->where('started_at', '>=', Carbon::parse($filters['started_from'])->startOfDay());
|
||||
}
|
||||
|
||||
if (! empty($filters['started_to'])) {
|
||||
$query->whereDate('started_at', '<=', $filters['started_to']);
|
||||
$query->where('started_at', '<=', Carbon::parse($filters['started_to'])->endOfDay());
|
||||
}
|
||||
|
||||
// 정렬 — 요청 값은 허용 목록으로만 해석한다.
|
||||
@@ -108,6 +115,7 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
|
||||
columns: ['*'],
|
||||
sort: $sort,
|
||||
perPage: $perPage,
|
||||
relations: ['triggeredBy'],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Search\Contracts;
|
||||
|
||||
use App\Search\DTO\SearchIndexHealth;
|
||||
|
||||
/**
|
||||
* 검색 인덱스 점검·재생성 계약
|
||||
*
|
||||
* Scout 엔진마다 "인덱스" 의 실체가 다릅니다 — MySQL FULLTEXT 는 테이블에 붙은 인덱스,
|
||||
* Meilisearch/Elasticsearch 는 외부 서버의 인덱스입니다. 그래서 코어는 **무엇을 어떻게
|
||||
* 점검·재생성할지 모르는 채** 이 계약만 호출하고, 판정 방법은 각 엔진 제공자가 정합니다.
|
||||
*
|
||||
* 확장(모듈/플러그인)이 자체 검색 엔진을 등록할 때 이 계약의 구현을 함께 등록하면
|
||||
* 관리자 화면·커맨드·업데이트 절차가 코어 수정 없이 그 엔진을 다룹니다.
|
||||
* 등록은 `core.search.index_maintainers` 필터 훅에 `드라이버명 => 구현 클래스` 로 합니다.
|
||||
*
|
||||
* ```php
|
||||
* HookManager::addFilter('core.search.index_maintainers', function (array $maintainers) {
|
||||
* $maintainers['meilisearch'] = MeilisearchIndexMaintainer::class;
|
||||
*
|
||||
* return $maintainers;
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* 구현하지 않은 엔진은 점검 대상에서 제외될 뿐 검색 자체는 정상 동작합니다.
|
||||
*/
|
||||
interface SearchIndexMaintainer
|
||||
{
|
||||
/**
|
||||
* 이 유지보수기가 담당하는 Scout 드라이버명을 반환합니다.
|
||||
*
|
||||
* `config('scout.driver')` 값과 대조해 활성 엔진의 유지보수기를 고릅니다.
|
||||
*
|
||||
* @return string 드라이버명 (예: mysql-fulltext)
|
||||
*/
|
||||
public function driver(): string;
|
||||
|
||||
/**
|
||||
* 현재 환경에서 점검을 수행할 수 있는지 반환합니다.
|
||||
*
|
||||
* 예) FULLTEXT 미지원 DBMS, 외부 검색 서버 미연결 등에서 false.
|
||||
*
|
||||
* @return bool 점검 가능 여부
|
||||
*/
|
||||
public function isAvailable(): bool;
|
||||
|
||||
/**
|
||||
* 점검 불가 사유를 반환합니다.
|
||||
*
|
||||
* `isAvailable()` 이 false 일 때 운영자에게 보여 줄 문장입니다.
|
||||
* 사유를 남기지 않으면 "점검 대상 0" 과 "점검할 수 없었음" 이 구분되지 않습니다.
|
||||
*
|
||||
* @return string|null 사유 (사용 가능하면 null)
|
||||
*/
|
||||
public function unavailableReason(): ?string;
|
||||
|
||||
/**
|
||||
* 관리 중인 인덱스의 건강도를 판정합니다.
|
||||
*
|
||||
* @param array<string, mixed> $filters 엔진별 필터 (예: ['table' => 'pages'])
|
||||
* @return array<int, SearchIndexHealth> 인덱스별 판정 결과
|
||||
*/
|
||||
public function inspect(array $filters = []): array;
|
||||
|
||||
/**
|
||||
* 재생성이 필요하다고 판정된 인덱스를 재생성합니다.
|
||||
*
|
||||
* 재생성은 비용이 크고 서비스에 영향을 줄 수 있으므로, 호출자는 반드시
|
||||
* 운영자의 명시적 선택을 받은 뒤에만 호출합니다.
|
||||
*
|
||||
* @param SearchIndexHealth $health 재생성 대상 판정 결과
|
||||
* @return void
|
||||
*
|
||||
* @throws \Throwable 재생성 실패 시
|
||||
*/
|
||||
public function rebuild(SearchIndexHealth $health): void;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Search\DTO;
|
||||
|
||||
/**
|
||||
* FULLTEXT 인덱스 정의 (Value Object)
|
||||
*
|
||||
* `INFORMATION_SCHEMA` + `SHOW CREATE TABLE` 에서 읽어 온 실제 인덱스 구성입니다.
|
||||
* 재생성 시 이 값을 그대로 다시 써서 검색 동작이 달라지지 않게 합니다.
|
||||
*/
|
||||
readonly class FulltextIndexDefinition
|
||||
{
|
||||
/**
|
||||
* @param string $table 테이블명 (프리픽스 포함 — 스키마에서 읽은 실제 이름)
|
||||
* @param string $name 인덱스명
|
||||
* @param array<int, string> $columns 색인 컬럼 목록
|
||||
* @param string|null $parser 파서명 (예: ngram). 지정되지 않은 인덱스는 null
|
||||
*/
|
||||
public function __construct(
|
||||
public string $table,
|
||||
public string $name,
|
||||
public array $columns,
|
||||
public ?string $parser = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 백틱을 두른 테이블명을 반환합니다.
|
||||
*
|
||||
* @return string 예: `g7_pages`
|
||||
*/
|
||||
public function quotedTable(): string
|
||||
{
|
||||
return '`'.$this->table.'`';
|
||||
}
|
||||
|
||||
/**
|
||||
* 백틱을 두른 컬럼 목록을 반환합니다.
|
||||
*
|
||||
* @return string 예: `title`, `content`
|
||||
*/
|
||||
public function quotedColumns(): string
|
||||
{
|
||||
return '`'.implode('`, `', $this->columns).'`';
|
||||
}
|
||||
|
||||
/**
|
||||
* `ALTER TABLE ... ADD FULLTEXT` 에 붙일 파서 절을 반환합니다.
|
||||
*
|
||||
* @return string 파서가 없으면 빈 문자열
|
||||
*/
|
||||
public function parserClause(): string
|
||||
{
|
||||
return $this->parser === null ? '' : ' WITH PARSER '.$this->parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사람이 읽는 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 예: g7_pages.ft_pages_title
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return $this->table.'.'.$this->name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Search\DTO;
|
||||
|
||||
use App\Enums\SearchIndexStatus;
|
||||
|
||||
/**
|
||||
* 검색 인덱스 건강도 판정 결과 (Value Object · 엔진 중립)
|
||||
*
|
||||
* 어떤 엔진이든 공통으로 답할 수 있는 것만 필드로 둡니다 — 무엇을(`identifier`),
|
||||
* 어떤 상태로(`status`), 무엇을 근거로(`measurement`) 판정했는가.
|
||||
*
|
||||
* 엔진마다 다른 세부(FULLTEXT 의 테이블·컬럼·파서, 외부 엔진의 샤드·문서 수 등)는
|
||||
* `details` 에 담습니다. 코어가 그 내용을 해석하지 않으므로 새 엔진이 추가되어도
|
||||
* 코어를 고칠 일이 없습니다.
|
||||
*
|
||||
* `context` 는 엔진 구현이 재생성에 필요한 자기 정보를 실어 두는 자리입니다
|
||||
* (코어는 그대로 되돌려 줄 뿐 들여다보지 않습니다).
|
||||
*/
|
||||
readonly class SearchIndexHealth
|
||||
{
|
||||
/**
|
||||
* @param string $driver 판정을 만든 Scout 드라이버명
|
||||
* @param string $identifier 인덱스 식별자 (엔진 내에서 유일)
|
||||
* @param SearchIndexStatus $status 판정 등급
|
||||
* @param string $measurement 판정 근거 수치·사유 (사람이 읽는 한 줄)
|
||||
* @param array<string, mixed> $details 엔진별 부가 정보 (표시 전용)
|
||||
* @param array<string, mixed> $context 재생성에 필요한 엔진 내부 정보
|
||||
*/
|
||||
public function __construct(
|
||||
public string $driver,
|
||||
public string $identifier,
|
||||
public SearchIndexStatus $status,
|
||||
public string $measurement = '',
|
||||
public array $details = [],
|
||||
public array $context = [],
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 재생성 대상인지 여부.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function needsRebuild(): bool
|
||||
{
|
||||
return $this->status === SearchIndexStatus::Stale;
|
||||
}
|
||||
|
||||
/**
|
||||
* 기계 판독용 배열로 반환합니다.
|
||||
*
|
||||
* `context` 는 엔진 내부 정보라 응답에 싣지 않습니다.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'driver' => $this->driver,
|
||||
'identifier' => $this->identifier,
|
||||
'status' => $this->status->value,
|
||||
'status_label' => $this->status->label(),
|
||||
'measurement' => $this->measurement,
|
||||
'details' => $this->details,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace App\Search\DTO;
|
||||
|
||||
/**
|
||||
* 검색 인덱스 재생성 실행 보고 (Value Object · 엔진 중립)
|
||||
*
|
||||
* 커맨드는 콘솔 출력으로, 컨트롤러는 API 응답으로 같은 값을 씁니다.
|
||||
*
|
||||
* `remaining` 은 재생성 **후 다시 점검한** 잔존 목록입니다 — "재생성했다" 와
|
||||
* "복구됐다" 는 다른 사실이라 따로 담습니다.
|
||||
*/
|
||||
readonly class SearchIndexRepairReport
|
||||
{
|
||||
/**
|
||||
* @param string $driver 대상 Scout 드라이버명
|
||||
* @param int $inspected 점검한 인덱스 수
|
||||
* @param array<int, string> $repaired 재생성 성공 인덱스 식별자
|
||||
* @param array<string, string> $failed 재생성 실패 [식별자 => 사유]
|
||||
* @param array<int, string> $remaining 재생성 후에도 색인 누락으로 남은 식별자
|
||||
* @param bool $available 이 엔진에서 점검을 수행할 수 있었는지
|
||||
* @param string|null $reason 수행 불가 사유 (available=false 일 때)
|
||||
*/
|
||||
public function __construct(
|
||||
public string $driver,
|
||||
public int $inspected = 0,
|
||||
public array $repaired = [],
|
||||
public array $failed = [],
|
||||
public array $remaining = [],
|
||||
public bool $available = true,
|
||||
public ?string $reason = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 점검을 수행할 수 없었던 경우의 보고를 만듭니다.
|
||||
*
|
||||
* @param string $driver 드라이버명
|
||||
* @param string|null $reason 사유
|
||||
* @return self
|
||||
*/
|
||||
public static function unavailable(string $driver, ?string $reason): self
|
||||
{
|
||||
return new self(driver: $driver, available: false, reason: $reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 재생성 대상이 없었을 때의 보고를 만듭니다.
|
||||
*
|
||||
* @param string $driver 드라이버명
|
||||
* @param int $inspected 점검한 인덱스 수
|
||||
* @return self
|
||||
*/
|
||||
public static function nothingToDo(string $driver, int $inspected): self
|
||||
{
|
||||
return new self(driver: $driver, inspected: $inspected);
|
||||
}
|
||||
|
||||
/**
|
||||
* 재생성을 실제로 수행했는지 여부.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function didRebuild(): bool
|
||||
{
|
||||
return $this->repaired !== [] || $this->failed !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 전부 복구되었는지 여부 (실패·잔존 모두 없음).
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isClean(): bool
|
||||
{
|
||||
return $this->failed === [] && $this->remaining === [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 줄 요약을 반환합니다.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function summary(): string
|
||||
{
|
||||
if (! $this->available) {
|
||||
return $this->reason ?? __('search.index.unavailable', ['driver' => $this->driver]);
|
||||
}
|
||||
|
||||
if (! $this->didRebuild()) {
|
||||
return __('search.index.report.nothing_to_do', ['count' => $this->inspected]);
|
||||
}
|
||||
|
||||
return __('search.index.report.rebuilt', [
|
||||
'inspected' => $this->inspected,
|
||||
'repaired' => count($this->repaired),
|
||||
'failed' => count($this->failed),
|
||||
'remaining' => count($this->remaining),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 기계 판독용 배열로 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'driver' => $this->driver,
|
||||
'available' => $this->available,
|
||||
'reason' => $this->reason,
|
||||
'inspected' => $this->inspected,
|
||||
'repaired' => $this->repaired,
|
||||
'failed' => $this->failed,
|
||||
'remaining' => $this->remaining,
|
||||
'summary' => $this->summary(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Search\Engines\Maintenance;
|
||||
|
||||
use App\Enums\SearchIndexStatus;
|
||||
use App\Search\Contracts\SearchIndexMaintainer;
|
||||
use App\Search\DTO\FulltextIndexDefinition;
|
||||
use App\Search\DTO\SearchIndexHealth;
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
use App\Search\FulltextIndexInspector;
|
||||
|
||||
/**
|
||||
* `mysql-fulltext` 드라이버의 인덱스 유지보수기
|
||||
*
|
||||
* 엔진 중립 계약(`SearchIndexMaintainer`)을 MySQL FULLTEXT 방식으로 구현합니다.
|
||||
* 판정 방법(자기 매칭 프로브)과 재생성 방법(같은 정의로 DROP/ADD)은
|
||||
* `FulltextIndexInspector` 가 갖고 있고, 이 클래스는 그 결과를 엔진 중립 DTO 로 옮깁니다.
|
||||
*
|
||||
* 다른 엔진(Meilisearch 등)은 이 클래스를 상속하지 않고 계약을 각자 구현합니다 —
|
||||
* 인덱스의 실체가 다르므로 공유할 구현이 없습니다.
|
||||
*/
|
||||
class FulltextIndexMaintainer implements SearchIndexMaintainer
|
||||
{
|
||||
/** 이 유지보수기가 담당하는 Scout 드라이버명 */
|
||||
public const DRIVER = 'mysql-fulltext';
|
||||
|
||||
/**
|
||||
* @param FulltextIndexInspector $inspector FULLTEXT 인덱스 점검기
|
||||
*/
|
||||
public function __construct(private readonly FulltextIndexInspector $inspector) {}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function driver(): string
|
||||
{
|
||||
return self::DRIVER;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
return DatabaseFulltextEngine::supportsFulltext();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function unavailableReason(): ?string
|
||||
{
|
||||
return $this->isAvailable()
|
||||
? null
|
||||
: __('search.index.fulltext.unsupported_driver');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* 지원 필터: `table`(테이블명, 프리픽스 생략 가능) · `index`(인덱스명) · `samples`(표본 행 수)
|
||||
*/
|
||||
public function inspect(array $filters = []): array
|
||||
{
|
||||
$sampleSize = (int) ($filters['samples'] ?? FulltextIndexInspector::DEFAULT_SAMPLE_SIZE);
|
||||
|
||||
$results = $this->inspector->inspectAll(
|
||||
table: isset($filters['table']) ? (string) $filters['table'] : null,
|
||||
index: isset($filters['index']) ? (string) $filters['index'] : null,
|
||||
sampleSize: max(1, $sampleSize),
|
||||
);
|
||||
|
||||
return array_map(fn (array $result) => $this->toHealth($result), $results);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function rebuild(SearchIndexHealth $health): void
|
||||
{
|
||||
$context = $health->context;
|
||||
|
||||
$this->inspector->rebuild(new FulltextIndexDefinition(
|
||||
table: (string) ($context['table'] ?? ''),
|
||||
name: (string) ($context['name'] ?? ''),
|
||||
columns: (array) ($context['columns'] ?? []),
|
||||
parser: isset($context['parser']) ? (string) $context['parser'] : null,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 점검기 결과를 엔진 중립 판정 DTO 로 옮깁니다.
|
||||
*
|
||||
* @param array{definition: FulltextIndexDefinition, status: SearchIndexStatus, probed: int, found: int, reason: ?string} $result 점검기 결과
|
||||
* @return SearchIndexHealth
|
||||
*/
|
||||
private function toHealth(array $result): SearchIndexHealth
|
||||
{
|
||||
$definition = $result['definition'];
|
||||
$status = $result['status'];
|
||||
|
||||
$measurement = $status === SearchIndexStatus::Skipped
|
||||
? (string) $result['reason']
|
||||
: __('search.index.fulltext.self_match', ['found' => $result['found'], 'probed' => $result['probed']]);
|
||||
|
||||
return new SearchIndexHealth(
|
||||
driver: self::DRIVER,
|
||||
identifier: $definition->label(),
|
||||
status: $status,
|
||||
measurement: $measurement,
|
||||
details: [
|
||||
'table' => $definition->table,
|
||||
'index' => $definition->name,
|
||||
'columns' => $definition->columns,
|
||||
'parser' => $definition->parser,
|
||||
'probed' => $result['probed'],
|
||||
'found' => $result['found'],
|
||||
],
|
||||
context: [
|
||||
'table' => $definition->table,
|
||||
'name' => $definition->name,
|
||||
'columns' => $definition->columns,
|
||||
'parser' => $definition->parser,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
<?php
|
||||
|
||||
namespace App\Search;
|
||||
|
||||
use App\Enums\SearchIndexStatus;
|
||||
use App\Search\DTO\FulltextIndexDefinition;
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* FULLTEXT 인덱스 건강도 점검·복구기
|
||||
*
|
||||
* 인덱스는 존재하는데 **행이 색인되어 있지 않아** `MATCH ... AGAINST` 가 아무것도
|
||||
* 돌려주지 않는 상태를 검출하고, 같은 정의로 재생성해 복구합니다. 이 상태는
|
||||
* 오류를 남기지 않고 "검색 결과 0건" 으로만 나타나므로 로그·예외로는 드러나지 않습니다.
|
||||
*
|
||||
* 대상은 하드코딩하지 않습니다 — `INFORMATION_SCHEMA` 에서 현재 스키마의 FULLTEXT
|
||||
* 인덱스를 전수 수집하므로 코어·모듈·플러그인이 나중에 추가하는 인덱스도 자동 포함됩니다.
|
||||
*
|
||||
* ## 판정 방법 — 자기 매칭(self-match)
|
||||
*
|
||||
* 표본 행을 뽑아 **그 행 자신의 내용에서 만든 검색어로 그 행을 찾을 수 있는지** 봅니다.
|
||||
* 특정 키워드를 사람이 골라 넣지 않으므로 어떤 테이블·언어에도 그대로 적용됩니다.
|
||||
*
|
||||
* 토큰은 행마다 여러 개 만듭니다. 하나만 쓰면 토크나이저 특성으로 인한 실패를
|
||||
* 색인 누락으로 오판합니다 — 예를 들어 ngram(`ngram_token_size=2`) 은 `Basic` 을
|
||||
* `Ba/as/si/ic` 로 쪼개는데 그중 `as` 가 기본 불용어라 구문 검색이 깨집니다.
|
||||
* 그래서 **한 행이 어떤 토큰으로도 자신을 찾지 못할 때만** 그 행을 실패로 셉니다.
|
||||
*
|
||||
* ## 판정 등급
|
||||
*
|
||||
* - `healthy` — 표본 전 행이 자기 자신을 찾는다
|
||||
* - `degraded` — 일부만 찾는다. 토크나이저 특성일 수도, 일부 행만 누락된 것일 수도 있어
|
||||
* 자동 복구 대상에서 제외하고 수치만 보고한다
|
||||
* - `stale` — 표본 중 **한 행도** 자기 자신을 찾지 못한다. 색인 누락의 신호이며 복구 대상
|
||||
* - `skipped` — 표본을 만들 수 없다(행이 없거나 내용이 모두 비어 토큰 추출 불가). 사유·수치 기재
|
||||
*/
|
||||
class FulltextIndexInspector
|
||||
{
|
||||
/** 인덱스당 기본 표본 행 수 */
|
||||
public const DEFAULT_SAMPLE_SIZE = 5;
|
||||
|
||||
/** 한 행에서 만들 최대 토큰 수 */
|
||||
private const MAX_TOKENS_PER_ROW = 4;
|
||||
|
||||
/** 토큰 최대 길이 (긴 토큰은 구문 검색 비용만 늘린다) */
|
||||
private const MAX_TOKEN_LENGTH = 12;
|
||||
|
||||
/**
|
||||
* 현재 스키마의 FULLTEXT 인덱스를 전수 수집합니다.
|
||||
*
|
||||
* @param string|null $table 테이블명 필터 (프리픽스 포함/미포함 모두 허용)
|
||||
* @param string|null $index 인덱스명 필터
|
||||
* @return array<int, FulltextIndexDefinition>
|
||||
*/
|
||||
public function discover(?string $table = null, ?string $index = null): array
|
||||
{
|
||||
if (! DatabaseFulltextEngine::supportsFulltext()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = DB::select(
|
||||
'SELECT TABLE_NAME AS table_name, INDEX_NAME AS index_name,
|
||||
GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) AS columns
|
||||
FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND INDEX_TYPE = ?
|
||||
GROUP BY TABLE_NAME, INDEX_NAME
|
||||
ORDER BY TABLE_NAME, INDEX_NAME',
|
||||
['FULLTEXT']
|
||||
);
|
||||
|
||||
$prefix = DB::getTablePrefix();
|
||||
$wanted = $table === null ? null : [$table, $prefix.$table];
|
||||
|
||||
$definitions = [];
|
||||
foreach ($rows as $row) {
|
||||
if ($wanted !== null && ! in_array($row->table_name, $wanted, true)) {
|
||||
continue;
|
||||
}
|
||||
if ($index !== null && $row->index_name !== $index) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$definitions[] = new FulltextIndexDefinition(
|
||||
table: $row->table_name,
|
||||
name: $row->index_name,
|
||||
columns: explode(',', (string) $row->columns),
|
||||
parser: $this->resolveParser($row->table_name, $row->index_name),
|
||||
);
|
||||
}
|
||||
|
||||
return $definitions;
|
||||
}
|
||||
|
||||
/**
|
||||
* 인덱스 하나의 건강도를 판정합니다.
|
||||
*
|
||||
* 엔진 중립 DTO 로의 변환은 호출자(`FulltextIndexMaintainer`)가 합니다 — 이 클래스는
|
||||
* FULLTEXT 고유의 판정만 담당하고 표현 형식을 알지 않습니다.
|
||||
*
|
||||
* @param FulltextIndexDefinition $definition 인덱스 정의
|
||||
* @param int $sampleSize 표본 행 수
|
||||
* @return array{definition: FulltextIndexDefinition, status: SearchIndexStatus, probed: int, found: int, reason: string|null}
|
||||
*/
|
||||
public function inspect(FulltextIndexDefinition $definition, int $sampleSize = self::DEFAULT_SAMPLE_SIZE): array
|
||||
{
|
||||
$key = $this->resolvePrimaryKey($definition->table);
|
||||
|
||||
if ($key === null) {
|
||||
return $this->skipped($definition, __('search.index.fulltext.skip.no_single_pk'));
|
||||
}
|
||||
|
||||
$samples = $this->sampleRows($definition, $key, $sampleSize);
|
||||
|
||||
if ($samples === []) {
|
||||
return $this->skipped($definition, __('search.index.fulltext.skip.no_rows'));
|
||||
}
|
||||
|
||||
$probed = 0;
|
||||
$found = 0;
|
||||
|
||||
foreach ($samples as $sample) {
|
||||
$tokens = $this->buildTokens((string) $sample->body);
|
||||
|
||||
if ($tokens === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$probed++;
|
||||
|
||||
if ($this->rowFindsItself($definition, $key, $sample->pk, $tokens)) {
|
||||
$found++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($probed === 0) {
|
||||
return $this->skipped($definition, __('search.index.fulltext.skip.no_tokens'));
|
||||
}
|
||||
|
||||
return [
|
||||
'definition' => $definition,
|
||||
'status' => match (true) {
|
||||
$found === 0 => SearchIndexStatus::Stale,
|
||||
$found < $probed => SearchIndexStatus::Degraded,
|
||||
default => SearchIndexStatus::Healthy,
|
||||
},
|
||||
'probed' => $probed,
|
||||
'found' => $found,
|
||||
'reason' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체(또는 필터된) 인덱스의 건강도를 판정합니다.
|
||||
*
|
||||
* @param string|null $table 테이블명 필터
|
||||
* @param string|null $index 인덱스명 필터
|
||||
* @param int $sampleSize 표본 행 수
|
||||
* @return array<int, array{definition: FulltextIndexDefinition, status: SearchIndexStatus, probed: int, found: int, reason: string|null}>
|
||||
*/
|
||||
public function inspectAll(?string $table = null, ?string $index = null, int $sampleSize = self::DEFAULT_SAMPLE_SIZE): array
|
||||
{
|
||||
return array_map(
|
||||
fn (FulltextIndexDefinition $definition) => $this->inspect($definition, $sampleSize),
|
||||
$this->discover($table, $index)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 판정 불가 결과를 만듭니다.
|
||||
*
|
||||
* @param FulltextIndexDefinition $definition 인덱스 정의
|
||||
* @param string $reason 사유
|
||||
* @return array{definition: FulltextIndexDefinition, status: SearchIndexStatus, probed: int, found: int, reason: string}
|
||||
*/
|
||||
private function skipped(FulltextIndexDefinition $definition, string $reason): array
|
||||
{
|
||||
return [
|
||||
'definition' => $definition,
|
||||
'status' => SearchIndexStatus::Skipped,
|
||||
'probed' => 0,
|
||||
'found' => 0,
|
||||
'reason' => $reason,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 인덱스를 같은 정의로 재생성합니다.
|
||||
*
|
||||
* 컬럼 구성과 파서를 그대로 유지하므로 검색 동작이 달라지지 않습니다.
|
||||
* 재생성 중에는 대상 테이블이 잠기므로 대용량 테이블에서는 시간이 걸립니다.
|
||||
*
|
||||
* @param FulltextIndexDefinition $definition 인덱스 정의
|
||||
* @return void
|
||||
*
|
||||
* @throws Throwable 재생성 실패 시 (드롭까지만 되고 끝나지 않도록 예외를 그대로 전파)
|
||||
*/
|
||||
public function rebuild(FulltextIndexDefinition $definition): void
|
||||
{
|
||||
$table = $definition->quotedTable();
|
||||
$name = $definition->name;
|
||||
|
||||
DB::statement("ALTER TABLE {$table} DROP INDEX `{$name}`");
|
||||
|
||||
try {
|
||||
DB::statement(
|
||||
"ALTER TABLE {$table} ADD FULLTEXT INDEX `{$name}` ({$definition->quotedColumns()})"
|
||||
.$definition->parserClause()
|
||||
);
|
||||
} catch (Throwable $e) {
|
||||
// 드롭만 되고 끝나면 검색이 아예 죽는다 — 원 정의로 되돌린 뒤 예외를 전파한다
|
||||
$this->restoreQuietly($definition);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 인덱스의 파서를 조회합니다.
|
||||
*
|
||||
* `INFORMATION_SCHEMA` 는 파서를 노출하지 않으므로 `SHOW CREATE TABLE` 정의에서 읽습니다.
|
||||
*
|
||||
* @param string $table 테이블명 (프리픽스 포함)
|
||||
* @param string $index 인덱스명
|
||||
* @return string|null 파서명 (없으면 null)
|
||||
*/
|
||||
private function resolveParser(string $table, string $index): ?string
|
||||
{
|
||||
try {
|
||||
$create = DB::selectOne('SHOW CREATE TABLE `'.$table.'`');
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$sql = (array) $create;
|
||||
$ddl = (string) (($sql['Create Table'] ?? $sql['Create View'] ?? ''));
|
||||
|
||||
$pattern = '/FULLTEXT\s+KEY\s+`'.preg_quote($index, '/').'`[^\n]*?WITH\s+PARSER\s+`?(\w+)`?/i';
|
||||
|
||||
return preg_match($pattern, $ddl, $m) === 1 ? $m[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 테이블의 단일 컬럼 기본키를 조회합니다.
|
||||
*
|
||||
* @param string $table 테이블명 (프리픽스 포함)
|
||||
* @return string|null 기본키 컬럼명 (복합키·부재 시 null)
|
||||
*/
|
||||
private function resolvePrimaryKey(string $table): ?string
|
||||
{
|
||||
$rows = DB::select(
|
||||
'SELECT COLUMN_NAME AS column_name FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND INDEX_NAME = ?
|
||||
ORDER BY SEQ_IN_INDEX',
|
||||
[$table, 'PRIMARY']
|
||||
);
|
||||
|
||||
return count($rows) === 1 ? (string) $rows[0]->column_name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 색인 컬럼에 내용이 있는 표본 행을 뽑습니다.
|
||||
*
|
||||
* @param FulltextIndexDefinition $definition 인덱스 정의
|
||||
* @param string $key 기본키 컬럼명
|
||||
* @param int $sampleSize 표본 행 수
|
||||
* @return array<int, object> `pk`, `body` 를 가진 행 배열
|
||||
*/
|
||||
private function sampleRows(FulltextIndexDefinition $definition, string $key, int $sampleSize): array
|
||||
{
|
||||
$body = "CONCAT_WS(' ', {$definition->quotedColumns()})";
|
||||
|
||||
return DB::select(
|
||||
"SELECT `{$key}` AS pk, {$body} AS body
|
||||
FROM {$definition->quotedTable()}
|
||||
WHERE {$body} <> '' AND {$body} IS NOT NULL
|
||||
ORDER BY `{$key}` DESC
|
||||
LIMIT ".max(1, $sampleSize)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 내용에서 검색 토큰 후보를 만듭니다.
|
||||
*
|
||||
* 비-라틴(한글·한자 등) 조각을 먼저 담습니다 — 기본 불용어 목록이 영어라
|
||||
* 라틴 토큰보다 토크나이저 영향을 덜 받습니다.
|
||||
*
|
||||
* @param string $text 행 내용
|
||||
* @return array<int, string> 토큰 후보 목록
|
||||
*/
|
||||
private function buildTokens(string $text): array
|
||||
{
|
||||
// 부울 모드 연산자(+ - > < ( ) ~ * " @)와 구분자를 제거한다
|
||||
$normalized = preg_replace('/[^\p{L}\p{N}]+/u', ' ', $text) ?? '';
|
||||
$pieces = array_values(array_filter(
|
||||
explode(' ', $normalized),
|
||||
fn (string $piece) => mb_strlen($piece) >= 2
|
||||
));
|
||||
|
||||
if ($pieces === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 길이 내림차순 — 짧은 조각일수록 불용어·잡음일 확률이 높다
|
||||
usort($pieces, fn (string $a, string $b) => mb_strlen($b) <=> mb_strlen($a));
|
||||
|
||||
$nonLatin = [];
|
||||
$latin = [];
|
||||
|
||||
foreach ($pieces as $piece) {
|
||||
$token = mb_substr($piece, 0, self::MAX_TOKEN_LENGTH);
|
||||
|
||||
if (preg_match('/^[\x00-\x7F]+$/', $token) === 1) {
|
||||
$latin[] = $token;
|
||||
} else {
|
||||
$nonLatin[] = $token;
|
||||
}
|
||||
}
|
||||
|
||||
return array_slice(array_values(array_unique([...$nonLatin, ...$latin])), 0, self::MAX_TOKENS_PER_ROW);
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 행이 자기 토큰 중 하나로 자신을 찾을 수 있는지 확인합니다.
|
||||
*
|
||||
* @param FulltextIndexDefinition $definition 인덱스 정의
|
||||
* @param string $key 기본키 컬럼명
|
||||
* @param mixed $pk 행의 기본키 값
|
||||
* @param array<int, string> $tokens 토큰 후보
|
||||
* @return bool 하나라도 찾으면 true
|
||||
*/
|
||||
private function rowFindsItself(FulltextIndexDefinition $definition, string $key, mixed $pk, array $tokens): bool
|
||||
{
|
||||
foreach ($tokens as $token) {
|
||||
$hit = DB::selectOne(
|
||||
"SELECT COUNT(*) AS hits FROM {$definition->quotedTable()}
|
||||
WHERE `{$key}` = ? AND MATCH({$definition->quotedColumns()}) AGAINST(? IN BOOLEAN MODE)",
|
||||
[$pk, '"'.$token.'"']
|
||||
);
|
||||
|
||||
if ((int) ($hit->hits ?? 0) > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 재생성 실패 시 원 정의로 되돌립니다 (실패해도 원 예외를 가리지 않도록 조용히 처리).
|
||||
*
|
||||
* @param FulltextIndexDefinition $definition 인덱스 정의
|
||||
* @return void
|
||||
*/
|
||||
private function restoreQuietly(FulltextIndexDefinition $definition): void
|
||||
{
|
||||
try {
|
||||
DB::statement(
|
||||
"ALTER TABLE {$definition->quotedTable()} ADD FULLTEXT INDEX `{$definition->name}` "
|
||||
."({$definition->quotedColumns()})".$definition->parserClause()
|
||||
);
|
||||
} catch (Throwable) {
|
||||
// 되돌리기까지 실패하면 원 예외가 더 중요한 정보다
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace App\Search;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Search\Contracts\SearchIndexMaintainer;
|
||||
use App\Search\DTO\SearchIndexHealth;
|
||||
use App\Search\DTO\SearchIndexRepairReport;
|
||||
use App\Search\Engines\Maintenance\FulltextIndexMaintainer;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 검색 인덱스 점검·재생성 진입점
|
||||
*
|
||||
* 활성 Scout 드라이버에 해당하는 `SearchIndexMaintainer` 를 찾아 위임합니다.
|
||||
* 코어는 어떤 엔진이 무엇을 어떻게 점검하는지 알지 못하며, 등급(`SearchIndexStatus`)만
|
||||
* 보고 재생성 대상을 고릅니다.
|
||||
*
|
||||
* ## 등록
|
||||
*
|
||||
* 기본 제공은 `mysql-fulltext` 하나이고, 확장은 필터 훅으로 자기 엔진의 유지보수기를
|
||||
* 추가합니다.
|
||||
*
|
||||
* ```php
|
||||
* HookManager::addFilter('core.search.index_maintainers', function (array $maintainers) {
|
||||
* $maintainers['meilisearch'] = MeilisearchIndexMaintainer::class;
|
||||
*
|
||||
* return $maintainers;
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* 유지보수기를 등록하지 않은 엔진은 점검 대상에서 빠질 뿐 검색은 그대로 동작합니다.
|
||||
* 그 경우 `hasMaintainer()` 가 false 이고, 화면·커맨드는 "이 엔진은 점검을 제공하지
|
||||
* 않는다" 를 명시합니다 — 점검 결과 0건과 구분되어야 하기 때문입니다.
|
||||
*
|
||||
* ## 재생성은 언제나 선택 사항이다
|
||||
*
|
||||
* 재생성 비용은 엔진에 따라 테이블 잠금(FULLTEXT)이나 전체 재색인(외부 엔진)입니다.
|
||||
* 운영 중인 사이트에서 확장 업데이트만으로 그 비용이 발생하면 안 되므로,
|
||||
* 이 클래스는 어떤 자동 트리거에도 연결하지 않고 호출자의 명시적 요청만 수행합니다.
|
||||
*/
|
||||
class SearchIndexMaintenanceManager
|
||||
{
|
||||
/** 확장이 유지보수기를 등록하는 필터 훅 */
|
||||
public const MAINTAINERS_FILTER = 'core.search.index_maintainers';
|
||||
|
||||
/** 해석된 유지보수기 캐시 (요청 수명) */
|
||||
private ?SearchIndexMaintainer $resolved = null;
|
||||
|
||||
/** 해석을 시도했는지 여부 (없음도 캐시하기 위함) */
|
||||
private bool $resolvedAttempted = false;
|
||||
|
||||
/**
|
||||
* 현재 활성 Scout 드라이버명을 반환합니다.
|
||||
*
|
||||
* @return string 드라이버명
|
||||
*/
|
||||
public function driver(): string
|
||||
{
|
||||
return (string) config('scout.driver', 'mysql-fulltext');
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록된 유지보수기 맵을 반환합니다.
|
||||
*
|
||||
* @return array<string, class-string<SearchIndexMaintainer>> 드라이버명 => 구현 클래스
|
||||
*/
|
||||
public function registered(): array
|
||||
{
|
||||
$maintainers = [
|
||||
'mysql-fulltext' => FulltextIndexMaintainer::class,
|
||||
];
|
||||
|
||||
$maintainers = HookManager::applyFilters(self::MAINTAINERS_FILTER, $maintainers);
|
||||
|
||||
return is_array($maintainers) ? $maintainers : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 드라이버의 유지보수기를 반환합니다.
|
||||
*
|
||||
* @return SearchIndexMaintainer|null 등록되지 않았으면 null
|
||||
*/
|
||||
public function maintainer(): ?SearchIndexMaintainer
|
||||
{
|
||||
if ($this->resolvedAttempted) {
|
||||
return $this->resolved;
|
||||
}
|
||||
|
||||
$this->resolvedAttempted = true;
|
||||
$class = $this->registered()[$this->driver()] ?? null;
|
||||
|
||||
if ($class === null) {
|
||||
return $this->resolved = null;
|
||||
}
|
||||
|
||||
try {
|
||||
$instance = app($class);
|
||||
} catch (Throwable $e) {
|
||||
Log::warning('검색 인덱스 유지보수기 생성 실패', [
|
||||
'driver' => $this->driver(),
|
||||
'class' => $class,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->resolved = null;
|
||||
}
|
||||
|
||||
if (! $instance instanceof SearchIndexMaintainer) {
|
||||
Log::warning('검색 인덱스 유지보수기가 계약을 구현하지 않음', [
|
||||
'driver' => $this->driver(),
|
||||
'class' => $class,
|
||||
]);
|
||||
|
||||
return $this->resolved = null;
|
||||
}
|
||||
|
||||
return $this->resolved = $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 엔진이 점검을 제공하는지 여부.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasMaintainer(): bool
|
||||
{
|
||||
return $this->maintainer() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 엔진의 인덱스를 점검합니다.
|
||||
*
|
||||
* @param array<string, mixed> $filters 엔진별 필터
|
||||
* @return array<int, SearchIndexHealth>
|
||||
*/
|
||||
public function inspect(array $filters = []): array
|
||||
{
|
||||
$maintainer = $this->maintainer();
|
||||
|
||||
if ($maintainer === null || ! $maintainer->isAvailable()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $maintainer->inspect($filters);
|
||||
}
|
||||
|
||||
/**
|
||||
* 점검 불가 사유를 반환합니다.
|
||||
*
|
||||
* @return string|null 점검 가능하면 null
|
||||
*/
|
||||
public function unavailableReason(): ?string
|
||||
{
|
||||
$maintainer = $this->maintainer();
|
||||
|
||||
if ($maintainer === null) {
|
||||
return __('search.index.no_maintainer', ['driver' => $this->driver()]);
|
||||
}
|
||||
|
||||
return $maintainer->isAvailable() ? null : $maintainer->unavailableReason();
|
||||
}
|
||||
|
||||
/**
|
||||
* 색인이 누락된 인덱스를 재생성합니다.
|
||||
*
|
||||
* 재생성 후 **다시 점검해서** 잔존 여부를 담습니다 — 재생성했다는 사실만으로
|
||||
* 복구됐다고 단정하지 않습니다.
|
||||
*
|
||||
* @param array<string, mixed> $filters 엔진별 필터
|
||||
* @return SearchIndexRepairReport 실행 보고
|
||||
*/
|
||||
public function repairStale(array $filters = []): SearchIndexRepairReport
|
||||
{
|
||||
$maintainer = $this->maintainer();
|
||||
|
||||
if ($maintainer === null) {
|
||||
return SearchIndexRepairReport::unavailable($this->driver(), $this->unavailableReason());
|
||||
}
|
||||
|
||||
if (! $maintainer->isAvailable()) {
|
||||
return SearchIndexRepairReport::unavailable($this->driver(), $maintainer->unavailableReason());
|
||||
}
|
||||
|
||||
$before = $maintainer->inspect($filters);
|
||||
$targets = array_values(array_filter($before, fn (SearchIndexHealth $h) => $h->needsRebuild()));
|
||||
|
||||
if ($targets === []) {
|
||||
return SearchIndexRepairReport::nothingToDo($this->driver(), count($before));
|
||||
}
|
||||
|
||||
$repaired = [];
|
||||
$failed = [];
|
||||
|
||||
foreach ($targets as $target) {
|
||||
try {
|
||||
$maintainer->rebuild($target);
|
||||
$repaired[] = $target->identifier;
|
||||
} catch (Throwable $e) {
|
||||
$failed[$target->identifier] = $e->getMessage();
|
||||
Log::error('검색 인덱스 재생성 실패', [
|
||||
'driver' => $this->driver(),
|
||||
'index' => $target->identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$after = $maintainer->inspect($filters);
|
||||
$remaining = array_values(array_map(
|
||||
fn (SearchIndexHealth $h) => $h->identifier,
|
||||
array_filter($after, fn (SearchIndexHealth $h) => $h->needsRebuild())
|
||||
));
|
||||
|
||||
Log::info('검색 인덱스 재생성 수행', [
|
||||
'driver' => $this->driver(),
|
||||
'inspected' => count($after),
|
||||
'repaired' => $repaired,
|
||||
'failed' => array_keys($failed),
|
||||
'remaining' => $remaining,
|
||||
]);
|
||||
|
||||
return new SearchIndexRepairReport(
|
||||
driver: $this->driver(),
|
||||
inspected: count($after),
|
||||
repaired: $repaired,
|
||||
failed: $failed,
|
||||
remaining: $remaining,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -256,9 +256,10 @@ class LanguagePackService
|
||||
* 코어/번들 확장의 `lang/{ko,en}/` 디렉토리를 자동 스캔하여 가상 보호 LanguagePack
|
||||
* 인스턴스 컬렉션을 반환합니다 (요구사항 #1, #2).
|
||||
*
|
||||
* 스캔 대상:
|
||||
* 스캔 대상 — **런타임이 실제로 로드하는 경로**와 같아야 한다. 어긋나면 관리자 화면이
|
||||
* "내장 번역" 으로 보여주는 것과 화면에 나오는 문구의 출처가 달라진다.
|
||||
* - 코어: lang/{ko,en}/
|
||||
* - 번들 모듈: modules/_bundled/{id}/resources/lang/{ko,en}/
|
||||
* - 번들 모듈: modules/_bundled/{id}/src/lang/{ko,en}/ (TranslationServiceProvider 기준)
|
||||
* - 번들 플러그인: plugins/_bundled/{id}/lang/{ko,en}/
|
||||
* - 번들 템플릿: templates/_bundled/{id}/lang/{ko,en}.json
|
||||
*
|
||||
@@ -288,11 +289,11 @@ class LanguagePackService
|
||||
}
|
||||
}
|
||||
|
||||
// 번들 모듈
|
||||
// 번들 모듈 (런타임 등록 경로 = src/lang)
|
||||
$packs = $packs->concat($this->scanBundledExtensionLang(
|
||||
bundledRoot: 'modules/_bundled',
|
||||
scope: LanguagePackScope::Module->value,
|
||||
langSubpath: 'resources/lang/'.$locale,
|
||||
langSubpath: 'src/lang/'.$locale,
|
||||
locale: $locale,
|
||||
filters: $filters,
|
||||
));
|
||||
|
||||
Reference in new issue
Block a user