-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
240 lines (199 loc) · 9 KB
/
Copy pathmain.py
File metadata and controls
240 lines (199 loc) · 9 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
from __future__ import annotations
import argparse
import contextlib
import logging
import os
from pathlib import Path
import sys
import warnings
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from app import auth
from app.api.dependencies import get_auth_service, get_model_registry_service
from app.api.routes import ALL_ROUTERS
from app.core.cors import build_cors_config
from app.core.dependencies import get_config_service, get_rate_limiter
from app.core.llm_errors import LLMProviderError, llm_provider_error_to_response
from app.core.logging import configure_logging, request_tracing_middleware
from app.core.security_exceptions import SecurityValidationError
from app.core.stt_errors import STTProviderError, stt_provider_error_to_response
from app.startup.bootstrap import BootstrapManager, StartupCommand
from app.startup.diagnostics import StartupLogger
from app.startup.healthcheck import run_healthcheck
from app.startup.service_launcher import LaunchOptions, ServiceLauncher
_CONFIG_SERVICE = get_config_service()
_RATE_LIMITER = get_rate_limiter()
_SETTINGS = _CONFIG_SERVICE.snapshot()
configure_logging(_SETTINGS)
logger = logging.getLogger(__name__)
@contextlib.asynccontextmanager
async def lifespan(_: FastAPI):
settings = _CONFIG_SERVICE.snapshot()
configure_logging(settings)
await auth.init_db()
auth_service = get_auth_service()
auth_service.refresh_runtime()
if not settings.google_client_id:
warnings.warn(
"VITE_GOOGLE_CLIENT_ID / GOOGLE_CLIENT_ID is not set. Google Sign-In will be unavailable.",
stacklevel=1,
)
token_count = auth_service.configured_api_token_count()
if token_count:
print(f"[INFO] {token_count} static API token(s) configured.", flush=True)
model_registry = get_model_registry_service()
missing_local_models = [check for check in model_registry.validate_local_models(settings) if not check.get("ok")]
if missing_local_models:
warnings.warn(
"Some local model paths are not available: "
+ ", ".join(f"{item.get('name')} ({item.get('path')})" for item in missing_local_models),
stacklevel=1,
)
yield
app = FastAPI(
title="Audio Processing API",
description=(
"Modular API for transcribing, summarizing, and visualizing audio. "
"Supports Google OAuth, email/password, and static API token authentication."
),
lifespan=lifespan,
)
@app.exception_handler(LLMProviderError)
async def handle_llm_provider_error(_: Request, exc: LLMProviderError):
return llm_provider_error_to_response(exc)
@app.exception_handler(SecurityValidationError)
async def handle_security_validation_error(_: Request, exc: SecurityValidationError):
return JSONResponse(status_code=exc.status_code, content=exc.to_payload())
@app.exception_handler(STTProviderError)
async def handle_stt_provider_error(_: Request, exc: STTProviderError):
return stt_provider_error_to_response(exc)
app.add_middleware(
CORSMiddleware,
**build_cors_config(_CONFIG_SERVICE.snapshot(), logger),
)
app.add_middleware(GZipMiddleware, minimum_size=1024)
@app.middleware("http")
async def add_api_security_headers(request: Request, call_next):
try:
await _RATE_LIMITER.enforce(request)
except HTTPException as exc:
response = JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
if request.url.path.startswith("/api/"):
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "no-referrer"
response.headers["Cache-Control"] = "no-store"
response.headers["Pragma"] = "no-cache"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Permissions-Policy"] = "geolocation=(), microphone=()"
return response
response = await request_tracing_middleware(request, call_next)
if request.url.path.startswith("/api/"):
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "no-referrer"
response.headers["Cache-Control"] = "no-store"
response.headers["Pragma"] = "no-cache"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Permissions-Policy"] = "geolocation=(), microphone=()"
return response
for router in ALL_ROUTERS:
app.include_router(router)
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="RecordNote startup manager")
parser.add_argument("--setup", action="store_true", help="Prepare environment and exit.")
parser.add_argument("--healthcheck", action="store_true", help="Run startup health checks and exit.")
parser.add_argument("--diagnostics", action="store_true", help="Print startup diagnostics and exit.")
parser.add_argument("--dev", action="store_true", help="Run in development mode.")
parser.add_argument("--prod", action="store_true", help="Run in production mode.")
parser.add_argument("--backend-only", action="store_true", help="Start backend service only.")
parser.add_argument("--frontend-only", action="store_true", help="Start frontend service only.")
parser.add_argument("--host", default=os.getenv("HOST", "0.0.0.0"), help="Host interface.")
parser.add_argument("--backend-port", type=int, default=int(os.getenv("BACKEND_PORT", "8000")), help="Backend port.")
parser.add_argument("--frontend-port", type=int, default=int(os.getenv("FRONTEND_PORT", "5173")), help="Frontend port.")
parser.add_argument("--no-frontend-install", action="store_true", help="Do not auto-run npm install.")
return parser
def _resolve_command(args: argparse.Namespace) -> StartupCommand:
frontend_exists = (Path(__file__).resolve().parent / "frontend").exists()
dev_mode = True
if args.prod:
dev_mode = False
elif args.dev:
dev_mode = True
if args.frontend_only:
return StartupCommand(
backend=False,
frontend=True,
dev_mode=dev_mode,
host=args.host,
backend_port=args.backend_port,
frontend_port=args.frontend_port,
)
if args.backend_only:
return StartupCommand(
backend=True,
frontend=False,
dev_mode=dev_mode,
host=args.host,
backend_port=args.backend_port,
frontend_port=args.frontend_port,
)
return StartupCommand(
backend=True,
frontend=frontend_exists and dev_mode,
dev_mode=dev_mode,
host=args.host,
backend_port=args.backend_port,
frontend_port=args.frontend_port,
)
def _run_cli() -> int:
parser = _build_parser()
args = parser.parse_args()
repo_root = Path(__file__).resolve().parent
startup_logger = StartupLogger()
manager = BootstrapManager(repo_root=repo_root, config_service=_CONFIG_SERVICE, logger=startup_logger)
setup_result = manager.setup_environment()
# Validate frontend and auto-recover before resolving the startup command so
# that _resolve_command() can see the frontend directory if it was just restored.
manager.validate_and_recover_frontend()
command = _resolve_command(args)
if args.diagnostics:
startup_logger.success("Startup diagnostics", summary=manager.startup_summary(), setup=setup_result)
return 0
dependency_checks = manager.validate_dependencies(command=command)
blocking_dependency_error = any((not item.ok) and item.blocking for item in dependency_checks)
if blocking_dependency_error:
startup_logger.error("Blocking dependency checks failed; startup stopped.")
return 2
manager.detect_and_register_models(setup_result["env_path"])
manager.validate_providers()
db_ok = manager.initialize_database()
if not db_ok:
return 3
if args.healthcheck:
health = run_healthcheck(_CONFIG_SERVICE)
if health.get("ready"):
startup_logger.success("Healthcheck passed", health=health)
return 0
startup_logger.error("Healthcheck failed", health=health)
return 4
if args.setup:
startup_logger.success("Setup completed successfully", summary=manager.startup_summary())
return 0
if not manager.validate_ports(command):
return 5
startup_logger.success("Startup summary", summary=manager.startup_summary(), mode="dev" if command.dev_mode else "prod")
launcher = ServiceLauncher(repo_root=repo_root, logger=startup_logger)
return launcher.run(
LaunchOptions(
backend=command.backend,
frontend=command.frontend,
dev_mode=command.dev_mode,
host=command.host,
backend_port=command.backend_port,
frontend_port=command.frontend_port,
install_frontend_deps=not args.no_frontend_install,
)
)
if __name__ == "__main__":
sys.exit(_run_cli())