File size: 7,661 Bytes
2756f0f
 
7a3215f
2756f0f
be69d1e
2756f0f
7a3215f
a8788e5
3ee736f
2756f0f
3ee736f
 
2756f0f
 
7a3215f
fe40b87
 
2756f0f
7a3215f
 
fe40b87
 
2756f0f
 
 
 
 
 
fe40b87
 
 
2756f0f
 
fe40b87
be69d1e
6963661
2756f0f
 
fe40b87
e980186
2756f0f
 
 
 
6963661
 
fe40b87
e980186
2756f0f
 
 
be69d1e
 
 
 
 
 
2756f0f
 
7a3215f
 
2756f0f
 
 
be69d1e
2756f0f
 
 
 
 
 
 
7a3215f
 
2756f0f
7a3215f
 
 
 
 
2756f0f
 
 
7a3215f
 
 
 
2756f0f
 
 
 
 
 
3ee736f
2756f0f
 
 
3ee736f
 
 
 
 
 
 
 
 
 
 
a8788e5
7bf5a7e
6963661
 
3ee736f
 
 
 
 
 
 
 
 
7bf5a7e
 
3ee736f
a8788e5
 
 
 
 
3ee736f
 
 
 
 
 
 
 
a8788e5
 
 
3ee736f
a8788e5
3ee736f
 
a8788e5
 
