Compare commits

..
Author SHA1 Message Date
elky 214f3d6406 fix(providers): hide billing fields in provider form 2026-09-02 23:17:01 +08:00
92 changed files with 3717 additions and 1965 deletions
+3 -3
View File
@@ -51,7 +51,7 @@ JWT_SECRET_KEY=change-this-to-a-secure-random-string
ENCRYPTION_KEY=change-this-to-another-secure-random-string
# 启动自举管理员(仅在当前库里还没有活动管理员时生效)
# 首次启动前必须设置 ADMIN_PASSWORD;install.sh 首次生成配置时会提示输入。
# 手动部署时取消注释并设置;install.sh 首次生成配置时会提示输入。
ADMIN_EMAIL=[email protected]
ADMIN_USERNAME=admin123456
# ADMIN_PASSWORD=
@@ -69,8 +69,8 @@ ADMIN_USERNAME=admin123456
# AETHER_VSCODEX_PUBLIC_WS_URL=wss://aether.example.com/api/vscodex/ws
# AETHER_VSCODEX_ALLOWED_ORIGINS=https://aether.example.com
# 启动时的数据库准备策略:auto(默认)或 verify-only
# AETHER_GATEWAY_DATABASE_MODE=auto
# docker compose 下 app 启动前自动执行 pending migration/backfill(默认 true)
# AETHER_GATEWAY_AUTO_PREPARE_DATABASE=true
# PostgreSQL 连接池配置(默认每核 4 条、总池至少 32 条且最多 100 条;多实例部署应显式分配每实例预算)
# AETHER_GATEWAY_DATA_POSTGRES_MIN_CONNECTIONS=12
+12 -36
View File
@@ -6,7 +6,7 @@ DEV_RUST_LOG := $(RUST_LOG)
endif
export DEV_RUST_LOG
.PHONY: dev dev-backend dev-frontend db-status db-prepare migration backfill
.PHONY: dev dev-backend dev-frontend migration backfill
define DEV_BACKEND_SCRIPT
set -euo pipefail
@@ -20,13 +20,6 @@ set -a
source .env
set +a
if [[ -n "$${ADMIN_EMAIL:-}" || -n "$${ADMIN_USERNAME:-}" || -n "$${ADMIN_PASSWORD:-}" ]]; then
if [[ -z "$${ADMIN_USERNAME:-}" || -z "$${ADMIN_PASSWORD:-}" ]]; then
echo "=> 管理员自举配置不完整,请在 .env 中设置 ADMIN_USERNAME 和 ADMIN_PASSWORD"
exit 1
fi
fi
dotenv_has_key() {
local key="$$1"
grep -Eq "^[[:space:]]*$${key}=" .env
@@ -208,17 +201,12 @@ print_startup_failure_hint() {
if [ -n "$${log_file}" ] && [ -f "$${log_file}" ]; then
if grep -Eq "database schema is behind" "$${log_file}"; then
echo "=> 检测到数据库尚未准备完成,请执行: make db-prepare"
echo "=> 检测到数据库 schema 落后,请执行: make migration"
return
fi
if grep -Eq "database backfills are behind" "$${log_file}"; then
echo "=> 检测到数据库尚未准备完成,请执行: make db-prepare"
return
fi
if grep -Eq "bootstrap admin env is partially configured.*ADMIN_PASSWORD" "$${log_file}"; then
echo "=> 首次启动需要管理员密码,请在 .env 中设置 ADMIN_PASSWORD"
echo "=> 检测到待执行 backfills,请执行: make backfill"
return
fi
fi
@@ -364,8 +352,8 @@ create_gateway_log_file
echo "=> 启动 aether-gateway (Rust frontdoor: 0.0.0.0:$${APP_PORT})..."
echo "=> 日志过滤: $${RUST_LOG}"
echo "=> 执行命令: cargo run -p aether-gateway --bin aether-gateway -- --app-port $${APP_PORT}"
cargo run -p aether-gateway --bin aether-gateway -- --app-port "$${APP_PORT}" > >(
echo "=> 执行命令: cargo run -p aether-gateway -- --app-port $${APP_PORT}"
cargo run -p aether-gateway -- --app-port "$${APP_PORT}" > >(
tee -a "$${GATEWAY_LOG_FILE}"
) 2>&1 &
GATEWAY_PID=$$!
@@ -456,7 +444,7 @@ if [ -f .env ]; then
fi
export APP_PORT="$${APP_PORT:-8084}"
echo "=> 启动后端: RUST_LOG=$${DEV_RUST_LOG} cargo run -p aether-gateway --bin aether-gateway -- --app-port $${APP_PORT:-8084}"
echo "=> 启动后端: RUST_LOG=$${DEV_RUST_LOG} cargo run -p aether-gateway -- --app-port $${APP_PORT:-8084}"
/bin/bash -euo pipefail -c "$$DEV_BACKEND_SCRIPT" &
backend_pid=$$!
@@ -506,14 +494,8 @@ export DEV_SCRIPT
define DB_TASK_SCRIPT
set -euo pipefail
if [ -z "$${DB_TASK_COMMAND:-}" ] || [ -z "$${DB_TASK_LABEL:-}" ]; then
echo "=> 内部错误: DB_TASK_COMMAND / DB_TASK_LABEL 未设置"
exit 1
fi
read -r -a db_task_args <<< "$${DB_TASK_COMMAND}"
if [ "$${#db_task_args[@]}" -eq 0 ]; then
echo "=> 内部错误: DB_TASK_COMMAND 为空"
if [ -z "$${DB_TASK_FLAG:-}" ] || [ -z "$${DB_TASK_LABEL:-}" ]; then
echo "=> 内部错误: DB_TASK_FLAG / DB_TASK_LABEL 未设置"
exit 1
fi
@@ -564,8 +546,8 @@ if ! command -v cargo >/dev/null 2>&1; then
exit 1
fi
echo "=> 执行 $${DB_TASK_LABEL}: cargo run -p aether-gateway --bin aether-gateway -- $${db_task_args[*]}"
exec cargo run -p aether-gateway --bin aether-gateway -- "$${db_task_args[@]}"
echo "=> 执行 $${DB_TASK_LABEL}: cargo run -p aether-gateway -- $${DB_TASK_FLAG}"
exec cargo run -p aether-gateway -- "$${DB_TASK_FLAG}"
endef
export DB_TASK_SCRIPT
@@ -578,14 +560,8 @@ dev-backend:
dev-frontend:
@cd frontend && npm run dev
db-status:
@DB_TASK_COMMAND="db status" DB_TASK_LABEL="数据库状态检查" $(SHELL) -euo pipefail -c "$$DB_TASK_SCRIPT"
db-prepare:
@DB_TASK_COMMAND="db prepare" DB_TASK_LABEL="数据库准备" $(SHELL) -euo pipefail -c "$$DB_TASK_SCRIPT"
migration:
@DB_TASK_COMMAND="--migrate" DB_TASK_LABEL="数据库迁移" $(SHELL) -euo pipefail -c "$$DB_TASK_SCRIPT"
@DB_TASK_FLAG=--migrate DB_TASK_LABEL="数据库迁移" $(SHELL) -euo pipefail -c "$$DB_TASK_SCRIPT"
backfill:
@DB_TASK_COMMAND="--apply-backfills" DB_TASK_LABEL="数据库 backfill" $(SHELL) -euo pipefail -c "$$DB_TASK_SCRIPT"
@DB_TASK_FLAG=--apply-backfills DB_TASK_LABEL="数据库 backfill" $(SHELL) -euo pipefail -c "$$DB_TASK_SCRIPT"
+1 -9
View File
@@ -128,7 +128,6 @@ Docker Compose 用户可在部署目录的 `.env` 中设置 `APP_IMAGE=ghcr.io/f
## 本地开发
依赖 Docker、Rust toolchain、Node.js 和 make。
首次启动前需要在 `.env` 中设置 `ADMIN_PASSWORD`,用于创建本地管理员。
```bash
make dev
@@ -136,12 +135,6 @@ make dev
`make dev` 会同时启动后端 `aether-gateway` 和前端 `frontend` 的 Vite dev server。需要单独启动时可使用 `make dev-backend` 或 `make dev-frontend`。
Postgres / Redis 本地依赖未就绪时,`make dev` 会自动执行 `docker compose up -d postgres redis`。
数据库 schema 和历史数据准备也会在启动时自动完成;通常不需要手动区分 migration 与 backfill。排查或部署前预执行时可使用:
```bash
make db-status
make db-prepare
```
## Codex 远程协同
@@ -180,8 +173,7 @@ Aether Tunnel 是配套的正向代理节点,部署在海外 VPS 上,为墙
- `AETHER_MAX_REDACTED_SYNC_RESPONSE_BODY_MB`:可选的 PII 恢复同步响应缓冲上限;未配置或设为 `0` 时不限制
- `REDIS_URL`:Redis 连接串;仅 Postgres + Redis 的 Docker Compose 部署需要配置
- `AETHER_RUNTIME_BACKEND=memory|redis`:运行时缓存/协调后端。SQLite 默认用 `memory`,不会连接 Redis;多节点部署和需要跨 gateway 重启恢复 OpenAI Responses continuation history 的部署必须使用共享 Redis
- `AETHER_GATEWAY_DATABASE_MODE=auto|verify-only`:数据库启动策略,默认 `auto`,自动完成挂起的 schema migration 和 backfill;`verify-only` 仅检查并在数据库落后时拒绝启动
- `AETHER_GATEWAY_AUTO_PREPARE_DATABASE`:旧版兼容开关;新配置请使用 `AETHER_GATEWAY_DATABASE_MODE`
- `AETHER_GATEWAY_AUTO_PREPARE_DATABASE`:常规启动前自动执行挂起的 schema migration 和 backfill;仓库自带的 `docker-compose.yml` 默认开启
- `JWT_SECRET_KEY` / `ENCRYPTION_KEY`:认证和敏感数据加密所需密钥
- `API_KEY_PREFIX`:用户和管理员新建 API Key 时使用的前缀,默认 `sk`
- `ADMIN_USERNAME` / `ADMIN_PASSWORD` / `ADMIN_EMAIL`:首次启动时自举首个本地管理员;`install.sh` 会提示输入管理员密码
@@ -9,7 +9,7 @@ use aether_ai_serving::{
use aether_dispatch_core::{DispatchSequence, DispatchSequenceItem};
use aether_routing_core::{
rank_vector_for_candidate, CandidateKind, ResolvedRoutingPolicy, RoutingCandidateFacts,
RoutingCandidateTrace, RoutingDecisionTrace, RoutingExecutionPolicy,
RoutingCandidateTrace, RoutingDecisionTrace,
};
use aether_scheduler_core::{
ClientSessionAffinity, SchedulerMinimalCandidateSelectionCandidate, SchedulerRankingOutcome,
@@ -79,13 +79,6 @@ type DecorateSkippedCandidateFn<'a> = Arc<
pub(crate) trait LocalExecutionAttemptSource<T>: Send {
async fn next_execution_attempt(&mut self) -> Result<Option<T>, GatewayError>;
/// Returns the request-scoped execution behaviour selected by routing.
/// Execution wrappers use this snapshot before consuming the first
/// attempt, avoiding a second lookup against mutable system settings.
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
None
}
async fn drain_execution_attempts(&mut self) -> Result<Vec<T>, GatewayError>;
async fn skip_credential(&mut self, key_id: &str) -> Result<(), GatewayError>;
@@ -1244,7 +1237,9 @@ async fn scheduler_cache_affinity_enabled(
state: PlannerAppState<'_>,
routing_policy: Option<&ResolvedRoutingPolicy>,
) -> bool {
scheduler_ordering_config_for_routing_policy(routing_policy).scheduling_mode
scheduler_ordering_config_for_routing_policy(state, routing_policy)
.await
.scheduling_mode
== SchedulerSchedulingMode::CacheAffinity
}
@@ -6,11 +6,14 @@ use aether_ai_serving::{
use aether_routing_core::ResolvedRoutingPolicy;
use async_trait::async_trait;
use tokio::sync::Mutex;
use tracing::warn;
use crate::ai_serving::{GatewayAuthApiKeySnapshot, PlannerAppState};
use crate::clock::current_unix_ms;
use crate::handlers::shared::provider_pool::admin_provider_pool_config_from_config_value;
use crate::scheduler::config::{SchedulerOrderingConfig, SchedulerSchedulingMode};
use crate::scheduler::config::{
read_scheduler_ordering_config, SchedulerOrderingConfig, SchedulerSchedulingMode,
};
use aether_scheduler_core::{
matches_affinity_target, ClientSessionAffinity, SchedulerAffinityTarget,
SchedulerMinimalCandidateSelectionCandidate, SchedulerPriorityMode, SchedulerRankableCandidate,
@@ -130,7 +133,7 @@ pub(crate) async fn rank_eligible_local_execution_candidates(
required_capabilities: Option<&serde_json::Value>,
routing_policy: Option<&ResolvedRoutingPolicy>,
) -> Vec<EligibleLocalExecutionCandidate> {
let ordering_config = scheduler_ordering_config_for_routing_policy(routing_policy);
let ordering_config = scheduler_ordering_config_for_routing_policy(state, routing_policy).await;
let port = GatewayLocalCandidateRankingPort {
state,
requested_model,
@@ -181,24 +184,16 @@ fn ai_ranking_scheduling_mode(mode: SchedulerSchedulingMode) -> AiRankingSchedul
}
}
/// Return the immutable scheduler snapshot carried by a resolved routing
/// policy. A missing policy is a programming error in production request
/// paths; unit tests may use the scheduler default for isolated ranking tests.
pub(crate) fn scheduler_ordering_config_for_routing_policy(
/// Ordering config for a request. A resolved routing policy is authoritative
/// and is never merged with legacy system-config values; without a policy the
/// effective default (system-default routing group, then legacy keys) applies.
pub(crate) async fn scheduler_ordering_config_for_routing_policy(
state: PlannerAppState<'_>,
routing_policy: Option<&ResolvedRoutingPolicy>,
) -> SchedulerOrderingConfig {
match routing_policy {
Some(policy) => SchedulerOrderingConfig::from_routing_policy(policy),
None => {
#[cfg(test)]
{
SchedulerOrderingConfig::default()
}
#[cfg(not(test))]
{
panic!("resolved routing policy is required before candidate scheduling")
}
}
None => read_scheduler_ordering_config_or_default(state).await,
}
}
@@ -243,6 +238,23 @@ fn routing_overlaid_candidate(
overlaid
}
async fn read_scheduler_ordering_config_or_default(
state: PlannerAppState<'_>,
) -> SchedulerOrderingConfig {
match read_scheduler_ordering_config(state.app()).await {
Ok(config) => config,
Err(error) => {
warn!(
event_name = "planner_scheduler_ordering_config_load_failed",
log_type = "event",
error = ?error,
"failed to load scheduler ordering config while ranking local execution candidates"
);
SchedulerOrderingConfig::default()
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
@@ -251,16 +263,10 @@ mod tests {
use aether_ai_serving::{
ai_ranking_context, build_ai_rankable_candidate, AiRankableCandidateParts,
};
use aether_data::repository::{
provider_catalog::InMemoryProviderCatalogReadRepository,
routing_profiles::InMemoryRoutingGroupRepository,
};
use aether_data::repository::provider_catalog::InMemoryProviderCatalogReadRepository;
use aether_data_contracts::repository::provider_catalog::{
StoredProviderCatalogEndpoint, StoredProviderCatalogKey, StoredProviderCatalogProvider,
};
use aether_data_contracts::repository::routing_profiles::{
CreateRoutingGroupRecord, RoutingGroupWriteRepository,
};
use aether_scheduler_core::{
apply_scheduler_candidate_ranking,
build_scheduler_affinity_cache_key_for_api_key_id_with_client_session,
@@ -290,11 +296,7 @@ mod tests {
required_capabilities: Option<&serde_json::Value>,
) -> Vec<SchedulerMinimalCandidateSelectionCandidate> {
let normalized_client_api_format = client_api_format.trim().to_ascii_lowercase();
let ordering_config =
crate::scheduler::config::read_system_default_routing_ordering_config(state.app())
.await
.expect("routing strategy should load")
.unwrap_or_default();
let ordering_config = super::read_scheduler_ordering_config_or_default(state).await;
let mut candidates = candidates;
let mut rankables = Vec::with_capacity(candidates.len());
let mut ordering_cache = CandidateTransportRankingFactsCache::default();
@@ -370,7 +372,6 @@ mod tests {
scheduling_mode: aether_routing_core::RoutingSchedulingMode::CacheAffinity,
keep_priority_on_conversion: false,
sticky_key_attempts: aether_routing_core::DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: Default::default(),
ranking_overlay: aether_routing_core::RankingOverlay::default(),
mutation_plan: Default::default(),
pool_policy_overrides: BTreeMap::new(),
@@ -407,14 +408,17 @@ mod tests {
scheduling_mode: aether_routing_core::RoutingSchedulingMode::FixedOrder,
keep_priority_on_conversion: false,
sticky_key_attempts: aether_routing_core::DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: Default::default(),
ranking_overlay: Default::default(),
mutation_plan: Default::default(),
pool_policy_overrides: Default::default(),
matched_rules: Vec::new(),
};
let ordering = super::scheduler_ordering_config_for_routing_policy(Some(&policy));
let ordering = super::scheduler_ordering_config_for_routing_policy(
PlannerAppState::new(&state),
Some(&policy),
)
.await;
assert_eq!(
ordering.scheduling_mode,
@@ -442,7 +446,6 @@ mod tests {
scheduling_mode: aether_routing_core::RoutingSchedulingMode::CacheAffinity,
keep_priority_on_conversion: false,
sticky_key_attempts: aether_routing_core::DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: Default::default(),
ranking_overlay: aether_routing_core::RankingOverlay {
pool_priority_overrides: BTreeMap::from([("provider-1".to_string(), 4)]),
key_priority_overrides: BTreeMap::from([("representative-key".to_string(), 1)]),
@@ -914,8 +917,7 @@ mod tests {
}
#[tokio::test]
async fn local_execution_ranking_keeps_cross_format_priority_when_strategy_override_is_enabled()
{
async fn local_execution_ranking_keeps_cross_format_priority_when_global_override_is_enabled() {
let provider_catalog = InMemoryProviderCatalogReadRepository::seed(
vec![
sample_provider_with_options("provider-same", false, 10),
@@ -930,32 +932,14 @@ mod tests {
sample_key_for_provider("provider-cross", "key-cross", ""),
],
);
let routing_repository = std::sync::Arc::new(InMemoryRoutingGroupRepository::default());
routing_repository
.create_routing_group(CreateRoutingGroupRecord {
id: "strategy-default".to_string(),
name: "strategy-default".to_string(),
description: None,
enabled: true,
is_system_default: true,
sort_order: 0,
config_json: json!({
"default_policy": {
"keep_priority_on_conversion": true
}
}),
version: 1,
created_at: 1,
updated_at: 1,
published_at: None,
})
.await
.expect("routing strategy should be created");
let data_state = GatewayDataState::with_provider_transport_reader_for_tests(
std::sync::Arc::new(provider_catalog),
"development-key",
)
.with_routing_group_repository_for_tests(routing_repository);
.with_system_config_values_for_tests(vec![(
"keep_priority_on_conversion".to_string(),
json!(true),
)]);
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(data_state);
@@ -384,7 +384,8 @@ async fn resolve_and_rank_local_execution_candidates_with_pool_expansion(
None
} else {
Some(
scheduler_ordering_config_for_routing_policy(routing_policy)
scheduler_ordering_config_for_routing_policy(state, routing_policy)
.await
.sticky_key_attempts,
)
};
@@ -174,9 +174,8 @@ impl AiCandidatePreselectionPort for GatewayLocalCandidatePreselectionPort<'_> {
self.ranking_seed,
false,
self.request_operation,
super::candidate_ranking::scheduler_ordering_config_for_routing_policy(
self.routing_policy,
),
self.routing_policy
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await?;
@@ -428,7 +427,11 @@ impl<'a> LocalCandidatePreselectionPageCursor<'a> {
);
let ordering_config =
super::candidate_ranking::scheduler_ordering_config_for_routing_policy(routing_policy);
super::candidate_ranking::scheduler_ordering_config_for_routing_policy(
state,
routing_policy,
)
.await;
Self {
state,
@@ -1290,7 +1293,9 @@ impl<'a> LocalCandidatePreselectionPageCursor<'a> {
.then_some(self.client_session_affinity.as_ref())
.flatten(),
self.ranking_seed,
self.ordering_config,
self.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await?;
let skipped_candidates = skipped_candidates
@@ -1885,7 +1890,6 @@ mod tests {
scheduling_mode: aether_routing_core::RoutingSchedulingMode::FixedOrder,
keep_priority_on_conversion: false,
sticky_key_attempts: aether_routing_core::DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: Default::default(),
ranking_overlay: Default::default(),
mutation_plan: Default::default(),
pool_policy_overrides: Default::default(),
@@ -1950,7 +1954,6 @@ mod tests {
scheduling_mode: aether_routing_core::RoutingSchedulingMode::FixedOrder,
keep_priority_on_conversion: false,
sticky_key_attempts: aether_routing_core::DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: Default::default(),
ranking_overlay: Default::default(),
mutation_plan: Default::default(),
pool_policy_overrides: Default::default(),
@@ -2689,7 +2692,6 @@ mod tests {
scheduling_mode: aether_routing_core::RoutingSchedulingMode::FixedOrder,
keep_priority_on_conversion: true,
sticky_key_attempts: aether_routing_core::DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: Default::default(),
ranking_overlay: Default::default(),
mutation_plan: Default::default(),
pool_policy_overrides: Default::default(),
@@ -625,17 +625,21 @@ pub(crate) async fn attach_routing_policy_to_local_requested_model_input(
GatewayRoutingSelectionError::NotFound(explicit_group.unwrap_or_default()),
));
}
return Err(routing_selection_error(
GatewayRoutingSelectionError::NoDefault,
));
None
}
};
let Some((group_id, group_version, group_config_json, selection_source)) = selected_group
else {
return Err(routing_selection_error(
GatewayRoutingSelectionError::NoDefault,
));
input.client_session_affinity = client_session_affinity_from_api_request(
client_api_format,
&parts.headers,
Some(body_json),
);
input.routing_policy = None;
input.routing_trace_seed = None;
input.routing_context = None;
return Ok(());
};
if try_attach_static_default_routing_policy_to_input(
@@ -859,10 +863,6 @@ fn routing_selection_error(error: GatewayRoutingSelectionError) -> GatewayError
GatewayRoutingSelectionError::Repository(message) => {
GatewayError::Internal(format!("routing group repository lookup failed: {message}"))
}
GatewayRoutingSelectionError::NoDefault => GatewayError::Client {
status: StatusCode::SERVICE_UNAVAILABLE,
message: "no enabled routing strategy is configured for this request".to_string(),
},
error => GatewayError::Client {
status: StatusCode::FORBIDDEN,
message: error.to_string(),
@@ -1207,7 +1207,6 @@ mod tests {
description: None,
enabled: true,
is_system_default: false,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -26,6 +26,7 @@ use crate::ai_serving::{
};
use crate::client_session_affinity::client_session_affinity_from_api_request;
use crate::clock::current_unix_secs;
use crate::scheduler::config::SchedulerOrderingConfig;
use crate::{AppState, GatewayError};
use super::{
@@ -140,9 +141,10 @@ pub(crate) async fn materialize_local_same_format_provider_candidate_attempts(
current_unix_secs(),
false,
spec.operation.map(|operation| operation.as_str()),
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await?;
let outcome = materialize_local_execution_candidates_with_serving(
@@ -249,9 +251,10 @@ pub(crate) async fn build_local_same_format_provider_candidate_attempt_source<'a
current_unix_secs(),
false,
spec.operation.map(|operation| operation.as_str()),
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await?;
@@ -26,7 +26,6 @@ use super::{
LocalSameFormatProviderCandidateAttemptSource, LocalSameFormatProviderDecisionInput,
LocalSameFormatProviderSpec,
};
use aether_routing_core::RoutingExecutionPolicy;
pub(crate) struct LocalSameFormatProviderSyncAttemptSource<'a> {
state: &'a AppState,
@@ -190,13 +189,6 @@ pub(crate) async fn build_local_stream_attempt_source<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalSameFormatProviderSyncAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiSyncAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_sync_attempt(attempt).await? {
@@ -242,13 +234,6 @@ impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalSameFormatProviderSyncA
impl LocalExecutionAttemptSource<AiStreamAttempt>
for LocalSameFormatProviderStreamAttemptSource<'_>
{
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiStreamAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_stream_attempt(attempt).await? {
@@ -21,8 +21,7 @@ use crate::client_session_affinity::{
};
use crate::orchestration::{
insert_pool_key_lease_report_context_fields, ExecutionAttemptIdentity,
ROUTING_EXECUTION_POLICY_REPORT_FIELD, ROUTING_POOL_POLICY_OVERRIDE_REPORT_FIELD,
SCHEDULER_AFFINITY_EPOCH_REPORT_FIELD,
ROUTING_POOL_POLICY_OVERRIDE_REPORT_FIELD, SCHEDULER_AFFINITY_EPOCH_REPORT_FIELD,
};
use crate::scheduler::affinity::insert_scheduler_affinity_policy_report_context_field;
@@ -113,11 +112,6 @@ pub(crate) fn build_local_execution_report_context(
}
insert_pool_key_lease_report_context_fields(&mut extra_fields, parts.pool_key_lease);
insert_scheduler_affinity_policy_report_context_field(&mut extra_fields, parts.routing_policy);
if let Some(policy) = parts.routing_policy {
if let Ok(value) = serde_json::to_value(policy.execution_policy) {
extra_fields.insert(ROUTING_EXECUTION_POLICY_REPORT_FIELD.to_string(), value);
}
}
if let Some(override_policy) = parts
.routing_policy
.and_then(|policy| policy.pool_policy_overrides.get(parts.provider_id))
@@ -17,7 +17,6 @@ use crate::ai_serving::{
resolve_gemini_files_sync_spec as resolve_sync_spec, LocalGeminiFilesSpec,
};
use crate::{AiExecutionDecision, AppState, GatewayError};
use aether_routing_core::RoutingExecutionPolicy;
use self::decision::maybe_build_local_gemini_files_decision_payload_for_candidate;
use self::support::{
@@ -175,13 +174,6 @@ pub(crate) async fn build_local_gemini_files_stream_attempt_source_for_kind<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalGeminiFilesSyncAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiSyncAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_sync_attempt(attempt).await? {
@@ -220,13 +212,6 @@ impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalGeminiFilesSyncAttemptS
#[async_trait]
impl LocalExecutionAttemptSource<AiStreamAttempt> for LocalGeminiFilesStreamAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiStreamAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_stream_attempt(attempt).await? {
@@ -26,6 +26,7 @@ use crate::ai_serving::{
};
use crate::client_session_affinity::client_session_affinity_from_parts;
use crate::clock::current_unix_secs;
use crate::scheduler::config::SchedulerOrderingConfig;
use crate::{AppState, GatewayError};
pub(super) use crate::ai_serving::planner::candidate_materialization::LocalExecutionCandidateAttempt as LocalGeminiFilesCandidateAttempt;
@@ -108,9 +109,10 @@ pub(super) async fn materialize_local_gemini_files_candidate_attempts(
Some(&input.auth_snapshot),
input.client_session_affinity.as_ref(),
current_unix_secs(),
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await?;
let outcome = materialize_local_execution_candidates_with_serving(
@@ -184,9 +186,10 @@ pub(super) async fn build_local_gemini_files_candidate_attempt_source<'a>(
Some(&input.auth_snapshot),
input.client_session_affinity.as_ref(),
current_unix_secs(),
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await?;
Ok(build_local_execution_candidate_attempt_source_with_serving(
@@ -19,7 +19,6 @@ use crate::ai_serving::{
resolve_local_image_sync_spec as resolve_sync_spec,
};
use crate::{AiExecutionDecision, AppState, GatewayError};
use aether_routing_core::RoutingExecutionPolicy;
use self::decision::maybe_build_local_openai_image_decision_payload_for_candidate;
use self::support::{
@@ -253,13 +252,6 @@ pub(crate) async fn build_local_image_stream_attempt_source_for_kind<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalOpenAiImageSyncAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiSyncAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_sync_attempt(attempt).await? {
@@ -298,13 +290,6 @@ impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalOpenAiImageSyncAttemptS
#[async_trait]
impl LocalExecutionAttemptSource<AiStreamAttempt> for LocalOpenAiImageStreamAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiStreamAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_stream_attempt(attempt).await? {
@@ -27,6 +27,7 @@ use crate::ai_serving::{
};
use crate::client_session_affinity::client_session_affinity_from_parts;
use crate::clock::current_unix_secs;
use crate::scheduler::config::SchedulerOrderingConfig;
use crate::{AppState, GatewayError};
use aether_scheduler_core::SchedulerMinimalCandidateSelectionCandidate;
@@ -127,9 +128,10 @@ pub(super) async fn list_local_openai_image_candidate_attempts(
input.client_session_affinity.as_ref(),
current_unix_secs(),
false,
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await
{
@@ -204,9 +206,10 @@ pub(super) async fn build_local_openai_image_candidate_attempt_source<'a>(
input.client_session_affinity.as_ref(),
current_unix_secs(),
false,
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await
{
@@ -16,7 +16,6 @@ use crate::ai_serving::{
LocalVideoCreateSpec,
};
use crate::{AiExecutionDecision, AppState, GatewayError};
use aether_routing_core::RoutingExecutionPolicy;
use self::decision::maybe_build_local_video_create_decision_payload_for_candidate;
use self::support::{
@@ -105,13 +104,6 @@ pub(crate) async fn build_local_video_sync_attempt_source_for_kind<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalVideoCreateSyncAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiSyncAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_sync_attempt(attempt).await? {
@@ -29,6 +29,7 @@ use crate::ai_serving::{
};
use crate::client_session_affinity::client_session_affinity_from_parts;
use crate::clock::current_unix_secs;
use crate::scheduler::config::SchedulerOrderingConfig;
use crate::{AppState, GatewayError};
pub(super) use crate::ai_serving::planner::candidate_materialization::LocalExecutionCandidateAttempt as LocalVideoCreateCandidateAttempt;
@@ -133,9 +134,10 @@ pub(super) async fn list_local_video_create_candidate_attempts(
input.client_session_affinity.as_ref(),
current_unix_secs(),
false,
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await
{
@@ -193,9 +195,10 @@ pub(super) async fn build_local_video_create_candidate_attempt_source<'a>(
input.client_session_affinity.as_ref(),
current_unix_secs(),
false,
crate::ai_serving::planner::candidate_ranking::scheduler_ordering_config_for_routing_policy(
input.routing_policy.as_ref(),
),
input
.routing_policy
.as_ref()
.map(SchedulerOrderingConfig::from_routing_policy),
)
.await
{
@@ -18,7 +18,6 @@ use crate::ai_serving::planner::spec_metadata::{
};
use crate::ai_serving::GatewayControlDecision;
use crate::{AiExecutionDecision, AppState, GatewayError};
use aether_routing_core::RoutingExecutionPolicy;
use super::candidates::{
build_local_standard_candidate_attempt_source, resolve_local_standard_decision_input,
@@ -178,13 +177,6 @@ pub(crate) async fn build_local_stream_attempt_source<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalStandardSyncAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiSyncAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_sync_attempt(attempt).await? {
@@ -228,13 +220,6 @@ impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalStandardSyncAttemptSour
#[async_trait]
impl LocalExecutionAttemptSource<AiStreamAttempt> for LocalStandardStreamAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiStreamAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_stream_attempt(attempt).await? {
@@ -1,4 +1,3 @@
use aether_routing_core::RoutingExecutionPolicy;
use async_trait::async_trait;
use std::collections::VecDeque;
use tracing::warn;
@@ -120,13 +119,6 @@ pub(crate) async fn build_local_openai_chat_stream_attempt_source<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiStreamAttempt> for LocalOpenAiChatStreamAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiStreamAttempt>, GatewayError> {
let select_started_at = std::time::Instant::now();
let selected = self.next_execution_attempt_with_target_select().await?;
@@ -1,4 +1,3 @@
use aether_routing_core::RoutingExecutionPolicy;
use async_trait::async_trait;
use tracing::warn;
@@ -93,13 +92,6 @@ pub(crate) async fn build_local_openai_chat_sync_attempt_source<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalOpenAiChatSyncAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiSyncAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_sync_attempt(attempt).await? {
@@ -1,4 +1,3 @@
use aether_routing_core::RoutingExecutionPolicy;
use async_trait::async_trait;
use tracing::warn;
@@ -162,13 +161,6 @@ pub(super) async fn build_local_stream_attempt_source<'a>(
#[async_trait]
impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalOpenAiResponsesSyncAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiSyncAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_sync_attempt(attempt).await? {
@@ -212,13 +204,6 @@ impl LocalExecutionAttemptSource<AiSyncAttempt> for LocalOpenAiResponsesSyncAtte
#[async_trait]
impl LocalExecutionAttemptSource<AiStreamAttempt> for LocalOpenAiResponsesStreamAttemptSource<'_> {
fn routing_execution_policy(&self) -> Option<RoutingExecutionPolicy> {
self.input
.routing_policy
.as_ref()
.map(|policy| policy.execution_policy)
}
async fn next_execution_attempt(&mut self) -> Result<Option<AiStreamAttempt>, GatewayError> {
while let Some(attempt) = self.candidates.next_attempt().await? {
match self.build_stream_attempt(attempt).await? {
@@ -12,8 +12,9 @@ use crate::scheduler::config::SchedulerOrderingConfig;
use crate::GatewayError;
impl<'a> PlannerAppState<'a> {
/// `ordering_config` is the immutable scheduler snapshot derived from the
/// request's resolved routing policy.
/// `ordering_config` is the request's routing-policy derived scheduler
/// config (see `SchedulerOrderingConfig::from_routing_policy`). `None`
/// falls back to the runtime default.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn list_selectable_candidates(
self,
@@ -25,7 +26,7 @@ impl<'a> PlannerAppState<'a> {
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
enable_model_directives: bool,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<Vec<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
crate::scheduler::candidate::list_selectable_candidates(
self.app().data.as_ref(),
@@ -54,7 +55,7 @@ impl<'a> PlannerAppState<'a> {
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
enable_model_directives: bool,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<
(
Vec<SchedulerMinimalCandidateSelectionCandidate>,
@@ -89,7 +90,7 @@ impl<'a> PlannerAppState<'a> {
now_unix_secs: u64,
enable_model_directives: bool,
request_operation: Option<&str>,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<
(
Vec<SchedulerMinimalCandidateSelectionCandidate>,
@@ -145,7 +146,7 @@ impl<'a> PlannerAppState<'a> {
auth_snapshot: Option<&GatewayAuthApiKeySnapshot>,
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<
(
Vec<SchedulerMinimalCandidateSelectionCandidate>,
@@ -176,7 +177,7 @@ impl<'a> PlannerAppState<'a> {
auth_snapshot: Option<&GatewayAuthApiKeySnapshot>,
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<Vec<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
let wait_timeout = Duration::from_millis(API_KEY_CONCURRENCY_WAIT_TIMEOUT_MS);
let wait_interval = Duration::from_millis(API_KEY_CONCURRENCY_WAIT_POLL_INTERVAL_MS.max(1));
@@ -5077,7 +5077,6 @@ mod tests {
scheduling_mode: RoutingSchedulingMode::CacheAffinity,
keep_priority_on_conversion: false,
sticky_key_attempts: aether_routing_core::DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: Default::default(),
ranking_overlay: RankingOverlay {
allowed_keys: key_ids.into_iter().map(str::to_string).collect(),
..RankingOverlay::default()
@@ -118,7 +118,8 @@ use crate::execution_runtime::{
use crate::log_ids::short_request_id;
use crate::orchestration::{
apply_local_execution_effect, build_local_error_flow_metadata, classify_failure_disposition,
spawn_local_oauth_success_effect, trace_upstream_response_body, with_error_flow_report_context,
cyber_continue_failover_enabled, spawn_local_oauth_success_effect,
trace_upstream_response_body, with_error_flow_report_context,
with_upstream_response_report_context, FailureDisposition, FailureTokenAction,
LocalAdaptiveRateLimitEffect, LocalAdaptiveSuccessEffect, LocalAttemptFailureEffect,
LocalExecutionEffect, LocalExecutionEffectContext, LocalFailoverAnalysis,
@@ -6172,10 +6173,7 @@ async fn execute_stream_from_frame_stream_with_retry_scope(
}
let prefetch_for_cyber_failover =
is_openai_responses_family_format(plan.provider_api_format.as_str())
&& crate::orchestration::routing_execution_policy_from_report_context(
report_context.as_ref(),
)
.is_some_and(|policy| policy.cyber_continue_failover);
&& cyber_continue_failover_enabled(state).await;
let stream_commit_policy = StreamCommitPolicy::for_response(
direct_stream_finalize_kind.is_some(),
upstream_content_type,
@@ -8503,6 +8501,14 @@ mod tests {
Arc::new(provider_catalog),
"development-key",
);
let data_state = if continue_failover {
data_state.with_system_config_values_for_tests([(
crate::orchestration::CYBER_CONTINUE_FAILOVER_CONFIG_KEY.to_string(),
json!(true),
)])
} else {
data_state
};
let state = AppState::new()
.expect("app state should build")
.with_data_state_for_tests(data_state);
@@ -8551,10 +8557,7 @@ mod tests {
"candidate_index": 0,
"retry_index": 0,
"provider_api_format": "openai:responses",
"client_api_format": "openai:responses",
"routing_execution_policy": {
"cyber_continue_failover": continue_failover
}
"client_api_format": "openai:responses"
})),
crate::clock::current_unix_ms(),
Instant::now(),
@@ -10512,7 +10515,7 @@ mod tests {
}
#[tokio::test]
async fn prefetched_codex_cyber_policy_violation_retries_when_routing_strategy_is_enabled() {
async fn prefetched_codex_cyber_policy_violation_retries_when_system_setting_is_enabled() {
assert!(
execute_prefetched_codex_cyber_policy_failure(true)
.await
@@ -54,10 +54,13 @@ use crate::executor::{
record_failed_usage_for_exhausted_request, LocalExecutionExhaustion,
LocalExecutionRequestOutcome,
};
use crate::handlers::shared::system_config_bool;
use crate::request_diagnostics::{current_request_diagnostics, scope_request_diagnostics_with};
use crate::stage_metrics::observe_gateway_stage_ms;
use crate::{AiExecutionDecision, AppState, GatewayError};
const ENABLE_OPENAI_IMAGE_SYNC_HEARTBEAT_CONFIG_KEY: &str = "enable_openai_image_sync_heartbeat";
const ENABLE_STANDARD_TEXT_SYNC_HEARTBEAT_CONFIG_KEY: &str = "enable_standard_text_sync_heartbeat";
const OPENAI_IMAGE_SYNC_HEARTBEAT_INTERNAL_ERROR_STATUS: u16 = 502;
const OPENAI_IMAGE_SYNC_HEARTBEAT_EXHAUSTED_STATUS: u16 = 503;
const OPENAI_IMAGE_SYNC_HEARTBEAT_ERROR_MESSAGE_LIMIT: usize = 4096;
@@ -104,10 +107,7 @@ pub(crate) async fn maybe_execute_sync_via_local_decision(
return Ok(LocalExecutionRequestOutcome::NoPath);
};
if standard_text_sync_heartbeat_should_wrap(
plan_kind,
attempt_source.routing_execution_policy(),
) {
if standard_text_sync_heartbeat_should_wrap(state, plan_kind).await {
let parts_for_task = parts.clone();
let body_json_for_task = body_json.clone();
let transfer_tracker_for_task = transfer_tracker.clone();
@@ -264,10 +264,7 @@ pub(crate) async fn maybe_execute_sync_via_local_openai_responses_decision(
return Ok(LocalExecutionRequestOutcome::NoPath);
};
if standard_text_sync_heartbeat_should_wrap(
plan_kind,
attempt_source.routing_execution_policy(),
) {
if standard_text_sync_heartbeat_should_wrap(state, plan_kind).await {
let parts_for_task = parts.clone();
let body_json_for_task = body_json.clone();
let transfer_tracker_for_task = transfer_tracker.clone();
@@ -384,10 +381,7 @@ pub(crate) async fn maybe_execute_sync_via_standard_family_decision(
return Ok(LocalExecutionRequestOutcome::NoPath);
};
if standard_text_sync_heartbeat_should_wrap(
plan_kind,
attempt_source.routing_execution_policy(),
) {
if standard_text_sync_heartbeat_should_wrap(state, plan_kind).await {
let parts_for_task = parts.clone();
let body_json_for_task = body_json.clone();
let transfer_tracker_for_task = transfer_tracker.clone();
@@ -615,10 +609,7 @@ pub(crate) async fn maybe_execute_sync_via_local_same_format_provider_decision(
return Ok(LocalExecutionRequestOutcome::NoPath);
};
if standard_text_sync_heartbeat_should_wrap(
plan_kind,
attempt_source.routing_execution_policy(),
) {
if standard_text_sync_heartbeat_should_wrap(state, plan_kind).await {
let parts_for_task = parts.clone();
let body_json_for_task = body_json.clone();
let transfer_tracker_for_task = transfer_tracker.clone();
@@ -755,6 +746,42 @@ pub(crate) async fn maybe_execute_sync_via_local_gemini_files_decision(
.await
}
async fn openai_image_sync_heartbeat_enabled(state: &AppState) -> bool {
match state
.read_system_config_json_value(ENABLE_OPENAI_IMAGE_SYNC_HEARTBEAT_CONFIG_KEY)
.await
{
Ok(value) => system_config_bool(value.as_ref(), false),
Err(err) => {
tracing::warn!(
event_name = "openai_image_sync_heartbeat_config_read_failed",
log_type = "ops",
error = ?err,
"gateway failed to read sync image heartbeat config; defaulting disabled"
);
false
}
}
}
async fn standard_text_sync_heartbeat_enabled(state: &AppState) -> bool {
match state
.read_system_config_json_value(ENABLE_STANDARD_TEXT_SYNC_HEARTBEAT_CONFIG_KEY)
.await
{
Ok(value) => system_config_bool(value.as_ref(), false),
Err(err) => {
tracing::warn!(
event_name = "standard_text_sync_heartbeat_config_read_failed",
log_type = "ops",
error = ?err,
"gateway failed to read standard text sync heartbeat config; defaulting disabled"
);
false
}
}
}
fn standard_text_sync_heartbeat_applies_to_plan_kind(plan_kind: &str) -> bool {
matches!(
plan_kind,
@@ -768,12 +795,9 @@ fn standard_text_sync_heartbeat_applies_to_plan_kind(plan_kind: &str) -> bool {
)
}
fn standard_text_sync_heartbeat_should_wrap(
plan_kind: &str,
execution_policy: Option<aether_routing_core::RoutingExecutionPolicy>,
) -> bool {
async fn standard_text_sync_heartbeat_should_wrap(state: &AppState, plan_kind: &str) -> bool {
standard_text_sync_heartbeat_applies_to_plan_kind(plan_kind)
&& execution_policy.is_some_and(|policy| policy.enable_cf_heartbeat)
&& standard_text_sync_heartbeat_enabled(state).await
}
fn standard_text_sync_heartbeat_client_api_format_for_plan_kind(plan_kind: &str) -> &'static str {
@@ -1305,10 +1329,7 @@ pub(crate) async fn maybe_execute_sync_via_local_image_decision(
return Ok(LocalExecutionRequestOutcome::NoPath);
};
if attempt_source
.routing_execution_policy()
.is_some_and(|policy| policy.enable_cf_heartbeat)
{
if openai_image_sync_heartbeat_enabled(state).await {
let mut attempts = Vec::new();
while let Some(attempt) = attempt_source.next_execution_attempt().await? {
attempts.push(attempt);
@@ -1846,10 +1867,11 @@ mod tests {
assert_eq!(body, json!({"data": [{"b64_json": "x"}]}));
}
#[test]
fn openai_image_sync_heartbeat_missing_routing_policy_defaults_disabled() {
assert!(!Option::<aether_routing_core::RoutingExecutionPolicy>::None
.is_some_and(|policy| policy.enable_cf_heartbeat));
#[tokio::test]
async fn openai_image_sync_heartbeat_missing_config_defaults_disabled() {
let state = AppState::new().expect("state should build");
assert!(!openai_image_sync_heartbeat_enabled(&state).await);
}
#[tokio::test]
@@ -2128,8 +2150,22 @@ mod tests {
}
#[tokio::test]
async fn standard_text_sync_heartbeat_no_local_candidates_preserves_no_path() {
async fn standard_text_sync_heartbeat_missing_config_defaults_disabled() {
let state = AppState::new().expect("state should build");
assert!(!standard_text_sync_heartbeat_enabled(&state).await);
}
#[tokio::test]
async fn standard_text_sync_heartbeat_no_local_candidates_preserves_no_path() {
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
crate::data::GatewayDataState::disabled().with_system_config_values_for_tests([(
ENABLE_STANDARD_TEXT_SYNC_HEARTBEAT_CONFIG_KEY.to_string(),
json!(true),
)]),
);
let (parts, _) = http::Request::builder()
.method(http::Method::POST)
.uri("/v1/responses")
@@ -67,14 +67,11 @@ pub(crate) async fn build_admin_global_model_routing_payload(
.push(key);
}
// The admin view reports the system-default routing strategy.
let ordering_config =
match crate::scheduler::config::read_system_default_routing_ordering_config(state.app())
.await
{
Ok(Some(config)) => config,
Ok(None) | Err(_) => crate::scheduler::config::SchedulerOrderingConfig::default(),
};
// Effective default scheduling: system-default routing group first, then
// legacy system-config keys.
let ordering_config = crate::scheduler::config::read_scheduler_ordering_config(state.app())
.await
.unwrap_or_default();
let scheduling_mode = ordering_config.scheduling_mode_str().to_string();
let priority_mode = ordering_config.priority_mode_str().to_string();
let keep_priority_on_conversion = ordering_config.keep_priority_on_conversion;
@@ -265,9 +265,7 @@ pub(super) async fn build_admin_monitoring_cache_snapshot(
state: &AdminAppState<'_>,
) -> Result<AdminMonitoringCacheSnapshot, GatewayError> {
let ordering_config =
crate::scheduler::config::read_system_default_routing_ordering_config(state.app())
.await?
.unwrap_or_default();
crate::scheduler::config::read_scheduler_ordering_config(state.app()).await?;
let scheduling_mode = ordering_config.scheduling_mode_str().to_string();
let provider_priority_mode = ordering_config.priority_mode_str().to_string();
@@ -44,8 +44,6 @@ struct AdminRoutingGroupCreateRequest {
#[serde(default)]
is_system_default: bool,
#[serde(default)]
sort_order: i64,
#[serde(default)]
config_json: Option<Value>,
}
@@ -139,7 +137,6 @@ async fn maybe_build_routing_groups_response(
description: payload.description,
enabled: payload.enabled,
is_system_default: payload.is_system_default,
sort_order: payload.sort_order,
config_json,
version: 1,
created_at: now,
@@ -467,9 +464,6 @@ fn build_routing_group_update_patch(
if let Some(value) = object.get("is_system_default") {
patch.is_system_default = Some(required_bool(value, "is_system_default")?);
}
if let Some(value) = object.get("sort_order") {
patch.sort_order = Some(required_i64(value, "sort_order")?.max(0));
}
if let Some(value) = object.get("config_json") {
validate_config_json(value)?;
patch.config_json = Some(value.clone());
@@ -610,7 +604,6 @@ fn routing_group_payload(group: &StoredRoutingGroup) -> Value {
"description": group.description,
"enabled": group.enabled,
"is_system_default": group.is_system_default,
"sort_order": group.sort_order,
"config_json": group.config_json,
"version": group.version,
"created_at": group.created_at,
+22 -1
View File
@@ -68,6 +68,7 @@ use crate::scheduler::candidate::{
is_auth_api_key_concurrency_limit_skip_reason, AUTH_API_KEY_CONCURRENCY_LIMIT_SKIP_REASON,
LEGACY_API_KEY_CONCURRENCY_LIMIT_SKIP_REASON,
};
use crate::scheduler::config::{read_scheduler_ordering_config, SchedulerSchedulingMode};
use crate::stage_metrics::observe_gateway_stage_ms;
use crate::{
AppState, FrontdoorUserRpmOutcome, GatewayError, GatewayFallbackMetricKind,
@@ -410,7 +411,27 @@ async fn maybe_forward_public_request_to_tunnel_owner(
policy_context,
)
} else {
return Ok(None);
let cache_affinity_enabled = match read_scheduler_ordering_config(state).await {
Ok(config) => config.scheduling_mode == SchedulerSchedulingMode::CacheAffinity,
Err(err) => {
warn!(
trace_id = %request_context.trace_id,
error = ?err,
"gateway failed to load scheduler config while checking tunnel affinity forwarding mode"
);
SchedulerSchedulingMode::default() == SchedulerSchedulingMode::CacheAffinity
}
};
if !cache_affinity_enabled {
return Ok(None);
}
crate::scheduler::affinity::read_cached_scheduler_affinity_target(
state,
&auth_context.api_key_id,
affinity_context.client_session_affinity.as_ref(),
api_format,
&affinity_context.requested_model,
)
};
let Some(target) = target else {
return Ok(None);
+71 -362
View File
@@ -76,29 +76,6 @@ enum DatabaseDriverArg {
Postgres,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum DatabaseModeArg {
Auto,
VerifyOnly,
}
fn resolve_database_mode(
configured: Option<DatabaseModeArg>,
legacy_auto_prepare: Option<bool>,
) -> DatabaseModeArg {
if let Some(configured) = configured {
return configured;
}
if let Some(legacy_auto_prepare) = legacy_auto_prepare {
return if legacy_auto_prepare {
DatabaseModeArg::Auto
} else {
DatabaseModeArg::VerifyOnly
};
}
DatabaseModeArg::Auto
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum ExportDomainArg {
Users,
@@ -561,71 +538,46 @@ fn automatic_sql_pool_config_for_parallelism(
#[derive(ClapArgs, Debug, Clone)]
struct GatewayDataArgs {
#[arg(long, env = "AETHER_DATABASE_DRIVER", global = true)]
#[arg(long, env = "AETHER_DATABASE_DRIVER")]
database_driver: Option<DatabaseDriverArg>,
#[arg(long, env = "AETHER_DATABASE_URL", global = true)]
#[arg(long, env = "AETHER_DATABASE_URL")]
database_url: Option<String>,
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_URL", global = true)]
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_URL")]
postgres_url: Option<String>,
#[arg(long, env = "AETHER_GATEWAY_DATA_ENCRYPTION_KEY", global = true)]
#[arg(long, env = "AETHER_GATEWAY_DATA_ENCRYPTION_KEY")]
encryption_key: Option<String>,
#[arg(long, env = "AETHER_GATEWAY_DATA_REDIS_URL", global = true)]
#[arg(long, env = "AETHER_GATEWAY_DATA_REDIS_URL")]
redis_url: Option<String>,
#[arg(long, env = "AETHER_GATEWAY_DATA_REDIS_KEY_PREFIX", global = true)]
#[arg(long, env = "AETHER_GATEWAY_DATA_REDIS_KEY_PREFIX")]
redis_key_prefix: Option<String>,
#[arg(
long,
env = "AETHER_GATEWAY_DATA_POSTGRES_MIN_CONNECTIONS",
global = true
)]
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_MIN_CONNECTIONS")]
postgres_min_connections: Option<u32>,
#[arg(
long,
env = "AETHER_GATEWAY_DATA_POSTGRES_MAX_CONNECTIONS",
global = true
)]
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_MAX_CONNECTIONS")]
postgres_max_connections: Option<u32>,
#[arg(
long,
env = "AETHER_GATEWAY_DATA_POSTGRES_ACQUIRE_TIMEOUT_MS",
global = true
)]
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_ACQUIRE_TIMEOUT_MS")]
postgres_acquire_timeout_ms: Option<u64>,
#[arg(
long,
env = "AETHER_GATEWAY_DATA_POSTGRES_IDLE_TIMEOUT_MS",
global = true
)]
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_IDLE_TIMEOUT_MS")]
postgres_idle_timeout_ms: Option<u64>,
#[arg(
long,
env = "AETHER_GATEWAY_DATA_POSTGRES_MAX_LIFETIME_MS",
global = true
)]
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_MAX_LIFETIME_MS")]
postgres_max_lifetime_ms: Option<u64>,
#[arg(
long,
env = "AETHER_GATEWAY_DATA_POSTGRES_STATEMENT_CACHE_CAPACITY",
global = true
)]
#[arg(long, env = "AETHER_GATEWAY_DATA_POSTGRES_STATEMENT_CACHE_CAPACITY")]
postgres_statement_cache_capacity: Option<usize>,
#[arg(
long,
env = "AETHER_GATEWAY_DATA_POSTGRES_REQUIRE_SSL",
default_value_t = false,
global = true
default_value_t = false
)]
postgres_require_ssl: bool,
}
@@ -1192,26 +1144,13 @@ enum DataCommand {
Import(DataImportArgs),
/// Copy persistent SQL data directly between two databases without a JSONL file.
Copy(DataCopyArgs),
/// Inspect or prepare the configured database.
Db(DatabaseCommandArgs),
}
#[derive(ClapArgs, Debug, Clone)]
struct DatabaseCommandArgs {
#[command(subcommand)]
command: DatabaseCommand,
}
#[derive(Subcommand, Debug, Clone)]
enum DatabaseCommand {
/// Show whether schema migrations and data backfills are current.
Status,
/// Apply pending schema migrations and data backfills.
Prepare,
}
#[derive(ClapArgs, Debug, Clone)]
struct DataExportArgs {
#[command(flatten)]
data: GatewayDataArgs,
#[arg(long)]
output: PathBuf,
@@ -1221,6 +1160,9 @@ struct DataExportArgs {
#[derive(ClapArgs, Debug, Clone)]
struct DataImportArgs {
#[command(flatten)]
data: GatewayDataArgs,
#[arg(long)]
input: PathBuf,
}
@@ -1342,25 +1284,18 @@ struct Args {
)]
node_role: NodeRoleArg,
#[arg(long, hide = true, default_value_t = false)]
#[arg(long, default_value_t = false)]
migrate: bool,
#[arg(long, hide = true, default_value_t = false)]
#[arg(long, default_value_t = false)]
apply_backfills: bool,
/// Database startup policy. Defaults to auto when neither this nor the legacy setting is set.
#[arg(long, env = "AETHER_GATEWAY_DATABASE_MODE", value_enum)]
database_mode: Option<DatabaseModeArg>,
/// Legacy compatibility switch. Prefer --database-mode.
#[arg(
long,
env = "AETHER_GATEWAY_AUTO_PREPARE_DATABASE",
hide = true,
num_args = 0..=1,
default_missing_value = "true"
default_value_t = false
)]
auto_prepare_database: Option<bool>,
auto_prepare_database: bool,
/// Path to frontend static files directory (SPA). When set, the gateway
/// serves the frontend directly without nginx.
@@ -1470,10 +1405,6 @@ struct Args {
}
impl Args {
fn effective_database_mode(&self) -> DatabaseModeArg {
resolve_database_mode(self.database_mode, self.auto_prepare_database)
}
fn effective_runtime_backend(
&self,
database: Option<&SqlDatabaseConfig>,
@@ -1544,7 +1475,15 @@ impl Args {
}
fn runtime_config(&self) -> Result<ServiceRuntimeConfig, std::io::Error> {
let default_log_filter = "aether_gateway=info,aether_data=info";
let default_log_filter = if self.command.is_some()
|| self.migrate
|| self.apply_backfills
|| self.auto_prepare_database
{
"aether_gateway=info,aether_data=info"
} else {
"aether_gateway=info"
};
let config = self
.logging
.apply_to_runtime_config(ServiceRuntimeConfig::new(
@@ -1847,7 +1786,7 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
if let Some(command) = args.command.as_ref() {
init_service_runtime(args.runtime_config()?)?;
return run_data_command(command, &args.data).await;
return run_data_command(command).await;
}
if args.migrate {
init_service_runtime(args.runtime_config()?)?;
@@ -2147,7 +2086,7 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
execution_runtime_configured = state.execution_runtime_configured(),
"aether-gateway data layer configured"
);
prepare_database_startup_requirements(&state, args.effective_database_mode()).await?;
prepare_database_startup_requirements(&state, args.auto_prepare_database).await?;
state.warm_database_pools().await?;
let reset_stale_proxy_nodes = state.reset_stale_proxy_node_tunnel_statuses().await?;
if reset_stale_proxy_nodes > 0 {
@@ -2162,11 +2101,16 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
info!(
group_id = %group.id,
group_name = %group.name,
"created system default routing group from routing strategy defaults"
"created system default routing group from legacy scheduler config"
);
}
Ok(None) => {}
Err(err) => return Err(err.into()),
Err(err) => {
warn!(
error = %err,
"failed to bootstrap system default routing group; scheduler falls back to legacy system config"
);
}
}
match state.prewarm_chat_pii_redaction_runtime_config().await {
Ok(enabled) => {
@@ -2264,77 +2208,14 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
async fn run_data_command(
command: &DataCommand,
data: &GatewayDataArgs,
) -> Result<(), Box<dyn std::error::Error>> {
async fn run_data_command(command: &DataCommand) -> Result<(), Box<dyn std::error::Error>> {
match command {
DataCommand::Export(args) => run_data_export(args, data).await,
DataCommand::Import(args) => run_data_import(args, data).await,
DataCommand::Export(args) => run_data_export(args).await,
DataCommand::Import(args) => run_data_import(args).await,
DataCommand::Copy(args) => run_data_copy(args).await,
DataCommand::Db(args) => run_database_command(args, data).await,
}
}
async fn run_database_command(
args: &DatabaseCommandArgs,
data: &GatewayDataArgs,
) -> Result<(), Box<dyn std::error::Error>> {
match args.command {
DatabaseCommand::Status => run_database_status(data).await,
DatabaseCommand::Prepare => run_database_prepare(data).await,
}
}
fn database_maintenance_state(
data: &GatewayDataArgs,
) -> Result<(DatabaseDriver, AppState), Box<dyn std::error::Error>> {
let database = required_sql_database_config(data)?;
let driver = database.driver;
let state = AppState::new()?.with_data_config(data.to_config())?;
Ok((driver, state))
}
async fn run_database_status(data: &GatewayDataArgs) -> Result<(), Box<dyn std::error::Error>> {
let (driver, state) = database_maintenance_state(data)?;
let pending_migrations = state
.pending_database_migrations()
.await?
.unwrap_or_default();
if let Some(next) = pending_migrations.first() {
println!("database {driver}: preparation required");
println!("pending migrations: {}", pending_migrations.len());
println!("next migration: {} ({})", next.version, next.description);
println!("pending backfills: not checked until migrations are current");
println!("run `aether-gateway db prepare`");
return Ok(());
}
let pending_backfills = state
.pending_database_backfills()
.await?
.unwrap_or_default();
if let Some(next) = pending_backfills.first() {
println!("database {driver}: preparation required");
println!("pending migrations: 0");
println!("pending backfills: {}", pending_backfills.len());
println!("next backfill: {} ({})", next.version, next.description);
println!("run `aether-gateway db prepare`");
return Ok(());
}
println!("database {driver}: ready (schema and backfills are current)");
Ok(())
}
async fn run_database_prepare(data: &GatewayDataArgs) -> Result<(), Box<dyn std::error::Error>> {
let (driver, state) = database_maintenance_state(data)?;
prepare_database_startup_requirements(&state, DatabaseModeArg::Auto).await?;
println!("database {driver}: ready (schema and backfills are current)");
Ok(())
}
fn required_sql_database_config(
data: &GatewayDataArgs,
) -> Result<SqlDatabaseConfig, Box<dyn std::error::Error>> {
@@ -2361,11 +2242,8 @@ fn current_unix_secs() -> Result<u64, std::time::SystemTimeError> {
.as_secs())
}
async fn run_data_export(
args: &DataExportArgs,
data: &GatewayDataArgs,
) -> Result<(), Box<dyn std::error::Error>> {
let database = required_sql_database_config(data)?;
async fn run_data_export(args: &DataExportArgs) -> Result<(), Box<dyn std::error::Error>> {
let database = required_sql_database_config(&args.data)?;
let driver = database.driver;
let domains = requested_export_domains(args);
let created_at_unix_secs = current_unix_secs()?;
@@ -2387,11 +2265,8 @@ async fn run_data_export(
Ok(())
}
async fn run_data_import(
args: &DataImportArgs,
data: &GatewayDataArgs,
) -> Result<(), Box<dyn std::error::Error>> {
let database = required_sql_database_config(data)?;
async fn run_data_import(args: &DataImportArgs) -> Result<(), Box<dyn std::error::Error>> {
let database = required_sql_database_config(&args.data)?;
let driver = database.driver;
let input = tokio::fs::read_to_string(&args.input).await?;
let imported = import_database_jsonl(database, &input).await?;
@@ -2551,15 +2426,17 @@ async fn run_explicit_backfills(args: &Args) -> Result<(), Box<dyn std::error::E
async fn prepare_database_startup_requirements(
state: &AppState,
database_mode: DatabaseModeArg,
auto_prepare_database: bool,
) -> Result<(), Box<dyn std::error::Error>> {
if matches!(database_mode, DatabaseModeArg::VerifyOnly) {
if !auto_prepare_database {
ensure_database_schema_is_current(state).await?;
ensure_database_backfills_are_current(state).await?;
return Ok(());
}
info!("database preparation enabled; applying pending migrations and backfills");
info!(
"auto database preparation enabled; applying pending migrations and backfills before serving traffic"
);
let Some(pending_migrations) = state.prepare_database_for_startup().await? else {
return Ok(());
@@ -2573,10 +2450,10 @@ async fn prepare_database_startup_requirements(
next_version = next.version,
next_description = %next.description,
pending_versions = %format_pending_migrations(&pending_migrations),
"running database migrations during database preparation..."
"running database migrations during service startup..."
);
if state.run_database_migrations().await? {
info!("database migrations complete");
info!("database migrations complete during service startup");
}
}
@@ -2595,10 +2472,10 @@ async fn prepare_database_startup_requirements(
next_version = next.version,
next_description = %next.description,
pending_versions = %format_pending_backfills(&pending_backfills),
"running database backfills during database preparation..."
"running database backfills during service startup..."
);
if state.run_database_backfills().await? {
info!("database backfills complete");
info!("database backfills complete during service startup");
}
Ok(())
@@ -2643,7 +2520,7 @@ async fn ensure_database_backfills_are_current(
async fn ensure_database_schema_is_current(
state: &AppState,
) -> Result<(), Box<dyn std::error::Error>> {
let Some(pending) = state.pending_database_migrations().await? else {
let Some(pending) = state.prepare_database_for_startup().await? else {
return Ok(());
};
if pending.is_empty() {
@@ -2662,7 +2539,7 @@ fn pending_schema_error(
next_description: &str,
) -> std::io::Error {
std::io::Error::other(format!(
"database schema is behind by {} migration(s); next pending migration is {} ({})\nrun `aether-gateway db prepare` before starting the service",
"database schema is behind by {} migration(s); next pending migration is {} ({})\nrun `aether-gateway --migrate` before starting the service",
pending_count, next_version, next_description
))
}
@@ -2673,7 +2550,7 @@ fn pending_backfills_error(
next_description: &str,
) -> std::io::Error {
std::io::Error::other(format!(
"database backfills are behind by {} backfill(s); next pending backfill is {} ({})\nrun `aether-gateway db prepare` before starting the service",
"database backfills are behind by {} backfill(s); next pending backfill is {} ({})\nrun `aether-gateway --apply-backfills` before starting the service",
pending_count, next_version, next_description
))
}
@@ -2685,9 +2562,8 @@ mod tests {
automatic_gateway_request_concurrency_for_parallelism, automatic_sql_pool_config,
automatic_sql_pool_config_for_parallelism, automatic_usage_queue_workers_for_parallelism,
ensure_database_backfills_are_current, ensure_database_schema_is_current,
pending_backfills_error, pending_schema_error, resolve_database_mode,
resolve_healthcheck_url, usage_database_config_for_role, Args, DataCommand,
DatabaseCommand, DatabaseDriverArg, DatabaseModeArg, DeploymentTopologyArg,
pending_backfills_error, pending_schema_error, resolve_healthcheck_url,
usage_database_config_for_role, Args, DatabaseDriverArg, DeploymentTopologyArg,
GatewayDataArgs, GatewayFrontdoorArgs, GatewayLogDestinationArg, GatewayLogFormatArg,
GatewayLogRotationArg, GatewayLoggingArgs, GatewayRateLimitArgs, GatewayUsageArgs,
NodeRoleArg, RuntimeBackendArg, VideoTaskTruthSourceArg,
@@ -2698,7 +2574,6 @@ mod tests {
};
use aether_data::{DatabaseDriver, SqlDatabaseConfig, SqlPoolConfig};
use aether_gateway::AppState;
use clap::Parser;
fn test_args() -> Args {
Args {
@@ -2713,8 +2588,7 @@ mod tests {
node_role: NodeRoleArg::All,
migrate: false,
apply_backfills: false,
database_mode: None,
auto_prepare_database: None,
auto_prepare_database: false,
static_dir: None,
video_task_truth_source_mode: VideoTaskTruthSourceArg::PythonSyncReport,
video_task_poller_interval_ms: 5_000,
@@ -2816,19 +2690,6 @@ mod tests {
.expect("test database config should build")
}
fn temporary_sqlite_args(label: &str) -> (Args, std::path::PathBuf) {
let mut args = test_args();
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("clock should be available")
.as_nanos();
let database_path =
std::env::temp_dir().join(format!("aether-{label}-{}-{nonce}.db", std::process::id()));
args.data.database_driver = Some(DatabaseDriverArg::Sqlite);
args.data.database_url = Some(format!("sqlite://{}", database_path.display()));
(args, database_path)
}
#[test]
fn resolves_healthcheck_url_from_app_port() {
assert_eq!(
@@ -2940,14 +2801,11 @@ mod tests {
}
#[test]
fn normal_runtime_config_includes_database_lifecycle_logs() {
fn normal_runtime_config_keeps_gateway_only_logs() {
let config = test_args()
.runtime_config()
.expect("runtime config should build");
assert_eq!(
config.default_log_filter,
"aether_gateway=info,aether_data=info"
);
assert_eq!(config.default_log_filter, "aether_gateway=info");
}
#[test]
@@ -2964,7 +2822,7 @@ mod tests {
#[test]
fn auto_prepare_database_runtime_config_enables_data_logs() {
let mut args = test_args();
args.auto_prepare_database = Some(true);
args.auto_prepare_database = true;
let config = args.runtime_config().expect("runtime config should build");
assert_eq!(
config.default_log_filter,
@@ -2972,87 +2830,6 @@ mod tests {
);
}
#[test]
fn database_mode_defaults_to_auto_and_preserves_legacy_false() {
assert_eq!(resolve_database_mode(None, None), DatabaseModeArg::Auto);
assert_eq!(
resolve_database_mode(None, Some(false)),
DatabaseModeArg::VerifyOnly
);
assert_eq!(
resolve_database_mode(Some(DatabaseModeArg::Auto), Some(false)),
DatabaseModeArg::Auto
);
}
#[test]
fn parses_database_commands_and_verify_only_mode() {
let status = Args::try_parse_from(["aether-gateway", "db", "status"])
.expect("db status should parse");
assert!(matches!(
status.command,
Some(DataCommand::Db(args))
if matches!(args.command, DatabaseCommand::Status)
));
let verify_only =
Args::try_parse_from(["aether-gateway", "--database-mode", "verify-only"])
.expect("verify-only mode should parse");
assert_eq!(
verify_only.effective_database_mode(),
DatabaseModeArg::VerifyOnly
);
let legacy_false =
Args::try_parse_from(["aether-gateway", "--auto-prepare-database=false"])
.expect("legacy false setting should parse");
assert_eq!(
legacy_false.effective_database_mode(),
DatabaseModeArg::VerifyOnly
);
let prepare = Args::try_parse_from(["aether-gateway", "db", "prepare"])
.expect("db prepare should parse");
assert!(matches!(
prepare.command,
Some(DataCommand::Db(args))
if matches!(args.command, DatabaseCommand::Prepare)
));
}
#[test]
fn database_arguments_are_global_for_database_commands() {
let before = Args::try_parse_from([
"aether-gateway",
"--database-driver",
"sqlite",
"--database-url",
"sqlite:///tmp/before.db",
"db",
"status",
])
.expect("database arguments before db should parse");
assert_eq!(
before.data.database_url.as_deref(),
Some("sqlite:///tmp/before.db")
);
let after = Args::try_parse_from([
"aether-gateway",
"db",
"prepare",
"--database-driver",
"sqlite",
"--database-url",
"sqlite:///tmp/after.db",
])
.expect("database arguments after db prepare should parse");
assert_eq!(
after.data.database_url.as_deref(),
Some("sqlite:///tmp/after.db")
);
}
#[test]
fn gateway_data_pool_auto_sizes_sqlite_to_single_connection() {
let mut args = test_args();
@@ -3723,17 +3500,17 @@ mod tests {
}
#[test]
fn pending_schema_error_mentions_database_prepare_command() {
fn pending_schema_error_mentions_explicit_migrate_command() {
let error = pending_schema_error(2, 20260413020000, "squash usage schema split");
let message = error.to_string();
assert!(message.contains("database schema is behind by 2 migration(s)"));
assert!(message.contains("20260413020000"));
assert!(message.contains("squash usage schema split"));
assert!(message.contains("aether-gateway db prepare"));
assert!(message.contains("aether-gateway --migrate"));
}
#[test]
fn pending_backfills_error_mentions_database_prepare_command() {
fn pending_backfills_error_mentions_explicit_apply_backfills_command() {
let message = pending_backfills_error(
1,
20260422110000,
@@ -3743,7 +3520,7 @@ mod tests {
assert!(message.contains("database backfills are behind by 1 backfill(s)"));
assert!(message.contains("20260422110000"));
assert!(message.contains("backfill stats aggregate read path support"));
assert!(message.contains("aether-gateway db prepare"));
assert!(message.contains("aether-gateway --apply-backfills"));
assert!(message.contains("before starting the service"));
}
@@ -3766,79 +3543,11 @@ mod tests {
#[tokio::test]
async fn auto_prepare_database_is_noop_without_database_pool() {
let state = AppState::new().expect("state should build");
super::prepare_database_startup_requirements(&state, DatabaseModeArg::Auto)
super::prepare_database_startup_requirements(&state, true)
.await
.expect("disabled data backend should not block startup");
}
#[tokio::test]
async fn verify_only_does_not_prepare_fresh_sqlite_database() {
let (args, database_path) = temporary_sqlite_args("verify-only");
let state = AppState::new()
.expect("state should build")
.with_data_config(args.data.to_config())
.expect("sqlite state should build");
let pending_before = state
.pending_database_migrations()
.await
.expect("pending migrations should load")
.expect("sqlite should expose migration state");
assert!(!pending_before.is_empty());
let error =
super::prepare_database_startup_requirements(&state, DatabaseModeArg::VerifyOnly)
.await
.expect_err("verify-only should reject a fresh database");
assert!(error.to_string().contains("aether-gateway db prepare"));
let pending_after = state
.pending_database_migrations()
.await
.expect("pending migrations should reload")
.expect("sqlite should expose migration state");
assert_eq!(pending_after, pending_before);
drop(state);
let _ = std::fs::remove_file(database_path);
}
#[tokio::test]
async fn auto_mode_prepares_fresh_sqlite_database() {
let (args, database_path) = temporary_sqlite_args("auto-prepare");
let state = AppState::new()
.expect("state should build")
.with_data_config(args.data.to_config())
.expect("sqlite state should build");
super::prepare_database_startup_requirements(&state, DatabaseModeArg::Auto)
.await
.expect("auto mode should prepare a fresh database");
assert!(state
.pending_database_migrations()
.await
.expect("pending migrations should load")
.expect("sqlite should expose migration state")
.is_empty());
assert!(state
.pending_database_backfills()
.await
.expect("pending backfills should load")
.expect("sqlite should expose backfill state")
.is_empty());
drop(state);
let _ = std::fs::remove_file(database_path);
}
#[tokio::test]
async fn database_prepare_requires_database_url() {
let data = test_args().data;
let error = super::run_database_prepare(&data)
.await
.expect_err("missing database URL should fail");
assert!(error
.to_string()
.contains("AETHER_DATABASE_DRIVER/AETHER_DATABASE_URL"));
}
#[tokio::test]
async fn explicit_migrate_requires_database_url() {
let args = test_args();
@@ -53,6 +53,7 @@ use crate::scheduler::affinity::{
scheduler_affinity_policy_context_from_report_context, SCHEDULER_AFFINITY_POLICY_REPORT_FIELD,
SCHEDULER_AFFINITY_TTL,
};
use crate::scheduler::config::{read_scheduler_ordering_config, SchedulerSchedulingMode};
use crate::AppState;
const POOL_SCORE_FEEDBACK_GATE_MAX_ENTRIES: usize = 50_000;
@@ -762,19 +763,36 @@ async fn local_scheduler_affinity_matches_failed_target(
local_execution_plan_uses_pool(state, plan).await
}
fn scheduler_cache_affinity_enabled(report_context: Option<&Value>) -> bool {
report_context
async fn scheduler_cache_affinity_enabled(
state: &AppState,
report_context: Option<&Value>,
) -> bool {
if report_context
.and_then(|context| context.get(SCHEDULER_AFFINITY_POLICY_REPORT_FIELD))
.is_some()
&& scheduler_affinity_policy_context_from_report_context(report_context)
.is_some_and(|context| context.cache_affinity_enabled())
{
return scheduler_affinity_policy_context_from_report_context(report_context)
.is_some_and(|context| context.cache_affinity_enabled());
}
match read_scheduler_ordering_config(state).await {
Ok(config) => config.scheduling_mode == SchedulerSchedulingMode::CacheAffinity,
Err(error) => {
warn!(
event_name = "orchestration_scheduler_affinity_config_load_failed",
log_type = "event",
error = ?error,
"failed to load scheduler config while checking cache affinity mode"
);
SchedulerSchedulingMode::default() == SchedulerSchedulingMode::CacheAffinity
}
}
}
async fn remember_successful_local_scheduler_affinity(
state: &AppState,
context: LocalExecutionEffectContext<'_>,
) {
if !scheduler_cache_affinity_enabled(context.report_context) {
if !scheduler_cache_affinity_enabled(state, context.report_context).await {
return;
}
let Some(cache_key) = local_scheduler_affinity_cache_key(context.report_context) else {
+4 -5
View File
@@ -56,11 +56,10 @@ pub(crate) use self::oauth_error::{
};
pub(crate) use self::policy::{
append_local_failover_policy_to_value, codex_cyber_flag_passthrough_enabled,
local_failover_policy_from_report_context, local_failover_policy_from_transport,
resolve_local_failover_policy, responses_websocket_adapter,
routing_execution_policy_from_report_context, LocalFailoverPolicy, LocalFailoverRegexRule,
ResponsesWebSocketAdapter, RESPONSES_WEBSOCKET_CONFIG_KEY,
ROUTING_EXECUTION_POLICY_REPORT_FIELD,
cyber_continue_failover_enabled, local_failover_policy_from_report_context,
local_failover_policy_from_transport, resolve_local_failover_policy,
responses_websocket_adapter, LocalFailoverPolicy, LocalFailoverRegexRule,
ResponsesWebSocketAdapter, CYBER_CONTINUE_FAILOVER_CONFIG_KEY, RESPONSES_WEBSOCKET_CONFIG_KEY,
};
pub(crate) use self::recovery::{
analyze_local_failover, analyze_local_transport_error, apply_provider_failure_disposition,
+12 -13
View File
@@ -4,13 +4,11 @@ use aether_contracts::ExecutionPlan;
use serde_json::{json, Value};
use tracing::debug;
use aether_routing_core::RoutingExecutionPolicy;
use crate::provider_transport::GatewayProviderTransportSnapshot;
use crate::AppState;
pub(crate) const CYBER_CONTINUE_FAILOVER_CONFIG_KEY: &str = "cyber_continue_failover";
pub(crate) const RESPONSES_WEBSOCKET_CONFIG_KEY: &str = "responses_websocket";
pub(crate) const ROUTING_EXECUTION_POLICY_REPORT_FIELD: &str = "routing_execution_policy";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LocalFailoverPolicy {
@@ -52,7 +50,7 @@ pub(crate) struct LocalFailoverRegexRule {
pub(crate) async fn resolve_local_failover_policy(
state: &AppState,
plan: &ExecutionPlan,
report_context: Option<&serde_json::Value>,
_report_context: Option<&serde_json::Value>,
) -> LocalFailoverPolicy {
let mut policy = match state
.read_provider_transport_snapshot(&plan.provider_id, &plan.endpoint_id, &plan.key_id)
@@ -61,8 +59,7 @@ pub(crate) async fn resolve_local_failover_policy(
Ok(Some(transport)) => local_failover_policy_from_transport(&transport),
Ok(None) | Err(_) => LocalFailoverPolicy::default(),
};
let cyber_continue_failover = routing_execution_policy_from_report_context(report_context)
.is_some_and(|policy| policy.cyber_continue_failover);
let cyber_continue_failover = cyber_continue_failover_enabled(state).await;
policy.stop_cyber_policy_errors = !cyber_continue_failover;
debug!(
event_name = "local_failover_policy_loaded",
@@ -86,13 +83,15 @@ pub(crate) async fn resolve_local_failover_policy(
policy
}
pub(crate) fn routing_execution_policy_from_report_context(
report_context: Option<&Value>,
) -> Option<RoutingExecutionPolicy> {
report_context
.and_then(Value::as_object)
.and_then(|object| object.get(ROUTING_EXECUTION_POLICY_REPORT_FIELD))
.and_then(|value| serde_json::from_value(value.clone()).ok())
pub(crate) async fn cyber_continue_failover_enabled(state: &AppState) -> bool {
state
.read_system_config_json_value(CYBER_CONTINUE_FAILOVER_CONFIG_KEY)
.await
.ok()
.flatten()
.as_ref()
.and_then(Value::as_bool)
.unwrap_or(false)
}
pub(crate) fn local_failover_policy_from_transport(
+3 -38
View File
@@ -95,7 +95,6 @@ pub(crate) fn resolve_gateway_static_default_routing_policy(
scheduling_mode: default_policy.scheduling_mode,
keep_priority_on_conversion: default_policy.keep_priority_on_conversion,
sticky_key_attempts: default_policy.sticky_key_attempts,
execution_policy: default_policy.execution_policy,
ranking_overlay: RankingOverlay::default(),
mutation_plan: MutationPlan::default(),
pool_policy_overrides: BTreeMap::new(),
@@ -109,10 +108,8 @@ fn static_default_policy_fields(
let Some(object) = config_json.as_object() else {
return Ok(None);
};
// A strategy's default policy applies to every model. Only model policies
// and rules require the request-context-aware resolver; unknown legacy
// fields (including the removed group allowlist) are intentionally ignored.
if !routing_array_field_is_missing_or_empty(object, "model_policies")
if !routing_array_field_is_missing_or_empty(object, "allowed_models")
|| !routing_array_field_is_missing_or_empty(object, "model_policies")
|| !routing_array_field_is_missing_or_empty(object, "rules")
{
return Ok(None);
@@ -148,47 +145,15 @@ fn static_default_policy_fields(
})?,
None => DEFAULT_STICKY_KEY_ATTEMPTS,
};
let enable_cf_heartbeat = routing_bool_field(
default_policy.get("enable_cf_heartbeat"),
"enable_cf_heartbeat",
)?;
// Older strategies stored separate image/text heartbeat flags. Treat
// either legacy flag as enabling the unified CF heartbeat setting while
// allowing newly saved strategies to use only the canonical key.
let legacy_image_heartbeat = routing_bool_field(
default_policy.get("enable_openai_image_sync_heartbeat"),
"enable_openai_image_sync_heartbeat",
)?;
let legacy_text_heartbeat = routing_bool_field(
default_policy.get("enable_standard_text_sync_heartbeat"),
"enable_standard_text_sync_heartbeat",
)?;
let execution_policy = aether_routing_core::RoutingExecutionPolicy {
enable_cf_heartbeat: enable_cf_heartbeat || legacy_image_heartbeat || legacy_text_heartbeat,
cyber_continue_failover: routing_bool_field(
default_policy.get("cyber_continue_failover"),
"cyber_continue_failover",
)?,
};
Ok(Some(RoutingDefaultPolicy {
priority_mode,
scheduling_mode,
keep_priority_on_conversion,
sticky_key_attempts,
execution_policy,
}))
}
fn routing_bool_field(value: Option<&Value>, field: &str) -> Result<bool, GatewayError> {
match value {
Some(value) => value
.as_bool()
.ok_or_else(|| invalid_routing_group_config(format!("{field} must be a boolean"))),
None => Ok(false),
}
}
fn routing_array_field_is_missing_or_empty(
object: &serde_json::Map<String, Value>,
key: &str,
@@ -236,7 +201,7 @@ mod tests {
"scheduling_mode": "load_balance",
"keep_priority_on_conversion": true
},
"allowed_models": ["legacy-model"],
"allowed_models": [],
"model_policies": [],
"rules": []
});
@@ -8,8 +8,6 @@ pub(crate) const ROUTING_GROUP_HEADER: &str = "x-aether-scheduler-group";
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub(crate) enum GatewayRoutingSelectionError {
#[error("no enabled routing strategy is configured for this request")]
NoDefault,
#[error("routing group was explicitly requested but was not found: {0}")]
NotFound(String),
#[error("routing group was explicitly requested but is not enabled: {0}")]
@@ -241,7 +239,6 @@ mod tests {
description: None,
enabled: true,
is_system_default: false,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -290,7 +287,6 @@ mod tests {
description: None,
enabled: true,
is_system_default: true,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -326,7 +322,6 @@ mod tests {
description: None,
enabled: true,
is_system_default: false,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -449,7 +444,6 @@ mod tests {
description: None,
enabled: false,
is_system_default: false,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -487,7 +481,6 @@ mod tests {
description: None,
enabled: true,
is_system_default: false,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -1,6 +1,7 @@
use self::selection::{
collect_selectable_candidates, collect_selectable_candidates_with_skip_reasons_and_ordering,
collect_selectable_enumerated_candidates_with_skip_reasons,
resolve_preselection_ordering_config,
};
use super::config::SchedulerOrderingConfig;
use super::state::SchedulerRuntimeState;
@@ -55,7 +56,8 @@ enum RequiredCapabilityMatchMode {
}
/// `ordering_config` carries the request's routing-policy derived scheduler
/// config. Every production scheduling pass must provide this snapshot.
/// config. `None` falls back to the runtime default (system-default routing
/// group, then legacy system-config keys).
#[allow(clippy::too_many_arguments)]
pub(crate) async fn list_selectable_candidates(
selection_row_source: &(impl MinimalCandidateSelectionRowSource + Sync),
@@ -68,7 +70,7 @@ pub(crate) async fn list_selectable_candidates(
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
enable_model_directives: bool,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<Vec<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
collect_selectable_candidates(
selection_row_source,
@@ -105,7 +107,7 @@ pub(crate) async fn list_selectable_candidates_with_skip_reasons(
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
enable_model_directives: bool,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<
(
Vec<SchedulerMinimalCandidateSelectionCandidate>,
@@ -143,7 +145,7 @@ pub(crate) async fn list_selectable_candidates_with_skip_reasons_for_request_ope
now_unix_secs: u64,
enable_model_directives: bool,
request_operation: Option<&str>,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<
(
Vec<SchedulerMinimalCandidateSelectionCandidate>,
@@ -178,7 +180,7 @@ pub(crate) async fn list_selectable_enumerated_candidates_with_skip_reasons(
auth_snapshot: Option<&GatewayAuthApiKeySnapshot>,
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<
(
Vec<SchedulerMinimalCandidateSelectionCandidate>,
@@ -186,6 +188,8 @@ pub(crate) async fn list_selectable_enumerated_candidates_with_skip_reasons(
),
GatewayError,
> {
let ordering_config =
resolve_preselection_ordering_config(runtime_state, ordering_config).await?;
let priority_affinity_key = selection::scheduling_priority_affinity_key(
auth_snapshot,
client_session_affinity,
@@ -216,7 +220,7 @@ pub(crate) async fn list_selectable_candidates_for_required_capability_without_r
auth_snapshot: Option<&GatewayAuthApiKeySnapshot>,
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<Vec<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
Ok(
list_selectable_candidates_for_required_capability_without_requested_model_with_auth_limit_signal(
@@ -245,7 +249,7 @@ pub(crate) async fn list_selectable_candidates_for_required_capability_without_r
auth_snapshot: Option<&GatewayAuthApiKeySnapshot>,
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<(Vec<SchedulerMinimalCandidateSelectionCandidate>, bool), GatewayError> {
let normalized_api_format = normalize_api_format(candidate_api_format);
if normalized_api_format.is_empty() {
@@ -47,7 +47,7 @@ pub(super) fn is_exact_all_skipped_by_auth_limit(
.all(|candidate| is_auth_api_key_concurrency_limit_skip_reason(candidate.skip_reason))
}
#[cfg(test)]
#[cfg_attr(not(test), allow(dead_code))]
pub(super) async fn select_minimal_candidate(
selection_row_source: &(impl MinimalCandidateSelectionRowSource + Sync),
runtime_state: &impl SchedulerRuntimeState,
@@ -59,8 +59,20 @@ pub(super) async fn select_minimal_candidate(
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
enable_model_directives: bool,
ordering_config: SchedulerOrderingConfig,
) -> Result<Option<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
let affinity_epoch = runtime_state.scheduler_affinity_epoch();
let ordering_config = runtime_state.read_scheduler_ordering_config().await?;
let affinity_cache_key = build_scheduler_affinity_cache_key(
auth_snapshot,
api_format,
global_model_name,
client_session_affinity,
);
let priority_affinity_key = scheduling_priority_affinity_key(
auth_snapshot,
client_session_affinity,
ordering_config.scheduling_mode,
);
let candidates = enumerate_scheduler_candidates(
selection_row_source,
api_format,
@@ -72,7 +84,7 @@ pub(super) async fn select_minimal_candidate(
None,
)
.await?;
Ok(collect_selectable_enumerated_candidates_with_skip_reasons(
let selected = collect_selectable_enumerated_candidates_with_skip_reasons(
runtime_state,
api_format,
global_model_name,
@@ -82,16 +94,25 @@ pub(super) async fn select_minimal_candidate(
client_session_affinity,
now_unix_secs,
ordering_config,
scheduling_priority_affinity_key(
auth_snapshot,
client_session_affinity,
ordering_config.scheduling_mode,
),
priority_affinity_key,
)
.await?
.0
.into_iter()
.next())
.next();
if ordering_config.scheduling_mode == SchedulerSchedulingMode::CacheAffinity
&& has_explicit_session_affinity(client_session_affinity)
{
if let Some(candidate) = selected.as_ref() {
remember_scheduler_affinity(
affinity_cache_key.as_deref(),
runtime_state,
candidate,
Some(affinity_epoch),
);
}
}
Ok(selected)
}
#[allow(clippy::too_many_arguments)]
@@ -106,7 +127,7 @@ pub(super) async fn collect_selectable_candidates(
client_session_affinity: Option<&ClientSessionAffinity>,
now_unix_secs: u64,
enable_model_directives: bool,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<Vec<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
Ok(
collect_selectable_candidates_with_skip_reasons_and_ordering(
@@ -128,8 +149,10 @@ pub(super) async fn collect_selectable_candidates(
)
}
/// Legacy-shaped entrypoint that resolves the ordering config from the
/// runtime state. Prefer `collect_selectable_candidates_with_skip_reasons_and_ordering`
/// and pass the request's routing-policy config explicitly.
#[allow(clippy::too_many_arguments)]
#[cfg(test)]
pub(super) async fn collect_selectable_candidates_with_skip_reasons(
selection_row_source: &(impl MinimalCandidateSelectionRowSource + Sync),
runtime_state: &impl SchedulerRuntimeState,
@@ -161,11 +184,24 @@ pub(super) async fn collect_selectable_candidates_with_skip_reasons(
now_unix_secs,
enable_model_directives,
request_operation,
SchedulerOrderingConfig::default(),
None,
)
.await
}
/// Resolve the ordering config for a preselection pass: the routing-policy
/// derived config wins when the caller has one; otherwise fall back to the
/// runtime default (system-default routing group, then legacy keys).
pub(super) async fn resolve_preselection_ordering_config(
runtime_state: &impl SchedulerRuntimeState,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<SchedulerOrderingConfig, GatewayError> {
match ordering_config {
Some(config) => Ok(config),
None => runtime_state.read_scheduler_ordering_config().await,
}
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn collect_selectable_candidates_with_skip_reasons_and_ordering(
selection_row_source: &(impl MinimalCandidateSelectionRowSource + Sync),
@@ -179,7 +215,7 @@ pub(super) async fn collect_selectable_candidates_with_skip_reasons_and_ordering
now_unix_secs: u64,
enable_model_directives: bool,
request_operation: Option<&str>,
ordering_config: SchedulerOrderingConfig,
ordering_config: Option<SchedulerOrderingConfig>,
) -> Result<
(
Vec<SchedulerMinimalCandidateSelectionCandidate>,
@@ -187,6 +223,8 @@ pub(super) async fn collect_selectable_candidates_with_skip_reasons_and_ordering
),
GatewayError,
> {
let ordering_config =
resolve_preselection_ordering_config(runtime_state, ordering_config).await?;
let priority_affinity_key = scheduling_priority_affinity_key(
auth_snapshot,
client_session_affinity,
@@ -23,7 +23,6 @@ use crate::data::candidate_selection::{
read_requested_model_rows, MinimalCandidateSelectionRowSource,
};
use crate::data::GatewayDataState;
use crate::scheduler::config::SchedulerOrderingConfig;
use crate::{AppState, GatewayError};
use super::super::affinity::build_scheduler_affinity_cache_key;
@@ -51,7 +50,6 @@ async fn select_candidate(
client_session_affinity,
now_unix_secs,
false,
SchedulerOrderingConfig::default(),
)
.await
}
@@ -65,7 +65,7 @@ async fn compatible_required_capability_prefers_matching_keys_without_hard_filte
None,
None,
100,
crate::scheduler::config::SchedulerOrderingConfig::default(),
None,
)
.await
.expect("selection should succeed");
@@ -121,7 +121,7 @@ async fn exclusive_required_capability_keeps_hard_filtering_only_matching_keys()
None,
None,
100,
crate::scheduler::config::SchedulerOrderingConfig::default(),
None,
)
.await
.expect("selection should succeed");
@@ -198,7 +198,7 @@ async fn required_capability_without_model_uses_session_scoped_affinity() {
Some(&auth_snapshot),
Some(&client_session_affinity),
100,
crate::scheduler::config::SchedulerOrderingConfig::default(),
None,
)
.await
.expect("selection should succeed");
@@ -276,7 +276,7 @@ async fn required_capability_reports_auth_limit_signal_when_every_model_is_block
Some(&auth_snapshot),
None,
100,
crate::scheduler::config::SchedulerOrderingConfig::default(),
None,
)
.await
.expect("selection should succeed");
@@ -5,7 +5,6 @@ use aether_data::repository::candidate_selection::InMemoryMinimalCandidateSelect
use aether_data::repository::candidates::InMemoryRequestCandidateRepository;
use aether_data::repository::provider_catalog::InMemoryProviderCatalogReadRepository;
use aether_data::repository::quota::InMemoryProviderQuotaRepository;
use aether_data::repository::routing_profiles::InMemoryRoutingGroupRepository;
use aether_data_contracts::repository::candidate_selection::{
StoredMinimalCandidateSelectionRow, StoredProviderModelMapping,
};
@@ -14,9 +13,6 @@ use aether_data_contracts::repository::candidates::{
};
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogKey;
use aether_data_contracts::repository::quota::StoredProviderQuotaSnapshot;
use aether_data_contracts::repository::routing_profiles::{
CreateRoutingGroupRecord, RoutingGroupWriteRepository,
};
use aether_scheduler_core::{ClientSessionAffinity, SchedulerMinimalCandidateSelectionCandidate};
use serde_json::json;
@@ -24,7 +20,6 @@ use crate::cache::SchedulerAffinityTarget;
use crate::data::auth::GatewayAuthApiKeySnapshot;
use crate::data::candidate_selection::MinimalCandidateSelectionRowSource;
use crate::data::GatewayDataState;
use crate::scheduler::config::SchedulerOrderingConfig;
use crate::{AppState, GatewayError};
use super::super::affinity::build_scheduler_affinity_cache_key;
@@ -36,39 +31,6 @@ use super::super::selection::{
};
use super::support::{sample_auth_snapshot, sample_key, sample_provider, sample_row};
async fn state_with_routing_default_policy(
data_state: GatewayDataState,
default_policy: serde_json::Value,
) -> AppState {
let repository = Arc::new(InMemoryRoutingGroupRepository::default());
repository
.create_routing_group(CreateRoutingGroupRecord {
id: "selection-test-default".to_string(),
name: "selection-test-default".to_string(),
description: None,
enabled: true,
is_system_default: true,
sort_order: 0,
config_json: json!({"default_policy": default_policy}),
version: 1,
created_at: 1,
updated_at: 1,
published_at: None,
})
.await
.expect("routing strategy should be created");
AppState::new()
.expect("state should build")
.with_data_state_for_tests(data_state.with_routing_group_repository_for_tests(repository))
}
async fn ordering_config(state: &AppState) -> SchedulerOrderingConfig {
crate::scheduler::config::read_system_default_routing_ordering_config(state)
.await
.expect("routing strategy should load")
.unwrap_or_default()
}
async fn select_candidate(
selection_row_source: &(impl MinimalCandidateSelectionRowSource + Sync),
runtime_state: &AppState,
@@ -78,7 +40,6 @@ async fn select_candidate(
auth_snapshot: Option<&GatewayAuthApiKeySnapshot>,
now_unix_secs: u64,
) -> Result<Option<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
let ordering_config = ordering_config(runtime_state).await;
select_candidate_impl(
selection_row_source,
runtime_state,
@@ -90,7 +51,6 @@ async fn select_candidate(
None,
now_unix_secs,
false,
ordering_config,
)
.await
}
@@ -104,7 +64,6 @@ async fn collect_selectable_candidates(
auth_snapshot: Option<&GatewayAuthApiKeySnapshot>,
now_unix_secs: u64,
) -> Result<Vec<SchedulerMinimalCandidateSelectionCandidate>, GatewayError> {
let ordering_config = ordering_config(runtime_state).await;
collect_selectable_candidates_impl(
selection_row_source,
runtime_state,
@@ -116,7 +75,7 @@ async fn collect_selectable_candidates(
None,
now_unix_secs,
false,
ordering_config,
None,
)
.await
}
@@ -330,11 +289,15 @@ async fn selects_by_provider_priority_when_priority_mode_is_provider() {
global_key_first,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"priority_mode": "provider"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"provider_priority_mode".to_string(),
json!("provider"),
)]),
);
let selected = select_candidate(
state.data.as_ref(),
@@ -380,11 +343,15 @@ async fn selects_by_global_key_priority_when_priority_mode_is_global_key() {
global_key_first,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"priority_mode": "global_key"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"provider_priority_mode".to_string(),
json!("global_key"),
)]),
);
let selected = select_candidate(
state.data.as_ref(),
@@ -448,7 +415,6 @@ async fn scheduler_selection_prefers_required_capability_matches_before_priority
None,
100,
false,
SchedulerOrderingConfig::default(),
)
.await
.expect("selection should succeed")
@@ -484,11 +450,15 @@ async fn fixed_order_ignores_cached_scheduler_affinity_promotion() {
first, second,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"scheduling_mode": "fixed_order"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"scheduling_mode".to_string(),
json!("fixed_order"),
)]),
);
let auth_snapshot = sample_auth_snapshot("affinity-key-1");
state.remember_scheduler_affinity_target(
@@ -545,11 +515,15 @@ async fn fixed_order_disables_same_priority_affinity_hash_tiebreaker() {
first, second,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"scheduling_mode": "fixed_order"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"scheduling_mode".to_string(),
json!("fixed_order"),
)]),
);
let auth_snapshot = sample_auth_snapshot("affinity-key-1");
let selection = collect_selectable_candidates(
@@ -595,11 +569,15 @@ async fn cache_affinity_promotes_cached_scheduler_affinity_candidate_when_enable
first, second,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"scheduling_mode": "cache_affinity"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"scheduling_mode".to_string(),
json!("cache_affinity"),
)]),
);
let auth_snapshot = sample_auth_snapshot("affinity-key-1");
let client_session_affinity = ClientSessionAffinity::from_session_key("session-1");
@@ -632,7 +610,6 @@ async fn cache_affinity_promotes_cached_scheduler_affinity_candidate_when_enable
Some(&client_session_affinity),
100,
false,
ordering_config(&state).await,
)
.await
.expect("selection should succeed")
@@ -668,11 +645,15 @@ async fn cache_affinity_ignores_cached_scheduler_affinity_without_client_session
first, second,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"scheduling_mode": "cache_affinity"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"scheduling_mode".to_string(),
json!("cache_affinity"),
)]),
);
let auth_snapshot = sample_auth_snapshot("affinity-key-1");
state.remember_scheduler_affinity_target(
@@ -710,11 +691,15 @@ async fn load_balance_selection_does_not_remember_scheduler_affinity() {
row,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"scheduling_mode": "load_balance"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"scheduling_mode".to_string(),
json!("load_balance"),
)]),
);
let auth_snapshot = sample_auth_snapshot("affinity-key-1");
let client_session_affinity = ClientSessionAffinity::from_session_key("session-1");
let cache_key = build_scheduler_affinity_cache_key(
@@ -736,7 +721,6 @@ async fn load_balance_selection_does_not_remember_scheduler_affinity() {
Some(&client_session_affinity),
100,
false,
ordering_config(&state).await,
)
.await
.expect("selection should succeed")
@@ -774,11 +758,15 @@ async fn load_balance_ignores_provider_priority_and_cached_affinity() {
first, second,
]));
let quotas = Arc::new(InMemoryProviderQuotaRepository::seed(vec![]));
let state = state_with_routing_default_policy(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas),
json!({"scheduling_mode": "load_balance"}),
)
.await;
let state = AppState::new()
.expect("state should build")
.with_data_state_for_tests(
GatewayDataState::with_candidate_selection_and_quota_for_tests(candidates, quotas)
.with_system_config_values_for_tests(vec![(
"scheduling_mode".to_string(),
json!("load_balance"),
)]),
);
let auth_snapshot = sample_auth_snapshot("affinity-key-1");
state.remember_scheduler_affinity_target(
+125 -61
View File
@@ -55,7 +55,7 @@ impl Default for SchedulerOrderingConfig {
impl SchedulerOrderingConfig {
/// Ordering config derived from a resolved routing policy. The policy is
/// the single source of truth for request scheduling.
/// the single source of truth: no legacy system-config value is merged in.
pub(crate) fn from_routing_policy(policy: &ResolvedRoutingPolicy) -> Self {
Self {
priority_mode: scheduler_priority_mode_from_routing(policy.priority_mode),
@@ -87,7 +87,6 @@ impl SchedulerOrderingConfig {
},
keep_priority_on_conversion: self.keep_priority_on_conversion,
sticky_key_attempts: self.sticky_key_attempts,
execution_policy: aether_routing_core::RoutingExecutionPolicy::default(),
}
}
@@ -115,6 +114,61 @@ fn scheduler_scheduling_mode_from_routing(mode: RoutingSchedulingMode) -> Schedu
}
}
pub(crate) fn parse_scheduler_priority_mode(
value: Option<&serde_json::Value>,
) -> SchedulerPriorityMode {
match value
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(|value| value.to_ascii_lowercase())
.as_deref()
{
Some("global_key") => SchedulerPriorityMode::GlobalKey,
_ => SchedulerPriorityMode::Provider,
}
}
pub(crate) fn parse_keep_priority_on_conversion(value: Option<&serde_json::Value>) -> bool {
value.and_then(serde_json::Value::as_bool).unwrap_or(false)
}
pub(crate) fn parse_scheduler_scheduling_mode(
value: Option<&serde_json::Value>,
) -> SchedulerSchedulingMode {
match value
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(|value| value.to_ascii_lowercase())
.as_deref()
{
Some("fixed_order") => SchedulerSchedulingMode::FixedOrder,
Some("load_balance") => SchedulerSchedulingMode::LoadBalance,
_ => SchedulerSchedulingMode::CacheAffinity,
}
}
/// Effective scheduler ordering config for requests that carry no resolved
/// routing policy.
///
/// Resolution order:
/// 1. the enabled system-default routing group's `default_policy`;
/// 2. the legacy system-config keys (`provider_priority_mode`,
/// `scheduling_mode`, `keep_priority_on_conversion`).
///
/// Step 2 only exists so deployments that never created a routing group keep
/// their behaviour; once the legacy keys are removed this function collapses
/// to step 1 plus `SchedulerOrderingConfig::default()`.
pub(crate) async fn read_scheduler_ordering_config(
state: &AppState,
) -> Result<SchedulerOrderingConfig, GatewayError> {
if let Some(config) = read_system_default_routing_ordering_config(state).await? {
return Ok(config);
}
read_legacy_scheduler_ordering_config(state).await
}
/// Ordering config from the enabled system-default routing group, if any.
pub(crate) async fn read_system_default_routing_ordering_config(
state: &AppState,
@@ -147,6 +201,38 @@ pub(crate) async fn read_system_default_routing_ordering_config(
)))
}
/// Legacy system-config based ordering config. Kept only as a migration
/// fallback; see `read_scheduler_ordering_config`.
pub(crate) async fn read_legacy_scheduler_ordering_config(
state: &AppState,
) -> Result<SchedulerOrderingConfig, GatewayError> {
let priority_mode = parse_scheduler_priority_mode(
state
.read_system_config_json_value("provider_priority_mode")
.await?
.as_ref(),
);
let scheduling_mode = parse_scheduler_scheduling_mode(
state
.read_system_config_json_value("scheduling_mode")
.await?
.as_ref(),
);
let keep_priority_on_conversion = parse_keep_priority_on_conversion(
state
.read_system_config_json_value("keep_priority_on_conversion")
.await?
.as_ref(),
);
Ok(SchedulerOrderingConfig {
priority_mode,
scheduling_mode,
keep_priority_on_conversion,
// Legacy config never carried a sticky-key setting; use the routing default.
sticky_key_attempts: DEFAULT_STICKY_KEY_ATTEMPTS,
})
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
@@ -161,6 +247,14 @@ mod tests {
use super::*;
use crate::data::GatewayDataState;
fn legacy_values() -> [(String, serde_json::Value); 3] {
[
("provider_priority_mode".to_string(), json!("global_key")),
("scheduling_mode".to_string(), json!("load_balance")),
("keep_priority_on_conversion".to_string(), json!(true)),
]
}
async fn create_system_default(
repository: &InMemoryRoutingGroupRepository,
enabled: bool,
@@ -173,7 +267,6 @@ mod tests {
description: None,
enabled,
is_system_default: true,
sort_order: 0,
config_json,
version: 1,
created_at: 1,
@@ -185,7 +278,7 @@ mod tests {
}
#[tokio::test]
async fn system_default_routing_group_exposes_strategy_ordering() {
async fn system_default_routing_group_overrides_legacy_keys() {
let repository = Arc::new(InMemoryRoutingGroupRepository::default());
create_system_default(
&repository,
@@ -200,13 +293,12 @@ mod tests {
)
.await;
let state = AppState::new().unwrap().with_data_state_for_tests(
GatewayDataState::disabled().with_routing_group_repository_for_tests(repository),
GatewayDataState::disabled()
.with_system_config_values_for_tests(legacy_values())
.with_routing_group_repository_for_tests(repository),
);
let config = read_system_default_routing_ordering_config(&state)
.await
.unwrap()
.unwrap();
let config = read_scheduler_ordering_config(&state).await.unwrap();
assert_eq!(config.priority_mode, SchedulerPriorityMode::Provider);
assert_eq!(config.scheduling_mode, SchedulerSchedulingMode::FixedOrder);
@@ -218,19 +310,18 @@ mod tests {
let repository = Arc::new(InMemoryRoutingGroupRepository::default());
create_system_default(&repository, true, json!({})).await;
let state = AppState::new().unwrap().with_data_state_for_tests(
GatewayDataState::disabled().with_routing_group_repository_for_tests(repository),
GatewayDataState::disabled()
.with_system_config_values_for_tests(legacy_values())
.with_routing_group_repository_for_tests(repository),
);
let config = read_system_default_routing_ordering_config(&state)
.await
.unwrap()
.unwrap();
let config = read_scheduler_ordering_config(&state).await.unwrap();
assert_eq!(config, SchedulerOrderingConfig::default());
}
#[tokio::test]
async fn disabled_or_missing_system_default_group_uses_routing_defaults() {
async fn disabled_or_missing_system_default_group_falls_back_to_legacy_keys() {
let repository = Arc::new(InMemoryRoutingGroupRepository::default());
create_system_default(
&repository,
@@ -239,25 +330,28 @@ mod tests {
)
.await;
let with_disabled_group = AppState::new().unwrap().with_data_state_for_tests(
GatewayDataState::disabled().with_routing_group_repository_for_tests(repository),
GatewayDataState::disabled()
.with_system_config_values_for_tests(legacy_values())
.with_routing_group_repository_for_tests(repository),
);
let without_repository = AppState::new().unwrap().with_data_state_for_tests(
GatewayDataState::disabled().with_system_config_values_for_tests(legacy_values()),
);
let without_repository = AppState::new()
.unwrap()
.with_data_state_for_tests(GatewayDataState::disabled());
for state in [with_disabled_group, without_repository] {
let config = read_system_default_routing_ordering_config(&state)
.await
.unwrap();
assert!(config.is_none());
let config = read_scheduler_ordering_config(&state).await.unwrap();
assert_eq!(config.priority_mode, SchedulerPriorityMode::GlobalKey);
assert_eq!(config.scheduling_mode, SchedulerSchedulingMode::LoadBalance);
assert!(config.keep_priority_on_conversion);
}
}
#[tokio::test]
async fn bootstrap_creates_system_default_group_from_routing_defaults_once() {
async fn bootstrap_creates_system_default_group_from_legacy_keys_once() {
let repository = Arc::new(InMemoryRoutingGroupRepository::default());
let state = AppState::new().unwrap().with_data_state_for_tests(
GatewayDataState::disabled()
.with_system_config_values_for_tests(legacy_values())
.with_routing_group_repository_for_tests(repository.clone()),
);
@@ -271,9 +365,9 @@ mod tests {
assert_eq!(
created.config_json["default_policy"],
json!({
"priority_mode": "provider",
"scheduling_mode": "cache_affinity",
"keep_priority_on_conversion": false,
"priority_mode": "global_key",
"scheduling_mode": "load_balance",
"keep_priority_on_conversion": true,
"sticky_key_attempts": DEFAULT_STICKY_KEY_ATTEMPTS
})
);
@@ -292,39 +386,9 @@ mod tests {
Some(created.id)
);
let config = read_system_default_routing_ordering_config(&state)
.await
.unwrap()
.unwrap();
assert_eq!(config, SchedulerOrderingConfig::default());
}
#[tokio::test]
async fn bootstrap_does_not_migrate_legacy_scheduler_keys() {
let repository = Arc::new(InMemoryRoutingGroupRepository::default());
let state = AppState::new().unwrap().with_data_state_for_tests(
GatewayDataState::disabled()
.with_system_config_values_for_tests([
("provider_priority_mode".to_string(), json!("global_key")),
("scheduling_mode".to_string(), json!("load_balance")),
("keep_priority_on_conversion".to_string(), json!(true)),
])
.with_routing_group_repository_for_tests(repository),
);
let created = state
.ensure_system_default_routing_group_inner()
.await
.unwrap()
.expect("bootstrap should create the strategy");
assert_eq!(
created.config_json["default_policy"],
json!({
"priority_mode": "provider",
"scheduling_mode": "cache_affinity",
"keep_priority_on_conversion": false,
"sticky_key_attempts": DEFAULT_STICKY_KEY_ATTEMPTS
})
);
let config = read_scheduler_ordering_config(&state).await.unwrap();
assert_eq!(config.priority_mode, SchedulerPriorityMode::GlobalKey);
assert_eq!(config.scheduling_mode, SchedulerSchedulingMode::LoadBalance);
assert!(config.keep_priority_on_conversion);
}
}
@@ -10,6 +10,8 @@ use async_trait::async_trait;
use crate::GatewayError;
use super::config::SchedulerOrderingConfig;
#[async_trait]
pub(crate) trait SchedulerRuntimeState {
async fn read_provider_quota_snapshot(
@@ -58,4 +60,7 @@ pub(crate) trait SchedulerRuntimeState {
max_entries: usize,
expected_epoch: Option<u64>,
) -> bool;
async fn read_scheduler_ordering_config(&self)
-> Result<SchedulerOrderingConfig, GatewayError>;
}
+11 -7
View File
@@ -79,7 +79,12 @@ const SYSTEM_CONFIG_CACHE_TTL: Duration = Duration::from_secs(30);
// five minutes of total age. Direct database edits that bypass AppState
// invalidation can therefore take at most this bounded interval to appear.
const SYSTEM_CONFIG_CACHE_MAX_STALENESS: Duration = Duration::from_secs(5 * 60);
const SCHEDULER_AFFECTING_SYSTEM_CONFIG_KEYS: &[&str] = &["enable_format_conversion"];
const SCHEDULER_AFFECTING_SYSTEM_CONFIG_KEYS: &[&str] = &[
"enable_format_conversion",
"keep_priority_on_conversion",
"provider_priority_mode",
"scheduling_mode",
];
const AUTH_AFFECTING_SYSTEM_CONFIG_KEYS: &[&str] = &[
crate::constants::DEFAULT_USER_GROUP_CONFIG_KEY,
crate::constants::ANTIGRAVITY_BEARER_BRIDGE_CONFIG_KEY,
@@ -4345,13 +4350,12 @@ mod tests {
}
#[tokio::test]
async fn system_config_entry_write_refreshes_cache_and_scheduler_affinity_for_format_conversion(
) {
async fn system_config_entry_write_refreshes_cache_and_scheduler_affinity_for_routing_keys() {
let state = AppState::new()
.expect("app state should build")
.with_data_state_for_tests(
GatewayDataState::disabled().with_system_config_values_for_tests([(
"enable_format_conversion".to_string(),
"keep_priority_on_conversion".to_string(),
json!(false),
)]),
);
@@ -4360,7 +4364,7 @@ mod tests {
assert_eq!(
state
.read_system_config_json_value("enable_format_conversion")
.read_system_config_json_value("keep_priority_on_conversion")
.await
.expect("system config read should succeed"),
Some(json!(false))
@@ -4381,13 +4385,13 @@ mod tests {
let initial_epoch = state.scheduler_affinity_epoch();
state
.upsert_system_config_entry("enable_format_conversion", &json!(true), None)
.upsert_system_config_entry("keep_priority_on_conversion", &json!(true), None)
.await
.expect("admin config write should succeed");
assert_eq!(
state
.read_system_config_json_value("enable_format_conversion")
.read_system_config_json_value("keep_priority_on_conversion")
.await
.expect("system config read should use refreshed cache"),
Some(json!(true))
@@ -680,4 +680,10 @@ impl SchedulerRuntimeState for AppState {
expected_epoch,
)
}
async fn read_scheduler_ordering_config(
&self,
) -> Result<crate::scheduler::config::SchedulerOrderingConfig, GatewayError> {
crate::scheduler::config::read_scheduler_ordering_config(self).await
}
}
@@ -15,9 +15,10 @@ const BOOTSTRAP_SYSTEM_DEFAULT_ROUTING_GROUP_NAME: &str = "system-default";
impl AppState {
/// Make sure an enabled system-default routing group exists.
///
/// When none exists, one is created from the routing defaults.
/// Returns the created group, or `None` when nothing had to be created (no
/// routing storage, no writer, or a system default already exists).
/// When none exists, one is created from the legacy scheduler system-config
/// keys so that removing those keys later does not change behaviour. Returns
/// the created group, or `None` when nothing had to be created (no routing
/// storage, no writer, or a system default already exists).
pub async fn ensure_system_default_routing_group(
&self,
) -> Result<Option<StoredRoutingGroup>, std::io::Error> {
@@ -43,12 +44,16 @@ impl AppState {
warn!(
event_name = "routing_system_default_bootstrap_skipped",
log_type = "event",
"no system default routing group exists and routing storage is read-only; scheduler uses routing defaults"
"no system default routing group exists and routing storage is read-only; scheduler falls back to legacy system config"
);
return Ok(None);
}
let config = RoutingGroupConfig::default();
let legacy = crate::scheduler::config::read_legacy_scheduler_ordering_config(self).await?;
let config = RoutingGroupConfig {
default_policy: legacy.to_routing_default_policy(),
..RoutingGroupConfig::default()
};
let config_json = serde_json::to_value(config)
.map_err(|err| GatewayError::Internal(format!("serialize routing config: {err}")))?;
@@ -70,10 +75,9 @@ impl AppState {
self.create_routing_group(CreateRoutingGroupRecord {
id: uuid::Uuid::new_v4().to_string(),
name,
description: Some("系统默认调度策略".to_string()),
description: Some("自动从旧版调度配置迁移生成的系统默认策略".to_string()),
enabled: true,
is_system_default: true,
sort_order: 0,
config_json,
version: 1,
created_at: now,
@@ -780,6 +780,14 @@ async fn gateway_updates_admin_provider_locally_with_trusted_admin_principal() {
let provider_catalog_repository = Arc::new(InMemoryProviderCatalogReadRepository::seed(
vec![
sample_provider("provider-openai", "openai", 10)
.with_billing_fields(
Some("free_tier".to_string()),
None,
None,
Some(30),
None,
None,
)
.with_transport_fields(
true,
false,
@@ -974,6 +982,7 @@ async fn gateway_updates_admin_provider_locally_with_trusted_admin_principal() {
.iter()
.find(|provider| provider.id == "provider-openai")
.expect("provider should exist");
assert_eq!(updated_provider.billing_type.as_deref(), Some("free_tier"));
assert_eq!(
updated_provider.request_timeout_secs,
Some(aether_contracts::MAX_EXECUTION_REQUEST_TIMEOUT_SECS as f64)
@@ -1106,6 +1115,7 @@ async fn gateway_creates_admin_provider_locally_with_trusted_admin_principal() {
.find(|provider| provider.id == "provider-existing")
.expect("existing provider should remain");
assert_eq!(created.provider_type, "codex");
assert_eq!(created.billing_type.as_deref(), Some("pay_as_you_go"));
assert_eq!(created.provider_priority, 0);
assert_eq!(existing.provider_priority, 1);
assert_eq!(created.website.as_deref(), Some("https://codex.example"));
+28 -1
View File
@@ -1725,6 +1725,8 @@ pub fn admin_system_config_default_value(key: &str) -> Option<serde_json::Value>
"proxy_node_metrics_cleanup_batch_size" => Some(json!(5000)),
"enable_provider_checkin" => Some(json!(true)),
"provider_checkin_time" => Some(json!("01:05")),
"provider_priority_mode" => Some(json!("provider")),
"scheduling_mode" => Some(json!("cache_affinity")),
"auto_delete_expired_keys" => Some(json!(false)),
"turnstile_enabled" => Some(json!(false)),
"turnstile_site_key" => Some(serde_json::Value::Null),
@@ -1752,8 +1754,10 @@ pub fn admin_system_config_default_value(key: &str) -> Option<serde_json::Value>
"email_suffix_mode" => Some(json!("none")),
"email_suffix_list" => Some(json!([])),
"enable_format_conversion" => Some(json!(false)),
"cyber_continue_failover" => Some(json!(false)),
"enable_model_directives" => Some(json!(false)),
"model_directives" => Some(aether_ai_formats::default_model_directives_config()),
"keep_priority_on_conversion" => Some(json!(false)),
"audit_log_retention_days" => Some(json!(30)),
"enable_db_maintenance" => Some(json!(true)),
"system_proxy_node_id" => Some(serde_json::Value::Null),
@@ -2232,7 +2236,8 @@ pub fn parse_admin_system_config_update(
}
match normalized_key.as_str() {
"enable_model_directives"
"cyber_continue_failover"
| "enable_model_directives"
| "module.important_notification.enabled"
| "module.important_notification.email_enabled"
| "module.server_chan_push.enabled"
@@ -3503,6 +3508,28 @@ mod tests {
);
}
#[test]
fn cyber_continue_failover_defaults_to_disabled() {
assert_eq!(
admin_system_config_default_value("cyber_continue_failover"),
Some(json!(false))
);
}
#[test]
fn cyber_continue_failover_update_requires_a_boolean() {
let update =
parse_admin_system_config_update("cyber_continue_failover", br#"{"value":true}"#)
.expect("boolean Cyber failover setting should parse");
assert_eq!(update.value, json!(true));
assert!(parse_admin_system_config_update(
"cyber_continue_failover",
br#"{"value":"true"}"#,
)
.is_err());
}
#[test]
fn model_directives_update_accepts_legacy_and_current_config_shapes() {
for body in [
@@ -1,3 +0,0 @@
ALTER TABLE routing_groups
ADD COLUMN sort_order BIGINT NOT NULL DEFAULT 0,
ADD KEY routing_groups_enabled_sort_idx (enabled, sort_order, name, id);
@@ -15,7 +15,6 @@ SELECT
description,
enabled,
is_system_default,
sort_order,
config_json,
version,
created_at,
@@ -62,12 +61,10 @@ impl MysqlRoutingGroupRepository {
#[async_trait]
impl RoutingGroupReadRepository for MysqlRoutingGroupRepository {
async fn list_routing_groups(&self) -> Result<Vec<StoredRoutingGroup>, DataLayerError> {
let rows = sqlx::query(&format!(
"{ROUTING_GROUP_SELECT} ORDER BY enabled DESC, sort_order ASC, name ASC, id ASC"
))
.fetch_all(&self.pool)
.await
.map_sql_err()?;
let rows = sqlx::query(&format!("{ROUTING_GROUP_SELECT} ORDER BY name ASC, id ASC"))
.fetch_all(&self.pool)
.await
.map_sql_err()?;
rows.iter().map(map_group_row).collect()
}
@@ -176,10 +173,10 @@ impl RoutingGroupWriteRepository for MysqlRoutingGroupRepository {
sqlx::query(
r#"
INSERT INTO routing_groups (
id, name, description, enabled, is_system_default, sort_order, config_json,
id, name, description, enabled, is_system_default, config_json,
version, created_at, updated_at, published_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"#,
)
.bind(&group.id)
@@ -187,7 +184,6 @@ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
.bind(&group.description)
.bind(group.enabled)
.bind(group.is_system_default)
.bind(group.sort_order)
.bind(json_to_string(
&group.config_json,
"routing_groups.config_json",
@@ -245,7 +241,6 @@ SET name = ?,
description = ?,
enabled = ?,
is_system_default = ?,
sort_order = ?,
config_json = ?,
version = ?,
updated_at = ?,
@@ -257,7 +252,6 @@ WHERE id = ?
.bind(&group.description)
.bind(group.enabled)
.bind(group.is_system_default)
.bind(group.sort_order)
.bind(json_to_string(
&group.config_json,
"routing_groups.config_json",
@@ -466,7 +460,6 @@ fn map_group_row(row: &MySqlRow) -> Result<StoredRoutingGroup, DataLayerError> {
description: row.try_get("description").map_sql_err()?,
enabled: row.try_get("enabled").map_sql_err()?,
is_system_default: row.try_get("is_system_default").map_sql_err()?,
sort_order: row.try_get("sort_order").map_sql_err()?,
config_json: json_from_string(
row.try_get("config_json").map_sql_err()?,
"routing_groups.config_json",
@@ -79,4 +79,4 @@ BEGIN
END IF;
END $$;
CREATE INDEX IF NOT EXISTS routing_group_versions_group_id_idx
ON public.routing_group_versions USING btree (group_id);
ON public.routing_group_versions USING btree (group_id);
@@ -1,5 +0,0 @@
ALTER TABLE public.routing_groups
ADD COLUMN sort_order bigint NOT NULL DEFAULT 0;
CREATE INDEX IF NOT EXISTS routing_groups_enabled_sort_idx
ON public.routing_groups (enabled DESC, sort_order, name, id);
@@ -22,7 +22,6 @@ SELECT
description,
enabled,
is_system_default,
sort_order,
config_json,
version,
created_at,
@@ -69,9 +68,7 @@ impl PostgresRoutingGroupRepository {
#[async_trait]
impl RoutingGroupReadRepository for PostgresRoutingGroupRepository {
async fn list_routing_groups(&self) -> Result<Vec<StoredRoutingGroup>, DataLayerError> {
let sql = format!(
"{ROUTING_GROUP_SELECT} ORDER BY enabled DESC, sort_order ASC, name ASC, id ASC"
);
let sql = format!("{ROUTING_GROUP_SELECT} ORDER BY name ASC, id ASC");
let mut rows = sqlx::query(&sql).fetch(&self.pool);
let mut groups = Vec::new();
while let Some(row) = rows.try_next().await.map_postgres_err()? {
@@ -181,10 +178,10 @@ impl RoutingGroupWriteRepository for PostgresRoutingGroupRepository {
sqlx::query(
r#"
INSERT INTO routing_groups (
id, name, description, enabled, is_system_default, sort_order, config_json,
id, name, description, enabled, is_system_default, config_json,
version, created_at, updated_at, published_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
"#,
)
.bind(&group.id)
@@ -192,7 +189,6 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
.bind(&group.description)
.bind(group.enabled)
.bind(group.is_system_default)
.bind(group.sort_order)
.bind(&group.config_json)
.bind(group.version)
.bind(group.created_at)
@@ -242,11 +238,10 @@ SET name = $2,
description = $3,
enabled = $4,
is_system_default = $5,
sort_order = $6,
config_json = $7,
version = $8,
updated_at = $9,
published_at = $10
config_json = $6,
version = $7,
updated_at = $8,
published_at = $9
WHERE id = $1
"#,
)
@@ -255,7 +250,6 @@ WHERE id = $1
.bind(&group.description)
.bind(group.enabled)
.bind(group.is_system_default)
.bind(group.sort_order)
.bind(&group.config_json)
.bind(group.version)
.bind(group.updated_at)
@@ -447,7 +441,6 @@ fn map_group_row(row: &PgRow) -> Result<StoredRoutingGroup, DataLayerError> {
description: row.try_get("description").map_postgres_err()?,
enabled: row.try_get("enabled").map_postgres_err()?,
is_system_default: row.try_get("is_system_default").map_postgres_err()?,
sort_order: row.try_get("sort_order").map_postgres_err()?,
config_json: row.try_get("config_json").map_postgres_err()?,
version: row.try_get("version").map_postgres_err()?,
created_at: row.try_get("created_at").map_postgres_err()?,
@@ -1,4 +0,0 @@
ALTER TABLE routing_groups ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0;
CREATE INDEX IF NOT EXISTS routing_groups_enabled_sort_idx
ON routing_groups (enabled, sort_order, name, id);
@@ -15,7 +15,6 @@ SELECT
description,
enabled,
is_system_default,
sort_order,
config_json,
version,
created_at,
@@ -62,12 +61,10 @@ impl SqliteRoutingGroupRepository {
#[async_trait]
impl RoutingGroupReadRepository for SqliteRoutingGroupRepository {
async fn list_routing_groups(&self) -> Result<Vec<StoredRoutingGroup>, DataLayerError> {
let rows = sqlx::query(&format!(
"{ROUTING_GROUP_SELECT} ORDER BY enabled DESC, sort_order ASC, name ASC, id ASC"
))
.fetch_all(&self.pool)
.await
.map_sql_err()?;
let rows = sqlx::query(&format!("{ROUTING_GROUP_SELECT} ORDER BY name ASC, id ASC"))
.fetch_all(&self.pool)
.await
.map_sql_err()?;
rows.iter().map(map_group_row).collect()
}
@@ -171,10 +168,10 @@ impl RoutingGroupWriteRepository for SqliteRoutingGroupRepository {
sqlx::query(
r#"
INSERT INTO routing_groups (
id, name, description, enabled, is_system_default, sort_order, config_json,
id, name, description, enabled, is_system_default, config_json,
version, created_at, updated_at, published_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"#,
)
.bind(&group.id)
@@ -182,7 +179,6 @@ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
.bind(&group.description)
.bind(group.enabled)
.bind(group.is_system_default)
.bind(group.sort_order)
.bind(json_to_string(
&group.config_json,
"routing_groups.config_json",
@@ -233,7 +229,6 @@ SET name = ?,
description = ?,
enabled = ?,
is_system_default = ?,
sort_order = ?,
config_json = ?,
version = ?,
updated_at = ?,
@@ -245,7 +240,6 @@ WHERE id = ?
.bind(&group.description)
.bind(group.enabled)
.bind(group.is_system_default)
.bind(group.sort_order)
.bind(json_to_string(
&group.config_json,
"routing_groups.config_json",
@@ -444,7 +438,6 @@ fn map_group_row(row: &SqliteRow) -> Result<StoredRoutingGroup, DataLayerError>
description: row.try_get("description").map_sql_err()?,
enabled: row.try_get("enabled").map_sql_err()?,
is_system_default: row.try_get("is_system_default").map_sql_err()?,
sort_order: row.try_get("sort_order").map_sql_err()?,
config_json: json_from_string(
row.try_get("config_json").map_sql_err()?,
"routing_groups.config_json",
@@ -521,7 +514,6 @@ mod tests {
description: Some("initial".to_string()),
enabled: true,
is_system_default: true,
sort_order: 0,
config_json: json!({"allowed_models": ["gpt-*"]}),
version: 1,
created_at: 10,
@@ -798,7 +790,6 @@ SET is_default = 1,
description: None,
enabled: true,
is_system_default,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -10,9 +10,6 @@ pub struct StoredRoutingGroup {
pub description: Option<String>,
pub enabled: bool,
pub is_system_default: bool,
/// Stable administrator-defined display order. This is intentionally not
/// consulted by request routing or candidate selection.
pub sort_order: i64,
pub config_json: Value,
pub version: i64,
pub created_at: i64,
@@ -31,7 +28,6 @@ impl StoredRoutingGroup {
description: record.description,
enabled: record.enabled,
is_system_default: record.is_system_default,
sort_order: record.sort_order.max(0),
config_json: record.config_json,
version: record.version.max(1),
created_at: record.created_at,
@@ -48,7 +44,6 @@ pub struct CreateRoutingGroupRecord {
pub description: Option<String>,
pub enabled: bool,
pub is_system_default: bool,
pub sort_order: i64,
pub config_json: Value,
pub version: i64,
pub created_at: i64,
@@ -62,7 +57,6 @@ pub struct UpdateRoutingGroupRecord {
pub description: Option<Option<String>>,
pub enabled: Option<bool>,
pub is_system_default: Option<bool>,
pub sort_order: Option<i64>,
pub config_json: Option<Value>,
pub version: Option<i64>,
pub updated_at: i64,
@@ -261,9 +255,6 @@ pub fn apply_group_patch(
if let Some(is_system_default) = patch.is_system_default {
group.is_system_default = is_system_default;
}
if let Some(sort_order) = patch.sort_order {
group.sort_order = sort_order.max(0);
}
if let Some(config_json) = patch.config_json {
if !config_json.is_object() {
return Err(crate::DataLayerError::InvalidInput(
@@ -85,4 +85,4 @@ BEGIN
END IF;
END $$;
CREATE INDEX IF NOT EXISTS routing_group_versions_group_id_idx
ON public.routing_group_versions USING btree (group_id);
ON public.routing_group_versions USING btree (group_id);
@@ -391,7 +391,6 @@ CREATE TABLE IF NOT EXISTS routing_groups (
`description` LONGTEXT,
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
`is_system_default` TINYINT(1) NOT NULL DEFAULT 0,
`sort_order` BIGINT NOT NULL DEFAULT 0,
`config_json` JSON NOT NULL,
`version` BIGINT NOT NULL DEFAULT 1,
`created_at` BIGINT NOT NULL,
@@ -399,8 +398,7 @@ CREATE TABLE IF NOT EXISTS routing_groups (
`published_at` BIGINT,
PRIMARY KEY (`id`),
UNIQUE KEY routing_groups_name_key (`name`),
KEY routing_groups_system_default_idx (`is_system_default`, `enabled`),
KEY routing_groups_enabled_sort_idx (`enabled`, `sort_order`, `name`, `id`)
KEY routing_groups_system_default_idx (`is_system_default`, `enabled`)
);
CREATE TABLE IF NOT EXISTS routing_group_bindings (
@@ -404,7 +404,6 @@ CREATE TABLE IF NOT EXISTS public.routing_groups (
description text,
enabled boolean DEFAULT true NOT NULL,
is_system_default boolean DEFAULT false NOT NULL,
sort_order bigint DEFAULT 0 NOT NULL,
config_json jsonb NOT NULL,
version bigint DEFAULT 1 NOT NULL,
created_at bigint NOT NULL,
@@ -415,7 +414,6 @@ CREATE TABLE IF NOT EXISTS public.routing_groups (
ALTER TABLE ONLY public.routing_groups ADD CONSTRAINT routing_groups_pkey PRIMARY KEY (id);
ALTER TABLE ONLY public.routing_groups ADD CONSTRAINT routing_groups_name_key UNIQUE (name);
CREATE INDEX IF NOT EXISTS routing_groups_system_default_idx ON public.routing_groups USING btree (is_system_default, enabled);
CREATE INDEX IF NOT EXISTS routing_groups_enabled_sort_idx ON public.routing_groups USING btree (enabled, sort_order, name, id);
CREATE TABLE IF NOT EXISTS public.routing_group_bindings (
id character varying(64) NOT NULL,
@@ -378,7 +378,6 @@ CREATE TABLE IF NOT EXISTS routing_groups (
description TEXT,
enabled INTEGER NOT NULL DEFAULT 1,
is_system_default INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
config_json TEXT NOT NULL,
version INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
@@ -387,7 +386,6 @@ CREATE TABLE IF NOT EXISTS routing_groups (
UNIQUE (name)
);
CREATE INDEX IF NOT EXISTS routing_groups_system_default_idx ON routing_groups (is_system_default, enabled);
CREATE INDEX IF NOT EXISTS routing_groups_enabled_sort_idx ON routing_groups (enabled, sort_order, name, id);
CREATE TABLE IF NOT EXISTS routing_group_bindings (
id TEXT PRIMARY KEY NOT NULL,
@@ -1733,11 +1733,6 @@ name = "is_system_default"
type = "bool"
default = false
[[table.routing_groups.columns]]
name = "sort_order"
type = "int64"
default = 0
[[table.routing_groups.columns]]
name = "config_json"
type = "json"
@@ -1768,10 +1763,6 @@ columns = ["name"]
name = "routing_groups_system_default_idx"
columns = ["is_system_default", "enabled"]
[[table.routing_groups.indexes]]
name = "routing_groups_enabled_sort_idx"
columns = ["enabled", "sort_order", "name", "id"]
[table.routing_group_bindings]
domain = "provider_catalog"
order = 111
@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
use sqlx::{
migrate::{Migrate, MigrateError, Migrator},
query, query_scalar, Connection, MySqlConnection, Row,
query, Connection, MySqlConnection, Row,
};
use tracing::{error, info, warn};
@@ -11,7 +11,6 @@ use crate::driver::mysql::MysqlPool;
static BACKFILL_MIGRATOR: Migrator = sqlx::migrate!("./backfills/mysql");
const SCHEMA_BACKFILLS_TABLE_EXISTS_SQL: &str = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'schema_backfills'";
const ENSURE_SCHEMA_BACKFILLS_TABLE_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS schema_backfills (
version BIGINT NOT NULL,
@@ -162,21 +161,12 @@ async fn run_backfills_locked(conn: &mut MySqlConnection) -> Result<(), MigrateE
async fn pending_backfills_locked(
conn: &mut MySqlConnection,
) -> Result<Vec<PendingBackfillInfo>, MigrateError> {
if !schema_backfills_table_exists(conn).await? {
return Ok(pending_backfills_from_applied(&[]));
}
ensure_schema_backfills_table(conn).await?;
let applied_backfills = list_applied_backfills(conn).await?;
validate_applied_backfills(&applied_backfills)?;
Ok(pending_backfills_from_applied(&applied_backfills))
}
async fn schema_backfills_table_exists(conn: &mut MySqlConnection) -> Result<bool, MigrateError> {
let total: i64 = query_scalar(SCHEMA_BACKFILLS_TABLE_EXISTS_SQL)
.fetch_one(&mut *conn)
.await?;
Ok(total > 0)
}
async fn ensure_schema_backfills_table(conn: &mut MySqlConnection) -> Result<(), MigrateError> {
query(ENSURE_SCHEMA_BACKFILLS_TABLE_SQL)
.execute(&mut *conn)
@@ -155,23 +155,17 @@ async fn run_backfills_locked(conn: &mut PgConnection) -> Result<(), MigrateErro
async fn pending_backfills_locked(
conn: &mut PgConnection,
) -> Result<Vec<PendingBackfillInfo>, MigrateError> {
if !schema_backfills_table_exists(conn).await? {
return Ok(pending_backfills_from_applied(&[]));
}
ensure_schema_backfills_table(conn).await?;
let applied_backfills = list_applied_backfills(conn).await?;
validate_applied_backfills(&applied_backfills)?;
Ok(pending_backfills_from_applied(&applied_backfills))
}
async fn schema_backfills_table_exists(conn: &mut PgConnection) -> Result<bool, MigrateError> {
query_scalar(SCHEMA_BACKFILLS_TABLE_EXISTS_SQL)
.fetch_one(&mut *conn)
.await
.map_err(Into::into)
}
async fn ensure_schema_backfills_table(conn: &mut PgConnection) -> Result<(), MigrateError> {
if schema_backfills_table_exists(conn).await? {
let exists: bool = query_scalar(SCHEMA_BACKFILLS_TABLE_EXISTS_SQL)
.fetch_one(&mut *conn)
.await?;
if exists {
return Ok(());
}
query(ENSURE_SCHEMA_BACKFILLS_TABLE_SQL)
@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
use sqlx::{
migrate::{Migrate, MigrateError, Migrator},
query, query_scalar, Connection, Row, SqliteConnection,
query, Connection, Row, SqliteConnection,
};
use tracing::{error, info, warn};
@@ -11,8 +11,6 @@ use crate::driver::sqlite::SqlitePool;
static BACKFILL_MIGRATOR: Migrator = sqlx::migrate!("./backfills/sqlite");
const SCHEMA_BACKFILLS_TABLE_EXISTS_SQL: &str =
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'schema_backfills'";
const ENSURE_SCHEMA_BACKFILLS_TABLE_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS schema_backfills (
version INTEGER NOT NULL PRIMARY KEY,
@@ -164,21 +162,12 @@ async fn run_backfills_locked(conn: &mut SqliteConnection) -> Result<(), Migrate
async fn pending_backfills_locked(
conn: &mut SqliteConnection,
) -> Result<Vec<PendingBackfillInfo>, MigrateError> {
if !schema_backfills_table_exists(conn).await? {
return Ok(pending_backfills_from_applied(&[]));
}
ensure_schema_backfills_table(conn).await?;
let applied_backfills = list_applied_backfills(conn).await?;
validate_applied_backfills(&applied_backfills)?;
Ok(pending_backfills_from_applied(&applied_backfills))
}
async fn schema_backfills_table_exists(conn: &mut SqliteConnection) -> Result<bool, MigrateError> {
let total: i64 = query_scalar(SCHEMA_BACKFILLS_TABLE_EXISTS_SQL)
.fetch_one(&mut *conn)
.await?;
Ok(total > 0)
}
async fn ensure_schema_backfills_table(conn: &mut SqliteConnection) -> Result<(), MigrateError> {
query(ENSURE_SCHEMA_BACKFILLS_TABLE_SQL)
.execute(&mut *conn)
@@ -310,31 +310,6 @@ INSERT INTO usage_settlement_snapshots (
}
}
#[tokio::test]
async fn pending_sqlite_backfills_does_not_create_tracking_table() {
let pool = sqlx::sqlite::SqlitePoolOptions::new()
.max_connections(1)
.connect("sqlite::memory:")
.await
.expect("sqlite backfill status pool should connect");
run_sqlite_migrations(&pool)
.await
.expect("sqlite schema should migrate");
let pending = pending_sqlite_backfills(&pool)
.await
.expect("sqlite pending backfills should load");
assert!(!pending.is_empty());
let tracking_tables: i64 = query_scalar(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'schema_backfills'",
)
.fetch_one(&pool)
.await
.expect("sqlite tracking table state should load");
assert_eq!(tracking_tables, 0);
}
#[tokio::test]
async fn sqlite_backfills_apply_portable_repairs_and_record_versions() {
let pool = sqlx::sqlite::SqlitePoolOptions::new()
@@ -59,14 +59,7 @@ impl RoutingGroupReadRepository for InMemoryRoutingGroupRepository {
.values()
.cloned()
.collect::<Vec<_>>();
groups.sort_by(|left, right| {
right
.enabled
.cmp(&left.enabled)
.then(left.sort_order.cmp(&right.sort_order))
.then(left.name.cmp(&right.name))
.then(left.id.cmp(&right.id))
});
groups.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id)));
Ok(groups)
}
@@ -280,7 +273,6 @@ mod tests {
description: None,
enabled: true,
is_system_default: true,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
@@ -328,49 +320,6 @@ mod tests {
);
}
#[tokio::test]
async fn lists_enabled_groups_first_and_respects_sort_order() {
let repository = InMemoryRoutingGroupRepository::default();
for (id, enabled, sort_order) in [
("disabled-first", false, 0),
("enabled-second", true, 20),
("enabled-first", true, 10),
] {
repository
.create_routing_group(CreateRoutingGroupRecord {
id: id.to_string(),
name: id.to_string(),
description: None,
enabled,
is_system_default: false,
sort_order,
config_json: json!({}),
version: 1,
created_at: 1,
updated_at: 1,
published_at: None,
})
.await
.expect("group should store");
}
let ids = repository
.list_routing_groups()
.await
.expect("groups should list")
.into_iter()
.map(|group| group.id)
.collect::<Vec<_>>();
assert_eq!(
ids,
vec![
"enabled-first".to_string(),
"enabled-second".to_string(),
"disabled-first".to_string(),
]
);
}
#[tokio::test]
async fn keeps_system_and_subject_defaults_unique() {
let repository = InMemoryRoutingGroupRepository::default();
@@ -465,7 +414,6 @@ mod tests {
description: None,
enabled: true,
is_system_default,
sort_order: 0,
config_json: json!({}),
version: 1,
created_at: 1,
+3 -3
View File
@@ -13,9 +13,9 @@ pub use actions::{
};
pub use conditions::{RoutingCondition, RoutingConditionContext, RoutingConditionOp};
pub use model::{
RoutingDefaultPolicy, RoutingExecutionPolicy, RoutingGroupBinding, RoutingGroupBindingSubject,
RoutingGroupConfig, RoutingGroupRecord, RoutingGroupVersionRecord, RoutingModelPolicy,
RoutingPoolPolicyOverride, RoutingRule, RoutingSchedulingPreset, DEFAULT_STICKY_KEY_ATTEMPTS,
RoutingDefaultPolicy, RoutingGroupBinding, RoutingGroupBindingSubject, RoutingGroupConfig,
RoutingGroupRecord, RoutingGroupVersionRecord, RoutingModelPolicy, RoutingPoolPolicyOverride,
RoutingRule, RoutingSchedulingPreset, DEFAULT_STICKY_KEY_ATTEMPTS,
};
pub use mutations::{
apply_json_patch_operations, validate_header_patch, validate_json_patch_operations,
+2 -52
View File
@@ -27,47 +27,6 @@ pub struct RoutingPoolPolicyOverride {
/// failing over: one retry on the same key.
pub const DEFAULT_STICKY_KEY_ATTEMPTS: u32 = 2;
/// Request-independent execution behaviours selected by a routing strategy.
///
/// These flags deliberately live beside scheduling rather than in provider
/// transport configuration. A resolved policy is snapshotted for the request
/// and can therefore be consumed by execution without rereading mutable
/// system settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Default)]
pub struct RoutingExecutionPolicy {
#[serde(default, skip_serializing_if = "is_false")]
pub enable_cf_heartbeat: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub cyber_continue_failover: bool,
}
impl<'de> Deserialize<'de> for RoutingExecutionPolicy {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize, Default)]
struct LegacyCompatibleExecutionPolicy {
#[serde(default)]
enable_cf_heartbeat: bool,
#[serde(default)]
enable_openai_image_sync_heartbeat: bool,
#[serde(default)]
enable_standard_text_sync_heartbeat: bool,
#[serde(default)]
cyber_continue_failover: bool,
}
let value = LegacyCompatibleExecutionPolicy::deserialize(deserializer)?;
Ok(Self {
enable_cf_heartbeat: value.enable_cf_heartbeat
|| value.enable_openai_image_sync_heartbeat
|| value.enable_standard_text_sync_heartbeat,
cyber_continue_failover: value.cyber_continue_failover,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoutingDefaultPolicy {
#[serde(default)]
@@ -81,10 +40,6 @@ pub struct RoutingDefaultPolicy {
/// `0` and `1` both mean no same-key retry.
#[serde(default = "default_sticky_key_attempts")]
pub sticky_key_attempts: u32,
/// Strategy-scoped execution behaviour. Flattened for a stable JSON
/// shape and backwards-compatible migration from system settings.
#[serde(flatten)]
pub execution_policy: RoutingExecutionPolicy,
}
impl Default for RoutingDefaultPolicy {
@@ -94,7 +49,6 @@ impl Default for RoutingDefaultPolicy {
scheduling_mode: RoutingSchedulingMode::default(),
keep_priority_on_conversion: false,
sticky_key_attempts: DEFAULT_STICKY_KEY_ATTEMPTS,
execution_policy: RoutingExecutionPolicy::default(),
}
}
}
@@ -103,10 +57,6 @@ fn default_sticky_key_attempts() -> u32 {
DEFAULT_STICKY_KEY_ATTEMPTS
}
fn is_false(value: &bool) -> bool {
!*value
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RoutingModelPolicy {
pub model: String,
@@ -150,8 +100,8 @@ pub struct RoutingRule {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RoutingGroupConfig {
/// The default policy is global for the selected strategy group. Model
/// differences are expressed through `model_policies` and `rules`.
#[serde(default)]
pub allowed_models: Vec<String>,
#[serde(default)]
pub default_policy: RoutingDefaultPolicy,
#[serde(default)]
+45 -41
View File
@@ -8,9 +8,7 @@ use crate::actions::{
RoutingAction, RoutingRulePhase, RoutingSchedulingMode, RoutingSetPriorityMode,
};
use crate::conditions::RoutingConditionContext;
use crate::model::{
RoutingExecutionPolicy, RoutingGroupConfig, RoutingModelPolicy, RoutingPoolPolicyOverride,
};
use crate::model::{RoutingGroupConfig, RoutingModelPolicy, RoutingPoolPolicyOverride};
use crate::mutations::{validate_header_patch, validate_json_patch_operations, MutationPlan};
use crate::ranking::RankingOverlay;
use crate::validation::validate_routing_group_config;
@@ -19,7 +17,7 @@ use crate::validation::validate_routing_group_config;
pub enum RoutingPolicyError {
#[error("routing group config is invalid: {0}")]
InvalidConfig(String),
#[error("model is not allowed by routing rule: {0}")]
#[error("model is not allowed by routing group: {0}")]
ModelNotAllowed(String),
#[error("mutation action is invalid: {0}")]
InvalidMutation(String),
@@ -62,8 +60,6 @@ pub struct ResolvedRoutingPolicy {
/// See `RoutingDefaultPolicy::sticky_key_attempts`.
#[serde(default = "default_sticky_key_attempts")]
pub sticky_key_attempts: u32,
#[serde(flatten)]
pub execution_policy: RoutingExecutionPolicy,
pub ranking_overlay: RankingOverlay,
pub mutation_plan: MutationPlan,
#[serde(default)]
@@ -79,6 +75,14 @@ pub fn resolve_routing_policy(
validate_routing_group_config(config)
.map_err(|error| RoutingPolicyError::InvalidConfig(error.to_string()))?;
if !model_allowed(&config.allowed_models, input.requested_model)
&& !model_allowed(&config.allowed_models, input.resolved_model)
{
return Err(RoutingPolicyError::ModelNotAllowed(
input.requested_model.to_string(),
));
}
let mut policy = ResolvedRoutingPolicy {
group_id: input.group_id.map(str::to_string),
group_version: input.group_version,
@@ -89,7 +93,6 @@ pub fn resolve_routing_policy(
scheduling_mode: config.default_policy.scheduling_mode,
keep_priority_on_conversion: config.default_policy.keep_priority_on_conversion,
sticky_key_attempts: config.default_policy.sticky_key_attempts,
execution_policy: config.default_policy.execution_policy,
ranking_overlay: RankingOverlay::default(),
mutation_plan: MutationPlan::default(),
pool_policy_overrides: BTreeMap::new(),
@@ -319,6 +322,7 @@ mod tests {
#[test]
fn resolves_model_policy_and_matching_rule() {
let config = RoutingGroupConfig {
allowed_models: vec!["gpt-*".to_string()],
default_policy: RoutingDefaultPolicy::default(),
model_policies: vec![RoutingModelPolicy {
model: "gpt-5".to_string(),
@@ -385,14 +389,14 @@ mod tests {
}
#[test]
fn default_policy_applies_to_models_without_an_override() {
fn empty_allowlist_keeps_default_policy_for_models_without_an_override() {
let config = RoutingGroupConfig {
allowed_models: vec![],
default_policy: RoutingDefaultPolicy {
priority_mode: RoutingSetPriorityMode::GlobalKey,
scheduling_mode: RoutingSchedulingMode::LoadBalance,
keep_priority_on_conversion: true,
sticky_key_attempts: 3,
execution_policy: Default::default(),
},
model_policies: vec![RoutingModelPolicy {
model: "special-model".to_string(),
@@ -467,38 +471,6 @@ mod tests {
.is_empty());
}
#[test]
fn legacy_group_model_allowlist_is_ignored() {
let config: RoutingGroupConfig = serde_json::from_value(json!({
"allowed_models": ["gpt-5"],
"default_policy": {
"priority_mode": "provider",
"scheduling_mode": "cache_affinity"
},
"model_policies": [],
"rules": []
}))
.expect("legacy routing config should remain readable");
resolve_routing_policy(
&config,
RoutingPolicyInput {
group_id: Some("group-1"),
group_version: Some(1),
selection_source: "system_default",
requested_model: "claude-sonnet",
resolved_model: "claude-sonnet",
api_format: "openai:chat",
user_id: None,
api_key_id: None,
headers: &json!({}),
body: &json!({}),
phase: RoutingRulePhase::ClientRequest,
},
)
.expect("the legacy allowlist must not reject another model");
}
#[test]
fn sticky_key_attempts_defaults_to_two_and_can_be_overridden_by_rule() {
let default_config = RoutingGroupConfig::default();
@@ -569,9 +541,41 @@ mod tests {
assert_eq!(policy.sticky_key_attempts, 1);
}
#[test]
fn rejects_disallowed_model() {
let config = RoutingGroupConfig {
allowed_models: vec!["gpt-5".to_string()],
..RoutingGroupConfig::default()
};
let err = resolve_routing_policy(
&config,
RoutingPolicyInput {
group_id: None,
group_version: None,
selection_source: "test",
requested_model: "claude",
resolved_model: "claude",
api_format: "openai:chat",
user_id: None,
api_key_id: None,
headers: &json!({}),
body: &json!({}),
phase: RoutingRulePhase::ClientRequest,
},
)
.unwrap_err();
assert_eq!(
err,
RoutingPolicyError::ModelNotAllowed("claude".to_string())
);
}
#[test]
fn restrict_model_action_rejects_matching_request() {
let config = RoutingGroupConfig {
allowed_models: vec!["*".to_string()],
rules: vec![RoutingRule {
id: "restrict".to_string(),
priority: 1,
+2 -2
View File
@@ -228,6 +228,6 @@ docker image prune -f >/dev/null 2>&1 || true
echo ">>> Done!"
echo ">>> Note: empty databases auto-bootstrap on first start."
echo ">>> Note: database schema and data preparation run automatically before app startup."
echo ">>> Note: set AETHER_GATEWAY_DATABASE_MODE=verify-only to require a separate database prepare step."
echo ">>> Note: docker compose now defaults to auto-running pending migrations/backfills on app startup."
echo ">>> Note: set AETHER_GATEWAY_AUTO_PREPARE_DATABASE=false if you want to keep manual rollout."
"${DC[@]}" ps
-3
View File
@@ -13,7 +13,6 @@ export interface RoutingGroupRecord {
description?: string | null
enabled: boolean
is_system_default: boolean
sort_order: number
config_json: RoutingGroupConfig
version: number
created_at: number
@@ -62,7 +61,6 @@ export interface RoutingGroupCreateRequest {
description?: string | null
enabled?: boolean
is_system_default?: boolean
sort_order?: number
config_json?: RoutingGroupConfig
}
@@ -71,7 +69,6 @@ export interface RoutingGroupUpdateRequest {
description?: string | null
enabled?: boolean
is_system_default?: boolean
sort_order?: number
config_json?: RoutingGroupConfig
version?: number
published_at?: number | null
@@ -1,33 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
import { CircleHelp } from 'lucide-vue-next'
const props = defineProps<{
label: string
text: string
}>()
const open = ref(false)
</script>
<template>
<span class="group relative inline-flex">
<button
type="button"
class="inline-flex items-center justify-center rounded-sm p-0.5 text-muted-foreground/60 transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
:aria-label="`${props.label}说明`"
:aria-expanded="open"
:title="props.text"
@click.stop="open = !open"
>
<CircleHelp class="h-3.5 w-3.5" />
</button>
<span
role="tooltip"
class="pointer-events-none invisible absolute left-1/2 top-full z-[230] mt-2 w-max max-w-xs -translate-x-1/2 rounded-md border bg-popover px-3 py-2 text-xs leading-5 text-popover-foreground opacity-0 shadow-md transition-opacity group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100"
:class="open ? 'visible opacity-100' : ''"
>
{{ props.text }}
</span>
</span>
</template>
File diff suppressed because it is too large Load Diff
@@ -37,7 +37,6 @@
:provider-proxy-node-name="getProviderProxyNodeName()"
:saving-provider-proxy="savingProviderProxy"
@toggle-format-conversion="toggleFormatConversion"
@toggle-keep-priority-on-conversion="toggleKeepPriorityOnConversion"
@open-failover-rules="failoverRulesDialogOpen = true"
@set-provider-proxy="setProviderProxy"
@clear-provider-proxy="clearProviderProxy"
@@ -1413,24 +1412,6 @@ async function toggleFormatConversion() {
}
}
async function toggleKeepPriorityOnConversion() {
if (!provider.value) return
const formatConversionAvailable =
provider.value.enable_format_conversion || systemFormatConversionEnabled.value
if (!formatConversionAvailable) return
const newValue = !provider.value.keep_priority_on_conversion
try {
const updated = await updateProvider(provider.value.id, {
keep_priority_on_conversion: newValue,
})
applyProviderSnapshot(updated)
showSuccess(legacyT(newValue ? '已启用格式转换保持优先级' : '已禁用格式转换保持优先级'))
emit('refresh')
} catch {
showError(legacyT('切换格式转换保持优先级失败'))
}
}
function getProviderProxyNodeName(): string {
const nodeId = provider.value?.proxy?.node_id
if (!nodeId) return legacyT('未知节点')
@@ -24,17 +24,6 @@
<Shuffle class="w-4 h-4" />
</Button>
</span>
<span :title="keepPriorityTitle">
<Button
variant="ghost"
size="icon"
:class="provider.keep_priority_on_conversion ? 'text-primary' : ''"
:disabled="!formatConversionAvailable"
@click="$emit('toggleKeepPriorityOnConversion')"
>
<Layers class="w-4 h-4" />
</Button>
</span>
<span :title="legacyT(hasFailoverRules ? '已配置故障转移规则(点击编辑)' : '配置故障转移规则')">
<Button
variant="ghost"
@@ -174,7 +163,7 @@
<script setup lang="ts">
import { computed } from 'vue'
import { Edit, GitBranch, Globe, Layers, Loader2, Plus, Power, Shuffle, X } from 'lucide-vue-next'
import { Edit, GitBranch, Globe, Loader2, Plus, Power, Shuffle, X } from 'lucide-vue-next'
import Button from '@/components/ui/button.vue'
import Badge from '@/components/ui/badge.vue'
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui'
@@ -196,7 +185,6 @@ const props = defineProps<{
defineEmits<{
(e: 'toggleFormatConversion'): void
(e: 'toggleKeepPriorityOnConversion'): void
(e: 'openFailoverRules'): void
(e: 'update:providerProxyPopoverOpen', value: boolean): void
(e: 'setProviderProxy', value: string): void
@@ -215,15 +203,4 @@ const formatConversionTitle = computed(() => {
if (props.provider.enable_format_conversion) return legacyT('已启用格式转换(点击关闭)')
return legacyT('启用格式转换')
})
const formatConversionAvailable = computed(() => (
props.provider.enable_format_conversion || props.systemFormatConversionEnabled
))
const keepPriorityTitle = computed(() => {
if (!formatConversionAvailable.value) return legacyT('请先启用格式转换')
return props.provider.keep_priority_on_conversion
? legacyT('已启用格式转换保持优先级(点击关闭)')
: legacyT('启用格式转换保持优先级')
})
</script>
@@ -123,39 +123,11 @@
</div>
</div>
<!-- 计费与限流 / 请求配置 -->
<!-- 请求配置 -->
<div class="space-y-3">
<div class="grid grid-cols-2 gap-4">
<h3 class="text-sm font-medium border-b pb-2">
{{ legacyT('计费与限流') }}
</h3>
<h3 class="text-sm font-medium border-b pb-2">
{{ legacyT('请求配置') }}
</h3>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-1.5">
<Label>{{ legacyT('计费类型') }}</Label>
<Select
v-model="form.billing_type"
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly_quota">
{{ legacyT('月卡额度') }}
</SelectItem>
<SelectItem value="pay_as_you_go">
{{ legacyT('按量付费') }}
</SelectItem>
<SelectItem value="free_tier">
{{ legacyT('免费套餐') }}
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<h3 class="text-sm font-medium border-b pb-2">
{{ legacyT('请求配置') }}
</h3>
<!-- 超时配置 -->
<div class="grid grid-cols-2 gap-4">
@@ -229,49 +201,6 @@
/>
</div>
</div>
<!-- 月卡配置 -->
<div
v-if="form.billing_type === 'monthly_quota'"
class="grid grid-cols-2 gap-4 p-3 border rounded-lg bg-muted/50"
>
<div class="space-y-1.5">
<Label class="text-xs">{{ legacyT('周期额度 (USD)') }}</Label>
<Input
:model-value="form.monthly_quota_usd ?? ''"
type="number"
step="0.01"
min="0"
@update:model-value="(v) => form.monthly_quota_usd = parseNumberInput(v, { allowFloat: true })"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">{{ legacyT('重置周期 (天)') }}</Label>
<Input
:model-value="form.quota_reset_day ?? ''"
type="number"
min="1"
max="365"
@update:model-value="(v) => form.quota_reset_day = parseNumberInput(v) ?? 30"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">
{{ legacyT('周期开始时间') }} <span class="text-red-500">*</span>
</Label>
<Input
v-model="form.quota_last_reset_at"
type="datetime-local"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">{{ legacyT('过期时间') }}</Label>
<Input
v-model="form.quota_expires_at"
type="datetime-local"
/>
</div>
</div>
</div>
<!-- 功能开关 -->
@@ -280,6 +209,19 @@
{{ legacyT('功能开关') }}
</h3>
<div class="flex items-center justify-between p-3 border rounded-lg bg-muted/50">
<div class="space-y-0.5">
<span class="text-sm font-medium">{{ legacyT('格式转换保持优先级') }}</span>
<p class="text-xs text-muted-foreground">
{{ legacyT('跨格式请求时保持原优先级排名,不降级到格式匹配的提供商之后') }}
</p>
</div>
<Switch
:model-value="form.keep_priority_on_conversion"
@update:model-value="(v: boolean) => form.keep_priority_on_conversion = v"
/>
</div>
<div class="flex items-center justify-between p-3 border rounded-lg bg-muted/50">
<div class="space-y-0.5">
<span class="text-sm font-medium">{{ legacyT('号池调度模式') }}</span>
@@ -413,7 +355,6 @@ import {
} from '@/api/endpoints'
import { parseApiError } from '@/utils/errorParser'
import { parseNumberInput } from '@/utils/form'
import { dateTimeLocalToRfc3339, formatDateTimeLocalInput } from '@/utils/date'
const props = defineProps<{
modelValue: boolean
@@ -455,13 +396,8 @@ const form = ref({
provider_type: 'custom' as ProviderType,
description: '',
website: '',
// 计费配置
billing_type: 'pay_as_you_go' as 'monthly_quota' | 'pay_as_you_go' | 'free_tier',
monthly_quota_usd: undefined as number | undefined,
quota_reset_day: 30,
quota_last_reset_at: '', // 周期开始时间
quota_expires_at: '',
provider_priority: 100,
keep_priority_on_conversion: false, // 格式转换时是否保持优先级
// 状态配置
is_active: true,
rate_limit: undefined as number | undefined,
@@ -490,12 +426,8 @@ function resetForm() {
provider_type: 'custom',
description: '',
website: '',
billing_type: 'pay_as_you_go',
monthly_quota_usd: undefined,
quota_reset_day: 30,
quota_last_reset_at: '',
quota_expires_at: '',
provider_priority: defaultPriority.value,
keep_priority_on_conversion: false,
is_active: true,
rate_limit: undefined,
concurrent_limit: undefined,
@@ -527,12 +459,8 @@ function loadProviderData() {
provider_type: props.provider.provider_type || 'custom',
description: props.provider.description || '',
website: props.provider.website || '',
billing_type: (props.provider.billing_type as 'monthly_quota' | 'pay_as_you_go' | 'free_tier') || 'pay_as_you_go',
monthly_quota_usd: props.provider.monthly_quota_usd || undefined,
quota_reset_day: props.provider.quota_reset_day || 30,
quota_last_reset_at: formatDateTimeLocalInput(props.provider.quota_last_reset_at),
quota_expires_at: formatDateTimeLocalInput(props.provider.quota_expires_at),
provider_priority: props.provider.provider_priority || 999,
keep_priority_on_conversion: props.provider.keep_priority_on_conversion ?? false,
is_active: props.provider.is_active,
rate_limit: undefined,
concurrent_limit: undefined,
@@ -579,23 +507,6 @@ watch(() => form.value.provider_type, () => {
// 提交表单
const handleSubmit = async () => {
// 月卡类型必须设置周期开始时间
if (form.value.billing_type === 'monthly_quota' && !form.value.quota_last_reset_at) {
showError(legacyT('月卡类型必须设置周期开始时间'), legacyT('验证失败'))
return
}
const quotaLastResetAt = dateTimeLocalToRfc3339(form.value.quota_last_reset_at)
if (form.value.billing_type === 'monthly_quota' && !quotaLastResetAt) {
showError(legacyT('周期开始时间必须是合法时间'), legacyT('验证失败'))
return
}
const quotaExpiresAt = dateTimeLocalToRfc3339(form.value.quota_expires_at)
if (form.value.quota_expires_at && !quotaExpiresAt) {
showError(legacyT('过期时间必须是合法时间'), legacyT('验证失败'))
return
}
loading.value = true
try {
const currentPoolAdvanced = normalizePoolAdvancedConfig(props.provider?.pool_advanced)
@@ -604,11 +515,7 @@ const handleSubmit = async () => {
provider_type: form.value.provider_type,
description: form.value.description || undefined,
website: form.value.website || undefined,
billing_type: form.value.billing_type,
monthly_quota_usd: form.value.monthly_quota_usd,
quota_reset_day: form.value.quota_reset_day,
quota_last_reset_at: quotaLastResetAt,
quota_expires_at: quotaExpiresAt,
keep_priority_on_conversion: form.value.keep_priority_on_conversion,
responses_websocket_enabled: form.value.responses_websocket_enabled,
is_active: form.value.is_active,
// 请求配置
@@ -98,6 +98,19 @@
<div class="hidden sm:block h-4 w-px bg-border" />
<!-- 调度策略 -->
<button
class="group inline-flex items-center gap-1.5 px-2.5 h-8 rounded-md border border-border/50 bg-muted/20 hover:bg-muted/40 hover:border-primary/40 transition-all duration-200 text-xs"
:title="legacyT('点击调整调度策略')"
@click="$emit('openPriorityDialog')"
>
<span class="text-muted-foreground/80 hidden sm:inline">{{ legacyT('调度:') }}</span>
<span class="font-medium text-foreground/90">{{ priorityModeLabel }}</span>
<ChevronDown class="w-3 h-3 text-muted-foreground/70 group-hover:text-foreground transition-colors" />
</button>
<div class="hidden sm:block h-4 w-px bg-border" />
<!-- 操作按钮 -->
<Button
variant="ghost"
@@ -128,7 +141,7 @@
</template>
<script setup lang="ts">
import { Search, Plus, FilterX, Users } from 'lucide-vue-next'
import { Search, Plus, ChevronDown, FilterX, Users } from 'lucide-vue-next'
import Button from '@/components/ui/button.vue'
import Input from '@/components/ui/input.vue'
import Select from '@/components/ui/select.vue'
@@ -149,6 +162,7 @@ defineProps<{
apiFormatFilters: FilterOption[]
modelFilters: FilterOption[]
hasActiveFilters: boolean
priorityModeLabel: string
loading: boolean
}>()
@@ -158,6 +172,7 @@ defineEmits<{
'update:filterApiFormat': [value: string]
'update:filterModel': [value: string]
'resetFilters': []
'openPriorityDialog': []
'batchProcess': []
'addProvider': []
'refresh': []
@@ -137,6 +137,36 @@ function clickButton(text: string) {
button.click()
}
const billingFieldNames = [
'billing_type',
'monthly_quota_usd',
'quota_reset_day',
'quota_last_reset_at',
'quota_expires_at',
] as const
function expectBillingConfigurationHidden() {
for (const text of [
'计费类型',
'月卡额度',
'按量付费',
'免费套餐',
'周期额度 (USD)',
'重置周期 (天)',
'周期开始时间',
'过期时间',
]) {
expect(document.body.textContent).not.toContain(text)
}
}
function expectBillingFieldsOmitted(payload: unknown) {
expect(payload).toEqual(expect.any(Object))
for (const field of billingFieldNames) {
expect(payload).not.toHaveProperty(field)
}
}
beforeEach(() => {
endpointMocks.createProvider.mockReset()
endpointMocks.createProvider.mockResolvedValue({ id: 'provider-new', name: 'New Provider' })
@@ -226,6 +256,41 @@ describe('ProviderFormDialog transfer limits', () => {
})
})
describe('ProviderFormDialog billing configuration', () => {
it('hides billing configuration and omits billing fields when creating', async () => {
mountDialog(null)
await settle()
expectBillingConfigurationHidden()
await setInput('#name', 'New Provider')
clickButton('创建')
await settle()
expect(endpointMocks.createProvider).toHaveBeenCalledTimes(1)
expectBillingFieldsOmitted(endpointMocks.createProvider.mock.calls[0]?.[0])
})
it('hides existing monthly quota configuration and preserves it when editing', async () => {
mountDialog(makeProvider({
billing_type: 'monthly_quota',
monthly_quota_usd: 200,
quota_reset_day: 30,
quota_last_reset_at: '2026-08-01T00:00:00Z',
quota_expires_at: '2026-09-01T00:00:00Z',
}))
await settle()
expectBillingConfigurationHidden()
clickButton('保存')
await settle()
expect(endpointMocks.updateProvider).toHaveBeenCalledTimes(1)
expectBillingFieldsOmitted(endpointMocks.updateProvider.mock.calls[0]?.[1])
})
})
describe('ProviderFormDialog provider types', () => {
it('creates an experimental Claude Code provider from the add dialog', async () => {
mountDialog(null)
@@ -9,6 +9,7 @@ export { default as EndpointFormDialog } from './EndpointFormDialog.vue'
export { default as KeyFormDialog } from './KeyFormDialog.vue'
export { default as KeyAllowedModelsDialog } from './KeyAllowedModelsDialog.vue'
export { default as KeyAllowedModelsEditDialog } from './KeyAllowedModelsEditDialog.vue'
export { default as PriorityManagementDialog } from './PriorityManagementDialog.vue'
export { default as ProviderModelFormDialog } from './ProviderModelFormDialog.vue'
export { default as ProviderDetailDrawer } from './ProviderDetailDrawer.vue'
export { default as EndpointHealthTimeline } from './EndpointHealthTimeline.vue'
@@ -2,17 +2,27 @@ import { describe, expect, it } from 'vitest'
import {
DEFAULT_ROUTING_POLICY_MODEL,
allowedModelsMirrorPerModelPolicies,
clearAllowedModels,
copyPerModelRoutingConfig,
createEmptyModelPolicy,
createEmptyRoutingGroupConfig,
formatAllowedModelsInput,
getDefaultModelPolicy,
getModelScheduling,
modelSchedulingRuleId,
normalizeRoutingGroupConfig,
normalizeStickyKeyAttempts,
parseAllowedModelsInput,
removePerModelRoutingConfig,
resolveModelKeyPriorityOverride,
routingModelScopeLabel,
savePerModelRoutingConfig,
setDefaultPoolPriorityOverrides,
setDefaultProviderPriorityOverrides,
setModelKeyPriorityOverridesForFormat,
setRoutingSortingScope,
updateAllowedModelsFromInput,
upsertModelSchedulingRule,
upsertModelPolicy,
} from '../utils/routingPolicy'
@@ -20,18 +30,13 @@ import { sortCandidateTraces, summarizeRoutingTrace, type RoutingDecisionTrace }
describe('routingPolicy', () => {
it('normalizes partial configs with stable defaults', () => {
const config = normalizeRoutingGroupConfig({})
const config = normalizeRoutingGroupConfig({
allowed_models: ['gpt-5'],
})
expect(config.default_policy.priority_mode).toBe('provider')
expect(config.default_policy.scheduling_mode).toBe('cache_affinity')
})
it('drops the legacy group model allowlist while normalizing config', () => {
const config = normalizeRoutingGroupConfig({
allowed_models: ['legacy-model'],
} as unknown as Parameters<typeof normalizeRoutingGroupConfig>[0])
expect(config).not.toHaveProperty('allowed_models')
expect(config.allowed_models).toEqual(['gpt-5'])
})
it('upserts model policies by model name', () => {
@@ -150,6 +155,115 @@ describe('routingPolicy', () => {
scheduling_mode: 'fixed_order',
})
})
it('updates the model allowlist only through explicit scope controls', () => {
const config = normalizeRoutingGroupConfig({
allowed_models: ['legacy-model'],
})
expect(parseAllowedModelsInput(' gpt-5\nclaude-*\nlegacy-model\ngpt-5 ')).toEqual([
'gpt-5',
'claude-*',
'legacy-model',
])
const restricted = updateAllowedModelsFromInput(
config,
'gpt-5\nclaude-*\nlegacy-model\ngpt-5',
)
expect(restricted.allowed_models).toEqual(['gpt-5', 'claude-*', 'legacy-model'])
expect(formatAllowedModelsInput(restricted.allowed_models)).toBe('gpt-5\nclaude-*\nlegacy-model')
expect(routingModelScopeLabel(restricted)).toBe('3 个模型')
const unrestricted = clearAllowedModels(restricted)
expect(unrestricted.allowed_models).toEqual([])
expect(routingModelScopeLabel(unrestricted)).toBe('全部模型')
})
it('round-trips selectors containing commas and labels wildcard scope as unrestricted', () => {
const selectors = ['vendor,model', 'gpt-*']
expect(parseAllowedModelsInput(formatAllowedModelsInput(selectors))).toEqual(selectors)
const wildcard = normalizeRoutingGroupConfig({ allowed_models: ['gpt-*', '*'] })
expect(routingModelScopeLabel(wildcard)).toBe('全部模型')
})
it('preserves historical empty selectors until unrestricted scope is explicit', () => {
const legacy = normalizeRoutingGroupConfig({ allowed_models: ['', ' '] })
expect(updateAllowedModelsFromInput(legacy, ' \n')).toMatchObject({
allowed_models: ['', ' '],
})
expect(clearAllowedModels(legacy).allowed_models).toEqual([])
})
it('preserves an explicit model allowlist across per-model editing actions', () => {
const allowlist = ['gpt-*', 'legacy-model']
let config = normalizeRoutingGroupConfig({
allowed_models: allowlist,
model_policies: [{
...createEmptyModelPolicy('special-model'),
allowed_providers: ['provider-special'],
}],
})
config = upsertModelSchedulingRule(config, 'special-model', {
priority_mode: 'global_key',
scheduling_mode: 'fixed_order',
})
const perModel = setRoutingSortingScope(config, 'per_model')
expect(perModel.allowed_models).toEqual(allowlist)
expect(getModelScheduling(perModel, 'special-model')).toMatchObject({
priority_mode: 'global_key',
scheduling_mode: 'fixed_order',
})
const saved = savePerModelRoutingConfig(perModel, 'new-special-model')
expect(saved.allowed_models).toEqual(allowlist)
expect(saved.model_policies.map(policy => policy.model)).toContain('new-special-model')
const copied = copyPerModelRoutingConfig(
saved,
saved,
'special-model',
'copied-special-model',
)
expect(copied.allowed_models).toEqual(allowlist)
expect(copied.model_policies.find(policy => policy.model === 'copied-special-model'))
.toMatchObject({ allowed_providers: ['provider-special'] })
expect(getModelScheduling(copied, 'copied-special-model')).toMatchObject({
priority_mode: 'global_key',
scheduling_mode: 'fixed_order',
})
const removed = removePerModelRoutingConfig(copied, 'special-model')
expect(removed.allowed_models).toEqual(allowlist)
expect(removed.model_policies.map(policy => policy.model)).not.toContain('special-model')
expect(removed.rules.map(rule => rule.id)).not.toContain(modelSchedulingRuleId('special-model'))
const unified = setRoutingSortingScope(removed, 'unified')
expect(unified.allowed_models).toEqual(allowlist)
expect(unified.model_policies.filter(policy => policy.model !== DEFAULT_ROUTING_POLICY_MODEL))
.toEqual([])
expect(unified.rules.some(rule => rule.id.startsWith('ui_model_scheduling:'))).toBe(false)
})
it('recognizes legacy allowlist mirrors without mutating historical values', () => {
const config = normalizeRoutingGroupConfig({
allowed_models: [' model-b ', 'model-a', 'model-a'],
model_policies: [
createEmptyModelPolicy('model-a'),
createEmptyModelPolicy('model-b'),
],
})
expect(allowedModelsMirrorPerModelPolicies(config)).toBe(true)
expect(config.allowed_models).toEqual([' model-b ', 'model-a', 'model-a'])
expect(allowedModelsMirrorPerModelPolicies({
...config,
allowed_models: ['model-*'],
})).toBe(false)
})
})
describe('routingTrace', () => {
@@ -1,5 +1,16 @@
<template>
<section class="space-y-4">
<div class="grid gap-3">
<label class="space-y-1 text-sm">
<span class="text-muted-foreground">允许模型</span>
<input
v-model="allowedModelsText"
class="h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
placeholder="gpt-5, claude-sonnet-*"
>
</label>
</div>
<RoutingModelPolicyEditor
:model-policies="config.model_policies"
@update:model-policies="updateModelPolicies"
@@ -23,6 +34,16 @@ const emit = defineEmits<{
const config = computed(() => normalizeRoutingGroupConfig(props.config))
const allowedModelsText = computed({
get: () => config.value.allowed_models.join(', '),
set: value => {
emit('update:config', {
...config.value,
allowed_models: value.split(',').map(item => item.trim()).filter(Boolean),
})
},
})
function updateModelPolicies(modelPolicies: RoutingModelPolicy[]) {
emit('update:config', {
...config.value,
@@ -10,8 +10,6 @@ export interface RoutingDefaultPolicy {
priority_mode: RoutingPriorityMode
scheduling_mode: RoutingSchedulingMode
keep_priority_on_conversion: boolean
enable_cf_heartbeat: boolean
cyber_continue_failover: boolean
/** 首个候选的总尝试次数;后续候选始终只尝试 1 次。0 或 1 表示不重试 */
sticky_key_attempts: number
}
@@ -62,6 +60,7 @@ export interface RoutingSetSchedulingAction {
}
export interface RoutingGroupConfig {
allowed_models: string[]
default_policy: RoutingDefaultPolicy
model_policies: RoutingModelPolicy[]
rules: RoutingRule[]
@@ -72,12 +71,11 @@ export const MODEL_SCHEDULING_RULE_PREFIX = 'ui_model_scheduling:'
export function createEmptyRoutingGroupConfig(): RoutingGroupConfig {
return {
allowed_models: [],
default_policy: {
priority_mode: 'provider',
scheduling_mode: 'cache_affinity',
keep_priority_on_conversion: false,
enable_cf_heartbeat: false,
cyber_continue_failover: false,
sticky_key_attempts: DEFAULT_STICKY_KEY_ATTEMPTS,
},
model_policies: [],
@@ -106,25 +104,14 @@ export function createEmptyModelPolicy(model = ''): RoutingModelPolicy {
export function normalizeRoutingGroupConfig(value: Partial<RoutingGroupConfig> | null | undefined): RoutingGroupConfig {
const base = createEmptyRoutingGroupConfig()
const rawDefaultPolicy = (value?.default_policy ?? {}) as Partial<RoutingDefaultPolicy> & {
enable_openai_image_sync_heartbeat?: boolean
enable_standard_text_sync_heartbeat?: boolean
}
const {
enable_openai_image_sync_heartbeat: legacyImageHeartbeat,
enable_standard_text_sync_heartbeat: legacyTextHeartbeat,
...defaultPolicyWithoutLegacyHeartbeat
} = rawDefaultPolicy
return {
allowed_models: Array.isArray(value?.allowed_models) ? [...value.allowed_models] : base.allowed_models,
default_policy: {
...base.default_policy,
...defaultPolicyWithoutLegacyHeartbeat,
enable_cf_heartbeat: Boolean(
rawDefaultPolicy.enable_cf_heartbeat || legacyImageHeartbeat || legacyTextHeartbeat,
),
...(value?.default_policy ?? {}),
sticky_key_attempts: normalizeStickyKeyAttempts(
rawDefaultPolicy.sticky_key_attempts ?? DEFAULT_STICKY_KEY_ATTEMPTS,
value?.default_policy?.sticky_key_attempts ?? DEFAULT_STICKY_KEY_ATTEMPTS,
),
},
model_policies: Array.isArray(value?.model_policies)
@@ -146,6 +133,74 @@ export function normalizeRoutingGroupConfig(value: Partial<RoutingGroupConfig> |
}
}
export function parseAllowedModelsInput(value: string): string[] {
const seen = new Set<string>()
return value
.split(/\r\n?|\n/u)
.map(item => item.trim())
.filter(Boolean)
.filter((model) => {
if (seen.has(model)) return false
seen.add(model)
return true
})
}
export function formatAllowedModelsInput(models: string[]): string {
return models.join('\n')
}
export function updateAllowedModelsFromInput(
config: RoutingGroupConfig,
value: string,
): RoutingGroupConfig {
const next = normalizeRoutingGroupConfig(config)
// Preserve the historical "empty selector" form until the user explicitly
// chooses the unrestricted scope. It is distinct from an empty allowlist in
// the routing core, where it matches no normal model.
const hasHistoricalEmptySelector = next.allowed_models.length > 0
&& next.allowed_models.every(model => model.trim() === '')
if (value.trim() === '' && hasHistoricalEmptySelector) {
return next
}
next.allowed_models = parseAllowedModelsInput(value)
return next
}
export function clearAllowedModels(config: RoutingGroupConfig): RoutingGroupConfig {
const next = normalizeRoutingGroupConfig(config)
next.allowed_models = []
return next
}
export function routingModelScopeLabel(config: RoutingGroupConfig): string {
const models = normalizeRoutingGroupConfig(config).allowed_models
if (models.length === 0 || models.some(model => model.trim() === '*')) {
return '全部模型'
}
return `${models.length} 个模型`
}
export function allowedModelsMirrorPerModelPolicies(config: RoutingGroupConfig): boolean {
const normalized = normalizeRoutingGroupConfig(config)
const allowedModels = normalized.allowed_models
.map(model => model.trim())
.filter(Boolean)
const perModelNames = normalized.model_policies
.map(policy => policy.model)
.map(model => model.trim())
.filter(Boolean)
.filter(model => model !== DEFAULT_ROUTING_POLICY_MODEL)
if (allowedModels.length === 0 || perModelNames.length === 0) return false
if (allowedModels.some(model => model.includes('*'))) return false
const allowedSet = new Set(allowedModels)
const perModelSet = new Set(perModelNames)
return allowedSet.size === perModelSet.size
&& [...allowedSet].every(model => perModelSet.has(model))
}
export function upsertModelPolicy(config: RoutingGroupConfig, policy: RoutingModelPolicy): RoutingGroupConfig {
const model = policy.model.trim()
if (!model) {
@@ -372,8 +427,6 @@ export function getModelScheduling(
priority_mode: action?.priority_mode ?? normalized.default_policy.priority_mode,
scheduling_mode: action?.scheduling_mode ?? normalized.default_policy.scheduling_mode,
keep_priority_on_conversion: normalized.default_policy.keep_priority_on_conversion,
enable_cf_heartbeat: normalized.default_policy.enable_cf_heartbeat,
cyber_continue_failover: normalized.default_policy.cyber_continue_failover,
sticky_key_attempts: action?.sticky_key_attempts ?? normalized.default_policy.sticky_key_attempts,
}
}
+1
View File
@@ -3264,6 +3264,7 @@ const legacyFallbackTokens: Array<[string, string]> = [
['策略分组', 'policy groups'],
['策略', 'policy'],
['维度', 'dimension'],
['模型范围', 'model scope'],
['默认策略', 'default policy'],
['更新时间', 'updated at'],
['回溯时间', 'lookback time'],
@@ -24,12 +24,14 @@
:api-format-filters="apiFormatFilters"
:model-filters="modelFilters"
:has-active-filters="hasActiveFilters"
:priority-mode-label="priorityModeConfig.label"
:loading="loading"
@update:search-query="searchQuery = $event"
@update:filter-status="filterStatus = $event"
@update:filter-api-format="filterApiFormat = $event"
@update:filter-model="filterModel = $event"
@reset-filters="resetFilters"
@open-priority-dialog="openPriorityDialog"
@batch-process="openProviderBatchDialog"
@add-provider="openAddProviderDialog"
@refresh="loadProviders"
@@ -213,6 +215,11 @@
@changed="handleProviderBatchChanged"
/>
<PriorityManagementDialog
v-model="priorityDialogOpen"
@saved="handlePrioritySaved"
/>
<ProviderDetailDrawer
v-if="providerDrawerMounted"
:open="providerDrawerOpen"
@@ -243,7 +250,7 @@ import TableHead from '@/components/ui/table-head.vue'
import SortableTableHead from '@/components/ui/sortable-table-head.vue'
import TableFilterMenu from '@/components/ui/table-filter-menu.vue'
import Pagination from '@/components/ui/pagination.vue'
import { ProviderFormDialog, ProviderAuthDialog } from '@/features/providers/components'
import { ProviderFormDialog, PriorityManagementDialog, ProviderAuthDialog } from '@/features/providers/components'
import ProviderBatchActionDialog from '@/features/providers/components/ProviderBatchActionDialog.vue'
import ProviderTableHeader from '@/features/providers/components/ProviderTableHeader.vue'
import ProviderTableRow from '@/features/providers/components/ProviderTableRow.vue'
@@ -264,6 +271,9 @@ import {
getGlobalModels,
type ProviderWithEndpointsSummary,
} from '@/api/endpoints'
import { adminApi } from '@/api/admin'
import { listRoutingGroups } from '@/api/routing-profiles'
import { normalizeRoutingGroupConfig } from '@/features/routing/utils/routingPolicy'
import { parseApiError } from '@/utils/errorParser'
import { useI18n } from '@/i18n'
@@ -299,6 +309,8 @@ let providersRequestId = 0
const providerDialogOpen = ref(false)
const providerBatchDialogOpen = ref(false)
const providerToEdit = ref<ProviderWithEndpointsSummary | null>(null)
const priorityDialogOpen = ref(false)
const priorityMode = ref<'provider' | 'global_key'>('provider')
const providerDrawerOpen = ref(false)
const providerDrawerMounted = ref(false)
const selectedProviderId = ref<string | null>(null)
@@ -313,6 +325,7 @@ const DELETE_POLL_INTERVAL_MS = 2000
const DELETE_POLL_MAX_MS = 30 * 60 * 1000
const DELETE_POLL_MAX_FAILURES = 3
const PROVIDER_SUMMARY_CACHE_TTL_MS = 10 * 1000
const PROVIDER_PRIORITY_MODE_CACHE_TTL_MS = 30 * 1000
const PROVIDER_MODEL_FILTER_CACHE_TTL_MS = 10 * 1000
async function pollProviderDeleteTask(providerId: string, taskId: string) {
@@ -506,6 +519,13 @@ async function saveDescription(_event: Event, provider: ProviderWithEndpointsSum
}
}
// 优先级模式配置
const priorityModeConfig = computed(() => {
return {
label: legacyT(priorityMode.value === 'global_key' ? '全局 Key 优先' : '提供商优先'),
}
})
// 当前已有提供商的最大优先级
const maxProviderPriority = computed(() => {
if (providers.value.length === 0) return undefined
@@ -515,6 +535,30 @@ const maxProviderPriority = computed(() => {
return priorities.length > 0 ? Math.max(...priorities) : undefined
})
// 加载优先级模式:优先使用启用中的系统默认调度策略,旧的系统配置键仅作兜底
async function loadPriorityMode(options: { cacheTtlMs?: number } = {}) {
try {
const groups = await listRoutingGroups()
const systemDefault = groups.items.find(group => group.is_system_default && group.enabled)
if (systemDefault) {
priorityMode.value = normalizeRoutingGroupConfig(systemDefault.config_json).default_policy.priority_mode
return
}
} catch {
// 路由策略不可用时继续尝试旧配置
}
try {
const response = await adminApi.getSystemConfig('provider_priority_mode', {
cacheTtlMs: options.cacheTtlMs ?? 0,
})
if (response.value) {
priorityMode.value = response.value as 'provider' | 'global_key'
}
} catch {
priorityMode.value = 'provider'
}
}
// 加载全局模型列表(用于模型筛选下拉)
async function loadGlobalModelList(options: { cacheTtlMs?: number } = {}) {
try {
@@ -592,6 +636,11 @@ function openAddProviderDialog() {
providerDialogOpen.value = true
}
// 打开优先级管理对话框
function openPriorityDialog() {
priorityDialogOpen.value = true
}
function openProviderBatchDialog() {
providerBatchDialogOpen.value = true
}
@@ -660,6 +709,12 @@ async function handleDrawerRefresh() {
await refreshProviderSnapshot(selectedProviderId.value)
}
// 优先级保存成功回调
async function handlePrioritySaved() {
await loadProviders()
await loadPriorityMode()
}
// 处理提供商添加
function handleProviderAdded() {
void loadProviders()
@@ -736,6 +791,7 @@ function handleGlobalClick(event: MouseEvent) {
onMounted(() => {
void loadProviders({ cacheTtlMs: PROVIDER_SUMMARY_CACHE_TTL_MS })
void loadPriorityMode({ cacheTtlMs: PROVIDER_PRIORITY_MODE_CACHE_TTL_MS })
void loadGlobalModelList({ cacheTtlMs: PROVIDER_MODEL_FILTER_CACHE_TTL_MS })
void loadArchitectureSchemas()
document.addEventListener('click', handleGlobalClick, true)
File diff suppressed because it is too large Load Diff
@@ -81,6 +81,9 @@
:registration-privacy-policy-version="systemConfig.registration_privacy_policy_version"
:auto-delete-expired-keys="systemConfig.auto_delete_expired_keys"
:enable-format-conversion="systemConfig.enable_format_conversion"
:enable-openai-image-sync-heartbeat="systemConfig.enable_openai_image_sync_heartbeat"
:enable-standard-text-sync-heartbeat="systemConfig.enable_standard_text_sync_heartbeat"
:cyber-continue-failover="systemConfig.cyber_continue_failover"
:loading="systemConfigLoading || basicConfigLoading"
:has-changes="hasBasicConfigChanges"
@save="saveBasicConfig"
@@ -104,6 +107,9 @@
@update:registration-privacy-policy-version="systemConfig.registration_privacy_policy_version = $event"
@update:auto-delete-expired-keys="systemConfig.auto_delete_expired_keys = $event"
@update:enable-format-conversion="systemConfig.enable_format_conversion = $event"
@update:enable-openai-image-sync-heartbeat="systemConfig.enable_openai_image_sync_heartbeat = $event"
@update:enable-standard-text-sync-heartbeat="systemConfig.enable_standard_text_sync_heartbeat = $event"
@update:cyber-continue-failover="systemConfig.cyber_continue_failover = $event"
/>
<!-- 请求记录配置 -->
@@ -0,0 +1,519 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createApp, defineComponent, h, nextTick, type App } from 'vue'
import RoutingProfiles from '../RoutingProfiles.vue'
import type {
RoutingGroupCreateRequest,
RoutingGroupRecord,
RoutingGroupUpdateRequest,
} from '@/api/routing-profiles'
const apiMocks = vi.hoisted(() => ({
listRoutingGroups: vi.fn(),
createRoutingGroup: vi.fn(),
updateRoutingGroup: vi.fn(),
deleteRoutingGroup: vi.fn(),
getGlobalModels: vi.fn(),
}))
const routeMocks = vi.hoisted(() => ({
route: null as null | { name: string; params: Record<string, string> },
push: vi.fn(),
replace: vi.fn(),
}))
const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }))
vi.mock('vue-router', async () => {
const { reactive } = await import('vue')
routeMocks.route = reactive({
name: 'RoutingProfileDetail',
params: { groupId: 'group-1' },
})
return {
useRoute: () => routeMocks.route,
useRouter: () => ({ push: routeMocks.push, replace: routeMocks.replace }),
}
})
vi.mock('@/api/routing-profiles', () => ({
listRoutingGroups: apiMocks.listRoutingGroups,
createRoutingGroup: apiMocks.createRoutingGroup,
updateRoutingGroup: apiMocks.updateRoutingGroup,
deleteRoutingGroup: apiMocks.deleteRoutingGroup,
}))
vi.mock('@/api/global-models', () => ({ getGlobalModels: apiMocks.getGlobalModels }))
vi.mock('@/composables/useToast', () => ({ useToast: () => toastMocks }))
vi.mock('@/utils/logger', () => ({ log: { error: vi.fn() } }))
vi.mock('@/components/layout', async () => {
const { defineComponent, h } = await import('vue')
return {
PageContainer: defineComponent({
setup(_, { slots }) {
return () => h('main', slots.default?.())
},
}),
}
})
vi.mock('@/components/ui', async () => {
const { defineComponent, h } = await import('vue')
const wrapper = (tag = 'div') => defineComponent({
inheritAttrs: false,
props: { class: String },
setup(props, { attrs, slots }) {
return () => h(tag, { ...attrs, class: props.class }, [
slots.header?.(),
slots.default?.(),
])
},
})
const Input = defineComponent({
inheritAttrs: false,
props: {
modelValue: { type: [String, Number], default: '' },
class: String,
disabled: Boolean,
},
emits: ['update:modelValue'],
setup(props, { attrs, emit }) {
return () => h('input', {
...attrs,
class: props.class,
disabled: props.disabled,
value: props.modelValue,
onInput: (event: Event) => emit(
'update:modelValue',
(event.target as HTMLInputElement).value,
),
})
},
})
const Textarea = defineComponent({
inheritAttrs: false,
props: {
modelValue: { type: String, default: '' },
class: String,
disabled: Boolean,
},
emits: ['update:modelValue'],
setup(props, { attrs, emit }) {
return () => h('textarea', {
...attrs,
class: props.class,
disabled: props.disabled,
value: props.modelValue,
onInput: (event: Event) => emit(
'update:modelValue',
(event.target as HTMLTextAreaElement).value,
),
})
},
})
const Button = defineComponent({
inheritAttrs: false,
props: {
class: String,
disabled: Boolean,
type: { type: String, default: 'button' },
},
setup(props, { attrs, slots }) {
return () => h('button', {
...attrs,
class: props.class,
disabled: props.disabled,
type: props.type,
}, slots.default?.())
},
})
const Switch = defineComponent({
inheritAttrs: false,
props: {
modelValue: { type: Boolean, default: false },
disabled: Boolean,
},
emits: ['update:modelValue'],
setup(props, { attrs, emit }) {
return () => h('button', {
...attrs,
type: 'button',
role: 'switch',
'aria-checked': props.modelValue,
disabled: props.disabled,
onClick: () => emit('update:modelValue', !props.modelValue),
})
},
})
return {
Badge: wrapper(),
Button,
Card: wrapper('section'),
Input,
Switch,
Table: wrapper('table'),
TableBody: wrapper('tbody'),
TableCard: wrapper(),
TableCell: wrapper('td'),
TableHead: wrapper('th'),
TableHeader: wrapper('thead'),
TableRow: wrapper('tr'),
Textarea,
}
})
vi.mock('@/components/ui/dropdown-menu', async () => {
const { defineComponent, h } = await import('vue')
const wrapper = defineComponent({
setup(_, { slots }) {
return () => h('div', slots.default?.())
},
})
return {
DropdownMenu: wrapper,
DropdownMenuContent: wrapper,
DropdownMenuItem: wrapper,
DropdownMenuTrigger: wrapper,
}
})
vi.mock('@/components/common', async () => {
const { defineComponent, h } = await import('vue')
return { AlertDialog: defineComponent({ setup: () => () => h('div') }) }
})
vi.mock('@/features/routing/components', async () => {
const { defineComponent, h } = await import('vue')
return {
RoutingPriorityPolicyEditor: defineComponent({
setup: () => () => h('div', { 'data-testid': 'routing-policy-editor' }),
}),
}
})
let app: App | undefined
let root: HTMLElement | undefined
function routingGroup(
allowedModels: string[] = [],
overrides: Partial<RoutingGroupRecord> = {},
): RoutingGroupRecord {
return {
id: 'group-1',
name: 'Default routing',
description: null,
enabled: true,
is_system_default: true,
config_json: {
allowed_models: allowedModels,
default_policy: {
priority_mode: 'provider',
scheduling_mode: 'cache_affinity',
keep_priority_on_conversion: false,
sticky_key_attempts: 2,
},
model_policies: [],
rules: [],
},
version: 1,
created_at: 1,
updated_at: 1,
published_at: null,
...overrides,
}
}
async function flushPromises(iterations = 5): Promise<void> {
for (let index = 0; index < iterations; index += 1) {
await Promise.resolve()
}
await nextTick()
}
async function mountPage(
input: RoutingGroupRecord | RoutingGroupRecord[] = routingGroup(),
): Promise<void> {
const groups = Array.isArray(input) ? input : [input]
apiMocks.listRoutingGroups.mockResolvedValue({ items: groups, total: groups.length })
apiMocks.getGlobalModels.mockResolvedValue({ models: [] })
apiMocks.updateRoutingGroup.mockImplementation(
async (groupId: string, payload: RoutingGroupUpdateRequest) => {
const group = groups.find(item => item.id === groupId)
if (!group) throw new Error(`unknown routing group: ${groupId}`)
return {
...group,
...payload,
config_json: payload.config_json ?? group.config_json,
updated_at: 2,
}
},
)
root = document.createElement('div')
document.body.appendChild(root)
app = createApp(defineComponent({
setup: () => () => h(RoutingProfiles),
}))
app.mount(root)
await flushPromises()
}
function setTextareaValue(textarea: HTMLTextAreaElement, value: string): void {
textarea.value = value
textarea.dispatchEvent(new Event('input', { bubbles: true }))
}
beforeEach(() => {
vi.clearAllMocks()
if (!routeMocks.route) throw new Error('route mock was not initialized')
routeMocks.route.name = 'RoutingProfileDetail'
routeMocks.route.params = { groupId: 'group-1' }
})
afterEach(() => {
app?.unmount()
root?.remove()
app = undefined
root = undefined
})
describe('RoutingProfiles model allowlist', () => {
it('saves one selector per line without an extra apply step', async () => {
await mountPage()
const textarea = root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement
expect(textarea).toBeInstanceOf(HTMLTextAreaElement)
setTextareaValue(textarea, 'gpt-5\nclaude-*\nvendor,model')
await nextTick()
const saveButton = root?.querySelector(
'button[aria-label="保存"]',
) as HTMLButtonElement
expect(saveButton.disabled).toBe(false)
saveButton.click()
await flushPromises()
expect(apiMocks.updateRoutingGroup).toHaveBeenCalledWith(
'group-1',
expect.objectContaining({
config_json: expect.objectContaining({
allowed_models: ['gpt-5', 'claude-*', 'vendor,model'],
}),
}),
)
})
it('locks the editor while a save is in flight', async () => {
const group = routingGroup(['model-a'])
let resolveUpdate: ((value: RoutingGroupRecord) => void) | undefined
let submittedPayload: RoutingGroupUpdateRequest | undefined
await mountPage(group)
apiMocks.updateRoutingGroup.mockImplementationOnce(
async (_groupId: string, payload: RoutingGroupUpdateRequest) => {
submittedPayload = payload
return await new Promise<RoutingGroupRecord>((resolve) => {
resolveUpdate = resolve
})
},
)
const textarea = root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement
setTextareaValue(textarea, 'model-a\nmodel-b')
await nextTick()
const saveButton = root?.querySelector(
'button[aria-label="保存"]',
) as HTMLButtonElement
saveButton.click()
await nextTick()
const editor = root?.querySelector('[aria-busy="true"]') as HTMLElement
const clearButton = root?.querySelector(
'[data-testid="clear-allowed-models"]',
) as HTMLButtonElement
expect(editor.hasAttribute('inert')).toBe(true)
expect(textarea.disabled).toBe(true)
expect(clearButton.disabled).toBe(true)
expect(saveButton.disabled).toBe(true)
setTextareaValue(textarea, 'model-c')
await nextTick()
expect(submittedPayload?.config_json?.allowed_models).toEqual(['model-a', 'model-b'])
if (!resolveUpdate || !submittedPayload) throw new Error('save request did not start')
resolveUpdate({
...group,
...submittedPayload,
config_json: submittedPayload.config_json ?? group.config_json,
updated_at: 2,
})
await flushPromises()
expect(root?.querySelector('[aria-busy="true"]')).toBeNull()
expect((root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement).value).toBe('model-a\nmodel-b')
expect(apiMocks.updateRoutingGroup).toHaveBeenCalledTimes(1)
})
it('keeps another group selected when an earlier save response arrives', async () => {
const firstGroup = routingGroup(['model-a'], {
id: 'group-1',
name: 'First routing',
})
const secondGroup = routingGroup(['model-b'], {
id: 'group-2',
name: 'Second routing',
is_system_default: false,
})
let resolveUpdate: ((value: RoutingGroupRecord) => void) | undefined
let submittedPayload: RoutingGroupUpdateRequest | undefined
await mountPage([firstGroup, secondGroup])
apiMocks.updateRoutingGroup.mockImplementationOnce(
async (_groupId: string, payload: RoutingGroupUpdateRequest) => {
submittedPayload = payload
return await new Promise<RoutingGroupRecord>((resolve) => {
resolveUpdate = resolve
})
},
)
const textarea = root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement
setTextareaValue(textarea, 'model-a\nmodel-a-new')
await nextTick()
;(root?.querySelector('button[aria-label="保存"]') as HTMLButtonElement).click()
await nextTick()
if (!routeMocks.route) throw new Error('route mock was not initialized')
routeMocks.route.params = { groupId: 'group-2' }
await nextTick()
expect((root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement).value).toBe('model-b')
if (!resolveUpdate || !submittedPayload) throw new Error('save request did not start')
resolveUpdate({
...firstGroup,
...submittedPayload,
config_json: submittedPayload.config_json ?? firstGroup.config_json,
updated_at: 2,
})
await flushPromises()
expect(root?.querySelector('h2')?.textContent).toContain('Second routing')
expect((root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement).value).toBe('model-b')
expect(routeMocks.replace).not.toHaveBeenCalled()
})
it('refreshes a clean draft when returning to the saved group before the response arrives', async () => {
const group = routingGroup(['model-a'])
let resolveUpdate: ((value: RoutingGroupRecord) => void) | undefined
let submittedPayload: RoutingGroupUpdateRequest | undefined
await mountPage(group)
apiMocks.updateRoutingGroup.mockImplementationOnce(
async (_groupId: string, payload: RoutingGroupUpdateRequest) => {
submittedPayload = payload
return await new Promise<RoutingGroupRecord>((resolve) => {
resolveUpdate = resolve
})
},
)
const textarea = root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement
setTextareaValue(textarea, 'model-a\nmodel-b')
await nextTick()
;(root?.querySelector('button[aria-label="保存"]') as HTMLButtonElement).click()
await nextTick()
if (!routeMocks.route) throw new Error('route mock was not initialized')
routeMocks.route.name = 'RoutingProfiles'
routeMocks.route.params = {}
await nextTick()
routeMocks.route.name = 'RoutingProfileDetail'
routeMocks.route.params = { groupId: 'group-1' }
await nextTick()
expect((root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement).value).toBe('model-a')
if (!resolveUpdate || !submittedPayload) throw new Error('save request did not start')
resolveUpdate({
...group,
...submittedPayload,
config_json: submittedPayload.config_json ?? group.config_json,
updated_at: 2,
})
await flushPromises()
expect((root?.querySelector(
'[data-testid="allowed-models-input"]',
) as HTMLTextAreaElement).value).toBe('model-a\nmodel-b')
expect((root?.querySelector(
'button[aria-label="保存"]',
) as HTMLButtonElement).disabled).toBe(true)
})
it('does not attach an old create response to a recreated draft', async () => {
if (!routeMocks.route) throw new Error('route mock was not initialized')
routeMocks.route.name = 'RoutingProfileCreate'
routeMocks.route.params = {}
let resolveCreate: ((value: RoutingGroupRecord) => void) | undefined
let submittedPayload: RoutingGroupCreateRequest | undefined
await mountPage([])
apiMocks.createRoutingGroup.mockImplementationOnce(
async (payload: RoutingGroupCreateRequest) => {
submittedPayload = payload
return await new Promise<RoutingGroupRecord>((resolve) => {
resolveCreate = resolve
})
},
)
;(root?.querySelector('button[aria-label="保存"]') as HTMLButtonElement).click()
await nextTick()
routeMocks.route.name = 'RoutingProfiles'
await nextTick()
routeMocks.route.name = 'RoutingProfileCreate'
await nextTick()
expect(root?.querySelector('h2')?.textContent).toContain('新建调度策略')
if (!resolveCreate || !submittedPayload) throw new Error('create request did not start')
const config = submittedPayload.config_json
resolveCreate({
...routingGroup(config?.allowed_models ?? [], {
id: 'created-group',
name: submittedPayload.name,
description: submittedPayload.description,
enabled: submittedPayload.enabled ?? false,
is_system_default: submittedPayload.is_system_default ?? false,
}),
config_json: config ?? routingGroup().config_json,
})
await flushPromises()
expect(root?.querySelector('h2')?.textContent).toContain('新建调度策略')
expect(routeMocks.replace).not.toHaveBeenCalled()
expect(apiMocks.createRoutingGroup).toHaveBeenCalledTimes(1)
})
})
@@ -151,6 +151,69 @@
</div>
</div>
<div class="flex items-center h-full">
<div class="flex items-center space-x-2">
<Checkbox
id="enable-openai-image-sync-heartbeat"
:checked="enableOpenaiImageSyncHeartbeat"
@update:checked="$emit('update:enableOpenaiImageSyncHeartbeat', $event)"
/>
<div>
<Label
for="enable-openai-image-sync-heartbeat"
class="cursor-pointer"
>
同步生图心跳
</Label>
<p class="text-xs text-muted-foreground">
开启后同步生图外层 HTTP 状态固定为 200,上游失败需读取响应体 error.upstream_status
</p>
</div>
</div>
</div>
<div class="flex items-center h-full">
<div class="flex items-center space-x-2">
<Checkbox
id="enable-standard-text-sync-heartbeat"
:checked="enableStandardTextSyncHeartbeat"
@update:checked="$emit('update:enableStandardTextSyncHeartbeat', $event)"
/>
<div>
<Label
for="enable-standard-text-sync-heartbeat"
class="cursor-pointer"
>
标准文本非流式心跳
</Label>
<p class="text-xs text-muted-foreground">
开启后标准文本非流式接口外层 HTTP 状态固定为 200,上游失败需读取响应体 error.upstream_status
</p>
</div>
</div>
</div>
<div class="flex items-center h-full">
<div class="flex items-center space-x-2">
<Checkbox
id="cyber-continue-failover"
:checked="cyberContinueFailover"
@update:checked="$emit('update:cyberContinueFailover', $event)"
/>
<div>
<Label
for="cyber-continue-failover"
class="cursor-pointer"
>
Cyber继续转移
</Label>
<p class="text-xs text-muted-foreground">
关闭时Cyber Policy错误直接返回客户端;开启后在响应内容开始前按普通错误继续故障转移,可能增加首字等待时间
</p>
</div>
</div>
</div>
<div class="md:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-4 border-t pt-5">
<div class="flex items-center h-full">
<div class="flex items-center space-x-2">
@@ -476,6 +539,9 @@ defineProps<{
registrationPrivacyPolicyVersion: string
autoDeleteExpiredKeys: boolean
enableFormatConversion: boolean
enableOpenaiImageSyncHeartbeat: boolean
enableStandardTextSyncHeartbeat: boolean
cyberContinueFailover: boolean
loading: boolean
hasChanges: boolean
}>()
@@ -502,5 +568,8 @@ defineEmits<{
'update:registrationPrivacyPolicyVersion': [value: string]
'update:autoDeleteExpiredKeys': [value: boolean]
'update:enableFormatConversion': [value: boolean]
'update:enableOpenaiImageSyncHeartbeat': [value: boolean]
'update:enableStandardTextSyncHeartbeat': [value: boolean]
'update:cyberContinueFailover': [value: boolean]
}>()
</script>
@@ -59,6 +59,7 @@ describe('useSystemConfig', () => {
resolveConfigs?.([
{ key: 'request_record_level', value: 'basic' },
{ key: 'proxy_node_metrics_cleanup_batch_size', value: 5000 },
{ key: 'enable_standard_text_sync_heartbeat', value: false },
])
await loadPromise
@@ -70,6 +71,50 @@ describe('useSystemConfig', () => {
expect(state.hasLogConfigChanges.value).toBe(true)
})
it('loads and saves the standard text sync heartbeat flag as a basic config item', async () => {
getAllSystemConfigsMock.mockResolvedValue([
{ key: 'enable_standard_text_sync_heartbeat', value: false },
])
updateSystemConfigMock.mockResolvedValue({})
const state = useSystemConfig()
await state.loadSystemConfig()
expect(state.systemConfig.value.enable_standard_text_sync_heartbeat).toBe(false)
state.systemConfig.value.enable_standard_text_sync_heartbeat = true
expect(state.hasBasicConfigChanges.value).toBe(true)
await state.saveBasicConfig()
expect(updateSystemConfigMock).toHaveBeenCalledWith(
'enable_standard_text_sync_heartbeat',
true,
'标准文本非流式心跳开关:开启后外层 HTTP 状态固定为 200,上游失败写入响应体'
)
expect(state.hasBasicConfigChanges.value).toBe(false)
})
it('keeps Cyber failover disabled by default and saves the enabled state', async () => {
getAllSystemConfigsMock.mockResolvedValue([])
updateSystemConfigMock.mockResolvedValue({})
const state = useSystemConfig()
await state.loadSystemConfig()
expect(state.systemConfig.value.cyber_continue_failover).toBe(false)
state.systemConfig.value.cyber_continue_failover = true
expect(state.hasBasicConfigChanges.value).toBe(true)
await state.saveBasicConfig()
expect(updateSystemConfigMock).toHaveBeenCalledWith(
'cyber_continue_failover',
true,
'Cyber继续转移开关:开启后在响应内容开始前将Cyber Policy错误按普通错误继续故障转移,可能增加首字等待时间'
)
expect(state.hasBasicConfigChanges.value).toBe(false)
})
it('uses backend-compatible defaults when config rows have not been persisted yet', async () => {
getAllSystemConfigsMock.mockResolvedValue([])
@@ -33,6 +33,12 @@ export interface SystemConfig {
auto_delete_expired_keys: boolean
// 格式转换
enable_format_conversion: boolean
// 同步生图心跳
enable_openai_image_sync_heartbeat: boolean
// 标准文本非流式心跳
enable_standard_text_sync_heartbeat: boolean
// Cyber Policy 错误继续故障转移
cyber_continue_failover: boolean
// 请求记录
request_record_level: string
sensitive_headers: string[]
@@ -83,6 +89,12 @@ const CONFIG_KEYS = [
'auto_delete_expired_keys',
// 格式转换
'enable_format_conversion',
// 同步生图心跳
'enable_openai_image_sync_heartbeat',
// 标准文本非流式心跳
'enable_standard_text_sync_heartbeat',
// Cyber Policy 错误继续故障转移
'cyber_continue_failover',
// 请求记录
'request_record_level',
'sensitive_headers',
@@ -135,6 +147,12 @@ function createDefaultConfig(): SystemConfig {
auto_delete_expired_keys: false,
// 格式转换
enable_format_conversion: false,
// 同步生图心跳
enable_openai_image_sync_heartbeat: false,
// 标准文本非流式心跳
enable_standard_text_sync_heartbeat: false,
// Cyber Policy 错误继续故障转移
cyber_continue_failover: false,
// 请求记录
request_record_level: 'full',
sensitive_headers: ['authorization', 'x-api-key', 'api-key', 'cookie', 'set-cookie'],
@@ -217,7 +235,13 @@ export function useSystemConfig() {
systemConfig.value.registration_privacy_policy_version !==
originalConfig.value.registration_privacy_policy_version ||
systemConfig.value.auto_delete_expired_keys !== originalConfig.value.auto_delete_expired_keys ||
systemConfig.value.enable_format_conversion !== originalConfig.value.enable_format_conversion
systemConfig.value.enable_format_conversion !== originalConfig.value.enable_format_conversion ||
systemConfig.value.enable_openai_image_sync_heartbeat !==
originalConfig.value.enable_openai_image_sync_heartbeat ||
systemConfig.value.enable_standard_text_sync_heartbeat !==
originalConfig.value.enable_standard_text_sync_heartbeat ||
systemConfig.value.cyber_continue_failover !==
originalConfig.value.cyber_continue_failover
)
})
@@ -466,6 +490,21 @@ export function useSystemConfig() {
value: systemConfig.value.enable_format_conversion,
description: '全局格式转换开关:开启时强制允许所有提供商的格式转换',
},
{
key: 'enable_openai_image_sync_heartbeat',
value: systemConfig.value.enable_openai_image_sync_heartbeat,
description: '同步生图心跳开关:开启后外层 HTTP 状态固定为 200,上游失败写入响应体',
},
{
key: 'enable_standard_text_sync_heartbeat',
value: systemConfig.value.enable_standard_text_sync_heartbeat,
description: '标准文本非流式心跳开关:开启后外层 HTTP 状态固定为 200,上游失败写入响应体',
},
{
key: 'cyber_continue_failover',
value: systemConfig.value.cyber_continue_failover,
description: 'Cyber继续转移开关:开启后在响应内容开始前将Cyber Policy错误按普通错误继续故障转移,可能增加首字等待时间',
},
]
const turnstileSecret = systemConfig.value.turnstile_secret_key.trim()
if (turnstileSecret) {
@@ -516,6 +555,12 @@ export function useSystemConfig() {
systemConfig.value.auto_delete_expired_keys
originalConfig.value.enable_format_conversion =
systemConfig.value.enable_format_conversion
originalConfig.value.enable_openai_image_sync_heartbeat =
systemConfig.value.enable_openai_image_sync_heartbeat
originalConfig.value.enable_standard_text_sync_heartbeat =
systemConfig.value.enable_standard_text_sync_heartbeat
originalConfig.value.cyber_continue_failover =
systemConfig.value.cyber_continue_failover
}
success('基础配置已保存')
} catch (err) {
@@ -68,14 +68,6 @@ import { BookOpen } from 'lucide-vue-next'
<div class="space-y-4 mt-4 text-[#666663] dark:text-[#a3a094] text-sm">
<ul class="list-decimal pl-5 space-y-2">
<li><strong class="text-[#262624] dark:text-[#f1ead8] font-medium">提供商类型:</strong>自定义或反代;一般自定义即可,反代请进入反代章节。</li>
<li>
<strong class="text-[#262624] dark:text-[#f1ead8] font-medium">计费类型:</strong>
<ul class="list-disc pl-5 mt-1 space-y-1">
<li>按量付费:持续使用</li>
<li>月卡额度:按周期(天)限额</li>
<li>免费套餐:不计入成本即倍率为0</li>
</ul>
</li>
<li><strong class="text-[#262624] dark:text-[#f1ead8] font-medium">最大重试次数:</strong>在缓存亲和调度模式下,首次请求失败后的重试次数。</li>
<li>
<strong class="text-[#262624] dark:text-[#f1ead8] font-medium">超时时间:</strong>
@@ -15,16 +15,12 @@
## 2. 添加提供商
1. **提供商类型**: 自定义或反代; 一般自定义即可, 反代请进入反代章节
2. **计费类型**:
- 按量付费: 持续使用
- 月卡额度: 按周期(天)限额
- 免费套餐: 不计入成本即倍率为0
3. **最大重试次数**
2. **最大重试次数**
- 在缓存亲和调度模式下, 首次请求失败后的重试次数。
4. **超时时间**
3. **超时时间**
- 流式首字超时时间: 流式请求收到首字前的超时时间
- 非流请求超时时间: 非流请求的总超时时间
5. **保持优先级**
4. **保持优先级**
- 通过格式转换的请求, 是否保持当前优先级。
![image.png](/Aether%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B/image%2010.png)
+8 -6
View File
@@ -1153,7 +1153,7 @@ AETHER_BASE_DIR=${INSTALL_ROOT}
AETHER_UPDATE_STRATEGY=self
AETHER_GATEWAY_STATIC_DIR=${INSTALL_ROOT}/current/frontend
AETHER_GATEWAY_VIDEO_TASK_TRUTH_SOURCE_MODE=rust-authoritative
AETHER_GATEWAY_DATABASE_MODE=auto
AETHER_GATEWAY_AUTO_PREPARE_DATABASE=true
AETHER_RUNTIME_BACKEND=memory
API_KEY_PREFIX=sk
@@ -1196,7 +1196,7 @@ AETHER_GATEWAY_DEPLOYMENT_TOPOLOGY=multi-node
AETHER_GATEWAY_NODE_ROLE=${role}
AETHER_GATEWAY_STATIC_DIR=${INSTALL_ROOT}/current/frontend
AETHER_GATEWAY_VIDEO_TASK_TRUTH_SOURCE_MODE=rust-authoritative
AETHER_GATEWAY_DATABASE_MODE=auto
AETHER_GATEWAY_AUTO_PREPARE_DATABASE=true
AETHER_RUNTIME_BACKEND=redis
API_KEY_PREFIX=sk
@@ -1283,7 +1283,7 @@ generate_compose_env() {
replace_or_append_env "${output}" "AETHER_UPDATE_STRATEGY" "docker"
replace_or_append_env "${output}" "AETHER_DOCKER_UPDATE_COMMAND" "./update.sh"
append_compose_log_env_defaults "${output}"
replace_or_append_env "${output}" "AETHER_GATEWAY_DATABASE_MODE" "auto"
replace_or_append_env "${output}" "AETHER_GATEWAY_AUTO_PREPARE_DATABASE" "true"
}
generate_compose_single_node_env() {
@@ -1305,7 +1305,7 @@ AETHER_UPDATE_STRATEGY=docker
AETHER_DOCKER_UPDATE_COMMAND=./update.sh
AETHER_GATEWAY_STATIC_DIR=${COMPOSE_RELEASE_FRONTEND_DIR}
AETHER_GATEWAY_VIDEO_TASK_TRUTH_SOURCE_MODE=rust-authoritative
AETHER_GATEWAY_DATABASE_MODE=auto
AETHER_GATEWAY_AUTO_PREPARE_DATABASE=true
AETHER_RUNTIME_BACKEND=memory
API_KEY_PREFIX=sk
@@ -1945,7 +1945,8 @@ EOF
cat <<EOF
Database:
schema migrations and data backfills are prepared automatically before startup
empty database: first service start auto-bootstraps to the current baseline
later schema upgrades: ${INSTALL_ROOT}/current/bin/aether-gateway --migrate
Current release:
${INSTALL_ROOT}/current
@@ -2128,7 +2129,8 @@ EOF
cat <<EOF
Database:
schema migrations and data backfills are prepared automatically before startup
empty database: first service start auto-bootstraps to the current baseline
later schema upgrades: ${INSTALL_ROOT}/current/bin/aether-gateway --migrate
Current release:
${INSTALL_ROOT}/current