-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.py
104 lines (83 loc) · 2.82 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
103
104
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 endorser.services.dependency_injection.container import Container
from endorser.services.endorsement_processor import EndorsementProcessor
from shared.constants import PROJECT_VERSION
from shared.log_config import get_logger
logger = get_logger(__name__)
@asynccontextmanager
async def app_lifespan(_: FastAPI):
logger.info("Endorser Service startup")
# Initialize the container
container = Container()
await container.init_resources()
container.wire(modules=[__name__])
endorsement_processor = await container.endorsement_processor()
endorsement_processor.start()
yield
logger.info("Shutting down Endorser services ...")
await endorsement_processor.stop()
await container.shutdown_resources()
logger.info("Shutdown Endorser services.")
def create_app() -> FastAPI:
openapi_name = os.getenv("OPENAPI_NAME", "Aries Cloud API: Endorser Service")
application = FastAPI(
title=openapi_name,
version=PROJECT_VERSION,
lifespan=app_lifespan,
redoc_url=None,
docs_url=None,
)
return application
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")
@inject
async def health_check(
endorsement_processor: EndorsementProcessor = Depends(
Provide[Container.endorsement_processor]
),
):
if endorsement_processor.are_tasks_running():
return {"status": "healthy"}
else:
raise HTTPException(
status_code=503, detail="One or more background tasks are not running."
)
@app.get("/health/ready")
@inject
async def health_ready(
endorsement_processor: EndorsementProcessor = Depends(
Provide[Container.endorsement_processor]
),
):
try:
jetstream_status = await asyncio.wait_for(
endorsement_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"},
)