Skip to content

Commit

Permalink
Delay sending app info in middleware for Starlette
Browse files Browse the repository at this point in the history
  • Loading branch information
itssimon committed Oct 20, 2023
1 parent 9b21cc1 commit 6ffa4ae
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion apitally/flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(
self.client.start_sync_loop()

# Get and send app info after a short delay to allow app routes to be registered first
timer = Timer(0.5, self.delayed_send_app_info, kwargs={"app_version": app_version, "openapi_url": openapi_url})
timer = Timer(1.0, self.delayed_send_app_info, kwargs={"app_version": app_version, "openapi_url": openapi_url})
timer.start()

def delayed_send_app_info(self, app_version: Optional[str] = None, openapi_url: Optional[str] = None) -> None:
Expand Down
12 changes: 10 additions & 2 deletions apitally/starlette.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
import json
import sys
import time
Expand Down Expand Up @@ -54,10 +55,17 @@ def __init__(
self.client = ApitallyClient(
client_id=client_id, env=env, sync_api_keys=sync_api_keys, sync_interval=sync_interval
)
self.client.send_app_info(app_info=_get_app_info(app, app_version, openapi_url))
self.client.start_sync_loop()
super().__init__(app)

# Get and send app info after a short delay to allow app routes to be registered first
asyncio.create_task(self.delayed_send_app_info(app_version, openapi_url))

async def delayed_send_app_info(self, app_version: Optional[str] = None, openapi_url: Optional[str] = None) -> None:
await asyncio.sleep(1.0)
app_info = _get_app_info(self.app, app_version, openapi_url)
self.client.send_app_info(app_info=app_info)

async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
try:
start_time = time.perf_counter()
Expand Down Expand Up @@ -187,7 +195,7 @@ def _get_app_info(app: ASGIApp, app_version: Optional[str] = None, openapi_url:
app_info: Dict[str, Any] = {}
if openapi_url and (openapi := _get_openapi(app, openapi_url)):
app_info["openapi"] = openapi
elif endpoints := _get_endpoint_info(app):
if endpoints := _get_endpoint_info(app):
app_info["paths"] = [{"path": endpoint.path, "method": endpoint.http_method} for endpoint in endpoints]
app_info["versions"] = _get_versions(app_version)
app_info["client"] = "apitally-python"
Expand Down

0 comments on commit 6ffa4ae

Please sign in to comment.