Repository navigation
SEL-346: AMW API: per-key usage events and daily per-key summary #195
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1f170f8
SEL-346: AMW API: per-key usage events and daily per-key summary
PetrefiedThunder df635e4
test(core-db): create api_key_usage_daily view in the required-schema…
PetrefiedThunder 8845782
docs(openapi): regenerate for the per-key usage admin route
PetrefiedThunder 14cfc09
fix: bound API key usage writes and freeze migration view
PetrefiedThunder a8e3fa9
Merge remote-tracking branch 'origin/main' into port/api-841-merge
PetrefiedThunder 210a390
SEL-346: bound per-key usage report reads in SQL and add opt-in reten…
PetrefiedThunder da7dc1e
SEL-346: rechain api_key_usage_events migration to 046 after #216's 0…
PetrefiedThunder bb727cc
chore: merge origin/main into port/api-841
PetrefiedThunder 7b97556
fix(gateway): satisfy mypy on api_key_usage rowcount
PetrefiedThunder 50ef6e9
Merge branch 'main' into port/api-841
PetrefiedThunder File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| """Metadata-only HTTP usage events for database-backed API keys.""" | ||
|
|
||
| import logging | ||
| import time | ||
| from uuid import uuid4 | ||
|
|
||
| from starlette.types import ASGIApp, Message, Receive, Scope, Send | ||
|
|
||
| from .auth import CREDENTIAL_ACCEPTANCE | ||
| from ..db.database import get_session_factory | ||
| from ..db.models import APIKeyUsageEventModel | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| async def record_api_key_usage_event( | ||
| *, | ||
| key_id: str, | ||
| tenant: str | None, | ||
| method: str, | ||
| endpoint: str, | ||
| status_code: int, | ||
| latency_ms: int, | ||
| ) -> None: | ||
| """Append one event using a separate session after the response.""" | ||
| async with get_session_factory()() as session: | ||
| session.add( | ||
| APIKeyUsageEventModel( | ||
| id=str(uuid4()), | ||
| key_id=key_id, | ||
| tenant=tenant, | ||
| method=method, | ||
| endpoint=endpoint, | ||
| status_code=status_code, | ||
| latency_ms=latency_ms, | ||
| ) | ||
| ) | ||
| await session.commit() | ||
|
|
||
|
|
||
| class APIKeyUsageMiddleware: | ||
| """Record the resolved key and final HTTP status once per API request.""" | ||
|
|
||
| def __init__(self, app: ASGIApp) -> None: | ||
| self.app = app | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
| if scope["type"] != "http": | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| # RateLimitMiddleware sets this shared holder before entering this | ||
| # layer; auth fills its key identity in the child task after lookup. | ||
| acceptance = CREDENTIAL_ACCEPTANCE.get() | ||
| if acceptance is None: | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| started = time.perf_counter() | ||
| status_code = 500 | ||
|
|
||
| async def send_with_status(message: Message) -> None: | ||
| nonlocal status_code | ||
| if message["type"] == "http.response.start": | ||
| status_code = message["status"] | ||
| await send(message) | ||
|
|
||
| try: | ||
| await self.app(scope, receive, send_with_status) | ||
| finally: | ||
| # route.path is the registered template. Never substitute scope's | ||
| # raw path, which could contain IDs, query values, or user text. | ||
| endpoint = getattr(scope.get("route"), "path", None) | ||
| if acceptance.key_id and endpoint: | ||
| latency_ms = max(0, int((time.perf_counter() - started) * 1000)) | ||
| try: | ||
| await record_api_key_usage_event( | ||
| key_id=acceptance.key_id, | ||
| tenant=acceptance.tenant, | ||
| method=scope.get("amw_original_method", scope["method"]), | ||
| endpoint=endpoint, | ||
| status_code=status_code, | ||
| latency_ms=latency_ms, | ||
| ) | ||
| except Exception as exc: # noqa: BLE001 - usage cannot fail API calls | ||
| logger.warning( | ||
| "api_key_usage_event_write_failed error_type=%s", | ||
| type(exc).__name__, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| """Portable daily API-key usage view definition. | ||
|
|
||
| Timestamps in this database are naive UTC. Percentiles use continuous linear | ||
| interpolation, matching PostgreSQL's percentile_cont on both supported SQL | ||
| dialects. The SQLite development schema and Alembic migration share this SQL. | ||
| """ | ||
|
|
||
|
|
||
| def _percentile_expression(percent: int) -> str: | ||
| return ( | ||
| "SUM(CASE " | ||
| f"WHEN latency_rank = p{percent}_floor_rank " | ||
| f"THEN latency_ms * (100 - p{percent}_remainder) / 100.0 " | ||
| f"WHEN latency_rank = p{percent}_floor_rank + 1 " | ||
| f"THEN latency_ms * p{percent}_remainder / 100.0 " | ||
| f"ELSE 0 END) AS p{percent}_latency_ms" | ||
| ) | ||
|
|
||
|
|
||
| CREATE_API_KEY_USAGE_DAILY_VIEW_SQL = f""" | ||
| CREATE VIEW api_key_usage_daily AS | ||
| WITH ranked AS ( | ||
| SELECT | ||
| key_id, | ||
| DATE(created_at) AS day, | ||
| status_code, | ||
| latency_ms, | ||
| created_at, | ||
| ROW_NUMBER() OVER ( | ||
| PARTITION BY key_id, DATE(created_at) | ||
| ORDER BY latency_ms, id | ||
| ) AS latency_rank, | ||
| COUNT(*) OVER ( | ||
| PARTITION BY key_id, DATE(created_at) | ||
| ) AS call_count | ||
| FROM api_key_usage_events | ||
| ), positioned AS ( | ||
| SELECT | ||
| *, | ||
| ((call_count - 1) * 50) / 100 + 1 AS p50_floor_rank, | ||
| ((call_count - 1) * 50) % 100 AS p50_remainder, | ||
| ((call_count - 1) * 95) / 100 + 1 AS p95_floor_rank, | ||
| ((call_count - 1) * 95) % 100 AS p95_remainder | ||
| FROM ranked | ||
| ) | ||
| SELECT | ||
| key_id, | ||
| day, | ||
| COUNT(*) AS calls, | ||
| SUM(CASE WHEN status_code BETWEEN 400 AND 499 THEN 1 ELSE 0 END) AS calls_4xx, | ||
| SUM(CASE WHEN status_code BETWEEN 500 AND 599 THEN 1 ELSE 0 END) AS calls_5xx, | ||
| {_percentile_expression(50)}, | ||
| {_percentile_expression(95)}, | ||
| MIN(created_at) AS first_call_at, | ||
| MAX(created_at) AS last_call_at | ||
| FROM positioned | ||
| GROUP BY key_id, day | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.