3ee736f
 
 
 
 
2756f0f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""Application factory: routers, error envelope, request ids."""

import re
import uuid
from contextlib import asynccontextmanager

from ai_coach.config import get_settings as get_coach_settings
from ai_coach.pitch_report.v1_1.contract import PitchPayload
from ai_coach.swing_report.schemas import SwingAnalysisPayload, SwingReport
from fastapi import FastAPI, Request
from fastapi.openapi.utils import get_openapi
from pydantic.json_schema import models_json_schema

from app.core.config import get_settings
from app.core.errors import register_error_handlers, unexpected_error_response
from app.modules.academy_org.controller import router as academy_org_router
from app.modules.academy_staff.controller import router as academy_staff_router
from app.modules.accounts.controller import router as accounts_router
from app.modules.api_audit.controller import router as audit_router
from app.modules.api_audit.middleware import ApiAuditMiddleware
from app.modules.arm_care.controller import router as arm_care_router
from app.modules.assignments.controller import router as assignments_router
from app.modules.auth.controller import router as auth_router
from app.modules.billing.controller import router as billing_router
from app.modules.catalog.controller import router as catalog_router
from app.modules.coach.controller import router as coach_router
from app.modules.devices.controller import router as devices_router
from app.modules.drills.controller import router as drills_router
from app.modules.goals.controller import router as goals_router
from app.modules.notifications.controller import router as notifications_router
from app.modules.reporting.controller import router as reporting_router
from app.modules.reviews.controller import router as reviews_router
from app.modules.sessions.controller import router as sessions_router
from app.modules.settings.controller import router as settings_router
from app.modules.swing_reports import queue as report_queue
from app.modules.swing_reports.controller import pitch_router as pitch_reports_router
from app.modules.swing_reports.controller import router as swing_reports_router
from app.modules.teams.controller import router as teams_router
from app.modules.threads.controller import router as threads_router
from app.modules.threads.socket import router as chat_socket_router
from app.modules.uploads.controller import router as uploads_router

ROUTERS = (
    auth_router, accounts_router, teams_router, uploads_router, sessions_router, swing_reports_router,
    pitch_reports_router, drills_router, reviews_router, coach_router, devices_router, billing_router, catalog_router,
    audit_router,
    settings_router, notifications_router, threads_router, goals_router, assignments_router, arm_care_router,
    academy_staff_router, academy_org_router, reporting_router, chat_socket_router,
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    report_queue.kick()  # pick up reports that were still queued when the last process stopped
    yield


def create_app() -> FastAPI:
    settings = get_settings()
    if settings.env == "prod" and not get_coach_settings().llm_enabled:
        raise RuntimeError("GOOGLE_API_KEY is not set: the AI coach cannot write coaching text in production.")
    app = FastAPI(
        title="Cognivision Baseball API",
        version="0.1.0",
        lifespan=lifespan,
        docs_url=None if settings.env == "prod" else "/docs",
        openapi_url=None if settings.env == "prod" else "/openapi.json",
    )
    register_error_handlers(app)

    @app.middleware("http")
    async def request_id(request: Request, call_next):
        supplied = request.headers.get("x-request-id", "")
        rid = supplied if re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", supplied) else uuid.uuid4().hex
        request.state.request_id = rid
        try:
            response = await call_next(request)
        except Exception as exc:  # handled here so error responses carry the request id too
            request.state.audit_exception_type = type(exc).__name__
            response = unexpected_error_response(exc)
        response.headers["X-Request-Id"] = rid
        return response

    if settings.api_audit_enabled:
        app.add_middleware(ApiAuditMiddleware, max_body_bytes=settings.api_audit_max_body_bytes,
                           service_version=settings.service_version)

    @app.get("/healthz", include_in_schema=False)
    async def healthz() -> dict:
        return {"status": "ok"}

    for router in ROUTERS:
        app.include_router(router)
    app.openapi = lambda: _openapi(app)
    return app


ERROR_SCHEMA = {
    "type": "object", "required": ["error"],
    "properties": {"error": {"type": "object", "required": ["code", "message"], "properties": {
        "code": {"type": "string", "examples": ["VALIDATION", "NOT_FOUND", "PLAN_LIMIT"]},
        "message": {"type": "string", "description": "Safe to show in the app"},
        "fields": {"type": "object", "additionalProperties": {"type": "string"},
                   "description": "Field path -> problem, for validation errors"},
    }}},
}


REQUEST_MODELS = {"/v1/sessions/{session_id}/swing-report": ("SwingAnalysisPayload",),
                  "/v1/sessions/{session_id}/pitch-report": ("PitchPayload",)}


def _openapi(app: FastAPI) -> dict:
    """The generated schema, corrected to match what the API really returns (for client code generation)."""
    if app.openapi_schema:
        return app.openapi_schema
    spec = get_openapi(title=app.title, version=app.version, routes=app.routes)
    schemas = spec.setdefault("components", {}).setdefault("schemas", {})
    schemas.pop("HTTPValidationError", None)
    schemas.pop("ValidationError", None)
    schemas["ErrorResponse"] = ERROR_SCHEMA
    _, contract = models_json_schema([(SwingAnalysisPayload, "validation"), (SwingReport, "serialization")],
                                     ref_template="#/components/schemas/{model}")
    schemas.update(contract.get("$defs", {}))
    # Isolate pitch-1.1 validation definitions from existing input names and response serialization schemas.
    pitch_input = PitchPayload.model_json_schema(
        mode="validation", ref_template="#/components/schemas/PitchPayload_{model}")
    schemas.update({f"PitchPayload_{name}": value for name, value in pitch_input.pop("$defs", {}).items()})
    schemas["PitchPayload"] = pitch_input
    error_ref = {"description": "Error", "content": {"application/json": {
        "schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}
    for path, operations in spec["paths"].items():
        for operation in operations.values():
            responses = operation.setdefault("responses", {})
            responses.pop("422", None)
            responses.setdefault("400", error_ref)
            responses.setdefault("default", error_ref)
            request_models = REQUEST_MODELS.get(path)
            if request_models:
                refs = [{"$ref": f"#/components/schemas/{model}"} for model in request_models]
                operation["requestBody"] = {"required": True, "content": {"application/json": {
                    "schema": refs[0] if len(refs) == 1 else {"anyOf": refs}}}}
    session_out = schemas.get("SessionOut", {}).get("properties", {})
    if "report" in session_out:
        session_out["report"] = {"anyOf": [{"$ref": "#/components/schemas/SwingReport"},
                                            {"$ref": "#/components/schemas/PitchReport"}, {"type": "null"}],
                                 "description": "Null while status is pending"}
    app.openapi_schema = spec
    return spec


app = create_app()