From e664d7b1878ddca5eb997b591557aae4d17e6db2 Mon Sep 17 00:00:00 2001 From: hyungi Date: Tue, 16 Jun 2026 14:01:25 +0900 Subject: [PATCH] =?UTF-8?q?perf(setup):=20setup=20=EB=AF=B8=EB=93=A4?= =?UTF-8?q?=EC=9B=A8=EC=96=B4=20user=20COUNT=20=EC=BA=90=EC=8B=9C=20?= =?UTF-8?q?=E2=80=94=20per-request=20=EC=BF=BC=EB=A6=AC=20=EC=A0=9C?= =?UTF-8?q?=EA=B1=B0=20(R10)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit setup 완료 후에도 모든 비-bypass 요청이 select count(User.id) 를 실행하던 per-request 비용. 셋업 완료(user 존재)는 monotonic 이라 1회 확인 후 _setup_complete 플래그로 영구 skip(이후 요청 DB 쿼리 0). global 선언은 함수 첫 줄(read+assign 혼용 UnboundLocalError 방지). R10 잔여(library-tree jsonb 집계 golden-diff·facet-counts·events-count·synthesis cache TTL)는 결과 동등성 검증 동반이라 후속. 검증: py_compile 통과. Co-Authored-By: Claude Opus 4.8 (1M context) --- app/main.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 9710ae2..99320d0 100644 --- a/app/main.py +++ b/app/main.py @@ -240,21 +240,27 @@ SETUP_BYPASS_PREFIXES = ( "/api/setup", "/api/config", "/setup", "/health", "/docs", "/openapi.json", "/redoc", ) +# R10: 셋업 완료(user 존재)는 단조(monotonic) — 한 번 확인되면 영구. 매 요청 COUNT 쿼리 +# 대신 캐시 플래그로 전환 (setup 후 모든 요청이 users COUNT 하던 per-request 비용 제거). +_setup_complete = False + @app.middleware("http") async def setup_redirect_middleware(request: Request, call_next): + global _setup_complete # 함수 내 read+assign 둘 다 모듈 전역 참조 (UnboundLocalError 방지) path = request.url.path - # 바이패스 경로는 항상 통과 - if any(path.startswith(p) for p in SETUP_BYPASS_PREFIXES): + # 셋업 완료됐거나 바이패스 경로면 즉시 통과 (DB 쿼리 없음) + if _setup_complete or any(path.startswith(p) for p in SETUP_BYPASS_PREFIXES): return await call_next(request) - # 유저 존재 여부 확인 + # 유저 존재 여부 확인 (셋업 완료 전 1회성 — 완료 확인되면 플래그 set 후 영구 skip) try: async with async_session() as session: result = await session.execute(select(func.count(User.id))) user_count = result.scalar() if user_count == 0: return RedirectResponse(url="/setup") + _setup_complete = True except Exception: pass # DB 연결 실패 시 통과 (health에서 확인 가능)