-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.py
102 lines (77 loc) · 2.67 KB
/
main.py
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
import asyncio
import os
from contextlib import asynccontextmanager
from dependency_injector.wiring import Provide, inject
from fastapi import Depends, FastAPI, HTTPException
from scalar_fastapi import get_scalar_api_reference
from shared.constants import PROJECT_VERSION
from shared.log_config import get_logger
from waypoint.routers import sse
from waypoint.services.dependency_injection.container import Container
from waypoint.services.nats_service import NatsEventsProcessor
logger = get_logger(__name__)
@asynccontextmanager
async def app_lifespan(_: FastAPI):
logger.info("Waypoint Service startup")
container = Container()
await container.init_resources()
container.wire(modules=[__name__, sse])
await container.nats_events_processor()
yield
logger.debug("Shutting down Waypoint service...")
await container.shutdown_resources()
logger.info("Waypoint Service shutdown")
def create_app() -> FastAPI:
openapi_name = os.getenv("OPENAPI_NAME", "Waypoint Service")
application = FastAPI(
title=openapi_name,
description="""
Welcome to the OpenAPI interface for the Waypoint Service.
The Waypoint Service enables the ability to wait for a specific event to occur before continuing.
""",
version=PROJECT_VERSION,
lifespan=app_lifespan,
redoc_url=None,
docs_url=None,
)
application.include_router(sse.router)
return application
logger.info("Waypoint Service startup")
app = create_app()
# Use Scalar instead of Swagger
@app.get("/docs", include_in_schema=False)
async def scalar_html():
return get_scalar_api_reference(
openapi_url=app.openapi_url,
title=app.title,
)
@app.get("/health/live")
async def health_live():
return {"status": "live"}
@app.get("/health/ready")
@inject
async def health_ready(
nats_processor: NatsEventsProcessor = Depends(
Provide[Container.nats_events_processor]
),
):
try:
jetstream_status = await asyncio.wait_for(
nats_processor.check_jetstream(), timeout=5.0
)
except asyncio.TimeoutError:
raise HTTPException(
status_code=503,
detail={"status": "not ready", "error": "JetStream health check timed out"},
)
except Exception as e: # pylint: disable=W0718
raise HTTPException(
status_code=500, detail={"status": "error", "error": str(e)}
)
if jetstream_status["is_working"]:
return {"status": "ready", "jetstream": jetstream_status}
else:
raise HTTPException(
status_code=503,
detail={"status": "not ready", "jetstream": "JetStream not ready"},
)