공개 제보 https://github.com/gnuboard/g7/issues/122 대응 — 초기 부트스트랩 리소스(다국어 병합·컴포넌트 정의·라우트·확장 번들·템플릿 dist)를 캐시 버전 디렉토리(public/build/ext/{v}/)에 실파일로 게시해 웹서버가 rewrite 전에 직접 서빙한다. 부트 임계 경로의 PHP 왕복을 제거하고(실측 TTFB 131~144ms → 1~7ms), 미게시·부분게시·GC 직후에는 fetch·태그·번들 3계층이 종전 API 로 즉시 폴백한다. - 게시: 원자적 tmp→rename→manifest(존재=완료), 캐시 락 단일 실행, 인라인 GC (현재+직전 1개), incrementExtensionCacheVersion 단일 지점 terminating 트리거 + blade 자가 치유 + 설치기 태스크(best_effort) + 일일 cleanup 스케줄, sudo 업데이트 대비 소유권 정상화(normalizeOwnership)·prune/백업 제외 - 프론트(engine-v1.61.0): blade 주입 cache_version 1급 시드(이중 부트 로드 제거), fetchStaticFirst 즉시 폴백, ComponentRegistry 버전 키드 매니페스트, ModuleAssetLoader 번들 정적→레거시 폴백, asset-url-recovery staticToLegacy 역변환 - 폴백 API 품질: lang/components/routes ETag+304 + 환경 분기 Cache-Control, 열화 라우트 스냅샷 공개 캐시 금지(서버측 캐시 회피와 대칭), 게시 .htaccess mod_deflate + nginx gzip 스니펫(압축 전송량 회귀 방지) - SEO 정합: 봇 HTML 은 GC 대상 정적 URL 미사용(allowStatic:false), props $switch 봇측 해석 구현(engine-v1.56.0 패리티), 패리티 룰 expression-dialect 그룹 신설, 상주 allow 헤더 제거로 잠금 복원, _comment* 접두 주석 키 분류 - 검증: 전 수정 red→green 4단계, Playwright 라이브 21건, Chrome MCP 24축+M1~M3, 봇 curl 3축, 캐시 저장소(file/redis/database) 축 판정, 히스토리·공개이슈·커밋 이력 전수 재조사 반영 - 코어 7.0.10, engine-v1.61.0. kill-switch: G7_STATIC_CACHE=false
330 lines
11 KiB
PHP
330 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\Base;
|
|
|
|
use App\Helpers\ResponseHelper;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Response;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
|
|
/**
|
|
* API 컨트롤러의 최상위 베이스 클래스
|
|
*
|
|
* 모든 API 컨트롤러가 공통으로 사용하는 기능을 제공합니다.
|
|
* Admin, Auth, Public 컨트롤러는 이 클래스를 상속받습니다.
|
|
*/
|
|
abstract class BaseApiController extends Controller
|
|
{
|
|
/**
|
|
* 성공 응답을 생성합니다.
|
|
*
|
|
* @param string $messageKey 메시지 키
|
|
* @param mixed $data 응답 데이터
|
|
* @param int $statusCode HTTP 상태 코드
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse
|
|
*/
|
|
protected function success(
|
|
string $messageKey = 'common.success',
|
|
mixed $data = null,
|
|
int $statusCode = 200,
|
|
array $messageParams = []
|
|
) {
|
|
return ResponseHelper::success($messageKey, $data, $statusCode, $messageParams, 'core');
|
|
}
|
|
|
|
/**
|
|
* 실패 응답을 생성합니다.
|
|
*
|
|
* @param string $messageKey 메시지 키
|
|
* @param int $statusCode HTTP 상태 코드
|
|
* @param mixed $errors 오류 정보
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse
|
|
*/
|
|
protected function error(
|
|
string $messageKey = 'common.failed',
|
|
int $statusCode = 400,
|
|
mixed $errors = null,
|
|
array $messageParams = []
|
|
) {
|
|
return ResponseHelper::error($messageKey, $statusCode, $errors, $messageParams, 'core');
|
|
}
|
|
|
|
/**
|
|
* 리소스와 함께 성공 응답을 생성합니다.
|
|
*
|
|
* @param string $messageKey 메시지 키
|
|
* @param mixed $resource JSON 리소스
|
|
* @param int $statusCode HTTP 상태 코드
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse
|
|
*/
|
|
protected function successWithResource(
|
|
string $messageKey = 'common.success',
|
|
mixed $resource = null,
|
|
int $statusCode = 200,
|
|
array $messageParams = []
|
|
) {
|
|
return ResponseHelper::successWithResource($messageKey, $resource, $statusCode, $messageParams, 'core');
|
|
}
|
|
|
|
/**
|
|
* 현재 인증된 사용자를 반환합니다.
|
|
*
|
|
* @return User|null
|
|
*/
|
|
protected function getCurrentUser()
|
|
{
|
|
return Auth::user();
|
|
}
|
|
|
|
/**
|
|
* Not Found 응답을 생성합니다.
|
|
*
|
|
* @param string $messageKey 메시지 키
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse
|
|
*/
|
|
protected function notFound(
|
|
string $messageKey = 'common.not_found',
|
|
array $messageParams = []
|
|
) {
|
|
return $this->error($messageKey, 404, null, $messageParams);
|
|
}
|
|
|
|
/**
|
|
* Unauthorized 응답을 생성합니다.
|
|
*
|
|
* @param string $messageKey 메시지 키
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse
|
|
*/
|
|
protected function unauthorized(
|
|
string $messageKey = 'common.unauthorized',
|
|
array $messageParams = []
|
|
) {
|
|
return $this->error($messageKey, 401, null, $messageParams);
|
|
}
|
|
|
|
/**
|
|
* Forbidden 응답을 생성합니다.
|
|
*
|
|
* @param string $messageKey 메시지 키
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse
|
|
*/
|
|
protected function forbidden(
|
|
string $messageKey = 'common.forbidden',
|
|
array $messageParams = []
|
|
) {
|
|
return $this->error($messageKey, 403, null, $messageParams);
|
|
}
|
|
|
|
/**
|
|
* Validation Error 응답을 생성합니다.
|
|
*
|
|
* @param mixed $errors 검증 오류
|
|
* @param string $messageKey 메시지 키
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse
|
|
*/
|
|
protected function validationError(
|
|
mixed $errors,
|
|
string $messageKey = 'common.validation_failed',
|
|
array $messageParams = []
|
|
) {
|
|
return $this->error($messageKey, 422, $errors, $messageParams);
|
|
}
|
|
|
|
/**
|
|
* 파일 응답을 반환합니다 (ETag 및 캐싱 헤더 포함).
|
|
*
|
|
* @param string $filePath 파일 경로
|
|
* @param string $mimeType MIME 타입
|
|
* @param int $maxAge 캐시 유지 시간 (초, 기본: 1년)
|
|
*/
|
|
protected function fileResponse(string $filePath, string $mimeType, int $maxAge = 31536000): BinaryFileResponse|Response
|
|
{
|
|
// ETag 생성 (파일 수정 시간 + 파일 크기 기반)
|
|
$etag = md5(filemtime($filePath).filesize($filePath));
|
|
|
|
// If-None-Match 헤더 확인 (ETag 비교)
|
|
if (request()->header('If-None-Match') === $etag) {
|
|
return response('', 304)->header('ETag', $etag); // 304 Not Modified
|
|
}
|
|
|
|
// 환경별 캐싱 정책
|
|
$cacheControl = app()->environment('production')
|
|
? "public, max-age={$maxAge}, immutable" // 프로덕션: immutable 추가
|
|
: 'no-cache'; // 개발: 캐싱 비활성화
|
|
|
|
$response = response()->file($filePath, [
|
|
'Content-Type' => $mimeType,
|
|
'Expires' => gmdate('D, d M Y H:i:s', time() + $maxAge).' GMT',
|
|
'ETag' => $etag,
|
|
]);
|
|
|
|
// Cache-Control 헤더를 수동으로 설정 (기본 헤더 덮어쓰기)
|
|
$response->headers->set('Cache-Control', $cacheControl);
|
|
|
|
return $response;
|
|
}
|
|
|
|
/**
|
|
* 스토리지 스트림 응답에 ETag/캐싱 헤더를 부착합니다 (fileResponse 의 디스크 인지 대응).
|
|
*
|
|
* fileResponse() 는 로컬 절대 경로 전제(filemtime/filesize)라 S3 등 원격 디스크
|
|
* 행에는 쓸 수 없습니다. 원격/로컬 공통 서빙은 StorageInterface::response() 가
|
|
* 만든 스트림에 본 메서드로 동일한 캐싱 계약(ETag/304/Cache-Control/Expires)을
|
|
* 입힙니다. ETag 는 파일 stat 대신 호출자가 준 결정적 소스(행 메타)로 만듭니다.
|
|
*
|
|
* @param StreamedResponse $response 스토리지 인라인 스트림 응답
|
|
* @param string $etagSource ETag 소스 문자열 (디스크·경로·수정시각·크기 등 행 메타)
|
|
* @param int $maxAge 캐시 유지 시간 (초)
|
|
* @return StreamedResponse|Response 스트림 응답 또는 304
|
|
*/
|
|
protected function streamedFileResponse(StreamedResponse $response, string $etagSource, int $maxAge): StreamedResponse|Response
|
|
{
|
|
$etag = md5($etagSource);
|
|
|
|
// If-None-Match 헤더 확인 (ETag 비교)
|
|
if (request()->header('If-None-Match') === $etag) {
|
|
return response('', 304)->header('ETag', $etag);
|
|
}
|
|
|
|
// 환경별 캐싱 정책 (fileResponse 와 동일)
|
|
$cacheControl = app()->environment('production')
|
|
? "public, max-age={$maxAge}, immutable"
|
|
: 'no-cache';
|
|
|
|
$response->headers->set('ETag', $etag);
|
|
$response->headers->set('Expires', gmdate('D, d M Y H:i:s', time() + $maxAge).' GMT');
|
|
$response->headers->set('Cache-Control', $cacheControl);
|
|
|
|
return $response;
|
|
}
|
|
|
|
/**
|
|
* JSON 응답을 반환합니다 (조건부 캐싱 헤더 포함).
|
|
*
|
|
* ETag 기반 조건부 캐시(If-None-Match → 304)와 환경별 Cache-Control 분기를
|
|
* 적용한다 — 프로덕션은 `public, max-age`, 그 외 환경은 `no-cache`(파일 수정
|
|
* 즉시 반영 — `fileResponse` 의 환경 분기와 동일 사상).
|
|
*
|
|
* @param mixed $data JSON으로 변환할 데이터
|
|
* @param int $maxAge 캐시 유지 시간 (초, 기본: 1시간)
|
|
* @param int $status HTTP 상태 코드
|
|
* @return JsonResponse|Response JSON 응답 또는 304 응답
|
|
*/
|
|
protected function cachedJsonResponse(mixed $data, int $maxAge = 3600, int $status = 200): JsonResponse|Response
|
|
{
|
|
$etag = $this->generateETag($data);
|
|
|
|
$cacheControl = app()->environment('production')
|
|
? "public, max-age={$maxAge}"
|
|
: 'no-cache';
|
|
|
|
if ($status === 200 && $this->isNotModified($etag)) {
|
|
$response = $this->notModifiedResponse($etag, $maxAge);
|
|
$response->headers->set('Cache-Control', $cacheControl);
|
|
$response->headers->set('Vary', 'Accept-Encoding');
|
|
|
|
return $response;
|
|
}
|
|
|
|
return response()->json($data, $status, [
|
|
'Cache-Control' => $cacheControl,
|
|
'ETag' => $etag,
|
|
'Vary' => 'Accept-Encoding',
|
|
], ResponseHelper::JSON_ENCODE_OPTIONS);
|
|
}
|
|
|
|
/**
|
|
* ETag를 생성합니다.
|
|
*
|
|
* @param mixed $data 해시할 데이터
|
|
* @return string ETag 값 (따옴표 포함)
|
|
*/
|
|
protected function generateETag(mixed $data): string
|
|
{
|
|
$content = is_string($data) ? $data : json_encode($data);
|
|
|
|
return '"'.md5($content).'"';
|
|
}
|
|
|
|
/**
|
|
* 클라이언트 캐시가 유효한지 확인합니다.
|
|
*
|
|
* @param string $etag 현재 ETag 값
|
|
* @return bool 캐시가 유효하면 true
|
|
*/
|
|
protected function isNotModified(string $etag): bool
|
|
{
|
|
$clientEtag = request()->header('If-None-Match');
|
|
|
|
return $clientEtag !== null && $clientEtag === $etag;
|
|
}
|
|
|
|
/**
|
|
* 304 Not Modified 응답을 반환합니다.
|
|
*
|
|
* @param string $etag ETag 값
|
|
* @param int $maxAge 캐시 TTL (초)
|
|
* @return Response 304 응답
|
|
*/
|
|
protected function notModifiedResponse(string $etag, int $maxAge = 3600): Response
|
|
{
|
|
return response('', 304)
|
|
->header('ETag', $etag)
|
|
->header('Cache-Control', "public, max-age={$maxAge}");
|
|
}
|
|
|
|
/**
|
|
* 캐시 헤더와 함께 성공 응답을 반환합니다.
|
|
*
|
|
* 클라이언트의 ETag가 일치하면 304 Not Modified를 반환합니다.
|
|
*
|
|
* @param string $messageKey 메시지 키
|
|
* @param mixed $data 응답 데이터
|
|
* @param int $maxAge 캐시 TTL (초, 기본: 1시간)
|
|
* @param array $messageParams 메시지 매개변수
|
|
* @return JsonResponse|Response JSON 응답 또는 304 응답
|
|
*/
|
|
protected function successWithCache(
|
|
string $messageKey = 'common.success',
|
|
mixed $data = null,
|
|
int $maxAge = 3600,
|
|
array $messageParams = []
|
|
): JsonResponse|Response {
|
|
$etag = $this->generateETag($data);
|
|
|
|
// 환경별 캐싱 정책 — 프로덕션 외 환경은 no-cache 로 파일/데이터 수정 즉시 반영
|
|
// (`fileResponse`/`cachedJsonResponse` 와 동일 사상, #122 작업 D)
|
|
$cacheControl = app()->environment('production')
|
|
? "public, max-age={$maxAge}"
|
|
: 'no-cache';
|
|
|
|
// 304 Not Modified 처리
|
|
if ($this->isNotModified($etag)) {
|
|
$response = $this->notModifiedResponse($etag, $maxAge);
|
|
$response->headers->set('Cache-Control', $cacheControl);
|
|
|
|
return $response;
|
|
}
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => __($messageKey, $messageParams),
|
|
'data' => $data,
|
|
], 200, [], ResponseHelper::JSON_ENCODE_OPTIONS)
|
|
->header('ETag', $etag)
|
|
->header('Cache-Control', $cacheControl)
|
|
->header('Vary', 'Accept-Encoding, Accept-Language');
|
|
}
|
|
}
|