mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-03 08:01:10 +00:00
Compare commits
3
Commits
v3.61.1-rc.2
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5e691c63d | ||
|
|
2d0a52096a | ||
|
|
47620e217a |
@@ -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(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,6 +452,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
|
||||
@@ -484,9 +491,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
|
||||
|
||||
@@ -298,6 +298,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)
|
||||
@@ -355,13 +362,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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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` 字段,定位超时任务
|
||||
|
||||
费用被写入队列接管不等于已落库。数据库持续失败、收尾超时或进程强制退出时,未持久化费用与
|
||||
未写入的观测可能丢失,重启不会恢复这些内存队列。延长收尾预算不能保证费用不丢失
|
||||
|
||||
|
||||
@@ -1517,6 +1517,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,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() {
|
||||
|
||||
@@ -196,14 +196,13 @@ 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>
|
||||
|
||||
@@ -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>
|
||||
@@ -279,7 +278,12 @@ 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"
|
||||
@@ -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: {
|
||||
|
||||
@@ -2,6 +2,6 @@ version: 3.61.1-rc.2
|
||||
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