-
Notifications
You must be signed in to change notification settings - Fork 326
feat(fleet): add refresh endpoint #1128
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
Open
AnobleSCM
wants to merge
8
commits into
Soju06:main
Choose a base branch
from
AnobleSCM:feat/fleet-refresh-endpoint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
77a27fa
feat(fleet): add refresh endpoint
AnobleSCM 8fbb99a
fix(fleet): honor scoped refresh keys
AnobleSCM e293ec2
fix(fleet): respect quota visibility
AnobleSCM db1d932
fix(fleet): keep refresh session alive through cancellation
AnobleSCM 50f7040
fix(fleet): hide quota-derived status
AnobleSCM 94270c5
fix(fleet): isolate owned refresh singleflight
AnobleSCM 104aa13
fix(fleet): use structured owned refresh keys
AnobleSCM 03b74d6
feat(fleet): add observability endpoint
AnobleSCM 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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Fleet summary endpoints for external local dashboards.""" |
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,134 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
|
|
||
| from fastapi import APIRouter, Depends, Security | ||
|
|
||
| from app.core.auth.dependencies import set_dashboard_error_format, validate_usage_api_key | ||
| from app.core.config.settings_cache import get_settings_cache | ||
| from app.core.utils.time import utcnow | ||
| from app.db.models import AccountStatus | ||
| from app.db.session import get_background_session | ||
| from app.dependencies import AccountsContext, get_accounts_context | ||
| from app.modules.accounts.repository import AccountsRepository | ||
| from app.modules.api_keys.service import ApiKeyData | ||
| from app.modules.fleet.mappers import build_fleet_account_summaries | ||
| from app.modules.fleet.schemas import FleetRefreshResponse, FleetSummaryResponse | ||
| from app.modules.proxy.account_cache import get_account_selection_cache | ||
| from app.modules.proxy.rate_limit_cache import get_rate_limit_headers_cache | ||
| from app.modules.usage.repository import AdditionalUsageRepository, UsageRepository | ||
| from app.modules.usage.updater import UsageUpdater | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| router = APIRouter( | ||
| prefix="/api/fleet", | ||
| tags=["fleet"], | ||
| dependencies=[Depends(set_dashboard_error_format)], | ||
| ) | ||
|
|
||
| _REFRESH_SKIP_STATUSES = {AccountStatus.PAUSED, AccountStatus.REAUTH_REQUIRED, AccountStatus.DEACTIVATED} | ||
|
|
||
|
|
||
| def _visible_account_ids(api_key: ApiKeyData) -> list[str] | None: | ||
| return list(api_key.assigned_account_ids) if api_key.account_assignment_scope_enabled else None | ||
|
|
||
|
|
||
| def _usage_sections(raw: str) -> set[str]: | ||
| if not raw or not raw.strip(): | ||
| return set() | ||
| return {section.strip() for section in raw.split(",") if section.strip()} | ||
|
|
||
|
|
||
| async def _can_view_fleet_usage(api_key: ApiKeyData) -> bool: | ||
| if "account_pool_usage" not in _usage_sections(api_key.usage_sections): | ||
| return False | ||
| settings = await get_settings_cache().get() | ||
| return not bool(getattr(settings, "hide_upstream_quota_from_api_keys", False)) | ||
|
|
||
|
|
||
| @router.get("/summary", response_model=FleetSummaryResponse) | ||
| async def get_fleet_summary( | ||
| context: AccountsContext = Depends(get_accounts_context), | ||
| api_key: ApiKeyData = Security(validate_usage_api_key), | ||
| ) -> FleetSummaryResponse: | ||
| """Read-only, minimal per-account capacity summary for fleet consumers.""" | ||
|
|
||
| visible_account_ids = _visible_account_ids(api_key) | ||
| include_usage = await _can_view_fleet_usage(api_key) | ||
| accounts = await context.service.list_accounts(account_ids=visible_account_ids) | ||
| persisted_status_by_account_id: dict[str, str] | None = None | ||
| if not include_usage: | ||
| persisted_accounts = ( | ||
| await context.repository.list_accounts_by_ids(visible_account_ids, refresh_existing=True) | ||
| if visible_account_ids is not None | ||
| else await context.repository.list_accounts(refresh_existing=True) | ||
| ) | ||
| persisted_status_by_account_id = {account.id: account.status.value for account in persisted_accounts} | ||
| return FleetSummaryResponse( | ||
| accounts=build_fleet_account_summaries( | ||
| accounts, | ||
| include_usage=include_usage, | ||
| persisted_status_by_account_id=persisted_status_by_account_id, | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| @router.post("/refresh", response_model=FleetRefreshResponse) | ||
| async def refresh_fleet_usage( | ||
| api_key: ApiKeyData = Security(validate_usage_api_key), | ||
| ) -> FleetRefreshResponse: | ||
| """Request a bounded usage refresh using codex-lb's normal refresh rules.""" | ||
|
|
||
| task = asyncio.create_task( | ||
| _refresh_fleet_usage_with_owned_session(_visible_account_ids(api_key)), | ||
| name="fleet-usage-refresh", | ||
| ) | ||
| try: | ||
| return await asyncio.shield(task) | ||
| except asyncio.CancelledError: | ||
| task.add_done_callback(_log_cancelled_refresh_task_exception) | ||
| raise | ||
|
|
||
|
|
||
| async def _refresh_fleet_usage_with_owned_session(visible_account_ids: list[str] | None) -> FleetRefreshResponse: | ||
| async with get_background_session() as session: | ||
| accounts_repo = AccountsRepository(session) | ||
| usage_repo = UsageRepository(session) | ||
| additional_usage_repo = AdditionalUsageRepository(session) | ||
| accounts = ( | ||
| await accounts_repo.list_accounts_by_ids(visible_account_ids, refresh_existing=True) | ||
| if visible_account_ids is not None | ||
| else await accounts_repo.list_accounts(refresh_existing=True) | ||
| ) | ||
| eligible_accounts = [account for account in accounts if account.status not in _REFRESH_SKIP_STATUSES] | ||
| latest_primary = await usage_repo.latest_by_account(window="primary", account_ids=visible_account_ids) | ||
| usage_written = await UsageUpdater( | ||
| usage_repo, | ||
| accounts_repo, | ||
| additional_usage_repo, | ||
| ).refresh_accounts(eligible_accounts, latest_primary, own_singleflight_sessions=True) | ||
| if usage_written: | ||
| await get_rate_limit_headers_cache().invalidate() | ||
| get_account_selection_cache().invalidate() | ||
| return FleetRefreshResponse( | ||
| usage_written=usage_written, | ||
| account_count=len(accounts), | ||
| attempted_count=len(eligible_accounts), | ||
| generated_at=utcnow(), | ||
| ) | ||
|
|
||
|
|
||
| def _log_cancelled_refresh_task_exception(task: asyncio.Task[FleetRefreshResponse]) -> None: | ||
| if task.cancelled(): | ||
| return | ||
| try: | ||
| exc = task.exception() | ||
| except asyncio.CancelledError: | ||
| return | ||
| if exc is not None: | ||
| logger.error( | ||
| "Fleet usage refresh failed after request cancellation", | ||
| exc_info=(type(exc), exc, exc.__traceback__), | ||
| ) | ||
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,55 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from app.modules.accounts.schemas import AccountSummary | ||
| from app.modules.fleet.schemas import FleetAccountSummary, FleetWindowSummary | ||
|
|
||
|
|
||
| def fleet_account_summary_from_account( | ||
| account: AccountSummary, | ||
| *, | ||
| include_usage: bool = True, | ||
| persisted_status_by_account_id: dict[str, str] | None = None, | ||
| ) -> FleetAccountSummary: | ||
| """Project a dashboard account into the minimal fleet payload.""" | ||
|
|
||
| usage = account.usage | ||
| if include_usage: | ||
| status = account.status | ||
| elif persisted_status_by_account_id is None: | ||
| status = "unknown" | ||
| else: | ||
| status = persisted_status_by_account_id.get(account.account_id, "unknown") | ||
| return FleetAccountSummary( | ||
| account_id=account.account_id, | ||
| display_name=account.display_name, | ||
| email=account.email, | ||
| status=status, | ||
| plan_type=account.plan_type, | ||
| primary=FleetWindowSummary( | ||
| remaining_percent=usage.primary_remaining_percent if include_usage and usage is not None else None, | ||
| reset_at=account.reset_at_primary if include_usage else None, | ||
| window_minutes=account.window_minutes_primary if include_usage else None, | ||
| ), | ||
| secondary=FleetWindowSummary( | ||
| remaining_percent=usage.secondary_remaining_percent if include_usage and usage is not None else None, | ||
| reset_at=account.reset_at_secondary if include_usage else None, | ||
| window_minutes=account.window_minutes_secondary if include_usage else None, | ||
| ), | ||
| last_refresh_at=account.last_refresh_at if include_usage else None, | ||
| ) | ||
|
|
||
|
|
||
| def build_fleet_account_summaries( | ||
| accounts: list[AccountSummary], | ||
| *, | ||
| include_usage: bool = True, | ||
| persisted_status_by_account_id: dict[str, str] | None = None, | ||
| ) -> list[FleetAccountSummary]: | ||
| return [ | ||
| fleet_account_summary_from_account( | ||
| account, | ||
| include_usage=include_usage, | ||
| persisted_status_by_account_id=persisted_status_by_account_id, | ||
| ) | ||
| for account in accounts | ||
| ] |
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,40 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from datetime import datetime | ||
|
|
||
| from pydantic import Field | ||
|
|
||
| from app.modules.shared.schemas import DashboardModel | ||
|
|
||
|
|
||
| class FleetWindowSummary(DashboardModel): | ||
| """One minimal capacity window for a single account.""" | ||
|
|
||
| remaining_percent: float | None = None | ||
| reset_at: datetime | None = None | ||
| window_minutes: int | None = None | ||
|
|
||
|
|
||
| class FleetAccountSummary(DashboardModel): | ||
| """Non-sensitive capacity projection for fleet consumers.""" | ||
|
|
||
| account_id: str | ||
| display_name: str | ||
| email: str | ||
| status: str | ||
| plan_type: str | ||
| primary: FleetWindowSummary | ||
| secondary: FleetWindowSummary | ||
| last_refresh_at: datetime | None = None | ||
|
|
||
|
|
||
| class FleetSummaryResponse(DashboardModel): | ||
| accounts: list[FleetAccountSummary] = Field(default_factory=list) | ||
|
|
||
|
|
||
| class FleetRefreshResponse(DashboardModel): | ||
| ok: bool = True | ||
| usage_written: bool | ||
| account_count: int | ||
| attempted_count: int | ||
| generated_at: datetime |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fresh evidence after the quota-visibility fix is that this predicate still treats
account_pool_usagealone as permission to return the entire fleet summary./v1/usagegatesupstream_limitsseparately, but the fleet mapper returns per-accountresetAtandwindowMinutes; a key configured withusage_sections="account_pool_usage"and noupstream_limitscan recover reset/window quota details that are hidden from/v1/usage. Requireupstream_limitsfor those fields or null them independently.Useful? React with 👍 / 👎.