|
1 | 1 | from datetime import datetime, timedelta |
| 2 | +import asyncio |
2 | 3 |
|
3 | 4 | import httpx |
4 | | -import structlog |
| 5 | +from contextlib import asynccontextmanager |
5 | 6 | from fastapi import FastAPI, Header |
6 | 7 | from fastapi.middleware.cors import CORSMiddleware |
7 | 8 | from fastapi.middleware.gzip import GZipMiddleware |
8 | 9 | from fastapi.responses import ORJSONResponse, Response |
9 | 10 |
|
10 | 11 | from edge_proxy.health_check.responses import HealthCheckResponse |
11 | | -from fastapi_utils.tasks import repeat_every |
12 | 12 |
|
13 | 13 | from edge_proxy.cache import LocalMemEnvironmentsCache |
14 | 14 | from edge_proxy.environments import EnvironmentService |
|
24 | 24 | httpx.AsyncClient(timeout=settings.api_poll_timeout_seconds), |
25 | 25 | settings, |
26 | 26 | ) |
27 | | -app = FastAPI() |
| 27 | + |
| 28 | + |
| 29 | +async def poll_environments(): |
| 30 | + while True: |
| 31 | + await environment_service.refresh_environment_caches() |
| 32 | + await asyncio.sleep(settings.api_poll_frequency_seconds) |
| 33 | + |
| 34 | + |
| 35 | +@asynccontextmanager |
| 36 | +async def lifespan(app: FastAPI): |
| 37 | + await environment_service.refresh_environment_caches() |
| 38 | + poll = asyncio.create_task(poll_environments()) |
| 39 | + yield |
| 40 | + poll.cancel() |
| 41 | + |
| 42 | + |
| 43 | +app = FastAPI(lifespan=lifespan) |
28 | 44 |
|
29 | 45 |
|
30 | 46 | @app.exception_handler(FlagsmithUnknownKeyError) |
@@ -109,16 +125,6 @@ async def get_identities( |
109 | 125 | return ORJSONResponse(data) |
110 | 126 |
|
111 | 127 |
|
112 | | -@app.on_event("startup") |
113 | | -@repeat_every( |
114 | | - seconds=settings.api_poll_frequency_seconds, |
115 | | - raise_exceptions=True, |
116 | | - logger=structlog.get_logger(__name__), |
117 | | -) |
118 | | -async def refresh_cache(): |
119 | | - await environment_service.refresh_environment_caches() |
120 | | - |
121 | | - |
122 | 128 | app.add_middleware( |
123 | 129 | CORSMiddleware, |
124 | 130 | allow_origins=settings.allow_origins, |
|
0 commit comments