"""Route helper wrappers.""" from __future__ import annotations import logging from collections.abc import Callable from typing import Any from backend.dto.common import ApiError, response_from_exception, success_response from core.identity import RequestContext logger = logging.getLogger("imagestudio.routes") def handle_request(ctx: RequestContext, callback: Callable[[], Any]) -> dict[str, Any]: try: return success_response(callback(), request_id=ctx.request_id) except ApiError as exc: # Expected domain outcome (validation, permission, not-found). Logged at # debug so a support session can still reconstruct the exchange without # flooding production logs. logger.debug( "ImageStudio request %s rejected: %s %s", ctx.request_id, exc.error_code, exc.message, ) return response_from_exception(exc, request_id=ctx.request_id) except Exception as exc: # Everything else is a bug. This used to collapse into a bare # UNKNOWN_ERROR response carrying only the exception class name, with no # log line anywhere -- an internal failure on any of the 166 routes was # invisible in production. The traceback goes to the log; the client # still gets the same opaque response, so nothing leaks outward. logger.exception( "ImageStudio request %s failed (actor=%s source=%s)", ctx.request_id, ctx.actor_id, ctx.source, ) return response_from_exception(exc, request_id=ctx.request_id)