mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 09:20:22 +08:00
refactor: 移除独立 hub/proxy/executor/gateway crate,统一为 gateway tunnel 架构
- 删除 aether-hub、aether-proxy 独立项目及其 Dockerfile/配置 - 删除 crates/aether-executor 和 crates/aether-gateway 全部模块 - 新增 apps/ 目录作为应用入口 - 将 hub 概念重构为 gateway tunnel transport - 将 executor 重构为 execution runtime - 新增 tunnel.rs 合约定义和 testkit tunnel/execution_runtime 模块 - 更新 Python 服务层和测试适配新架构命名
This commit is contained in:
116
apps/aether-gateway/src/wallet_runtime/access.rs
Normal file
116
apps/aether-gateway/src/wallet_runtime/access.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use aether_data::repository::wallet::StoredWalletSnapshot;
|
||||
use aether_wallet::{
|
||||
WalletAccessDecision, WalletAccessFailure, WalletLimitMode, WalletSnapshot, WalletStatus,
|
||||
};
|
||||
|
||||
use crate::gateway::gateway_data::StoredGatewayAuthApiKeySnapshot;
|
||||
use crate::gateway::{AppState, GatewayError, GatewayLocalAuthRejection};
|
||||
|
||||
pub(crate) async fn resolve_wallet_auth_gate(
|
||||
state: &AppState,
|
||||
auth_snapshot: &StoredGatewayAuthApiKeySnapshot,
|
||||
) -> Result<Option<WalletAccessDecision>, GatewayError> {
|
||||
if !state.has_wallet_data_reader() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let wallet = state
|
||||
.read_wallet_snapshot_for_auth(
|
||||
&auth_snapshot.user_id,
|
||||
&auth_snapshot.api_key_id,
|
||||
auth_snapshot.api_key_is_standalone,
|
||||
)
|
||||
.await?;
|
||||
let is_admin = auth_snapshot.user_role.eq_ignore_ascii_case("admin");
|
||||
|
||||
Ok(Some(match wallet.as_ref() {
|
||||
Some(wallet) => map_wallet_snapshot(wallet).access_decision(is_admin),
|
||||
None if is_admin => WalletAccessDecision::allowed(None),
|
||||
None => WalletAccessDecision::wallet_unavailable(None),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn local_rejection_from_wallet_access(
|
||||
decision: &WalletAccessDecision,
|
||||
) -> Option<GatewayLocalAuthRejection> {
|
||||
match decision.failure.as_ref() {
|
||||
Some(WalletAccessFailure::WalletUnavailable) => {
|
||||
Some(GatewayLocalAuthRejection::WalletUnavailable)
|
||||
}
|
||||
Some(WalletAccessFailure::BalanceDenied) => {
|
||||
Some(GatewayLocalAuthRejection::BalanceDenied {
|
||||
remaining: decision.remaining,
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_wallet_snapshot(snapshot: &StoredWalletSnapshot) -> WalletSnapshot {
|
||||
WalletSnapshot {
|
||||
wallet_id: snapshot.id.clone(),
|
||||
user_id: snapshot.user_id.clone(),
|
||||
api_key_id: snapshot.api_key_id.clone(),
|
||||
recharge_balance: snapshot.balance,
|
||||
gift_balance: snapshot.gift_balance,
|
||||
limit_mode: WalletLimitMode::parse(&snapshot.limit_mode),
|
||||
currency: snapshot.currency.clone(),
|
||||
status: WalletStatus::parse(&snapshot.status),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use aether_data::repository::wallet::StoredWalletSnapshot;
|
||||
use aether_wallet::{WalletAccessFailure, WalletLimitMode, WalletSnapshot, WalletStatus};
|
||||
|
||||
use super::{local_rejection_from_wallet_access, map_wallet_snapshot};
|
||||
use crate::gateway::GatewayLocalAuthRejection;
|
||||
|
||||
#[test]
|
||||
fn maps_wallet_snapshot_and_derives_balance_denied() {
|
||||
let stored = StoredWalletSnapshot::new(
|
||||
"wallet-1".to_string(),
|
||||
Some("user-1".to_string()),
|
||||
None,
|
||||
0.0,
|
||||
0.0,
|
||||
"finite".to_string(),
|
||||
"USD".to_string(),
|
||||
"active".to_string(),
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
100,
|
||||
)
|
||||
.expect("wallet should build");
|
||||
|
||||
let decision = map_wallet_snapshot(&stored).access_decision(false);
|
||||
assert_eq!(decision.failure, Some(WalletAccessFailure::BalanceDenied));
|
||||
assert_eq!(
|
||||
local_rejection_from_wallet_access(&decision),
|
||||
Some(GatewayLocalAuthRejection::BalanceDenied {
|
||||
remaining: Some(0.0),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlimited_admin_wallet_gate_allows_without_remaining() {
|
||||
let decision = WalletSnapshot {
|
||||
wallet_id: "wallet-1".to_string(),
|
||||
user_id: Some("user-1".to_string()),
|
||||
api_key_id: None,
|
||||
recharge_balance: 0.0,
|
||||
gift_balance: 0.0,
|
||||
limit_mode: WalletLimitMode::Unlimited,
|
||||
currency: "USD".to_string(),
|
||||
status: WalletStatus::Active,
|
||||
}
|
||||
.access_decision(true);
|
||||
|
||||
assert!(decision.allowed);
|
||||
assert_eq!(decision.remaining, None);
|
||||
}
|
||||
}
|
||||
7
apps/aether-gateway/src/wallet_runtime/mod.rs
Normal file
7
apps/aether-gateway/src/wallet_runtime/mod.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
mod access;
|
||||
mod quota;
|
||||
mod runtime;
|
||||
|
||||
pub(crate) use access::{local_rejection_from_wallet_access, resolve_wallet_auth_gate};
|
||||
pub(crate) use quota::spawn_provider_quota_reset_worker;
|
||||
pub(crate) use runtime::settle_usage_if_needed;
|
||||
126
apps/aether-gateway/src/wallet_runtime/quota.rs
Normal file
126
apps/aether-gateway/src/wallet_runtime/quota.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tracing::warn;
|
||||
|
||||
use crate::gateway::gateway_data::GatewayDataState;
|
||||
|
||||
const QUOTA_RESET_INTERVAL: Duration = Duration::from_secs(60 * 60);
|
||||
|
||||
pub(crate) async fn reset_due_provider_quotas_once(
|
||||
data: &GatewayDataState,
|
||||
) -> Result<usize, aether_data::DataLayerError> {
|
||||
let now_unix_secs = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
data.reset_due_provider_quotas(now_unix_secs).await
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_provider_quota_reset_worker(
|
||||
data: Arc<GatewayDataState>,
|
||||
) -> Option<tokio::task::JoinHandle<()>> {
|
||||
if !data.has_provider_quota_writer() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(tokio::spawn(async move {
|
||||
if let Err(err) = reset_due_provider_quotas_once(&data).await {
|
||||
warn!(error = %err, "gateway provider quota reset startup failed");
|
||||
}
|
||||
let mut interval = tokio::time::interval(QUOTA_RESET_INTERVAL);
|
||||
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
interval.tick().await;
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if let Err(err) = reset_due_provider_quotas_once(&data).await {
|
||||
warn!(error = %err, "gateway provider quota reset tick failed");
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use aether_data::repository::quota::{
|
||||
InMemoryProviderQuotaRepository, ProviderQuotaReadRepository, StoredProviderQuotaSnapshot,
|
||||
};
|
||||
|
||||
use super::{reset_due_provider_quotas_once, spawn_provider_quota_reset_worker};
|
||||
use crate::gateway::gateway_data::GatewayDataState;
|
||||
|
||||
#[tokio::test]
|
||||
async fn resets_due_provider_quotas_from_runtime() {
|
||||
let repository = Arc::new(InMemoryProviderQuotaRepository::seed(vec![
|
||||
StoredProviderQuotaSnapshot::new(
|
||||
"provider-1".to_string(),
|
||||
"monthly_quota".to_string(),
|
||||
Some(20.0),
|
||||
4.0,
|
||||
Some(1),
|
||||
Some(1),
|
||||
None,
|
||||
true,
|
||||
)
|
||||
.expect("quota should build"),
|
||||
]));
|
||||
let data = GatewayDataState::with_provider_quota_repository_for_tests(repository.clone());
|
||||
|
||||
let reset = reset_due_provider_quotas_once(&data)
|
||||
.await
|
||||
.expect("quota reset should succeed");
|
||||
assert_eq!(reset, 1);
|
||||
|
||||
let stored = repository
|
||||
.find_by_provider_id("provider-1")
|
||||
.await
|
||||
.expect("quota lookup should succeed")
|
||||
.expect("quota should exist");
|
||||
assert_eq!(stored.monthly_used_usd, 0.0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawned_worker_resets_due_provider_quotas_immediately() {
|
||||
let repository = Arc::new(InMemoryProviderQuotaRepository::seed(vec![
|
||||
StoredProviderQuotaSnapshot::new(
|
||||
"provider-1".to_string(),
|
||||
"monthly_quota".to_string(),
|
||||
Some(20.0),
|
||||
4.0,
|
||||
Some(1),
|
||||
Some(1),
|
||||
None,
|
||||
true,
|
||||
)
|
||||
.expect("quota should build"),
|
||||
]));
|
||||
let data = Arc::new(GatewayDataState::with_provider_quota_repository_for_tests(
|
||||
repository.clone(),
|
||||
));
|
||||
let handle = spawn_provider_quota_reset_worker(data).expect("worker should spawn");
|
||||
|
||||
let stored = tokio::time::timeout(Duration::from_secs(1), async {
|
||||
loop {
|
||||
let stored = repository
|
||||
.find_by_provider_id("provider-1")
|
||||
.await
|
||||
.expect("quota lookup should succeed")
|
||||
.expect("quota should exist");
|
||||
if stored.monthly_used_usd == 0.0 {
|
||||
break stored;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("worker should reset quota on startup");
|
||||
|
||||
handle.abort();
|
||||
|
||||
assert_eq!(stored.monthly_used_usd, 0.0);
|
||||
assert!(stored.quota_last_reset_at_unix_secs.unwrap_or_default() > 1);
|
||||
}
|
||||
}
|
||||
44
apps/aether-gateway/src/wallet_runtime/runtime.rs
Normal file
44
apps/aether-gateway/src/wallet_runtime/runtime.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use aether_data::repository::usage::StoredRequestUsageAudit;
|
||||
use aether_data::repository::wallet::UsageSettlementInput;
|
||||
use aether_data::{DataLayerError, DataLayerError::InvalidInput};
|
||||
|
||||
use crate::gateway::gateway_data::GatewayDataState;
|
||||
|
||||
pub(crate) async fn settle_usage_if_needed(
|
||||
data: &GatewayDataState,
|
||||
usage: &StoredRequestUsageAudit,
|
||||
) -> Result<(), DataLayerError> {
|
||||
if !data.has_wallet_writer() || usage.billing_status != "pending" {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(usage.status.as_str(), "completed" | "failed" | "cancelled") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let finalized_at_unix_secs = usage
|
||||
.finalized_at_unix_secs
|
||||
.or(Some(usage.updated_at_unix_secs));
|
||||
let input = UsageSettlementInput {
|
||||
request_id: usage.request_id.clone(),
|
||||
user_id: usage.user_id.clone(),
|
||||
api_key_id: usage.api_key_id.clone(),
|
||||
provider_id: usage.provider_id.clone(),
|
||||
status: usage.status.clone(),
|
||||
billing_status: usage.billing_status.clone(),
|
||||
total_cost_usd: finite_cost(usage.total_cost_usd)?,
|
||||
actual_total_cost_usd: finite_cost(usage.actual_total_cost_usd)?,
|
||||
finalized_at_unix_secs,
|
||||
};
|
||||
let _ = data.settle_usage(input).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finite_cost(value: f64) -> Result<f64, DataLayerError> {
|
||||
if value.is_finite() {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(InvalidInput(
|
||||
"wallet settlement cost must be finite".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user