feat(refactor/phase1): foundation infrastructure for modular pipeline
Phase 1 of PLAN_REFACTOR.md — all four sub-tasks implemented:
1.1 PipelineLogger (backend/app/core/pipeline_logger.py)
- Structured step_start/step_done/step_error/step_progress API
- Publishes to Python logging AND Redis SSE via log_task_event
- Context manager `pl.step("name")` for auto-timing
1.2 RenderJobDocument (backend/app/domains/rendering/job_document.py)
- Pydantic JSONB schema: state machine + per-step records + timing
- begin_step/finish_step/fail_step/skip_step helpers
- Migration 048: adds render_job_doc JSONB column to order_lines
- OrderLine model updated with render_job_doc field
1.3 TenantContextMiddleware (backend/app/core/middleware.py)
- Decodes JWT, stores tenant_id + role in request.state
- get_db updated to auto-apply RLS SET LOCAL from request.state
- Registered in main.py (runs before every request)
- JWT now embeds tenant_id claim via create_access_token()
- Login endpoint passes tenant_id to token creation
1.4 ProcessStep Registry (backend/app/core/process_steps.py)
- StepName StrEnum with all 20 pipeline step names
- Single source of truth for log prefixes, DB records, UI labels
Also adds db_utils.py with set_tenant_sync() + get_sync_session()
for use inside Celery tasks (bypass-safe RLS helper).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
"""Application middleware.
|
||||
|
||||
TenantContextMiddleware
|
||||
Decodes the JWT Bearer token (if present) from every incoming request and
|
||||
stores tenant_id + role in request.state. The get_db dependency reads
|
||||
request.state to automatically set the RLS context before yielding the
|
||||
session — no endpoint code change required.
|
||||
"""
|
||||
import logging
|
||||
from jose import JWTError, jwt
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.config import settings
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TenantContextMiddleware(BaseHTTPMiddleware):
|
||||
"""Extract JWT → inject tenant_id + role into request.state.
|
||||
|
||||
Does NOT reject unauthenticated requests — that is still handled by the
|
||||
route-level dependencies (require_admin, get_current_user, etc.).
|
||||
Missing / invalid tokens result in request.state.tenant_id = None.
|
||||
"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next) -> Response:
|
||||
tenant_id: str | None = None
|
||||
role: str | None = None
|
||||
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
if auth_header.startswith("Bearer "):
|
||||
token = auth_header[7:]
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
settings.jwt_secret_key,
|
||||
algorithms=[settings.jwt_algorithm],
|
||||
)
|
||||
tenant_id = payload.get("tenant_id")
|
||||
role = payload.get("role")
|
||||
except JWTError:
|
||||
pass # invalid/expired tokens are handled per-endpoint
|
||||
|
||||
request.state.tenant_id = tenant_id
|
||||
request.state.role = role
|
||||
|
||||
return await call_next(request)
|
||||
Reference in New Issue
Block a user