-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
286 lines (261 loc) · 9.77 KB
/
Copy pathapp.py
File metadata and controls
286 lines (261 loc) · 9.77 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""Application factory — wires dependencies and registers routes."""
import os
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
from nene2.auth import (
ApiKeyAuthMiddleware,
BearerTokenMiddleware,
LocalBearerJwtVerifier,
LocalTokenVerifier,
)
from nene2.config import AppSettings
from nene2.database import (
DatabaseHealthCheck,
DatabaseQueryExecutorInterface,
SqlAlchemyQueryExecutor,
)
from nene2.http import HealthStatus
from nene2.log import setup_logging
from nene2.middleware import (
ErrorHandlerMiddleware,
RequestIdMiddleware,
RequestLoggingMiddleware,
RequestSizeLimitMiddleware,
SecurityHeadersMiddleware,
ThrottleMiddleware,
)
from nene2.middleware.error_handler import request_validation_error_handler
from nene2.validation.exceptions import ValidationException
from .comment.exceptions import CommentNotFoundExceptionHandler
from .comment.handler import make_comment_router
from .comment.repository import CommentRepositoryInterface, InMemoryCommentRepository
from .comment.sqlalchemy_repository import SqlAlchemyCommentRepository
from .comment.use_case import (
CreateCommentUseCase,
DeleteCommentUseCase,
GetCommentUseCase,
ListCommentsUseCase,
UpdateCommentUseCase,
)
from .note.exceptions import NoteNotFoundExceptionHandler
from .note.handler import make_note_router
from .note.repository import InMemoryNoteRepository, NoteRepositoryInterface
from .note.sqlalchemy_repository import SqlAlchemyNoteRepository
from .note.use_case import (
CreateNoteUseCase,
DeleteNoteUseCase,
GetNoteUseCase,
ListNotesUseCase,
UpdateNoteUseCase,
)
from .schema import ensure_schema
from .tag.exceptions import TagNotFoundExceptionHandler
from .tag.handler import make_tag_router
from .tag.repository import InMemoryTagRepository, TagRepositoryInterface
from .tag.sqlalchemy_repository import SqlAlchemyTagRepository
from .tag.use_case import (
CreateTagUseCase,
DeleteTagUseCase,
GetTagUseCase,
ListTagsUseCase,
UpdateTagUseCase,
)
# OpenAPI / NENE2 PHP parity (FrameworkInfo in hideyukiMORI/NENE2).
_FRAMEWORK_NAME = "NENE2"
_FRAMEWORK_DESCRIPTION = "JSON APIs first, minimal server HTML, frontend ready, AI-readable."
# Matches nene2-js tools/compose-ft-evac.yaml default for local evac smoke.
_DEFAULT_MACHINE_API_KEYS = ["ft-evac-local-machine-api-key-32ch!!"]
_DEFAULT_JWT_SECRET = "ft-evac-local-jwt-secret-min-32-chars!!" # noqa: S105
type _Repos = tuple[
NoteRepositoryInterface,
TagRepositoryInterface,
CommentRepositoryInterface,
DatabaseQueryExecutorInterface | None,
]
def _build_repositories(cfg: AppSettings) -> _Repos:
"""Build repositories based on DB_ADAPTER setting."""
if cfg.db_adapter == "sqlite":
is_memory = cfg.db_name == ":memory:"
engine = create_engine(
cfg.db_url,
connect_args={"check_same_thread": False},
poolclass=StaticPool if is_memory else None,
)
ensure_schema(engine)
executor = SqlAlchemyQueryExecutor(engine)
return (
SqlAlchemyNoteRepository(executor),
SqlAlchemyTagRepository(executor),
SqlAlchemyCommentRepository(executor),
executor,
)
if cfg.db_adapter in ("mysql", "pgsql"):
engine = create_engine(cfg.db_url)
executor = SqlAlchemyQueryExecutor(engine)
return (
SqlAlchemyNoteRepository(executor),
SqlAlchemyTagRepository(executor),
SqlAlchemyCommentRepository(executor),
executor,
)
return InMemoryNoteRepository(), InMemoryTagRepository(), InMemoryCommentRepository(), None
def create_app(settings: AppSettings | None = None) -> FastAPI:
cfg = settings or AppSettings()
# Local dev / consumer FT: throttle off unless THROTTLE_ENABLED is set (nene2-python#592).
if cfg.app_env == "local" and os.getenv("THROTTLE_ENABLED") is None:
cfg = cfg.model_copy(update={"throttle_enabled": False})
setup_logging(cfg.app_env)
app = FastAPI(
title=cfg.app_name,
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
# Registration order: innermost first, outermost last.
# Starlette executes in reverse — the last registered wraps all others.
app.add_middleware(
ErrorHandlerMiddleware,
debug=cfg.app_debug,
domain_handlers=[
NoteNotFoundExceptionHandler(),
TagNotFoundExceptionHandler(),
CommentNotFoundExceptionHandler(),
],
)
if cfg.security_headers_enabled:
app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(RequestIdMiddleware)
app.add_middleware(RequestLoggingMiddleware)
app.add_middleware(RequestSizeLimitMiddleware, max_bytes=cfg.max_body_size)
if cfg.throttle_enabled:
app.add_middleware(
ThrottleMiddleware,
limit=cfg.throttle_limit,
window=cfg.throttle_window,
)
# Auth sits inside the CORS layer so preflight OPTIONS bypasses auth checks.
if cfg.bearer_token_enabled:
app.add_middleware(
BearerTokenMiddleware,
verifier=LocalTokenVerifier(cfg.bearer_tokens),
)
if cfg.api_key_enabled:
app.add_middleware(
ApiKeyAuthMiddleware,
verifier=LocalTokenVerifier(cfg.api_keys),
)
if cfg.api_key_enabled and cfg.api_keys:
machine_keys = cfg.api_keys
else:
machine_keys = _DEFAULT_MACHINE_API_KEYS
app.add_middleware(
ApiKeyAuthMiddleware,
verifier=LocalTokenVerifier(machine_keys),
include_paths=["/machine/health"],
header_name="X-NENE2-API-Key",
)
jwt_secret = os.getenv("NENE2_LOCAL_JWT_SECRET", _DEFAULT_JWT_SECRET)
if len(jwt_secret) >= 32:
app.add_middleware(
BearerTokenMiddleware,
verifier=LocalBearerJwtVerifier(jwt_secret),
include_paths=["/examples/protected"],
)
# CORS must be outermost — register last so preflight OPTIONS is handled
# before throttle, auth, or any other middleware runs.
if cfg.cors_enabled:
app.add_middleware(
CORSMiddleware,
allow_origins=cfg.cors_origins,
allow_credentials=cfg.cors_allow_credentials,
allow_methods=cfg.cors_allow_methods,
allow_headers=cfg.cors_allow_headers,
)
app.add_exception_handler(
ValidationException,
ErrorHandlerMiddleware.handle_validation_exception,
)
app.add_exception_handler(
RequestValidationError,
request_validation_error_handler,
)
note_repo, tag_repo, comment_repo, db_executor = _build_repositories(cfg)
app.state.db_executor = db_executor
# OpenAPI parity with NENE2 PHP: /examples/notes, /examples/tags (nene2-js client paths).
app.include_router(
make_note_router(
ListNotesUseCase(note_repo),
GetNoteUseCase(note_repo),
CreateNoteUseCase(note_repo),
UpdateNoteUseCase(note_repo),
DeleteNoteUseCase(note_repo),
),
prefix="/examples",
)
app.include_router(
make_tag_router(
ListTagsUseCase(tag_repo),
GetTagUseCase(tag_repo),
CreateTagUseCase(tag_repo),
UpdateTagUseCase(tag_repo),
DeleteTagUseCase(tag_repo),
),
prefix="/examples",
)
app.include_router(
make_comment_router(
ListCommentsUseCase(comment_repo, note_repo),
GetCommentUseCase(comment_repo),
CreateCommentUseCase(comment_repo, note_repo),
UpdateCommentUseCase(comment_repo),
DeleteCommentUseCase(comment_repo),
),
prefix="/examples",
)
@app.get("/", tags=["system"], summary="Framework smoke endpoint")
async def framework_smoke() -> JSONResponse:
return JSONResponse(
{
"name": _FRAMEWORK_NAME,
"description": _FRAMEWORK_DESCRIPTION,
"status": "ok",
}
)
@app.get("/examples/ping", tags=["system"], summary="Example ping")
async def example_ping() -> JSONResponse:
return JSONResponse({"message": "pong", "status": "ok"})
@app.get("/examples/protected", tags=["Examples"], summary="Protected example endpoint")
async def examples_protected(request: Request) -> JSONResponse:
claims = getattr(request.state, "nene2_auth_claims", {})
return JSONResponse(
{
"message": "Welcome, authenticated user.",
"claims": claims,
}
)
@app.get("/machine/health", tags=["system"], summary="Protected machine health endpoint")
async def machine_health(request: Request) -> JSONResponse:
credential_type = getattr(request.state, "nene2_auth_credential_type", "api_key")
return JSONResponse(
{
"status": "ok",
"service": _FRAMEWORK_NAME,
"credential_type": credential_type,
}
)
db_health = DatabaseHealthCheck(db_executor) if db_executor else None
@app.get("/health", tags=["system"], summary="Health check")
async def health() -> JSONResponse:
status = db_health.check() if db_health else HealthStatus(status="ok")
api_status = "ok" if status.is_healthy else "degraded"
code = 200 if status.is_healthy else 503
return JSONResponse(
{"status": api_status, "service": "NENE2", "checks": status.checks},
status_code=code,
)
return app
app = create_app()