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
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user