|
1 | 1 | import uvicorn |
2 | 2 | from fastapi import Depends, FastAPI, Request, status |
| 3 | +from fastapi.encoders import jsonable_encoder |
3 | 4 | from fastapi.responses import JSONResponse |
4 | 5 | from prometheus_fastapi_instrumentator import Instrumentator |
5 | 6 | from sqlalchemy.orm import Session |
|
11 | 12 | CreateMessageSchema, |
12 | 13 | CreateQueueSchema, |
13 | 14 | CreateTopicSchema, |
| 15 | + HealthSchema, |
14 | 16 | ListMessageSchema, |
15 | 17 | ListQueueSchema, |
16 | 18 | ListTopicSchema, |
|
21 | 23 | TopicSchema, |
22 | 24 | UpdateQueueSchema, |
23 | 25 | ) |
24 | | -from fastqueue.services import MessageService, QueueService, TopicService |
| 26 | +from fastqueue.services import HealthService, MessageService, QueueService, TopicService |
25 | 27 |
|
26 | 28 | tags_metadata = [ |
27 | 29 | { |
@@ -67,7 +69,8 @@ def already_exists_exception_handler(request: Request, exc: AlreadyExistsError): |
67 | 69 |
|
68 | 70 | @app.exception_handler(NotFoundError) |
69 | 71 | def not_found_exception_handler(request: Request, exc: NotFoundError): |
70 | | - return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"detail": exc.args[0]}) |
| 72 | + response = jsonable_encoder(NotFoundSchema(detail=exc.args[0])) |
| 73 | + return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content=response) |
71 | 74 |
|
72 | 75 |
|
73 | 76 | @app.post("/topics", response_model=TopicSchema, status_code=status.HTTP_201_CREATED, tags=["topics"]) |
@@ -206,10 +209,22 @@ def nack_message(message_id: str, session: Session = Depends(get_session)): |
206 | 209 | return MessageService(session=session).nack(id=message_id) |
207 | 210 |
|
208 | 211 |
|
| 212 | +@app.get( |
| 213 | + "/health", |
| 214 | + response_model=HealthSchema, |
| 215 | + status_code=status.HTTP_200_OK, |
| 216 | + tags=["healthcheck"], |
| 217 | + responses={500: {"model": HealthSchema}}, |
| 218 | +) |
| 219 | +def health(session: Session = Depends(get_session)): |
| 220 | + response = HealthService(session=session).check() |
| 221 | + status_code = status.HTTP_200_OK if response.success else status.HTTP_500_INTERNAL_SERVER_ERROR |
| 222 | + return JSONResponse(status_code=status_code, content=jsonable_encoder(response)) |
| 223 | + |
| 224 | + |
209 | 225 | def run_server(): |
210 | 226 | uvicorn.run( |
211 | 227 | "fastqueue.api:app", |
212 | | - debug=settings.debug, |
213 | 228 | host=settings.server_host, |
214 | 229 | port=settings.server_port, |
215 | 230 | log_level=settings.log_level.lower(), |
|
0 commit comments