mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-03 16:01:22 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99c5864914 | ||
|
|
060b275ce6 | ||
|
|
3c560b9276 | ||
|
|
77c42cea98 | ||
|
|
3eefb8d156 | ||
|
|
dd234c3619 | ||
|
|
df5d50bbf5 | ||
|
|
b5e691c63d | ||
|
|
2d0a52096a | ||
|
|
47620e217a |
Generated
+19
@@ -2708,6 +2708,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rust2"
|
||||
version = "0.26.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7861572250348d13073a9035c6a83f3e583ec9a76a65ce92f338fe1107d8f5"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-sys"
|
||||
version = "0.1.20"
|
||||
@@ -3405,6 +3411,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sevenz-rust2",
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
@@ -4186,6 +4193,18 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sevenz-rust2"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e668242e054ba8b7360918104c30c6685bdedf847909a784cf267d002f40a6a"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"js-sys",
|
||||
"lzma-rust2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
|
||||
@@ -79,7 +79,7 @@ impl Providers {
|
||||
)
|
||||
.await?;
|
||||
environment.host.report_startup_ready("OpenAI Provider");
|
||||
let antigravity = provider_antigravity::initialize(ports.clone())?;
|
||||
let antigravity = provider_antigravity::initialize(ports.clone()).await?;
|
||||
environment
|
||||
.host
|
||||
.report_startup_ready("Antigravity Provider");
|
||||
|
||||
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
self.run_cycle_inner().await;
|
||||
// 中止在途探测,避免把停机当成探测失败而延长冻结
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_cycle_inner())
|
||||
.await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -698,7 +698,7 @@ pub struct PreparedCredentialRotationFacts {
|
||||
pub plan_type: Option<String>,
|
||||
/// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐
|
||||
pub preserve_profile: bool,
|
||||
/// 连接配置变更保留当前凭据健康状态与错误事实
|
||||
/// 凭据或连接配置更新保留提交时的健康状态与错误事实
|
||||
pub preserve_credential_state: bool,
|
||||
pub preserve_access_token_expiry: bool,
|
||||
pub provider_material: ProviderDocument,
|
||||
@@ -722,7 +722,7 @@ impl PreparedCredentialRotation {
|
||||
Self { facts, guard }
|
||||
}
|
||||
|
||||
/// 仅修改连接配置时,不把配置更新视为凭据恢复成功
|
||||
/// 更新本身不能证明账号已恢复时,保留提交时的状态
|
||||
#[must_use]
|
||||
pub fn preserving_credential_state(mut self) -> Self {
|
||||
self.facts.preserve_credential_state = true;
|
||||
|
||||
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.run_due())
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
tokio::select! {
|
||||
() = context.cancellation().cancelled() => {},
|
||||
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
|
||||
}
|
||||
Ok(())
|
||||
.unwrap_or(Ok(()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ResetCreditAutomationTask {
|
||||
async fn run_due(&self) -> Result<(), WorkerTaskError> {
|
||||
let settings = self
|
||||
.settings
|
||||
.load_runtime_settings()
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
|
||||
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
|
||||
let due = self
|
||||
.store
|
||||
.due_reset_credit_automations(Utc::now(), 100)
|
||||
.await
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
|
||||
let work = futures::stream::iter(due)
|
||||
.map(|account_id| async move {
|
||||
let id = ProviderAccountId::new(account_id.clone())
|
||||
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
|
||||
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error_kind = error.kind().as_str(),
|
||||
"自动重置卡任务失败"
|
||||
);
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
|
||||
.collect::<Vec<_>>();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use event_listener::Event;
|
||||
use futures::FutureExt as _;
|
||||
use futures::future::{BoxFuture, pending};
|
||||
use futures_timer::Delay;
|
||||
|
||||
@@ -142,6 +143,14 @@ impl CancellationToken {
|
||||
self.reason().is_some()
|
||||
}
|
||||
|
||||
/// 取消优先于同时就绪的工作,只用于可安全丢弃的 future
|
||||
pub async fn run_until_cancelled<T>(&self, work: impl Future<Output = T>) -> Option<T> {
|
||||
futures::select_biased! {
|
||||
() = self.cancelled().fuse() => None,
|
||||
result = work.fuse() => Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cancelled(&self) {
|
||||
if self.is_cancelled() {
|
||||
return;
|
||||
|
||||
@@ -399,14 +399,13 @@ struct RuntimeSnapshotReconciliationTask {
|
||||
}
|
||||
|
||||
impl ScheduledTask for RuntimeSnapshotReconciliationTask {
|
||||
fn run_cycle(
|
||||
&self,
|
||||
_context: WorkerCycleContext,
|
||||
) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
self.publisher
|
||||
.refresh_with_mode(RefreshMode::Reconcile)
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.publisher.refresh_with_mode(RefreshMode::Reconcile))
|
||||
.await
|
||||
.transpose()
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("runtime snapshot reconciliation failed")
|
||||
@@ -430,10 +429,12 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
||||
let cancellation = context.cancellation();
|
||||
let mut retry_delay = INITIAL_BACKOFF;
|
||||
loop {
|
||||
if cancellation.is_cancelled() {
|
||||
let Some(subscription) = cancellation
|
||||
.run_until_cancelled(self.subscriptions.subscribe_snapshot_revisions())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
}
|
||||
let subscription = self.subscriptions.subscribe_snapshot_revisions().await;
|
||||
};
|
||||
let mut subscription = match subscription {
|
||||
Ok(subscription) => {
|
||||
retry_delay = INITIAL_BACKOFF;
|
||||
@@ -456,7 +457,13 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
|
||||
};
|
||||
match notified {
|
||||
Some(Ok(_)) => {
|
||||
let _ = self.publisher.refresh().await;
|
||||
if cancellation
|
||||
.run_until_cancelled(self.publisher.refresh())
|
||||
.await
|
||||
.is_none()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Some(Err(_)) | None => break,
|
||||
}
|
||||
|
||||
@@ -122,11 +122,12 @@ impl WorkerSupervisor {
|
||||
health: &self.health,
|
||||
};
|
||||
let deadline = tokio::time::Instant::now() + timeout;
|
||||
for (_, handle) in &mut shutdown.handles {
|
||||
for (worker, handle) in &mut shutdown.handles {
|
||||
if tokio::time::timeout_at(deadline, &mut *handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(target: "gateway_shutdown", %worker, "后台任务收尾超时,强制终止");
|
||||
handle.abort();
|
||||
let _ = handle.await;
|
||||
}
|
||||
@@ -459,6 +460,7 @@ async fn acquire_and_run(
|
||||
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
|
||||
tokio::pin!(acquisition);
|
||||
let acquisition = tokio::select! {
|
||||
biased;
|
||||
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
|
||||
acquisition = &mut acquisition => acquisition,
|
||||
};
|
||||
@@ -490,12 +492,13 @@ async fn run_local_cycle(
|
||||
.catch_unwind();
|
||||
tokio::pin!(cycle);
|
||||
tokio::select! {
|
||||
outcome = &mut cycle => task_result(outcome),
|
||||
biased;
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
ScheduledOutcome::ShuttingDown
|
||||
}
|
||||
outcome = &mut cycle => task_result(outcome),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,17 +530,21 @@ async fn run_leased_cycle(
|
||||
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
result = &mut cycle => break task_result(result),
|
||||
biased;
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
break ScheduledOutcome::ShuttingDown;
|
||||
}
|
||||
result = &mut cycle => break task_result(result),
|
||||
() = &mut renewal => {
|
||||
let renewed = renew_guard(
|
||||
let Some(renewed) = cancellation.run_until_cancelled(renew_guard(
|
||||
guard.as_mut(),
|
||||
schedule.leader_lease_renewal_interval(),
|
||||
).await;
|
||||
)).await else {
|
||||
// 返回循环首个取消分支,统一等待正在执行的周期收尾
|
||||
continue;
|
||||
};
|
||||
if let Err(error) = renewed {
|
||||
cycle_cancel.cancel();
|
||||
let _ = cycle.await;
|
||||
|
||||
@@ -219,6 +219,7 @@ enum LeaseStep {
|
||||
enum RenewStep {
|
||||
Success,
|
||||
Error,
|
||||
Pending,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -268,11 +269,12 @@ impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
|
||||
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
|
||||
Box::pin(async move {
|
||||
lock_unpoisoned(&self.renewals).push(self.worker.clone());
|
||||
match lock_unpoisoned(&self.renew_scripts)
|
||||
let step = lock_unpoisoned(&self.renew_scripts)
|
||||
.get_mut(&self.worker)
|
||||
.and_then(VecDeque::pop_front)
|
||||
.unwrap_or(RenewStep::Success)
|
||||
{
|
||||
.unwrap_or(RenewStep::Success);
|
||||
match step {
|
||||
RenewStep::Pending => pending().await,
|
||||
RenewStep::Success => Ok(()),
|
||||
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
|
||||
}
|
||||
@@ -510,6 +512,31 @@ async fn long_cycle_renews_leader_lease_before_ttl() {
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn shutdown_signals_the_cycle_while_lease_renewal_is_pending() {
|
||||
let leases = Arc::new(FakeLeasePort::default());
|
||||
leases.renew_script(target_worker(), [RenewStep::Pending]);
|
||||
let task = CancellationTask {
|
||||
entered: Arc::new(AtomicUsize::new(0)),
|
||||
observed: Arc::new(AtomicUsize::new(0)),
|
||||
};
|
||||
let supervisor = supervisor();
|
||||
supervisor
|
||||
.start(
|
||||
target_plan(task.clone(), renewal_schedule()),
|
||||
leases.clone(),
|
||||
Arc::new(RecordingDiagnostics::default()),
|
||||
)
|
||||
.unwrap();
|
||||
yield_until(|| task.entered.load(Ordering::SeqCst) != 0).await;
|
||||
tokio::time::advance(Duration::from_millis(10)).await;
|
||||
yield_until(|| leases.renewal_count(&target_worker()) == 1).await;
|
||||
// 关闭预算短于续租超时,协作取消仍应完成
|
||||
supervisor.shutdown(Duration::from_millis(1)).await;
|
||||
assert_eq!(task.observed.load(Ordering::SeqCst), 1);
|
||||
assert!(lock_unpoisoned(&leases.active_guards).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
|
||||
let task = ConcurrentCycleTask {
|
||||
|
||||
@@ -240,18 +240,21 @@ pub(crate) struct StaleModelRequestRecoveryTask {
|
||||
impl ScheduledTask for StaleModelRequestRecoveryTask {
|
||||
fn run_cycle(
|
||||
&self,
|
||||
_context: WorkerCycleContext,
|
||||
context: WorkerCycleContext,
|
||||
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
gateway_core::engine::ExecutionStore::recover_expired(
|
||||
self.execution.as_ref(),
|
||||
SystemTime::now(),
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("stale request recovery failed").with_source(source)
|
||||
})
|
||||
context
|
||||
.cancellation()
|
||||
.run_until_cancelled(gateway_core::engine::ExecutionStore::recover_expired(
|
||||
self.execution.as_ref(),
|
||||
SystemTime::now(),
|
||||
))
|
||||
.await
|
||||
.transpose()
|
||||
.map(|_| ())
|
||||
.map_err(|source| {
|
||||
WorkerTaskError::safe("stale request recovery failed").with_source(source)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ http-body-util = "0.1.5"
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["json", "rustls-tls-native-roots", "socks", "stream"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["raw_value"] }
|
||||
sevenz-rust2 = { version = "0.27.0", default-features = false }
|
||||
sha2 = "0.11.0"
|
||||
tar = { version = "0.4.46", default-features = false }
|
||||
tempfile = "3.27.0"
|
||||
@@ -39,6 +40,7 @@ uuid = { version = "1.23.3", features = ["v7"] }
|
||||
zip = { version = "9.8.0", default-features = false, features = ["deflate-flate2"] }
|
||||
|
||||
[dev-dependencies]
|
||||
sevenz-rust2 = { version = "0.27.0", default-features = false, features = ["compress"] }
|
||||
wiremock = "0.6.5"
|
||||
tokio = { version = "=1.53.3", features = ["rt-multi-thread"] }
|
||||
|
||||
|
||||
@@ -308,6 +308,18 @@ impl CatalogService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !refresh
|
||||
&& matches!(
|
||||
current.account.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
)
|
||||
{
|
||||
return Ok(ProviderModels {
|
||||
models: Vec::new(),
|
||||
observed_at: None,
|
||||
});
|
||||
}
|
||||
if current.account.authentication_kind() == super::api_key::API_KEY {
|
||||
let material = super::api_key::ApiKeyMaterial::load(¤t)?;
|
||||
let client = crate::transport::GenAiClient::new(
|
||||
@@ -316,7 +328,12 @@ impl CatalogService {
|
||||
)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client.catalog(&material.api_key).await.map_err(|e| {
|
||||
let result = client.catalog(&material.api_key).await;
|
||||
if let Err(failure) = &result {
|
||||
super::record_account_failure(self.accounts.as_ref(), ¤t.account, failure)
|
||||
.await;
|
||||
}
|
||||
let catalog = result.map_err(|e| {
|
||||
error(AdminKind::Unavailable)
|
||||
.with_public_message("GenAI 模型目录查询失败")
|
||||
.with_source(e)
|
||||
@@ -333,15 +350,16 @@ impl CatalogService {
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client
|
||||
.catalog(&material.access_token)
|
||||
.await
|
||||
.map_err(|e| match e.kind() {
|
||||
Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e),
|
||||
_ => error(AdminKind::Unavailable)
|
||||
.with_public_message("Antigravity 项目或模型目录查询失败")
|
||||
.with_source(e),
|
||||
})?;
|
||||
let result = client.catalog(&material.access_token).await;
|
||||
if let Err(error) = &result {
|
||||
super::record_account_failure(self.accounts.as_ref(), ¤t.account, error).await;
|
||||
}
|
||||
let catalog = result.map_err(|e| match e.kind() {
|
||||
Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e),
|
||||
_ => error(AdminKind::Unavailable)
|
||||
.with_public_message("Antigravity 项目或模型目录查询失败")
|
||||
.with_source(e),
|
||||
})?;
|
||||
self.publish(
|
||||
¤t.account,
|
||||
current.account.plan_type().map(str::to_owned),
|
||||
@@ -452,6 +470,13 @@ impl CatalogService {
|
||||
&self,
|
||||
cancellation: &gateway_core::lifecycle::CancellationToken,
|
||||
) -> Result<(), gateway_core::task::WorkerTaskError> {
|
||||
cancellation
|
||||
.run_until_cancelled(self.refresh_due_accounts())
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
async fn refresh_due_accounts(&self) -> Result<(), gateway_core::task::WorkerTaskError> {
|
||||
use futures::{StreamExt, stream};
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
let catalogs = self
|
||||
@@ -469,7 +494,11 @@ impl CatalogService {
|
||||
.await
|
||||
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
|
||||
due.retain(|account| {
|
||||
matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||
!matches!(
|
||||
account.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
) && matches!(account.authentication_kind(), "oauth" | "api_key")
|
||||
&& observations.get(account.id()).is_none_or(|observation| {
|
||||
observation.revision != account.revision()
|
||||
|| observation.observed_at.elapsed().unwrap_or_default()
|
||||
@@ -484,9 +513,9 @@ impl CatalogService {
|
||||
let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len();
|
||||
due.rotate_left(offset);
|
||||
due.truncate(32);
|
||||
let mut updates=stream::iter(due).map(|account|async move {
|
||||
tokio::select! {biased;_=cancellation.cancelled()=>Ok(()),result=self.account_models(account.id(),true)=>result.map(|_|())}
|
||||
}).buffer_unordered(4);
|
||||
let mut updates = stream::iter(due)
|
||||
.map(|account| async move { self.account_models(account.id(), true).await })
|
||||
.buffer_unordered(4);
|
||||
let mut first_error = None;
|
||||
while let Some(result) = updates.next().await {
|
||||
if let Err(error) = result
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! 资源服务的明确拒绝更新账号访问状态,普通授权失败只触发 AT 续期
|
||||
|
||||
use crate::transport::{AccountRejection, account_rejection};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountErrorReason, AccountStateChange, CredentialState, ProviderAccount,
|
||||
ProviderAccountStore,
|
||||
},
|
||||
error::{ProviderError, ProviderErrorKind, StoreError},
|
||||
upstream::UpstreamSendState,
|
||||
};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
pub(crate) async fn record_account_failure(
|
||||
accounts: &dyn ProviderAccountStore,
|
||||
account: &ProviderAccount,
|
||||
error: &ProviderError,
|
||||
) {
|
||||
if error.send_state() != UpstreamSendState::Sent {
|
||||
return;
|
||||
}
|
||||
let state = match account_rejection(error) {
|
||||
Some(AccountRejection::VerificationRequired) => Some((
|
||||
CredentialState::Invalid,
|
||||
AccountErrorReason::AccountUnverified,
|
||||
"Google 要求验证账号,完成验证后恢复账号状态",
|
||||
)),
|
||||
Some(AccountRejection::Banned) => Some((
|
||||
CredentialState::Banned,
|
||||
AccountErrorReason::AccountBanned,
|
||||
"Google 已停用账号",
|
||||
)),
|
||||
None if error.kind() == ProviderErrorKind::Unauthorized
|
||||
&& account.authentication_kind() == super::api_key::API_KEY =>
|
||||
{
|
||||
Some((
|
||||
CredentialState::Invalid,
|
||||
AccountErrorReason::CredentialInvalid,
|
||||
"上游拒绝 API Key",
|
||||
))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let feedback = async {
|
||||
if let Some((credential_state, error_reason, message)) = state {
|
||||
accounts
|
||||
.apply_state_change(AccountStateChange {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
credential_state,
|
||||
observed_at: SystemTime::now(),
|
||||
error_reason: Some(error_reason),
|
||||
message: Some(message.into()),
|
||||
})
|
||||
.await?;
|
||||
} else if error.kind() == ProviderErrorKind::Unauthorized {
|
||||
// 资源服务拒绝 AT 不能证明 RT 失效,续期由 OAuth worker 负责
|
||||
accounts
|
||||
.expire_access_token(account, SystemTime::now())
|
||||
.await?;
|
||||
}
|
||||
Ok::<_, StoreError>(())
|
||||
};
|
||||
if !matches!(
|
||||
tokio::time::timeout(Duration::from_millis(100), feedback).await,
|
||||
Ok(Ok(()))
|
||||
) {
|
||||
tracing::warn!("Antigravity 账号失败反馈未能写入共享状态");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ pub(crate) mod api_key;
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
mod failure;
|
||||
pub(crate) use failure::record_account_failure;
|
||||
mod model_groups;
|
||||
pub(crate) mod oauth;
|
||||
pub(crate) mod quota;
|
||||
|
||||
@@ -175,15 +175,20 @@ impl QuotaService {
|
||||
.map_err(upstream)?;
|
||||
// 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照
|
||||
let observed_at = SystemTime::now();
|
||||
let info = client
|
||||
.account_info(&material.access_token)
|
||||
.await
|
||||
.map_err(upstream)?;
|
||||
let (catalog, summary) = tokio::try_join!(
|
||||
client.catalog_for_project(&material.access_token, info.project.clone()),
|
||||
client.quota_summary(&material.access_token, &info.project),
|
||||
)
|
||||
.map_err(upstream)?;
|
||||
let result = async {
|
||||
let info = client.account_info(&material.access_token).await?;
|
||||
let (catalog, summary) = tokio::try_join!(
|
||||
client.catalog_for_project(&material.access_token, info.project.clone()),
|
||||
client.quota_summary(&material.access_token, &info.project),
|
||||
)?;
|
||||
Ok::<_, gateway_core::error::ProviderError>((info, catalog, summary))
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = &result {
|
||||
super::super::record_account_failure(self.accounts.as_ref(), ¤t.account, error)
|
||||
.await;
|
||||
}
|
||||
let (info, catalog, summary) = result.map_err(upstream)?;
|
||||
let (tier, plan_description) = match info.paid_tier {
|
||||
Some(paid) => (Some(paid.tier), paid.description),
|
||||
None => (info.current_tier, None),
|
||||
@@ -298,6 +303,13 @@ impl QuotaService {
|
||||
&self,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
cancel
|
||||
.run_until_cancelled(self.refresh_due_accounts())
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
async fn refresh_due_accounts(&self) -> Result<(), WorkerTaskError> {
|
||||
let accounts = self
|
||||
.accounts
|
||||
.list_for_provider(&self.kind, false)
|
||||
@@ -317,10 +329,15 @@ impl QuotaService {
|
||||
let stale_before = now - interval;
|
||||
let mut due = Vec::new();
|
||||
let mut stale = Vec::new();
|
||||
for account in accounts
|
||||
.iter()
|
||||
.filter(|a| a.enabled() && a.authentication_kind() == "oauth")
|
||||
{
|
||||
for account in accounts.iter().filter(|a| {
|
||||
a.enabled()
|
||||
&& a.authentication_kind() == "oauth"
|
||||
&& !matches!(
|
||||
a.credential_state(),
|
||||
gateway_core::account::CredentialState::Invalid
|
||||
| gateway_core::account::CredentialState::Banned
|
||||
)
|
||||
}) {
|
||||
let snapshot = observations
|
||||
.remove(account.id())
|
||||
.filter(|s| s.credential_revision == account.revision());
|
||||
@@ -355,13 +372,7 @@ impl QuotaService {
|
||||
due.rotate_left(offset);
|
||||
due.truncate(32);
|
||||
let mut results = stream::iter(due)
|
||||
.map(|id| async move {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Ok(()),
|
||||
result = self.refresh(&id) => result,
|
||||
}
|
||||
})
|
||||
.map(|id| async move { self.refresh(&id).await })
|
||||
.buffer_unordered(4);
|
||||
while let Some(result) = results.next().await {
|
||||
if let Err(e) = result
|
||||
|
||||
@@ -4,8 +4,8 @@ use super::{oauth::error, service::CredentialService};
|
||||
use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, CredentialState,
|
||||
LoadedCredential, PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery,
|
||||
CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, LoadedCredential,
|
||||
PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery,
|
||||
},
|
||||
provider_ports::provider_refresh_backoff_at,
|
||||
task::WorkerTaskError,
|
||||
@@ -79,8 +79,8 @@ impl CredentialService {
|
||||
material,
|
||||
facts.access_token_expires_at.map(Into::into),
|
||||
None,
|
||||
)?
|
||||
.with_account_state(CredentialState::Ready, SystemTime::now(), None, None);
|
||||
)?;
|
||||
// AT 续期不证明资源服务已解除验证或封禁,提交时保留当前账号访问状态
|
||||
match self
|
||||
.accounts
|
||||
.compare_and_swap_credential(record)
|
||||
|
||||
@@ -304,6 +304,7 @@ impl CredentialService {
|
||||
Ok(grant) => grant,
|
||||
};
|
||||
self.rotation(¤t.account, grant, guards)
|
||||
.map(PreparedCredentialRotation::preserving_credential_state)
|
||||
}
|
||||
|
||||
pub(super) fn rotation(
|
||||
|
||||
@@ -15,11 +15,12 @@ use std::sync::Arc;
|
||||
#[error("Antigravity Provider 初始化失败")]
|
||||
pub struct ConfigError;
|
||||
|
||||
pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
|
||||
pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
|
||||
let kind = ProviderKind::new("antigravity").map_err(|_| ConfigError)?;
|
||||
let oauth = Arc::new(credential::GoogleOAuth::for_provider()?);
|
||||
let origin = oauth.resource_origin().clone();
|
||||
let release = Arc::new(profile::ReleaseService::new(ports.artifact_profiles())?);
|
||||
release.restore().await;
|
||||
let credentials = Arc::new(credential::CredentialService::new(
|
||||
kind.clone(),
|
||||
&ports,
|
||||
|
||||
@@ -20,12 +20,12 @@ impl Drop for ParseGuard {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CancellableFile {
|
||||
file: std::fs::File,
|
||||
pub(crate) struct CancellableFile<R = std::fs::File> {
|
||||
file: R,
|
||||
cancellation: CancellationToken,
|
||||
}
|
||||
impl CancellableFile {
|
||||
pub(crate) fn new(file: std::fs::File) -> (Self, ParseGuard) {
|
||||
impl<R> CancellableFile<R> {
|
||||
pub(crate) fn new(file: R) -> (Self, ParseGuard) {
|
||||
let cancellation = CancellationToken::new();
|
||||
(
|
||||
Self {
|
||||
@@ -36,7 +36,7 @@ impl CancellableFile {
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Read for CancellableFile {
|
||||
impl<R: Read> Read for CancellableFile<R> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(io::Error::other("制品解析已取消"));
|
||||
@@ -44,6 +44,14 @@ impl Read for CancellableFile {
|
||||
self.file.read(buffer)
|
||||
}
|
||||
}
|
||||
impl<R: Seek> Seek for CancellableFile<R> {
|
||||
fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(io::Error::other("制品解析已取消"));
|
||||
}
|
||||
self.file.seek(from)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn invalid() -> WorkerTaskError {
|
||||
WorkerTaskError::safe("Antigravity 发布包核验失败")
|
||||
@@ -131,10 +139,6 @@ impl<'a> RemoteArtifact<'a> {
|
||||
}
|
||||
Ok(body.into())
|
||||
}
|
||||
|
||||
pub(crate) async fn prefix(&self, maximum: u64) -> Result<Bytes, WorkerTaskError> {
|
||||
self.read(0, self.size.min(maximum)).await
|
||||
}
|
||||
}
|
||||
|
||||
/// 只缓存目录和所需条目,未下载的区间不能被当作零填充数据读取
|
||||
@@ -189,7 +193,7 @@ impl<'a> RemoteZip<'a> {
|
||||
|
||||
fn archive(
|
||||
&self,
|
||||
member: Option<(u64, Bytes)>,
|
||||
member: Vec<(u64, Bytes)>,
|
||||
) -> Result<zip::ZipArchive<Segments>, WorkerTaskError> {
|
||||
let mut chunks = vec![(
|
||||
self.artifact.size - self.tail.len() as u64,
|
||||
@@ -209,12 +213,22 @@ impl<'a> RemoteZip<'a> {
|
||||
name: &str,
|
||||
maximum: usize,
|
||||
) -> Result<Vec<u8>, WorkerTaskError> {
|
||||
let archive = self.archive(None)?;
|
||||
self.inspect(name, maximum as u64, move |reader| bounded(reader, maximum))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn inspect<T: Send + 'static>(
|
||||
&self,
|
||||
name: &str,
|
||||
maximum: u64,
|
||||
inspect: impl FnOnce(&mut dyn Read) -> Result<T, WorkerTaskError> + Send + 'static,
|
||||
) -> Result<T, WorkerTaskError> {
|
||||
let archive = self.archive(Vec::new())?;
|
||||
let index = archive.index_for_name(name).ok_or_else(invalid)?;
|
||||
let entry = archive
|
||||
.by_index_data(index)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
if entry.size() > maximum as u64 || entry.is_dir() || entry.is_symlink() {
|
||||
if entry.size() > maximum || entry.is_dir() || entry.is_symlink() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let start = entry.header_start();
|
||||
@@ -224,12 +238,25 @@ impl<'a> RemoteZip<'a> {
|
||||
.checked_add(30 + 2 * u64::from(u16::MAX))
|
||||
.ok_or_else(invalid)?
|
||||
.min(self.artifact.size.checked_sub(start).ok_or_else(invalid)?);
|
||||
let member = self.artifact.read(start, length).await?;
|
||||
let mut archive = self.archive(Some((start, member)))?;
|
||||
let file = archive
|
||||
.by_name(name)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
bounded(file, maximum)
|
||||
let mut members = Vec::new();
|
||||
let mut offset = start;
|
||||
while offset < start + length {
|
||||
let length = (start + length - offset).min(MAX_RANGE_BYTES);
|
||||
members.push((offset, self.artifact.read(offset, length).await?));
|
||||
offset += length;
|
||||
}
|
||||
let archive = self.archive(members)?;
|
||||
let (reader, _guard) = CancellableFile::new(archive.into_inner());
|
||||
let name = name.to_owned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut archive = zip::ZipArchive::new(reader).map_err(|e| invalid().with_source(e))?;
|
||||
let mut file = archive
|
||||
.by_name(&name)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
inspect(&mut file)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| invalid().with_source(e))?
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 从官方发布包核对版本和目标平台,不执行下载的程序或发起模型请求
|
||||
|
||||
use super::archive::{CancellableFile, RemoteArtifact, RemoteZip, bounded, download, invalid};
|
||||
use super::archive::{CancellableFile, RemoteZip, bounded, download, invalid};
|
||||
use super::selection::{Architecture, ClientKind, Platform, ReleaseTarget};
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
use std::io::Read;
|
||||
@@ -14,8 +14,8 @@ pub(crate) struct Release {
|
||||
pub(crate) sha512: Option<String>,
|
||||
}
|
||||
|
||||
const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
|
||||
pub(super) const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024;
|
||||
pub(super) const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
pub(crate) async fn verify(
|
||||
client: &reqwest::Client,
|
||||
@@ -23,7 +23,7 @@ pub(crate) async fn verify(
|
||||
version: &str,
|
||||
url: &str,
|
||||
sha512: Option<&str>,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
match (target.client, target.platform) {
|
||||
(ClientKind::Desktop, Platform::Macos) => {
|
||||
let url = url.strip_suffix(".dmg").ok_or_else(invalid)?;
|
||||
@@ -40,14 +40,14 @@ pub(crate) async fn verify(
|
||||
let executable = archive
|
||||
.read("Antigravity.app/Contents/MacOS/Antigravity", 1024 * 1024)
|
||||
.await?;
|
||||
architecture(&executable, target)
|
||||
}
|
||||
(ClientKind::Desktop, Platform::Windows) => {
|
||||
let artifact = RemoteArtifact::open(client, url.to_owned()).await?;
|
||||
let header = artifact.prefix(1024 * 1024).await?;
|
||||
let (offset, size) = pe_resources(&header)?;
|
||||
let resources = artifact.read(offset, size).await?;
|
||||
windows_version(&resources, version)
|
||||
architecture(&executable, target)?;
|
||||
archive
|
||||
.inspect(
|
||||
"Antigravity.app/Contents/Resources/bin/language_server",
|
||||
MAX_BINARY_BYTES,
|
||||
move |reader| verify_binary(reader, target, None),
|
||||
)
|
||||
.await
|
||||
}
|
||||
_ => {
|
||||
let file = download(client, url, sha512).await?;
|
||||
@@ -55,8 +55,12 @@ pub(crate) async fn verify(
|
||||
let (file, _guard) = CancellableFile::new(file);
|
||||
let version = version.to_owned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if target.client == ClientKind::Cli && target.platform == Platform::Windows {
|
||||
verify_binary(file, target, &version)
|
||||
if target.platform == Platform::Windows {
|
||||
if target.client == ClientKind::Cli {
|
||||
verify_binary(file, target, Some(&version))
|
||||
} else {
|
||||
super::installer::verify(file, target, &version)
|
||||
}
|
||||
} else {
|
||||
verify_tar(file, target, &version)
|
||||
}
|
||||
@@ -124,11 +128,12 @@ pub(crate) fn verify_tar(
|
||||
file: impl Read,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let decoder = flate2::read::GzDecoder::new(file);
|
||||
let mut archive = tar::Archive::new(decoder.take(2 * 1024 * 1024 * 1024));
|
||||
let mut found_version = false;
|
||||
let mut found_executable = false;
|
||||
let mut changelist = None;
|
||||
for (index, entry) in archive
|
||||
.entries()
|
||||
.map_err(|e| invalid().with_source(e))?
|
||||
@@ -153,7 +158,7 @@ pub(crate) fn verify_tar(
|
||||
if found_executable || entry.size() > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
verify_binary(&mut entry, target, version)?;
|
||||
changelist = Some(verify_binary(&mut entry, target, Some(version))?);
|
||||
found_version = true;
|
||||
found_executable = true;
|
||||
} else if target.client == ClientKind::Desktop {
|
||||
@@ -163,6 +168,11 @@ pub(crate) fn verify_tar(
|
||||
return Err(invalid());
|
||||
}
|
||||
found_version = true;
|
||||
} else if path.ends_with("resources/bin/language_server") {
|
||||
if changelist.is_some() || entry.size() > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(verify_binary(&mut entry, target, None)?);
|
||||
} else if name == "antigravity" {
|
||||
if found_executable {
|
||||
return Err(invalid());
|
||||
@@ -177,7 +187,7 @@ pub(crate) fn verify_tar(
|
||||
}
|
||||
}
|
||||
if found_version && found_executable {
|
||||
Ok(())
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
@@ -186,24 +196,54 @@ pub(crate) fn verify_tar(
|
||||
pub(crate) fn verify_binary(
|
||||
mut reader: impl Read,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
version: Option<&str>,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let mut header = [0; 1024];
|
||||
reader
|
||||
.read_exact(&mut header)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
architecture(&header, target)?;
|
||||
// 官方 CLI 把版本文件嵌入 Go 制品,保留其换行与终止字节避免匹配依赖版本
|
||||
let marker = format!("\0{version}\n\0").into_bytes();
|
||||
let marker = version.map(|version| format!("\0{version}\n\0").into_bytes());
|
||||
// Go 制品的源码根目录携带实际 CL;发布目录编号、依赖版本不能代替这个值
|
||||
const PREFIX: &[u8] = b"googlefile:/google_src/files/";
|
||||
const SUFFIX: &[u8] = b"/depot/";
|
||||
let overlap = marker
|
||||
.as_ref()
|
||||
.map_or(0, Vec::len)
|
||||
.max(PREFIX.len() + 20 + SUFFIX.len());
|
||||
let mut tail = header.to_vec();
|
||||
let mut chunk = [0; 64 * 1024];
|
||||
let mut count = 1024u64;
|
||||
let mut found = false;
|
||||
let mut found = marker.is_none();
|
||||
let mut changelist = None;
|
||||
loop {
|
||||
if tail.windows(marker.len()).any(|v| v == marker) {
|
||||
if marker
|
||||
.as_ref()
|
||||
.is_some_and(|marker| tail.windows(marker.len()).any(|v| v == marker))
|
||||
{
|
||||
found = true;
|
||||
}
|
||||
let keep = tail.len().saturating_sub(marker.len());
|
||||
for (offset, candidate) in tail.windows(PREFIX.len()).enumerate() {
|
||||
if candidate != PREFIX {
|
||||
continue;
|
||||
}
|
||||
let rest = &tail[offset + PREFIX.len()..];
|
||||
let digits = rest.iter().take_while(|c| c.is_ascii_digit()).count();
|
||||
if !rest[digits..].starts_with(SUFFIX) {
|
||||
continue;
|
||||
}
|
||||
let value = std::str::from_utf8(&rest[..digits])
|
||||
.ok()
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
.filter(|value| *value > 0)
|
||||
.ok_or_else(invalid)?;
|
||||
if changelist.is_some_and(|previous| previous != value) {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(value);
|
||||
}
|
||||
let keep = tail.len().saturating_sub(overlap);
|
||||
tail.drain(..keep);
|
||||
let size = reader
|
||||
.read(&mut chunk)
|
||||
@@ -217,7 +257,11 @@ pub(crate) fn verify_binary(
|
||||
}
|
||||
tail.extend_from_slice(&chunk[..size]);
|
||||
}
|
||||
if found { Ok(()) } else { Err(invalid()) }
|
||||
if found {
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
}
|
||||
|
||||
fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
|
||||
@@ -231,52 +275,6 @@ fn pe_offset(body: &[u8]) -> Result<usize, WorkerTaskError> {
|
||||
Ok(offset)
|
||||
}
|
||||
|
||||
pub(crate) fn pe_resources(body: &[u8]) -> Result<(u64, u64), WorkerTaskError> {
|
||||
let pe = pe_offset(body)?;
|
||||
let count = u16_at(body, pe + 6)? as usize;
|
||||
let start = pe + 24 + u16_at(body, pe + 20)? as usize;
|
||||
for i in 0..count.min(96) {
|
||||
let section = start + i * 40;
|
||||
if body.get(section..section + 8) == Some(b".rsrc\0\0\0") {
|
||||
return Ok((
|
||||
u64::from(u32_at(body, section + 20)?),
|
||||
u64::from(u32_at(body, section + 16)?),
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(invalid())
|
||||
}
|
||||
|
||||
pub(crate) fn windows_version(body: &[u8], version: &str) -> Result<(), WorkerTaskError> {
|
||||
let parts: Vec<u16> = version
|
||||
.split('.')
|
||||
.map(str::parse)
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|_| invalid())?;
|
||||
if parts.len() != 3 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let high = u32::from(parts[0]) << 16 | u32::from(parts[1]);
|
||||
let low = u32::from(parts[2]) << 16;
|
||||
let mut found = false;
|
||||
for (offset, bytes) in body.windows(8).enumerate() {
|
||||
// 官方 Windows 安装器的 dwStrucVersion 为零,也接受标准的 0x00010000
|
||||
if bytes.starts_with(b"\xbd\x04\xef\xfe")
|
||||
&& matches!(u32_at(body, offset + 4)?, 0 | 0x0001_0000)
|
||||
{
|
||||
if u32_at(body, offset + 8)? != high
|
||||
|| u32_at(body, offset + 12)? != low
|
||||
|| u32_at(body, offset + 16)? != high
|
||||
|| u32_at(body, offset + 20)? != low
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if found { Ok(()) } else { Err(invalid()) }
|
||||
}
|
||||
|
||||
fn u16_at(body: &[u8], offset: usize) -> Result<u16, WorkerTaskError> {
|
||||
Ok(u16::from_le_bytes(
|
||||
body.get(offset..offset + 2)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! 读取 Windows 安装器内的 7z 应用包,将版本与 language server 的 CL 绑定核验
|
||||
|
||||
use super::archive::{bounded, invalid};
|
||||
use super::artifact::{MAX_ASAR_BYTES, MAX_BINARY_BYTES, asar_version, verify_binary};
|
||||
use super::selection::ReleaseTarget;
|
||||
use gateway_core::task::WorkerTaskError;
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
|
||||
pub(crate) fn verify(
|
||||
mut file: impl Read + Seek,
|
||||
target: ReleaseTarget,
|
||||
version: &str,
|
||||
) -> Result<u64, WorkerTaskError> {
|
||||
let mut prefix = Vec::new();
|
||||
file.by_ref()
|
||||
.take(2 * 1024 * 1024)
|
||||
.read_to_end(&mut prefix)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let start = prefix
|
||||
.windows(8)
|
||||
.position(|bytes| bytes == b"7z\xbc\xaf\x27\x1c\0\x04")
|
||||
.ok_or_else(invalid)? as u64;
|
||||
file.seek(SeekFrom::Start(start))
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
let source = Payload { file, start };
|
||||
let mut archive = sevenz_rust2::ArchiveReader::new_with_memory_limit(
|
||||
source,
|
||||
sevenz_rust2::Password::empty(),
|
||||
// 官方 NSIS 应用包使用 256 MiB 字典,另预留 1 MiB 解码状态,线程限制为一个
|
||||
257 * 1024,
|
||||
)
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
archive.set_thread_count(1);
|
||||
let files = &archive.archive().files;
|
||||
if files.len() > 16_384
|
||||
|| files
|
||||
.iter()
|
||||
.try_fold(0u64, |sum, file| sum.checked_add(file.size))
|
||||
.is_none_or(|size| size > 2 * 1024 * 1024 * 1024)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut found_version = false;
|
||||
let mut changelist = None;
|
||||
archive
|
||||
.for_each_entries(|entry, reader| {
|
||||
let result = (|| {
|
||||
if entry.is_directory || entry.is_anti_item {
|
||||
return Ok(());
|
||||
}
|
||||
match entry.name.as_str() {
|
||||
"resources/app.asar" => {
|
||||
if found_version
|
||||
|| entry.size > MAX_ASAR_BYTES as u64
|
||||
|| asar_version(&bounded(reader, MAX_ASAR_BYTES)?)? != version
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
found_version = true;
|
||||
}
|
||||
"resources/bin/language_server.exe" => {
|
||||
if changelist.is_some() || entry.size > MAX_BINARY_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
changelist = Some(verify_binary(reader, target, None)?);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
result.map_err(|_| {
|
||||
sevenz_rust2::Error::Other("Antigravity Windows 制品内容无效".into())
|
||||
})?;
|
||||
Ok(true)
|
||||
})
|
||||
.map_err(|e| invalid().with_source(e))?;
|
||||
if found_version {
|
||||
changelist.ok_or_else(invalid)
|
||||
} else {
|
||||
Err(invalid())
|
||||
}
|
||||
}
|
||||
|
||||
/// 安装器前缀不属于 7z,解码器的偏移必须以实际签名为零点
|
||||
struct Payload<R> {
|
||||
file: R,
|
||||
start: u64,
|
||||
}
|
||||
impl<R: Read> Read for Payload<R> {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||
self.file.read(buffer)
|
||||
}
|
||||
}
|
||||
impl<R: Seek> Seek for Payload<R> {
|
||||
fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
|
||||
let from = match from {
|
||||
SeekFrom::Start(offset) => SeekFrom::Start(
|
||||
self.start
|
||||
.checked_add(offset)
|
||||
.ok_or(io::ErrorKind::InvalidInput)?,
|
||||
),
|
||||
other => other,
|
||||
};
|
||||
self.file
|
||||
.seek(from)?
|
||||
.checked_sub(self.start)
|
||||
.ok_or_else(|| io::ErrorKind::InvalidInput.into())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub(crate) mod archive;
|
||||
pub(crate) mod artifact;
|
||||
pub(crate) mod installer;
|
||||
pub(crate) mod release;
|
||||
pub(crate) mod selection;
|
||||
pub(crate) mod verification;
|
||||
@@ -17,17 +18,9 @@ pub(crate) fn resolve(
|
||||
releases: &ReleaseService,
|
||||
) -> Result<ClientProfile, ProviderAdminError> {
|
||||
let selection = Selection::parse(configuration)?;
|
||||
Ok(selection.resolve(
|
||||
releases
|
||||
.snapshot(selection.target())
|
||||
.version(selection.client),
|
||||
))
|
||||
Ok(releases.snapshot(selection.target()).profile(&selection))
|
||||
}
|
||||
pub(crate) fn default_profile(releases: &ReleaseService) -> ClientProfile {
|
||||
let selection = Selection::default();
|
||||
selection.resolve(
|
||||
releases
|
||||
.snapshot(selection.target())
|
||||
.version(selection.client),
|
||||
)
|
||||
releases.snapshot(selection.target()).profile(&selection)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! 按客户端、平台与架构刷新官方发布资料,失败时保留上次成功结果
|
||||
//! 跟踪官方发布资料并整组切换已核验画像,更新失败时保留当前画像
|
||||
|
||||
pub(crate) use super::artifact::Release;
|
||||
use super::selection::{Architecture, ClientKind, Platform, ReleaseTarget, valid_version};
|
||||
use super::selection::{
|
||||
Architecture, ClientKind, ClientProfile, Platform, ReleaseTarget, Selection, valid_version,
|
||||
};
|
||||
use super::verification::{VerificationCache, VerifiedArtifact};
|
||||
use crate::ConfigError;
|
||||
use chrono::{DateTime, Utc};
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use futures::{StreamExt, future::BoxFuture, stream};
|
||||
use gateway_core::task::{ScheduledTask, WorkerCycleContext, WorkerTaskError};
|
||||
use gateway_core::{provider_ports::ProviderArtifactProfileCachePort, routing::ProviderKind};
|
||||
@@ -20,32 +22,49 @@ const DESKTOP_PREFIX: &str = "https://storage.googleapis.com/antigravity-public/
|
||||
const CLI_MANIFESTS: &str =
|
||||
"https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests";
|
||||
const MAX_RELEASE_BYTES: usize = 2 * 1024 * 1024;
|
||||
const RELEASE_CHECK_INTERVAL: TimeDelta = TimeDelta::hours(1);
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct ReleaseSnapshot {
|
||||
pub(crate) release: Option<Release>,
|
||||
pub(crate) candidate: Option<Release>,
|
||||
pub(crate) checked: Option<DateTime<Utc>>,
|
||||
pub(crate) failed: bool,
|
||||
pub(crate) discovery_failed: bool,
|
||||
pub(crate) verification_failed: bool,
|
||||
verified: Option<VerifiedArtifact>,
|
||||
}
|
||||
impl ReleaseSnapshot {
|
||||
pub(crate) fn profile(&self, selection: &Selection) -> ClientProfile {
|
||||
match &self.verified {
|
||||
Some(verified) => {
|
||||
selection.resolve(&verified.release.version, Some(verified.changelist))
|
||||
}
|
||||
None => selection.resolve(selection.client.baseline(), None),
|
||||
}
|
||||
}
|
||||
pub(crate) fn verified_at(&self, version: &str) -> Option<DateTime<Utc>> {
|
||||
self.verified
|
||||
.as_ref()
|
||||
.filter(|verified| {
|
||||
verified.release.version == version
|
||||
&& self.release.as_ref() == Some(&verified.release)
|
||||
})
|
||||
.filter(|verified| verified.release.version == version)
|
||||
.map(|v| v.verified_at)
|
||||
}
|
||||
pub(crate) fn version(&self, client: ClientKind) -> &str {
|
||||
self.release
|
||||
.as_ref()
|
||||
.map_or(client.baseline().version, |release| {
|
||||
release.version.as_str()
|
||||
})
|
||||
pub(crate) fn pending_verification(&self) -> bool {
|
||||
self.candidate.is_some()
|
||||
&& self.candidate.as_ref() != self.verified.as_ref().map(|artifact| &artifact.release)
|
||||
}
|
||||
}
|
||||
|
||||
fn targets(client: ClientKind) -> impl Iterator<Item = ReleaseTarget> {
|
||||
[Platform::Macos, Platform::Linux, Platform::Windows]
|
||||
.into_iter()
|
||||
.flat_map(move |platform| {
|
||||
[Architecture::Arm64, Architecture::Amd64].map(move |arch| ReleaseTarget {
|
||||
client,
|
||||
platform,
|
||||
arch,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) struct ReleaseService {
|
||||
client: reqwest::Client,
|
||||
state: RwLock<BTreeMap<ReleaseTarget, ReleaseSnapshot>>,
|
||||
@@ -85,16 +104,40 @@ impl ReleaseService {
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
pub(crate) fn publish(&self, target: ReleaseTarget, result: Option<Release>) {
|
||||
pub(crate) async fn restore(&self) {
|
||||
let mut loads = stream::iter(targets(ClientKind::Desktop).chain(targets(ClientKind::Cli)))
|
||||
.map(|target| async move { (target, self.verification.load(target).await) })
|
||||
.buffer_unordered(3);
|
||||
while let Some((target, result)) = loads.next().await {
|
||||
match result {
|
||||
Ok(Some(verified)) => {
|
||||
self.state
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.entry(target)
|
||||
.or_default()
|
||||
.verified = Some(verified);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(?target, %error, "Antigravity release cache could not be restored")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn observe(&self, target: ReleaseTarget, result: Option<Release>) {
|
||||
let mut state = self
|
||||
.state
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let entry = state.entry(target).or_default();
|
||||
entry.checked = Some(Utc::now());
|
||||
entry.failed = result.is_none();
|
||||
entry.discovery_failed = result.is_none();
|
||||
if let Some(release) = result {
|
||||
entry.release = Some(release);
|
||||
if entry.candidate.as_ref() != Some(&release) {
|
||||
entry.verification_failed = false;
|
||||
}
|
||||
entry.candidate = Some(release);
|
||||
}
|
||||
}
|
||||
async fn fetch(&self, url: &str) -> Result<Vec<u8>, WorkerTaskError> {
|
||||
@@ -124,15 +167,16 @@ impl ReleaseService {
|
||||
}
|
||||
pub(crate) async fn update(&self) -> Result<(), WorkerTaskError> {
|
||||
let due = {
|
||||
let now = Utc::now();
|
||||
let state = self
|
||||
.state
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.is_empty()
|
||||
|| state.values().any(|s| {
|
||||
s.failed
|
||||
s.discovery_failed
|
||||
|| s.checked
|
||||
.is_none_or(|at| (Utc::now() - at).num_seconds() >= 86400)
|
||||
.is_none_or(|at| now - at >= RELEASE_CHECK_INTERVAL)
|
||||
})
|
||||
};
|
||||
let mut first_error = if due {
|
||||
@@ -150,23 +194,31 @@ impl ReleaseService {
|
||||
let mut verification = stream::iter(targets)
|
||||
.map(|target| async move {
|
||||
let snapshot = self.snapshot(target);
|
||||
let Some(release) = snapshot.release.as_ref() else {
|
||||
let Some(release) = snapshot.candidate.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let verified = self
|
||||
.verification
|
||||
.verify(&self.client, target, release, snapshot.verified.as_ref())
|
||||
.await?;
|
||||
.await;
|
||||
let mut state = self
|
||||
.state
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(current) = state.get_mut(&target)
|
||||
&& current.release.as_ref() == Some(&verified.release)
|
||||
{
|
||||
current.verified = Some(verified);
|
||||
let Some(current) = state
|
||||
.get_mut(&target)
|
||||
.filter(|current| current.candidate.as_ref() == Some(release))
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
current.verification_failed = verified.is_err();
|
||||
match verified {
|
||||
Ok(verified) => {
|
||||
current.verified = Some(verified);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
Ok::<_, WorkerTaskError>(())
|
||||
})
|
||||
.buffer_unordered(2);
|
||||
while let Some(result) = verification.next().await {
|
||||
@@ -179,39 +231,23 @@ impl ReleaseService {
|
||||
async fn refresh(&self) -> Result<(), WorkerTaskError> {
|
||||
let page = self.fetch(DOWNLOAD_PAGE).await;
|
||||
let mut first_error = None;
|
||||
for platform in [Platform::Macos, Platform::Linux, Platform::Windows] {
|
||||
for arch in [Architecture::Arm64, Architecture::Amd64] {
|
||||
let target = ReleaseTarget {
|
||||
client: ClientKind::Desktop,
|
||||
platform,
|
||||
arch,
|
||||
};
|
||||
let release = page
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|page| std::str::from_utf8(page).ok())
|
||||
.and_then(|page| parse_desktop(page, target));
|
||||
if release.is_none() {
|
||||
first_error = Some(WorkerTaskError::safe(
|
||||
"无法解析 Antigravity Desktop 发布资料",
|
||||
));
|
||||
}
|
||||
self.publish(target, release);
|
||||
for target in targets(ClientKind::Desktop) {
|
||||
let release = page
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|page| std::str::from_utf8(page).ok())
|
||||
.and_then(|page| parse_desktop(page, target));
|
||||
if release.is_none() {
|
||||
first_error = Some(WorkerTaskError::safe(
|
||||
"无法解析 Antigravity Desktop 发布资料",
|
||||
));
|
||||
}
|
||||
self.observe(target, release);
|
||||
}
|
||||
if let Err(error) = page {
|
||||
first_error = Some(error);
|
||||
}
|
||||
let targets = [Platform::Macos, Platform::Linux, Platform::Windows]
|
||||
.into_iter()
|
||||
.flat_map(|platform| {
|
||||
[Architecture::Arm64, Architecture::Amd64].map(move |arch| ReleaseTarget {
|
||||
client: ClientKind::Cli,
|
||||
platform,
|
||||
arch,
|
||||
})
|
||||
});
|
||||
let mut updates = stream::iter(targets)
|
||||
let mut updates = stream::iter(targets(ClientKind::Cli))
|
||||
.map(|target| async move {
|
||||
let url = format!(
|
||||
"{CLI_MANIFESTS}/{}_{}.json",
|
||||
@@ -222,7 +258,7 @@ impl ReleaseService {
|
||||
.fetch(&url)
|
||||
.await
|
||||
.and_then(|body| parse_cli(&body, target));
|
||||
self.publish(target, result.as_ref().ok().cloned());
|
||||
self.observe(target, result.as_ref().ok().cloned());
|
||||
result
|
||||
})
|
||||
.buffer_unordered(3);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! 客户端选择与冻结身份,不读取网络或运行时设置
|
||||
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind};
|
||||
use gateway_core::account::OpaqueProviderData;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -12,10 +11,6 @@ pub(crate) enum ClientKind {
|
||||
Desktop,
|
||||
Cli,
|
||||
}
|
||||
pub(crate) struct ClientBuild {
|
||||
pub(crate) version: &'static str,
|
||||
changelist: u64,
|
||||
}
|
||||
impl ClientKind {
|
||||
pub(crate) const fn product(self) -> &'static str {
|
||||
match self {
|
||||
@@ -23,17 +18,10 @@ impl ClientKind {
|
||||
Self::Cli => "Antigravity CLI",
|
||||
}
|
||||
}
|
||||
pub(crate) const fn baseline(self) -> ClientBuild {
|
||||
// 版本与 CL 成对取自官方二进制及已认证请求,下载目录的编号不是 CL
|
||||
pub(crate) const fn baseline(self) -> &'static str {
|
||||
match self {
|
||||
Self::Desktop => ClientBuild {
|
||||
version: "2.34.0",
|
||||
changelist: 1_026_637_980,
|
||||
},
|
||||
Self::Cli => ClientBuild {
|
||||
version: "1.5.17",
|
||||
changelist: 1_029_496_841,
|
||||
},
|
||||
Self::Desktop => "2.37.0",
|
||||
Self::Cli => "1.5.23",
|
||||
}
|
||||
}
|
||||
const fn subclient(self) -> &'static str {
|
||||
@@ -142,19 +130,15 @@ impl Selection {
|
||||
arch: self.arch.unwrap_or_else(|| self.platform.default_arch()),
|
||||
}
|
||||
}
|
||||
pub(crate) fn resolve(&self, latest: &str) -> ClientProfile {
|
||||
pub(crate) fn resolve(&self, latest: &str, changelist: Option<u64>) -> ClientProfile {
|
||||
let version = self.client_version.as_deref().unwrap_or(latest);
|
||||
let baseline = self.client.baseline();
|
||||
ClientProfile {
|
||||
client: self.client,
|
||||
platform: self.platform,
|
||||
arch: self.target().arch,
|
||||
client_version: version.into(),
|
||||
// 发布资料只有版本号;未知版本不沿用另一个版本的构建号
|
||||
changelist: match (self.client, version) {
|
||||
(ClientKind::Cli, "1.5.15") => Some(1_027_820_220),
|
||||
_ => (version == baseline.version).then_some(baseline.changelist),
|
||||
},
|
||||
// 固定版本不能借用其他版本制品中的 CL
|
||||
changelist: changelist.filter(|cl| version == latest && *cl > 0),
|
||||
system_prompt: self
|
||||
.system_prompt
|
||||
.as_deref()
|
||||
@@ -195,22 +179,6 @@ impl ClientProfile {
|
||||
pub(crate) fn frozen(&self) -> OpaqueProviderData {
|
||||
object(json!(self))
|
||||
}
|
||||
pub(crate) fn verified_at(&self) -> Option<DateTime<Utc>> {
|
||||
let baseline = self.client.baseline();
|
||||
if self.client_version != baseline.version || self.changelist != Some(baseline.changelist) {
|
||||
return None;
|
||||
}
|
||||
// 对应平台的 OAuth HTTP 请求已实测;此时间不代表 TLS 指纹或发布资料轮询时间
|
||||
match (self.client, self.platform, self.arch) {
|
||||
(ClientKind::Desktop, Platform::Macos, Architecture::Arm64) => {
|
||||
Utc.with_ymd_and_hms(2026, 11, 23, 11, 11, 15).single()
|
||||
}
|
||||
(ClientKind::Cli, Platform::Linux, Architecture::Amd64) => {
|
||||
Utc.with_ymd_and_hms(2026, 11, 26, 16, 1, 16).single()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(crate) fn client_identifier(&self) -> String {
|
||||
format!(
|
||||
"antigravity/{}/{}",
|
||||
@@ -232,6 +200,7 @@ impl ClientProfile {
|
||||
// CLI 的个人 OAuth 身份携带此字段;Desktop 的已认证请求未携带
|
||||
user_agent.push_str("; auth_method=consumer");
|
||||
}
|
||||
// datacollection_opt_in=false 属于官方管理员强制关闭遥测的策略,不能由普通遥测开关推导
|
||||
user_agent.push(')');
|
||||
user_agent
|
||||
}
|
||||
@@ -251,7 +220,7 @@ fn invalid() -> ProviderAdminError {
|
||||
.with_public_message("Antigravity 客户端配置无效;固定版本须为三段数字")
|
||||
}
|
||||
|
||||
// AGY CLI 1.5.15 内置身份模板的默认交互分支;工具和工作区模板由各客户端管理
|
||||
// AGY CLI 1.5.23 内置身份模板的默认交互分支;工具和工作区模板由各客户端管理
|
||||
pub(crate) const DEFAULT_SYSTEM_PROMPT: &str = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\nYou are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.";
|
||||
|
||||
fn validate_system_prompt(prompt: &str) -> Result<(), ProviderAdminError> {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::{
|
||||
artifact::{self, Release},
|
||||
selection::ReleaseTarget,
|
||||
selection::{ReleaseTarget, valid_version},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_core::{
|
||||
@@ -23,8 +23,9 @@ const RENEW_INTERVAL: Duration = Duration::from_secs(86400);
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct VerifiedArtifact {
|
||||
pub(crate) release: Release,
|
||||
pub(crate) changelist: u64,
|
||||
pub(crate) verified_at: DateTime<Utc>,
|
||||
renewed_at: Instant,
|
||||
renewed_at: Option<Instant>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -32,6 +33,7 @@ pub(crate) struct VerifiedArtifact {
|
||||
struct Payload {
|
||||
target: ReleaseTarget,
|
||||
release: Release,
|
||||
changelist: u64,
|
||||
}
|
||||
|
||||
pub(crate) struct VerificationCache {
|
||||
@@ -46,6 +48,40 @@ impl VerificationCache {
|
||||
Self { provider, cache }
|
||||
}
|
||||
|
||||
pub(crate) async fn load(
|
||||
&self,
|
||||
target: ReleaseTarget,
|
||||
) -> Result<Option<VerifiedArtifact>, WorkerTaskError> {
|
||||
let key = key(target);
|
||||
let Some(cached) = self
|
||||
.cache
|
||||
.read(&self.provider, &key)
|
||||
.await
|
||||
.map_err(|e| error().with_source(e))?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let payload: Payload = serde_json::from_value(serde_json::Value::Object(
|
||||
cached.profile().expose_to_provider().clone(),
|
||||
))
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
if cached.provider_kind() != &self.provider
|
||||
|| cached.artifact_key() != key
|
||||
|| payload.target != target
|
||||
|| payload.changelist == 0
|
||||
|| !valid_version(&payload.release.version)
|
||||
|| cached.artifact_sequence() != sequence(&payload.release.version)?
|
||||
{
|
||||
return Err(error());
|
||||
}
|
||||
Ok(Some(VerifiedArtifact {
|
||||
release: payload.release,
|
||||
changelist: payload.changelist,
|
||||
verified_at: cached.verified_at().into(),
|
||||
renewed_at: None,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) async fn verify(
|
||||
&self,
|
||||
client: &reqwest::Client,
|
||||
@@ -54,46 +90,28 @@ impl VerificationCache {
|
||||
previous: Option<&VerifiedArtifact>,
|
||||
) -> Result<VerifiedArtifact, WorkerTaskError> {
|
||||
let sequence = sequence(&release.version)?;
|
||||
if let Some(previous) = previous.filter(|previous| previous.release == *release)
|
||||
&& previous.renewed_at.elapsed() < RENEW_INTERVAL
|
||||
{
|
||||
return Ok(previous.clone());
|
||||
if let Some(previous) = previous {
|
||||
validate_successor(previous, release, sequence)?;
|
||||
if previous.release == *release
|
||||
&& previous
|
||||
.renewed_at
|
||||
.is_some_and(|at| at.elapsed() < RENEW_INTERVAL)
|
||||
{
|
||||
return Ok(previous.clone());
|
||||
}
|
||||
}
|
||||
let key = key(target);
|
||||
let cached = self
|
||||
.cache
|
||||
.read(&self.provider, &key)
|
||||
.await
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
let verified_at = if let Some(cached) = cached {
|
||||
let payload: Payload = serde_json::from_value(serde_json::Value::Object(
|
||||
cached.profile().expose_to_provider().clone(),
|
||||
))
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
if cached.provider_kind() != &self.provider
|
||||
|| cached.artifact_key() != key
|
||||
|| payload.target != target
|
||||
|| cached.artifact_sequence() != self::sequence(&payload.release.version)?
|
||||
{
|
||||
return Err(error());
|
||||
}
|
||||
if cached.artifact_sequence() > sequence
|
||||
|| (cached.artifact_sequence() == sequence && payload.release != *release)
|
||||
{
|
||||
return Err(error());
|
||||
}
|
||||
(payload.release == *release).then(|| DateTime::<Utc>::from(cached.verified_at()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verified_at = match verified_at.or_else(|| {
|
||||
previous
|
||||
.filter(|v| v.release == *release)
|
||||
.map(|v| v.verified_at)
|
||||
}) {
|
||||
Some(at) => at,
|
||||
let cached = self.load(target).await?;
|
||||
if let Some(cached) = &cached {
|
||||
validate_successor(cached, release, sequence)?;
|
||||
}
|
||||
let matching = cached
|
||||
.as_ref()
|
||||
.filter(|v| v.release == *release)
|
||||
.or_else(|| previous.filter(|v| v.release == *release));
|
||||
let (verified_at, changelist) = match matching {
|
||||
Some(artifact) => (artifact.verified_at, artifact.changelist),
|
||||
None => {
|
||||
artifact::verify(
|
||||
let changelist = artifact::verify(
|
||||
client,
|
||||
target,
|
||||
&release.version,
|
||||
@@ -101,12 +119,13 @@ impl VerificationCache {
|
||||
release.sha512.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
Utc::now()
|
||||
(Utc::now(), changelist)
|
||||
}
|
||||
};
|
||||
let payload = serde_json::to_value(Payload {
|
||||
target,
|
||||
release: release.clone(),
|
||||
changelist,
|
||||
})
|
||||
.map_err(|e| error().with_source(e))?;
|
||||
let serde_json::Value::Object(payload) = payload else {
|
||||
@@ -114,7 +133,7 @@ impl VerificationCache {
|
||||
};
|
||||
let profile = ProviderArtifactProfile::new(
|
||||
self.provider.clone(),
|
||||
key,
|
||||
key(target),
|
||||
sequence,
|
||||
verified_at.into(),
|
||||
OpaqueProviderData::new(payload),
|
||||
@@ -129,19 +148,36 @@ impl VerificationCache {
|
||||
}
|
||||
Ok(VerifiedArtifact {
|
||||
release: release.clone(),
|
||||
changelist,
|
||||
verified_at,
|
||||
renewed_at: Instant::now(),
|
||||
renewed_at: Some(Instant::now()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_successor(
|
||||
current: &VerifiedArtifact,
|
||||
next: &Release,
|
||||
next_sequence: u64,
|
||||
) -> Result<(), WorkerTaskError> {
|
||||
let current_sequence = sequence(¤t.release.version)?;
|
||||
if next_sequence < current_sequence
|
||||
|| (next_sequence == current_sequence && current.release != *next)
|
||||
{
|
||||
return Err(WorkerTaskError::safe(
|
||||
"Antigravity 官方发布版本回退或同版本制品不一致",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn key(target: ReleaseTarget) -> String {
|
||||
let client = match target.client {
|
||||
super::selection::ClientKind::Desktop => "desktop",
|
||||
super::selection::ClientKind::Cli => "cli",
|
||||
};
|
||||
format!(
|
||||
"{client}-{}-{}",
|
||||
"build-v1-{client}-{}-{}",
|
||||
target.platform.os_type(),
|
||||
target.arch.label()
|
||||
)
|
||||
|
||||
@@ -14,33 +14,39 @@ use serde_json::{Value, json};
|
||||
pub(crate) fn options() -> OpaqueProviderData {
|
||||
let presets=[Platform::Macos,Platform::Linux,Platform::Windows].into_iter().flat_map(|platform|[ClientKind::Desktop,ClientKind::Cli].map(move|client|json!({"configuration":Selection {client,platform,..Selection::default()},"automaticAvailable":true,"reason":null}))).collect::<Vec<_>>();
|
||||
object(
|
||||
json!({"defaults":Selection::default(),"presets":presets,"defaultSystemPrompt":super::selection::DEFAULT_SYSTEM_PROMPT,"systemPromptSource":"Antigravity CLI 1.5.15"}),
|
||||
json!({"defaults":Selection::default(),"presets":presets,"defaultSystemPrompt":super::selection::DEFAULT_SYSTEM_PROMPT,"systemPromptSource":"Antigravity CLI 1.5.23"}),
|
||||
)
|
||||
}
|
||||
pub(crate) fn dashboard(selection: &Selection, releases: &ReleaseService) -> DashboardWireProfile {
|
||||
let snapshot = releases.snapshot(selection.target());
|
||||
let profile = selection.resolve(snapshot.version(selection.client));
|
||||
let profile = snapshot.profile(selection);
|
||||
let fixed = selection.version_mode == VersionMode::Fixed;
|
||||
let release = (!fixed).then(|| DashboardDesktopRelease {
|
||||
status: if snapshot.failed {
|
||||
status: if snapshot.discovery_failed || snapshot.verification_failed {
|
||||
DesktopReleaseStatus::Failed
|
||||
} else if snapshot.release.is_none() {
|
||||
} else if snapshot.candidate.is_none() {
|
||||
DesktopReleaseStatus::Unchecked
|
||||
} else if snapshot.pending_verification() {
|
||||
DesktopReleaseStatus::UpdateAvailable
|
||||
} else {
|
||||
DesktopReleaseStatus::Current
|
||||
},
|
||||
checked_at: snapshot.checked,
|
||||
latest_version: snapshot.release.as_ref().map(|r| r.version.clone()),
|
||||
latest_build: snapshot.release.as_ref().and_then(|r| r.build.clone()),
|
||||
download_url: snapshot.release.as_ref().map(|r| r.url.clone()),
|
||||
latest_version: snapshot.candidate.as_ref().map(|r| r.version.clone()),
|
||||
latest_build: snapshot.candidate.as_ref().and_then(|r| r.build.clone()),
|
||||
download_url: snapshot.candidate.as_ref().map(|r| r.url.clone()),
|
||||
published_at: None,
|
||||
minimum_system_version: None,
|
||||
hardware_requirements: None,
|
||||
download_size: None,
|
||||
signature_present: None,
|
||||
error: snapshot
|
||||
.failed
|
||||
.then(|| "无法读取 Google 官方客户端版本".into()),
|
||||
error: if snapshot.discovery_failed {
|
||||
Some("无法读取 Google 官方客户端版本".into())
|
||||
} else if snapshot.verification_failed {
|
||||
Some("无法核验 Google 官方客户端发布包".into())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
});
|
||||
DashboardWireProfile {
|
||||
provider: "antigravity".into(),
|
||||
@@ -65,9 +71,7 @@ pub(crate) fn dashboard(selection: &Selection, releases: &ReleaseService) -> Das
|
||||
],
|
||||
user_agent: profile.user_agent(),
|
||||
release,
|
||||
verified_at: snapshot
|
||||
.verified_at(&profile.client_version)
|
||||
.or_else(|| profile.verified_at()),
|
||||
verified_at: snapshot.verified_at(&profile.client_version),
|
||||
}
|
||||
}
|
||||
pub(crate) fn preview(
|
||||
|
||||
@@ -137,6 +137,7 @@ impl AntigravityProvider {
|
||||
};
|
||||
let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?;
|
||||
let translated_chat = translator.is_some();
|
||||
let native_error = !translated_chat && count_translator.is_none();
|
||||
let events = async_stream::try_stream! {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(unsent(Kind::Cancelled))?;
|
||||
@@ -144,12 +145,12 @@ impl AntigravityProvider {
|
||||
if deadline.is_elapsed() {
|
||||
Err(unsent(Kind::Timeout))?;
|
||||
}
|
||||
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||
.then(|| selected.material.token().to_owned());
|
||||
let error_token = selected.material.token().to_owned();
|
||||
let record_failure = async |error| {
|
||||
let error = match &probe_token {
|
||||
Some(token) => crate::transport::connection_test_error(error, token),
|
||||
None => error,
|
||||
let error = match terminal_context.account_eligibility() {
|
||||
AccountEligibilityPolicy::BypassForDiagnostic => crate::transport::connection_test_error(error, &error_token),
|
||||
AccountEligibilityPolicy::Enforce => crate::transport::client_error(error, &error_token, native_error),
|
||||
_ => error,
|
||||
};
|
||||
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
|
||||
};
|
||||
|
||||
@@ -18,42 +18,29 @@ impl AntigravityProvider {
|
||||
records_account_feedback: bool,
|
||||
error: ProviderError,
|
||||
) -> ProviderError {
|
||||
if error.send_state() != UpstreamSendState::Sent
|
||||
|| !matches!(error.kind(), Kind::Unauthorized | Kind::RateLimited)
|
||||
{
|
||||
if error.send_state() != UpstreamSendState::Sent {
|
||||
return error;
|
||||
}
|
||||
// 明确拒绝没有生成结果;换号仍受 Core 的交付屏障、范围与预算约束
|
||||
let error = error.with_replay_safe().with_pre_delivery_retry();
|
||||
let error = if !error.retry_is_prohibited()
|
||||
&& matches!(
|
||||
error.kind(),
|
||||
Kind::Unauthorized
|
||||
| Kind::RateLimited
|
||||
| Kind::QuotaExhausted
|
||||
| Kind::UpstreamCapacityUnavailable
|
||||
) {
|
||||
error.with_replay_safe().with_pre_delivery_retry()
|
||||
} else {
|
||||
error
|
||||
};
|
||||
if !records_account_feedback {
|
||||
return error;
|
||||
}
|
||||
crate::credential::record_account_failure(self.accounts.as_ref(), account, &error).await;
|
||||
let feedback = async {
|
||||
match error.kind() {
|
||||
Kind::Unauthorized => {
|
||||
if account.authentication_kind() == crate::credential::api_key::API_KEY {
|
||||
self.accounts
|
||||
.apply_state_change(gateway_core::account::AccountStateChange {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
credential_state: gateway_core::account::CredentialState::Invalid,
|
||||
observed_at: SystemTime::now(),
|
||||
error_reason: Some(
|
||||
gateway_core::account::AccountErrorReason::CredentialInvalid,
|
||||
),
|
||||
message: Some("上游拒绝 API Key".into()),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
// 资源服务拒绝 AT 不能证明 RT 失效,续期仍由已有 OAuth worker 负责
|
||||
self.accounts
|
||||
.expire_access_token(account, SystemTime::now())
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
Kind::RateLimited => {
|
||||
Kind::RateLimited | Kind::QuotaExhausted | Kind::UpstreamCapacityUnavailable => {
|
||||
if let Some(until) = error
|
||||
.retry_after()
|
||||
.and_then(|delay| SystemTime::now().checked_add(delay))
|
||||
|
||||
@@ -103,30 +103,43 @@ struct RefreshTask {
|
||||
impl ScheduledTask for RefreshTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let (candidates, concurrency) = self.credentials.refresh_candidates().await?;
|
||||
if candidates.is_empty() || context.cancellation().is_cancelled() {
|
||||
let cancellation = context.cancellation();
|
||||
let Some(batch) = cancellation
|
||||
.run_until_cancelled(self.credentials.refresh_candidates())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let (candidates, concurrency) = batch?;
|
||||
if candidates.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut catalogs = self
|
||||
.catalog
|
||||
.capture_refresh_catalogs(&candidates)
|
||||
let Some(catalogs) = cancellation
|
||||
.run_until_cancelled(self.catalog.capture_refresh_catalogs(&candidates))
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录");
|
||||
Default::default()
|
||||
});
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut catalogs = catalogs.unwrap_or_else(|_| {
|
||||
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录");
|
||||
Default::default()
|
||||
});
|
||||
let mut updates = stream::iter(candidates)
|
||||
.map(|loaded| {
|
||||
let cancellation = context.cancellation();
|
||||
let catalog = catalogs.remove(loaded.account.id());
|
||||
async move {
|
||||
if cancellation.is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
let revision = self.credentials.refresh_due(&loaded).await?;
|
||||
self.catalog
|
||||
.after_credential_refresh(loaded.account.id(), revision, catalog)
|
||||
cancellation
|
||||
.run_until_cancelled(self.catalog.after_credential_refresh(
|
||||
loaded.account.id(),
|
||||
revision,
|
||||
catalog,
|
||||
))
|
||||
.await
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
})
|
||||
.buffer_unordered(concurrency);
|
||||
|
||||
@@ -368,7 +368,16 @@ pub(super) async fn control<T: DeserializeOwned>(
|
||||
}
|
||||
data.extend_from_slice(&chunk);
|
||||
}
|
||||
serde_json::from_slice(&data).map_err(|e| sent(Kind::Protocol).with_source(e))
|
||||
let document: serde_json::Value =
|
||||
serde_json::from_slice(&data).map_err(|e| sent(Kind::Protocol).with_source(e))?;
|
||||
if super::failure::google_error(&document).is_some_and(serde_json::Value::is_object) {
|
||||
return Err(super::failure::body_error(
|
||||
None,
|
||||
&String::from_utf8_lossy(&data),
|
||||
token,
|
||||
));
|
||||
}
|
||||
serde_json::from_value(document).map_err(|e| sent(Kind::Protocol).with_source(e))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
||||
@@ -35,6 +35,9 @@ pub(crate) fn count_events(
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
let value: Value = serde_json::from_slice(&body).map_err(|_| sent(Kind::Protocol))?;
|
||||
if super::failure::google_error(&value).is_some_and(Value::is_object) {
|
||||
Err(super::failure::body_error(None, &String::from_utf8_lossy(&body), &context.token))?;
|
||||
}
|
||||
// Cloud Code 的 protobuf JSON 会省略零值;公开计数接口显式交付 totalTokens
|
||||
if value.as_object().is_some_and(serde_json::Map::is_empty) {
|
||||
body = br#"{"totalTokens":0}"#.to_vec();
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
use gateway_core::{
|
||||
error::{
|
||||
ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind,
|
||||
RawUpstreamError,
|
||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, GatewayError,
|
||||
OpaqueUpstreamValue, ProviderError, ProviderErrorKind as Kind, RawUpstreamError,
|
||||
},
|
||||
upstream::UpstreamSendState,
|
||||
upstream::{UpstreamFailureFields, UpstreamSendState},
|
||||
};
|
||||
use reqwest::{Response, StatusCode};
|
||||
use serde_json::Value;
|
||||
@@ -44,13 +44,41 @@ fn status_kind(status: StatusCode) -> Kind {
|
||||
}
|
||||
}
|
||||
pub(super) fn body_error(status: Option<u16>, body: &str, token: &str) -> ProviderError {
|
||||
let status = status.and_then(|code| StatusCode::from_u16(code).ok());
|
||||
let error = sent(status.map_or(Kind::Unavailable, status_kind));
|
||||
let error = if let Some(status) = status {
|
||||
error.with_status(status.as_u16())
|
||||
} else {
|
||||
error
|
||||
let document = serde_json::from_str::<Value>(body).ok();
|
||||
let failure = document.as_ref().and_then(google_error);
|
||||
let status = status
|
||||
.filter(|code| (400..=599).contains(code))
|
||||
.or_else(|| failure.and_then(rpc_status));
|
||||
let fields = UpstreamFailureFields {
|
||||
status,
|
||||
code: None,
|
||||
error_type: None,
|
||||
message: None,
|
||||
};
|
||||
let mut kind = status
|
||||
.and_then(|code| StatusCode::from_u16(code).ok())
|
||||
.map_or(Kind::Unavailable, status_kind);
|
||||
if matches!(status, Some(429 | 503)) {
|
||||
match failure
|
||||
.and_then(error_info)
|
||||
.and_then(|info| info["reason"].as_str())
|
||||
{
|
||||
Some("MODEL_CAPACITY_EXHAUSTED") if status == Some(503) => {
|
||||
kind = Kind::UpstreamCapacityUnavailable
|
||||
}
|
||||
Some(
|
||||
"QUOTA_EXHAUSTED"
|
||||
| "QUOTA_ENDPOINT_EXHAUSTED"
|
||||
| "QUOTA_PRODUCT_EXHAUSTED"
|
||||
| "QUOTA_RECIPE_EXHAUSTED",
|
||||
) if status == Some(429) => kind = Kind::QuotaExhausted,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut error = sent(kind).with_upstream_failure_fields(fields);
|
||||
if let Some(status) = status {
|
||||
error = error.with_status(status);
|
||||
}
|
||||
attach_body(error, body, token)
|
||||
}
|
||||
fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
|
||||
@@ -68,6 +96,34 @@ fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
|
||||
if body.is_empty() {
|
||||
return error;
|
||||
}
|
||||
let mut error = error;
|
||||
if let Ok(document) = serde_json::from_str::<Value>(body)
|
||||
&& let Some(failure) = google_error(&document)
|
||||
{
|
||||
let info = error_info(failure);
|
||||
let code = info
|
||||
.and_then(|info| info["reason"].as_str())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| failure["code"].as_u64().map(|code| code.to_string()));
|
||||
let status = error.upstream_status();
|
||||
error = error.with_upstream_failure_fields(UpstreamFailureFields {
|
||||
status,
|
||||
code: code.clone(),
|
||||
error_type: failure["status"].as_str().map(str::to_owned),
|
||||
message: failure["message"].as_str().map(str::to_owned),
|
||||
});
|
||||
if let Some(code) = code {
|
||||
error = error.with_upstream_code(OpaqueUpstreamValue::new(code));
|
||||
}
|
||||
if account_rejection(&error).is_some()
|
||||
|| (error.upstream_status() == Some(403)
|
||||
&& error
|
||||
.upstream_code()
|
||||
.is_some_and(|code| request_rejection(code.as_str())))
|
||||
{
|
||||
error = error.with_retry_prohibited();
|
||||
}
|
||||
}
|
||||
let end = body.floor_char_boundary(MAX_ERROR_BYTES.min(body.len()));
|
||||
let text = if end < body.len() {
|
||||
format!("{}\n[truncated]", &body[..end])
|
||||
@@ -88,7 +144,7 @@ pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> Provid
|
||||
let Some(failure) = google_error(&document) else {
|
||||
return error;
|
||||
};
|
||||
let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo");
|
||||
let info = error_info(failure);
|
||||
let safe_text = |value: &Value| {
|
||||
value
|
||||
.as_str()
|
||||
@@ -117,12 +173,182 @@ pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> Provid
|
||||
))
|
||||
}
|
||||
|
||||
fn google_error(document: &Value) -> Option<&Value> {
|
||||
pub(super) fn google_error(document: &Value) -> Option<&Value> {
|
||||
document
|
||||
.get("error")
|
||||
.or_else(|| document.pointer("/response/error"))
|
||||
}
|
||||
|
||||
fn error_info(error: &Value) -> Option<&Value> {
|
||||
error
|
||||
.get("details")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter(|detail| {
|
||||
detail["@type"] == "type.googleapis.com/google.rpc.ErrorInfo"
|
||||
&& detail["reason"]
|
||||
.as_str()
|
||||
.is_some_and(|reason| !reason.is_empty())
|
||||
})
|
||||
.max_by_key(|detail| {
|
||||
let reason = detail["reason"].as_str().unwrap_or_default();
|
||||
match account_rejection_reason(reason) {
|
||||
Some(AccountRejection::Banned) => 4,
|
||||
Some(AccountRejection::VerificationRequired) => 3,
|
||||
None if request_rejection(reason) => 2,
|
||||
None => 1,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum AccountRejection {
|
||||
VerificationRequired,
|
||||
Banned,
|
||||
}
|
||||
|
||||
pub(crate) fn account_rejection(error: &ProviderError) -> Option<AccountRejection> {
|
||||
if error.send_state() != UpstreamSendState::Sent || error.upstream_status() != Some(403) {
|
||||
return None;
|
||||
}
|
||||
account_rejection_reason(error.upstream_code()?.as_str())
|
||||
}
|
||||
|
||||
fn account_rejection_reason(reason: &str) -> Option<AccountRejection> {
|
||||
match reason {
|
||||
"VALIDATION_REQUIRED" => Some(AccountRejection::VerificationRequired),
|
||||
"TOS_VIOLATION"
|
||||
| "WORKSPACE_TOS_VIOLATION_CONTACT_SUPPORT"
|
||||
| "ACCOUNT_SUSPENDED"
|
||||
| "ACCOUNT_DISABLED"
|
||||
| "USER_SUSPENDED"
|
||||
| "USER_DISABLED" => Some(AccountRejection::Banned),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn request_rejection(reason: &str) -> bool {
|
||||
matches!(
|
||||
reason,
|
||||
"AI_POLICY_REQUIRED"
|
||||
| "AI_POLICY_SOFT_BLOCK_BANNER"
|
||||
| "AI_POLICY_SOFT_BLOCK_CLI"
|
||||
| "UNSUPPORTED_CLIENT"
|
||||
)
|
||||
}
|
||||
|
||||
fn rpc_status(error: &Value) -> Option<u16> {
|
||||
let code = error["code"].as_u64();
|
||||
if let Some(code @ 400..=599) = code {
|
||||
return u16::try_from(code).ok();
|
||||
}
|
||||
match error["status"].as_str() {
|
||||
Some("INVALID_ARGUMENT" | "FAILED_PRECONDITION" | "OUT_OF_RANGE") => Some(400),
|
||||
Some("UNAUTHENTICATED") => Some(401),
|
||||
Some("PERMISSION_DENIED") => Some(403),
|
||||
Some("NOT_FOUND") => Some(404),
|
||||
Some("ALREADY_EXISTS" | "ABORTED") => Some(409),
|
||||
Some("RESOURCE_EXHAUSTED") => Some(429),
|
||||
Some("CANCELLED") => Some(499),
|
||||
Some("UNKNOWN" | "INTERNAL" | "DATA_LOSS") => Some(500),
|
||||
Some("UNIMPLEMENTED") => Some(501),
|
||||
Some("UNAVAILABLE") => Some(503),
|
||||
Some("DEADLINE_EXCEEDED") => Some(504),
|
||||
_ => match code {
|
||||
Some(1) => Some(499),
|
||||
Some(2 | 13 | 15) => Some(500),
|
||||
Some(3 | 9 | 11) => Some(400),
|
||||
Some(4) => Some(504),
|
||||
Some(5) => Some(404),
|
||||
Some(6 | 10) => Some(409),
|
||||
Some(7) => Some(403),
|
||||
Some(8) => Some(429),
|
||||
Some(12) => Some(501),
|
||||
Some(14) => Some(503),
|
||||
Some(16) => Some(401),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 模型客户端只收到协议字段,账号验证链接和其他 metadata 留在受控诊断中
|
||||
pub(crate) fn client_error(error: ProviderError, token: &str, native: bool) -> ProviderError {
|
||||
let error = connection_test_error(error, token);
|
||||
let Some(status) = error
|
||||
.upstream_status()
|
||||
.filter(|status| (400..=599).contains(status))
|
||||
else {
|
||||
return error;
|
||||
};
|
||||
let gateway = GatewayError::from_provider(&error);
|
||||
let detail = error.client_visible_upstream_error();
|
||||
let message = detail.map_or(gateway.safe_message(), ClientVisibleUpstreamError::message);
|
||||
let code = detail.and_then(ClientVisibleUpstreamError::code);
|
||||
let body = if native {
|
||||
let rpc = match status {
|
||||
400 | 413 | 422 => "INVALID_ARGUMENT",
|
||||
401 => "UNAUTHENTICATED",
|
||||
403 => "PERMISSION_DENIED",
|
||||
404 => "NOT_FOUND",
|
||||
408 | 504 => "DEADLINE_EXCEEDED",
|
||||
409 => "ABORTED",
|
||||
429 => "RESOURCE_EXHAUSTED",
|
||||
499 => "CANCELLED",
|
||||
501 => "UNIMPLEMENTED",
|
||||
502 | 503 => "UNAVAILABLE",
|
||||
_ => "INTERNAL",
|
||||
};
|
||||
let mut body = serde_json::json!({"error":{"code":status,"status":rpc,"message":message}});
|
||||
if let Some(kind) = detail.and_then(ClientVisibleUpstreamError::error_type) {
|
||||
body["error"]["status"] = Value::String(kind.into());
|
||||
}
|
||||
if let Some(code) = code {
|
||||
body["error"]["details"] = serde_json::json!([{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":code}]);
|
||||
}
|
||||
if let Some(delay) = error.retry_after() {
|
||||
let detail = serde_json::json!({"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":format!("{}.{:09}s", delay.as_secs(), delay.subsec_nanos())});
|
||||
let details = body["error"].as_object_mut().and_then(|error| {
|
||||
error
|
||||
.entry("details")
|
||||
.or_insert_with(|| serde_json::json!([]))
|
||||
.as_array_mut()
|
||||
});
|
||||
if let Some(details) = details {
|
||||
details.push(detail);
|
||||
}
|
||||
}
|
||||
body
|
||||
} else {
|
||||
serde_json::json!({"error":{"message":message,"type":detail.and_then(ClientVisibleUpstreamError::error_type).unwrap_or("upstream_error"),"code":code}})
|
||||
};
|
||||
let mut response = ClientVisibleUpstreamResponse::new(
|
||||
status,
|
||||
Some(b"application/json".to_vec()),
|
||||
body.to_string().into(),
|
||||
);
|
||||
if let Some(delay) = error.retry_after() {
|
||||
let seconds = delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() != 0));
|
||||
response = response.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
|
||||
"retry-after",
|
||||
seconds.to_string().into(),
|
||||
)]);
|
||||
}
|
||||
let error = error.with_client_visible_upstream_response(response);
|
||||
if native
|
||||
&& let Ok(wire) = gateway_core::event::ProtocolWireEvent::json(
|
||||
gateway_protocol::genai::GENAI_PROTOCOL,
|
||||
None,
|
||||
body,
|
||||
)
|
||||
{
|
||||
return error
|
||||
.with_atomic_client_events(vec![gateway_core::event::ProviderEvent::wire(wire)]);
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> {
|
||||
error
|
||||
.get("details")?
|
||||
@@ -177,10 +403,6 @@ pub(super) async fn successful(
|
||||
.get(reqwest::header::RETRY_AFTER)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(retry_after);
|
||||
let mut error = sent(status_kind(status)).with_status(status.as_u16());
|
||||
if let Some(delay) = retry_after {
|
||||
error = error.with_retry_after(delay);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
let mut truncated = false;
|
||||
let read = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
@@ -195,14 +417,25 @@ pub(super) async fn successful(
|
||||
Ok::<_, reqwest::Error>(())
|
||||
})
|
||||
.await;
|
||||
let text = String::from_utf8_lossy(&body).into_owned();
|
||||
let mut error = body_error(
|
||||
Some(status.as_u16()),
|
||||
if truncated { "" } else { &text },
|
||||
token,
|
||||
);
|
||||
if let Some(delay) = retry_after {
|
||||
let delay = error
|
||||
.retry_after()
|
||||
.map_or(delay, |current| current.max(delay));
|
||||
error = error.with_retry_after(delay);
|
||||
}
|
||||
match read {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(source)) => error = error.with_source(source.without_url()),
|
||||
Err(source) => error = error.with_source(source),
|
||||
}
|
||||
let text = String::from_utf8_lossy(&body).into_owned();
|
||||
if truncated {
|
||||
return Err(error.redact_sensitive_context(&text));
|
||||
}
|
||||
Err(attach_body(error, &text, token))
|
||||
Err(error)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ mod tool_ids;
|
||||
pub(crate) use api_key::GenAiClient;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{connection_test_error, sent, unsent};
|
||||
pub(crate) use failure::{
|
||||
AccountRejection, account_rejection, client_error, connection_test_error, sent, unsent,
|
||||
};
|
||||
pub(crate) use headers::request_headers;
|
||||
pub(crate) use pool::ClientPool;
|
||||
pub(crate) use response::{ResponseContext, events, genai_events};
|
||||
|
||||
@@ -23,6 +23,10 @@ pub(super) fn request_body(
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
// Gateway 入口的本地状态不能声明成 OAuth 生成请求字段;正文和工具参数不递归改写
|
||||
if matches!(name, "hasFingerprintSet" | "has_fingerprint_set") {
|
||||
return Ok(Edit::Remove);
|
||||
}
|
||||
// 合并到已有的字段处理,避免为签名再解析、复制和校验整个请求
|
||||
if name == "contents" {
|
||||
return super::signatures::prepare_contents(value, model);
|
||||
|
||||
@@ -279,7 +279,7 @@ async fn imported_grants_cannot_inherit_missing_or_reduced_scopes() {
|
||||
async fn import_resolves_scopes_and_freezes_global_profile_until_the_next_refresh() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
*store.request_profile.lock().unwrap() = Some(crate::profile::object(json!({
|
||||
"client":"cli", "platform":"windows", "versionMode":"fixed", "clientVersion":"1.5.15",
|
||||
"client":"cli", "platform":"windows", "versionMode":"fixed", "clientVersion":"1.5.23",
|
||||
})));
|
||||
let mut response = token_response();
|
||||
response.as_object_mut().unwrap().remove("scope");
|
||||
@@ -325,7 +325,7 @@ async fn import_resolves_scopes_and_freezes_global_profile_until_the_next_refres
|
||||
for request in requests {
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
"antigravity/cli/1.5.15 (aidev_client; os_type=windows; arch=amd64; cl=1027820220; auth_method=consumer)"
|
||||
"antigravity/cli/1.5.23 (aidev_client; os_type=windows; arch=amd64; auth_method=consumer)"
|
||||
);
|
||||
}
|
||||
server.verify().await;
|
||||
|
||||
@@ -10,7 +10,7 @@ use wiremock::{
|
||||
|
||||
pub(crate) async fn refreshed_credential(server: &MockServer) -> (Url, String) {
|
||||
let origin = server.uri();
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0");
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0", None);
|
||||
let config:OAuthRegistration=serde_json::from_value(json!({"client_id":"fixture-cpr","client_secret":"fixture-secret","redirect_uri":"http://127.0.0.1:8020/callback","resource_scopes":["fixture-resource"],"resource_origin":origin})).unwrap();
|
||||
config.validate().unwrap();
|
||||
let oauth = GoogleOAuth::with_endpoints(
|
||||
|
||||
@@ -8,12 +8,17 @@ mod api_key_tests;
|
||||
mod authorization;
|
||||
#[path = "../../src/credential/documents.rs"]
|
||||
mod documents;
|
||||
#[path = "../../src/credential/failure.rs"]
|
||||
mod failure;
|
||||
pub(crate) use failure::record_account_failure;
|
||||
#[path = "../../src/credential/model_groups.rs"]
|
||||
mod model_groups;
|
||||
#[path = "../../src/credential/oauth.rs"]
|
||||
pub(crate) mod oauth;
|
||||
#[path = "../../src/credential/refresh.rs"]
|
||||
mod refresh;
|
||||
#[path = "refresh.rs"]
|
||||
mod refresh_tests;
|
||||
#[path = "../../src/credential/service.rs"]
|
||||
mod service;
|
||||
pub(crate) use authorization::AuthorizationService;
|
||||
|
||||
@@ -76,7 +76,7 @@ async fn exchange_and_refresh_preserve_verified_identity_and_offline_grant() {
|
||||
};
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0");
|
||||
let profile = crate::profile::Selection::default().resolve("2.34.0", None);
|
||||
let oauth = GoogleOAuth::with_endpoints(
|
||||
serde_json::from_value(registration()).unwrap(),
|
||||
&format!("{}/token", server.uri()),
|
||||
|
||||
@@ -169,7 +169,7 @@ async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
upstream(&server, json!(0.5), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary().loaded.lock().unwrap().account.clone();
|
||||
for (version, changelist) in [("1.5.14", ""), ("1.5.15", "; cl=1027820220")] {
|
||||
for (version, changelist) in [("9.8.7", ""), ("1.5.23", "")] {
|
||||
*f.store.request_profile.lock().unwrap() = Some(crate::profile::object(
|
||||
json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":version,"arch":null}),
|
||||
));
|
||||
@@ -238,7 +238,7 @@ async fn account_and_request_plans_use_the_desktop_description_for_every_tier()
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
@@ -453,7 +453,7 @@ async fn peer_model_facts_keep_membership_quota_and_revision_separate() {
|
||||
crate::support::request(false),
|
||||
crate::support::context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
@@ -539,7 +539,7 @@ async fn google_one_credits_require_opt_in_and_sufficient_balance() {
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! OAuth 续期保留资源服务拒绝,旧凭据反馈不能污染新授权
|
||||
|
||||
use super::documents_tests::fixture;
|
||||
use gateway_core::account::{AccountErrorReason, CredentialState, PlaintextCredential};
|
||||
use serde_json::json;
|
||||
use wiremock::{Mock, ResponseTemplate, matchers::path};
|
||||
|
||||
#[tokio::test]
|
||||
async fn token_refresh_preserves_a_denial_recorded_while_refresh_was_in_flight() {
|
||||
let (server, credentials, store) = fixture().await;
|
||||
let loaded = {
|
||||
let mut loaded = store.primary().loaded.lock().unwrap();
|
||||
let mut material = loaded.credential.expose_to_provider().clone();
|
||||
material.insert(
|
||||
"registration".into(),
|
||||
json!(credentials.oauth.registration()),
|
||||
);
|
||||
loaded.credential = PlaintextCredential::new(material);
|
||||
loaded.clone()
|
||||
};
|
||||
Mock::given(path("/token")).respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"access_token":"fresh-access","token_type":"Bearer","expires_in":3600,"scope":"email fixture-resource"
|
||||
}))).expect(2).mount(&server).await;
|
||||
{
|
||||
let mut current = store.primary().loaded.lock().unwrap();
|
||||
current.account = current.account.clone().with_account_facts(
|
||||
true,
|
||||
CredentialState::Invalid,
|
||||
current.account.quota(),
|
||||
Some(AccountErrorReason::AccountUnverified),
|
||||
Some("需验证".into()),
|
||||
);
|
||||
}
|
||||
let prepared = credentials.refresh_current(&loaded).await.unwrap();
|
||||
assert!(prepared.facts().preserve_credential_state);
|
||||
drop(prepared);
|
||||
let revision = credentials.refresh_due(&loaded).await.unwrap();
|
||||
let stale = gateway_core::error::ProviderError::new(
|
||||
gateway_core::error::ProviderErrorKind::PermissionDenied,
|
||||
gateway_core::upstream::UpstreamSendState::Sent,
|
||||
)
|
||||
.with_status(403)
|
||||
.with_upstream_code(gateway_core::error::OpaqueUpstreamValue::new(
|
||||
"TOS_VIOLATION",
|
||||
));
|
||||
super::record_account_failure(store.as_ref(), &loaded.account, &stale).await;
|
||||
let current = store.primary().loaded.lock().unwrap();
|
||||
assert_eq!(current.account.revision(), revision);
|
||||
assert_eq!(current.account.credential_state(), CredentialState::Invalid);
|
||||
assert_eq!(
|
||||
current.account.last_error_reason(),
|
||||
Some(AccountErrorReason::AccountUnverified)
|
||||
);
|
||||
assert_eq!(
|
||||
current.credential.expose_to_provider()["access_token"],
|
||||
"fresh-access"
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::profile::archive::{RemoteZip, download};
|
||||
use sha2::{Digest, Sha512};
|
||||
use std::io::Read;
|
||||
use std::io::{Read, Seek, Write};
|
||||
use wiremock::{Mock, MockServer, Request, ResponseTemplate, matchers::any};
|
||||
|
||||
pub(super) async fn serve(body: Vec<u8>, fault: &'static str) -> MockServer {
|
||||
@@ -121,4 +121,46 @@ fn cancelled_parser_stops_reading_its_temporary_file() {
|
||||
assert_eq!(file.read(&mut [0]).unwrap(), 0);
|
||||
drop(guard);
|
||||
assert!(file.read(&mut [0]).is_err());
|
||||
assert!(file.rewind().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn large_zip_member_uses_bounded_ranges_and_streaming_inspection() {
|
||||
let size = 16 * 1024 * 1024 + 5;
|
||||
let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
writer
|
||||
.start_file(
|
||||
"binary",
|
||||
zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Stored),
|
||||
)
|
||||
.unwrap();
|
||||
writer.write_all(&vec![37; size]).unwrap();
|
||||
let server = serve(writer.finish().unwrap().into_inner(), "").await;
|
||||
let client = reqwest::Client::new();
|
||||
let zip = RemoteZip::open(&client, server.uri()).await.unwrap();
|
||||
let count = zip
|
||||
.inspect("binary", size as u64, |reader| {
|
||||
std::io::copy(reader, &mut std::io::sink())
|
||||
.map_err(|e| crate::profile::archive::invalid().with_source(e))
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, size as u64);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let ranges: Vec<_> = requests
|
||||
.iter()
|
||||
.filter_map(|request| request.headers.get("range"))
|
||||
.collect();
|
||||
assert_eq!(ranges.len(), 3);
|
||||
for range in ranges {
|
||||
let (start, end) = range
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.strip_prefix("bytes=")
|
||||
.unwrap()
|
||||
.split_once('-')
|
||||
.unwrap();
|
||||
assert!(end.parse::<u64>().unwrap() - start.parse::<u64>().unwrap() < 16 * 1024 * 1024);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ pub(super) fn asar(version: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
pub(super) fn executable(target: ReleaseTarget, version: &str) -> Vec<u8> {
|
||||
executable_with_changelist(target, version, 1_234_567_890)
|
||||
}
|
||||
|
||||
fn executable_with_changelist(target: ReleaseTarget, version: &str, changelist: u64) -> Vec<u8> {
|
||||
let mut bytes = vec![0; 65_536];
|
||||
let arm = target.arch == Architecture::Arm64;
|
||||
match target.platform {
|
||||
@@ -45,10 +49,17 @@ pub(super) fn executable(target: ReleaseTarget, version: &str) -> Vec<u8> {
|
||||
}
|
||||
// 把版本放在扫描块边界上,覆盖跨块字符串识别
|
||||
bytes.extend_from_slice(format!("{version}\n\0").as_bytes());
|
||||
bytes.extend_from_slice(
|
||||
format!("googlefile:/google_src/files/{changelist}/depot/google3\0").as_bytes(),
|
||||
);
|
||||
bytes
|
||||
}
|
||||
|
||||
pub(super) fn desktop_zip(version: &str) -> Vec<u8> {
|
||||
desktop_zip_with_changelist(version, 1_234_567_890)
|
||||
}
|
||||
|
||||
pub(super) fn desktop_zip_with_changelist(version: &str, changelist: u64) -> Vec<u8> {
|
||||
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let options = zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
@@ -62,6 +73,17 @@ pub(super) fn desktop_zip(version: &str) -> Vec<u8> {
|
||||
version,
|
||||
))
|
||||
.unwrap();
|
||||
zip.start_file(
|
||||
"Antigravity.app/Contents/Resources/bin/language_server",
|
||||
options,
|
||||
)
|
||||
.unwrap();
|
||||
zip.write_all(&executable_with_changelist(
|
||||
crate::profile::Selection::default().target(),
|
||||
version,
|
||||
changelist,
|
||||
))
|
||||
.unwrap();
|
||||
zip.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
@@ -91,8 +113,8 @@ fn cli_binary_requires_target_architecture_and_exact_embedded_version() {
|
||||
arch,
|
||||
};
|
||||
let binary = executable(target, "1.5.16");
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, "1.5.16").is_ok());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, "1.5.15").is_err());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("1.5.16")).is_ok());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("1.5.15")).is_err());
|
||||
let other = ReleaseTarget {
|
||||
arch: if arch == Architecture::Arm64 {
|
||||
Architecture::Amd64
|
||||
@@ -101,23 +123,38 @@ fn cli_binary_requires_target_architecture_and_exact_embedded_version() {
|
||||
},
|
||||
..target
|
||||
};
|
||||
assert!(artifact::verify_binary(binary.as_slice(), other, "1.5.16").is_err());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), other, Some("1.5.16")).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_resource_requires_consistent_file_and_product_versions() {
|
||||
let mut resource = b"\xbd\x04\xef\xfe\0\0\x01\0".to_vec();
|
||||
for word in [2u32 << 16 | 35, 1 << 16, 2 << 16 | 35, 1 << 16] {
|
||||
resource.extend(word.to_le_bytes());
|
||||
fn binary_changelist_requires_one_valid_source_root_and_survives_chunk_boundaries() {
|
||||
let target = crate::profile::Selection::default().target();
|
||||
let mut binary = executable(target, "9.8.7");
|
||||
let marker = b"googlefile:/google_src/files/1234567890/depot/google3\0";
|
||||
binary.truncate(binary.len() - marker.len());
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("9.8.7")).is_err());
|
||||
for split in 1..marker.len() {
|
||||
let mut bytes = binary.clone();
|
||||
bytes.resize(1024 + 2 * 65536 - split, 0);
|
||||
bytes.extend_from_slice(marker);
|
||||
bytes.extend_from_slice(marker);
|
||||
assert_eq!(
|
||||
artifact::verify_binary(bytes.as_slice(), target, Some("9.8.7")).unwrap(),
|
||||
1_234_567_890
|
||||
);
|
||||
}
|
||||
assert!(artifact::windows_version(&resource, "2.35.1").is_ok());
|
||||
resource[4..8].fill(0);
|
||||
assert!(artifact::windows_version(&resource, "2.35.1").is_ok());
|
||||
assert!(artifact::windows_version(&resource, "2.35.2").is_err());
|
||||
resource[16] ^= 1;
|
||||
assert!(artifact::windows_version(&resource, "2.35.1").is_err());
|
||||
for value in ["0", "18446744073709551616", "", "not-a-number"] {
|
||||
let mut bytes = binary.clone();
|
||||
bytes.extend_from_slice(
|
||||
format!("googlefile:/google_src/files/{value}/depot/google3\0").as_bytes(),
|
||||
);
|
||||
assert!(artifact::verify_binary(bytes.as_slice(), target, Some("9.8.7")).is_err());
|
||||
}
|
||||
binary.extend_from_slice(marker);
|
||||
binary.extend_from_slice(b"googlefile:/google_src/files/9876543210/depot/google3\0");
|
||||
assert!(artifact::verify_binary(binary.as_slice(), target, Some("9.8.7")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -132,7 +169,13 @@ fn tar_requires_both_package_and_executable_and_rejects_wrong_version() {
|
||||
Vec::new(),
|
||||
flate2::Compression::fast(),
|
||||
));
|
||||
let mut files = vec![("Antigravity/resources/app.asar", asar("2.35.1"))];
|
||||
let mut files = vec![
|
||||
("Antigravity/resources/app.asar", asar("2.35.1")),
|
||||
(
|
||||
"Antigravity/resources/bin/language_server",
|
||||
executable(target, "2.35.1"),
|
||||
),
|
||||
];
|
||||
if include_executable {
|
||||
files.push(("Antigravity/antigravity", executable(target, "2.35.1")));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Windows 安装器内的版本、架构与 CL 必须来自同一应用包
|
||||
|
||||
use crate::profile::{
|
||||
installer,
|
||||
selection::{Architecture, ClientKind, Platform, ReleaseTarget},
|
||||
};
|
||||
use std::io::Cursor;
|
||||
|
||||
fn target() -> ReleaseTarget {
|
||||
ReleaseTarget {
|
||||
client: ClientKind::Desktop,
|
||||
platform: Platform::Windows,
|
||||
arch: Architecture::Amd64,
|
||||
}
|
||||
}
|
||||
|
||||
fn package(files: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut archive = sevenz_rust2::ArchiveWriter::new(Cursor::new(Vec::new())).unwrap();
|
||||
for (name, body) in files {
|
||||
archive
|
||||
.push_archive_entry(
|
||||
sevenz_rust2::ArchiveEntry::new_file(name),
|
||||
Some(body.as_slice()),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let mut installer = b"MZ fixture installer prefix".to_vec();
|
||||
installer.extend(archive.finish().unwrap().into_inner());
|
||||
installer.extend_from_slice(b"installer trailer");
|
||||
installer
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_archive_requires_matching_version_architecture_and_unique_runtime() {
|
||||
let files = vec![
|
||||
("resources/app.asar", super::artifact::asar("8.2.1")),
|
||||
(
|
||||
"resources/bin/language_server.exe",
|
||||
super::artifact::executable(target(), "internal-version"),
|
||||
),
|
||||
];
|
||||
let bytes = package(&files);
|
||||
assert_eq!(
|
||||
installer::verify(Cursor::new(&bytes), target(), "8.2.1").unwrap(),
|
||||
1_234_567_890
|
||||
);
|
||||
assert!(installer::verify(Cursor::new(&bytes), target(), "8.2.2").is_err());
|
||||
let arm = ReleaseTarget {
|
||||
arch: Architecture::Arm64,
|
||||
..target()
|
||||
};
|
||||
assert!(installer::verify(Cursor::new(&bytes), arm, "8.2.1").is_err());
|
||||
for files in [
|
||||
vec![files[0].clone()],
|
||||
vec![files[1].clone()],
|
||||
vec![files[0].clone(), files[1].clone(), files[1].clone()],
|
||||
] {
|
||||
assert!(installer::verify(Cursor::new(package(&files)), target(), "8.2.1").is_err());
|
||||
}
|
||||
assert!(installer::verify(Cursor::new(&bytes[..40]), target(), "8.2.1").is_err());
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod archive;
|
||||
mod artifact;
|
||||
mod installer;
|
||||
mod release;
|
||||
mod selection;
|
||||
mod verification;
|
||||
|
||||
@@ -10,30 +10,35 @@ fn client_presets_resolve_platform_and_frozen_version() {
|
||||
("linux", "linux", "amd64"),
|
||||
("windows", "windows", "amd64"),
|
||||
] {
|
||||
for (client, subclient, auth) in [
|
||||
("desktop", "hub", ""),
|
||||
("cli", "cli", "; auth_method=consumer"),
|
||||
for (client, subclient, version, cl, auth) in [
|
||||
("desktop", "hub", "2.37.0", "1033035865", ""),
|
||||
(
|
||||
"cli",
|
||||
"cli",
|
||||
"1.5.23",
|
||||
"1035033525",
|
||||
"; auth_method=consumer",
|
||||
),
|
||||
] {
|
||||
let selection = Selection::parse(&object(json!({"client":client,"platform":platform,"versionMode":"latest","clientVersion":null,"arch":null}))).unwrap();
|
||||
let initial = selection
|
||||
.resolve(selection.client.baseline().version)
|
||||
.resolve(selection.client.baseline(), Some(cl.parse().unwrap()))
|
||||
.frozen();
|
||||
let frozen = selection.resolve("2.35.0").frozen();
|
||||
let frozen = selection.resolve("9.8.7", None).frozen();
|
||||
let profile = ClientProfile::from_frozen(&frozen).unwrap();
|
||||
// 发布版本变化后不混入旧 CL,也不把未知版本标记为实测画像
|
||||
assert!(profile.verified_at().is_none());
|
||||
// 发布版本变化后不混入另一个版本的 CL
|
||||
assert_eq!(
|
||||
profile.user_agent(),
|
||||
format!(
|
||||
"antigravity/{subclient}/2.35.0 (aidev_client; os_type={os}; arch={arch}{auth})"
|
||||
"antigravity/{subclient}/9.8.7 (aidev_client; os_type={os}; arch={arch}{auth})"
|
||||
)
|
||||
);
|
||||
let original = ClientProfile::from_frozen(&initial).unwrap();
|
||||
assert!(original.user_agent().contains("; cl="));
|
||||
assert_eq!(
|
||||
original.verified_at().is_some(),
|
||||
(client == "desktop" && platform == "macos")
|
||||
|| (client == "cli" && platform == "linux")
|
||||
original.user_agent(),
|
||||
format!(
|
||||
"antigravity/{subclient}/{version} (aidev_client; os_type={os}; arch={arch}; cl={cl}{auth})"
|
||||
)
|
||||
);
|
||||
assert_ne!(original.user_agent(), profile.user_agent());
|
||||
}
|
||||
@@ -49,20 +54,39 @@ fn fixed_version_rejects_header_injection_and_incomplete_selection() {
|
||||
] {
|
||||
assert!(Selection::parse(&object(value)).is_err());
|
||||
}
|
||||
let selected = Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.17","arch":"arm64"}))).unwrap();
|
||||
let selected = Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.23","arch":"arm64"}))).unwrap();
|
||||
assert_eq!(
|
||||
selected.resolve("9.9.9").user_agent(),
|
||||
"antigravity/cli/1.5.17 (aidev_client; os_type=linux; arch=arm64; cl=1029496841; auth_method=consumer)"
|
||||
selected.resolve("9.9.9", Some(987654321)).user_agent(),
|
||||
"antigravity/cli/1.5.23 (aidev_client; os_type=linux; arch=arm64; auth_method=consumer)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arbitrary_verified_build_is_frozen_without_a_static_version_map() {
|
||||
let selection = Selection::default();
|
||||
let frozen = selection.resolve("41.8.12", Some(9_876_543_210)).frozen();
|
||||
let newer = selection.resolve("41.8.13", Some(9_876_543_211));
|
||||
let profile = ClientProfile::from_frozen(&frozen).unwrap();
|
||||
assert!(profile.user_agent().contains("/41.8.12 "));
|
||||
assert!(profile.user_agent().contains("cl=9876543210"));
|
||||
assert!(newer.user_agent().contains("cl=9876543211"));
|
||||
for version in [selection.client.baseline(), "41.8.12"] {
|
||||
assert!(
|
||||
!selection
|
||||
.resolve(version, None)
|
||||
.user_agent()
|
||||
.contains("cl=")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_prompt_defaults_and_customization_are_frozen_with_the_profile() {
|
||||
let mut selection = Selection::default();
|
||||
let default = selection.resolve("1.5.15");
|
||||
let default = selection.resolve("2.37.0", None);
|
||||
assert!(default.system_prompt.starts_with("You are Antigravity,"));
|
||||
selection.system_prompt = Some("Use the fixture instruction.".into());
|
||||
let frozen = selection.resolve("1.5.15").frozen();
|
||||
let frozen = selection.resolve("2.37.0", None).frozen();
|
||||
selection.system_prompt = Some("New configuration.".into());
|
||||
assert_eq!(
|
||||
ClientProfile::from_frozen(&frozen).unwrap().system_prompt,
|
||||
@@ -70,7 +94,10 @@ fn system_prompt_defaults_and_customization_are_frozen_with_the_profile() {
|
||||
);
|
||||
selection.system_prompt = Some(" \n".into());
|
||||
let reset = Selection::parse(&selection.configuration()).unwrap();
|
||||
assert_eq!(reset.resolve("1.5.15").system_prompt, default.system_prompt);
|
||||
assert_eq!(
|
||||
reset.resolve("2.37.0", None).system_prompt,
|
||||
default.system_prompt
|
||||
);
|
||||
for prompt in ["x".repeat(16 * 1024 + 1), "\0".into()] {
|
||||
selection.system_prompt = Some(prompt);
|
||||
assert!(Selection::parse(&selection.configuration()).is_err());
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
//! 缓存恢复保留事实时间,制品、目标或缓存变化不能借用旧核验结果
|
||||
|
||||
use crate::{
|
||||
profile::{ReleaseService, Selection, artifact::Release, verification::VerificationCache},
|
||||
profile::{
|
||||
ClientProfile, ReleaseService, Selection, artifact::Release, dashboard, default_profile,
|
||||
verification::VerificationCache,
|
||||
},
|
||||
support::profile::cache,
|
||||
};
|
||||
use gateway_admin::model::observability::DesktopReleaseStatus;
|
||||
use gateway_core::{provider_ports::ProviderArtifactProfile, routing::ProviderKind};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
fn provider() -> ProviderKind {
|
||||
ProviderKind::new("antigravity").unwrap()
|
||||
}
|
||||
fn release(server: &wiremock::MockServer, version: &str) -> Release {
|
||||
fn fixture_release(server: &wiremock::MockServer, version: &str) -> Release {
|
||||
Release {
|
||||
version: version.into(),
|
||||
build: Some("123".into()),
|
||||
@@ -26,7 +30,7 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = release(&server, "2.35.1");
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
let first = service
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
@@ -39,31 +43,87 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
|
||||
assert_eq!(same.verified_at, first.verified_at);
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
|
||||
let restarted = VerificationCache::new(provider(), cache.clone());
|
||||
let restored = restarted
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let restored = restarted.load(target).await.unwrap().unwrap();
|
||||
assert_eq!(restored.verified_at, first.verified_at);
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(first.changelist, 1_234_567_890);
|
||||
assert_eq!(restored.changelist, first.changelist);
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), requests);
|
||||
|
||||
let releases = ReleaseService::new(cache).unwrap();
|
||||
releases.publish(target, Some(release.clone()));
|
||||
releases.update().await.unwrap();
|
||||
let releases = ReleaseService::new(cache.clone()).unwrap();
|
||||
releases.restore().await;
|
||||
let restored = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(restored.version, release.version);
|
||||
assert!(restored.user_agent.contains("cl=1234567890"));
|
||||
assert_eq!(restored.verified_at, Some(first.verified_at));
|
||||
assert_eq!(
|
||||
crate::profile::dashboard(&Selection::default(), &releases).verified_at,
|
||||
restored.release.unwrap().status,
|
||||
DesktopReleaseStatus::Unchecked
|
||||
);
|
||||
releases.observe(target, Some(release));
|
||||
releases.update().await.unwrap();
|
||||
assert_eq!(cache.writes.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), requests);
|
||||
assert_eq!(
|
||||
dashboard(&Selection::default(), &releases).verified_at,
|
||||
Some(first.verified_at)
|
||||
);
|
||||
let new_release = Release {
|
||||
version: "2.36.0".into(),
|
||||
..release
|
||||
};
|
||||
releases.publish(target, Some(new_release));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn latest_profile_switches_version_and_changelist_only_after_verified_publication() {
|
||||
let old_server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
|
||||
let new_server = super::archive::serve(
|
||||
super::artifact::desktop_zip_with_changelist("2.36.0", 2_345_678_901),
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let cache = cache();
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let target = Selection::default().target();
|
||||
let client = reqwest::Client::new();
|
||||
let old = service
|
||||
.verify(
|
||||
&client,
|
||||
target,
|
||||
&fixture_release(&old_server, "2.35.1"),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let new_release = fixture_release(&new_server, "2.36.0");
|
||||
let releases = ReleaseService::new(cache.clone()).unwrap();
|
||||
releases.restore().await;
|
||||
let before = dashboard(&Selection::default(), &releases);
|
||||
let frozen = default_profile(&releases).frozen();
|
||||
releases.observe(target, Some(new_release.clone()));
|
||||
let pending = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(pending.user_agent, before.user_agent);
|
||||
let observation = pending.release.unwrap();
|
||||
assert_eq!(observation.status, DesktopReleaseStatus::UpdateAvailable);
|
||||
assert_eq!(observation.latest_version.as_deref(), Some("2.36.0"));
|
||||
|
||||
cache.fail.store(true, Ordering::SeqCst);
|
||||
assert!(releases.update().await.is_err());
|
||||
assert!(
|
||||
crate::profile::dashboard(&Selection::default(), &releases)
|
||||
.verified_at
|
||||
.is_none()
|
||||
let failed = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(failed.user_agent, before.user_agent);
|
||||
assert_eq!(failed.verified_at, Some(old.verified_at));
|
||||
assert_eq!(failed.release.unwrap().status, DesktopReleaseStatus::Failed);
|
||||
|
||||
cache.fail.store(false, Ordering::SeqCst);
|
||||
let new = service
|
||||
.verify(&client, target, &new_release, Some(&old))
|
||||
.await
|
||||
.unwrap();
|
||||
releases.update().await.unwrap();
|
||||
let after = dashboard(&Selection::default(), &releases);
|
||||
assert_eq!(after.version, new_release.version);
|
||||
assert!(after.user_agent.contains("cl=2345678901"));
|
||||
assert_eq!(after.verified_at, Some(new.verified_at));
|
||||
assert_eq!(after.release.unwrap().status, DesktopReleaseStatus::Current);
|
||||
assert_eq!(
|
||||
ClientProfile::from_frozen(&frozen).unwrap().user_agent(),
|
||||
before.user_agent
|
||||
);
|
||||
}
|
||||
|
||||
@@ -74,7 +134,7 @@ async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = release(&server, "2.35.1");
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
service
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
@@ -132,7 +192,7 @@ async fn version_disagreement_leaves_the_previous_cache_intact() {
|
||||
let service = VerificationCache::new(provider(), cache.clone());
|
||||
let client = reqwest::Client::new();
|
||||
let target = Selection::default().target();
|
||||
let release = release(&server, "2.35.1");
|
||||
let release = fixture_release(&server, "2.35.1");
|
||||
let first = service
|
||||
.verify(&client, target, &release, None)
|
||||
.await
|
||||
|
||||
@@ -31,7 +31,7 @@ use wiremock::{
|
||||
};
|
||||
|
||||
fn frozen_profile() -> OpaqueProviderData {
|
||||
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null}))).unwrap().resolve("9.9.9").frozen()
|
||||
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null}))).unwrap().resolve("9.9.9", None).frozen()
|
||||
}
|
||||
|
||||
async fn released(fixture: &Fixture) {
|
||||
@@ -528,13 +528,14 @@ async fn connection_probe_reports_google_rejection_without_verification_links()
|
||||
async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() {
|
||||
for (status, kind) in [
|
||||
(401, ProviderErrorKind::Unauthorized),
|
||||
(403, ProviderErrorKind::PermissionDenied),
|
||||
(429, ProviderErrorKind::RateLimited),
|
||||
] {
|
||||
let upstream = MockServer::start().await;
|
||||
mock_project(&upstream).await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.and(body_partial_json(json!({"project":"probe-project"})))
|
||||
.respond_with(ResponseTemplate::new(status).insert_header("retry-after", "30"))
|
||||
.respond_with(ResponseTemplate::new(status).insert_header("retry-after", "30").set_body_json(if status == 403 {json!({"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}})} else {json!({})}))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
@@ -560,6 +561,17 @@ async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feed
|
||||
assert_eq!(error.upstream_status(), Some(status));
|
||||
assert!(!fixture.store.expired.load(Ordering::SeqCst));
|
||||
assert!(fixture.store.cooldowns.lock().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.feedback
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
//! Google 拒绝的协议交付、账号范围与查询反馈合同
|
||||
|
||||
use crate::support::{Fixture, context, request};
|
||||
use futures::TryStreamExt;
|
||||
use gateway_core::{
|
||||
account::{AccountErrorReason, CredentialState, ProviderAccountId, ProviderAccountStore},
|
||||
engine::provider::Provider,
|
||||
error::ProviderErrorKind as Kind,
|
||||
lifecycle::CancellationToken,
|
||||
};
|
||||
use serde_json::json;
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_late_stream_denial_finishes_with_an_error_frame_and_disables_the_account() {
|
||||
let server = MockServer::start().await;
|
||||
let rejection = json!({"error":{"code":7,"status":"PERMISSION_DENIED","message":"Verify account.","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}});
|
||||
let body = format!(
|
||||
"data: {}\n\ndata: {rejection}\n\n",
|
||||
json!({"response":{"candidates":[{"content":{"parts":[{"text":"partial"}]}}]}})
|
||||
);
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(body, "text/event-stream"))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let mut stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(true),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first = stream.try_next().await.unwrap().unwrap();
|
||||
assert!(
|
||||
first
|
||||
.wire_event()
|
||||
.unwrap()
|
||||
.data()
|
||||
.to_string()
|
||||
.contains("partial")
|
||||
);
|
||||
let mut error = stream.try_next().await.unwrap_err();
|
||||
assert!(error.retry_is_prohibited());
|
||||
let events = error.take_atomic_client_events();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(
|
||||
events[0].wire_event().unwrap().data()["error"]["details"][0]["reason"],
|
||||
"VALIDATION_REQUIRED"
|
||||
);
|
||||
assert!(stream.try_next().await.unwrap().is_none());
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Invalid
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn count_tokens_recognizes_a_success_status_containing_an_rpc_denial() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{Operation, RawJsonPayload, TokenCountRequest},
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:countTokens")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"error":{"code":7,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}}))).expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let input = ProviderRequest::new(
|
||||
Operation::CountTokens(TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new("genai", br#"{"contents":[]}"#.as_slice().into()).unwrap(),
|
||||
)),
|
||||
request(false).candidate().clone(),
|
||||
);
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
input,
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), Kind::PermissionDenied);
|
||||
assert_eq!(
|
||||
error.client_visible_upstream_response().unwrap().status(),
|
||||
403
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.last_error_reason(),
|
||||
Some(AccountErrorReason::AccountUnverified)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn structured_denials_preserve_protocol_and_only_suspend_the_confirmed_account() {
|
||||
for (status, reason, state, error_reason) in [
|
||||
(
|
||||
403,
|
||||
"VALIDATION_REQUIRED",
|
||||
CredentialState::Invalid,
|
||||
Some(AccountErrorReason::AccountUnverified),
|
||||
),
|
||||
(
|
||||
403,
|
||||
"TOS_VIOLATION",
|
||||
CredentialState::Banned,
|
||||
Some(AccountErrorReason::AccountBanned),
|
||||
),
|
||||
(
|
||||
403,
|
||||
"WORKSPACE_TOS_VIOLATION_CONTACT_SUPPORT",
|
||||
CredentialState::Banned,
|
||||
Some(AccountErrorReason::AccountBanned),
|
||||
),
|
||||
(
|
||||
200,
|
||||
"WORKSPACE_TOS_VIOLATION_CONTACT_SUPPORT",
|
||||
CredentialState::Banned,
|
||||
Some(AccountErrorReason::AccountBanned),
|
||||
),
|
||||
(
|
||||
403,
|
||||
"ACCESS_TOKEN_SCOPE_INSUFFICIENT",
|
||||
CredentialState::Ready,
|
||||
None,
|
||||
),
|
||||
(403, "PROJECT_DISABLED", CredentialState::Ready, None),
|
||||
(403, "AI_POLICY_REQUIRED", CredentialState::Ready, None),
|
||||
(
|
||||
200,
|
||||
"VALIDATION_REQUIRED",
|
||||
CredentialState::Invalid,
|
||||
Some(AccountErrorReason::AccountUnverified),
|
||||
),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let metadata = json!({
|
||||
"validation_url":"https://accounts.example.test/verify?nonce=private",
|
||||
"appeal_url":"https://accounts.example.test/appeal?nonce=private",
|
||||
"appeal_url_link_text":"Submit Appeal",
|
||||
"uiMessage":"Account action required."
|
||||
});
|
||||
let mut body = json!({"error":{"code": if status == 200 {7} else {403},"status":"PERMISSION_DENIED","message":"Verify your account to continue.","details":[
|
||||
{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"ACCESS_TOKEN_SCOPE_INSUFFICIENT"},
|
||||
{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":reason,"metadata":metadata}
|
||||
]}});
|
||||
if state == CredentialState::Banned {
|
||||
body["error"]["details"].as_array_mut().unwrap().push(json!({"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}));
|
||||
} else if reason == "AI_POLICY_REQUIRED" {
|
||||
body["error"]["details"].as_array_mut().unwrap().push(json!({"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"PROJECT_DISABLED"}));
|
||||
}
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(status).set_body_json(body))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let fixture = Fixture::with_two_accounts(&server.uri());
|
||||
let mut error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), Kind::PermissionDenied);
|
||||
assert_eq!(error.upstream_status(), Some(403));
|
||||
assert_eq!(
|
||||
error.retry_is_prohibited(),
|
||||
error_reason.is_some() || reason == "AI_POLICY_REQUIRED"
|
||||
);
|
||||
let fields = error.upstream_failure_fields().unwrap();
|
||||
assert_eq!(fields.code.as_deref(), Some(reason));
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
assert_eq!(response.status(), 403);
|
||||
let response: serde_json::Value = serde_json::from_slice(response.body()).unwrap();
|
||||
assert_eq!(response["error"]["code"], 403);
|
||||
assert_eq!(response["error"]["status"], "PERMISSION_DENIED");
|
||||
assert_eq!(response["error"]["details"][0]["reason"], reason);
|
||||
assert_eq!(
|
||||
response["error"]["message"],
|
||||
"Verify your account to continue."
|
||||
);
|
||||
assert!(response["error"]["details"][0].get("metadata").is_none());
|
||||
assert!(!response.to_string().contains("nonce=private"));
|
||||
let raw: serde_json::Value =
|
||||
serde_json::from_str(error.raw_upstream_error().unwrap().as_str()).unwrap();
|
||||
assert_eq!(raw["error"]["details"][1]["metadata"], metadata);
|
||||
let events = error.take_atomic_client_events();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].wire_event().unwrap().data(), &response);
|
||||
{
|
||||
let loaded = fixture.store.primary().loaded.lock().unwrap();
|
||||
assert_eq!(loaded.account.credential_state(), state);
|
||||
assert_eq!(loaded.account.last_error_reason(), error_reason);
|
||||
}
|
||||
let standby = fixture
|
||||
.store
|
||||
.get_account(&ProviderAccountId::new("acct_standby").unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(standby.credential_state(), CredentialState::Ready);
|
||||
if error_reason.is_some() {
|
||||
assert_eq!(
|
||||
fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new()
|
||||
)
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.kind(),
|
||||
Kind::NoEligibleAccount
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn not_found_preserves_the_upstream_error_without_penalizing_the_account() {
|
||||
for stream in [false, true] {
|
||||
let server = MockServer::start().await;
|
||||
let body = json!({"error":{"code":404,"status":"NOT_FOUND","message":"Requested entity was not found."}});
|
||||
Mock::given(path(if stream {
|
||||
"/v1internal:streamGenerateContent"
|
||||
} else {
|
||||
"/v1internal:generateContent"
|
||||
}))
|
||||
.respond_with(ResponseTemplate::new(404).set_body_json(&body))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(stream),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.37.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
assert_eq!(response.status(), 404);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(response.body()).unwrap(),
|
||||
body
|
||||
);
|
||||
assert_eq!(
|
||||
error.upstream_failure_fields().unwrap().code.as_deref(),
|
||||
Some("404")
|
||||
);
|
||||
let loaded = fixture.store.primary().loaded.lock().unwrap();
|
||||
assert_eq!(loaded.account.credential_state(), CredentialState::Ready);
|
||||
assert_eq!(loaded.account.last_error_reason(), None);
|
||||
assert!(fixture.store.cooldowns.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn untyped_and_sensitive_denials_cannot_change_account_state_or_escape_diagnostics() {
|
||||
for (typed, message) in [(false, "VALIDATION_REQUIRED"), (true, "fixture-access")] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(403).set_body_json(json!({"error":{"status":"PERMISSION_DENIED","message":message,"details":[{"@type":if typed {"type.googleapis.com/google.rpc.ErrorInfo"} else {"unknown"},"reason":"VALIDATION_REQUIRED"}]}})))
|
||||
.expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
assert!(error.upstream_code().is_none());
|
||||
assert!(
|
||||
!String::from_utf8_lossy(error.client_visible_upstream_response().unwrap().body())
|
||||
.contains("fixture-access")
|
||||
);
|
||||
assert_eq!(error.raw_upstream_error().is_some(), !typed);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resource_queries_share_denial_state_and_background_queries_stop() {
|
||||
for (quota, api_key) in [(false, false), (true, false), (false, true)] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path(if api_key {"/v1beta/models"} else {"/v1internal:loadCodeAssist"}))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"error":{"code":7,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}})))
|
||||
.expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
if api_key {
|
||||
fixture
|
||||
.store
|
||||
.use_api_key(&format!("{}/v1beta", server.uri()));
|
||||
}
|
||||
let account = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.clone();
|
||||
if quota {
|
||||
assert!(fixture.quota.refresh(account.id()).await.is_err());
|
||||
} else {
|
||||
assert!(
|
||||
fixture
|
||||
.catalog
|
||||
.account_models(account.id(), true)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.last_error_reason(),
|
||||
Some(AccountErrorReason::AccountUnverified)
|
||||
);
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
if !api_key {
|
||||
fixture
|
||||
.quota
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
fixture
|
||||
.catalog
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
fixture
|
||||
.catalog
|
||||
.account_models(account.id(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_capacity_and_symbolic_rpc_errors_keep_distinct_facts() {
|
||||
for (status, code, rpc, reason, kind, mapped) in [
|
||||
(
|
||||
429,
|
||||
Some(429),
|
||||
"RESOURCE_EXHAUSTED",
|
||||
"QUOTA_EXHAUSTED",
|
||||
Kind::QuotaExhausted,
|
||||
429,
|
||||
),
|
||||
(
|
||||
429,
|
||||
Some(429),
|
||||
"RESOURCE_EXHAUSTED",
|
||||
"MODEL_CAPACITY_EXHAUSTED",
|
||||
Kind::RateLimited,
|
||||
429,
|
||||
),
|
||||
(
|
||||
503,
|
||||
Some(503),
|
||||
"UNAVAILABLE",
|
||||
"MODEL_CAPACITY_EXHAUSTED",
|
||||
Kind::UpstreamCapacityUnavailable,
|
||||
503,
|
||||
),
|
||||
(
|
||||
200,
|
||||
Some(8),
|
||||
"RESOURCE_EXHAUSTED",
|
||||
"RATE_LIMIT_EXCEEDED",
|
||||
Kind::RateLimited,
|
||||
429,
|
||||
),
|
||||
(
|
||||
200,
|
||||
None,
|
||||
"PERMISSION_DENIED",
|
||||
"ACCESS_TOKEN_SCOPE_INSUFFICIENT",
|
||||
Kind::PermissionDenied,
|
||||
403,
|
||||
),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(status).set_body_json(json!({"error":{"code":code,"status":rpc,"message":"Rejected.","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":reason},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"30s"}]}})))
|
||||
.expect(1).mount(&server).await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0", None)
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), kind);
|
||||
assert_eq!(error.upstream_status(), Some(mapped));
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(response.body()).unwrap();
|
||||
assert_eq!(body["error"]["details"][1]["retryDelay"], "30.000000000s");
|
||||
assert!(
|
||||
response
|
||||
.headers()
|
||||
.iter()
|
||||
.any(|header| header.name() == "retry-after" && header.value().as_ref() == b"30")
|
||||
);
|
||||
assert_eq!(
|
||||
error.upstream_failure_fields().unwrap().code.as_deref(),
|
||||
Some(reason)
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.credential_state(),
|
||||
CredentialState::Ready
|
||||
);
|
||||
assert_eq!(
|
||||
fixture.store.cooldowns.lock().unwrap().len(),
|
||||
usize::from(mapped != 403)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,10 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let profile = crate::profile::Selection::parse(&crate::profile::object(json!({
|
||||
"client":"cli", "platform":"linux", "versionMode":"fixed", "clientVersion":"1.5.17"
|
||||
"client":"cli", "platform":"linux", "versionMode":"fixed", "clientVersion":"1.5.23"
|
||||
})))
|
||||
.unwrap()
|
||||
.resolve("1.5.17")
|
||||
.resolve("1.5.23", Some(1200034567))
|
||||
.frozen();
|
||||
let ctx = || {
|
||||
context(
|
||||
@@ -50,7 +50,6 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
"authorization",
|
||||
"cookie",
|
||||
"cookie2",
|
||||
"user-agent",
|
||||
"x-goog-api-key",
|
||||
"x-goog-user-project",
|
||||
"x-goog-api-client",
|
||||
@@ -67,6 +66,12 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
.map(|name| json!([name, STANDARD.encode("forbidden")]))
|
||||
.collect();
|
||||
headers.extend([
|
||||
// 下游客户端的管理员策略和认证类型不能覆盖当前账号的个人 OAuth 画像
|
||||
json!([
|
||||
"user-agent",
|
||||
STANDARD
|
||||
.encode("antigravity/cli/9.9.9 (auth_method=gateway; datacollection_opt_in=false)")
|
||||
]),
|
||||
json!(["x-business-extension", STANDARD.encode(b"first\x80")]),
|
||||
json!(["x-business-extension", STANDARD.encode("second")]),
|
||||
json!(["traceparent", STANDARD.encode("original-trace")]),
|
||||
@@ -75,7 +80,7 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
for (protocol, body) in [
|
||||
(
|
||||
gateway_protocol::genai::GENAI_PROTOCOL,
|
||||
json!({"contents":[]}),
|
||||
json!({"contents":[], "hasFingerprintSet":true, "has_fingerprint_set":true}),
|
||||
),
|
||||
(
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
@@ -97,7 +102,7 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
Operation::CountTokens(TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new(
|
||||
gateway_protocol::genai::GENAI_PROTOCOL,
|
||||
br#"{"contents":[]}"#.as_slice().into(),
|
||||
br#"{"contents":[],"hasFingerprintSet":true}"#.as_slice().into(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(metadata.as_object().unwrap().clone()),
|
||||
@@ -116,6 +121,9 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 3);
|
||||
for request in requests {
|
||||
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
|
||||
assert!(body["request"].get("hasFingerprintSet").is_none());
|
||||
assert!(body["request"].get("has_fingerprint_set").is_none());
|
||||
let values: Vec<_> = request
|
||||
.headers
|
||||
.get_all("x-business-extension")
|
||||
@@ -128,10 +136,10 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
assert_eq!(request.headers["content-type"], "application/json");
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
"antigravity/cli/1.5.17 (aidev_client; os_type=linux; arch=amd64; cl=1029496841; auth_method=consumer)"
|
||||
"antigravity/cli/1.5.23 (aidev_client; os_type=linux; arch=amd64; cl=1200034567; auth_method=consumer)"
|
||||
);
|
||||
for name in forbidden {
|
||||
if !matches!(name, "authorization" | "user-agent" | "content-length") {
|
||||
if !matches!(name, "authorization" | "content-length") {
|
||||
assert!(!request.headers.contains_key(name), "unexpected {name}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
mod affinity;
|
||||
mod api_key;
|
||||
mod execution;
|
||||
mod feedback;
|
||||
mod headers;
|
||||
mod middleware;
|
||||
mod round_robin;
|
||||
|
||||
@@ -144,7 +144,7 @@ impl ProviderCredentialStatePort for MemoryPorts {
|
||||
&'a self,
|
||||
_account_id: &'a ProviderAccountId,
|
||||
) -> BoxFuture<'a, Result<(), ProviderStoreError>> {
|
||||
unreachable!("unused fixture port: ProviderCredentialStatePort::clear_refresh_backoff")
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,9 +548,43 @@ impl ProviderAccountStore for MemoryPorts {
|
||||
}
|
||||
async fn compare_and_swap_credential(
|
||||
&self,
|
||||
_update: CredentialCasUpdate,
|
||||
update: CredentialCasUpdate,
|
||||
) -> Result<CredentialCasOutcome, StoreError> {
|
||||
unreachable!("unused fixture port: ProviderAccountStore::compare_and_swap_credential")
|
||||
let update = update.into_parts();
|
||||
let entry = &self.accounts[&update.account_id];
|
||||
let mut loaded = entry.loaded.lock().unwrap();
|
||||
if loaded.account.revision() != update.expected_revision {
|
||||
return Ok(CredentialCasOutcome::Conflict);
|
||||
}
|
||||
let revision = CredentialRevision::new(update.expected_revision.get() + 1).unwrap();
|
||||
let previous = &loaded.account;
|
||||
let (state, reason, message) = update.account_state.map_or_else(
|
||||
|| {
|
||||
(
|
||||
previous.credential_state(),
|
||||
previous.last_error_reason(),
|
||||
previous.last_error_message().map(str::to_owned),
|
||||
)
|
||||
},
|
||||
|state| (state.credential_state, state.error_reason, state.message),
|
||||
);
|
||||
loaded.account = ProviderAccount::new(
|
||||
previous.id().clone(),
|
||||
previous.provider().clone(),
|
||||
previous.name().into(),
|
||||
previous.upstream_user_id().map(str::to_owned),
|
||||
previous.authentication_kind().into(),
|
||||
revision,
|
||||
if update.preserve_access_token_expiry {
|
||||
previous.access_token_expires_at()
|
||||
} else {
|
||||
update.access_token_expires_at
|
||||
},
|
||||
)
|
||||
.with_account_facts(previous.enabled(), state, previous.quota(), reason, message)
|
||||
.with_refresh_schedule(update.has_refresh_token, update.next_refresh_at);
|
||||
loaded.credential = update.credential;
|
||||
Ok(CredentialCasOutcome::Updated(revision))
|
||||
}
|
||||
async fn get_quotas(
|
||||
&self,
|
||||
|
||||
@@ -23,9 +23,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
let (origin, access_token) = refreshed_credential(&server).await;
|
||||
let profile =
|
||||
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
|
||||
// 官方 macOS arm64 Desktop 2.34.0 在默认参数下实际发送的已认证请求头
|
||||
let user_agent =
|
||||
"antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64; cl=1026637980)";
|
||||
let user_agent = "antigravity/hub/2.37.0 (aidev_client; os_type=darwin; arch=arm64)";
|
||||
let client = CloudCodeClient::new(&origin, None, &profile).unwrap();
|
||||
let post = |p| {
|
||||
Mock::given(method("POST"))
|
||||
|
||||
@@ -22,7 +22,7 @@ use wiremock::{
|
||||
};
|
||||
|
||||
fn profile() -> OpaqueProviderData {
|
||||
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null,"systemPrompt":"count identity"}))).unwrap().resolve("9.9.9").frozen()
|
||||
Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null,"systemPrompt":"count identity"}))).unwrap().resolve("9.9.9", None).frozen()
|
||||
}
|
||||
|
||||
fn counted(protocol: &str, body: Value) -> gateway_core::engine::provider::ProviderRequest {
|
||||
|
||||
@@ -165,7 +165,7 @@ async fn repeated_account_reuses_tcp_without_caching_token_project_or_prompt() {
|
||||
let peer = KeepAlivePeer::start().await;
|
||||
let pool = ClientPool::default();
|
||||
let account = account("acct_one", 1);
|
||||
let mut profile = Selection::default().resolve("2.34.0");
|
||||
let mut profile = Selection::default().resolve("2.34.0", None);
|
||||
for index in 0..5 {
|
||||
profile.system_prompt = format!("fixture prompt {index}");
|
||||
generate(
|
||||
@@ -202,8 +202,8 @@ async fn repeated_account_reuses_tcp_without_caching_token_project_or_prompt() {
|
||||
async fn account_revision_and_user_agent_isolate_connection_pools() {
|
||||
let peer = KeepAlivePeer::start().await;
|
||||
let pool = ClientPool::default();
|
||||
let profile = Selection::default().resolve("2.34.0");
|
||||
let changed_profile = Selection::default().resolve("2.35.0");
|
||||
let profile = Selection::default().resolve("2.34.0", None);
|
||||
let changed_profile = Selection::default().resolve("2.35.0", None);
|
||||
for (id, revision, profile) in [
|
||||
("acct_one", 1, &profile),
|
||||
("acct_two", 1, &profile),
|
||||
@@ -233,7 +233,7 @@ async fn proxy_routes_keep_independent_pools_and_preserve_the_direct_pool() {
|
||||
let first_proxy = KeepAlivePeer::start().await;
|
||||
let second_proxy = KeepAlivePeer::start().await;
|
||||
let pool = ClientPool::default();
|
||||
let profile = Selection::default().resolve("2.34.0");
|
||||
let profile = Selection::default().resolve("2.34.0", None);
|
||||
for proxy in [
|
||||
None,
|
||||
Some(&first_proxy.origin),
|
||||
@@ -264,7 +264,7 @@ async fn proxy_routes_keep_independent_pools_and_preserve_the_direct_pool() {
|
||||
async fn cache_evicts_the_least_recently_used_client_after_sixty_four_identities() {
|
||||
let peer = KeepAlivePeer::start().await;
|
||||
let pool = ClientPool::default();
|
||||
let profile = Selection::default().resolve("2.34.0");
|
||||
let profile = Selection::default().resolve("2.34.0", None);
|
||||
for index in (0..64).chain([0, 64, 0, 1]) {
|
||||
generate(
|
||||
&pool,
|
||||
|
||||
@@ -18,7 +18,7 @@ async fn oauth_identity_edits_preserve_remaining_json_bytes_and_duplicate_busine
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&selection.resolve("2.34.0"),
|
||||
&selection.resolve("2.34.0", None),
|
||||
)
|
||||
.unwrap();
|
||||
let instruction = r#""systemInstruction":{"parts":[{"text":"OAuth fixture"}]}"#;
|
||||
@@ -102,7 +102,7 @@ async fn generation_and_count_preserve_client_rules_and_instruction_metadata() {
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&selection.resolve("2.34.0"),
|
||||
&selection.resolve("2.34.0", None),
|
||||
)
|
||||
.unwrap();
|
||||
// CLI 1.5.18 Gateway 请求把全局和项目规则放在系统指令中
|
||||
@@ -146,3 +146,65 @@ async fn generation_and_count_preserve_client_rules_and_instruction_metadata() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oauth_filters_local_fingerprint_state_without_changing_business_data_or_key_upstreams() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(wiremock::matchers::any())
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(json!({"response":{},"totalTokens":1})),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let profile = profile::Selection::default().resolve("8.4.2", Some(1_234_567_890));
|
||||
let oauth = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
|
||||
let api_key = crate::transport::GenAiClient::new(server.uri().parse().unwrap(), None).unwrap();
|
||||
for state in [
|
||||
r#""hasFingerprintSet":true,"has_fingerprint_set":false,"hasFingerprintSet":false,"#,
|
||||
r#""has_fingerprint_set":true,"hasFingerprintSet":false,"#,
|
||||
"",
|
||||
] {
|
||||
let body = format!(
|
||||
r#"{{{state}"contents":[{{"parts":[{{"functionCall":{{"name":"tool","args":{{"hasFingerprintSet":true,"has_fingerprint_set":false}}}}}}]}}],"tools":[{{"functionDeclarations":[{{"name":"tool","parameters":{{"type":"OBJECT","properties":{{"hasFingerprintSet":{{"type":"BOOLEAN"}}}}}}}}]}}]}}"#
|
||||
);
|
||||
oauth
|
||||
.generate(
|
||||
"project",
|
||||
"model",
|
||||
"oauth-token",
|
||||
body.as_bytes(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
oauth
|
||||
.count_tokens("oauth-token", body.as_bytes(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
api_key
|
||||
.execute(
|
||||
"model",
|
||||
"upstream-key",
|
||||
body.as_bytes(),
|
||||
"generateContent",
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let key_request = requests.last().unwrap();
|
||||
assert_eq!(key_request.body, body.as_bytes());
|
||||
assert_eq!(key_request.headers["x-goog-api-key"], "upstream-key");
|
||||
let original: serde_json::Value = serde_json::from_str(&body).unwrap();
|
||||
for request in requests.iter().rev().skip(1).take(2) {
|
||||
let envelope: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
|
||||
let request_body = &envelope["request"];
|
||||
assert!(request_body.get("hasFingerprintSet").is_none());
|
||||
assert!(request_body.get("has_fingerprint_set").is_none());
|
||||
assert_eq!(request_body["contents"], original["contents"]);
|
||||
assert_eq!(request_body["tools"], original["tools"]);
|
||||
assert_eq!(request.headers["authorization"], "Bearer oauth-token");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ async fn fixture(reply: &str) -> (MockServer, CloudCodeClient) {
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&profile::Selection::default().resolve("2.34.0"),
|
||||
&profile::Selection::default().resolve("2.34.0", None),
|
||||
)
|
||||
.unwrap();
|
||||
(server, client)
|
||||
|
||||
@@ -27,7 +27,7 @@ async fn client() -> (MockServer, CloudCodeClient) {
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&profile::Selection::default().resolve("2.34.0"),
|
||||
&profile::Selection::default().resolve("2.34.0", None),
|
||||
)
|
||||
.unwrap();
|
||||
(server, client)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 额度权威读取、刷新、错误反馈与服务组装
|
||||
|
||||
use super::*;
|
||||
use gateway_core::lifecycle::CancellationToken;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum QuotaRefreshAuthority {
|
||||
@@ -145,16 +146,36 @@ impl CodexCredentialQuotaService {
|
||||
&self,
|
||||
now: SystemTime,
|
||||
) -> Result<CodexQuotaSyncSummary, CodexCredentialQuotaError> {
|
||||
let mut accounts = self.repository.list_for_provider(true).await?;
|
||||
self.synchronize_until(now, &CancellationToken::new()).await
|
||||
}
|
||||
|
||||
pub async fn synchronize_until(
|
||||
&self,
|
||||
now: SystemTime,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<CodexQuotaSyncSummary, CodexCredentialQuotaError> {
|
||||
let mut summary = CodexQuotaSyncSummary::default();
|
||||
let Some(accounts) = cancellation
|
||||
.run_until_cancelled(self.repository.list_for_provider(true))
|
||||
.await
|
||||
else {
|
||||
return Ok(summary);
|
||||
};
|
||||
let mut accounts = accounts?;
|
||||
accounts.retain(|account| {
|
||||
account.authentication_kind() == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH
|
||||
});
|
||||
let mut summary = CodexQuotaSyncSummary::default();
|
||||
let account_ids = accounts
|
||||
.iter()
|
||||
.map(|account| account.id().clone())
|
||||
.collect::<Vec<_>>();
|
||||
let observed = self.store.get_quotas(&account_ids).await?;
|
||||
let Some(observed) = cancellation
|
||||
.run_until_cancelled(self.store.get_quotas(&account_ids))
|
||||
.await
|
||||
else {
|
||||
return Ok(summary);
|
||||
};
|
||||
let observed = observed?;
|
||||
let observed_snapshots = observed
|
||||
.iter()
|
||||
.filter_map(|obs| {
|
||||
@@ -190,20 +211,30 @@ impl CodexCredentialQuotaService {
|
||||
if accounts.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
let client = match self.global_profile_client().await {
|
||||
Ok(client) => client,
|
||||
Err(error) => {
|
||||
let client = match cancellation
|
||||
.run_until_cancelled(self.global_profile_client())
|
||||
.await
|
||||
{
|
||||
Some(Ok(client)) => client,
|
||||
other => {
|
||||
// 身份配置失败尚未发出请求,也需要释放已预留的首查任务
|
||||
self.scheduling.defer_failed_initial_refreshes(
|
||||
&pending_initial,
|
||||
self.initial_sync_delays.as_ref(),
|
||||
);
|
||||
return Err(error);
|
||||
return other.transpose().map(|_| summary);
|
||||
}
|
||||
};
|
||||
for account in accounts {
|
||||
let observed_at = SystemTime::now();
|
||||
match self.fetch_usage(&client, &account).await {
|
||||
// 查询及其重试可以取消,已取得的额度事实继续完成本账号写入
|
||||
let Some(usage) = cancellation
|
||||
.run_until_cancelled(self.fetch_usage(&client, &account))
|
||||
.await
|
||||
else {
|
||||
break;
|
||||
};
|
||||
match usage {
|
||||
Ok(FetchedCodexQuota { account, value }) => {
|
||||
// 单账号解析或落库失败只影响该账号;其余账号继续同步
|
||||
match self
|
||||
|
||||
@@ -12,6 +12,7 @@ use gateway_core::error::ErrorSource;
|
||||
use gateway_core::account::{
|
||||
AccountErrorReason, CredentialState, ProviderAccount, ProviderAccountId, ProviderRefreshQuery,
|
||||
};
|
||||
use gateway_core::lifecycle::CancellationToken;
|
||||
use gateway_core::provider_ports::{
|
||||
ProviderCredentialStatePort, ProviderLeaseAcquisition, ProviderLeasePort, ProviderLeaseRequest,
|
||||
ProviderRefreshCapacityRequest, ProviderRefreshLeaseRequest, ProviderRefreshPolicy,
|
||||
@@ -220,17 +221,42 @@ impl CodexCredentialRefreshService {
|
||||
pub async fn refresh_due(
|
||||
&self,
|
||||
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
|
||||
self.refresh_due_excluding(&BTreeSet::new()).await
|
||||
self.refresh_due_until(&CancellationToken::new()).await
|
||||
}
|
||||
|
||||
pub async fn refresh_due_until(
|
||||
&self,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
|
||||
self.refresh_batch(&BTreeSet::new(), cancellation).await
|
||||
}
|
||||
|
||||
pub async fn refresh_due_excluding(
|
||||
&self,
|
||||
excluded: &BTreeSet<ProviderAccountId>,
|
||||
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
|
||||
let policy = self.runtime_policy.load_refresh_policy().await?;
|
||||
let (due, mut outcomes) = self.list_due_refresh(excluded, policy).await?;
|
||||
self.refresh_batch(excluded, &CancellationToken::new())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn refresh_batch(
|
||||
&self,
|
||||
excluded: &BTreeSet<ProviderAccountId>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
|
||||
let load_candidates = async {
|
||||
let policy = self.runtime_policy.load_refresh_policy().await?;
|
||||
let (due, outcomes) = self.list_due_refresh(excluded, policy).await?;
|
||||
Ok::<_, CodexCredentialRefreshError>((policy, due, outcomes))
|
||||
};
|
||||
let Some(batch) = cancellation.run_until_cancelled(load_candidates).await else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let (policy, due, mut outcomes) = batch?;
|
||||
outcomes.reserve(due.len());
|
||||
let refreshed = stream::iter(due.into_iter().map(|credential| async move {
|
||||
// 停止领取新账号,已发出的令牌交换继续写回
|
||||
let candidates = due.into_iter().take_while(|_| !cancellation.is_cancelled());
|
||||
let refreshed = stream::iter(candidates.map(|credential| async move {
|
||||
let account_id = credential.account.id().to_string();
|
||||
let snapshot =
|
||||
gateway_core::account::AccountHistorySnapshot::from_account(&credential.account);
|
||||
|
||||
@@ -142,12 +142,9 @@ pub(super) struct OpenAiOAuthRefreshTask {
|
||||
impl ScheduledTask for OpenAiOAuthRefreshTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
let outcomes = self
|
||||
.service
|
||||
.refresh_due()
|
||||
.refresh_due_until(context.cancellation())
|
||||
.await
|
||||
.map_err(|error| WorkerTaskError::safe("令牌刷新失败").with_source(error))?;
|
||||
let mut changed = Vec::new();
|
||||
@@ -272,10 +269,11 @@ impl ScheduledTask for OpenAiDesktopReleaseTask {
|
||||
impl ScheduledTask for OpenAiQuotaTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
match self.quota.synchronize().await {
|
||||
match self
|
||||
.quota
|
||||
.synchronize_until(std::time::SystemTime::now(), context.cancellation())
|
||||
.await
|
||||
{
|
||||
Ok(summary) if summary.has_operational_failures() => {
|
||||
tracing::warn!(
|
||||
updated = summary.updated,
|
||||
@@ -300,10 +298,14 @@ impl ScheduledTask for OpenAiQuotaTask {
|
||||
impl ScheduledTask for OpenAiCatalogTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
let Some(catalogs) = context
|
||||
.cancellation()
|
||||
.run_until_cancelled(self.catalog.refresh_catalogs())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
}
|
||||
let result = match self.catalog.refresh_catalogs().await {
|
||||
};
|
||||
let result = match catalogs {
|
||||
Ok(_) | Err(CodexCredentialCatalogError::NoEligibleCredential) => Ok(()),
|
||||
Err(error) => Err(WorkerTaskError::safe("模型目录同步失败").with_source(error)),
|
||||
};
|
||||
@@ -401,10 +403,18 @@ impl OpenAiWarmupTask {
|
||||
impl ScheduledTask for OpenAiWarmupTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let cron_result = self.run_cron_cycle(&context).await;
|
||||
let bucket_result = tokio::select! {
|
||||
() = context.cancellation().cancelled() => return Ok(()),
|
||||
result = self.quota.execute_bucket_warmup_at(chrono::Utc::now()) => result,
|
||||
let cancellation = context.cancellation();
|
||||
let Some(cron_result) = cancellation
|
||||
.run_until_cancelled(self.run_cron_cycle())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(bucket_result) = cancellation
|
||||
.run_until_cancelled(self.quota.execute_bucket_warmup_at(chrono::Utc::now()))
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if let Err(error) = bucket_result {
|
||||
tracing::warn!(error = %error, "OpenAI quota bucket warmup cycle failed");
|
||||
@@ -415,10 +425,7 @@ impl ScheduledTask for OpenAiWarmupTask {
|
||||
}
|
||||
|
||||
impl OpenAiWarmupTask {
|
||||
async fn run_cron_cycle(&self, context: &WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
async fn run_cron_cycle(&self) -> Result<(), WorkerTaskError> {
|
||||
let policy = self
|
||||
.quota
|
||||
.runtime_policy()
|
||||
@@ -460,11 +467,7 @@ impl OpenAiWarmupTask {
|
||||
return Ok(());
|
||||
}
|
||||
tracing::info!(%slot, model, "OpenAI account warmup cycle started");
|
||||
let outcome = tokio::select! {
|
||||
() = context.cancellation().cancelled() => return Ok(()),
|
||||
outcome = self.quota.execute_warmup(model) => outcome,
|
||||
};
|
||||
match outcome {
|
||||
match self.quota.execute_warmup(model).await {
|
||||
Ok(summary) => {
|
||||
tracing::info!(
|
||||
warmed_up = summary.warmed_up,
|
||||
|
||||
@@ -71,6 +71,45 @@ fn local_service(
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_interrupts_pending_usage_and_preserves_completed_observations() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
for id in ["acct_quota_a", "acct_quota_b", "acct_quota_c"] {
|
||||
create_account(&store, id).await;
|
||||
}
|
||||
let server = MockServer::start().await;
|
||||
let second = Arc::new(tokio::sync::Notify::new());
|
||||
let received = second.clone();
|
||||
let calls = std::sync::atomic::AtomicUsize::new(0);
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/codex/usage"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
let response = ResponseTemplate::new(200).set_body_json(usage_ok());
|
||||
if calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 1 {
|
||||
received.notify_one();
|
||||
return response.set_delay(Duration::from_secs(60));
|
||||
}
|
||||
response
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
let service = local_service(&store, &server, zero_delays());
|
||||
let cancellation = gateway_core::lifecycle::CancellationToken::new();
|
||||
let cycle = service.synchronize_until(SystemTime::now(), &cancellation);
|
||||
let stop = async {
|
||||
second.notified().await;
|
||||
cancellation.cancel();
|
||||
};
|
||||
let (summary, ()) =
|
||||
tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(cycle, stop) })
|
||||
.await
|
||||
.expect("shutdown while upstream is pending");
|
||||
assert_eq!(summary.unwrap().updated, 1);
|
||||
assert_eq!(usage_requests(&server).await, 2);
|
||||
mount_usage(&server, 200).await;
|
||||
assert_eq!(service.synchronize().await.unwrap().updated, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_account_without_quota_is_observed_when_initial_delay_expires() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
|
||||
@@ -247,6 +247,58 @@ async fn seed_refreshable_account(
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_preserves_inflight_token_rotation_and_skips_queued_accounts() {
|
||||
struct RotatingRefresher(gateway_core::lifecycle::CancellationToken);
|
||||
#[async_trait]
|
||||
impl TokenRefresher for RotatingRefresher {
|
||||
async fn refresh(&self, _: &str) -> Result<TokenPair, RefreshFailure> {
|
||||
self.0.cancel();
|
||||
tokio::task::yield_now().await;
|
||||
Ok(TokenPair {
|
||||
access_token: Some("new-access".to_owned()),
|
||||
refresh_token: Some("new-refresh".to_owned()),
|
||||
id_token: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let cancellation = gateway_core::lifecycle::CancellationToken::new();
|
||||
let service = CodexCredentialRefreshService::new(
|
||||
store.repository(),
|
||||
Arc::new(RotatingRefresher(cancellation.clone())),
|
||||
Arc::new(RefreshLeases),
|
||||
Arc::new(RefreshCredentialState),
|
||||
MutableRuntimePolicy::new(Duration::from_secs(300)),
|
||||
Arc::new(crate::RecordingDiagnostics::default()),
|
||||
);
|
||||
for id in ["acct_rotation_a", "acct_rotation_b"] {
|
||||
seed_refreshable_account(&store, id, SystemTime::now(), None).await;
|
||||
}
|
||||
let outcomes = service.refresh_due_until(&cancellation).await.unwrap();
|
||||
let [CodexCredentialRefreshOutcome::Refreshed { account_id, .. }] = outcomes.as_slice() else {
|
||||
panic!("only the started exchange should finish");
|
||||
};
|
||||
let account = store.account(account_id).expect("refreshed account");
|
||||
let stored = store
|
||||
.load_credential(account.id(), account.revision())
|
||||
.await
|
||||
.expect("stored rotation");
|
||||
let runtime = CodexCredentialCodec::decode(&stored.credential).expect("runtime credential");
|
||||
assert_eq!(
|
||||
runtime
|
||||
.authentication
|
||||
.oauth()
|
||||
.expect("OAuth credential")
|
||||
.refresh_token
|
||||
.as_ref()
|
||||
.expect("rotated refresh token")
|
||||
.expose_secret(),
|
||||
"new-refresh"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scheduled_refresh_rotates_tokens_without_enabling_scheduling() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
|
||||
@@ -414,6 +414,30 @@ impl GrokCredentialQuotaService {
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<GrokQuotaSnapshot, GrokQuotaError> {
|
||||
let (account, document) = self.fetch_billing(account_id).await?;
|
||||
self.store_billing(&account, document).await
|
||||
}
|
||||
|
||||
/// 定时同步只取消远端查询,已读取的额度按同一凭据版本写回
|
||||
pub(crate) async fn synchronize_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
cancellation: &gateway_core::lifecycle::CancellationToken,
|
||||
) -> Result<(), GrokQuotaError> {
|
||||
let Some(billing) = cancellation
|
||||
.run_until_cancelled(self.fetch_billing(account_id))
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let (account, document) = billing?;
|
||||
self.store_billing(&account, document).await.map(|_| ())
|
||||
}
|
||||
|
||||
async fn fetch_billing(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<(ProviderAccount, serde_json::Map<String, serde_json::Value>), GrokQuotaError> {
|
||||
let loaded = self
|
||||
.repository
|
||||
.load_current(account_id)
|
||||
@@ -450,16 +474,23 @@ impl GrokCredentialQuotaService {
|
||||
Ok(None) => {}
|
||||
Err(error) => tracing::warn!(%error, "xAI subscription query failed"),
|
||||
}
|
||||
Ok((loaded.account, document))
|
||||
}
|
||||
|
||||
async fn store_billing(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
document: serde_json::Map<String, serde_json::Value>,
|
||||
) -> Result<GrokQuotaSnapshot, GrokQuotaError> {
|
||||
let observed_at = Utc::now();
|
||||
let presentation = billing_presentation(&document)?;
|
||||
let quota = loaded
|
||||
.account
|
||||
let quota = account
|
||||
.quota()
|
||||
.merge_observation(quota_access_observation(&presentation, observed_at.into()));
|
||||
self.repository
|
||||
.replace_quota(
|
||||
loaded.account.id().clone(),
|
||||
loaded.account.revision(),
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
document,
|
||||
observed_at.into(),
|
||||
quota,
|
||||
@@ -467,8 +498,8 @@ impl GrokCredentialQuotaService {
|
||||
.await
|
||||
.map_err(map_quota_repository_error)?;
|
||||
let snapshot = GrokQuotaSnapshot {
|
||||
account_id: loaded.account.id().clone(),
|
||||
credential_revision: loaded.account.revision(),
|
||||
account_id: account.id().clone(),
|
||||
credential_revision: account.revision(),
|
||||
observed_at,
|
||||
billing: presentation,
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@ use gateway_core::account::{
|
||||
AccountErrorReason, CredentialRevision, CredentialState, LoadedCredential, ProviderAccountId,
|
||||
ProviderRefreshQuery,
|
||||
};
|
||||
use gateway_core::lifecycle::CancellationToken;
|
||||
use gateway_core::provider_ports::{
|
||||
ProviderCredentialStatePort, ProviderLeaseAcquisition, ProviderLeasePort, ProviderLeaseRequest,
|
||||
ProviderRefreshCapacityRequest, ProviderRefreshLeaseRequest, ProviderRefreshPolicy,
|
||||
@@ -374,7 +375,14 @@ impl GrokCredentialRefreshService {
|
||||
pub async fn refresh_due(
|
||||
&self,
|
||||
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
|
||||
self.refresh_due_excluding(&[]).await
|
||||
self.refresh_due_until(&CancellationToken::new()).await
|
||||
}
|
||||
|
||||
pub async fn refresh_due_until(
|
||||
&self,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
|
||||
self.refresh_batch(&[], cancellation).await
|
||||
}
|
||||
|
||||
async fn refresh_rejected(
|
||||
@@ -520,11 +528,27 @@ impl GrokCredentialRefreshService {
|
||||
&self,
|
||||
excluded_account_ids: &[ProviderAccountId],
|
||||
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
|
||||
let policy = self.runtime_policy.load_refresh_policy().await?;
|
||||
let batch = self
|
||||
.repository
|
||||
.list_due_refresh_batch_excluding(excluded_account_ids, policy)
|
||||
.await?;
|
||||
self.refresh_batch(excluded_account_ids, &CancellationToken::new())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn refresh_batch(
|
||||
&self,
|
||||
excluded_account_ids: &[ProviderAccountId],
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
|
||||
let load_candidates = async {
|
||||
let policy = self.runtime_policy.load_refresh_policy().await?;
|
||||
let batch = self
|
||||
.repository
|
||||
.list_due_refresh_batch_excluding(excluded_account_ids, policy)
|
||||
.await?;
|
||||
Ok::<_, GrokCredentialRefreshError>((policy, batch))
|
||||
};
|
||||
let Some(batch) = cancellation.run_until_cancelled(load_candidates).await else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let (policy, batch) = batch?;
|
||||
let mut outcomes = batch
|
||||
.failed_account_ids
|
||||
.into_iter()
|
||||
@@ -537,27 +561,38 @@ impl GrokCredentialRefreshService {
|
||||
if credentials
|
||||
.iter()
|
||||
.any(|credential| credential.outbound_proxy.is_none())
|
||||
&& self.refresher.prepare_cycle().await.is_err()
|
||||
{
|
||||
if credentials
|
||||
.iter()
|
||||
.all(|credential| credential.outbound_proxy.is_none())
|
||||
{
|
||||
return Err(GrokCredentialRefreshError::Preparation);
|
||||
}
|
||||
// 默认出口发现失败不能阻止其他出口上的账号刷新
|
||||
credentials.retain(|credential| {
|
||||
if credential.outbound_proxy.is_some() {
|
||||
return true;
|
||||
let Some(prepared) = cancellation
|
||||
.run_until_cancelled(self.refresher.prepare_cycle())
|
||||
.await
|
||||
else {
|
||||
return Ok(outcomes);
|
||||
};
|
||||
if prepared.is_err() {
|
||||
if credentials
|
||||
.iter()
|
||||
.all(|credential| credential.outbound_proxy.is_none())
|
||||
{
|
||||
return Err(GrokCredentialRefreshError::Preparation);
|
||||
}
|
||||
outcomes.push(GrokCredentialRefreshOutcome::Failed {
|
||||
account_id: credential.account_id.clone(),
|
||||
// 默认出口发现失败不能阻止其他出口上的账号刷新
|
||||
credentials.retain(|credential| {
|
||||
if credential.outbound_proxy.is_some() {
|
||||
return true;
|
||||
}
|
||||
outcomes.push(GrokCredentialRefreshOutcome::Failed {
|
||||
account_id: credential.account_id.clone(),
|
||||
});
|
||||
false
|
||||
});
|
||||
false
|
||||
});
|
||||
}
|
||||
}
|
||||
outcomes.reserve(credentials.len());
|
||||
let refreshed = stream::iter(credentials.into_iter().map(|credential| async move {
|
||||
// 停止领取新账号,已发出的令牌交换继续写回
|
||||
let candidates = credentials
|
||||
.into_iter()
|
||||
.take_while(|_| !cancellation.is_cancelled());
|
||||
let refreshed = stream::iter(candidates.map(|credential| async move {
|
||||
let account_id = credential.account_id.clone();
|
||||
(
|
||||
account_id,
|
||||
|
||||
@@ -103,12 +103,9 @@ impl ScheduledTask for XaiCliReleaseTask {
|
||||
impl ScheduledTask for XaiOAuthRefreshTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
let outcomes = self
|
||||
.service
|
||||
.refresh_due()
|
||||
.refresh_due_until(context.cancellation())
|
||||
.await
|
||||
.map_err(|error| WorkerTaskError::safe("令牌刷新失败").with_source(error))?;
|
||||
let failures = outcomes
|
||||
@@ -148,27 +145,41 @@ pub(super) struct XaiQuotaCatalogTask {
|
||||
impl ScheduledTask for XaiQuotaCatalogTask {
|
||||
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
|
||||
Box::pin(async move {
|
||||
let accounts = self
|
||||
.accounts
|
||||
.list_for_provider(&self.provider_kind, true)
|
||||
let cancellation = context.cancellation();
|
||||
let Some(accounts) = cancellation
|
||||
.run_until_cancelled(self.accounts.list_for_provider(&self.provider_kind, true))
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let accounts = accounts
|
||||
.map_err(|source| WorkerTaskError::safe("账号列表读取失败").with_source(source))?;
|
||||
let mut failures = QuotaCatalogFailure::default();
|
||||
let now = SystemTime::now();
|
||||
let accounts = self.reserve_periodic_refreshes(accounts, now);
|
||||
for account in accounts {
|
||||
if context.cancellation().is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
match self.quota.refresh_account(account.id()).await {
|
||||
Ok(_) | Err(GrokQuotaError::AccountUnavailable) => {}
|
||||
for account in accounts
|
||||
.into_iter()
|
||||
.take_while(|_| !cancellation.is_cancelled())
|
||||
{
|
||||
match self
|
||||
.quota
|
||||
.synchronize_account(account.id(), cancellation)
|
||||
.await
|
||||
{
|
||||
Ok(()) | Err(GrokQuotaError::AccountUnavailable) => {}
|
||||
Err(error) => {
|
||||
failures.quota_failures = failures.quota_failures.saturating_add(1);
|
||||
failures.first_quota_error.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.catalog.query_models().await {
|
||||
let Some(catalog) = cancellation
|
||||
.run_until_cancelled(self.catalog.query_models())
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
match catalog {
|
||||
Ok(_) | Err(GrokCredentialCatalogError::NoEligibleCredential) => {}
|
||||
Err(error) => failures.catalog_error = Some(error),
|
||||
}
|
||||
|
||||
@@ -789,6 +789,8 @@ metrics_exporter = "none"
|
||||
WebSocket 会话完成,进程退出时强制断开剩余连接。待写费用、已入队的观测与后台清理保留
|
||||
`host.worker_shutdown_timeout_seconds`(默认 30 秒)的收尾预算;客户端在新进程就绪后重新连接
|
||||
|
||||
若重启耗尽收尾预算,查看日志中「后台任务收尾超时,强制终止」的 `worker` 字段,定位超时任务
|
||||
|
||||
费用被写入队列接管不等于已落库。数据库持续失败、收尾超时或进程强制退出时,未持久化费用与
|
||||
未写入的观测可能丢失,重启不会恢复这些内存队列。延长收尾预算不能保证费用不丢失
|
||||
|
||||
|
||||
+12
-4
@@ -268,6 +268,8 @@ AGY 在 API Key 模式下使用 `gemini-3.1-flash-lite-preview` 发起同样的
|
||||
|
||||
OAuth 普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 Cloud Code SSE 数据帧。API Key 直接保留 GenAI JSON 和 SSE 数据正文。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果和未知字段;OAuth 的思考签名按下述来源规则处理,API Key 不改写签名。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
|
||||
|
||||
上游结构化拒绝保留 HTTP 状态、`ErrorInfo.reason` 和重试时间;HTTP 200 中的 RPC 错误按同一规则处理。已开始交付的原生流通过 SSE 错误帧结束,不重放已输出内容。账号验证链接及其他错误 metadata 仅保留在受控诊断中,不发送给模型客户端
|
||||
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;OAuth 的认证、项目和 UA 由所选账号与冻结画像生成;API Key 仅使用所选账号的 `x-goog-api-key`,不附带 Google 项目或 AGY 画像。`X-Goog-Api-Client` 与 Gateway 的 `X-Goog-Ext-525006001-Bin` 不进入 Cloud Code 请求。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
|
||||
|
||||
以下提示词、工具 ID 和签名处理只适用于 OAuth Cloud Code 上游,API Key 保留调用方原生正文。
|
||||
@@ -1882,7 +1884,7 @@ OAuth start 使用:
|
||||
|
||||
Antigravity 的全局客户端设置保存在 `providerRequestProfiles.antigravity`,Key 可用 `providerRequestProfileOverrides.antigravity` 覆盖。配置使用 `client`(`desktop` 或 `cli`)、`platform`(`macos`、`linux` 或 `windows`)、`versionMode`、`clientVersion` 和 `arch`。`arch: null` 使用预设架构:macOS 为 `arm64`,Linux 与 Windows 为 `amd64`;也可显式选择 `arm64` 或 `amd64`
|
||||
|
||||
AGY 请求画像的 `systemPrompt` 最长 16 KiB,省略、`null` 或空白值使用内置默认。选项接口通过 `defaultSystemPrompt` 和 `systemPromptSource` 返回 AGY CLI 1.5.15 身份模板及其来源。原生生成与计数在客户端系统指令之前加入画像提示词。普通 Chat 转发只应用[提示词改写规则](#提示词改写)
|
||||
AGY 请求画像的 `systemPrompt` 最长 16 KiB,省略、`null` 或空白值使用内置默认。选项接口通过 `defaultSystemPrompt` 和 `systemPromptSource` 返回 AGY CLI 1.5.23 身份模板及其来源。原生生成与计数在客户端系统指令之前加入画像提示词。普通 Chat 转发只应用[提示词改写规则](#提示词改写)
|
||||
|
||||
自动版本示例:
|
||||
|
||||
@@ -1890,9 +1892,15 @@ AGY 请求画像的 `systemPrompt` 最长 16 KiB,省略、`null` 或空白值
|
||||
{"client":"desktop","platform":"macos","versionMode":"latest","clientVersion":null,"arch":null}
|
||||
```
|
||||
|
||||
固定版本使用 `"versionMode":"fixed"`,并将 `clientVersion` 设为三段数字版本。Desktop 与 CLI 分别跟随各自的官方发布资料,各实例启动后检查,之后每 24 小时更新一次;检查失败保留上次成功结果,尚无结果时使用已核实的内置版本。请求开始时冻结客户端、平台、架构、版本及对应的 CL 构建号,重试沿用同一画像。发布资料不提供 CL,未知版本省略该字段,不套用旧版本的构建号。[Google 官方下载](https://antigravity.google/download)
|
||||
自动模式从对应平台的发布包取得版本和 CL,核验通过后一起生效。更新失败时继续使用当前画像。启动时恢复缓存,没有可用画像时先用内置版本并省略 CL。[Google 官方下载](https://antigravity.google/download)
|
||||
|
||||
预览与实际出站请求共用 `User-Agent` 生成规则。本机 macOS arm64 的 Desktop 2.34.0 已认证请求为 `antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64; cl=1026637980)`;Linux amd64 的 CLI 1.5.17 经个人 OAuth 打印模式的控制面与生成请求核实使用 `cli` 子客户端标识、CL `1029496841` 及 `auth_method=consumer`。默认身份不添加关闭遥测才出现的 `datacollection_opt_in` 或 ACP 宿主传入的 `host_path`
|
||||
固定版本使用 `"versionMode":"fixed"`,并将 `clientVersion` 设为三段数字版本。有对应制品的核验结果时附带 CL。请求重试沿用首次冻结的画像
|
||||
|
||||
预览与实际出站请求共用 `User-Agent` 生成规则。Desktop 使用 `hub` 子客户端标识,CLI 使用 `cli` 并携带 `auth_method=consumer`。入站 `User-Agent` 被过滤,由所选画像重建;ACP 宿主的 `host_path` 不继承
|
||||
|
||||
官方客户端仅在管理员策略强制关闭遥测(`TelemetryLocked`)时追加 `datacollection_opt_in=false`,账号的普通遥测开关不直接决定该标记。CPR 使用个人 OAuth 画像,未接入该管理员策略,故省略此标记;省略不表示用户开启遥测,也不修改 Google 账号的遥测设置
|
||||
|
||||
客户端使用网关 API Key 不决定上游认证方式;选中 Google OAuth 账号时,出站身份按个人 OAuth 画像重建。`HasFingerprintSet` 是官方本地 `UserStatus` 的状态字段,不能由 OAuth 本地状态中的 `false` 推断 Gateway 入口一定没有其他值。OAuth 生成和计数请求移除入站顶层的 `hasFingerprintSet`、`has_fingerprint_set`,不向 Cloud Code 伪造该字段;正文、工具参数和 schema 内的同名字段保持不变。选中 GenAI API Key 上游时仍使用公开模型路径,不套用 OAuth 请求改写
|
||||
|
||||
Cloud Code 请求固定使用 HTTP/1.1 和 `Accept-Encoding: gzip`,响应按流解压,大小限制作用于解压后的内容。
|
||||
传输显式使用 rustls,TLS 握手与官方 Go 客户端不同;reqwest 的默认 `Accept: */*` 和请求头顺序也不完全一致。画像预览不代表 TLS 或完整网络指纹一致
|
||||
@@ -3124,7 +3132,7 @@ Dashboard 的当前账号摘要包含 `upstream`,结构与账号列表一致
|
||||
|
||||
Antigravity 的 `client_identifier` 与实际 User-Agent 共用产品标识,格式为 `antigravity/{hub|cli}/{version}`;`target` 返回系统与架构,未携带的系统版本和终端为空
|
||||
|
||||
Antigravity 的发布状态仅比较官方发布版本,页面显示“版本一致”;`verifiedAt` 只表示对应平台、架构与版本的实际画像核验时间,不随发布资料轮询刷新,尚未核验的组合为空
|
||||
Antigravity 的 `version` 是生效版本,`release.latestVersion` 是最近发现的官方版本。`verifiedAt` 记录生效画像所用制品的核验时间,没有对应记录时返回 `null`
|
||||
|
||||
### Dashboard 容量与账号用量
|
||||
|
||||
|
||||
@@ -1138,6 +1138,7 @@ OpenAI、xAI、Antigravity 的 OAuth 认证及账号后台操作由各 Provider
|
||||
Provider 在额度观测中保存与同次模型目录核对的分组成员 ID。Admin 按模型和窗口边界汇总本地 Token,账号用量另按部署时区今天及前 6 天统计,展示为“近一周”。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
|
||||
账号列表和展开的额度面板读取已保存的快照,点击“刷新额度”时立即查询上游。后台补齐启用账号缺失或凭据版本失效的快照。健康账号仅在距上次观测已满 5 分钟、且有生成请求在该次观测后成功完成时补查。整号耗尽按重置时间复查,缺少重置时间时在耗尽观测满 5 分钟后复查
|
||||
正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试
|
||||
生成、计数、目录和额度查询共用 Google 结构化错误分类。明确的账号验证要求写入 `invalid/account_unverified`,账号停用写入 `banned/account_banned`;普通权限拒绝不推断为账号封禁。后台目录和额度查询跳过这些账号,管理员完成上游验证后显式恢复账号状态。普通令牌续期保留提交时的访问状态,不能解除在途请求确认的拒绝
|
||||
- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后,
|
||||
由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。
|
||||
同身份重新授权在事务内保留额度观测和按桶预热进度,旧凭据版本的在途观测无法覆盖新版本。
|
||||
@@ -1467,11 +1468,9 @@ OpenAI 客户端画像由 Provider 每小时检查发布元数据,发布标识
|
||||
同版本的有效制品缓存每 24 小时续期,保留 30 天;续期保留原核验时间,失败不推进成功写入游标。
|
||||
版本及缓存更新失败保留当前画像,下轮继续尝试;Host 只监督调度与取消。
|
||||
|
||||
Antigravity 每天检查官方发布资料,后台按已使用的客户端、平台和架构核对发布包版本,
|
||||
CLI 同时校验官方清单的 SHA-512;核验不执行下载程序,也不发送模型请求。
|
||||
核验事实绑定完整制品标识,使用同一缓存端口保留 30 天,每 24 小时续期并保留原核验时间。
|
||||
版本或制品变化后重新核验,失败不将旧证据套用到新制品;发布包核验不代表 TLS 或完整请求指纹一致,
|
||||
未知版本的请求构建号仍省略。
|
||||
Antigravity 启动时恢复有效制品缓存,每小时检查发布资料。后台按已使用的客户端、平台和架构核对发布包版本并提取 CL,CLI 同时校验清单的 SHA-512。
|
||||
版本、CL 和核验时间绑定同一制品。缓存每 24 小时续期,保留 30 天及原核验时间。Provider 在缓存写入成功后整组发布画像,失败保留当前画像。
|
||||
发布资料单独记录最新观测,供管理端展示。
|
||||
|
||||
互联同步使用账号出口的受管 HTTP 客户端,不跟随跳转;网络等待不持有数据库事务。
|
||||
运行期排程、并发预算、连接失效和观测提交见 [CPR 互联观测](#cpr-互联观测),失败遵守退避及上游 `Retry-After`
|
||||
@@ -1517,6 +1516,7 @@ Core 与 Store 在各自的探针上声明接收请求所需的依赖。API 的
|
||||
|
||||
Host 对管理端重启、OS 关闭信号和内部取消使用统一策略:停止监听并拒绝新连接注册,
|
||||
不等待存量会话,随后在独立预算内取消并等待 Worker 排空队列和完成后台清理。
|
||||
额度查询、目录同步和冻结探测在关闭时取消,OAuth 刷新停止领取新账号,宿主在关闭预算内等待已开始的令牌交换和写回。逾期任务终止时记录任务标识。
|
||||
剩余连接随进程退出终止。观测队列和费用 writer 分别收尾,费用被 Store 接管不代表已写入 PostgreSQL;
|
||||
排空超时、持续写入失败或进程异常退出时,未落库的观测和费用都可能丢失。
|
||||
重启不恢复内存费用队列,也不执行隐式业务重放;费用接管与幂等写入边界见[Client Key 结算](#client-key-限额与结算)。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { TransitionPresets, usePreferredReducedMotion, useTransition } from '@vueuse/core'
|
||||
import { computed } from 'vue'
|
||||
import { transition, TransitionPresets, usePreferredReducedMotion } from '@vueuse/core'
|
||||
import { computed, shallowRef, watch } from 'vue'
|
||||
|
||||
type MetricValueFormatter = (value: number) => string
|
||||
|
||||
@@ -28,10 +28,25 @@ const sourceValue = computed(() => (hasAnimatedValue.value
|
||||
? (props.rawValue ?? 0)
|
||||
: 0))
|
||||
const disabled = computed(() => preferredMotion.value === 'reduce' || !hasAnimatedValue.value)
|
||||
const animatedValue = useTransition(sourceValue, {
|
||||
duration: computed(() => props.duration),
|
||||
easing: TransitionPresets.easeOutCubic,
|
||||
disabled,
|
||||
const animatedValue = shallowRef(sourceValue.value)
|
||||
|
||||
watch([sourceValue, disabled], ([value, isDisabled], _, onCleanup) => {
|
||||
let cancelled = false
|
||||
onCleanup(() => {
|
||||
cancelled = true
|
||||
})
|
||||
|
||||
// 禁用动画期间也同步显示起点,恢复动画时不能退回旧值
|
||||
if (isDisabled || value === animatedValue.value) {
|
||||
animatedValue.value = value
|
||||
return
|
||||
}
|
||||
|
||||
void transition(animatedValue, animatedValue.value, value, {
|
||||
duration: props.duration,
|
||||
easing: TransitionPresets.easeOutCubic,
|
||||
abort: () => cancelled,
|
||||
})
|
||||
})
|
||||
|
||||
const displayValue = computed(() =>
|
||||
|
||||
@@ -66,10 +66,11 @@ const sizes = {
|
||||
md: { text: 'text-z-xs font-heavy', singleLine: 'h-5.5 px-2' },
|
||||
}
|
||||
|
||||
const paletteClass = computed(() => {
|
||||
const appearanceClasses = computed(() => {
|
||||
const key = props.planType?.trim().toLowerCase() || ''
|
||||
return planPalettes.get(displayText.value?.trim().toLowerCase() || key)
|
||||
const palette = planPalettes.get(displayText.value?.trim().toLowerCase() || key)
|
||||
?? fallbackPalettes[stableVisualIndex(key, fallbackPalettes.length)]
|
||||
return ['rounded-md', palette]
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -77,18 +78,18 @@ const paletteClass = computed(() => {
|
||||
<AccountUpstreamBadge v-if="upstreamPeer || upstream?.discovered" :size="size" />
|
||||
<span
|
||||
v-else-if="wrap"
|
||||
class="line-clamp-3 max-w-full py-0.75 text-center leading-4 text-balance wrap-anywhere whitespace-normal"
|
||||
:class="sizes[size].text"
|
||||
class="line-clamp-3 max-w-full text-center text-balance wrap-anywhere whitespace-normal"
|
||||
:class="[sizes[size].text, size === 'xs' ? 'py-0.5 leading-3.5' : 'py-0.75 leading-4']"
|
||||
>
|
||||
<span class="box-decoration-clone rounded-md px-1.25 py-0.75" :class="paletteClass">
|
||||
<span class="box-decoration-clone" :class="[appearanceClasses, size === 'xs' ? 'px-1 py-0.5' : 'px-1.25 py-0.75']">
|
||||
{{ displayText }}
|
||||
<span v-if="count !== undefined" class="tabular-nums">{{ count }}</span>
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex min-w-0 max-w-full items-center justify-center gap-1 rounded-full whitespace-nowrap leading-none shadow-z-tertiary"
|
||||
:class="[sizes[size].text, sizes[size].singleLine, paletteClass]"
|
||||
class="inline-flex min-w-0 max-w-full items-center justify-center gap-1 whitespace-nowrap leading-none"
|
||||
:class="[appearanceClasses, sizes[size].text, sizes[size].singleLine]"
|
||||
>
|
||||
<span class="truncate">{{ displayText }}</span>
|
||||
<span v-if="count !== undefined" class="shrink-0 tabular-nums">{{ count }}</span>
|
||||
|
||||
@@ -66,7 +66,10 @@ function resize() {
|
||||
function applyOption(option: EChartsOption) {
|
||||
if (!chart.value)
|
||||
return
|
||||
chart.value.setOption(option, true)
|
||||
// 保留同 ID 系列的图形状态,同时清理切换指标后失效的系列和坐标轴
|
||||
chart.value.setOption(option, {
|
||||
replaceMerge: ['series', 'xAxis', 'yAxis'],
|
||||
})
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
|
||||
@@ -85,7 +85,7 @@ watch(hasPersonalInfo, (available) => {
|
||||
v-if="(account.capabilities.quota || quotaEntries.length > 0 || account.upstream?.discovered) && (hasPlanBadge || lastRefreshed)"
|
||||
class="col-span-2 row-start-2 m-0 flex min-w-0 items-center gap-1.5 text-z-xs font-emphasis text-z-text-secondary"
|
||||
>
|
||||
<AccountPlanBadge v-if="hasPlanBadge" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" class="shrink-0 rounded-md!" />
|
||||
<AccountPlanBadge v-if="hasPlanBadge" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" class="shrink-0" />
|
||||
<span v-if="lastRefreshed" class="min-w-0 truncate">{{ lastRefreshed }}</span>
|
||||
</p>
|
||||
<div v-if="hasActions" class="col-start-2 row-start-1 flex items-center gap-0.5 [&_svg]:size-3.5 [&_svg]:stroke-2">
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ const avatarToneClass = computed(() =>
|
||||
<strong class="min-w-0 truncate text-z leading-[1.15] font-heavy text-z-text">
|
||||
{{ displayTitle }}
|
||||
</strong>
|
||||
<AccountPlanBadge :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="xs" />
|
||||
<AccountPlanBadge wrap size="xs" class="max-w-2/3! shrink-0" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" />
|
||||
</span>
|
||||
<span
|
||||
v-if="secondaryText"
|
||||
|
||||
@@ -196,19 +196,18 @@ const normalRate = computed(() => {
|
||||
|
||||
const statusBars = computed(() => {
|
||||
const counts = accountStatusCounts.value
|
||||
if (!counts || counts.total === 0)
|
||||
return []
|
||||
const total = counts?.total || 1
|
||||
return [
|
||||
{ pct: (counts.normal / counts.total) * 100, cls: 'bg-z-success' },
|
||||
{ pct: (counts.quotaLimited / counts.total) * 100, cls: 'bg-z-warning' },
|
||||
{ pct: (counts.rateLimited / counts.total) * 100, cls: 'bg-z-warning' },
|
||||
{ pct: ((counts.disabled + counts.error) / counts.total) * 100, cls: 'bg-z-error' },
|
||||
].filter(b => b.pct > 0)
|
||||
{ key: 'normal', pct: ((counts?.normal ?? 0) / total) * 100, cls: 'bg-z-success' },
|
||||
{ key: 'quotaLimited', pct: ((counts?.quotaLimited ?? 0) / total) * 100, cls: 'bg-z-warning' },
|
||||
{ key: 'rateLimited', pct: ((counts?.rateLimited ?? 0) / total) * 100, cls: 'bg-z-warning' },
|
||||
{ key: 'pending', pct: (((counts?.disabled ?? 0) + (counts?.error ?? 0)) / total) * 100, cls: 'bg-z-error' },
|
||||
]
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZCard as="article" class="w-full xl:h-112.5">
|
||||
<ZCard as="article" class="w-full xl:min-h-112.5">
|
||||
<div
|
||||
class="grid xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.28fr)_minmax(280px,0.9fr)] xl:gap-7"
|
||||
>
|
||||
@@ -233,7 +232,7 @@ const statusBars = computed(() => {
|
||||
</div>
|
||||
<div v-if="!unlimitedCapacity" class="mt-4 h-2.5 w-full overflow-hidden rounded-full bg-z-progress-remaining">
|
||||
<i
|
||||
class="block h-2.5 rounded-full bg-z-success"
|
||||
class="block h-2.5 rounded-full bg-z-success motion-safe:transition-[width] motion-safe:duration-400 motion-safe:ease-out"
|
||||
:style="usedProgressStyle"
|
||||
/>
|
||||
</div>
|
||||
@@ -262,7 +261,7 @@ const statusBars = computed(() => {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="min-w-0 w-full">
|
||||
<section class="@container min-w-0 w-full">
|
||||
<h2 class="m-0 text-xl leading-[1.15] font-heavy text-z-text">
|
||||
{{ t('dashboard.activeAccounts.title') }}
|
||||
</h2>
|
||||
@@ -271,7 +270,7 @@ const statusBars = computed(() => {
|
||||
</p>
|
||||
|
||||
<div
|
||||
class="mt-5 flex w-full flex-col gap-2 overflow-hidden xl:mt-6.75 xl:h-82.5 xl:gap-2.5"
|
||||
class="mt-5 flex w-full flex-col gap-2 overflow-hidden xl:mt-6.75 xl:gap-2.5 xl:@lg:h-82.5"
|
||||
>
|
||||
<ZEmpty
|
||||
v-if="accounts.length === 0"
|
||||
@@ -279,19 +278,24 @@ const statusBars = computed(() => {
|
||||
surface="inset"
|
||||
class="min-h-40 place-content-center xl:h-full"
|
||||
/>
|
||||
<template v-else>
|
||||
<TransitionGroup
|
||||
v-else
|
||||
name="account-usage"
|
||||
tag="div"
|
||||
class="relative flex w-full flex-col gap-2 xl:gap-2.5"
|
||||
>
|
||||
<article
|
||||
v-for="account in accounts"
|
||||
:key="account.id"
|
||||
class="grid w-full shrink-0 grid-cols-1 gap-3 rounded-xl bg-z-fill-alter/70 px-3.5 py-3.5 transition-colors xl:h-18.75 xl:grid-cols-[minmax(0,1.32fr)_minmax(64px,0.4fr)_minmax(66px,0.42fr)_minmax(96px,0.7fr)] xl:items-center xl:gap-3 xl:px-4 xl:py-0"
|
||||
class="grid w-full shrink-0 grid-cols-1 gap-3 rounded-xl bg-z-fill-alter/70 px-3.5 py-3.5 transition-colors xl:@lg:h-18.75 xl:@lg:grid-cols-[minmax(0,1.32fr)_minmax(64px,0.4fr)_minmax(66px,0.42fr)_minmax(96px,0.7fr)] xl:@lg:items-center xl:@lg:px-4 xl:@lg:py-0"
|
||||
>
|
||||
<DashboardAccountIdentity
|
||||
:account="account"
|
||||
class="min-w-0 xl:pr-4"
|
||||
class="min-w-0 xl:@lg:pr-4"
|
||||
/>
|
||||
|
||||
<span
|
||||
class="grid min-w-0 grid-cols-[minmax(0,0.82fr)_minmax(0,0.64fr)_minmax(104px,1fr)] items-start gap-3 xl:contents"
|
||||
class="grid min-w-0 grid-cols-[minmax(0,0.82fr)_minmax(0,0.64fr)_minmax(104px,1fr)] items-start gap-3 xl:@lg:contents"
|
||||
>
|
||||
<span class="grid min-w-0 gap-1">
|
||||
<span class="text-z-xs leading-none font-bold text-z-text-quaternary">
|
||||
@@ -307,7 +311,7 @@ const statusBars = computed(() => {
|
||||
<span class="grid min-w-0 gap-1">
|
||||
<span class="text-z-xs leading-none font-bold text-z-text-quaternary">{{ t('dashboard.activeAccounts.recent') }}</span>
|
||||
<span
|
||||
class="min-w-0 truncate text-xs leading-[1.15] font-bold text-z-text-secondary xl:whitespace-nowrap"
|
||||
class="min-w-0 truncate text-xs leading-[1.15] font-bold text-z-text-secondary"
|
||||
>
|
||||
{{ formatRelativeTime(account.lastUsedRelative) }}
|
||||
</span>
|
||||
@@ -321,7 +325,7 @@ const statusBars = computed(() => {
|
||||
/>
|
||||
</span>
|
||||
</article>
|
||||
</template>
|
||||
</TransitionGroup>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -352,9 +356,9 @@ const statusBars = computed(() => {
|
||||
</div>
|
||||
<div class="mt-2.5 flex h-3 w-full overflow-hidden rounded-full bg-z-fill-tertiary">
|
||||
<i
|
||||
v-for="(bar, bi) in statusBars"
|
||||
:key="bi"
|
||||
class="h-3"
|
||||
v-for="bar in statusBars"
|
||||
:key="bar.key"
|
||||
class="h-3 shrink-0 motion-safe:transition-[flex-basis] motion-safe:duration-400 motion-safe:ease-out"
|
||||
:class="bar.cls"
|
||||
:style="{ flexBasis: `${bar.pct}%` }"
|
||||
/>
|
||||
@@ -391,3 +395,25 @@ const statusBars = computed(() => {
|
||||
</div>
|
||||
</ZCard>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.account-usage-move,
|
||||
.account-usage-enter-active,
|
||||
.account-usage-leave-active {
|
||||
transition:
|
||||
transform 420ms cubic-bezier(0.22, 1, 0.36, 1),
|
||||
opacity 180ms ease;
|
||||
}
|
||||
|
||||
.account-usage-enter-from,
|
||||
.account-usage-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(12px);
|
||||
}
|
||||
|
||||
.account-usage-leave-active {
|
||||
position: absolute;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { EChartsOption } from 'echarts'
|
||||
import type { MetricTone } from '../../constants'
|
||||
import type { MetricCardView } from './cards'
|
||||
import { ZCard, ZMotionIcon } from '@codex-proxy/ui'
|
||||
import { usePreferredReducedMotion } from '@vueuse/core'
|
||||
|
||||
import { computed } from 'vue'
|
||||
|
||||
@@ -25,6 +26,7 @@ const trendToneClasses: Record<MetricTone, string> = {
|
||||
}
|
||||
|
||||
const themeColor = useThemeColor()
|
||||
const preferredMotion = usePreferredReducedMotion()
|
||||
const sparklineColorTokens: Record<MetricTone, { token: string, fallback: string }> = {
|
||||
normal: { token: 'color-blue-solid', fallback: '#5983F4' },
|
||||
info: { token: 'color-blue-solid', fallback: '#5983F4' },
|
||||
@@ -41,7 +43,10 @@ const sparklineOption = computed<EChartsOption | null>(() => {
|
||||
const colorToken = sparklineColorTokens[props.metric.sparkline?.tone ?? 'normal']
|
||||
const color = themeColor(colorToken.token, colorToken.fallback)
|
||||
return {
|
||||
animation: false,
|
||||
animation: preferredMotion.value !== 'reduce',
|
||||
animationDuration: 0,
|
||||
animationDurationUpdate: 420,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
grid: { left: 0, right: 0, top: 4, bottom: 4 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
@@ -56,6 +61,7 @@ const sparklineOption = computed<EChartsOption | null>(() => {
|
||||
},
|
||||
series: [
|
||||
{
|
||||
id: 'metric-trend',
|
||||
type: 'line',
|
||||
data: values,
|
||||
smooth: true,
|
||||
|
||||
@@ -97,7 +97,7 @@ export function useRequestTrendChart(options: {
|
||||
: 420,
|
||||
animationDurationUpdate: preferredMotion.value === 'reduce'
|
||||
? 0
|
||||
: 220,
|
||||
: 420,
|
||||
animationEasing: 'cubicOut',
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
tooltip: {
|
||||
|
||||
+6
-11
@@ -1,17 +1,12 @@
|
||||
# v3.61.1-rc.2
|
||||
|
||||
## 新增功能
|
||||
|
||||
- 启用在线重启的部署可在管理端「系统更新」中手动重启服务,确认前可查看请求中断影响和插件风险
|
||||
# v3.61.1-rc.3
|
||||
|
||||
## 优化改进
|
||||
|
||||
- Codex OAuth 的 SSE 请求在应用隐私规则后仍可复用匹配的历史,只向同一上游 WebSocket 发送新增输入
|
||||
- 管理端仅在当前操作按钮显示加载状态,账号列表隐藏为零的 Token 用量
|
||||
- Antigravity 自动核验对应平台的官方发布包,版本和构建号一同生效,核验失败时沿用当前画像
|
||||
- 仪表盘更新指标和账号排序时平滑过渡,订阅标识与账号页统一,窄卡片下账号信息分行显示
|
||||
|
||||
## 问题修复
|
||||
|
||||
- Fast 模式按本次选中的账号和模型应用分组策略,重试切换账号时重新匹配
|
||||
- Chat Completions 可处理历史中的空占位消息和可空字段,转发到 Messages 和 GenAI 时保留停止序列
|
||||
- OpenAI 额度桶提前重置后,从观察到归零时起等待五分钟,再复查是否需要预热
|
||||
- HTTP 和 WebSocket 错误保留可识别的上游请求 ID,账号选择失败时区分额度耗尽和传输方式不匹配
|
||||
- Google 明确要求验证时,Antigravity 将对应账号标记为待验证并停止调度,避免反复使用同一账号(#836)
|
||||
- Antigravity 保留 Google 结构化拒绝的状态、错误原因和重试时间,原生流已输出内容时以 SSE 错误帧结束
|
||||
- 停止或重启服务时优先收尾后台任务,超出收尾预算时在日志中标明任务名称
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.61.1-rc.2
|
||||
version: 3.61.1-rc.3
|
||||
published:
|
||||
'3':
|
||||
stable: 3.61.0
|
||||
rc: 3.61.1-rc.1
|
||||
beta: 3.61.1-rc.1
|
||||
alpha: 3.61.1-rc.1
|
||||
rc: 3.61.1-rc.2
|
||||
beta: 3.61.1-rc.2
|
||||
alpha: 3.61.1-rc.2
|
||||
|
||||
Reference in New Issue
Block a user