mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 08:01:04 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75d0d0e0f8 | ||
|
|
1d92d638ba | ||
|
|
4e96567b6d | ||
|
|
42fdaecd7a |
@@ -1170,6 +1170,7 @@ pub struct DiagnosticObservation {
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
|
||||
@@ -1052,14 +1052,23 @@ pub struct ProviderResetCreditResult {
|
||||
pub credit: Option<ProviderResetCredit>,
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 保留账号已有的套餐子类型,仅在缺失时使用上游额度快照补全
|
||||
pub(crate) fn fill_missing_plan_type(&self, account_plan_type: &mut Option<String>) {
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = explicit_plan_type(self.plan_type.as_deref()).map(str::to_owned);
|
||||
}
|
||||
/// 用额度观测补齐缺失的套餐 ID,只采用与账号套餐相符的描述
|
||||
pub fn resolve_observed_plan<'a>(
|
||||
account_plan_type: &mut Option<String>,
|
||||
observed_type: Option<&str>,
|
||||
observed_display: Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let observed_type = explicit_plan_type(observed_type);
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = observed_type.map(str::to_owned);
|
||||
}
|
||||
observed_display.filter(|_| {
|
||||
observed_type
|
||||
.is_none_or(|id| Some(id.trim()) == account_plan_type.as_deref().map(str::trim))
|
||||
})
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 选择账号用量统计窗口,同时返回展示所需的周期事实
|
||||
///
|
||||
/// 周/月额度使用边界完整、可归属到整个账号的窗口
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::model::provider_credentials::{
|
||||
ProviderExport, ProviderExportCredentialInput, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderProfileStatistics, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription,
|
||||
explicit_plan_type,
|
||||
explicit_plan_type, resolve_observed_plan,
|
||||
};
|
||||
use crate::model::{
|
||||
provider_credentials::{ProviderDocument, ProviderQuotaWindow},
|
||||
@@ -558,15 +558,14 @@ impl ProviderAdminRegistry {
|
||||
plan_type: &mut Option<String>,
|
||||
quota: Option<&ProviderQuota>,
|
||||
) -> Option<String> {
|
||||
if let Some(quota) = quota {
|
||||
quota.fill_missing_plan_type(plan_type);
|
||||
// 保留账号已知的套餐,不能给它配上另一档快照的描述
|
||||
let quota_id = explicit_plan_type(quota.plan_type.as_deref()).map(str::trim);
|
||||
if let Some(display) = "a.plan_type_display
|
||||
&& quota_id.is_none_or(|id| Some(id) == plan_type.as_deref().map(str::trim))
|
||||
{
|
||||
return Some(display.clone());
|
||||
}
|
||||
if let Some(quota) = quota
|
||||
&& let Some(display) = resolve_observed_plan(
|
||||
plan_type,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_type_display.as_deref(),
|
||||
)
|
||||
{
|
||||
return Some(display.to_owned());
|
||||
}
|
||||
self.plan_type_display(provider_kind, plan_type.as_deref())
|
||||
}
|
||||
|
||||
@@ -380,11 +380,10 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: item.account_provider_kind.as_deref().and_then(
|
||||
|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, item.account_plan_type.as_deref())
|
||||
},
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.account_provider_kind.as_deref(),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
@@ -422,17 +421,26 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "operations errors"))?;
|
||||
for error in &mut page.items {
|
||||
error.provider_account_plan_type_display =
|
||||
error.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, error.provider_account_plan_type.as_deref())
|
||||
});
|
||||
error.provider_account_plan_type_display = self.historical_plan_display(
|
||||
error.provider_account_plan_type_display.take(),
|
||||
error.provider_kind.as_deref(),
|
||||
error.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultObservabilityService {
|
||||
fn historical_plan_display(
|
||||
&self,
|
||||
display: Option<String>,
|
||||
provider: Option<&str>,
|
||||
plan_type: Option<&str>,
|
||||
) -> Option<String> {
|
||||
display.or_else(|| self.providers.plan_type_display(provider?, plan_type))
|
||||
}
|
||||
|
||||
async fn current_upstream_peers<'a>(
|
||||
&self,
|
||||
ids: impl Iterator<Item = &'a str>,
|
||||
@@ -540,11 +548,11 @@ impl DefaultObservabilityService {
|
||||
.provider_account_ref
|
||||
.as_ref()
|
||||
.and_then(|id| peers.get(id).copied());
|
||||
record.provider_account_plan_type_display =
|
||||
record.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, record.provider_account_plan_type.as_deref())
|
||||
});
|
||||
record.provider_account_plan_type_display = self.historical_plan_display(
|
||||
record.provider_account_plan_type_display.take(),
|
||||
record.provider_kind.as_deref(),
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -541,6 +541,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
account_provider_kind: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
request_count,
|
||||
|
||||
@@ -751,6 +751,7 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
account_provider_kind: Some("openai".to_owned()),
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
name: "diag@example.invalid".to_owned(),
|
||||
request_count: 2,
|
||||
success_count: 2,
|
||||
@@ -1093,6 +1094,12 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
closed.error_message =
|
||||
Some("OpenAI WebSocket closed before a terminal response".to_owned());
|
||||
records.push(closed);
|
||||
let mut agy = records[0].clone();
|
||||
agy.id = "request_antigravity".to_owned();
|
||||
agy.provider_kind = Some("antigravity".to_owned());
|
||||
agy.provider_account_plan_type = Some("g1-pro-tier".to_owned());
|
||||
agy.provider_account_plan_type_display = Some("Pro subscription".to_owned());
|
||||
records.push(agy);
|
||||
}
|
||||
let response = observability::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
@@ -1112,6 +1119,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.expect("usage response body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("usage response JSON");
|
||||
|
||||
assert_eq!(value["data"]["items"][5]["accountPlanType"], "g1-pro-tier");
|
||||
assert_eq!(
|
||||
value["data"]["items"][5]["accountPlanTypeDisplay"],
|
||||
"Pro subscription"
|
||||
);
|
||||
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
||||
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
||||
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
||||
@@ -1248,6 +1260,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
"$0.007"
|
||||
);
|
||||
|
||||
let value_before_peer_refresh = value["data"]["items"].as_array().unwrap();
|
||||
// 互联标识随当前摘要变化,重复请求共享同一账号,既有请求快照保持原值
|
||||
for peer in [
|
||||
Some((true, true)),
|
||||
@@ -1277,7 +1290,15 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(item["accountName"], "Snapshot Alpha");
|
||||
assert_eq!(item["accountPlanType"], "supergrok_plus");
|
||||
let old = value_before_peer_refresh
|
||||
.iter()
|
||||
.find(|old| old["id"] == item["id"])
|
||||
.unwrap();
|
||||
assert_eq!(item["accountPlanType"], old["accountPlanType"]);
|
||||
assert_eq!(
|
||||
item["accountPlanTypeDisplay"],
|
||||
old["accountPlanTypeDisplay"]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -817,6 +817,8 @@ pub struct AccountHistorySnapshot {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_display_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub notes_snapshot: Option<String>,
|
||||
}
|
||||
|
||||
@@ -828,6 +830,7 @@ impl AccountHistorySnapshot {
|
||||
email: account.email().map(str::to_owned),
|
||||
authentication_kind: account.authentication_kind().to_owned(),
|
||||
plan_type_snapshot: account.plan_type().map(str::to_owned),
|
||||
plan_type_display_snapshot: None,
|
||||
notes_snapshot: account.notes().map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -947,6 +947,7 @@ fn account_snapshot_bytes(
|
||||
snapshot.email.as_deref(),
|
||||
Some(snapshot.authentication_kind.as_str()),
|
||||
snapshot.plan_type_snapshot.as_deref(),
|
||||
snapshot.plan_type_display_snapshot.as_deref(),
|
||||
snapshot.notes_snapshot.as_deref(),
|
||||
])
|
||||
})
|
||||
|
||||
@@ -637,6 +637,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
account_provider_kind: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
request_count: metrics.request_count,
|
||||
success_count: metrics.success_count,
|
||||
failure_count: metrics.failure_count,
|
||||
@@ -670,9 +671,9 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type,coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -686,6 +687,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
item.account_provider_kind = get(&row, "provider_kind")?;
|
||||
item.account_authentication_kind = get(&row, "authentication_kind")?;
|
||||
item.account_plan_type = get(&row, "plan_type")?;
|
||||
item.account_plan_type_display = get(&row, "plan_type_display")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,6 +282,7 @@ fn admin_diagnostic_observation(
|
||||
account_provider_kind: observation.account_provider_kind,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
account_plan_type: observation.account_plan_type,
|
||||
account_plan_type_display: observation.account_plan_type_display,
|
||||
request_count: observation.request_count,
|
||||
success_count: observation.success_count,
|
||||
failure_count: observation.failure_count,
|
||||
@@ -391,7 +392,7 @@ pub(crate) fn usage_list_record_from_row(
|
||||
provider_account_notes: get(row, "provider_account_notes")?,
|
||||
provider_account_upstream_peer: None,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
provider_account_plan_type_display: None,
|
||||
provider_account_plan_type_display: get(row, "provider_account_plan_type_display")?,
|
||||
provider_account_authentication_kind: get(row, "provider_account_authentication_kind")?,
|
||||
upstream_model_id: get(row, "upstream_model_id")?,
|
||||
upstream_transport: get(row, "upstream_transport")?,
|
||||
@@ -558,7 +559,7 @@ pub(crate) fn ops_error_from_row(row: &sqlx::postgres::PgRow) -> StoreResult<Ops
|
||||
provider_account_name: get(row, "provider_account_name")?,
|
||||
provider_account_email: get(row, "provider_account_email")?,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
provider_account_plan_type_display: None,
|
||||
provider_account_plan_type_display: get(row, "provider_account_plan_type_display")?,
|
||||
provider_account_authentication_kind: get(row, "provider_account_authentication_kind")?,
|
||||
upstream_model_id: get(row, "upstream_model_id")?,
|
||||
upstream_transport: get(row, "upstream_transport")?,
|
||||
|
||||
@@ -386,6 +386,7 @@ pub struct DiagnosticObservation {
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
|
||||
@@ -11,6 +11,7 @@ const REQUEST_ERROR_SELECT: &str = "select 'model_request'::text as source,
|
||||
mr.provider_account_name_snapshot as provider_account_name,
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
mr.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
mr.upstream_model_id, mr.upstream_transport,
|
||||
@@ -43,6 +44,7 @@ const OPS_EVENT_SELECT: &str = "select 'ops_event'::text as source,
|
||||
oe.provider_account_name_snapshot as provider_account_name,
|
||||
oe.provider_account_email_snapshot as provider_account_email,
|
||||
oe.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
oe.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
oe.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
oe.upstream_model_id, null::text as upstream_transport, oe.failure_kind,
|
||||
|
||||
@@ -138,6 +138,7 @@ pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
mr.provider_account_notes_snapshot as provider_account_notes,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
mr.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
mr.upstream_model_id, mr.upstream_transport, mr.service_tier,
|
||||
|
||||
@@ -109,6 +109,7 @@ impl OpsEventRepository for PgOpsEventRepository {
|
||||
provider_kind, provider_account_ref, upstream_model_id,
|
||||
provider_account_name_snapshot, provider_account_email_snapshot,
|
||||
provider_account_authentication_kind_snapshot, provider_account_plan_type_snapshot,
|
||||
provider_account_plan_type_display_snapshot,
|
||||
failure_kind, upstream_send_state, status_code, provider_error_code, retry_after_ms,
|
||||
upstream_request_id, latency_ms, message, error_details,
|
||||
created_at
|
||||
@@ -117,6 +118,7 @@ impl OpsEventRepository for PgOpsEventRepository {
|
||||
$8::jsonb ->> 'name',
|
||||
$8::jsonb ->> 'email',
|
||||
$8::jsonb ->> 'authenticationKind', $8::jsonb ->> 'planTypeSnapshot',
|
||||
$8::jsonb ->> 'planTypeDisplaySnapshot',
|
||||
$11, $12, $13, $14, $15, $16, $17, $18, $19, $20
|
||||
)",
|
||||
)
|
||||
|
||||
@@ -164,10 +164,14 @@ async fn request_snapshots_should_survive_account_deletion() {
|
||||
)
|
||||
.await;
|
||||
let store = PgExecutionStore::new(database.pool.clone());
|
||||
let mut first_attempt = attempt(&database.pool, "req_snap_a", 1, "acct_snap_a").await;
|
||||
let snapshot = first_attempt.account_snapshot.as_mut().unwrap();
|
||||
snapshot.plan_type_snapshot = Some("g1-pro-tier".to_owned());
|
||||
snapshot.plan_type_display_snapshot = Some("Pro subscription".to_owned());
|
||||
store
|
||||
.insert_model_request_with_first_attempt(
|
||||
new_request("req_snap_a", started_at),
|
||||
attempt(&database.pool, "req_snap_a", 1, "acct_snap_a").await,
|
||||
first_attempt,
|
||||
)
|
||||
.await
|
||||
.expect("insert request with first attempt");
|
||||
@@ -217,6 +221,15 @@ async fn request_snapshots_should_survive_account_deletion() {
|
||||
)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
Some("g1-pro-tier")
|
||||
);
|
||||
assert_eq!(
|
||||
record.provider_account_plan_type_display.as_deref(),
|
||||
Some("Pro subscription")
|
||||
);
|
||||
|
||||
let detail = repository
|
||||
.usage_record_detail("req_snap_a")
|
||||
.await
|
||||
@@ -1282,6 +1295,7 @@ async fn account_snapshot(
|
||||
email,
|
||||
authentication_kind,
|
||||
plan_type_snapshot,
|
||||
plan_type_display_snapshot: None,
|
||||
notes_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,6 +147,12 @@ impl Document {
|
||||
valid_until,
|
||||
})
|
||||
}
|
||||
pub(super) fn plan_display(&self) -> Option<&str> {
|
||||
self.plan_description
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn plan_type(&self) -> Option<String> {
|
||||
self.tier
|
||||
.as_ref()
|
||||
@@ -254,11 +260,7 @@ impl Document {
|
||||
}),
|
||||
limit_reached: self.access(observed).is_exhausted(),
|
||||
plan_type: self.plan_type(),
|
||||
plan_type_display: self
|
||||
.plan_description
|
||||
.as_ref()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.cloned(),
|
||||
plan_type_display: self.plan_display().map(str::to_owned),
|
||||
observed_at: Some(DateTime::<Utc>::from(observed)),
|
||||
windows,
|
||||
..Default::default()
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
mod document;
|
||||
mod service;
|
||||
|
||||
pub(crate) use service::{QuotaService, QuotaTask};
|
||||
pub(crate) use service::{CandidateQuota, QuotaService, QuotaTask};
|
||||
|
||||
@@ -29,6 +29,13 @@ use std::{
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
pub(crate) struct CandidateQuota {
|
||||
pub(crate) exhausted: bool,
|
||||
pub(crate) signals: Option<AccountQuotaSignals>,
|
||||
pub(crate) plan_type: Option<String>,
|
||||
pub(crate) plan_display: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct QuotaService {
|
||||
kind: ProviderKind,
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
@@ -245,8 +252,7 @@ impl QuotaService {
|
||||
&self,
|
||||
accounts: &[ProviderAccount],
|
||||
model: &str,
|
||||
) -> Result<BTreeMap<ProviderAccountId, (bool, Option<AccountQuotaSignals>)>, ProviderAdminError>
|
||||
{
|
||||
) -> Result<BTreeMap<ProviderAccountId, CandidateQuota>, ProviderAdminError> {
|
||||
let owners: BTreeMap<_, _> = accounts.iter().map(|a| (a.id().clone(), a)).collect();
|
||||
let ids: Vec<_> = owners.keys().cloned().collect();
|
||||
let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?;
|
||||
@@ -260,13 +266,20 @@ impl QuotaService {
|
||||
.map(|account| (o, account))
|
||||
})
|
||||
.map(|(o, account)| {
|
||||
let result = parse(&o)?.model_signals(
|
||||
let document = parse(&o)?;
|
||||
let (exhausted, signals) = document.model_signals(
|
||||
model,
|
||||
account.auto_use_quota_credits(),
|
||||
o.observed_at,
|
||||
now,
|
||||
);
|
||||
Ok((o.account_id, result))
|
||||
let quota = CandidateQuota {
|
||||
exhausted,
|
||||
signals,
|
||||
plan_type: document.plan_type(),
|
||||
plan_display: document.plan_display().map(str::to_owned),
|
||||
};
|
||||
Ok((o.account_id, quota))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 从本地目录、凭据版本、额度和租约信号构建本轮候选
|
||||
|
||||
use super::AntigravityProvider;
|
||||
use crate::transport::unsent;
|
||||
use crate::{credential::quota::CandidateQuota, transport::unsent};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountCandidate, AccountSelectionContext, AccountStatus, CredentialRevision,
|
||||
@@ -22,6 +22,7 @@ pub(super) enum Project {
|
||||
pub(super) struct CandidatePool {
|
||||
pub(super) accounts: Vec<AccountCandidate>,
|
||||
pub(super) projects: BTreeMap<ProviderAccountId, (CredentialRevision, Project)>,
|
||||
pub(super) quotas: BTreeMap<ProviderAccountId, CandidateQuota>,
|
||||
pub(super) selection: AccountSelectionContext,
|
||||
}
|
||||
|
||||
@@ -72,13 +73,11 @@ impl AntigravityProvider {
|
||||
.iter()
|
||||
.map(|account| account.id().clone())
|
||||
.collect();
|
||||
let mut quota = if diagnostic {
|
||||
BTreeMap::new()
|
||||
} else {
|
||||
self.quota
|
||||
.scheduling(&accounts, model.as_str())
|
||||
.await
|
||||
.map_err(super::unavailable)?
|
||||
let mut quotas = match self.quota.scheduling(&accounts, model.as_str()).await {
|
||||
Ok(quotas) => quotas,
|
||||
// 固定探测绕过额度门槛,读取不到套餐快照也应能继续
|
||||
Err(_) if diagnostic => BTreeMap::new(),
|
||||
Err(error) => return Err(super::unavailable(error)),
|
||||
};
|
||||
let scheduling = self
|
||||
.leases
|
||||
@@ -118,7 +117,6 @@ impl AntigravityProvider {
|
||||
let mut candidates = Vec::new();
|
||||
let mut model_exhausted = false;
|
||||
for account in accounts {
|
||||
let (exhausted, quota_signals) = quota.remove(account.id()).unwrap_or_default();
|
||||
if projects
|
||||
.get(account.id())
|
||||
.is_none_or(|(revision, _)| *revision != account.revision())
|
||||
@@ -127,7 +125,8 @@ impl AntigravityProvider {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if exhausted {
|
||||
let quota = quotas.get_mut(account.id()).filter(|_| !diagnostic);
|
||||
if quota.as_ref().is_some_and(|q| q.exhausted) {
|
||||
model_exhausted |= !excluded.contains(account.id())
|
||||
&& matches!(
|
||||
account.status_projection(now, None).status,
|
||||
@@ -143,7 +142,7 @@ impl AntigravityProvider {
|
||||
.cloned()
|
||||
.ok_or_else(|| unsent(Kind::ProviderInfrastructureUnavailable))?
|
||||
.with_runtime_health(failure_rate, first_output_latency)
|
||||
.with_provider_quota(quota_signals);
|
||||
.with_provider_quota(quota.and_then(|q| q.signals.take()));
|
||||
candidates.push(AccountCandidate {
|
||||
account,
|
||||
signals,
|
||||
@@ -168,6 +167,7 @@ impl AntigravityProvider {
|
||||
Ok(CandidatePool {
|
||||
accounts: candidates,
|
||||
projects,
|
||||
quotas,
|
||||
selection,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::{AntigravityProvider, candidates::Project};
|
||||
use crate::transport::unsent;
|
||||
use futures::StreamExt;
|
||||
use gateway_core::{
|
||||
account::AccountHistorySnapshot,
|
||||
engine::{
|
||||
AttemptContext,
|
||||
provider::{
|
||||
@@ -68,9 +67,7 @@ impl AntigravityProvider {
|
||||
)
|
||||
.with_credential_revision(selected.account.revision())
|
||||
.with_selection_observation(selection)
|
||||
.with_account_snapshot(Some(AccountHistorySnapshot::from_account(
|
||||
&selected.account,
|
||||
)));
|
||||
.with_account_snapshot(Some(selected.snapshot));
|
||||
let cancellation = ctx.cancellation().clone();
|
||||
let deadline = ctx.deadline();
|
||||
let started_at = ctx.timing_started_at();
|
||||
|
||||
@@ -5,10 +5,11 @@ use super::{
|
||||
candidates::{CandidatePool, Project},
|
||||
};
|
||||
use crate::{credential::Material, transport::unsent};
|
||||
use gateway_admin::model::provider_credentials::resolve_observed_plan;
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountCapacitySnapshot, AccountSelector, PreferredAccountSelection, ProviderAccount,
|
||||
RotationStrategy,
|
||||
AccountCapacitySnapshot, AccountHistorySnapshot, AccountSelector,
|
||||
PreferredAccountSelection, ProviderAccount, RotationStrategy,
|
||||
},
|
||||
concurrency::{CapacityWait, ConcurrencyQueuePolicy, QueueRejection},
|
||||
engine::{
|
||||
@@ -29,6 +30,7 @@ pub(super) struct SelectedAccount {
|
||||
pub(super) account: ProviderAccount,
|
||||
pub(super) capacity: Option<AccountCapacitySnapshot>,
|
||||
pub(super) material: Material,
|
||||
pub(super) snapshot: AccountHistorySnapshot,
|
||||
pub(super) project: Project,
|
||||
pub(super) lease: Box<dyn ProviderLeaseGuard>,
|
||||
pub(super) account_switch: bool,
|
||||
@@ -102,6 +104,7 @@ impl AntigravityProvider {
|
||||
let CandidatePool {
|
||||
accounts,
|
||||
mut projects,
|
||||
mut quotas,
|
||||
mut selection,
|
||||
} = self.load_candidates(model, ctx, search).await?;
|
||||
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
|
||||
@@ -233,9 +236,16 @@ impl AntigravityProvider {
|
||||
|| ctx
|
||||
.account_state_owner()
|
||||
.is_some_and(|owner| !owner.matches(&self.kind, account.id()));
|
||||
let selected = self
|
||||
.load_selected(account, project, lease, capacity, account_switch, ctx)
|
||||
.await?;
|
||||
let (current, material) = self.load_selected(account, ctx).await?;
|
||||
let mut snapshot = AccountHistorySnapshot::from_account(¤t);
|
||||
if let Some(quota) = quotas.remove(account.id()) {
|
||||
snapshot.plan_type_display_snapshot = resolve_observed_plan(
|
||||
&mut snapshot.plan_type_snapshot,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_display.as_deref(),
|
||||
)
|
||||
.map(str::to_owned);
|
||||
}
|
||||
let claim = affinity.as_ref().map(|affinity| {
|
||||
affinity.claim(
|
||||
account.id(),
|
||||
@@ -265,11 +275,19 @@ impl AntigravityProvider {
|
||||
.await
|
||||
.map_err(super::unavailable)?
|
||||
{
|
||||
selected.lease.release().await.map_err(super::unavailable)?;
|
||||
lease.release().await.map_err(super::unavailable)?;
|
||||
tokio::task::yield_now().await;
|
||||
continue 'refresh;
|
||||
}
|
||||
return Ok(selected);
|
||||
return Ok(SelectedAccount {
|
||||
account: current,
|
||||
snapshot,
|
||||
capacity,
|
||||
material,
|
||||
project,
|
||||
lease,
|
||||
account_switch,
|
||||
});
|
||||
}
|
||||
ProviderLeaseAcquisition::Busy { retry_after: delay } => {
|
||||
if let Some(delay) = delay {
|
||||
@@ -309,12 +327,8 @@ impl AntigravityProvider {
|
||||
async fn load_selected(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
project: Project,
|
||||
lease: Box<dyn ProviderLeaseGuard>,
|
||||
capacity: Option<AccountCapacitySnapshot>,
|
||||
account_switch: bool,
|
||||
ctx: &AttemptContext,
|
||||
) -> Result<SelectedAccount, ProviderError> {
|
||||
) -> Result<(ProviderAccount, Material), ProviderError> {
|
||||
let current = self
|
||||
.credentials
|
||||
.current(account.id())
|
||||
@@ -326,13 +340,6 @@ impl AntigravityProvider {
|
||||
return Err(unsent(Kind::NoEligibleAccount));
|
||||
}
|
||||
let material = self.credentials.material(¤t)?;
|
||||
Ok(SelectedAccount {
|
||||
account: current.account,
|
||||
capacity,
|
||||
material,
|
||||
project,
|
||||
lease,
|
||||
account_switch,
|
||||
})
|
||||
Ok((current.account, material))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +195,10 @@ async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_plan_uses_the_desktop_description_for_every_tier() {
|
||||
async fn account_and_request_plans_use_the_desktop_description_for_every_tier() {
|
||||
use crate::support::{context, request};
|
||||
use gateway_core::engine::provider::Provider as _;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(1.0), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
@@ -228,6 +231,23 @@ async fn account_plan_uses_the_desktop_description_for_every_tier() {
|
||||
let view = f.quota.read(account.id()).await.unwrap();
|
||||
assert_eq!(view.plan_type.as_deref(), paid_id.or(Some("free-tier")));
|
||||
assert_eq!(view.plan_type_display.as_deref(), description);
|
||||
let stream = f
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = stream.metadata().account_snapshot().unwrap();
|
||||
assert_eq!(snapshot.plan_type_snapshot, view.plan_type);
|
||||
assert_eq!(snapshot.plan_type_display_snapshot.as_deref(), description);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,10 +290,14 @@ async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
.scheduling(std::slice::from_ref(&account), "other-model")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(gemini[account.id()].0);
|
||||
assert!(!claude[account.id()].0);
|
||||
assert!(gemini[account.id()].exhausted);
|
||||
assert!(!claude[account.id()].exhausted);
|
||||
assert_eq!(
|
||||
claude[account.id()].1.as_ref().unwrap().remaining_rank(),
|
||||
claude[account.id()]
|
||||
.signals
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.remaining_rank(),
|
||||
Some(8000)
|
||||
);
|
||||
{
|
||||
@@ -285,8 +309,8 @@ async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!expired[account.id()].0);
|
||||
assert!(expired[account.id()].1.is_none());
|
||||
assert!(!expired[account.id()].exhausted);
|
||||
assert!(expired[account.id()].signals.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -305,7 +329,7 @@ async fn unknown_quota_preserves_only_observed_windows_without_inventing_percent
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap()[account.id()]
|
||||
.0
|
||||
.exhausted
|
||||
);
|
||||
}
|
||||
|
||||
@@ -500,14 +524,14 @@ async fn google_one_credits_require_opt_in_and_sufficient_balance() {
|
||||
.unwrap();
|
||||
assert_eq!(credits.balance.as_deref(), Some(balance));
|
||||
assert_eq!(credits.has_credits, usable);
|
||||
let (blocked, _) = fixture
|
||||
let quota = fixture
|
||||
.quota
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap()
|
||||
.remove(account.id())
|
||||
.unwrap();
|
||||
assert_eq!(blocked, !(enabled && usable));
|
||||
assert_eq!(quota.exhausted, !(enabled && usable));
|
||||
let result = fixture
|
||||
.provider
|
||||
.clone()
|
||||
|
||||
@@ -44,3 +44,4 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m
|
||||
23eeb6ef99de2315cf4a198638e9c73b364fb1cb40b7e571a3f15d3e9d15f67c 0044_account_quota_settings.sql
|
||||
5cfe0227e2a4b26c268bf5b6ef7f93904e02c57d9d2d05cfe2e32db0a7d4e7a2 0045_account_group_policies_and_openai_request_settings.sql
|
||||
e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_and_runtime_settings.sql
|
||||
98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
-- 请求与运维事件保留各自选中账号时的套餐描述
|
||||
alter table ops_events add column provider_account_plan_type_display_snapshot text;
|
||||
|
||||
create or replace function model_request_observation_valid(document jsonb) returns boolean
|
||||
language plpgsql immutable parallel safe as $$
|
||||
declare
|
||||
spec record;
|
||||
item jsonb;
|
||||
number numeric;
|
||||
begin
|
||||
if document is null or jsonb_typeof(document) <> 'object'
|
||||
or octet_length(document::text) > 1048576 then
|
||||
return false;
|
||||
end if;
|
||||
for spec in select * from (values
|
||||
('{}'::text[], array['account','continuation','error','recovery','request','response','routing','scheduling','timings','transport']::text[]),
|
||||
('{request}'::text[], array['clientApiKeyNameSnapshot','clientIp','compact','configRevision','endpoint','protocol','reasoningEffort','reasoningPreset','subagentKind','userAgent']::text[]),
|
||||
('{account}'::text[], array['authenticationKind','email','name','planTypeSnapshot','planTypeDisplaySnapshot','notesSnapshot']::text[]),
|
||||
('{routing}'::text[], array['groupNamesSnapshot','groupRefs','scope']::text[]),
|
||||
('{error}'::text[], array['message','providerErrorCode','retryAfterMs']::text[]),
|
||||
('{timings}'::text[], array['local','upstream']::text[]),
|
||||
('{timings,local}'::text[], array['connectMs','firstEventMs','firstReasoningMs','firstTextMs','firstTokenMs','headersMs','latencyMs','transportDecisionWaitMs']::text[]),
|
||||
('{timings,upstream}'::text[], array['processingMs','responseMs','apiOverheadMs','engineMs','engineIapiTtftMs','engineServiceTtftMs','engineIapiTbtMs','engineServiceTbtMs']::text[]),
|
||||
('{scheduling}'::text[], array['accountSelectionWaitMs','admissionDecisionMs','capacityTotalSlots','capacityUsedSlots']::text[]),
|
||||
('{transport}'::text[], array['connection','httpVersion','websocketPool']::text[]),
|
||||
('{transport,connection}'::text[], array['ageMs','exitReason','id','idleMs']::text[]),
|
||||
('{response}'::text[], array['responseModel']::text[]),
|
||||
('{continuation}'::text[], array['previousResponseIdHash','unavailableReason']::text[]),
|
||||
('{recovery}'::text[], array['retryDelayMs','totalLatencyMs']::text[])) as groups(path, allowed_keys) loop
|
||||
item := document #> spec.path;
|
||||
if item is not null and (jsonb_typeof(item) <> 'object' or item - spec.allowed_keys <> '{}'::jsonb) then
|
||||
return false;
|
||||
end if;
|
||||
end loop;
|
||||
for spec in select * from (values
|
||||
('{request,configRevision}'::text[], 'number'),
|
||||
('{request,protocol}'::text[], 'string'),
|
||||
('{request,endpoint}'::text[], 'string'),
|
||||
('{request,clientApiKeyNameSnapshot}'::text[], 'string'),
|
||||
('{account,planTypeSnapshot}'::text[], 'string'),
|
||||
('{account,planTypeDisplaySnapshot}'::text[], 'string'),
|
||||
('{account,notesSnapshot}'::text[], 'string'),
|
||||
('{account,name}'::text[], 'string'),
|
||||
('{account,email}'::text[], 'string'),
|
||||
('{account,authenticationKind}'::text[], 'string'),
|
||||
('{routing,scope}'::text[], 'string'),
|
||||
('{routing,groupRefs}'::text[], 'array'),
|
||||
('{routing,groupNamesSnapshot}'::text[], 'array'),
|
||||
('{error,providerErrorCode}'::text[], 'string'),
|
||||
('{error,message}'::text[], 'string'),
|
||||
('{error,retryAfterMs}'::text[], 'number'),
|
||||
('{request,clientIp}'::text[], 'string'),
|
||||
('{request,userAgent}'::text[], 'string'),
|
||||
('{request,reasoningEffort}'::text[], 'string'),
|
||||
('{request,reasoningPreset}'::text[], 'string'),
|
||||
('{request,subagentKind}'::text[], 'string'),
|
||||
('{request,compact}'::text[], 'boolean'),
|
||||
('{timings,local,transportDecisionWaitMs}'::text[], 'number'),
|
||||
('{timings,local,connectMs}'::text[], 'number'),
|
||||
('{timings,local,headersMs}'::text[], 'number'),
|
||||
('{timings,local,firstEventMs}'::text[], 'number'),
|
||||
('{timings,local,firstReasoningMs}'::text[], 'number'),
|
||||
('{timings,local,firstTextMs}'::text[], 'number'),
|
||||
('{timings,local,firstTokenMs}'::text[], 'number'),
|
||||
('{timings,local,latencyMs}'::text[], 'number'),
|
||||
('{timings,upstream,processingMs}'::text[], 'number'),
|
||||
('{timings,upstream,apiOverheadMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineIapiTtftMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineServiceTtftMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineIapiTbtMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineServiceTbtMs}'::text[], 'milliseconds'),
|
||||
('{scheduling,admissionDecisionMs}'::text[], 'number'),
|
||||
('{scheduling,accountSelectionWaitMs}'::text[], 'number'),
|
||||
('{scheduling,capacityUsedSlots}'::text[], 'number'),
|
||||
('{scheduling,capacityTotalSlots}'::text[], 'number'),
|
||||
('{transport,httpVersion}'::text[], 'string'),
|
||||
('{transport,websocketPool}'::text[], 'string'),
|
||||
('{transport,connection,id}'::text[], 'string'),
|
||||
('{transport,connection,exitReason}'::text[], 'string'),
|
||||
('{transport,connection,ageMs}'::text[], 'number'),
|
||||
('{transport,connection,idleMs}'::text[], 'number'),
|
||||
('{response,responseModel}'::text[], 'string'),
|
||||
('{continuation,previousResponseIdHash}'::text[], 'string'),
|
||||
('{continuation,unavailableReason}'::text[], 'string'),
|
||||
('{recovery,retryDelayMs}'::text[], 'number'),
|
||||
('{recovery,totalLatencyMs}'::text[], 'number'),
|
||||
('{timings,upstream,responseMs}'::text[], 'number')) as fields(path, kind) loop
|
||||
item := document #> spec.path;
|
||||
if item is null or item = 'null'::jsonb then continue; end if;
|
||||
if spec.kind = 'milliseconds' then
|
||||
if jsonb_typeof(item) <> 'number' then return false; end if;
|
||||
number := (item #>> '{}')::numeric;
|
||||
if number < 0 or number > 9223372036854775807 then return false; end if;
|
||||
continue;
|
||||
end if;
|
||||
if jsonb_typeof(item) <> spec.kind then return false; end if;
|
||||
if spec.kind = 'number' then
|
||||
number := (item #>> '{}')::numeric;
|
||||
if item #>> '{}' !~ '^[0-9]+$' or number > 9223372036854775807 then return false; end if;
|
||||
elsif spec.kind = 'array' then
|
||||
if exists (select 1 from jsonb_array_elements(item) member where jsonb_typeof(member) <> 'string') then return false; end if;
|
||||
end if;
|
||||
end loop;
|
||||
if (document #> '{request,configRevision}' is not null
|
||||
and document #> '{request,configRevision}' <> 'null'::jsonb
|
||||
and document #> '{request,compact}' in ('true'::jsonb, 'false'::jsonb)
|
||||
and coalesce(length(document #>> '{request,protocol}'), 0) > 0
|
||||
and coalesce(length(document #>> '{request,endpoint}'), 0) > 0
|
||||
and jsonb_typeof(document #> '{routing,scope}') = 'string'
|
||||
and jsonb_typeof(document #> '{routing,groupRefs}') = 'array'
|
||||
and jsonb_typeof(document #> '{routing,groupNamesSnapshot}') = 'array') is not true then
|
||||
return false;
|
||||
end if;
|
||||
if document #>> '{request,clientIp}' is not null then
|
||||
perform (document #>> '{request,clientIp}')::inet;
|
||||
end if;
|
||||
return true;
|
||||
exception when invalid_text_representation or numeric_value_out_of_range then
|
||||
return false;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace view model_request_observations as
|
||||
select mr.*,
|
||||
coalesce(lease.lease_expires_at, mr.recovery_lease_expires_at) as effective_recovery_lease_expires_at,
|
||||
(mr.request_observation_json #>> '{request,configRevision}')::bigint as config_revision,
|
||||
(mr.request_observation_json #>> '{request,protocol}') as protocol,
|
||||
(mr.request_observation_json #>> '{request,endpoint}') as endpoint,
|
||||
(mr.request_observation_json #>> '{account,name}') as provider_account_name_snapshot,
|
||||
(mr.request_observation_json #>> '{account,email}') as provider_account_email_snapshot,
|
||||
(mr.request_observation_json #>> '{account,authenticationKind}') as provider_account_authentication_kind_snapshot,
|
||||
(mr.request_observation_json #>> '{routing,scope}') as routing_scope,
|
||||
array(select jsonb_array_elements_text(mr.request_observation_json #> '{routing,groupRefs}')) as routing_group_refs,
|
||||
(mr.request_observation_json #> '{routing,groupNamesSnapshot}') as routing_group_names_snapshot,
|
||||
(mr.request_observation_json #>> '{error,providerErrorCode}') as provider_error_code,
|
||||
(mr.request_observation_json #>> '{error,message}') as error_message,
|
||||
(mr.request_observation_json #>> '{error,retryAfterMs}')::bigint as retry_after_ms,
|
||||
(mr.request_observation_json #>> '{request,clientIp}')::inet as client_ip,
|
||||
(mr.request_observation_json #>> '{request,userAgent}') as user_agent,
|
||||
(mr.request_observation_json #>> '{request,reasoningEffort}') as reasoning_effort,
|
||||
(mr.request_observation_json #>> '{request,reasoningPreset}') as reasoning_preset,
|
||||
(mr.request_observation_json #>> '{request,subagentKind}') as subagent_kind,
|
||||
(mr.request_observation_json #>> '{request,compact}')::boolean as compact,
|
||||
measured.transport_decision_wait_ms as transport_decision_wait_ms,
|
||||
measured.connect_ms as connect_ms,
|
||||
measured.headers_ms as headers_ms,
|
||||
measured.first_event_ms as first_event_ms,
|
||||
measured.first_reasoning_ms as first_reasoning_ms,
|
||||
measured.first_text_ms as first_text_ms,
|
||||
measured.first_token_ms as first_token_ms,
|
||||
measured.latency_ms as latency_ms,
|
||||
measured.provider_processing_ms as provider_processing_ms,
|
||||
measured.admission_decision_ms as admission_decision_ms,
|
||||
measured.account_selection_wait_ms as account_selection_wait_ms,
|
||||
measured.capacity_used_slots as capacity_used_slots,
|
||||
measured.capacity_total_slots as capacity_total_slots,
|
||||
(mr.request_observation_json #>> '{transport,httpVersion}') as http_version,
|
||||
(mr.request_observation_json #>> '{transport,websocketPool}') as websocket_pool,
|
||||
(mr.request_observation_json #>> '{transport,connection,id}') as upstream_connection_id,
|
||||
(mr.request_observation_json #>> '{transport,connection,exitReason}') as upstream_connection_exit_reason,
|
||||
(mr.request_observation_json #>> '{transport,connection,ageMs}')::bigint as upstream_connection_age_ms,
|
||||
(mr.request_observation_json #>> '{transport,connection,idleMs}')::bigint as upstream_connection_idle_ms,
|
||||
(mr.request_observation_json #>> '{response,responseModel}') as upstream_response_model,
|
||||
(mr.request_observation_json #>> '{continuation,previousResponseIdHash}') as continuation_previous_response_id_hash,
|
||||
(mr.request_observation_json #>> '{continuation,unavailableReason}') as continuation_unavailable_reason,
|
||||
(mr.request_observation_json #>> '{recovery,retryDelayMs}')::bigint as recovery_retry_delay_ms,
|
||||
(mr.request_observation_json #>> '{recovery,totalLatencyMs}')::bigint as recovery_total_latency_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,apiOverheadMs}')::double precision as upstream_api_overhead_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineMs}')::double precision as upstream_engine_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineIapiTtftMs}')::double precision as upstream_engine_iapi_ttft_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineServiceTtftMs}')::double precision as upstream_engine_service_ttft_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineIapiTbtMs}')::double precision as upstream_engine_iapi_tbt_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineServiceTbtMs}')::double precision as upstream_engine_service_tbt_ms,
|
||||
measured.upstream_response_ms as upstream_response_ms,
|
||||
mr.request_observation_json #>> '{request,clientApiKeyNameSnapshot}' as client_api_key_name_snapshot,
|
||||
mr.request_observation_json #>> '{account,planTypeSnapshot}' as provider_account_plan_type_snapshot,
|
||||
mr.request_observation_json #>> '{account,notesSnapshot}' as provider_account_notes_snapshot,
|
||||
mr.request_observation_json #>> '{account,planTypeDisplaySnapshot}' as provider_account_plan_type_display_snapshot
|
||||
from model_requests mr
|
||||
left join model_request_leases lease on lease.request_id = mr.id
|
||||
cross join lateral (
|
||||
select (mr.request_observation_json #>> '{timings,local,transportDecisionWaitMs}')::bigint as transport_decision_wait_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,connectMs}')::bigint as connect_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,headersMs}')::bigint as headers_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstEventMs}')::bigint as first_event_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstReasoningMs}')::bigint as first_reasoning_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstTextMs}')::bigint as first_text_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstTokenMs}')::bigint as first_token_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,latencyMs}')::bigint as latency_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,processingMs}')::bigint as provider_processing_ms,
|
||||
(mr.request_observation_json #>> '{scheduling,admissionDecisionMs}')::bigint as admission_decision_ms,
|
||||
(mr.request_observation_json #>> '{scheduling,accountSelectionWaitMs}')::bigint as account_selection_wait_ms,
|
||||
(mr.request_observation_json #>> '{scheduling,capacityUsedSlots}')::bigint as capacity_used_slots,
|
||||
(mr.request_observation_json #>> '{scheduling,capacityTotalSlots}')::bigint as capacity_total_slots,
|
||||
(mr.request_observation_json #>> '{timings,upstream,responseMs}')::bigint as upstream_response_ms
|
||||
) measured;
|
||||
+1
-1
@@ -3058,7 +3058,7 @@ HTTP SSE 请求可能在返回 HTTP 200 后流内失败;WebSocket 已升级时
|
||||
`retryCount` 为额外执行尝试次数之和,`retryRate` 为发生过重试的请求数占该组请求数的比例,同一请求多次重试只计一次
|
||||
|
||||
使用记录列表和错误排查列表的 `accountPlanType` / `accountPlanTypeDisplay` 来自记录保存的账号订阅快照。
|
||||
Antigravity 请求快照只保存套餐 ID,历史记录的展示名为空。
|
||||
Antigravity 的展示名取自请求时已观测到的 Google 套餐描述,快照缺少描述时为 `null`
|
||||
账号维度诊断使用该账号最近请求的订阅快照,并通过 `authenticationKind` 返回同一请求的认证类型快照;未保存的字段为 `null`,非账号维度的认证类型为 `null`
|
||||
|
||||
管理端请求列表及 Dashboard 最近请求中的 `accountNotes` 来自请求保存的账号备注快照,未保存时为 `null`
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"forecastWeeklyMonthlyQuota": "Forecast weekly/monthly quota",
|
||||
"queryUnsupported": "Upstream quota queries are not supported",
|
||||
"quotaDetails": "Quota details",
|
||||
"quotaManagement": "Quota management",
|
||||
"viewDetails": "View {detailTitle} details",
|
||||
"details": "{detailTitle} details",
|
||||
"statisticalMethod": "Statistical method",
|
||||
@@ -551,7 +552,6 @@
|
||||
"weeklyThreshold": "Weekly quota remaining ≤ {percent}%",
|
||||
"minutesInAdvance": "{leadMinutes} min in advance",
|
||||
"nextUse": "Scheduled expiry use: {nextConsumeAtDisplay}",
|
||||
"limitReset": "Limit reset",
|
||||
"confirmLastReset": "Confirm last reset",
|
||||
"confirmResetAmount": "Confirm reset amount",
|
||||
"pendingAction": "View reset credits, an operation is awaiting confirmation",
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"forecastWeeklyMonthlyQuota": "预测周/月额度",
|
||||
"queryUnsupported": "暂不支持查询上游额度",
|
||||
"quotaDetails": "额度详情",
|
||||
"quotaManagement": "额度管理",
|
||||
"viewDetails": "查看{detailTitle}详情",
|
||||
"details": "{detailTitle}详情",
|
||||
"statisticalMethod": "统计方式",
|
||||
@@ -551,7 +552,6 @@
|
||||
"weeklyThreshold": "剩余周额度 ≤ {percent}%",
|
||||
"minutesInAdvance": "提前 {leadMinutes} 分钟",
|
||||
"nextUse": "临期用卡时间 {nextConsumeAtDisplay}",
|
||||
"limitReset": "额度重置",
|
||||
"confirmLastReset": "确认上次重置",
|
||||
"confirmResetAmount": "确认重置额度",
|
||||
"pendingAction": "查看主动重置卡,有一项操作待确认",
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"forecastWeeklyMonthlyQuota": "預測周/月額度",
|
||||
"queryUnsupported": "暫不支持查詢上游額度",
|
||||
"quotaDetails": "額度詳情",
|
||||
"quotaManagement": "額度管理",
|
||||
"viewDetails": "查看{detailTitle}詳情",
|
||||
"details": "{detailTitle}詳情",
|
||||
"statisticalMethod": "統計方式",
|
||||
@@ -551,7 +552,6 @@
|
||||
"weeklyThreshold": "剩餘週額度 ≤ {percent}%",
|
||||
"minutesInAdvance": "提前 {leadMinutes} 分鐘",
|
||||
"nextUse": "臨期用卡時間 {nextConsumeAtDisplay}",
|
||||
"limitReset": "額度重置",
|
||||
"confirmLastReset": "確認上次重置",
|
||||
"confirmResetAmount": "確認重置額度",
|
||||
"pendingAction": "查看主動重置卡,有一項操作待確認",
|
||||
|
||||
@@ -53,7 +53,7 @@ const {
|
||||
|
||||
const modalTitle = computed(() => {
|
||||
if (!confirmation.value)
|
||||
return t('accounts.quotaReset.limitReset')
|
||||
return t('accounts.quota.quotaManagement')
|
||||
return confirmation.value.ambiguous
|
||||
? t('accounts.quotaReset.confirmLastReset')
|
||||
: t('accounts.quotaReset.confirmResetAmount')
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import type { Account } from '@/api'
|
||||
|
||||
import { ZEmpty, ZScrollbar } from '@codex-proxy/ui'
|
||||
import { ZDialog, ZEmpty, ZScrollbar } from '@codex-proxy/ui'
|
||||
|
||||
import { ChartNoAxesCombined, Link2, RefreshCw, UserRound } from '@lucide/vue'
|
||||
import { ChartNoAxesCombined, Link2, RefreshCw, TicketCheck, UserRound } from '@lucide/vue'
|
||||
|
||||
import { computed, shallowRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -12,6 +12,7 @@ import { formatRelativeTime } from '@/utils/relative-time'
|
||||
import { groupedAccountQuotaWindows, orderedPanelQuotaWindows } from '../../constants'
|
||||
import AccountProfileModal from '../account-profile-modal/index.vue'
|
||||
import AccountQuotaForecastModal from '../account-quota-forecast-modal/index.vue'
|
||||
import AccountQuotaCredits from './Credits.vue'
|
||||
import AccountQuotaPanelEntry from './Entry.vue'
|
||||
import QuotaActionButton from './QuotaActionButton.vue'
|
||||
import QuotaSettings from './QuotaSettings.vue'
|
||||
@@ -47,6 +48,7 @@ const quotaEntries = computed(() => {
|
||||
: windows.filter(window => !window.sourceAccountId)
|
||||
return groupedAccountQuotaWindows(orderedPanelQuotaWindows(visibleWindows))
|
||||
})
|
||||
const creditsOpen = shallowRef(false)
|
||||
const profileOpen = shallowRef(false)
|
||||
const forecastOpen = shallowRef(false)
|
||||
const hasPlanBadge = computed(() => Boolean(props.account.planType) || props.account.authenticationKind === 'api_key')
|
||||
@@ -54,7 +56,7 @@ const hasForecast = computed(() => props.account.authenticationKind !== 'api_key
|
||||
const hasPersonalInfo = computed(() => props.account.capabilities.profile || props.account.capabilities.subscription)
|
||||
const needsPeerDiscovery = computed(() => props.account.upstream?.discovered === false)
|
||||
const canRefresh = computed(() => props.account.capabilities.quotaRefresh || props.account.upstream != null)
|
||||
const hasActions = computed(() => hasPersonalInfo.value || hasForecast.value || canRefresh.value || props.account.capabilities.resetCredits)
|
||||
const hasActions = computed(() => hasPersonalInfo.value || hasForecast.value || canRefresh.value || props.account.capabilities.resetCredits || props.account.capabilities.quotaCredits)
|
||||
const lastRefreshed = computed(() => {
|
||||
const { upstream, quota } = props.account
|
||||
if (upstream?.discovered && !upstream.observedAt)
|
||||
@@ -109,6 +111,19 @@ watch(hasPersonalInfo, (available) => {
|
||||
@account-updated="emit('accountUpdated', $event)"
|
||||
@consumed="emit('quotaReset', $event)"
|
||||
/>
|
||||
<template v-else-if="account.capabilities.quotaCredits">
|
||||
<QuotaActionButton
|
||||
:label="t('accounts.quota.quotaPoints')"
|
||||
aria-haspopup="dialog"
|
||||
:aria-pressed="creditsOpen || undefined"
|
||||
@click="creditsOpen = true"
|
||||
>
|
||||
<TicketCheck class="size-3.5" />
|
||||
</QuotaActionButton>
|
||||
<ZDialog v-model="creditsOpen" :title="t('accounts.quota.quotaManagement')" width="36rem">
|
||||
<AccountQuotaCredits :key="account.id" :account="account" @account-updated="emit('accountUpdated', $event)" />
|
||||
</ZDialog>
|
||||
</template>
|
||||
<QuotaActionButton
|
||||
v-if="hasForecast"
|
||||
:label="t('accounts.quota.forecastWeeklyMonthlyQuota')"
|
||||
|
||||
+19
-8
@@ -1,23 +1,34 @@
|
||||
# v3.56.0
|
||||
# v3.56.1
|
||||
|
||||
## 协议变更与升级
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 从 v3.56.0 起,网关移除了原生协议之间的内置转换。Responses、Messages 和 GenAI 请求各走对应的上游。Chat Completions 继续适配这三种上游,支持 JSON 和流式响应。
|
||||
>
|
||||
>做 2API 时,跨协议转换很容易变成长期维护负担。工具调用、流式事件和会话续接各有自己的规则,有些天生就不一致,即使是相当热门的开源项目,当下也正在频繁的遇到转换问题,甚至被拖着迈不动脚。这段时间我就在想,这是不是伪需求,发展线路正不正确,客户端更新新功能,转换逻辑就得跟着修,而且虽然各家推出了各家的协议文档,但是放到客户端上总有差别,甚至要花费海量的精力去处理因此带来的问题,更别提安全性,用钦定平台都会被风控,换一个就更别说了。
|
||||
>
|
||||
>后续我会把精力放在原生透传和链路安全上,尽量去抹平 apikey 接入带来的风险,实现 OAuth 级别的一致,继续把 Chat Completions 到各上游的适配做稳,为什么是 Chat 呢,因为它已经是成熟非变更的协议,而且国内很多客户端也都是走 Chat。
|
||||
>
|
||||
>当然如果有三方 harness 声明支持平台协议,我也很愿意去花费精力去适配少量的协议差错,但是不同的是,这次转变了,不再是网关,而是客户端。
|
||||
>
|
||||
>有特定跨协议需求时,可以通过上游适配插件实现,插件系统完全支持。[上游适配器文档](https://github.com/zyycn/codex-proxy-rs/blob/v3.56.1/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md)
|
||||
|
||||
- 此前用 Responses 调用 Messages API Key 账号的客户端,请切换到 `/v1/messages` 或 `/v1/chat/completions`
|
||||
- Codex 的模型列表只显示当前 Key 能通过 Responses 调用的模型。此前在 Codex 中选用 Antigravity 模型的用户,可切换到原生 GenAI 客户端或 Chat Completions
|
||||
|
||||
## 新增功能
|
||||
|
||||
- Antigravity OAuth 账号可开启自动使用 Google AI 点数,套餐额度耗尽后按上游余额和最低使用门槛继续生成
|
||||
- 中间件可用 `omitBodyAt` 省略指定阶段的请求正文,或用 `websocketErrorCodes` 仅订阅指定的 Responses WebSocket 下行错误
|
||||
|
||||
## 优化改进
|
||||
|
||||
- Chat Completions 直接适配 Responses、Messages 和 GenAI 上游,支持 JSON 和 SSE
|
||||
- Antigravity 原生 GenAI 接口支持 `x-goog-api-key` 传入网关 Client Key,桌面端和 CLI 按 Google 的菜单顺序显示当前 Key 可用的型号
|
||||
- xAI 原生 Responses 请求保留工具、推理参数和上游续接语义
|
||||
|
||||
## 问题修复
|
||||
|
||||
- Antigravity OAuth 账号的额度面板补上「额度点数」入口,可查看 Google AI 点数余额并设置是否自动使用
|
||||
- Codex 压缩请求从 HTTP 进入且无需 WebSocket 时,默认沿用 HTTP/SSE
|
||||
- Antigravity 刷新额度后,账号页使用 Google 返回的套餐描述
|
||||
- Antigravity 的新请求记录恢复显示请求发生时的订阅名称
|
||||
- 管理端与 Client Key 用量明细的思考档位列统一左对齐
|
||||
|
||||
## 升级须知
|
||||
|
||||
- 原生 Responses、Messages 和 GenAI 请求只匹配支持对应协议的上游;此前通过 Responses 调用已导入的 Messages API Key 账号时,请切换到 `/v1/messages` 或 `/v1/chat/completions`
|
||||
- Codex 模型目录只显示当前 Key 可通过 Responses 执行的模型,Antigravity 模型请通过原生 GenAI 客户端或 Chat Completions 调用
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.56.0
|
||||
version: 3.56.1
|
||||
published:
|
||||
'3':
|
||||
stable: 3.55.3
|
||||
rc: 3.55.3
|
||||
beta: 3.55.3
|
||||
alpha: 3.55.3
|
||||
stable: 3.56.0
|
||||
rc: 3.56.0
|
||||
beta: 3.56.0
|
||||
alpha: 3.56.0
|
||||
|
||||
Reference in New Issue
Block a user