계측 축이 "목록 SELECT" 하나였고 프로파일 12종이 커맨드 파일에 하드코딩돼 있어 확장이 자기 대상을 추가할 수 없었다. 확장이 설치·제거되는 설치본마다 "실제로 존재하는 대상"이 달라지므로, 대상을 소유자가 선언하고 코어가 수집하도록 뒤집었다. - 선언 지점 두 곳, 스키마 하나: 코어 config/benchmark.php, 확장 getBenchmarkProfiles (모듈/플러그인). 수집은 method_exists 기반이라 인터페이스를 직접 구현한 서드파티 확장이 깨지지 않는다. - 축 4종(목록/화면/쓰기/배치)을 실행기로 분리하고 컨테이너 태그로 주입 — 축이 늘 때 커맨드를 고치지 않는다. - 화면 축은 HTTP 커널로 내부 요청을 처리한다. 라우트만 dispatch 하면 전역 미들웨어를 건너뛰어 화면과 다른 것을 재게 된다. 인증은 프로파일이 선언한 권한만 가진 임시 계정이 기본이며 --as 로 기존 계정을 지목할 수 있다. - 화면/쓰기 축은 계측 계정 생성부터 처리까지 롤백되는 트랜잭션 안에서 실행해 운영 DB 에도 잔여 데이터를 남기지 않는다. 배치 축은 내부 커밋·락 보유 때문에 감싸지 않고 --allow-write 로만 통제한다. - 잘못된 선언은 조용히 버리지 않고 사유를 경고로 남긴다. 버려진 선언이 곧 계측 사각이 되기 때문이다. 전부 건너뛴 실행은 종료 코드 1 로 끝난다. - 리포트는 환경 정보를 함께 적어 저장소 밖(storage/app/benchmarks)에 남긴다. 측정값이 실행 머신에 종속되므로 저장소에 축적하면 비교 불가능한 수치가 섞인다. 작업 중 발견해 함께 고친 것: - 이관 프로파일 3종의 soft_delete 선언이 실제 스키마와 어긋나 있었다 (users/product_inquiries/pages 에 deleted_at 없음). - 주문 목록이 상태 미지정 시 임시 주문 상태를 NOT IN 으로 제외하는데 선언에 빠져 있었다. filters 가 등가 비교만 지원한 것이 근본 원인이라 연산자 형태를 받도록 넓히고, 미허용 연산자는 측정 전에 거부한다. - 댓글 프로파일은 지배적 술어가 상관 서브쿼리라 선언형으로 재현할 수 없어 제거했다. 맨 테이블 스캔은 어느 화면도 내지 않는 수치가 된다. g7:bench:pagination → g7:bench 로 개명(4축을 재므로). 이전 이름은 별칭으로 남겼다. 테스트 61건 통과, 라이브 18종 전건 측정.
142 lines
5.2 KiB
PHP
142 lines
5.2 KiB
PHP
<?php
|
|
|
|
namespace App\Benchmark\Axes;
|
|
|
|
use App\Benchmark\Contracts\BenchmarkAxisRunner;
|
|
use App\Benchmark\DTO\BenchmarkProfile;
|
|
use App\Benchmark\DTO\BenchmarkResult;
|
|
use App\Benchmark\DTO\BenchmarkRunOptions;
|
|
use App\Benchmark\QueryCollector;
|
|
use App\Enums\BenchmarkAxis;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
use Symfony\Component\Console\Output\BufferedOutput;
|
|
|
|
/**
|
|
* 배치 축 실행기 — 배치 커맨드 소요 시간 + 피크 메모리
|
|
*
|
|
* 배치는 한 번에 대량을 처리하므로 "느려짐"이 시간보다 메모리로 먼저 드러납니다(청크
|
|
* 없이 전건 로딩 → OOM). 그래서 시간과 함께 피크 메모리를 함께 잽니다.
|
|
*
|
|
* 다른 축과 달리 트랜잭션으로 감싸지 않습니다 — 배치 커맨드는 내부에서 커밋하거나 DDL 을
|
|
* 실행할 수 있고, 대량 처리를 긴 트랜잭션에 담으면 락 보유 시간이 계측 자체보다 위험해집니다.
|
|
* 대신 데이터를 변경하는 배치는 `--allow-write` 없이는 실행하지 않습니다.
|
|
*/
|
|
class BatchAxisRunner implements BenchmarkAxisRunner
|
|
{
|
|
public function __construct(private readonly QueryCollector $collector) {}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function axis(): BenchmarkAxis
|
|
{
|
|
return BenchmarkAxis::Batch;
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function run(BenchmarkProfile $profile, BenchmarkRunOptions $options, ?\Closure $onProgress = null): BenchmarkResult
|
|
{
|
|
$notify = $onProgress ?? static fn (string $message) => null;
|
|
|
|
if ($profile->mutates() && ! $options->allowWrite) {
|
|
return BenchmarkResult::skipped($profile, '데이터를 변경하는 배치입니다. --allow-write 를 붙여 실행하세요.');
|
|
}
|
|
|
|
$command = (string) $profile->option('command');
|
|
$arguments = (array) $profile->option('arguments', []);
|
|
|
|
if (! array_key_exists($command, Artisan::all())) {
|
|
return BenchmarkResult::skipped($profile, "등록되지 않은 커맨드: {$command} (해당 확장이 설치되어 있는지 확인)");
|
|
}
|
|
|
|
$notify("배치 실행: {$command}");
|
|
|
|
// 피크 메모리는 프로세스 단위 누적값이라 감소하지 않는다. 실행 전 값을 함께
|
|
// 기록해야 "이 배치가 피크를 밀어올렸는지"를 판정할 수 있다.
|
|
$peakBefore = memory_get_peak_usage(true);
|
|
$usageBefore = memory_get_usage(true);
|
|
$buffer = new BufferedOutput;
|
|
|
|
$start = microtime(true);
|
|
|
|
try {
|
|
$collected = $this->collector->collect(
|
|
static fn () => Artisan::call($command, $arguments, $buffer)
|
|
);
|
|
$exitCode = (int) $collected['value'];
|
|
$queries = $collected['queries'];
|
|
} catch (\Throwable $e) {
|
|
return BenchmarkResult::skipped($profile, '계측 실패: '.$e->getMessage());
|
|
}
|
|
|
|
$elapsedMs = (microtime(true) - $start) * 1000;
|
|
$peakAfter = memory_get_peak_usage(true);
|
|
$usageAfter = memory_get_usage(true);
|
|
$summary = $this->collector->summarize($queries);
|
|
|
|
$notes = [
|
|
sprintf('실행 전 피크 %s → 실행 후 피크 %s', $this->formatBytes($peakBefore), $this->formatBytes($peakAfter)),
|
|
];
|
|
|
|
if ($peakAfter <= $peakBefore) {
|
|
$notes[] = '이 배치가 프로세스 피크를 밀어올리지 않았습니다 (실행 전 피크가 이미 더 높음).';
|
|
}
|
|
|
|
if ($exitCode !== 0) {
|
|
$notes[] = "커맨드가 실패 종료했습니다 (exit={$exitCode}) — 시간·메모리는 실패 지점까지의 값입니다.";
|
|
}
|
|
|
|
$output = trim($buffer->fetch());
|
|
|
|
if ($output !== '') {
|
|
$notes[] = '커맨드 출력: '.$output;
|
|
}
|
|
|
|
return new BenchmarkResult(
|
|
profile: $profile,
|
|
headers: ['커맨드', '종료코드', '소요(ms)', '피크 메모리', '메모리 증가', '쿼리(건)'],
|
|
rows: [[
|
|
$command,
|
|
(string) $exitCode,
|
|
number_format($elapsedMs, 1),
|
|
$this->formatBytes($peakAfter),
|
|
$this->formatBytes(max(0, $usageAfter - $usageBefore)),
|
|
number_format($summary['count']),
|
|
]],
|
|
metrics: [
|
|
'command' => $command,
|
|
'arguments' => $arguments,
|
|
'exit_code' => $exitCode,
|
|
'elapsed_ms' => round($elapsedMs, 2),
|
|
'peak_memory_before_bytes' => $peakBefore,
|
|
'peak_memory_after_bytes' => $peakAfter,
|
|
'memory_delta_bytes' => $usageAfter - $usageBefore,
|
|
'query_count' => $summary['count'],
|
|
'db_ms' => $summary['db_ms'],
|
|
],
|
|
notes: $notes,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 바이트를 사람이 읽는 단위로 바꿉니다.
|
|
*
|
|
* @param int $bytes 바이트
|
|
* @return string 포맷된 문자열
|
|
*/
|
|
private function formatBytes(int $bytes): string
|
|
{
|
|
if ($bytes >= 1024 ** 3) {
|
|
return number_format($bytes / 1024 ** 3, 2).' GB';
|
|
}
|
|
|
|
if ($bytes >= 1024 ** 2) {
|
|
return number_format($bytes / 1024 ** 2, 1).' MB';
|
|
}
|
|
|
|
return number_format($bytes / 1024, 1).' KB';
|
|
}
|
|
}
|