mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-03 08:01:10 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48aeccd0e0 | ||
|
|
bdc618701b | ||
|
|
acd76a09dc | ||
|
|
808387442b | ||
|
|
5bc4e3e5c8 | ||
|
|
7e98130cac | ||
|
|
2821a5e3bd | ||
|
|
6a6a167d41 | ||
|
|
cffb6b35d2 | ||
|
|
17e50df06f | ||
|
|
f2d95cc3fa | ||
|
|
e4f6e1d4e3 | ||
|
|
66f650f097 |
@@ -30,6 +30,8 @@
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
|
||||
|
||||
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
|
||||
|
||||
## 交付前
|
||||
@@ -42,7 +44,7 @@
|
||||
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
|
||||
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
|
||||
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
|
||||
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
|
||||
|
||||
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
|
||||
|
||||
Generated
+1
@@ -1887,6 +1887,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"yaml-rust2 0.13.2",
|
||||
]
|
||||
|
||||
@@ -50,6 +50,8 @@ pub struct SystemUpdatePolicy {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SystemVersion {
|
||||
pub version: String,
|
||||
pub instance_id: String,
|
||||
pub restart_supported: bool,
|
||||
pub git_sha: String,
|
||||
pub build_time: String,
|
||||
pub deployment_mode: String,
|
||||
|
||||
@@ -27,6 +27,8 @@ impl SystemOperations for RecordingSystemOperations {
|
||||
}
|
||||
Ok(SystemVersion {
|
||||
version: "1.0.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: false,
|
||||
git_sha: "unknown".to_owned(),
|
||||
build_time: "unknown".to_owned(),
|
||||
deployment_mode: "source".to_owned(),
|
||||
|
||||
@@ -81,6 +81,8 @@ impl UpdateRequest {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SystemVersionView {
|
||||
version: String,
|
||||
instance_id: String,
|
||||
restart_supported: bool,
|
||||
git_sha: String,
|
||||
build_time: String,
|
||||
deployment_mode: String,
|
||||
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
|
||||
Self {
|
||||
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
|
||||
version: version.version,
|
||||
instance_id: version.instance_id,
|
||||
restart_supported: version.restart_supported,
|
||||
git_sha: version.git_sha,
|
||||
build_time: version.build_time,
|
||||
deployment_mode: version.deployment_mode,
|
||||
|
||||
@@ -11,6 +11,7 @@ use gateway_core::{
|
||||
error::ProviderErrorKind,
|
||||
policy::{ClientVersionRejection, CodexClientKind},
|
||||
};
|
||||
use gateway_protocol::http::preferred_response_request_id;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
||||
@@ -170,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
};
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
if !response.headers().contains_key("x-request-id")
|
||||
&& !response.headers().contains_key("x-oai-request-id")
|
||||
if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
|
||||
.is_none()
|
||||
&& let Some(request_id) = error.upstream_request_id()
|
||||
&& let Ok(value) = HeaderValue::from_str(request_id.as_str())
|
||||
{
|
||||
|
||||
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let response = engine_error_response(error);
|
||||
let failure_request_ids = ["x-request-id", "x-oai-request-id"]
|
||||
let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
|
||||
.into_iter()
|
||||
.flat_map(|name| {
|
||||
response
|
||||
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
|
||||
.collect::<Vec<_>>();
|
||||
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
|
||||
let mut response = apply_provider_response_headers(response, response_headers);
|
||||
response.headers_mut().remove("x-request-id");
|
||||
response.headers_mut().remove("x-oai-request-id");
|
||||
for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
|
||||
response.headers_mut().remove(name);
|
||||
}
|
||||
for (name, value) in failure_request_ids {
|
||||
response.headers_mut().append(name, value);
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
|
||||
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
|
||||
if !headers.get("x-request-id").is_some_and(usable) {
|
||||
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
|
||||
let client_id = headers
|
||||
.get("x-oai-request-id")
|
||||
.filter(|value| usable(value))
|
||||
.unwrap_or(&gateway_id)
|
||||
.clone();
|
||||
let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
|
||||
headers.get(name)?.to_str().ok()
|
||||
})
|
||||
.and_then(|value| HeaderValue::from_str(value).ok())
|
||||
.unwrap_or_else(|| gateway_id.clone());
|
||||
headers.insert("x-request-id", client_id);
|
||||
}
|
||||
headers.insert("x-gateway-request-id", gateway_id);
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
error::gateway_error_response,
|
||||
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
|
||||
router::IngressStarted,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
@@ -15,18 +16,43 @@ use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use std::net::SocketAddr;
|
||||
use std::{net::SocketAddr, time::Instant};
|
||||
|
||||
/// `POST /v1/responses`
|
||||
pub(crate) async fn responses(
|
||||
State(state): State<ApiState>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||
ingress_started: Option<Extension<IngressStarted>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
|
||||
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
|
||||
let encoding = match (encodings.next(), encodings.next()) {
|
||||
(None, _) => "identity",
|
||||
(Some(value), None) => value
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
["identity", "gzip", "deflate", "zstd"]
|
||||
.into_iter()
|
||||
.find(|known| known.eq_ignore_ascii_case(value.trim()))
|
||||
})
|
||||
.unwrap_or("other"),
|
||||
_ => "other",
|
||||
};
|
||||
tracing::info!(target: "request_trace", stage = "http.body.received",
|
||||
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
|
||||
encoded_bytes = body.len(), content_encoding = encoding,
|
||||
"HTTP request body received");
|
||||
let service = state.data_plane().clone();
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let started = Instant::now();
|
||||
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.auth.finished",
|
||||
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
|
||||
"HTTP request authentication finished");
|
||||
let client = match authentication {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
|
||||
}
|
||||
};
|
||||
let execution = service.execution();
|
||||
let prepared = match execution.prepare_execution(client).await {
|
||||
let started = Instant::now();
|
||||
let preparation = execution.prepare_execution(client).await;
|
||||
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
|
||||
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
|
||||
"HTTP execution preparation finished");
|
||||
let prepared = match preparation {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
|
||||
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
|
||||
headers: &HeaderMap,
|
||||
max_decompressed_bytes: usize,
|
||||
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, max_decompressed_bytes)?;
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?;
|
||||
Ok((decoded, Bytes::copy_from_slice(&body)))
|
||||
let started = std::time::Instant::now();
|
||||
let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decompressed",
|
||||
decompress_ms = started.elapsed().as_millis(),
|
||||
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
|
||||
accepted = decompressed.is_ok(), "HTTP request body decompressed");
|
||||
let body = decompressed?;
|
||||
let started = std::time::Instant::now();
|
||||
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
|
||||
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
|
||||
tracing::info!(target: "request_trace", stage = "http.body.decoded",
|
||||
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
|
||||
"HTTP request body decoded");
|
||||
decoded
|
||||
}
|
||||
|
||||
pub(super) fn decode_request_inner(
|
||||
|
||||
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
|
||||
use gateway_core::engine::EngineError;
|
||||
use gateway_core::error::ProviderErrorKind;
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
|
||||
use serde_json::{Map, Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> String {
|
||||
let mut headers = response_event_headers(response_headers);
|
||||
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
|
||||
.unwrap_or(request_id)
|
||||
.to_owned();
|
||||
headers
|
||||
.entry("x-request-id".to_owned())
|
||||
.or_insert_with(|| Value::String(request_id.to_owned()));
|
||||
.or_insert(Value::String(client_request_id));
|
||||
json!({
|
||||
"type": "response.metadata",
|
||||
"headers": headers,
|
||||
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
|
||||
let Ok(value) = std::str::from_utf8(header.value()) else {
|
||||
continue;
|
||||
};
|
||||
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id")
|
||||
if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
|
||||
&& (value.trim().is_empty() || http_value.to_str().is_err())
|
||||
{
|
||||
continue;
|
||||
@@ -182,8 +186,9 @@ pub(super) fn initial_engine_error_event(
|
||||
};
|
||||
if upstream.is_none() {
|
||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
headers.remove("x-request-id");
|
||||
headers.remove("x-oai-request-id");
|
||||
for name in RESPONSE_REQUEST_ID_HEADERS {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
let status = if provider
|
||||
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
|
||||
@@ -221,7 +226,7 @@ pub(super) fn initial_engine_error_event(
|
||||
}
|
||||
|
||||
fn has_request_id(headers: &Map<String, Value>) -> bool {
|
||||
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id")
|
||||
preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
|
||||
}
|
||||
|
||||
pub(super) fn error_event(
|
||||
|
||||
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
|
||||
.merge(super::provider_endpoints::router())
|
||||
}
|
||||
|
||||
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum DataPlaneNamespace {
|
||||
V1,
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::json;
|
||||
use tower_http::request_id::RequestId;
|
||||
|
||||
use crate::client_error::{AccessRejection, ProtocolErrorBody};
|
||||
use crate::data_plane::router::DataPlaneNamespace;
|
||||
use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
|
||||
|
||||
pub(crate) async fn record_ingress(
|
||||
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
|
||||
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
|
||||
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
|
||||
return next.run(request).await;
|
||||
};
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(IngressStarted(std::time::Instant::now()));
|
||||
let correlation_id = request
|
||||
.extensions()
|
||||
.get::<RequestId>()
|
||||
|
||||
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
|
||||
|
||||
use super::{AdminTestFixture, AdminTestState, unavailable_system};
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_expose_runtime_identity_and_restart_capability() {
|
||||
let fixture = crate::support::key_fixture().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
let response = app(fixture.state())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/system/version")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header("x-request-id", "req_system_version")
|
||||
.body(Body::empty())
|
||||
.expect("version request"),
|
||||
)
|
||||
.await
|
||||
.expect("version response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = crate::support::response_json(response).await;
|
||||
assert_eq!(body["data"]["instanceId"], "test-instance");
|
||||
assert_eq!(body["data"]["restartSupported"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
|
||||
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
|
||||
|
||||
@@ -256,12 +256,20 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
let mut request = chat_request(false);
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
request["messages"] = json!([
|
||||
{"role":"developer","content":"brief"},
|
||||
{"role":"system","content":null},
|
||||
{"role":"assistant","tool_calls":[]},
|
||||
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
|
||||
]);
|
||||
let response = fixture.post(request.clone()).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
||||
assert_eq!(observed.as_slice(), [request]);
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
|
||||
@@ -396,16 +396,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
);
|
||||
assert_eq!(
|
||||
projected.safe_message(),
|
||||
"The gateway account pool is busy."
|
||||
"No eligible account currently has capacity for this request."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
#[tokio::test]
|
||||
async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
let detail = ClientVisibleUpstreamError::new(
|
||||
"no account is eligible for the requested model",
|
||||
Some("no_eligible_account".to_owned()),
|
||||
Some("account_unavailable_error".to_owned()),
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
);
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
@@ -419,17 +419,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
|
||||
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
|
||||
assert_eq!(
|
||||
gateway.client_message(),
|
||||
"no account is eligible for the requested model"
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
|
||||
assert_eq!(
|
||||
gateway.client_error_type(),
|
||||
Some("account_unavailable_error")
|
||||
gateway.client_error_code(),
|
||||
Some("websocket_account_unavailable")
|
||||
);
|
||||
assert_eq!(gateway.client_error_type(), None);
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"The gateway found no eligible account for this request."
|
||||
);
|
||||
let response = engine_error_response(&error);
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
|
||||
assert_eq!(body["error"]["type"], "server_error");
|
||||
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
|
||||
assert_eq!(body["error"]["message"], gateway.client_message());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -508,6 +515,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
|
||||
|
||||
#[test]
|
||||
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Unauthorized,
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
@@ -516,11 +524,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
|
||||
let mapped = gateway_error_from_engine(&error);
|
||||
|
||||
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(
|
||||
mapped.safe_message(),
|
||||
"The upstream account cannot access the service."
|
||||
assert!(
|
||||
mapped
|
||||
.safe_message()
|
||||
.to_lowercase()
|
||||
.contains("upstream account")
|
||||
);
|
||||
messages.insert(mapped.safe_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
2,
|
||||
"authentication and permission failures must be distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -577,19 +593,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() {
|
||||
fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
|
||||
let mut messages = std::collections::HashSet::new();
|
||||
for kind in [
|
||||
ProviderErrorKind::Transport,
|
||||
ProviderErrorKind::Protocol,
|
||||
ProviderErrorKind::Unavailable,
|
||||
ProviderErrorKind::ProcessTerminated,
|
||||
] {
|
||||
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous));
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(kind, UpstreamSendState::Ambiguous)
|
||||
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
|
||||
);
|
||||
|
||||
let projected = gateway_error_from_engine(&error);
|
||||
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(projected.safe_message(), "Upstream service is unavailable.");
|
||||
assert!(!projected.client_message().contains("PRIVATE_"));
|
||||
messages.insert(projected.client_message().to_owned());
|
||||
}
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
4,
|
||||
"different failure causes must remain distinguishable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
|
||||
runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
|
||||
settings.runtime = serde_json::from_value(runtime).unwrap();
|
||||
settings.fast_mode = FastMode::Disabled;
|
||||
settings.fast_mode = Some(FastMode::Disabled);
|
||||
}),
|
||||
..Default::default()
|
||||
}));
|
||||
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
|
||||
"model-a"
|
||||
);
|
||||
assert_ne!(
|
||||
execution.client.policy().account_scope().fast_mode(),
|
||||
FastMode::Disabled
|
||||
execution
|
||||
.client
|
||||
.policy()
|
||||
.account_scope()
|
||||
.fast_mode_override(),
|
||||
Some(FastMode::Disabled)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3300,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
(&[], MODEL_REQUEST_ID),
|
||||
(&[("x-request-id", "upstream-primary")], "upstream-primary"),
|
||||
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
|
||||
(
|
||||
&[("x-openai-request-id", "upstream-openai")],
|
||||
"upstream-openai",
|
||||
),
|
||||
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
|
||||
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "upstream-primary"),
|
||||
@@ -3315,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
"upstream-alias",
|
||||
),
|
||||
(&[("x-request-id", "")], MODEL_REQUEST_ID),
|
||||
(
|
||||
&[
|
||||
("x-request-id", "é"),
|
||||
("x-oai-request-id", " "),
|
||||
("x-openai-request-id", ""),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-ms",
|
||||
),
|
||||
(
|
||||
&[
|
||||
("x-openai-request-id", "upstream-openai"),
|
||||
("x-ms-request-id", "upstream-ms"),
|
||||
],
|
||||
"upstream-openai",
|
||||
),
|
||||
];
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
@@ -3343,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["x-request-id"], *expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for (name, value) in *upstream_headers {
|
||||
if *name != "x-request-id" {
|
||||
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!to_bytes(response.into_body(), 64 * 1024)
|
||||
.await
|
||||
@@ -3359,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
let admin = crate::admin::AdminTestFixture::new().await.services;
|
||||
for provider in ["openai", "xai"] {
|
||||
for streaming in [false, true] {
|
||||
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] {
|
||||
for upstream_headers in [
|
||||
vec![],
|
||||
headers(&[("x-oai-request-id", "actual-error")]),
|
||||
headers(&[("x-openai-request-id", "actual-error")]),
|
||||
headers(&[("x-ms-request-id", "actual-error")]),
|
||||
] {
|
||||
let expected = if upstream_headers.is_empty() {
|
||||
MODEL_REQUEST_ID
|
||||
} else {
|
||||
@@ -3367,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
};
|
||||
let raw =
|
||||
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
|
||||
let error =
|
||||
let mut error =
|
||||
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
|
||||
.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(
|
||||
@@ -3377,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
)
|
||||
.with_headers(upstream_headers),
|
||||
);
|
||||
if expected == "actual-error" {
|
||||
// 最终响应头优先于错误对象中残留的旧观测 ID
|
||||
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
|
||||
}
|
||||
let session = failed_session(streaming, EngineError::Provider(error))
|
||||
.with_response_headers(headers(&[("x-request-id", "earlier-session")]));
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert_eq!(response.headers()["x-request-id"], expected);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
for name in ["x-openai-request-id", "x-ms-request-id"] {
|
||||
if let Some(value) = response.headers().get(name) {
|
||||
assert_eq!(value, "actual-error");
|
||||
}
|
||||
}
|
||||
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
|
||||
}
|
||||
|
||||
@@ -3394,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
|
||||
.with_response_headers(headers(&[
|
||||
("x-request-id", "earlier-session"),
|
||||
("x-oai-request-id", "earlier-alias"),
|
||||
("x-openai-request-id", "earlier-openai"),
|
||||
("x-ms-request-id", "earlier-ms"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||
assert_eq!(response.headers()["x-request-id"], "body-read-error");
|
||||
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
}
|
||||
}
|
||||
@@ -3414,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
|
||||
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
|
||||
("x-request-id", "opening-primary"),
|
||||
("x-oai-request-id", "opening-alias"),
|
||||
("x-openai-request-id", "opening-openai"),
|
||||
("x-ms-request-id", "opening-ms"),
|
||||
("x-codex-turn-state", "retained-turn-state"),
|
||||
]));
|
||||
let response = response(&admin, provider, session, streaming).await;
|
||||
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
|
||||
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
|
||||
assert!(response.headers().get("x-oai-request-id").is_none());
|
||||
assert!(response.headers().get("x-openai-request-id").is_none());
|
||||
assert!(response.headers().get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
response.headers()["x-codex-turn-state"],
|
||||
"retained-turn-state"
|
||||
|
||||
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
|
||||
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"]["x-oai-request-id"], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
|
||||
let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
|
||||
.with_status(502)
|
||||
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
|
||||
let error = initial_error(
|
||||
EngineError::Provider(provider),
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-codex-turn-state", b"old-turn-state"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(error["status"], 403);
|
||||
assert_eq!(error["headers"][name], "req_final");
|
||||
assert!(error["headers"].get("x-request-id").is_none());
|
||||
assert!(!error.to_string().contains("req_old_opening"));
|
||||
assert!(!error.to_string().contains("req_stale_fact"));
|
||||
assert!(!error.to_string().contains("old-turn-state"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old"),
|
||||
header("x-oai-request-id", b"req_old_alias"),
|
||||
header("x-openai-request-id", b"req_old_openai"),
|
||||
header("x-ms-request-id", b"req_old_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
],
|
||||
)
|
||||
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
|
||||
"observed-turn-state"
|
||||
);
|
||||
assert!(error["headers"].get("x-oai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-openai-request-id").is_none());
|
||||
assert!(error["headers"].get("x-ms-request-id").is_none());
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"Upstream service is unavailable."
|
||||
"Communication with the upstream service failed."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
vec![
|
||||
header("x-request-id", b"req_old_opening"),
|
||||
header("x-oai-request-id", b"req_observed"),
|
||||
header("x-openai-request-id", b"req_observed_openai"),
|
||||
header("x-ms-request-id", b"req_observed_ms"),
|
||||
header("x-codex-turn-state", b"observed-turn-state"),
|
||||
header("x-future-header", b"future-value"),
|
||||
],
|
||||
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
"headers": {
|
||||
"x-request-id": "req_old_opening",
|
||||
"x-oai-request-id": "req_observed",
|
||||
"x-openai-request-id": "req_observed_openai",
|
||||
"x-ms-request-id": "req_observed_ms",
|
||||
"x-codex-turn-state": "observed-turn-state",
|
||||
"x-future-header": "future-value",
|
||||
},
|
||||
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
|
||||
let cases: &[(&str, &[u8], Option<&str>)] = &[
|
||||
("x-oai-request-id", b"req_oai", Some("req_oai")),
|
||||
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
|
||||
("x-ms-request-id", b"req_ms", Some("req_ms")),
|
||||
("x-ms-request-id", b" \t ", None),
|
||||
("x-ms-request-id", b"\xc3\xa9", None),
|
||||
];
|
||||
for (name, value, expected) in cases {
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
|
||||
..AtomicFailureTrace::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(
|
||||
Arc::clone(&trace),
|
||||
vec![header("x-request-id", b"\xff"), header(name, value)],
|
||||
)
|
||||
.await;
|
||||
send_request(&mut socket).await;
|
||||
let metadata = next_event(&mut socket).await;
|
||||
assert_eq!(metadata["type"], "response.metadata");
|
||||
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(
|
||||
metadata["headers"]["x-request-id"],
|
||||
expected.unwrap_or(&model_id)
|
||||
);
|
||||
assert_eq!(
|
||||
metadata["headers"][name.to_ascii_lowercase()].as_str(),
|
||||
*expected
|
||||
);
|
||||
let error = next_event(&mut socket).await;
|
||||
assert_eq!(error["type"], "error");
|
||||
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
|
||||
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
|
||||
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
@@ -746,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
|
||||
let provider = ProviderError::new(
|
||||
async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
|
||||
let exhausted = ProviderError::new(
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
);
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], 429);
|
||||
assert_eq!(error["error"]["type"], "usage_limit_reached");
|
||||
assert_eq!(error["error"]["code"], "usage_limit_reached");
|
||||
let incompatible = ProviderError::new(
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"This request requires an upstream WebSocket.",
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
));
|
||||
for (provider, status, kind, code) in [
|
||||
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
|
||||
(
|
||||
incompatible,
|
||||
503,
|
||||
"server_error",
|
||||
"websocket_account_unavailable",
|
||||
),
|
||||
] {
|
||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||
assert_eq!(error["status"], status);
|
||||
assert_eq!(error["error"]["type"], kind);
|
||||
assert_eq!(error["error"]["code"], code);
|
||||
if status == 503 {
|
||||
assert_eq!(
|
||||
error["error"]["message"],
|
||||
"This request requires an upstream WebSocket."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
|
||||
|
||||
#[derive(Default)]
|
||||
struct AtomicFailureTrace {
|
||||
prepared_request_id: Mutex<Option<String>>,
|
||||
starts: AtomicUsize,
|
||||
next_calls: AtomicUsize,
|
||||
committed: AtomicBool,
|
||||
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
|
||||
impl ExecutionService for AtomicFailureExecution {
|
||||
fn middleware_plan(
|
||||
&self,
|
||||
_: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
prepared: &gateway_core::engine::execution::PreparedRootExecution,
|
||||
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
|
||||
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
|
||||
self.trace.middleware.clone()
|
||||
}
|
||||
|
||||
|
||||
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
|
||||
use std::io::Write as _;
|
||||
use tracing::instrument::WithSubscriber as _;
|
||||
|
||||
let recorder = Recorder {
|
||||
dump_enabled: false,
|
||||
events: Arc::default(),
|
||||
};
|
||||
let events = recorder.events.clone();
|
||||
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
|
||||
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder.write_all(decoded.as_bytes()).unwrap();
|
||||
let encoded = encoder.finish().unwrap();
|
||||
let encoded_len = encoded.len();
|
||||
assert!(encoded_len < decoded.len());
|
||||
async {
|
||||
let (router, _) = fixture().await;
|
||||
let body = Body::from_stream(futures::stream::once(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
|
||||
Ok::<_, std::io::Error>(encoded)
|
||||
}));
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::post("/v1/responses")
|
||||
.header("authorization", "Bearer unused-client-route-key")
|
||||
.header("content-encoding", "gzip")
|
||||
.body(body)
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
.with_subscriber(recorder)
|
||||
.await;
|
||||
let events = events.lock().unwrap();
|
||||
let phases = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event.get("stage").is_some_and(|stage| {
|
||||
stage.starts_with("http.body.") || stage == "http.auth.finished"
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
phases
|
||||
.iter()
|
||||
.map(|event| event["stage"].as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"http.body.received",
|
||||
"http.auth.finished",
|
||||
"http.body.decompressed",
|
||||
"http.body.decoded",
|
||||
]
|
||||
);
|
||||
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
|
||||
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
|
||||
assert_eq!(phases[0]["content_encoding"], "gzip");
|
||||
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
|
||||
assert_eq!(phases[2]["accepted"], "true");
|
||||
assert_eq!(phases[3]["accepted"], "false");
|
||||
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
|
||||
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -91,6 +91,8 @@ impl SystemOperations for VersionSystem {
|
||||
async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
|
||||
Ok(SystemVersion {
|
||||
version: "3.7.0".to_owned(),
|
||||
instance_id: "test-instance".to_owned(),
|
||||
restart_supported: true,
|
||||
git_sha: "internal-revision".to_owned(),
|
||||
build_time: "internal-build-time".to_owned(),
|
||||
deployment_mode: "binary".to_owned(),
|
||||
|
||||
@@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory {
|
||||
providers_with_accounts: BTreeSet<ProviderKind>,
|
||||
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
|
||||
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
|
||||
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
|
||||
}
|
||||
|
||||
impl RuntimeAccountDirectory {
|
||||
@@ -129,6 +130,7 @@ impl RuntimeAccountDirectory {
|
||||
providers_with_accounts,
|
||||
providers_by_group,
|
||||
group_model_access: BTreeMap::new(),
|
||||
group_fast_modes: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +143,12 @@ impl RuntimeAccountDirectory {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
|
||||
self.group_fast_modes = policies;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn accounts_in_group(
|
||||
&self,
|
||||
group: &AccountGroupId,
|
||||
@@ -288,7 +296,7 @@ impl ClientRoutingScope {
|
||||
pub struct FrozenAccountScope {
|
||||
allow_image_generation: bool,
|
||||
allow_subagents: bool,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
|
||||
directory: Arc<RuntimeAccountDirectory>,
|
||||
client_scope: ClientRoutingScope,
|
||||
@@ -355,16 +363,34 @@ impl FrozenAccountScope {
|
||||
self
|
||||
}
|
||||
|
||||
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关
|
||||
/// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
|
||||
self.fast_mode_override = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.fast_mode
|
||||
pub const fn fast_mode_override(&self) -> Option<FastMode> {
|
||||
self.fast_mode_override
|
||||
}
|
||||
|
||||
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
|
||||
#[must_use]
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account_id: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
if let Some(mode) = self.fast_mode_override {
|
||||
return mode;
|
||||
}
|
||||
let Some(account) = self.directory.account(account_id) else {
|
||||
return FastMode::Default;
|
||||
};
|
||||
self.matching_groups(account, |access| access.allows(upstream_model))
|
||||
.filter_map(|id| self.directory.group_fast_modes.get(id))
|
||||
.fold(FastMode::Default, |mode, other| mode.merge(*other))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -376,7 +402,7 @@ impl FrozenAccountScope {
|
||||
Self {
|
||||
allow_image_generation: true,
|
||||
allow_subagents: true,
|
||||
fast_mode: FastMode::Default,
|
||||
fast_mode_override: None,
|
||||
request_profiles: BTreeMap::new(),
|
||||
directory,
|
||||
client_scope,
|
||||
@@ -460,18 +486,31 @@ impl FrozenAccountScope {
|
||||
}
|
||||
match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => true,
|
||||
ClientRoutingScope::Restricted { .. } => {
|
||||
self.matching_groups(account, accepts).next().is_some()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn matching_groups<'a>(
|
||||
&'a self,
|
||||
account: &'a RuntimeAccount,
|
||||
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
|
||||
) -> impl Iterator<Item = &'a AccountGroupId> {
|
||||
let enabled = match &self.client_scope {
|
||||
ClientRoutingScope::AllAccounts => None,
|
||||
ClientRoutingScope::Restricted {
|
||||
enabled_group_ids, ..
|
||||
} => account
|
||||
.group_ids()
|
||||
.intersection(enabled_group_ids)
|
||||
.any(|id| {
|
||||
self.directory
|
||||
.group_model_access
|
||||
.get(id)
|
||||
.is_none_or(&accepts)
|
||||
}),
|
||||
}
|
||||
} => Some(enabled_group_ids),
|
||||
};
|
||||
account.group_ids().iter().filter(move |id| {
|
||||
enabled.is_some_and(|groups| groups.contains(*id))
|
||||
&& self
|
||||
.directory
|
||||
.group_model_access
|
||||
.get(*id)
|
||||
.is_none_or(&accepts)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1200,7 +1200,6 @@ where
|
||||
.with_lease_metadata(Arc::clone(&self.lease_metadata))
|
||||
.with_response_control(self.response_control.clone())
|
||||
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
|
||||
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
|
||||
"Mapped model unavailable for this API key. Check the model mapping."
|
||||
},
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProvider { .. }
|
||||
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
|
||||
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"The gateway has no eligible provider for this request.",
|
||||
"The gateway cannot select a provider for this model and the requested capabilities.",
|
||||
),
|
||||
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"No eligible provider is available for the requested API endpoint.",
|
||||
),
|
||||
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
|
||||
),
|
||||
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
|
||||
GatewayErrorKind::Unsupported,
|
||||
|
||||
@@ -330,7 +330,6 @@ pub struct RequestAttemptContext {
|
||||
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
@@ -424,12 +423,6 @@ impl RequestAttemptContext {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
|
||||
self.fast_mode = fast_mode;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_privacy(
|
||||
mut self,
|
||||
@@ -478,7 +471,6 @@ impl RequestAttemptContext {
|
||||
request_profile: None,
|
||||
prompt_rewrite_rules: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_websocket_pool: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
@@ -743,8 +735,14 @@ impl AttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fast_mode(&self) -> FastMode {
|
||||
self.request.fast_mode
|
||||
pub fn fast_mode_for_account(
|
||||
&self,
|
||||
account: &ProviderAccountId,
|
||||
upstream_model: &str,
|
||||
) -> FastMode {
|
||||
self.account_scope().map_or(FastMode::Default, |scope| {
|
||||
scope.fast_mode_for_account(account, upstream_model)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1436,14 +1436,14 @@ impl GatewayError {
|
||||
pub(crate) const fn concurrency_queue_full() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueFull,
|
||||
"The gateway request queue is full.",
|
||||
"The gateway concurrency queue is full.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const fn concurrency_queue_timeout() -> Self {
|
||||
Self::new(
|
||||
GatewayErrorKind::ConcurrencyQueueTimeout,
|
||||
"The request timed out in the gateway queue.",
|
||||
"Timed out waiting for available concurrency in the gateway.",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1516,20 +1516,25 @@ impl GatewayError {
|
||||
GatewayErrorKind::Unsupported,
|
||||
"Requested capability is unsupported.",
|
||||
),
|
||||
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new(
|
||||
ProviderErrorKind::Unauthorized => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account cannot access the service.",
|
||||
"Upstream account authentication failed.",
|
||||
),
|
||||
ProviderErrorKind::PermissionDenied => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream account does not have permission for this request.",
|
||||
),
|
||||
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|
||||
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
|
||||
Self::from,
|
||||
),
|
||||
ProviderErrorKind::RateLimited => {
|
||||
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
|
||||
}
|
||||
ProviderErrorKind::RateLimited => Self::new(
|
||||
GatewayErrorKind::RateLimited,
|
||||
"Upstream request rate limit reached.",
|
||||
),
|
||||
ProviderErrorKind::QuotaExhausted => Self::new(
|
||||
GatewayErrorKind::QuotaExhausted,
|
||||
"Account quota is exhausted.",
|
||||
"Upstream account quota is exhausted.",
|
||||
),
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
|
||||
GatewayErrorKind::AccountPoolQuotaExhausted,
|
||||
@@ -1539,7 +1544,7 @@ impl GatewayError {
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
|
||||
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::AccountCapacityUnavailable,
|
||||
"The gateway account pool is busy.",
|
||||
"No eligible account currently has capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::NoEligibleAccount => Self::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
@@ -1559,11 +1564,23 @@ impl GatewayError {
|
||||
ProviderErrorKind::Cancelled => {
|
||||
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
|
||||
}
|
||||
ProviderErrorKind::Transport
|
||||
| ProviderErrorKind::Protocol
|
||||
| ProviderErrorKind::Unavailable
|
||||
| ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
| ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
ProviderErrorKind::Transport => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Communication with the upstream service failed.",
|
||||
),
|
||||
ProviderErrorKind::Protocol => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream protocol handling failed.",
|
||||
),
|
||||
ProviderErrorKind::ProcessTerminated => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway stopped before the request completed.",
|
||||
),
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The upstream service has no capacity for this request.",
|
||||
),
|
||||
ProviderErrorKind::Unavailable => Self::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"Upstream service is unavailable.",
|
||||
),
|
||||
|
||||
@@ -158,7 +158,7 @@ impl RateLimits {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientSettings {
|
||||
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
pub fast_mode: FastMode,
|
||||
pub fast_mode_override: Option<FastMode>,
|
||||
pub limits: RateLimits,
|
||||
}
|
||||
|
||||
@@ -185,18 +185,18 @@ impl ClientPolicy {
|
||||
pub(crate) fn with_settings(
|
||||
mut self,
|
||||
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
fast_mode_override: Option<FastMode>,
|
||||
limits: RateLimits,
|
||||
) -> Self {
|
||||
if self.account_scope.request_profiles() != profiles
|
||||
|| self.account_scope.fast_mode() != fast_mode
|
||||
|| self.account_scope.fast_mode_override() != fast_mode_override
|
||||
{
|
||||
self.account_scope = Arc::new(
|
||||
self.account_scope
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_request_profiles(profiles.clone())
|
||||
.with_fast_mode(fast_mode),
|
||||
.with_fast_mode_override(fast_mode_override),
|
||||
);
|
||||
}
|
||||
self.limits = limits;
|
||||
@@ -217,7 +217,7 @@ impl ClientPolicy {
|
||||
name_snapshot: None,
|
||||
defaults: Arc::new(ClientSettings {
|
||||
request_profiles: account_scope.request_profiles().clone(),
|
||||
fast_mode: account_scope.fast_mode(),
|
||||
fast_mode_override: account_scope.fast_mode_override(),
|
||||
limits,
|
||||
}),
|
||||
key_id,
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::fmt;
|
||||
use std::num::{NonZeroU32, NonZeroU64};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::account::{AccountSelectionPolicy, FastMode};
|
||||
use crate::account::AccountSelectionPolicy;
|
||||
use crate::operation::{CapabilityRequirements, Feature, OperationKind};
|
||||
use crate::validation::{IdentifierError, RoutingError, validate_text};
|
||||
|
||||
@@ -767,11 +767,6 @@ impl RoutingPlan {
|
||||
Arc::clone(&self.pricing)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn fast_mode(&self) -> FastMode {
|
||||
self.account_scope.fast_mode()
|
||||
}
|
||||
|
||||
/// 本次请求冻结的已编译规则,重试不读取新的全局策略
|
||||
#[must_use]
|
||||
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
|
||||
|
||||
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ExecutionSettings {
|
||||
pub runtime: SettingsValues,
|
||||
pub fast_mode: FastMode,
|
||||
/// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
|
||||
pub fast_mode: Option<FastMode>,
|
||||
pub client_limits: RateLimits,
|
||||
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
|
||||
pub timeout_ms: Option<u64>,
|
||||
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
|
||||
defaults: Arc<ClientSettings>,
|
||||
client_key_id: String,
|
||||
input: Arc<ExecutionSettings>,
|
||||
fast_mode: Option<SettingOverride<FastMode>>,
|
||||
fast_mode: Option<SettingOverride<Option<FastMode>>>,
|
||||
client_limits: Option<SettingOverride<RateLimits>>,
|
||||
timeout_ms: Option<SettingOverride<Option<u64>>>,
|
||||
}
|
||||
@@ -186,9 +187,10 @@ impl RequestSettings {
|
||||
#[must_use]
|
||||
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
|
||||
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
|
||||
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
|
||||
policy.with_settings(
|
||||
values.runtime.request_profiles(),
|
||||
values.fast_mode,
|
||||
fast_mode,
|
||||
values.client_limits,
|
||||
)
|
||||
}
|
||||
@@ -247,9 +249,7 @@ impl RequestSettings {
|
||||
}
|
||||
ExecutionSettings {
|
||||
runtime,
|
||||
fast_mode: overrides
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map_or(defaults.fast_mode, |change| change.value),
|
||||
fast_mode: self.fast_mode_override(key, defaults),
|
||||
client_limits: overrides
|
||||
.and_then(|scope| scope.client_limits.as_ref())
|
||||
.map_or(defaults.limits, |change| change.value),
|
||||
@@ -259,6 +259,15 @@ impl RequestSettings {
|
||||
}
|
||||
}
|
||||
|
||||
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
|
||||
self.execution
|
||||
.as_ref()
|
||||
.filter(|scope| scope.client_key_id == key)
|
||||
.and_then(|scope| scope.fast_mode.as_ref())
|
||||
.map(|change| change.value)
|
||||
.unwrap_or(defaults.fast_mode_override)
|
||||
}
|
||||
|
||||
pub(crate) fn execution_deadline(
|
||||
&self,
|
||||
key: &ClientApiKeyId,
|
||||
|
||||
@@ -583,12 +583,19 @@ async fn compile_runtime_snapshot(
|
||||
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
|
||||
.collect();
|
||||
let account_directory = Arc::new(
|
||||
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access),
|
||||
RuntimeAccountDirectory::new(accounts)
|
||||
.with_group_model_access(group_model_access)
|
||||
.with_group_fast_modes(
|
||||
groups
|
||||
.values()
|
||||
.filter(|group| group.enabled && group.fast_mode != FastMode::Default)
|
||||
.map(|group| (group.id.clone(), group.fast_mode))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
|
||||
let mut client_policies = Vec::with_capacity(facts.client_policies.len());
|
||||
for policy in facts.client_policies {
|
||||
let mut fast_mode = FastMode::Default;
|
||||
let mut allow_image_generation = true;
|
||||
let mut allow_subagents = true;
|
||||
let account_scope = if policy.group_ids.is_empty() {
|
||||
@@ -607,8 +614,7 @@ async fn compile_runtime_snapshot(
|
||||
let group = groups
|
||||
.get(&group_id)
|
||||
.ok_or(RuntimeSnapshotCompileError::InvalidData)?;
|
||||
// 停用只影响选号,仍绑定的分组继续贡献请求策略
|
||||
fast_mode = fast_mode.merge(group.fast_mode);
|
||||
// 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制
|
||||
allow_image_generation &= group.allow_image_generation;
|
||||
allow_subagents &= group.allow_subagents;
|
||||
bound_groups.push(RoutingGroupSnapshot::new(
|
||||
@@ -635,7 +641,6 @@ async fn compile_runtime_snapshot(
|
||||
account_scope
|
||||
.with_image_generation(allow_image_generation)
|
||||
.with_subagents(allow_subagents)
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_request_profiles(policy.request_profiles),
|
||||
),
|
||||
true,
|
||||
|
||||
@@ -1138,26 +1138,12 @@ fn plan_with_location(
|
||||
operation: &Operation,
|
||||
account_selection_policy: AccountSelectionPolicy,
|
||||
request_location: gateway_core::account::RequestLocation,
|
||||
) -> RoutingPlan {
|
||||
plan_with_location_and_fast_policy(
|
||||
operation,
|
||||
account_selection_policy,
|
||||
request_location,
|
||||
FastMode::Default,
|
||||
)
|
||||
}
|
||||
|
||||
fn plan_with_location_and_fast_policy(
|
||||
operation: &Operation,
|
||||
account_selection_policy: AccountSelectionPolicy,
|
||||
request_location: gateway_core::account::RequestLocation,
|
||||
fast_mode: FastMode,
|
||||
) -> RoutingPlan {
|
||||
plan_with_profiles(
|
||||
operation,
|
||||
account_selection_policy,
|
||||
request_location,
|
||||
fast_mode,
|
||||
FastMode::Default,
|
||||
Default::default(),
|
||||
)
|
||||
}
|
||||
@@ -1255,7 +1241,7 @@ fn plan_with_protection(
|
||||
operation,
|
||||
Arc::new(
|
||||
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_fast_mode_override(Some(fast_mode))
|
||||
.with_request_profiles(profiles),
|
||||
),
|
||||
&RoutingContext {
|
||||
@@ -6414,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
|
||||
|
||||
#[test]
|
||||
fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
|
||||
|
||||
for mode in [
|
||||
FastMode::Default,
|
||||
FastMode::Enabled,
|
||||
@@ -6425,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
timezone: "Asia/Tokyo".parse().unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let route_plan = plan_with_location_and_fast_policy(
|
||||
&operation,
|
||||
plan(&operation).account_selection_policy(),
|
||||
location.clone(),
|
||||
mode,
|
||||
let kind = ProviderKind::new("openai").unwrap();
|
||||
let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap();
|
||||
let second_mode = if mode == FastMode::Disabled {
|
||||
FastMode::Default
|
||||
} else {
|
||||
FastMode::Disabled
|
||||
};
|
||||
let directory = Arc::new(
|
||||
RuntimeAccountDirectory::new(
|
||||
[
|
||||
("acct_first", first_group.clone()),
|
||||
("acct_second", second_group.clone()),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(account, group)| {
|
||||
(
|
||||
ProviderAccountId::new(account).unwrap(),
|
||||
RuntimeAccount::new(kind.clone(), BTreeSet::from([group])),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.with_group_fast_modes(BTreeMap::from([
|
||||
(first_group.clone(), mode),
|
||||
(second_group.clone(), second_mode),
|
||||
])),
|
||||
);
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::clone(&directory),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![
|
||||
RoutingGroupSnapshot::new(first_group.clone(), "A".into()),
|
||||
RoutingGroupSnapshot::new(second_group.clone(), "B".into()),
|
||||
],
|
||||
BTreeSet::from([first_group, second_group]),
|
||||
BTreeSet::from([kind.clone()]),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let route_plan = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None)
|
||||
.with_request_location(location.clone(), true),
|
||||
vec![kind.clone()],
|
||||
vec![ProviderModel::new(
|
||||
kind,
|
||||
UpstreamModelId::new("gpt-5").unwrap(),
|
||||
ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)),
|
||||
)],
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_account_directory(directory)
|
||||
.plan(
|
||||
&PublicModelId::new("gpt-5").unwrap(),
|
||||
&operation,
|
||||
Arc::clone(&scope),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let (coordinator, _, provider) = coordinator(vec![
|
||||
Script::Stream {
|
||||
account_id: "acct_first",
|
||||
@@ -6459,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
|
||||
block_on(session.commit_downstream(Some(200))).unwrap();
|
||||
let contexts = provider.contexts.lock().unwrap();
|
||||
assert_eq!(contexts.len(), 2);
|
||||
assert!(
|
||||
contexts
|
||||
.iter()
|
||||
.all(|context| context.request_location() == Some(&location)
|
||||
&& context.fast_mode() == mode)
|
||||
);
|
||||
for (context, account, expected) in [
|
||||
(&contexts[0], "acct_first", mode),
|
||||
(&contexts[1], "acct_second", second_mode),
|
||||
] {
|
||||
assert_eq!(context.request_location(), Some(&location));
|
||||
assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope));
|
||||
assert_eq!(
|
||||
context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3068,8 +3068,14 @@ impl Provider for ChargedProvider {
|
||||
request: ProviderRequest,
|
||||
context: AttemptContext,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
self.policies.lock().unwrap().push(context.fast_mode());
|
||||
let candidate = request.candidate();
|
||||
self.policies
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(context.fast_mode_for_account(
|
||||
&ProviderAccountId::new("acct_start").unwrap(),
|
||||
candidate.upstream_model().unwrap().as_str(),
|
||||
));
|
||||
let metadata = ProviderCallMetadata::new(
|
||||
candidate.provider().clone(),
|
||||
candidate.upstream_model().unwrap().clone(),
|
||||
@@ -4792,7 +4798,7 @@ fn start_snapshot_with_image_policy(
|
||||
account_scope(&provider, "acct_start")
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_fast_mode_override(Some(fast_mode))
|
||||
.with_image_generation(allow_image_generation),
|
||||
),
|
||||
enabled,
|
||||
@@ -5526,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() {
|
||||
.execution_values()
|
||||
.unwrap()
|
||||
.fast_mode,
|
||||
FastMode::Disabled
|
||||
Some(FastMode::Disabled)
|
||||
);
|
||||
assert_eq!(
|
||||
prepared
|
||||
@@ -5649,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
account_scope(&provider, "acct_start")
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode(FastMode::Disabled)
|
||||
.with_fast_mode_override(Some(FastMode::Disabled))
|
||||
.with_request_profiles(profiles(name)),
|
||||
),
|
||||
true,
|
||||
@@ -5688,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
let configuration = RequestSettings::new(snapshots.acquire().unwrap())
|
||||
.with_execution(parent.client().policy(), previous.timeout_ms);
|
||||
let mut values = previous.clone();
|
||||
values.fast_mode = FastMode::Default;
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
values.client_limits = RateLimits::unlimited();
|
||||
values.timeout_ms = Some(90_000);
|
||||
let mut runtime = serde_json::to_value(&values.runtime).unwrap();
|
||||
@@ -5722,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
|
||||
Some(actual.clone())
|
||||
);
|
||||
assert_eq!(actual.client_limits.max_concurrency, expected_limit);
|
||||
assert_eq!(actual.fast_mode, expected_fast);
|
||||
assert_eq!(actual.fast_mode, Some(expected_fast));
|
||||
assert_eq!(actual.timeout_ms, expected_timeout);
|
||||
let facts = serde_json::to_value(actual.runtime).unwrap();
|
||||
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
|
||||
|
||||
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
|
||||
));
|
||||
let gateway = GatewayError::from_provider(&error);
|
||||
|
||||
assert_eq!(gateway.safe_message(), "Account quota is exhausted.");
|
||||
assert_eq!(
|
||||
gateway.safe_message(),
|
||||
"Upstream account quota is exhausted."
|
||||
);
|
||||
assert_eq!(gateway.client_message(), message);
|
||||
assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
|
||||
assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
|
||||
|
||||
@@ -53,7 +53,7 @@ fn policy_with_profiles(
|
||||
Arc::new(
|
||||
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
|
||||
.with_request_profiles(overrides)
|
||||
.with_fast_mode(FastMode::Disabled),
|
||||
.with_fast_mode_override(Some(FastMode::Disabled)),
|
||||
),
|
||||
true,
|
||||
RateLimits {
|
||||
@@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
values.runtime = values
|
||||
.runtime
|
||||
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
|
||||
values.fast_mode = FastMode::Default;
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
values.client_limits = RateLimits::unlimited();
|
||||
values.timeout_ms = Some(90_000);
|
||||
let changed = original.replace_execution(&values, "plugin").unwrap();
|
||||
@@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
parent_values.runtime.request_profiles(),
|
||||
&profiles(&[("openai", "parent"), ("xai", "second")])
|
||||
);
|
||||
assert_eq!(parent_values.fast_mode, FastMode::Default);
|
||||
assert_eq!(parent_values.fast_mode, Some(FastMode::Default));
|
||||
let child_settings = rebased.with_execution(&child, Some(60_000));
|
||||
let child_values = child_settings.execution_values().unwrap();
|
||||
assert_eq!(
|
||||
child_values.runtime.request_profiles(),
|
||||
&profiles(&[("openai", "child"), ("xai", "second")])
|
||||
);
|
||||
assert_eq!(child_values.fast_mode, FastMode::Disabled);
|
||||
assert_eq!(child_values.fast_mode, Some(FastMode::Disabled));
|
||||
assert_eq!(child_values.client_limits, child.limits());
|
||||
assert_eq!(child_values.timeout_ms, Some(60_000));
|
||||
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
|
||||
@@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() {
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory},
|
||||
};
|
||||
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let account = ProviderAccountId::new("acct_group_fast").unwrap();
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(BTreeMap::from([(
|
||||
account.clone(),
|
||||
RuntimeAccount::new(provider.clone(), [group.clone()].into()),
|
||||
)]))
|
||||
.with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())],
|
||||
[group].into(),
|
||||
[provider].into(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let key = |name: &str| {
|
||||
ClientPolicy::new(
|
||||
ClientApiKeyId::new(name).unwrap(),
|
||||
PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(),
|
||||
scope.clone(),
|
||||
true,
|
||||
RateLimits::unlimited(),
|
||||
)
|
||||
};
|
||||
let parent = key("parent");
|
||||
let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None);
|
||||
assert_eq!(settings.execution_values().unwrap().fast_mode, None);
|
||||
let resolved = |settings: &RequestSettings, key| {
|
||||
settings
|
||||
.apply_policy(key)
|
||||
.account_scope()
|
||||
.fast_mode_for_account(&account, "model")
|
||||
};
|
||||
assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled);
|
||||
let unchanged = settings
|
||||
.replace_execution(&settings.execution_values().unwrap(), "pass-through")
|
||||
.unwrap();
|
||||
assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled);
|
||||
|
||||
let mut values = settings.execution_values().unwrap();
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
let direct_default = settings
|
||||
.replace_execution(&values, "follow-client")
|
||||
.unwrap();
|
||||
assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default);
|
||||
values.fast_mode = Some(FastMode::Enabled);
|
||||
let enabled = settings.replace_execution(&values, "force-fast").unwrap();
|
||||
assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled);
|
||||
values.fast_mode = Some(FastMode::Default);
|
||||
let default = enabled.replace_execution(&values, "follow-client").unwrap();
|
||||
assert_eq!(resolved(&default, parent.clone()), FastMode::Default);
|
||||
values.fast_mode = None;
|
||||
let cleared = default.replace_execution(&values, "group-policy").unwrap();
|
||||
assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled);
|
||||
assert_eq!(
|
||||
cleared.inspect()["execution"]["fast_mode"]["value"],
|
||||
serde_json::Value::Null
|
||||
);
|
||||
let child = key("child");
|
||||
assert_eq!(
|
||||
resolved(&default.with_execution(&child, None), child),
|
||||
FastMode::Disabled
|
||||
);
|
||||
assert_eq!(resolved(&settings, parent), FastMode::Disabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
|
||||
let host = snapshot(1, "first");
|
||||
|
||||
@@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() {
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
use gateway_core::routing::AccountGroupId;
|
||||
for (mode, other_mode, expected) in [
|
||||
@@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
let open_group_id =
|
||||
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
|
||||
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
|
||||
let first_account = ProviderAccountId::new("acct_first_group").unwrap();
|
||||
let second_account = ProviderAccountId::new("acct_second_group").unwrap();
|
||||
let facts = SnapshotFacts::new(
|
||||
revision(1),
|
||||
revision(1),
|
||||
@@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
)
|
||||
.with_fast_mode(other_mode),
|
||||
],
|
||||
vec![SnapshotProviderAccountFacts::new(
|
||||
account_id.clone(),
|
||||
"alpha",
|
||||
)],
|
||||
[&account_id, &first_account, &second_account]
|
||||
.into_iter()
|
||||
.map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha"))
|
||||
.collect(),
|
||||
vec![
|
||||
SnapshotAccountGroupMemberFacts::new(
|
||||
group_id.clone(),
|
||||
first_account.clone(),
|
||||
),
|
||||
SnapshotAccountGroupMemberFacts::new(
|
||||
open_group_id.clone(),
|
||||
second_account.clone(),
|
||||
),
|
||||
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
|
||||
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
|
||||
],
|
||||
@@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
for (account, effective) in [
|
||||
(
|
||||
&account_id,
|
||||
if group_enabled { expected } else { other_mode },
|
||||
),
|
||||
(
|
||||
&first_account,
|
||||
if group_enabled {
|
||||
mode
|
||||
} else {
|
||||
FastMode::Default
|
||||
},
|
||||
),
|
||||
(&second_account, other_mode),
|
||||
] {
|
||||
assert_eq!(
|
||||
plan.account_scope()
|
||||
.fast_mode_for_account(account, "public-model"),
|
||||
if bound { effective } else { FastMode::Default },
|
||||
"account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
plan.fast_mode(),
|
||||
if bound { expected } else { FastMode::Default },
|
||||
"mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
|
||||
plan.account_scope().allows(&first_account),
|
||||
!bound || group_enabled
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() {
|
||||
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId};
|
||||
use gateway_core::routing::AccountGroupId;
|
||||
|
||||
let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap();
|
||||
let account = ProviderAccountId::new("acct_model_fast").unwrap();
|
||||
let facts = SnapshotFacts::new(
|
||||
revision(1),
|
||||
revision(1),
|
||||
SettingsValues::new(3, "smart", BTreeMap::new(), None, None),
|
||||
vec![SnapshotClientPolicyFacts::new(
|
||||
ClientApiKeyId::new("key_model_fast").unwrap(),
|
||||
PlaintextClientApiKey::new("fixture-model-fast").unwrap(),
|
||||
vec![group(1), group(2)],
|
||||
RateLimits::unlimited(),
|
||||
)],
|
||||
vec![
|
||||
SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true)
|
||||
.with_fast_mode(FastMode::Enabled)
|
||||
.with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
vec!["fast-model".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true)
|
||||
.with_fast_mode(FastMode::Disabled)
|
||||
.with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Denylist,
|
||||
vec!["fast-model".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true)
|
||||
.with_fast_mode(FastMode::Disabled),
|
||||
],
|
||||
vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")],
|
||||
(1..=3)
|
||||
.map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone()))
|
||||
.collect(),
|
||||
);
|
||||
let snapshot = block_on(
|
||||
RuntimeSnapshotCompiler::new(
|
||||
Arc::new(TestSnapshotStore::new(Ok(facts))),
|
||||
Arc::new(TestCatalog::Unavailable),
|
||||
)
|
||||
.compile(),
|
||||
)
|
||||
.unwrap();
|
||||
let scope = snapshot.client_policies().next().unwrap().account_scope();
|
||||
for (model, expected) in [
|
||||
("fast-model", FastMode::Enabled),
|
||||
("standard-model", FastMode::Disabled),
|
||||
] {
|
||||
assert!(scope.allows_model(&account, model));
|
||||
assert_eq!(scope.fast_mode_for_account(&account, model), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_feature_permissions_merge_independently_with_deny_precedence() {
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
|
||||
@@ -48,6 +48,7 @@ tracing = "0.1.44"
|
||||
tracing-appender = "0.2.5"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||
yaml-rust2 = "0.13.0"
|
||||
uuid = { version = "1.23.3", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
|
||||
|
||||
@@ -37,6 +37,7 @@ const MAX_OFFICIAL_PLUGIN_MANIFEST_SIZE: u64 = 256 * 1024;
|
||||
/// gateway-admin 消费的真实进程/文件系统操作实现
|
||||
#[derive(Clone)]
|
||||
pub struct ProcessSystemOperations {
|
||||
instance_id: String,
|
||||
cancellation: CancellationToken,
|
||||
events: Arc<UpdateEvents>,
|
||||
config: Arc<SystemUpdateConfig>,
|
||||
@@ -62,6 +63,7 @@ impl ProcessSystemOperations {
|
||||
ReleaseFiles::installed(&config)
|
||||
}));
|
||||
Self {
|
||||
instance_id: uuid::Uuid::new_v4().to_string(),
|
||||
cancellation,
|
||||
events: Arc::new(UpdateEvents::default()),
|
||||
config: Arc::new(config),
|
||||
@@ -350,6 +352,8 @@ impl SystemOperations for ProcessSystemOperations {
|
||||
.await;
|
||||
Ok(SystemVersion {
|
||||
version: self.config.version.clone(),
|
||||
instance_id: self.instance_id.clone(),
|
||||
restart_supported: self.config.self_restart_enabled,
|
||||
git_sha: self.config.git_sha.clone(),
|
||||
build_time: self.config.build_time.clone(),
|
||||
deployment_mode: self.config.deployment_mode.clone(),
|
||||
|
||||
@@ -142,6 +142,8 @@ async fn restart_should_request_process_restart_inside_docker() {
|
||||
config.deployment_mode = "docker".to_owned();
|
||||
let shutdown = CancellationToken::new();
|
||||
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||
assert!(!service.update_status().await.expect("status").need_restart);
|
||||
assert!(service.version().await.expect("version").restart_supported);
|
||||
service
|
||||
.restart(Arc::new(AllowingUpdatePreflight))
|
||||
.await
|
||||
@@ -152,6 +154,48 @@ async fn restart_should_request_process_restart_inside_docker() {
|
||||
.expect("shutdown requested");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_distinguish_same_version_service_instances() {
|
||||
let fixture = Fixture::new();
|
||||
let config = fixture.config("http://127.0.0.1:1/repos");
|
||||
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
|
||||
let version = service.version().await.expect("version");
|
||||
assert!(!version.instance_id.is_empty());
|
||||
assert_eq!(
|
||||
service
|
||||
.clone()
|
||||
.version()
|
||||
.await
|
||||
.expect("same instance")
|
||||
.instance_id,
|
||||
version.instance_id
|
||||
);
|
||||
|
||||
let replacement = ProcessSystemOperations::new(CancellationToken::new(), config);
|
||||
let restarted = replacement.version().await.expect("new instance");
|
||||
assert_eq!(restarted.version, version.version);
|
||||
assert_ne!(restarted.instance_id, version.instance_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_should_report_restart_disabled_when_host_rejects_it() {
|
||||
let fixture = Fixture::new();
|
||||
let mut config = fixture.config("http://127.0.0.1:1/repos");
|
||||
config.self_restart_enabled = false;
|
||||
let shutdown = CancellationToken::new();
|
||||
let service = ProcessSystemOperations::new(shutdown.clone(), config);
|
||||
assert!(!service.version().await.expect("version").restart_supported);
|
||||
assert_eq!(
|
||||
service
|
||||
.restart(Arc::new(AllowingUpdatePreflight))
|
||||
.await
|
||||
.expect_err("restart disabled")
|
||||
.kind(),
|
||||
SystemOperationErrorKind::Conflict
|
||||
);
|
||||
assert!(!shutdown.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn accepted_restart_excludes_system_operations_until_service_release() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -248,21 +248,21 @@ impl Execution {
|
||||
request_body_limit,
|
||||
)
|
||||
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
|
||||
let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?;
|
||||
let request = UpstreamAdapterRequest {
|
||||
adapter_id: declaration.id.clone(),
|
||||
provider: declaration.provider,
|
||||
upstream_model: invocation
|
||||
.metadata
|
||||
.upstream_model()
|
||||
.ok_or_else(invalid)?
|
||||
.as_str()
|
||||
.to_owned(),
|
||||
upstream_model: upstream_model.as_str().to_owned(),
|
||||
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
|
||||
account_id: invocation.account.account_id().as_str().to_owned(),
|
||||
credential_revision: invocation.account.credential_revision().get(),
|
||||
protocol: invocation.operation.protocol().to_owned(),
|
||||
client_transport: invocation.context.client_transport().as_str().to_owned(),
|
||||
fast_mode: invocation.context.fast_mode().as_str().to_owned(),
|
||||
fast_mode: invocation
|
||||
.context
|
||||
.fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str())
|
||||
.as_str()
|
||||
.to_owned(),
|
||||
request_elapsed_ms: u64::try_from(
|
||||
invocation.context.timing_started_at().elapsed().as_millis(),
|
||||
)
|
||||
|
||||
@@ -7,13 +7,16 @@ use serde_json::{Value, json};
|
||||
#[tokio::test]
|
||||
async fn middleware_preserves_fast_modes_and_sources() {
|
||||
for (mode, expected) in [
|
||||
(FastMode::Default, FastMode::Default),
|
||||
(FastMode::Enabled, FastMode::Enabled),
|
||||
(FastMode::Disabled, FastMode::Disabled),
|
||||
(FastMode::Enabled, FastMode::Disabled),
|
||||
(FastMode::Ultrafast, FastMode::Ultrafast),
|
||||
(FastMode::Enabled, FastMode::Ultrafast),
|
||||
(FastMode::Disabled, FastMode::Default),
|
||||
(None, None),
|
||||
(None, Some(FastMode::Default)),
|
||||
(Some(FastMode::Default), Some(FastMode::Default)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Enabled)),
|
||||
(Some(FastMode::Disabled), Some(FastMode::Disabled)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Disabled)),
|
||||
(Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)),
|
||||
(Some(FastMode::Enabled), Some(FastMode::Ultrafast)),
|
||||
(Some(FastMode::Disabled), Some(FastMode::Default)),
|
||||
(Some(FastMode::Enabled), None),
|
||||
] {
|
||||
let snapshot = gateway_core::routing::RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
@@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
let settings = settings.replace_execution(&seed, "seed").unwrap();
|
||||
let wire = serde_json::to_value(&seed).unwrap();
|
||||
let mut updated = wire.clone();
|
||||
updated["fast_mode"] = json!(expected.as_str());
|
||||
updated["timeout_ms"] = json!(90_000);
|
||||
updated["fast_mode"] = json!(expected);
|
||||
let contribution = crate::support::contribution(
|
||||
Capability::Middleware,
|
||||
vec![Stage::Request],
|
||||
@@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
id: "fast-settings",
|
||||
configuration: json!({
|
||||
"mode":"settings", "expected_settings":wire, "settings":updated,
|
||||
"expected_fast_source": if mode == FastMode::Default { Value::Null } else {
|
||||
json!({"instance_id":"seed", "order":1, "value":mode.as_str()})
|
||||
"expected_fast_source": if mode.is_none() { Value::Null } else {
|
||||
json!({"instance_id":"seed", "order":1, "value":mode})
|
||||
},
|
||||
}),
|
||||
bindings: vec![binding(
|
||||
@@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
|
||||
assert_eq!(
|
||||
settings.execution_values().unwrap().timeout_ms,
|
||||
Some(90_000)
|
||||
Some(60_000)
|
||||
);
|
||||
let sources = settings.inspect();
|
||||
let fast_source = &sources["execution"]["fast_mode"];
|
||||
if mode == FastMode::Default && expected == FastMode::Default {
|
||||
if mode.is_none() && expected.is_none() {
|
||||
assert!(fast_source.is_null());
|
||||
} else {
|
||||
assert_eq!(
|
||||
@@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() {
|
||||
"fast-settings"
|
||||
}
|
||||
);
|
||||
assert_eq!(fast_source["value"], expected.as_str());
|
||||
assert_eq!(fast_source["value"], json!(expected));
|
||||
}
|
||||
assert_eq!(
|
||||
sources["execution"]["timeout_ms"]["instance_id"],
|
||||
"fast-settings"
|
||||
);
|
||||
assert!(sources["execution"]["timeout_ms"].is_null());
|
||||
next.run(request).await
|
||||
})
|
||||
}),
|
||||
|
||||
@@ -1277,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
||||
let baseline = ExecutionSettings {
|
||||
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
||||
.with_request_profiles(profiles("key-default")),
|
||||
fast_mode: FastMode::Disabled,
|
||||
fast_mode: Some(FastMode::Disabled),
|
||||
client_limits: RateLimits {
|
||||
max_concurrency: 2,
|
||||
requests_per_minute: 10,
|
||||
@@ -1314,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
|
||||
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||
)
|
||||
.with_request_profiles(profiles("key-default"))
|
||||
.with_fast_mode(baseline.fast_mode),
|
||||
.with_fast_mode_override(baseline.fast_mode),
|
||||
),
|
||||
true,
|
||||
baseline.client_limits,
|
||||
|
||||
@@ -179,7 +179,6 @@ fn context_with_body_limit(
|
||||
ClientApiKeyId::new(key).unwrap(),
|
||||
)
|
||||
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
|
||||
.with_fast_mode(mode)
|
||||
.with_request_body_limit(bytes),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
@@ -187,7 +186,13 @@ fn context_with_body_limit(
|
||||
gateway_core::account::RotationStrategy::RoundRobin,
|
||||
std::num::NonZeroU32::new(1).unwrap(),
|
||||
),
|
||||
AccountAttemptContext::new(Default::default(), None, None),
|
||||
AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new(
|
||||
gateway_core::routing::FrozenAccountScope::new(
|
||||
Arc::default(),
|
||||
gateway_core::routing::ClientRoutingScope::all_accounts(),
|
||||
)
|
||||
.with_fast_mode_override(Some(mode)),
|
||||
)),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
|
||||
@@ -588,7 +588,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
);
|
||||
if let Some(expected) = configuration.get("expected_fast_source") {
|
||||
let sources = &call.request.head.settings_sources["execution"];
|
||||
assert_eq!(sources["input"]["fast_mode"], "default");
|
||||
assert!(sources["input"]["fast_mode"].is_null());
|
||||
assert_eq!(&sources["fast_mode"], expected);
|
||||
}
|
||||
if let Some(settings) = configuration.get("settings") {
|
||||
|
||||
@@ -489,7 +489,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
|
||||
|
||||
#### 模型请求与 attempt
|
||||
|
||||
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 在进入 attempt 前应用宿主 Fast 策略;
|
||||
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 按选中账号和上游模型解析宿主 Fast 策略,在进入 attempt 前应用;
|
||||
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
|
||||
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
|
||||
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
|
||||
@@ -498,7 +498,8 @@ CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider
|
||||
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
|
||||
|
||||
request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。
|
||||
`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
|
||||
`fast_mode` 为 `null` 时按选中账号的有效分组解析;显式 `default` 表示跟随客户端,`enabled`、`ultrafast`、`disabled` 覆盖分组策略,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
|
||||
保留该字段不建立新覆盖,改写为 `null` 恢复按分组解析;其他改写形成当前 Key 的显式覆盖,优先于分组策略。attempt 中间件仍可直接改写正文档位
|
||||
`runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。
|
||||
SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。
|
||||
线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。
|
||||
|
||||
@@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili
|
||||
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
|
||||
原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件
|
||||
|
||||
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
|
||||
`fast_mode` 是按选中账号及上游模型解析后的有效策略,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`,请求设置的显式覆盖优先于分组策略。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
|
||||
适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。
|
||||
其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt)
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -13,7 +16,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
validate_request(chat)?;
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(parts(instructions, "instructions", true)?);
|
||||
system.extend(parts(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -30,7 +33,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
system.extend(parts(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -48,7 +51,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
let mut text = Vec::new();
|
||||
let mut media = Vec::new();
|
||||
for part in parts(&message["content"], &format!("{path}.content"), false)? {
|
||||
for part in parts(&message["content"], &format!("{path}.content"), role)? {
|
||||
if let Some(value) = part.get("text").and_then(Value::as_str) {
|
||||
text.push(value.to_owned());
|
||||
} else {
|
||||
@@ -61,12 +64,12 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
vec![response]
|
||||
} else {
|
||||
let mut content = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
parts(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut content = parts(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
content.push(json!({"text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -105,6 +108,9 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
content
|
||||
};
|
||||
if role == "assistant" && content.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append(
|
||||
&mut contents,
|
||||
if role == "assistant" { "model" } else { "user" },
|
||||
@@ -134,11 +140,10 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
generation.insert(to.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
generation.insert("stopSequences".into(), stops);
|
||||
}
|
||||
if let Some(effort) = reasoning_effort(chat) {
|
||||
let budget: i64 = match effort.as_str() {
|
||||
Some("none") => 0,
|
||||
Some("minimal" | "low") => 1024,
|
||||
@@ -158,11 +163,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(format) = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
@@ -205,7 +206,11 @@ fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn parts(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"text":text})]);
|
||||
}
|
||||
@@ -214,12 +219,13 @@ fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatErro
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
.map(|(index, part)| {
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?}))
|
||||
Ok(json!({"text":block_text(part.get("text"), &path)?}))
|
||||
}
|
||||
"refusal" if !system => Ok(
|
||||
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
|
||||
@@ -314,16 +320,10 @@ fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(
|
||||
let parameters = if kind == "custom" {
|
||||
custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
definition
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(definition, &path)?
|
||||
};
|
||||
if !parameters.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
|
||||
if let Some(value) = definition.get("description") {
|
||||
if let Some(value) = definition.get("description").filter(|v| !v.is_null()) {
|
||||
declaration["description"] = value.clone();
|
||||
}
|
||||
declarations.push(declaration);
|
||||
|
||||
@@ -4,7 +4,10 @@ use crate::anthropic::MessagesModelCapabilities;
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -37,6 +40,9 @@ pub fn convert_request(
|
||||
result.insert(field.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
result.insert("stop_sequences".into(), stops);
|
||||
}
|
||||
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
|
||||
match tier {
|
||||
"priority" => {
|
||||
@@ -53,7 +59,7 @@ pub fn convert_request(
|
||||
}
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(content(instructions, "instructions", true)?);
|
||||
system.extend(content(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -70,7 +76,7 @@ pub fn convert_request(
|
||||
system.extend(content(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -84,15 +90,15 @@ pub fn convert_request(
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
vec![
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}),
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), role)?}),
|
||||
]
|
||||
} else {
|
||||
let mut blocks = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
content(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut blocks = content(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
blocks.push(json!({"type":"text","text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -130,6 +136,9 @@ pub fn convert_request(
|
||||
}
|
||||
blocks
|
||||
};
|
||||
if role == "assistant" && blocks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append_message(
|
||||
&mut messages,
|
||||
if role == "assistant" {
|
||||
@@ -148,10 +157,7 @@ pub fn convert_request(
|
||||
}
|
||||
result.insert("messages".into(), messages.into());
|
||||
tools(chat, &mut result, capabilities)?;
|
||||
let format = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
|
||||
if let Some(format) = format.filter(|v| !v.is_null()) {
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
let schema = format
|
||||
@@ -190,7 +196,11 @@ fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn content(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"type":"text","text":text})]);
|
||||
}
|
||||
@@ -200,12 +210,13 @@ fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatEr
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
let block = match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?})
|
||||
json!({"type":"text","text":block_text(part.get("text"), &path)?})
|
||||
}
|
||||
"refusal" if !system => {
|
||||
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
|
||||
@@ -295,17 +306,11 @@ fn tools(
|
||||
let schema = if kind == "custom" {
|
||||
custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
declaration
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(declaration, &path)?
|
||||
};
|
||||
if !schema.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut target = json!({"name":name,"input_schema":schema});
|
||||
for field in ["description", "strict", "cache_control"] {
|
||||
if let Some(value) = declaration.get(field) {
|
||||
if let Some(value) = declaration.get(field).filter(|v| !v.is_null()) {
|
||||
target[field] = value.clone();
|
||||
}
|
||||
}
|
||||
@@ -393,11 +398,7 @@ fn reasoning(
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
max_tokens: u64,
|
||||
) -> Result<(), ChatError> {
|
||||
let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
else {
|
||||
let Some(effort) = reasoning_effort(chat) else {
|
||||
return Ok(());
|
||||
};
|
||||
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
|
||||
|
||||
@@ -30,11 +30,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
field: "messages".into(),
|
||||
expected: "an array",
|
||||
})?;
|
||||
if messages.is_empty() {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
let mut has_message = false;
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
let path = format!("messages[{index}]");
|
||||
let message = message.as_object().ok_or_else(|| invalid(&path))?;
|
||||
@@ -42,43 +38,51 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
|
||||
return Err(unsupported(&format!("{path}.role")));
|
||||
}
|
||||
for (field, allowed) in [
|
||||
("tool_calls", "assistant"),
|
||||
("refusal", "assistant"),
|
||||
("tool_call_id", "tool"),
|
||||
] {
|
||||
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(invalid(&format!("{path}.{field}")));
|
||||
let calls = match message.get("tool_calls") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(Value::Array(calls)) => calls.as_slice(),
|
||||
_ => return Err(invalid(&format!("{path}.tool_calls"))),
|
||||
};
|
||||
if role != "assistant" && !calls.is_empty() {
|
||||
return Err(invalid(&format!("{path}.tool_calls")));
|
||||
}
|
||||
let refusal = message.get("refusal").filter(|v| !v.is_null() && *v != "");
|
||||
if let Some(value) = refusal {
|
||||
if role != "assistant" {
|
||||
return Err(invalid(&format!("{path}.refusal")));
|
||||
}
|
||||
string(Some(value), &format!("{path}.refusal"), true)?;
|
||||
}
|
||||
for field in ["function_call", "audio"] {
|
||||
if message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(unsupported(&format!("{path}.{field}")));
|
||||
}
|
||||
}
|
||||
for field in ["name", "refusal"] {
|
||||
if let Some(value) = message.get(field).filter(|v| !v.is_null()) {
|
||||
string(Some(value), &format!("{path}.{field}"), true)?;
|
||||
}
|
||||
}
|
||||
if role == "tool" {
|
||||
string(
|
||||
message.get("tool_call_id"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
} else if message
|
||||
.get("tool_call_id")
|
||||
.is_some_and(|v| !v.is_null() && v != "")
|
||||
{
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
if let Some(content) = message.get("content").filter(|v| !v.is_null()) {
|
||||
let content = message.get("content").unwrap_or(&Value::Null);
|
||||
if !empty_history_content(role, content) {
|
||||
if !content.is_string() && !content.is_array() {
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
has_message = true;
|
||||
if let Some(parts) = content.as_array() {
|
||||
for (part_index, part) in parts.iter().enumerate() {
|
||||
let part_path = format!("{path}.content[{part_index}]");
|
||||
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
string(part.get("text"), &format!("{part_path}.text"), true)?;
|
||||
block_text(part.get("text"), &part_path)?;
|
||||
}
|
||||
"image_url" | "file" | "input_audio" | "input_image" | "input_file"
|
||||
if matches!(role, "user" | "tool") => {}
|
||||
@@ -89,45 +93,37 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if role != "assistant"
|
||||
|| (!message
|
||||
.get("tool_calls")
|
||||
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
|
||||
&& !message.get("refusal").is_some_and(Value::is_string))
|
||||
{
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) {
|
||||
for (call_index, call) in calls
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
has_message |= refusal.is_some() || !calls.is_empty();
|
||||
for (call_index, call) in calls.iter().enumerate() {
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if !has_message {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
|
||||
let valid = match field.as_str() {
|
||||
"n" => value.as_u64() == Some(1),
|
||||
@@ -150,7 +146,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
|
||||
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() {
|
||||
if !options.is_object() {
|
||||
return Err(invalid("stream_options"));
|
||||
}
|
||||
for field in ["include_usage", "include_obfuscation"] {
|
||||
@@ -161,13 +157,99 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
return Err(invalid(&format!("stream_options.{field}")));
|
||||
}
|
||||
}
|
||||
if options.get("include_obfuscation") == Some(&Value::Bool(true)) {
|
||||
if body.get("stream") == Some(&Value::Bool(true))
|
||||
&& options.get("include_obfuscation") == Some(&Value::Bool(true))
|
||||
{
|
||||
return Err(unsupported("stream_options.include_obfuscation"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 用户输入和工具结果保留原值,空指令或 assistant 正文不生成上游内容块
|
||||
pub(super) fn empty_history_content(role: &str, content: &Value) -> bool {
|
||||
can_omit_empty_text(role)
|
||||
&& (content.is_null()
|
||||
|| content == ""
|
||||
|| content
|
||||
.as_array()
|
||||
.is_some_and(|parts| parts.iter().all(plain_empty_text)))
|
||||
}
|
||||
|
||||
fn can_omit_empty_text(role: &str) -> bool {
|
||||
matches!(role, "system" | "developer" | "assistant")
|
||||
}
|
||||
|
||||
fn plain_empty_text(part: &Value) -> bool {
|
||||
// 只移除纯文本占位,带缓存断点等附加字段的块交给目标转换器
|
||||
part.get("text")
|
||||
.is_some_and(|text| text.is_null() || text == "")
|
||||
&& matches!(
|
||||
part.get("type").and_then(Value::as_str),
|
||||
Some("text" | "input_text" | "output_text")
|
||||
)
|
||||
&& part.as_object().is_some_and(|fields| {
|
||||
fields
|
||||
.iter()
|
||||
.all(|(key, value)| matches!(key.as_str(), "type" | "text") || value.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn empty_history_part(role: &str, part: &Value) -> bool {
|
||||
can_omit_empty_text(role) && plain_empty_text(part)
|
||||
}
|
||||
|
||||
// 部分 Chat 客户端用显式 null 表示空文本,缺少 text 或其他类型仍按原字段报错
|
||||
pub(super) fn block_text<'a>(
|
||||
value: Option<&'a Value>,
|
||||
part_path: &str,
|
||||
) -> Result<&'a str, ChatError> {
|
||||
match value {
|
||||
Some(Value::Null) => Ok(""),
|
||||
value => string(value, &format!("{part_path}.text"), true),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn response_format(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("response_format")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| body.get("text")?.get("format").filter(|v| !v.is_null()))
|
||||
}
|
||||
|
||||
pub(super) fn reasoning_effort(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("reasoning_effort")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| {
|
||||
body.get("reasoning")?
|
||||
.get("effort")
|
||||
.filter(|v| !v.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Value>, ChatError> {
|
||||
match body.get("stop") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(text)) => Ok(Some(json!([text]))),
|
||||
Some(Value::Array(values)) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
if !value.is_string() {
|
||||
return Err(invalid(&format!("stop[{index}]")));
|
||||
}
|
||||
}
|
||||
Ok((!values.is_empty()).then(|| Value::Array(values.clone())))
|
||||
}
|
||||
_ => Err(invalid("stop")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn function_parameters(function: &Value, path: &str) -> Result<Value, ChatError> {
|
||||
match function.get("parameters") {
|
||||
None | Some(Value::Null) => Ok(json!({"type":"object","properties":{}})),
|
||||
Some(schema) if schema.is_object() => Ok(schema.clone()),
|
||||
_ => Err(invalid(&format!("{path}.function.parameters"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn string<'a>(
|
||||
value: Option<&'a Value>,
|
||||
path: &str,
|
||||
@@ -222,28 +304,16 @@ pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
|
||||
.any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")),
|
||||
reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null())
|
||||
|| body.get("reasoning").is_some_and(Value::is_object),
|
||||
json_schema: body
|
||||
.get("response_format")
|
||||
json_schema: response_format(body)
|
||||
.and_then(|v| v.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema")
|
||||
|| body
|
||||
.get("text")
|
||||
.and_then(|v| v.pointer("/format/type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema"),
|
||||
== Some("json_schema"),
|
||||
..RequestFacts::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
|
||||
body.get("reasoning_effort")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| {
|
||||
body.get("reasoning")
|
||||
.and_then(|value| value.get("effort"))
|
||||
.and_then(Value::as_str)
|
||||
})
|
||||
reasoning_effort(body).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持
|
||||
|
||||
@@ -4,7 +4,11 @@ use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::chat_completions::{ChatError as RequestDecodeError, validate_request};
|
||||
use crate::chat_completions::{
|
||||
ChatError as RequestDecodeError,
|
||||
request::{block_text, empty_history_content, empty_history_part},
|
||||
validate_request,
|
||||
};
|
||||
|
||||
/// 将已验证的 Chat 正文直接转换为 Responses 请求
|
||||
pub fn convert_request(
|
||||
@@ -161,7 +165,6 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let path = format!("messages[{index}]");
|
||||
let mut message = object(value, &path)?;
|
||||
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
|
||||
let name = optional(&mut message, "name").filter(|name| name != "");
|
||||
if role == "tool" {
|
||||
let call_id = required_string(
|
||||
&mut message,
|
||||
@@ -182,7 +185,8 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
"function_call_output"
|
||||
};
|
||||
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
|
||||
if let Some(name) = name {
|
||||
if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
|
||||
string(&name, &format!("{path}.name"), true)?;
|
||||
item["name"] = name;
|
||||
}
|
||||
input.push(item);
|
||||
@@ -193,8 +197,9 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
.map(|value| tool_calls(value, &format!("{path}.tool_calls")))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let refusal = optional(&mut message, "refusal");
|
||||
let content = optional(&mut message, "content");
|
||||
let refusal = optional(&mut message, "refusal").filter(|v| v != "");
|
||||
let content =
|
||||
optional(&mut message, "content").filter(|v| !empty_history_content(&role, v));
|
||||
let is_assistant = role == "assistant";
|
||||
let mut parts = content
|
||||
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
|
||||
@@ -233,20 +238,23 @@ fn content_parts(
|
||||
is_assistant: bool,
|
||||
) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let parts = match value {
|
||||
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]),
|
||||
Value::String(text) => return Ok(vec![text_part(&text, is_assistant)]),
|
||||
Value::Array(parts) => parts,
|
||||
_ => return Err(invalid_type(path, "a string or an array")),
|
||||
};
|
||||
let mut result = Vec::with_capacity(parts.len());
|
||||
for (index, value) in parts.into_iter().enumerate() {
|
||||
for (index, value) in parts
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let mut part = object(value, &path)?;
|
||||
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
|
||||
let mut converted = match kind.as_str() {
|
||||
"text" | "input_text" | "output_text" => text_part(
|
||||
required_string(&mut part, "text", &format!("{path}.text"), true)?,
|
||||
is_assistant,
|
||||
),
|
||||
"text" | "input_text" | "output_text" => {
|
||||
text_part(block_text(part.get("text"), &path)?, is_assistant)
|
||||
}
|
||||
"image_url" if matches!(role, "user" | "tool") => image_part(
|
||||
required(&mut part, "image_url", &format!("{path}.image_url"))?,
|
||||
&format!("{path}.image_url"),
|
||||
@@ -278,7 +286,7 @@ fn content_parts(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn text_part(text: String, is_assistant: bool) -> Value {
|
||||
fn text_part(text: &str, is_assistant: bool) -> Value {
|
||||
if is_assistant {
|
||||
json!({"type": "output_text", "text": text, "annotations": []})
|
||||
} else {
|
||||
@@ -376,9 +384,17 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
if let Some(nested) = optional(&mut tool, &kind) {
|
||||
tool = object(nested, &format!("{path}.{kind}"))?;
|
||||
}
|
||||
if kind == "function" && tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
if tool.get("description") == Some(&Value::Null) {
|
||||
tool.remove("description");
|
||||
}
|
||||
if kind == "function" {
|
||||
if tool.get("parameters") == Some(&Value::Null) {
|
||||
tool.remove("parameters");
|
||||
}
|
||||
if tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
|
||||
|
||||
@@ -1,4 +1,21 @@
|
||||
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析
|
||||
//! 跨协议 HTTP 头分类、响应关联与重试时间解析
|
||||
|
||||
/// 响应关联 ID 的头名与优先级沿用官方 Codex
|
||||
pub const RESPONSE_REQUEST_ID_HEADERS: [&str; 4] = [
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"x-ms-request-id",
|
||||
];
|
||||
|
||||
/// 从各传输容器提供的可读 HTTP 头值中选取关联 ID,空值不阻止别名回退
|
||||
pub fn preferred_response_request_id<'a>(
|
||||
mut header: impl FnMut(&str) -> Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
RESPONSE_REQUEST_ID_HEADERS
|
||||
.iter()
|
||||
.find_map(|name| header(name).filter(|value| !value.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// 上游可交给客户端的秒级与毫秒级重试等待头
|
||||
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
|
||||
|
||||
@@ -4,7 +4,15 @@ use gateway_protocol::{
|
||||
chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses},
|
||||
request::{request_facts, request_observation},
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
fn target_requests(body: &Map<String, Value>) -> [Result<Map<String, Value>, ChatError>; 3] {
|
||||
[
|
||||
responses::convert_request(body),
|
||||
messages::convert_request(body, &Default::default()),
|
||||
genai::convert_request(body),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_retains_original_protocol_and_usage_preference() {
|
||||
@@ -42,7 +50,7 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
|
||||
("n", json!(2)),
|
||||
("store", json!(true)),
|
||||
("previous_response_id", json!("resp_previous")),
|
||||
("stream_options", json!({"include_usage":true})),
|
||||
("stream_options", json!(true)),
|
||||
] {
|
||||
let mut request = super::request();
|
||||
request.insert(field.into(), value);
|
||||
@@ -104,9 +112,320 @@ fn capability_facts_only_read_protocol_declarations() {
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).tools);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_is_omitted_only_when_converting() {
|
||||
let mut baseline = super::request();
|
||||
baseline["messages"] = json!([
|
||||
{"role":"developer","content":"Keep replies short."},
|
||||
{"role":"user","content":"hello"}
|
||||
]);
|
||||
let expected = target_requests(&baseline).map(Result::unwrap);
|
||||
for role in ["system", "developer", "assistant"] {
|
||||
for content in [
|
||||
None,
|
||||
Some(Value::Null),
|
||||
Some(json!("")),
|
||||
Some(json!([])),
|
||||
Some(json!([{"type":"text","text":""},{"type":"output_text","text":""}])),
|
||||
Some(json!([{"type":"input_text","text":null}])),
|
||||
Some(json!([{"type":"text","text":"","prompt_cache_breakpoint":null}])),
|
||||
] {
|
||||
let mut placeholder =
|
||||
json!({"role":role,"tool_calls":[],"refusal":"","tool_call_id":""});
|
||||
if let Some(content) = content {
|
||||
placeholder["content"] = content;
|
||||
}
|
||||
let mut body = baseline.clone();
|
||||
body["messages"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.insert(1, placeholder.clone());
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
assert_eq!(parsed, body);
|
||||
assert_eq!(target_requests(&parsed).map(Result::unwrap), expected);
|
||||
|
||||
body["messages"] = json!([placeholder]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_fields_preserve_tool_calls_results_and_refusals() {
|
||||
let mut body = super::request();
|
||||
body["messages"] = json!([
|
||||
{"role":"user","content":"hello"},
|
||||
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{}"}}]},
|
||||
{"role":"tool","tool_call_id":"c","content":""},
|
||||
{"role":"assistant","refusal":"declined"}
|
||||
]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[0]["input"][1]["call_id"], "c");
|
||||
assert_eq!(expected[0]["input"][2]["output"], "");
|
||||
assert_eq!(expected[1]["messages"][1]["content"][0]["type"], "tool_use");
|
||||
assert_eq!(expected[1]["messages"][3]["content"][0]["text"], "declined");
|
||||
assert_eq!(
|
||||
expected[2]["contents"][2]["parts"][0]["functionResponse"]["id"],
|
||||
"c"
|
||||
);
|
||||
assert_eq!(expected[2]["contents"][3]["parts"][0]["text"], "declined");
|
||||
body["messages"][0] = json!({"role":"user","content":"hello","name":17,"refusal":"","tool_calls":[],"tool_call_id":""});
|
||||
for content in [
|
||||
Value::Null,
|
||||
json!(""),
|
||||
json!([]),
|
||||
json!([{"type":"text","text":""}]),
|
||||
json!([{"type":"output_text","text":null}]),
|
||||
] {
|
||||
body["messages"][1]["content"] = content.clone();
|
||||
body["messages"][3]["content"] = content;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
body["messages"][2]["content"] =
|
||||
json!([{"type":"text","text":""},{"type":"text","text":"x"},{"type":"text","text":""}]);
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["input"][2]["output"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(
|
||||
messages["messages"][2]["content"][0]["content"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
genai["contents"][2]["parts"][0]["functionResponse"]["response"]["output"],
|
||||
"\nx\n"
|
||||
);
|
||||
body["messages"][2]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(
|
||||
target_requests(&body).map(Result::unwrap),
|
||||
[responses, messages, genai]
|
||||
);
|
||||
body["messages"][2]["content"] = json!("");
|
||||
body["messages"][2]["name"] = json!(17);
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
let [responses, messages, genai] = target_requests(&parsed);
|
||||
assert_eq!(responses.unwrap_err().parameter(), Some("messages[2].name"));
|
||||
assert_eq!(messages.unwrap(), expected[1]);
|
||||
assert_eq!(genai.unwrap(), expected[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_only_plain_empty_history_parts_and_keeps_source_indices() {
|
||||
let mut body = super::request();
|
||||
let blank = json!({"type":"input_text","text":""});
|
||||
let space = json!({"type":"text","text":" "});
|
||||
for role in ["system", "developer", "assistant", "user"] {
|
||||
body["messages"] = json!([{"role":role,"content":[space]}, {"role":"user","content":"hi"}]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"] = json!([blank, space, blank]);
|
||||
let actual = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), actual);
|
||||
if role == "user" {
|
||||
assert_eq!(
|
||||
actual[0]["input"][0]["content"].as_array().unwrap().len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(actual[1]["messages"][0]["content"][1]["text"], " ");
|
||||
assert_eq!(actual[2]["contents"][0]["parts"][1]["text"], " ");
|
||||
} else {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
let marked = json!({"type":"text","text":null,"prompt_cache_breakpoint":{"mode":"explicit"}});
|
||||
body["messages"][0] = json!({"role":"developer","content":[blank,marked]});
|
||||
let converted = responses::convert_request(&body).unwrap();
|
||||
assert_eq!(
|
||||
converted["input"][0]["content"],
|
||||
json!([{"type":"input_text","text":"","prompt_cache_breakpoint":{"mode":"explicit"}}])
|
||||
);
|
||||
body["messages"][0]["role"] = json!("assistant");
|
||||
assert_eq!(
|
||||
responses::convert_request(&body).unwrap_err().parameter(),
|
||||
Some("messages[0].content[1].prompt_cache_breakpoint")
|
||||
);
|
||||
for (part, code) in [
|
||||
(json!({"type":"text"}), "missing_required_parameter"),
|
||||
(json!({"type":"text","text":17}), "invalid_type"),
|
||||
(json!({"type":"text","text":{}}), "invalid_type"),
|
||||
] {
|
||||
body["messages"][0]["content"] = json!([{"type":"text","text":null},part]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages[0].content[1].text"));
|
||||
assert_eq!(error.code(), code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_chat_controls_fall_back_to_native_format_and_effort() {
|
||||
let mut body = super::request();
|
||||
let schema = json!({"type":"object","properties":{"q":{"type":"string"}}});
|
||||
body.insert(
|
||||
"text".into(),
|
||||
json!({"format":{"type":"json_schema","name":"answer","schema":schema}}),
|
||||
);
|
||||
body.insert("reasoning".into(), json!({"effort":"low"}));
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[1]["output_config"]["format"]["schema"], schema);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["responseJsonSchema"],
|
||||
schema
|
||||
);
|
||||
assert_eq!(expected[1]["thinking"]["budget_tokens"], 1024);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
1024
|
||||
);
|
||||
body.insert("response_format".into(), Value::Null);
|
||||
body.insert("reasoning_effort".into(), Value::Null);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
assert!(request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
|
||||
body["response_format"] = json!({"type":"text"});
|
||||
body["reasoning_effort"] = json!("none");
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
assert_eq!(responses["text"]["format"]["type"], "text");
|
||||
assert!(messages.get("output_config").is_none());
|
||||
assert!(
|
||||
genai["generationConfig"]
|
||||
.get("responseJsonSchema")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(messages["thinking"]["type"], "disabled");
|
||||
assert_eq!(
|
||||
genai["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
0
|
||||
);
|
||||
body["reasoning_effort"] = json!(5);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("reasoning_effort"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_function_parameters_follow_each_targets_default() {
|
||||
let mut body = super::request();
|
||||
body.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"function","function":{"name":"clock"}}]),
|
||||
);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert!(expected[0]["tools"][0].get("parameters").is_none());
|
||||
let default_schema = json!({"type":"object","properties":{}});
|
||||
assert_eq!(expected[1]["tools"][0]["input_schema"], default_schema);
|
||||
assert_eq!(
|
||||
expected[2]["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
default_schema
|
||||
);
|
||||
body["tools"][0]["function"] =
|
||||
json!({"name":"clock","parameters":null,"description":null,"strict":null});
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
|
||||
let schema =
|
||||
json!({"type":"object","properties":{"q":{"type":["string","null"],"default":null}}});
|
||||
body["tools"][0]["function"]["parameters"] = schema.clone();
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["tools"][0]["parameters"], schema);
|
||||
assert_eq!(messages["tools"][0]["input_schema"], schema);
|
||||
assert_eq!(
|
||||
genai["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
schema
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_sequences_are_mapped_only_for_targets_that_support_them() {
|
||||
let mut body = super::request();
|
||||
let baseline = target_requests(&body).map(Result::unwrap);
|
||||
for stop in [Value::Null, json!([])] {
|
||||
body.insert("stop".into(), stop);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), baseline);
|
||||
}
|
||||
for (stop, expected) in [
|
||||
(json!(" END"), json!([" END"])),
|
||||
(json!([" END", "\n"]), json!([" END", "\n"])),
|
||||
] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses, baseline[0]);
|
||||
assert_eq!(messages["stop_sequences"], expected);
|
||||
assert_eq!(genai["generationConfig"]["stopSequences"], expected);
|
||||
}
|
||||
for (stop, param) in [(json!(5), "stop"), (json!(["end", null]), "stop[1]")] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body);
|
||||
assert_eq!(responses.unwrap(), baseline[0]);
|
||||
for result in [messages, genai] {
|
||||
assert_eq!(result.unwrap_err().parameter(), Some(param));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_options_affect_only_streaming_delivery() {
|
||||
for stream in [None, Some(false), Some(true)] {
|
||||
let mut body = super::request();
|
||||
if let Some(stream) = stream {
|
||||
body.insert("stream".into(), json!(stream));
|
||||
}
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body.insert(
|
||||
"stream_options".into(),
|
||||
json!({"include_usage":true, "include_obfuscation":false}),
|
||||
);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
body["stream_options"]["include_obfuscation"] = json!(true);
|
||||
if stream == Some(true) {
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(
|
||||
error.parameter(),
|
||||
Some("stream_options.include_obfuscation")
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_targets_apply_the_same_common_request_validation() {
|
||||
for (field, value, parameter) in [
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"developer","content":null}]),
|
||||
"messages",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"developer"},{"role":"assistant","audio":{"id":"audio"}}]),
|
||||
"messages[1].audio",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":42}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"user","content":null}]),
|
||||
"messages[1].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"tool","tool_call_id":"c","content":null}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null,"tool_calls":[{}]}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"assistant","content":"ok","refusal":17}]),
|
||||
@@ -114,13 +433,18 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","name":17}]),
|
||||
"messages[0].name",
|
||||
json!([{"role":"assistant","tool_calls":{}}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","tool_calls":[]}]),
|
||||
"messages[0].tool_calls",
|
||||
json!([{"role":"developer","tool_call_id":"c"}]),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","refusal":"declined"}]),
|
||||
"messages[0].refusal",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
@@ -130,8 +454,8 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
("n", json!(2), "n"),
|
||||
(
|
||||
"stream_options",
|
||||
json!({"include_usage":true}),
|
||||
"stream_options",
|
||||
json!({"include_usage":1}),
|
||||
"stream_options.include_usage",
|
||||
),
|
||||
] {
|
||||
let mut body = super::request();
|
||||
@@ -140,11 +464,7 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(expected.parameter(), Some(parameter));
|
||||
for result in [
|
||||
responses::convert_request(&body),
|
||||
messages::convert_request(&body, &Default::default()),
|
||||
genai::convert_request(&body),
|
||||
] {
|
||||
for result in target_requests(&body) {
|
||||
assert_eq!(result.unwrap_err(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,61 @@
|
||||
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤
|
||||
|
||||
use gateway_protocol::http::{
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable,
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, preferred_response_request_id,
|
||||
response_header_is_forwardable,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn response_request_ids_follow_official_header_priority() {
|
||||
let names = [
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"x-ms-request-id",
|
||||
];
|
||||
let mut headers = http::HeaderMap::new();
|
||||
for name in names {
|
||||
headers.insert(name, http::HeaderValue::from_static(name));
|
||||
}
|
||||
headers.insert("cf-ray", http::HeaderValue::from_static("trace-only"));
|
||||
for name in names {
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
Some(name),
|
||||
);
|
||||
headers.remove(name);
|
||||
}
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_request_ids_skip_unusable_first_values_without_rewriting_headers() {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-request-id",
|
||||
http::HeaderValue::from_bytes(b"\xff").unwrap(),
|
||||
);
|
||||
headers.append(
|
||||
"x-request-id",
|
||||
http::HeaderValue::from_static("second-value"),
|
||||
);
|
||||
headers.insert("x-oai-request-id", http::HeaderValue::from_static(" \t "));
|
||||
headers.insert("x-openai-request-id", http::HeaderValue::from_static(""));
|
||||
headers.insert(
|
||||
"x-ms-request-id",
|
||||
http::HeaderValue::from_static(" opaque-id "),
|
||||
);
|
||||
assert_eq!(
|
||||
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
|
||||
Some(" opaque-id "),
|
||||
);
|
||||
assert_eq!(headers["x-request-id"].as_bytes(), b"\xff");
|
||||
assert_eq!(headers.get_all("x-request-id").iter().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
|
||||
for (header, expected) in [
|
||||
|
||||
@@ -775,6 +775,7 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}});
|
||||
body["stop"] = json!(["END", " STOP"]);
|
||||
body["messages"].as_array_mut().unwrap().insert(
|
||||
0,
|
||||
json!({"role":"system","content":"Preserve the caller's project rules."}),
|
||||
@@ -877,6 +878,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
json!([{"text": if streaming { "Apply the caller's project rules." } else { "Preserve the caller's project rules." }}])
|
||||
);
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["stopSequences"],
|
||||
json!(["END", " STOP"])
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
24576
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 额度桶重置后的延迟预热、使用证据复核和持久化领取
|
||||
|
||||
use super::snapshot::BucketUseTime;
|
||||
use super::snapshot::BucketTimestamp;
|
||||
use super::*;
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_core::account::QuotaWarmupStateUpdate;
|
||||
@@ -10,18 +10,21 @@ const RESET_WARMUP_DELAY_SECONDS: i64 = 5 * 60;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct BucketProgress {
|
||||
reset_at: Option<i64>,
|
||||
completed_reset_at: Option<i64>,
|
||||
last_warmup_at: Option<BucketUseTime>,
|
||||
reset_at: Option<BucketTimestamp>,
|
||||
completed_reset_at: Option<BucketTimestamp>,
|
||||
last_warmup_at: Option<BucketTimestamp>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
credit_reset: Option<CreditReset>,
|
||||
retry_at: Option<i64>,
|
||||
// 本登记周期内已观察到用量或触顶;用于被动识别上游提前重置后的归零快照
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
observed_used: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct CreditReset {
|
||||
started_at: DateTime<Utc>,
|
||||
previous_window_end: Option<i64>,
|
||||
previous_window_end: Option<BucketTimestamp>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -55,8 +58,24 @@ impl WarmupProgress {
|
||||
fn reconcile(&mut self, account: &ProviderAccount, snapshot: &CodexAccountQuotaSnapshot) {
|
||||
for window in enabled_windows(account, snapshot) {
|
||||
let progress = self.buckets.entry(window.key().to_owned()).or_default();
|
||||
let observed_reset = window.reset_at().map(|at| at.timestamp());
|
||||
let observed_reset = window.reset_at().map(BucketTimestamp);
|
||||
if let Some(reset) = progress.reset_at {
|
||||
// 上游系统级统一重置或在代理外提前重置不会经过 consume_reset_credit:
|
||||
// 本周期已观察到用量,而新快照在周期到期前显示归零且未触顶,
|
||||
// 说明周期已提前重开,把边界被动改锚到观测时刻,沿用既有延迟预热
|
||||
if progress.credit_reset.is_none()
|
||||
&& progress.observed_used
|
||||
&& window.used_percent() == Some(0.0)
|
||||
&& !window.limit_reached()
|
||||
{
|
||||
let observed_at = DateTime::<Utc>::from(snapshot.observed_at());
|
||||
if observed_at < reset.0 {
|
||||
progress.reset_at = Some(BucketTimestamp(observed_at));
|
||||
progress.retry_at = None;
|
||||
progress.observed_used = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let last_use = snapshot
|
||||
.last_used_at
|
||||
.get(window.source())
|
||||
@@ -67,7 +86,7 @@ impl WarmupProgress {
|
||||
let observed_at = DateTime::<Utc>::from(snapshot.observed_at());
|
||||
let used_after_reset = last_use.is_some_and(|used| match &progress.credit_reset {
|
||||
Some(credit) => used.0 >= credit.started_at,
|
||||
None => used.0.timestamp() >= reset,
|
||||
None => used >= reset,
|
||||
});
|
||||
let previous_end = progress
|
||||
.credit_reset
|
||||
@@ -76,10 +95,14 @@ impl WarmupProgress {
|
||||
.unwrap_or(reset);
|
||||
let newly_used = used_after_reset
|
||||
|| (observed_reset.is_some_and(|next| next > previous_end)
|
||||
&& observed_at.timestamp() >= reset
|
||||
&& observed_at >= reset.0
|
||||
&& window.used_percent().is_some_and(|used| used > 0.0));
|
||||
if newly_used {
|
||||
progress.complete(reset);
|
||||
} else {
|
||||
progress.observed_used = progress.observed_used
|
||||
|| window.limit_reached()
|
||||
|| window.used_percent().is_some_and(|used| used > 0.0);
|
||||
}
|
||||
}
|
||||
// 空闲桶的 resetAt 可能随查询滚动;已登记的本轮边界不能被新查询推迟
|
||||
@@ -91,6 +114,8 @@ impl WarmupProgress {
|
||||
{
|
||||
progress.reset_at = Some(reset);
|
||||
progress.retry_at = None;
|
||||
progress.observed_used =
|
||||
window.limit_reached() || window.used_percent().is_some_and(|used| used > 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,25 +125,30 @@ impl WarmupProgress {
|
||||
account: &ProviderAccount,
|
||||
snapshot: &CodexAccountQuotaSnapshot,
|
||||
started_at: DateTime<Utc>,
|
||||
confirmed_at: i64,
|
||||
confirmed_at: DateTime<Utc>,
|
||||
) -> bool {
|
||||
let mut registered = false;
|
||||
for window in
|
||||
enabled_windows(account, snapshot).filter(|w| w.kind() == CodexQuotaWindowKind::Weekly)
|
||||
{
|
||||
let bucket = self.buckets.entry(window.key().to_owned()).or_default();
|
||||
bucket.reset_at = Some(confirmed_at);
|
||||
bucket.reset_at = Some(BucketTimestamp(confirmed_at));
|
||||
bucket.retry_at = None;
|
||||
bucket.observed_used = false;
|
||||
bucket.credit_reset = Some(CreditReset {
|
||||
started_at,
|
||||
previous_window_end: window.reset_at().map(|at| at.timestamp()),
|
||||
previous_window_end: window.reset_at().map(BucketTimestamp),
|
||||
});
|
||||
registered = true;
|
||||
}
|
||||
registered
|
||||
}
|
||||
|
||||
fn due(&self, account: &ProviderAccount, now: DateTime<Utc>) -> Vec<(String, String, i64)> {
|
||||
fn due(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
now: DateTime<Utc>,
|
||||
) -> Vec<(String, String, BucketTimestamp)> {
|
||||
account
|
||||
.quota_settings()
|
||||
.iter()
|
||||
@@ -126,7 +156,8 @@ impl WarmupProgress {
|
||||
let warmup = settings.warmup.as_ref()?;
|
||||
let progress = self.buckets.get(key)?;
|
||||
let reset = progress.reset_at?;
|
||||
(now.timestamp() >= reset.saturating_add(RESET_WARMUP_DELAY_SECONDS)
|
||||
(now.signed_duration_since(reset.0)
|
||||
>= chrono::Duration::seconds(RESET_WARMUP_DELAY_SECONDS)
|
||||
&& progress
|
||||
.retry_at
|
||||
.is_none_or(|retry| now.timestamp() >= retry)
|
||||
@@ -138,11 +169,12 @@ impl WarmupProgress {
|
||||
}
|
||||
|
||||
impl BucketProgress {
|
||||
fn complete(&mut self, reset: i64) {
|
||||
fn complete(&mut self, reset: BucketTimestamp) {
|
||||
self.completed_reset_at = Some(self.completed_reset_at.map_or(reset, |old| old.max(reset)));
|
||||
self.reset_at = None;
|
||||
self.credit_reset = None;
|
||||
self.retry_at = None;
|
||||
self.observed_used = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,7 +228,7 @@ impl CodexCredentialQuotaService {
|
||||
return Ok(());
|
||||
}
|
||||
let request_id = request_id.to_string();
|
||||
let confirmed_at = Utc::now().timestamp();
|
||||
let confirmed_at = Utc::now();
|
||||
for _ in 0..QUOTA_MERGE_ATTEMPTS {
|
||||
let Some(account) = self.store.get_account(original.id()).await? else {
|
||||
return Ok(());
|
||||
@@ -386,7 +418,7 @@ impl CodexCredentialQuotaService {
|
||||
.buckets
|
||||
.entry(window.key().to_owned())
|
||||
.or_default()
|
||||
.last_warmup_at = Some(BucketUseTime(now));
|
||||
.last_warmup_at = Some(BucketTimestamp(now));
|
||||
}
|
||||
progress.reconcile(account, &snapshot);
|
||||
if self
|
||||
|
||||
@@ -111,11 +111,11 @@ impl CodexQuotaWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// 自然窗口按整秒划界,用卡操作还需区分同一秒内先后的使用
|
||||
/// 额度桶边界与使用时间保留亚秒精度,读取时兼容已有整秒记录
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||
pub(super) struct BucketUseTime(pub(super) DateTime<Utc>);
|
||||
pub(super) struct BucketTimestamp(pub(super) DateTime<Utc>);
|
||||
|
||||
impl<'de> Deserialize<'de> for BucketUseTime {
|
||||
impl<'de> Deserialize<'de> for BucketTimestamp {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
@@ -144,7 +144,7 @@ pub struct CodexAccountQuotaSnapshot {
|
||||
quota: QuotaState,
|
||||
windows: Vec<CodexQuotaWindow>,
|
||||
unconfirmed_limits: BTreeMap<String, f64>,
|
||||
pub(super) last_used_at: BTreeMap<String, BucketUseTime>,
|
||||
pub(super) last_used_at: BTreeMap<String, BucketTimestamp>,
|
||||
pub(super) recovery: Option<QuotaRecovery>,
|
||||
}
|
||||
|
||||
@@ -472,7 +472,7 @@ pub(crate) fn parse_account_quota_snapshot(
|
||||
usage
|
||||
.iter()
|
||||
.filter_map(|(source, at)| {
|
||||
Some((source.clone(), BucketUseTime::deserialize(at).ok()?))
|
||||
Some((source.clone(), BucketTimestamp::deserialize(at).ok()?))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
|
||||
@@ -564,6 +564,7 @@ impl CodexCredentialSelector {
|
||||
err,
|
||||
CredentialSelectionError::CapacityUnavailable { .. }
|
||||
| CredentialSelectionError::NoEligibleCredential
|
||||
| CredentialSelectionError::WebSocketUnavailable { .. }
|
||||
| CredentialSelectionError::QuotaExhausted
|
||||
)
|
||||
},
|
||||
@@ -939,6 +940,7 @@ impl CodexCredentialSelector {
|
||||
_ => None,
|
||||
};
|
||||
let mut catalog_rejected = 0_usize;
|
||||
let mut websocket_rejected = false;
|
||||
let mut native_accounts = BTreeSet::new();
|
||||
for account in accounts {
|
||||
let adapter = if let Some(model) = adapter_model.as_ref() {
|
||||
@@ -1043,14 +1045,22 @@ impl CodexCredentialSelector {
|
||||
(account.revision(), runtime.authentication.api_protocol()),
|
||||
);
|
||||
}
|
||||
if (request.requires_websocket
|
||||
&& runtime.transport == super::ResponsesTransport::Http)
|
||||
|| required_protocol.is_some_and(|protocol| {
|
||||
runtime.authentication.api_protocol() != protocol
|
||||
})
|
||||
if required_protocol
|
||||
.is_some_and(|protocol| runtime.authentication.api_protocol() != protocol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if request.requires_websocket
|
||||
&& runtime.transport == super::ResponsesTransport::Http
|
||||
{
|
||||
// 仅记录基础状态正常的 HTTP 账号,失效或已耗尽账号不能掩盖真实额度失败
|
||||
websocket_rejected |= (diagnostic
|
||||
|| account.status_projection(SystemTime::now(), None).status
|
||||
== AccountStatus::Normal)
|
||||
&& !request.attempt.excluded_accounts().contains(account.id())
|
||||
&& !request.attempt.excludes_proxy(account.outbound_proxy());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
eligible.push(account);
|
||||
}
|
||||
@@ -1475,7 +1485,7 @@ impl CodexCredentialSelector {
|
||||
Err(CredentialSelectionError::CapacityUnavailable {
|
||||
retry_after: shortest_retry,
|
||||
})
|
||||
} else if quota_exhausted {
|
||||
} else if quota_exhausted && !websocket_rejected {
|
||||
Err(CredentialSelectionError::QuotaExhausted)
|
||||
} else if cyber_policy_scope
|
||||
.as_ref()
|
||||
@@ -1496,6 +1506,8 @@ impl CodexCredentialSelector {
|
||||
{
|
||||
// 仅明确的会话策略排除使用此分类,空池、传输和容量失败保持原分类
|
||||
Err(CredentialSelectionError::SessionPolicyRestricted)
|
||||
} else if websocket_rejected {
|
||||
Err(CredentialSelectionError::WebSocketUnavailable { quota_exhausted })
|
||||
} else {
|
||||
Err(CredentialSelectionError::NoEligibleCredential)
|
||||
};
|
||||
@@ -2465,6 +2477,10 @@ pub enum CredentialSelectionError {
|
||||
IneligibleSessionAccountTimeout(&'static str),
|
||||
#[error("no eligible Codex account")]
|
||||
NoEligibleCredential,
|
||||
#[error(
|
||||
"no available WebSocket account; compatible account quota exhausted: {quota_exhausted}"
|
||||
)]
|
||||
WebSocketUnavailable { quota_exhausted: bool },
|
||||
#[error("upstream safety policy temporarily excludes accounts for this session")]
|
||||
SessionPolicyRestricted,
|
||||
#[error("all eligible Codex accounts have exhausted their quota")]
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::*;
|
||||
use crate::transport::protocol::responses::is_replaceable_response_prelude;
|
||||
use gateway_core::error::{ProxyConnectionHint, TransientRetryPolicy};
|
||||
use gateway_protocol::http::preferred_response_request_id;
|
||||
|
||||
/// OpenAI 失败对 Smart 账号分数的结构化 reason 闭集
|
||||
///
|
||||
@@ -731,10 +732,16 @@ pub(super) fn continuation_recovery_error(
|
||||
.map(|response| response.headers().to_vec())
|
||||
.unwrap_or_default();
|
||||
// 流内拒绝没有原始 HTTP 失败响应,仍需把该次失败的关联 ID 交给 HTTP 客户端
|
||||
if !headers.iter().any(|header| {
|
||||
header.name().eq_ignore_ascii_case("x-request-id")
|
||||
|| header.name().eq_ignore_ascii_case("x-oai-request-id")
|
||||
}) && let Some(request_id) = error.upstream_request_id()
|
||||
if preferred_response_request_id(|name| {
|
||||
let header = headers
|
||||
.iter()
|
||||
.find(|header| header.name().eq_ignore_ascii_case(name))?;
|
||||
let value = reqwest::header::HeaderValue::from_bytes(header.value()).ok()?;
|
||||
value.to_str().ok()?;
|
||||
std::str::from_utf8(header.value()).ok()
|
||||
})
|
||||
.is_none()
|
||||
&& let Some(request_id) = error.upstream_request_id()
|
||||
{
|
||||
headers.push(ProviderResponseHeader::new(
|
||||
"x-request-id",
|
||||
|
||||
@@ -863,7 +863,7 @@ impl Provider for CodexProvider {
|
||||
&& codex_guardian_role(payload.body(), payload.context())
|
||||
== Some(CodexGuardianRole::Housekeeper))
|
||||
&& let Some(tier) = fast_policy_tier(
|
||||
context.fast_mode(),
|
||||
context.fast_mode_for_account(lease.account_id(), upstream_model.as_str()),
|
||||
payload.body().get("service_tier").and_then(Value::as_str),
|
||||
|tier| {
|
||||
self.catalog
|
||||
|
||||
@@ -886,6 +886,27 @@ fn selection_failure(error: &CredentialSelectionError) -> ProviderError {
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
),
|
||||
CredentialSelectionError::WebSocketUnavailable { quota_exhausted } => provider_error(
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_diagnostic(
|
||||
ProviderDiagnostic::new(if *quota_exhausted {
|
||||
"WebSocket 账号额度耗尽,HTTP/SSE 账号不符合本次传输要求"
|
||||
} else {
|
||||
"请求需要上游 WebSocket,HTTP/SSE 账号不符合本次传输要求"
|
||||
})
|
||||
.with_classification("account_selection", "websocket_account_unavailable"),
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
if *quota_exhausted {
|
||||
"WebSocket-compatible accounts have exhausted their quota; HTTP/SSE-only accounts cannot serve this request. Enable WebSocket on an available account or use HTTP/SSE in the client."
|
||||
} else {
|
||||
"This request requires an upstream WebSocket, but no compatible account is available. Enable WebSocket on an available account or use HTTP/SSE in the client."
|
||||
},
|
||||
Some("websocket_account_unavailable".to_owned()),
|
||||
None,
|
||||
)),
|
||||
CredentialSelectionError::QuotaExhausted => provider_error(
|
||||
ProviderErrorKind::AccountPoolQuotaExhausted,
|
||||
UpstreamSendState::NotSent,
|
||||
|
||||
@@ -436,7 +436,6 @@ impl CodexBackendClient {
|
||||
.await;
|
||||
let can_reduce_history = self.protocol == OpenAiUpstreamProtocol::Codex
|
||||
&& plugin_payload.is_none()
|
||||
&& self.privacy.is_none()
|
||||
&& requirement == TransportRequirement::NewChain
|
||||
&& request.stream()
|
||||
&& !request.websocket_frame
|
||||
|
||||
@@ -5,25 +5,10 @@ pub(crate) mod evidence;
|
||||
use super::client::CodexClientVisibleUpstreamResponse;
|
||||
use super::protocol::responses::{ResponsesSseFailure, UsageLimitWindow, upstream_error_object};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
|
||||
use reqwest::{StatusCode, header::HeaderMap};
|
||||
use serde_json::Value;
|
||||
|
||||
const UPSTREAM_REQUEST_ID_HEADERS: &[&str] = &[
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"openai-request-id",
|
||||
"request-id",
|
||||
];
|
||||
|
||||
const UPSTREAM_TRACE_HEADERS: &[&str] = &[
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"openai-request-id",
|
||||
"request-id",
|
||||
"cf-ray",
|
||||
];
|
||||
const IDENTITY_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error";
|
||||
const IDENTITY_ERROR_JSON_HEADER: &str = "x-error-json";
|
||||
/// 上游拒绝相对业务 payload 的发送阶段
|
||||
@@ -368,7 +353,7 @@ impl CodexUpstreamDiagnostics {
|
||||
let Ok(name) = reqwest::header::HeaderName::from_bytes(name.as_bytes()) else {
|
||||
continue;
|
||||
};
|
||||
if !UPSTREAM_REQUEST_ID_HEADERS.contains(&name.as_str()) {
|
||||
if !RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
// 与官方 wrapped error 一致,只接受合法 HTTP 标量头;任意对象和数组不作 ID
|
||||
@@ -381,14 +366,18 @@ impl CodexUpstreamDiagnostics {
|
||||
mapped.insert(name, value);
|
||||
}
|
||||
}
|
||||
first_header(&mapped, UPSTREAM_REQUEST_ID_HEADERS)
|
||||
preferred_response_request_id(|name| mapped.get(name)?.to_str().ok())
|
||||
.map(str::trim)
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
pub fn from_headers(status_code: Option<u16>, headers: &HeaderMap) -> Self {
|
||||
Self {
|
||||
headers_observed_at: Some(std::time::SystemTime::now()),
|
||||
status_code,
|
||||
request_id: first_header(headers, UPSTREAM_REQUEST_ID_HEADERS),
|
||||
request_id: preferred_response_request_id(|name| headers.get(name)?.to_str().ok())
|
||||
.map(str::trim)
|
||||
.map(str::to_owned),
|
||||
identity_authorization_error: header_value(
|
||||
headers,
|
||||
IDENTITY_AUTHORIZATION_ERROR_HEADER,
|
||||
@@ -416,13 +405,10 @@ impl CodexUpstreamDiagnostics {
|
||||
}
|
||||
}
|
||||
|
||||
fn first_header(headers: &HeaderMap, names: &[&str]) -> Option<String> {
|
||||
names.iter().find_map(|name| header_value(headers, name))
|
||||
}
|
||||
|
||||
fn trace_headers(headers: &HeaderMap) -> Vec<(String, String)> {
|
||||
UPSTREAM_TRACE_HEADERS
|
||||
RESPONSE_REQUEST_ID_HEADERS
|
||||
.iter()
|
||||
.chain([&"cf-ray"])
|
||||
.filter_map(|name| header_value(headers, name).map(|value| ((*name).to_string(), value)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 验证通用额度桶延迟预热的时间边界、使用证据和重启去重
|
||||
|
||||
use super::*;
|
||||
use gateway_core::account::{OpaqueProviderData, QuotaObservation};
|
||||
use gateway_core::account::{OpaqueProviderData, QuotaObservation, QuotaWarmupStateUpdate};
|
||||
|
||||
async fn setup() -> (
|
||||
Arc<MemoryAccountStore>,
|
||||
@@ -112,7 +112,7 @@ async fn mount_warmup(server: &MockServer, expected: u64) {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_five_minutes_and_claim_survives_service_restart() {
|
||||
async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart() {
|
||||
let (store, server, now, reset) = setup().await;
|
||||
let quota = service(&store, &server);
|
||||
mount_usage(&server, reset + 604800, 0, 1).await;
|
||||
@@ -127,6 +127,30 @@ async fn waits_five_minutes_and_claim_survives_service_restart() {
|
||||
0
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let mut legacy = store
|
||||
.load_quota_warmup_state(&account)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
// 升级前的进度以整秒持久化,新读取器仍须沿用该边界与并发领取约束。
|
||||
legacy.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset);
|
||||
let observed_at = store
|
||||
.get_quotas(std::slice::from_ref(account.id()))
|
||||
.await
|
||||
.unwrap()[0]
|
||||
.observed_at;
|
||||
assert!(
|
||||
store
|
||||
.compare_and_swap_quota_warmup_state(QuotaWarmupStateUpdate {
|
||||
account: &account,
|
||||
expected_version: legacy.version,
|
||||
expected_quota_observed_at: Some(observed_at),
|
||||
data: legacy.data,
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let (one, two) = tokio::join!(
|
||||
quota.execute_bucket_warmup_at(now),
|
||||
quota.execute_bucket_warmup_at(now)
|
||||
@@ -522,3 +546,119 @@ async fn reset_credit_consume_starts_warmup_after_previous_cycle_was_completed()
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn early_reset_after_first_usage_snapshot_warms_once_after_restart() {
|
||||
let (store, server, now, reset) = setup_window(3 * 86400, 90).await;
|
||||
let quota = service(&store, &server);
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap();
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let detected = Utc::now();
|
||||
let observed_at = SystemTime::from(detected);
|
||||
store
|
||||
.compare_and_swap_quota(QuotaObservation {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
quota: OpaqueProviderData::new(usage(reset, 0).as_object().unwrap().clone()),
|
||||
observed_at,
|
||||
state: QuotaState::allowed(observed_at),
|
||||
quota_pause: None,
|
||||
expected_connection: None,
|
||||
plan_type: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let boundary = detected;
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(boundary + chrono::Duration::seconds(299))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
mount_usage(&server, reset + 604800, 0, 1).await;
|
||||
mount_warmup(&server, 1).await;
|
||||
assert_eq!(
|
||||
service(&store, &server)
|
||||
.execute_bucket_warmup_at(boundary + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
service(&store, &server)
|
||||
.execute_bucket_warmup_at(boundary + chrono::Duration::minutes(10))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn early_reset_distinguishes_usage_within_the_same_second() {
|
||||
for used_after_reset in [false, true] {
|
||||
let (store, server, now, reset) = setup_window(3 * 86400, 90).await;
|
||||
let quota = service(&store, &server);
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap();
|
||||
let second = now.timestamp() - 2;
|
||||
let detected = Utc.timestamp_opt(second, 900_000_000).unwrap();
|
||||
let before = Utc.timestamp_opt(second, 100_000_000).unwrap();
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let mut document = usage(reset, 0);
|
||||
document["_cpr_bucket_last_used_at"] = json!({"codex": before});
|
||||
let observe = |document: serde_json::Value, observed: chrono::DateTime<Utc>| {
|
||||
let account = account.clone();
|
||||
let store = store.clone();
|
||||
async move {
|
||||
let observed_at = SystemTime::from(observed);
|
||||
store
|
||||
.compare_and_swap_quota(QuotaObservation {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
quota: OpaqueProviderData::new(document.as_object().unwrap().clone()),
|
||||
observed_at,
|
||||
state: QuotaState::allowed(observed_at),
|
||||
quota_pause: None,
|
||||
expected_connection: None,
|
||||
plan_type: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
};
|
||||
observe(document.clone(), detected).await;
|
||||
quota.execute_bucket_warmup_at(detected).await.unwrap();
|
||||
if used_after_reset {
|
||||
let after = Utc.timestamp_opt(second, 950_000_000).unwrap();
|
||||
document["_cpr_bucket_last_used_at"] = json!({"codex": after});
|
||||
observe(document, after).await;
|
||||
}
|
||||
let restarted = service(&store, &server);
|
||||
let due = detected + chrono::Duration::minutes(5);
|
||||
assert_eq!(
|
||||
restarted
|
||||
.execute_bucket_warmup_at(due - chrono::Duration::milliseconds(1))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
let expected = u64::from(!used_after_reset);
|
||||
mount_usage(&server, reset + 604800, 0, expected).await;
|
||||
mount_warmup(&server, expected).await;
|
||||
assert_eq!(
|
||||
restarted
|
||||
.execute_bucket_warmup_at(due)
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
expected,
|
||||
"used_after_reset={used_after_reset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ fn chat_operation(stream: bool) -> Operation {
|
||||
unreachable!()
|
||||
};
|
||||
let mut body = json!({"model":"gpt-5.4", "stream":stream,
|
||||
"reasoning_effort":"xhigh",
|
||||
"reasoning_effort":"xhigh", "stop":"END",
|
||||
"messages":[{"role":"user","content":"hello"}]});
|
||||
if stream {
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
@@ -293,13 +293,15 @@ async fn chat_reaches_each_selected_protocol_with_target_header_boundaries() {
|
||||
}
|
||||
assert!(terminal_seen);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let headers = &requests
|
||||
let request = requests
|
||||
.iter()
|
||||
.find(|request| request.method == "POST")
|
||||
.unwrap()
|
||||
.headers;
|
||||
.unwrap();
|
||||
let headers = &request.headers;
|
||||
let body: Value = serde_json::from_slice(&request.body).unwrap();
|
||||
assert_eq!(headers.get("x-business-extension").unwrap(), "keep");
|
||||
if target == ApiKeyProtocol::Messages {
|
||||
assert_eq!(body["stop_sequences"], json!(["END"]));
|
||||
for name in [
|
||||
"session-id",
|
||||
"thread-id",
|
||||
@@ -309,7 +311,7 @@ async fn chat_reaches_each_selected_protocol_with_target_header_boundaries() {
|
||||
assert!(!headers.contains_key(name));
|
||||
}
|
||||
} else {
|
||||
let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
|
||||
assert!(body.get("stop_sequences").is_none() && body.get("stop").is_none());
|
||||
assert_eq!(body["reasoning"]["effort"], "xhigh");
|
||||
assert!(body.get("max_output_tokens").is_none());
|
||||
for name in [
|
||||
|
||||
@@ -154,7 +154,7 @@ async fn account_client_preparation_keeps_ca_read_cause_without_exposing_path()
|
||||
assert!(diagnostic.as_str().contains("OS cause:"));
|
||||
assert!(!diagnostic.as_str().contains("PRIVATE_"));
|
||||
let gateway = gateway_core::error::GatewayError::from_provider(&snapshot);
|
||||
assert_eq!(gateway.safe_message(), "Upstream service is unavailable.");
|
||||
assert_eq!(gateway.safe_message(), "Upstream protocol handling failed.");
|
||||
assert_eq!(gateway.diagnostic(), Some(diagnostic));
|
||||
}
|
||||
|
||||
@@ -1660,7 +1660,6 @@ pub(super) fn context_with_middleware(
|
||||
ModelRequestId::new(request_id).expect("request id"),
|
||||
ClientApiKeyId::new("key_openai_contract").expect("client key id"),
|
||||
)
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_middleware(
|
||||
Some(plan),
|
||||
Arc::from([]),
|
||||
@@ -1671,8 +1670,12 @@ pub(super) fn context_with_middleware(
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(30),
|
||||
account_policy(),
|
||||
AccountAttemptContext::new(BTreeSet::new(), None, None)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new(
|
||||
contract_account_scope()
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode_override(Some(fast_mode)),
|
||||
)),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
@@ -1696,14 +1699,23 @@ fn context_with_pricing(
|
||||
fast_mode: FastMode,
|
||||
pricing: gateway_core::metering::PricingOverrides,
|
||||
) -> AttemptContext {
|
||||
context_for_request(
|
||||
AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new(request_id).expect("request id"),
|
||||
ClientApiKeyId::new("key_openai_contract").expect("client key id"),
|
||||
)
|
||||
.with_fast_mode(fast_mode)
|
||||
.with_pricing(Arc::new(pricing))
|
||||
.with_request_location(Some(global_request_location())),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(30),
|
||||
account_policy(),
|
||||
AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new(
|
||||
contract_account_scope()
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode_override(Some(fast_mode)),
|
||||
)),
|
||||
None,
|
||||
cancellation,
|
||||
)
|
||||
}
|
||||
@@ -8714,6 +8726,77 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
|
||||
let original = operation.clone();
|
||||
let provider = provider_with_catalog_and_base_url(&store, base_url).await;
|
||||
let catalog = provider.query_model_capabilities().await.unwrap();
|
||||
let groups: Vec<_> = (1..=2)
|
||||
.map(|id| {
|
||||
gateway_core::routing::AccountGroupId::new(format!("grp_{id:032x}")).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let provider_kind = ProviderKind::new("openai").unwrap();
|
||||
// 同一个 Key 绑定两个互不相交的账号组,另一个组不能改写本次账号的档位
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(
|
||||
["acct_provider_contract", other]
|
||||
.into_iter()
|
||||
.zip(&groups)
|
||||
.map(|(id, group)| {
|
||||
(
|
||||
ProviderAccountId::new(id).unwrap(),
|
||||
RuntimeAccount::new(
|
||||
provider_kind.clone(),
|
||||
[group.clone()].into(),
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.with_group_fast_modes(
|
||||
[
|
||||
(groups[0].clone(), fast_mode),
|
||||
(
|
||||
groups[1].clone(),
|
||||
if fast_mode == FastMode::Disabled {
|
||||
FastMode::Enabled
|
||||
} else {
|
||||
FastMode::Disabled
|
||||
},
|
||||
),
|
||||
]
|
||||
.into(),
|
||||
),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
groups
|
||||
.iter()
|
||||
.map(|id| {
|
||||
gateway_core::routing::RoutingGroupSnapshot::new(
|
||||
id.clone(),
|
||||
id.to_string(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
groups.into_iter().collect(),
|
||||
[provider_kind].into(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let context = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_service_tier").unwrap(),
|
||||
ClientApiKeyId::new("key_openai_contract").unwrap(),
|
||||
),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(30),
|
||||
account_policy(),
|
||||
AccountAttemptContext::new(
|
||||
BTreeSet::new(),
|
||||
Some(ProviderAccountId::new("acct_provider_contract").unwrap()),
|
||||
None,
|
||||
)
|
||||
.with_account_scope(scope),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let mut stream = provider
|
||||
.execute(
|
||||
planned_request_with_presentation(
|
||||
@@ -8722,11 +8805,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
|
||||
"gpt-5.4",
|
||||
catalog[0].presentation().cloned(),
|
||||
),
|
||||
context_with_fast_policy(
|
||||
"req_service_tier",
|
||||
CancellationToken::new(),
|
||||
fast_mode,
|
||||
),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.expect("provider stream");
|
||||
@@ -11555,12 +11634,23 @@ async fn assert_error_body_read_failure(image: bool) {
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_failure_headers_override_opening_id_without_changing_raw_events() {
|
||||
assert_websocket_failure_headers(
|
||||
json!({"X-Request-Id": "req-current-error", "authorization": "synthetic-private-token"}),
|
||||
Some("req-current-error"),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
for (headers, expected) in [
|
||||
(
|
||||
json!({"X-Request-Id": "req-current-error", "authorization": "synthetic-private-token"}),
|
||||
"req-current-error",
|
||||
),
|
||||
(
|
||||
json!({"x-request-id": "", "x-oai-request-id": "é", "X-OpenAI-Request-ID": "req-openai", "x-ms-request-id": "req-ms"}),
|
||||
"req-openai",
|
||||
),
|
||||
(
|
||||
json!({"x-openai-request-id": " ", "X-Ms-Request-Id": "req-ms"}),
|
||||
"req-ms",
|
||||
),
|
||||
(json!({"x-ms-request-id": 123}), "123"),
|
||||
] {
|
||||
assert_websocket_failure_headers(headers, Some(expected), false).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -11570,6 +11660,7 @@ async fn websocket_failure_without_valid_headers_does_not_claim_opening_request_
|
||||
json!({}),
|
||||
json!({"x-request-id": " "}),
|
||||
json!({"x-request-id": ["invalid"], "x-oai-request-id": "\r\ninvalid"}),
|
||||
json!({"x-openai-request-id": {"invalid": true}, "x-ms-request-id": "é"}),
|
||||
] {
|
||||
assert_websocket_failure_headers(headers, None, false).await;
|
||||
}
|
||||
@@ -11577,12 +11668,14 @@ async fn websocket_failure_without_valid_headers_does_not_claim_opening_request_
|
||||
|
||||
#[tokio::test]
|
||||
async fn reused_websocket_response_failed_uses_current_request_id() {
|
||||
assert_websocket_failure_headers(
|
||||
json!({"x-request-id": "", "X-Oai-Request-Id": "req-reused-error"}),
|
||||
Some("req-reused-error"),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
for name in ["X-Oai-Request-Id", "X-OpenAI-Request-ID", "X-Ms-Request-Id"] {
|
||||
assert_websocket_failure_headers(
|
||||
json!({"x-request-id": "", (name): "req-reused-error"}),
|
||||
Some("req-reused-error"),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_websocket_failure_headers(headers: Value, request_id: Option<&str>, reuse: bool) {
|
||||
@@ -12541,14 +12634,14 @@ fn quota_continuation_operation(use_websocket: bool) -> Operation {
|
||||
#[tokio::test]
|
||||
async fn quota_continuation_opening_rejection_projects_replay_without_losing_upstream_facts() {
|
||||
for use_websocket in [false, true] {
|
||||
for (status, code, projects_replay) in [
|
||||
(429, "usage_limit_reached", true),
|
||||
(429, "project_spend_limit_exceeded", false),
|
||||
(402, "insufficient_quota", true),
|
||||
(429, "quota_exceeded", false),
|
||||
(429, "rate_limit_exceeded", false),
|
||||
(429, "slow_down", false),
|
||||
(429, "unknown_error", false),
|
||||
for (status, code, projects_replay, id_header) in [
|
||||
(429, "usage_limit_reached", true, "x-ms-request-id"),
|
||||
(429, "project_spend_limit_exceeded", false, "x-request-id"),
|
||||
(402, "insufficient_quota", true, "x-openai-request-id"),
|
||||
(429, "quota_exceeded", false, "x-request-id"),
|
||||
(429, "rate_limit_exceeded", false, "x-request-id"),
|
||||
(429, "slow_down", false, "x-request-id"),
|
||||
(429, "unknown_error", false, "x-request-id"),
|
||||
] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_provider_contract").await;
|
||||
@@ -12561,7 +12654,7 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
|
||||
ResponseTemplate::new(status)
|
||||
.insert_header("retry-after", "129600")
|
||||
.insert_header("retry-after-ms", "129600123")
|
||||
.insert_header("x-request-id", "req-upstream-quota")
|
||||
.insert_header(id_header, "req-upstream-quota")
|
||||
.set_body_json(&original),
|
||||
)
|
||||
.expect(1)
|
||||
@@ -12614,9 +12707,19 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
|
||||
response
|
||||
.headers()
|
||||
.iter()
|
||||
.any(|header| header.name() == "x-request-id"
|
||||
.any(|header| header.name() == id_header
|
||||
&& header.value().as_ref() == b"req-upstream-quota")
|
||||
);
|
||||
assert_eq!(
|
||||
error.upstream_request_id().unwrap().as_str(),
|
||||
"req-upstream-quota"
|
||||
);
|
||||
assert!(
|
||||
!response
|
||||
.headers()
|
||||
.iter()
|
||||
.any(|header| header.name() == "x-request-id")
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.account("acct_provider_contract")
|
||||
@@ -13303,8 +13406,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new(format!("req_fast_turn_{index}")).unwrap(),
|
||||
key,
|
||||
)
|
||||
.with_fast_mode(fast_mode),
|
||||
),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(30),
|
||||
account_policy(),
|
||||
@@ -13313,7 +13415,12 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
|
||||
None,
|
||||
Some(ProviderAccountStateOwner::new(provider_kind, account)),
|
||||
)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
.with_account_scope(Arc::new(
|
||||
contract_account_scope()
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode_override(Some(fast_mode)),
|
||||
)),
|
||||
binding,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
@@ -13451,43 +13558,78 @@ async fn oauth_http_transport_rejects_websocket_only_warmup_without_sending() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oauth_http_transport_rejects_downstream_websocket_chain_without_sending() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_provider_contract").await;
|
||||
store.set_oauth_transport(
|
||||
"acct_provider_contract",
|
||||
provider_openai::credential::ResponsesTransport::Http,
|
||||
);
|
||||
let upstream = MockServer::start().await;
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
"openai",
|
||||
json!({"model":"gpt-5.4", "input":"hello", "store":false, "stream":true})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(Map::from_iter([
|
||||
("use_websocket".to_owned(), json!(true)),
|
||||
(
|
||||
"downstream_websocket_connection_id".to_owned(),
|
||||
json!("client-connection"),
|
||||
),
|
||||
])),
|
||||
));
|
||||
let result = provider_with_base_url(&store, upstream.uri())
|
||||
.execute(
|
||||
planned_request("openai", operation),
|
||||
context("req_oauth_http_ws_chain", CancellationToken::new()),
|
||||
)
|
||||
.await;
|
||||
let Err(error) = result else {
|
||||
panic!("connection-local chain needs an upstream WebSocket")
|
||||
};
|
||||
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
async fn websocket_selection_distinguishes_http_only_accounts_from_exhausted_quota() {
|
||||
for (http_enabled, http_exhausted, with_exhausted_ws) in [
|
||||
(true, false, false),
|
||||
(true, false, true),
|
||||
(true, true, true),
|
||||
(false, false, true),
|
||||
] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account_with_enabled(&store, "acct_provider_contract", http_enabled).await;
|
||||
store.set_oauth_transport(
|
||||
"acct_provider_contract",
|
||||
provider_openai::credential::ResponsesTransport::Http,
|
||||
);
|
||||
if http_exhausted {
|
||||
exhaust_account_quota(&store, "acct_provider_contract").await;
|
||||
}
|
||||
if with_exhausted_ws {
|
||||
create_account(&store, "acct_scope_new").await;
|
||||
exhaust_account_quota(&store, "acct_scope_new").await;
|
||||
}
|
||||
let upstream = MockServer::start().await;
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
"openai",
|
||||
json!({"model":"gpt-5.4", "input":"hello", "store":false, "stream":true})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(Map::from_iter([
|
||||
("use_websocket".to_owned(), json!(true)),
|
||||
(
|
||||
"downstream_websocket_connection_id".to_owned(),
|
||||
json!("client-connection"),
|
||||
),
|
||||
])),
|
||||
));
|
||||
let result = provider_with_base_url(&store, upstream.uri())
|
||||
.execute(
|
||||
planned_request("openai", operation),
|
||||
context("req_oauth_http_ws_chain", CancellationToken::new()),
|
||||
)
|
||||
.await;
|
||||
let Err(error) = result else {
|
||||
panic!("connection-local chain needs an upstream WebSocket")
|
||||
};
|
||||
if http_enabled && !http_exhausted {
|
||||
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount);
|
||||
let gateway = gateway_core::error::GatewayError::from_provider(&error);
|
||||
assert_eq!(
|
||||
gateway.client_error_code(),
|
||||
Some("websocket_account_unavailable")
|
||||
);
|
||||
assert!(gateway.client_message().contains("HTTP/SSE"));
|
||||
assert_eq!(
|
||||
gateway.client_message().contains("exhausted their quota"),
|
||||
with_exhausted_ws
|
||||
);
|
||||
assert_eq!(
|
||||
gateway
|
||||
.diagnostic()
|
||||
.and_then(gateway_core::error::ProviderDiagnostic::code),
|
||||
Some("websocket_account_unavailable")
|
||||
);
|
||||
} else {
|
||||
assert_eq!(error.kind(), ProviderErrorKind::AccountPoolQuotaExhausted);
|
||||
assert!(error.client_visible_upstream_error().is_none());
|
||||
}
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -255,6 +255,161 @@ async fn privacy_workspace_alias_matches_websocket_opening_and_reused_frames() {
|
||||
captured.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn privacy_history_matching_uses_the_sanitized_request() {
|
||||
for rewrite_body in [false, true] {
|
||||
let turns = if rewrite_body { 4 } else { 2 };
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_provider_contract").await;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let output = json!({"type":"message","id":"msg_workspace","role":"assistant",
|
||||
"status":"completed","content":[{"type":"output_text","text":"ok"}]});
|
||||
let server_output = output.clone();
|
||||
let captured = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut metadata = String::new();
|
||||
let mut socket =
|
||||
crate::transport::accept_codex_test_websocket_with(stream, |request, _| {
|
||||
if rewrite_body {
|
||||
assert_eq!(
|
||||
request.headers()["authorization"],
|
||||
"Bearer configured-token"
|
||||
);
|
||||
}
|
||||
metadata = request.headers()["x-codex-turn-metadata"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
})
|
||||
.await;
|
||||
let mut frames = Vec::new();
|
||||
for n in 0..turns {
|
||||
let frame = timeout(Duration::from_secs(10), socket.next())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.into_text()
|
||||
.unwrap();
|
||||
frames.push(serde_json::from_str::<Value>(&frame).unwrap());
|
||||
let mut output = server_output.clone();
|
||||
output["id"] = json!(format!("msg_workspace_{n}"));
|
||||
let completed = json!({"type":"response.completed","response":{
|
||||
"id":format!("resp_workspace_{n}"),"model":"gpt-5.4",
|
||||
"status":"completed","output":[output]
|
||||
}});
|
||||
socket
|
||||
.send(Message::Text(completed.to_string().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
(metadata, frames)
|
||||
});
|
||||
let provider = provider_with_base_url(&store, format!("http://{address}"));
|
||||
let mut config = workspace_policy();
|
||||
if rewrite_body {
|
||||
let mut rewrite = rule(
|
||||
PrivacyScope::RequestBody,
|
||||
"$.input[*].content[*].text",
|
||||
PrivacyAction::RegexReplace,
|
||||
);
|
||||
rewrite.id = "rewrite-input".into();
|
||||
rewrite.steps[0].pattern = Some("hello".into());
|
||||
rewrite.steps[0].replacement = "hellohello".into();
|
||||
config.rules.push(rewrite);
|
||||
let mut header = rule(
|
||||
PrivacyScope::RequestHeader,
|
||||
"authorization",
|
||||
PrivacyAction::SetValue,
|
||||
);
|
||||
header.id = "rewrite-header".into();
|
||||
header.steps[0].value = json!("Bearer configured-token");
|
||||
config.rules.push(header);
|
||||
}
|
||||
let mut history = vec![
|
||||
json!({"type":"message","role":"user","content":[{
|
||||
"type":"input_text","text":"read /Users/alex/projects/private/note.txt"
|
||||
}]}),
|
||||
json!({"type":"message","role":"user","content":[{
|
||||
"type":"input_text","text":"hello"
|
||||
}]}),
|
||||
];
|
||||
let next = json!({"type":"message","role":"user","content":[{
|
||||
"type":"input_text","text":"continue hello"
|
||||
}]});
|
||||
for n in 0..turns {
|
||||
if n > 0 {
|
||||
let mut previous = output.clone();
|
||||
previous["id"] = json!(format!("msg_workspace_{}", n - 1));
|
||||
history.extend([previous, next.clone()]);
|
||||
}
|
||||
if rewrite_body && n == 2 {
|
||||
config.rules[1].steps[0].replacement = "greetings".into();
|
||||
}
|
||||
let Operation::Generate(original) =
|
||||
workspace_operation("workspace-history", "acct_provider_contract")
|
||||
else {
|
||||
unreachable!();
|
||||
};
|
||||
let mut body = original.protocol_payload().body().clone();
|
||||
body.insert("input".into(), json!(history));
|
||||
body.insert("stream".into(), json!(true));
|
||||
let request = GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body)
|
||||
.unwrap()
|
||||
.with_context(original.protocol_payload().context().clone()),
|
||||
)
|
||||
.with_provider_session_state(
|
||||
original.provider_session_state("openai").unwrap().clone(),
|
||||
);
|
||||
let mut stream = provider
|
||||
.clone()
|
||||
.execute(
|
||||
planned_request("openai", Operation::Generate(request)),
|
||||
privacy_context(&config, false),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
timeout(Duration::from_secs(15), async {
|
||||
while let Some(event) = stream.next().await {
|
||||
event.unwrap();
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let (metadata, frames) = captured.await.unwrap();
|
||||
assert_workspace_alias(&metadata, &frames[0]);
|
||||
assert!(
|
||||
frames
|
||||
.iter()
|
||||
.all(|frame| frame["client_metadata"]["x-codex-turn-metadata"]
|
||||
== frames[0]["client_metadata"]["x-codex-turn-metadata"])
|
||||
);
|
||||
assert!(frames[0].get("previous_response_id").is_none());
|
||||
assert_eq!(frames[1]["previous_response_id"], "resp_workspace_0");
|
||||
let mut expected_next = next.clone();
|
||||
if rewrite_body {
|
||||
assert_eq!(frames[0]["input"][1]["content"][0]["text"], "hellohello");
|
||||
expected_next["content"][0]["text"] = json!("continue hellohello");
|
||||
}
|
||||
assert_eq!(frames[1]["input"], json!([expected_next]));
|
||||
if rewrite_body {
|
||||
assert!(frames[2].get("previous_response_id").is_none());
|
||||
let mut expected_full = history[..6].to_vec();
|
||||
expected_full[1]["content"][0]["text"] = json!("greetings");
|
||||
for index in [3, 5] {
|
||||
expected_full[index]["content"][0]["text"] = json!("continue greetings");
|
||||
}
|
||||
assert_eq!(frames[2]["input"], json!(expected_full));
|
||||
assert_eq!(frames[3]["previous_response_id"], "resp_workspace_2");
|
||||
expected_next["content"][0]["text"] = json!("continue greetings");
|
||||
assert_eq!(frames[3]["input"], json!([expected_next]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_metadata_filtered(raw: &str, client_copy: bool) {
|
||||
let metadata: Value = serde_json::from_str(raw).unwrap();
|
||||
assert!(metadata.get("workspaces").is_none());
|
||||
|
||||
@@ -855,7 +855,7 @@ async fn child_queue_timeout_does_not_rebind_or_allow_provider_fallback() {
|
||||
assert_eq!(error.kind(), ProviderErrorKind::ConcurrencyQueueTimeout);
|
||||
assert_eq!(
|
||||
gateway_core::error::GatewayError::from_provider(&error).client_message(),
|
||||
"The request timed out in the gateway queue."
|
||||
"Timed out waiting for available concurrency in the gateway."
|
||||
);
|
||||
assert!(error.retry_is_prohibited());
|
||||
assert_eq!(affinity.binding_count(), 1);
|
||||
|
||||
@@ -235,7 +235,13 @@ impl gateway_core::engine::upstream_adapter::UpstreamAdapter for AdapterProbe {
|
||||
Some("chatgpt-acct_provider_contract".as_bytes().to_vec())
|
||||
);
|
||||
assert!(header("cookie").is_none());
|
||||
assert_eq!(invocation.context.fast_mode(), FastMode::Disabled);
|
||||
assert_eq!(
|
||||
invocation.context.fast_mode_for_account(
|
||||
invocation.account.account_id(),
|
||||
invocation.metadata.upstream_model().unwrap().as_str(),
|
||||
),
|
||||
FastMode::Disabled,
|
||||
);
|
||||
let Operation::Generate(generate) = &invocation.operation else {
|
||||
panic!("adapter must receive the original operation kind");
|
||||
};
|
||||
@@ -304,7 +310,6 @@ async fn upstream_adapter_reuses_selected_native_account_inside_attempt_onion_an
|
||||
ModelRequestId::new("req_adapter_native").unwrap(),
|
||||
ClientApiKeyId::new("key_openai_contract").unwrap(),
|
||||
)
|
||||
.with_fast_mode(FastMode::Disabled)
|
||||
.with_upstream_adapters(Some(
|
||||
gateway_core::engine::upstream_adapter::FrozenUpstreamAdapterPlan::new(
|
||||
Arc::new(AdapterProbe {
|
||||
@@ -322,8 +327,12 @@ async fn upstream_adapter_reuses_selected_native_account_inside_attempt_onion_an
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
account_policy(),
|
||||
AccountAttemptContext::new(BTreeSet::new(), None, None)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new(
|
||||
contract_account_scope()
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_fast_mode_override(Some(FastMode::Disabled)),
|
||||
)),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
|
||||
@@ -255,13 +255,29 @@ fn diagnostics_should_not_treat_cf_ray_as_a_request_id() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_should_accept_the_oai_request_id_header() {
|
||||
fn diagnostics_should_prefer_official_request_ids_and_preserve_all_trace_aliases() {
|
||||
let names = [
|
||||
"x-request-id",
|
||||
"x-oai-request-id",
|
||||
"x-openai-request-id",
|
||||
"x-ms-request-id",
|
||||
];
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("x-oai-request-id", HeaderValue::from_static("oai_req_1"));
|
||||
|
||||
for name in names {
|
||||
headers.insert(name, HeaderValue::from_static(name));
|
||||
}
|
||||
for (index, name) in names.iter().enumerate() {
|
||||
let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(500), &headers);
|
||||
assert_eq!(diagnostics.request_id.as_deref(), Some(*name));
|
||||
for remaining in &names[index..] {
|
||||
assert_eq!(trace_header(&diagnostics, remaining), Some(*remaining));
|
||||
}
|
||||
headers.insert(*name, HeaderValue::from_static(" \t "));
|
||||
}
|
||||
headers.insert("x-request-id", HeaderValue::from_bytes(b"\xff").unwrap());
|
||||
headers.insert("x-ms-request-id", HeaderValue::from_static("req_ms"));
|
||||
let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(500), &headers);
|
||||
|
||||
assert_eq!(diagnostics.request_id.as_deref(), Some("oai_req_1"));
|
||||
assert_eq!(diagnostics.request_id.as_deref(), Some("req_ms"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+3
-1
@@ -1001,9 +1001,11 @@ alpha、beta、rc、exp 在 GitHub 标记为 Pre-release,不覆盖 GitHub Late
|
||||
|
||||
在线更新要求官方构建且起始版本不低于 **v3.18.1**,版本选择遵循上述规则;源码等非官方构建返回不支持原因,不提供可用更新。
|
||||
不满足在线更新条件时,使用完整发行包或镜像[手动部署](#镜像升级与源码构建)。
|
||||
点击「下载更新」后,操作日志显示下载、校验与安装过程,完成后显示「待重启」及待生效版本。点击「立即重启」后才使用新程序。
|
||||
点击「下载更新」后,操作日志显示下载、校验与安装过程,完成后显示「待重启」及待生效版本。点击「重启服务」并确认后才使用新程序。
|
||||
「当前版本」表示正在运行的版本,「通道最新」显示所选通道已发布的版本。通道版本较低时仍显示其版本号,并提示无可用更新
|
||||
|
||||
启用在线重启的部署,在没有更新时也可点击「检查更新」左侧的「重启服务」。确认框提示请求中断影响,有不兼容插件时同时展示清单;取消不执行重启。服务恢复后页面自动刷新,未启用在线重启时按钮不可用
|
||||
|
||||
手动更换镜像或程序后,更新器会核对安装文件并校准历史状态,不以旧成功记录推断需要重启。
|
||||
运行期间检测到外部文件变动或文件缺失时会报告异常,需要核对完整发行包并重启服务后再检查。
|
||||
回滚入口只接受与记录指纹一致的完整备份;缺少指纹,或备份被替换、丢失时,不提供在线回滚,
|
||||
|
||||
+34
-19
@@ -328,18 +328,19 @@ print(completion.choices[0].message.content)
|
||||
| 字段 | 支持与映射 |
|
||||
| --- | --- |
|
||||
| `messages[].role` | `system`、`developer`、`user`、`assistant`、`tool`,保持顺序;assistant 文本历史转为 `output_text` |
|
||||
| `messages[].content` | 字符串或内容块数组;user 和 tool 可包含图片、文件与音频,assistant 支持文本与拒绝内容 |
|
||||
| `messages[].content` | 字符串或内容块数组。所有角色的 `text`、`input_text`、`output_text` 块均将显式 `"text": null` 按空字符串处理。缺少 `text` 或传入其他非字符串值时返回 `400`。user 和 tool 可包含图片、文件与音频,assistant 支持文本与拒绝内容 |
|
||||
| `system`、`developer`、`assistant` 的空正文 | 正文缺省、为 `null` 或 `""` 时省略。数组中移除没有附加信息的空文本块,保留空白字符和带缓存断点的块。数组为空时仍转换 assistant 的工具调用和拒绝内容。全部消息均为空占位时返回 `400` |
|
||||
| `image_url` 内容块 | HTTP(S) URL 或非空 `data:image/...;base64,...`,保留 `detail`,网关不代取图片 |
|
||||
| `file` 内容块 | `file.file_id`、`file.file_data`、`file.file_url` 至少提供一种,保留可选 `filename`;URL 和非 PDF 文件为网关的 Responses 扩展,实际支持由上游判断 |
|
||||
| `input_audio` 内容块 | Chat 的 `data` 和 `format` 转为 Responses `audio_url` data URL;原生音频引用与 `input_text`、`input_image`、`input_file` 内容块也可携带 |
|
||||
| `messages[].refusal`、assistant 的 `refusal` 内容块 | 保留拒绝历史;assistant 同时有工具调用或拒绝内容时,`content` 可省略或为 `null` |
|
||||
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果;保留 ID、参数或输入字符串,不解析或执行工具;custom 结果须携带前序调用历史 |
|
||||
| `messages[].name` | tool 消息的工具名随结果携带;其他角色的名称作为辅助信息忽略 |
|
||||
| `tools` | 展开 function/custom 定义,保留 schema、format 及原生工具对象;function 的 `strict` 省略或 `null` 时使用 `false` |
|
||||
| `messages[].refusal`、assistant 的 `refusal` 内容块 | 保留 assistant 拒绝历史,各角色消息的 `refusal: ""` 按缺省处理 |
|
||||
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果,保留 ID、参数或输入字符串。空调用列表按缺省处理。tool 必须携带调用 ID 和结果,其他角色忽略空 ID。custom 结果须携带前序调用历史 |
|
||||
| `messages[].name` | Responses 将 tool 消息的非空字符串名称随结果携带。Messages 和 GenAI 通过调用 ID 匹配历史。其他角色的名称作为辅助信息忽略 |
|
||||
| `tools` | 展开 function/custom 定义,保留 schema、format 及原生工具对象。function 的 `parameters: null` 按省略处理,`strict` 省略或为 `null` 时使用 `false` |
|
||||
| `tool_choice`、`parallel_tool_calls` | 展开指定 function/custom 和 `allowed_tools` 选择;原生选择与并行布尔值交给上游 |
|
||||
| `web_search_options` | `{}` 即要求上游执行 `web_search`;支持 `search_context_size` 与 `user_location.approximate` |
|
||||
| `response_format` | 映射到 `text.format`,保留 JSON Schema;未知格式交给上游 |
|
||||
| `reasoning_effort`、`verbosity` | 覆盖 `reasoning.effort`、`text.verbosity`,不固定枚举档位 |
|
||||
| `response_format` | 非 `null` 时优先于 `text.format`,保留 JSON Schema;未知格式交给 Responses 上游 |
|
||||
| `reasoning_effort`、`verbosity` | 非 `null` 时分别覆盖 `reasoning.effort`、`text.verbosity`,取值范围由 Responses 上游决定 |
|
||||
| `max_completion_tokens`、`max_tokens`、`max_output_tokens` | 映射到 `max_output_tokens`,按本行从左到右的顺序优先 |
|
||||
| `temperature`、`top_p` | 原值进入 Provider;是否生效见下文正文兼容规则 |
|
||||
| `user`、`safety_identifier`、`service_tier`、`prompt_cache_key`、`prompt_cache_retention` | 同语义字段保留原值 |
|
||||
@@ -348,8 +349,8 @@ print(completion.choices[0].message.content)
|
||||
| `logprobs`、`top_logprobs` | `logprobs: true` 请求输出文本 logprobs,并携带 `top_logprobs`;返回值位于 Chat 的 `choices[].logprobs` |
|
||||
| 内容块的 `prompt_cache_breakpoint` | 对象原样携带;assistant 输出消息不支持此选项 |
|
||||
|
||||
可选映射参数为 `null` 时按未提供处理。`stop`、`seed`、`frequency_penalty`、`presence_penalty`、
|
||||
`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。
|
||||
可选映射参数为 `null` 时按未提供处理。`stop` 的字符串或字符串数组在 Messages 中映射为 `stop_sequences`,在 GenAI 中映射为 `generationConfig.stopSequences`。空数组按省略处理,Responses 忽略此参数。
|
||||
`seed`、`frequency_penalty`、`presence_penalty`、`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。
|
||||
消息的 `reasoning_content` 和 `reasoning` 作为辅助历史忽略,不转为用户正文
|
||||
|
||||
`n`、`store`、`background`、`modalities` 和 `functions` 可省略或为 `null`。非空值仅接受 `n: 1`、`store: false`、`background: false`、`modalities: ["text"]` 和 `functions: []`。
|
||||
@@ -364,7 +365,7 @@ Messages 目标直接生成 `system`、`messages`、`tool_use`/`tool_result`
|
||||
`service_tier: priority` 映射为 `speed: fast` 并补充目标 beta,`default` 映射为 `standard_only`;不代表两种上游有相同的服务承诺
|
||||
|
||||
GenAI 目标直接生成 `systemInstruction`、`contents`、`functionCall`/`functionResponse` 和 `generationConfig`。
|
||||
两个目标都校验工具调用与结果的配对;custom 工具以单个字符串输入包装成函数,并在 Chat 回程还原。
|
||||
两个目标都校验工具调用与结果的配对。函数省略参数定义时使用空对象 schema。custom 工具以单个字符串输入包装成函数,并在 Chat 回程还原。
|
||||
Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.type: text`;grammar 等受约束格式返回 `400`,`param` 指向原始格式字段。
|
||||
多模态字段按目标能力映射,不支持的内容或声明返回字段错误,不转成另一平台协议重试
|
||||
|
||||
@@ -380,9 +381,9 @@ Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.ty
|
||||
索引对应合并后的消息正文。流式结果保留正文中的行内链接,并在结束前通过 `delta.annotations` 交付结构化引用,
|
||||
索引对应实际交付的合并正文
|
||||
|
||||
`stream_options` 仅在 `stream: true` 时可提供,
|
||||
`include_usage: true` 在完整上游用量可用时于结束前追加 `choices: []` 的用量块,其余块的 `usage` 为 `null`。
|
||||
未提供完整用量时不补造 Token 数;缺省不启用流长度混淆,`include_obfuscation: true` 不受支持,`false` 可接受
|
||||
`stream_options` 仅在 `stream: true` 时生效,非流式请求也可携带该对象。
|
||||
流式请求设置 `include_usage: true` 时,网关在完整上游用量可用时于结束前追加 `choices: []` 的用量块,其余块的 `usage` 为 `null`。
|
||||
未提供完整用量时不补造 Token 数。流式请求支持省略 `include_obfuscation` 或设为 `false`,设为 `true` 时返回 `400`
|
||||
|
||||
响应对象的额外普通属性、非必要事件不影响已有内容映射;无法表达的业务输出、缺少必要终态或终态冲突会失败,
|
||||
不补造成功终态。SSE 已开始后通过 `data: {"error": ...}` 交付错误,再以 `[DONE]` 结束,
|
||||
@@ -666,7 +667,7 @@ Responses WebSocket 接受文本消息,`response.create` 在同一连接串行
|
||||
| WS → SSE | 通常保留下游 WS。需要完整重放的 OpenAI 大包回退按下述规则重连 |
|
||||
| WS → WS | 保留当前绑定的上游 WS,支持下一轮续接 |
|
||||
|
||||
Codex OAuth 的 SSE 客户端可以每轮提交完整历史。复用同一上游 WS 时,若同一 Client Key 的请求配置和历史前缀匹配上一轮已完成的输入、输出,网关使用 `previous_response_id` 和新增输入续接。换连接或历史不匹配时发送本次完整输入。此优化用于 `store=false` 的生成请求;显式续接、出站插件接管的帧和启用隐私规则的请求沿用各自的传输合同
|
||||
Codex OAuth 的 SSE 客户端可以每轮提交完整历史。网关先执行隐私规则,再用处理后的内容匹配历史。复用同一上游 WS 时,若同一 Client Key 的请求配置和历史前缀匹配上一轮已完成的输入、输出,网关使用 `previous_response_id` 和新增输入续接。换连接或历史不匹配时发送本次完整输入。此优化用于 `store=false` 的生成请求;显式续接和出站插件接管的帧沿用各自的传输合同
|
||||
|
||||
活跃客户端 WS 的绑定不受普通空闲回收期限约束;上游 Close(不限关闭码)、EOF、传输读写失败、总寿命到期或连接被回收仍可能使连接内续接失效,
|
||||
网关在收到绑定上游的失效通知且下游空闲时,以关闭码 1000 要求客户端重连并发送完整输入。
|
||||
@@ -700,6 +701,9 @@ OAuth 账号默认 `prefer_websocket`,客户端使用 HTTP/SSE 时仍可能选
|
||||
可将账号上游传输方式设为 `http`,固定使用 HTTP/SSE。Responses API Key 账号默认使用 HTTP/SSE,
|
||||
也可配置 `prefer_websocket`;Messages API Key 账号只支持 `http`。
|
||||
OpenAI 的协议预热、依赖 WS 的非持久化新链和连接内续接要求账号支持上游 WS。
|
||||
`503 websocket_account_unavailable` 表示无法选出可用的 WS 账号,而授权范围内仍有基础状态正常的
|
||||
HTTP/SSE 账号被传输要求排除;可将账号上游传输改为 WS,或将客户端改为 HTTP/SSE。
|
||||
若兼容 WS 的账号均已耗尽额度,提示同时保留该原因,不将混合原因简化为整个账号池额度耗尽。
|
||||
HTTP 入站的 Codex 压缩请求未显式指定 `use_websocket: true` 且不依赖 WS 时,保留上游 HTTP/SSE;
|
||||
压缩根据 turn metadata 中的 `request_kind: compaction` 或输入中的 `compaction_trigger` 识别。
|
||||
WS 入站的压缩沿用常规传输策略。
|
||||
@@ -735,10 +739,14 @@ OpenAI 因大小走 HTTP/SSE 且需要完整重放的请求,在
|
||||
生成请求、Messages 输入计数、Images 和 Search 的 HTTP 响应在建立模型执行后返回两个关联 ID,OpenAI 与 xAI 规则相同:
|
||||
|
||||
- `x-gateway-request-id` 为模型执行 ID
|
||||
- `x-request-id` 优先取有效的上游同名头,其次取上游 `x-oai-request-id`,最后取模型执行 ID
|
||||
- `x-request-id` 按 `x-request-id`、`x-oai-request-id`、`x-openai-request-id`、`x-ms-request-id`
|
||||
顺序取有效上游值;全部缺失、为空或不可读时取模型执行 ID
|
||||
|
||||
错误正文读取失败时仍返回已知上游 ID 与允许下发的会话头(如 turn state)。只有在建立执行前拒绝请求时才使用中间件的入口关联
|
||||
|
||||
网关合成的 WebSocket `response.metadata` 采用相同的 ID 选择顺序。失败响应仅关联本次失败,
|
||||
不沿用先前握手或会话的 request ID
|
||||
|
||||
WebSocket 在交付业务事件前合成的错误保留已确认的失败状态和结构化 `message/type/code`,容量恢复按[重试规则](#容量拒绝与重试)处理。缺少结构化错误时使用安全提示。错误的 `headers` 携带允许下发的响应头,优先返回失败的上游 request ID,缺失时使用网关关联 ID。`x-gateway-request-id` 单独标识网关请求
|
||||
|
||||
### 模型目录
|
||||
@@ -943,7 +951,8 @@ Client Key 日周预算超限返回 `429`,`error.type` 为官方额度耗尽
|
||||
|
||||
OpenAI 选号阶段确认本次可选账号全部额度耗尽时,HTTP 返回 `429`,WebSocket 错误帧返回
|
||||
`status: 429`,两者的 `error.type` 与 `error.code` 均为 `usage_limit_reached`,提示客户端停止
|
||||
本轮自动重试,等待额度恢复或补充可用账号。空账号池、认证失效和临时容量不足不按额度耗尽处理;
|
||||
本轮自动重试,等待额度恢复或补充可用账号。空账号池、认证失效、临时容量不足,以及仍有正常账号因
|
||||
HTTP/SSE 配置无法承接 WS 请求的混合原因,不按整个账号池额度耗尽处理;
|
||||
仍有其他可用 Provider 或可安全恢复的续写时,网关先按现有路由规则尝试恢复
|
||||
|
||||
带 `previous_response_id` 的 OpenAI 原生续写仍绑定原账号。若该账号明确拒绝请求且额度已耗尽,
|
||||
@@ -1370,6 +1379,8 @@ OpenAI OAuth 账号的 `capabilities.quotaSettingsSupported` 为真。通过 `PO
|
||||
该轮存在对应通用桶的请求使用证据或新窗口非零用量时跳过,不把重置前的使用或具名桶用量算入本轮。
|
||||
正常请求的额度反馈即使用量取整为 0% 也保留使用证据,主动额度刷新不会清除;成功的账号预热同样计入。
|
||||
无重置时间时等待后续观测,不通过空闲窗口滚动的倒计时推迟已登记的边界。
|
||||
本周期已观察到用量或触顶,随后已有快照在原边界前显示 0% 且未触顶时,从该次观测起满 5 分钟复查并预热。
|
||||
该判断只消费已保存的额度,不增加发现重置的轮询;始终为 0% 的空闲桶仍按原边界处理。
|
||||
手动或自动用卡确认成功后,已开启预热的通用周桶从确认时间起满 5 分钟复查。额度恢复且本轮空闲时才发送,重试最近一次用卡时沿用原预热进度。
|
||||
同批到期的通用窗口合并一次请求,领取进度跨重启保留;已领取请求发生超时或取消时不自动重放。
|
||||
账号停用、凭据不可用、额度耗尽或达到调度上限时不执行;复查失败最多每 5 分钟重查
|
||||
@@ -1773,7 +1784,8 @@ OAuth 账号优先按可归属整个账号的实际周/月额度窗口统计,
|
||||
Antigravity 按部署时区汇总今天及前 6 天,`usage.windowKind` 为 `recent_week`,管理端显示“近一周”;其他 Provider 默认使用过去 24 小时,返回 `daily`。
|
||||
Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计;账号请求小时图仍独立展示最近 24 个 UTC 小时桶
|
||||
|
||||
账号列表展示额度桶时,Token 取自使用率对应窗口的 `localUsage`。桶内所有窗口的使用率均未知时取第一个展示窗口。窗口用量为零时显示 `0`,缺少统计时显示 `—`
|
||||
账号列表展示额度桶时,Token 取自使用率对应窗口的 `localUsage`。桶内所有窗口的使用率均未知时取第一个展示窗口。
|
||||
缺少窗口统计时显示 `—`。账号列表统一隐藏为零的 Token 用量
|
||||
|
||||
批量导入 AT / RT 使用 `accounts` JSON 数组,最多 200 项,不接受纯文本 token 列表。例如:
|
||||
|
||||
@@ -2165,7 +2177,8 @@ GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercen
|
||||
`allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。分组与账号共用[模型限制编辑器](#账号模型限制)。可从成员账号的目录勾选模型,也可在创建或编辑分组时手动添加目录外的 ID。分组和账号分别保存规则,账号自身的限制继续生效。
|
||||
Key 绑定多个组时,按模型分别合并启用组中的合格账号。例如两个组分别允许 X 和 Y,X 请求只能使用允许 X 的组内账号。
|
||||
|
||||
`fastMode` 默认跟随客户端。策略合并包括 Key 绑定的禁用分组,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端
|
||||
`fastMode` 默认跟随客户端。每次选定账号后,只合并当前 Key 绑定、已启用、包含该账号且允许本次上游模型的分组策略。
|
||||
其他账号的分组、停用分组和不允许该模型的分组不参与。同一账号命中多个有效分组时,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端
|
||||
|
||||
| 值 | OpenAI Responses 顶层 `service_tier` |
|
||||
| --- | --- |
|
||||
@@ -2177,7 +2190,7 @@ Key 绑定多个组时,按模型分别合并启用组中的合格账号。例
|
||||
目标档位缺少目录支持时保留原请求。
|
||||
OAuth 和 Responses API Key 共用上述档位规则,出站兼容层不额外删除原生 Responses 的 `auto/default`。
|
||||
宿主策略在 request 中间件之后应用,形成 attempt 输入基线;attempt 中间件继续改写档位时,以改写后的实际发送值为准。
|
||||
HTTP 和每个 WebSocket `response.create` 均使用请求开始时的分组策略,同一请求重试保持该策略;
|
||||
HTTP 和每个 WebSocket `response.create` 均冻结请求开始时的分组配置,重试按实际选中的账号和上游模型计算策略。
|
||||
HTTP 请求头及新建 WS 的握手提示按当时的最终出站档位构造;复用 WS 时不重发握手头,
|
||||
每个 `response.create` 仍独立应用档位策略,请求档位统计与本地费用估算使用各帧的最终出站档位
|
||||
|
||||
@@ -3423,6 +3436,8 @@ Provider metadata 分别保留 `requestedServiceTier` 与 `upstreamServiceTier`
|
||||
|
||||
版本接口只读本地构建和通道摘要,缓存未就绪时返回 `updateCached=false`、`latestVersion=null`。`updateChannel` 按运行版本推导,为 `stable`、`alpha`、`beta`、`rc`、`exp` 或 `unknown`
|
||||
|
||||
`restartSupported` 表示部署是否启用在线重启,与是否安装更新无关。`instanceId` 是当前宿主实例的随机标识,在该实例生命周期内保持不变,每次启动重新生成。重启前读取该标识,重启后须同时确认标识已变化且运行版本符合目标,不能仅凭版本号判断同版本重启完成
|
||||
|
||||
详情与安装接口的 `channel` 只对本次操作有效,省略时取运行通道。响应的 `policy` 包含 `channel` 和 `availableChannels`。普通实例可选 `stable`、`rc`、`beta`、`alpha`,实验实例仅可选 `exp`。
|
||||
未知枚举值返回参数错误。禁用通道、跨实验线、跨大版本、降级或同版本重装返回 `40901`。安装时同时提交已确认的 `channel` 和 `targetVersion`,服务端按[升级规则](../deploy/README.md#版本命名与升级规则)复核目标
|
||||
|
||||
|
||||
+10
-4
@@ -231,7 +231,7 @@ flowchart LR
|
||||
Runtime 将插件改写交回同一设置编译器;API 在认证、版本检查与正文解压前传递有效配置,不按业务接口增加设置包装。HTTP 超时由路由终端消费,`None` 清除本次超时。
|
||||
OpenAI 的 Fast 设置在 attempt 中间件前形成正文基线;OpenAI / xAI 的插件头修改覆盖账号与画像生成的同名头,不按字段名拦截。
|
||||
HTTP 正文的寿命覆盖惰性读取,WebSocket 升级后由独立连接取消信号和冻结发布代次接管,101 响应正文结束不会取消会话
|
||||
- **模型设置按请求重算**:Key 自身的画像、Fast 和限额默认值独立保留;`RequestSettings` 统一按宿主默认、当前 Key 默认、插件显式覆盖的顺序解析。
|
||||
- **模型设置按请求重算**:Key 自身的画像和限额默认值独立保留;`RequestSettings` 统一按宿主默认、当前 Key 默认、插件显式覆盖的顺序解析。Fast 分组默认值在选定账号后计算,请求设置只保留显式覆盖。
|
||||
认证、插件使用的 `ExecutionSettings` 视图和执行终端共用该规则。设置改写经过编译后由终端复用结果,截止时间仍相对请求开始时刻计算,不发布全局配置。
|
||||
子调用保留显式改写,在目标 Key 作用域重算默认值;Key 限额、Fast 和模型超时的覆盖绑定原 Key,同级调用互不改写。
|
||||
原生 Responses WebSocket 每轮从当前快照重新认证,保留握手的显式改写;已经开始的执行不随全局发布改变。具体字段与来源合同见 [SDK 中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#http-入口)
|
||||
@@ -555,9 +555,10 @@ Store 将策略与设置 revision 原子持久化;编译结果随快照、计
|
||||
每条规则跨承载副本原子提交;发送前拒绝携带 `NotSent` 和禁止重试标记。被规则改写的握手头参与 WS 池身份,防止复用旧值,
|
||||
关闭策略不进入改写管线。字段与执行限制见[隐私策略 API](api.md#隐私策略)
|
||||
|
||||
Fast 策略由 Core 合并 Client Key 的全部绑定分组并随同一快照链路冻结,禁用分组也参与合并;
|
||||
不按所选账号的分组重新解释。档位优先级与字段合同见[账号分组 API](api.md#6-账号分组)。
|
||||
OpenAI Provider 在独立编码请求上、生成上游头与观测前统一应用顶层档位覆盖,HTTP、WS 与重试共用。
|
||||
Fast 分组配置由 Core 随账号目录冻结,选号后通过同一账号范围解析器合并当前 Key 授权该账号与模型的启用分组策略。
|
||||
请求设置中的显式 Fast 覆盖优先于分组策略;未覆盖时,换号按新账号重算,仍使用请求开始时的快照,不读取新的全局配置。
|
||||
档位优先级与字段合同见[账号分组 API](api.md#6-账号分组)。
|
||||
OpenAI Provider 在选定账号后、attempt 中间件前应用顶层档位覆盖,HTTP、WS 与重试共用;上游适配器取得同一账号与模型的有效策略。
|
||||
该策略不改变选号、会话亲和或共享原始请求;每个新 WS 请求重新取得当前策略。
|
||||
WS 路由提示属于握手,连接复用时不重发;档位变化不重建连接或打断 `previous_response_id` 续写,
|
||||
各帧正文及计费仍使用本次请求的最终档位
|
||||
@@ -1366,6 +1367,11 @@ API 输出模型执行与上游请求的关联信息,具体响应头规则见
|
||||
失败终态及中间失败的上游请求 ID 优先取对应 `ProviderError`,缺失时再取该 attempt 的响应
|
||||
observation、调用 metadata;最终失败的关联头不与 opening 身份混合
|
||||
|
||||
Responses HTTP 的 `request_trace` 按入口 ID 记录正文接收、认证、解压、解码和执行准备阶段。
|
||||
`http.body.received` 的 `receive_ms` 从入口 middleware 开始,覆盖正文读取及 extractor 开销;
|
||||
`encoded_bytes` 是解压前实际收到的正文字节数,`http.body.decompressed` 的 `decoded_bytes` 是解压后大小。
|
||||
这些计时不属于模型执行耗时,也不能单独解释为客户端纯网络上传时间
|
||||
|
||||
正常路径的请求行仍在首次合法 ProviderStream 建立后随 attempt 合并创建。已进入 Core 执行会话、
|
||||
但在首次合法冷流建立前发生的无可用账号、准备失败、超时或取消,复用同一请求表补写失败终态与
|
||||
诊断快照;没有实际 attempt 时计数为零,账号与传输保持空值。Provider 的准备过程不得发送本次请求的
|
||||
|
||||
@@ -10,6 +10,8 @@ export interface SystemUpdatePolicy {
|
||||
|
||||
export interface SystemVersion {
|
||||
version: string
|
||||
instanceId: string
|
||||
restartSupported: boolean
|
||||
gitSha: string
|
||||
buildTime: string
|
||||
deploymentMode: string
|
||||
@@ -114,10 +116,11 @@ export interface SystemRestartPlan {
|
||||
incompatiblePlugins: { instanceId: string, name: string, reason: string }[]
|
||||
}
|
||||
|
||||
export function checkSystemRestart() {
|
||||
export function checkSystemRestart(options: RequestOptions = {}) {
|
||||
return request<SystemRestartPlan>({
|
||||
url: '/api/admin/system/restart/check',
|
||||
method: 'GET',
|
||||
...options,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
"forceUltrafast": "Force Ultrafast",
|
||||
"subagents": "Collaborative subagents",
|
||||
"memberModels": "Member account models",
|
||||
"fastModeHelp": "Default follows the client. Disable downgrades both accelerated tiers to standard. A forced tier overrides the client selection when the model supports it.",
|
||||
"fastModeHelp": "Default follows the client, Disable uses the standard tier, and Fast or Ultrafast overrides the client when supported. Only enabled groups bound to this key that contain the selected account and allow the model contribute. When several groups qualify, precedence is Disable > Fast > Ultrafast > Default",
|
||||
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent.",
|
||||
"noProviderSettings": "No group-specific settings for this platform"
|
||||
},
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
"restart": "Restart failed, please check again",
|
||||
"unconfirmed": "Update task has not been confirmed, check its status and try again",
|
||||
"updateFailed": "Update failed",
|
||||
"startTimeout": "Service v{version} did not start within the expected time",
|
||||
"activationTargetMissing": "No target version is pending activation"
|
||||
"startTimeout": "Timed out waiting for v{version} to restart. Refresh the page to check the running version.",
|
||||
"activationTargetMissing": "Cannot determine the restart target version"
|
||||
},
|
||||
"title": "System update",
|
||||
"description": "Check versions, read release notes, and install updates",
|
||||
@@ -65,11 +65,10 @@
|
||||
"actions": {
|
||||
"check": "Check for updates",
|
||||
"install": "Download update",
|
||||
"continueRestart": "Continue restart",
|
||||
"restart": "Restart now"
|
||||
"continueRestart": "Confirm restart",
|
||||
"restart": "Restart service"
|
||||
},
|
||||
"plugins": {
|
||||
"title": "Plugin compatibility notice",
|
||||
"description": "Incompatible plugins will remain stopped",
|
||||
"incompatible": "Incompatible plugins",
|
||||
"requestErrorHelp": "Data and settings are kept, retry from the plugins page"
|
||||
@@ -98,6 +97,12 @@
|
||||
"docker": "Docker",
|
||||
"binary": "Binary",
|
||||
"source": "From source"
|
||||
},
|
||||
"restart": {
|
||||
"title": "Restart service?",
|
||||
"description": "The service will be unavailable during restart",
|
||||
"unsupported": "Online restart is disabled for this deployment",
|
||||
"requestImpact": "Requests in progress will be interrupted. The page will refresh automatically when the service is ready."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
"forceUltrafast": "超快速",
|
||||
"subagents": "协作子代理",
|
||||
"memberModels": "成员账号模型",
|
||||
"fastModeHelp": "默认跟随客户端。禁用会将加速请求降为标准档。选择快速或超快速时,若模型支持该档位,分组设置会覆盖客户端选择",
|
||||
"fastModeHelp": "默认跟随客户端,禁用将加速请求降为标准档,快速和超快速在模型支持时覆盖客户端选择。仅合并选中账号所属、Key 已绑定且允许本次模型的启用分组。同一账号命中多个有效分组时,优先级为禁用 > 快速 > 超快速 > 默认",
|
||||
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求",
|
||||
"noProviderSettings": "该平台暂无分组专属设置"
|
||||
},
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
"restart": "重启失败,请重新检查",
|
||||
"unconfirmed": "尚未确认更新任务,请检查状态后重试",
|
||||
"updateFailed": "更新失败",
|
||||
"startTimeout": "服务未在预期时间内启动 v{version}",
|
||||
"activationTargetMissing": "缺少待生效的目标版本"
|
||||
"startTimeout": "等待 v{version} 重启确认超时,请刷新页面查看运行版本",
|
||||
"activationTargetMissing": "无法确定重启目标版本"
|
||||
},
|
||||
"title": "系统更新",
|
||||
"description": "检查版本、查看发布说明并执行在线更新",
|
||||
@@ -65,11 +65,10 @@
|
||||
"actions": {
|
||||
"check": "检查更新",
|
||||
"install": "下载更新",
|
||||
"continueRestart": "继续重启",
|
||||
"restart": "立即重启"
|
||||
"continueRestart": "确认重启",
|
||||
"restart": "重启服务"
|
||||
},
|
||||
"plugins": {
|
||||
"title": "插件兼容性提醒",
|
||||
"description": "重启后,不兼容插件将保持未启动",
|
||||
"incompatible": "不兼容插件",
|
||||
"requestErrorHelp": "配置和数据保留,可在插件页尝试启动"
|
||||
@@ -98,6 +97,12 @@
|
||||
"docker": "Docker",
|
||||
"binary": "二进制",
|
||||
"source": "源码运行"
|
||||
},
|
||||
"restart": {
|
||||
"title": "重启服务?",
|
||||
"description": "重启期间服务不可用",
|
||||
"unsupported": "当前部署未启用在线重启",
|
||||
"requestImpact": "正在进行的请求会中断,服务恢复后页面将自动刷新"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
"forceUltrafast": "超快速",
|
||||
"subagents": "協作子代理",
|
||||
"memberModels": "成員帳號模型",
|
||||
"fastModeHelp": "預設跟隨用戶端。禁用會將加速請求降為標準檔。選擇快速或超快速時,若模型支援該檔位,分組設定會覆寫用戶端選擇",
|
||||
"fastModeHelp": "預設跟隨用戶端,禁用將加速請求降為標準檔,快速和超快速在模型支援時覆寫用戶端選擇。僅合併所選帳號所屬、Key 已綁定且允許本次模型的已啟用分組。同一帳號命中多個有效分組時,優先順序為禁用 > 快速 > 超快速 > 預設",
|
||||
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求",
|
||||
"noProviderSettings": "此平台暫無分組專屬設定"
|
||||
},
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
"restart": "重啓失敗,請重新檢查",
|
||||
"unconfirmed": "尚未確認更新任務,請檢查狀態後重試",
|
||||
"updateFailed": "更新失敗",
|
||||
"startTimeout": "服務未在預期時間內啓動 v{version}",
|
||||
"activationTargetMissing": "缺少待生效的目標版本"
|
||||
"startTimeout": "等待 v{version} 重新啟動確認逾時,請重新整理頁面查看執行版本",
|
||||
"activationTargetMissing": "無法確定重啓目標版本"
|
||||
},
|
||||
"title": "系統更新",
|
||||
"description": "檢查版本、查看發佈說明並執行在線更新",
|
||||
@@ -65,11 +65,10 @@
|
||||
"actions": {
|
||||
"check": "檢查更新",
|
||||
"install": "下載更新",
|
||||
"continueRestart": "繼續重啓",
|
||||
"restart": "立即重啓"
|
||||
"continueRestart": "確認重啓",
|
||||
"restart": "重啓服務"
|
||||
},
|
||||
"plugins": {
|
||||
"title": "插件兼容性提醒",
|
||||
"description": "重新啟動後,不相容插件將維持未啟動",
|
||||
"incompatible": "不兼容插件",
|
||||
"requestErrorHelp": "設定與資料保留,可在插件頁嘗試啟動"
|
||||
@@ -98,6 +97,12 @@
|
||||
"docker": "Docker",
|
||||
"binary": "二進制",
|
||||
"source": "源碼運行"
|
||||
},
|
||||
"restart": {
|
||||
"title": "重啓服務?",
|
||||
"description": "重啓期間服務不可用",
|
||||
"unsupported": "當前部署未啓用在線重啓",
|
||||
"requestImpact": "正在進行的請求會中斷,服務恢復後頁面將自動重新整理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ const {
|
||||
const { loadSystem, checkUpdates, changeChannel, updateNow, restartNow } = systemUpdateStore
|
||||
|
||||
const updateLogScrollbar = useTemplateRef<InstanceType<typeof ZScrollbar>>('updateLogScrollbar')
|
||||
const restartButton = useTemplateRef<InstanceType<typeof ZButton>>('restartButton')
|
||||
const checkingRestart = shallowRef(false)
|
||||
const restartConfirmOpen = shallowRef(false)
|
||||
const restartPlan = shallowRef<SystemRestartPlan | null>(null)
|
||||
@@ -124,7 +125,7 @@ const hasReleaseNotes = computed(() => Boolean(updateInfo.value?.notes?.trim()))
|
||||
const releaseNotesLoading = computed(() => loading.value || changingChannel.value)
|
||||
|
||||
const showUpdateProgress = computed(
|
||||
() => updating.value || restarting.value || updateLogRows.value.length > 0,
|
||||
() => updating.value || updateLogRows.value.length > 0,
|
||||
)
|
||||
|
||||
async function scrollUpdateLogsToBottom() {
|
||||
@@ -172,12 +173,14 @@ async function handleRestart() {
|
||||
return
|
||||
checkingRestart.value = true
|
||||
try {
|
||||
restartPlan.value = await checkSystemRestart()
|
||||
if (restartPlan.value.incompatiblePlugins.length) {
|
||||
restartConfirmOpen.value = true
|
||||
restartPlan.value = await checkSystemRestart({ silent: true })
|
||||
if (!open.value)
|
||||
return
|
||||
}
|
||||
await restartNow(restartPlan.value)
|
||||
checkingRestart.value = false
|
||||
await nextTick()
|
||||
// 检查期间按钮暂时禁用,恢复焦点后再让确认框记录返回位置
|
||||
restartButton.value?.focus()
|
||||
restartConfirmOpen.value = true
|
||||
}
|
||||
catch (error: unknown) {
|
||||
ZNotification.error({
|
||||
@@ -451,6 +454,25 @@ watch(
|
||||
</div>
|
||||
</ZPopover>
|
||||
</div>
|
||||
<ZPopover :disabled="version?.restartSupported !== false" placement="top" trigger="hover-click">
|
||||
<template #reference>
|
||||
<span class="inline-flex" :tabindex="version?.restartSupported === false ? 0 : undefined">
|
||||
<ZButton
|
||||
ref="restartButton"
|
||||
:disabled="!canRestart || checkingRestart"
|
||||
@click="handleRestart"
|
||||
>
|
||||
<template #icon>
|
||||
<Power class="size-4" />
|
||||
</template>
|
||||
{{ t('systemUpdate.actions.restart') }}
|
||||
</ZButton>
|
||||
</span>
|
||||
</template>
|
||||
<p class="m-0 max-w-64 px-3 py-2 text-z-sm text-z-text-secondary">
|
||||
{{ t('systemUpdate.restart.unsupported') }}
|
||||
</p>
|
||||
</ZPopover>
|
||||
<ZButton
|
||||
:loading="checking"
|
||||
:disabled="loading || updating || restarting || changingChannel"
|
||||
@@ -465,19 +487,7 @@ watch(
|
||||
{{ t('systemUpdate.actions.check') }}
|
||||
</ZButton>
|
||||
<ZButton
|
||||
v-if="needRestart"
|
||||
type="primary"
|
||||
:loading="restarting || checkingRestart"
|
||||
:disabled="!canRestart || restartConfirmOpen"
|
||||
@click="handleRestart"
|
||||
>
|
||||
<template #icon>
|
||||
<Power class="size-4" />
|
||||
</template>
|
||||
{{ presentation.restartButtonLabel }}
|
||||
</ZButton>
|
||||
<ZButton
|
||||
v-else-if="hasUpdate || updating"
|
||||
v-if="!needRestart && (hasUpdate || updating)"
|
||||
type="primary"
|
||||
:loading="updating"
|
||||
:disabled="!canUpdate"
|
||||
@@ -493,18 +503,25 @@ watch(
|
||||
|
||||
<ZConfirmDialog
|
||||
v-model="restartConfirmOpen"
|
||||
:title="t('systemUpdate.plugins.title')"
|
||||
:description="t('systemUpdate.plugins.description')"
|
||||
:confirm-text="t('systemUpdate.actions.continueRestart')"
|
||||
:title="t('systemUpdate.restart.title')"
|
||||
:description="t('systemUpdate.restart.description')"
|
||||
:confirm-text="restarting ? t('systemUpdate.status.restarting') : t('systemUpdate.actions.continueRestart')"
|
||||
:loading="restarting"
|
||||
:confirm-disabled="!canRestart && !restarting"
|
||||
@confirm="handleConfirmRestart"
|
||||
>
|
||||
<div class="grid gap-4">
|
||||
<p class="m-0 text-z-sm leading-relaxed font-normal text-z-text-secondary">
|
||||
{{ t('systemUpdate.restart.requestImpact') }}
|
||||
</p>
|
||||
<div v-if="restartPlan?.targetVersion" class="flex items-center justify-between gap-3 text-z-sm">
|
||||
<span class="text-z-text-secondary">{{ t('systemUpdate.versionAfterRestart') }}</span>
|
||||
<span class="font-mono font-emphasis text-z-text">v{{ restartPlan.targetVersion }}</span>
|
||||
</div>
|
||||
<ul class="m-0 max-h-64 list-none overflow-y-auto p-0" :aria-label="t('systemUpdate.plugins.incompatible')">
|
||||
<p v-if="restartPlan?.incompatiblePlugins.length" class="m-0 text-z-sm text-z-warning">
|
||||
{{ t('systemUpdate.plugins.description') }}
|
||||
</p>
|
||||
<ul v-if="restartPlan?.incompatiblePlugins.length" class="m-0 max-h-64 list-none overflow-y-auto p-0" :aria-label="t('systemUpdate.plugins.incompatible')">
|
||||
<li v-for="plugin in restartPlan?.incompatiblePlugins" :key="plugin.instanceId" class="flex items-start gap-3 py-3 first:pt-0 last:pb-0">
|
||||
<TriangleAlert class="mt-0.5 size-4 shrink-0 text-z-warning" aria-hidden="true" />
|
||||
<div class="grid min-w-0 gap-1">
|
||||
@@ -513,7 +530,7 @@ watch(
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p class="m-0 rounded-z bg-z-fill-quaternary px-3 py-2.5 text-z-sm leading-relaxed font-normal text-z-text-secondary">
|
||||
<p v-if="restartPlan?.incompatiblePlugins.length" class="m-0 rounded-z bg-z-fill-quaternary px-3 py-2.5 text-z-sm leading-relaxed font-normal text-z-text-secondary">
|
||||
{{ t('systemUpdate.plugins.requestErrorHelp') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -26,9 +26,6 @@ export function resolveSystemUpdatePresentation(input: SystemUpdatePresentationI
|
||||
: input.updateStreamError
|
||||
? t('systemUpdate.logs.disconnectedState')
|
||||
: t('systemUpdate.logs.waiting'),
|
||||
restartButtonLabel: input.restarting
|
||||
? t('systemUpdate.status.restarting')
|
||||
: t('systemUpdate.actions.restart'),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,10 +107,8 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
})
|
||||
|
||||
const needRestart = computed(() => Boolean(updateStatus.value?.needRestart))
|
||||
const canRestart = computed(() => statusAvailable.value && needRestart.value && !updating.value && !restarting.value)
|
||||
const restartTargetVersion = computed(() => needRestart.value
|
||||
? normalizeSystemVersion(updateStatus.value?.currentVersion)
|
||||
: '')
|
||||
const canRestart = computed(() => version.value?.restartSupported === true
|
||||
&& statusAvailable.value && !UPDATE_BUSY_PHASES.has(phaseKind.value))
|
||||
const selectedChannel = computed(() => policy.value?.channel ?? 'stable')
|
||||
const availableChannels = computed(() => policy.value?.availableChannels ?? [])
|
||||
const canChangeChannel = computed(() => availableChannels.value.length > 1
|
||||
@@ -338,6 +336,7 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
setPhase({ kind: 'loading' })
|
||||
loadSystemPromise = (async () => {
|
||||
await Promise.all([
|
||||
loadVersion(),
|
||||
refreshUpdateStatus(),
|
||||
loadDetail(refresh, generation),
|
||||
])
|
||||
@@ -463,14 +462,15 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForServiceAndReload() {
|
||||
const expectedVersion = restartTargetVersion.value
|
||||
async function waitForServiceAndReload(expectedVersion: string, previousInstanceId: string) {
|
||||
const deadline = Date.now() + restartReadyTimeoutMs
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const readyVersion = await getSystemVersion({ timeout: restartProbeTimeoutMs, silent: true })
|
||||
if (normalizeSystemVersion(readyVersion.version) === expectedVersion) {
|
||||
// 同版本重启时,旧实例仍可能响应探测,必须等到新实例接管
|
||||
if (readyVersion.instanceId && readyVersion.instanceId !== previousInstanceId
|
||||
&& normalizeSystemVersion(readyVersion.version) === expectedVersion) {
|
||||
window.location.reload()
|
||||
return
|
||||
}
|
||||
@@ -490,16 +490,9 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
}
|
||||
|
||||
async function restartNow(confirmation: SystemRestartPlan) {
|
||||
if (restarting.value)
|
||||
if (!canRestart.value)
|
||||
return
|
||||
|
||||
if (!restartTargetVersion.value) {
|
||||
const error = new Error(t('systemUpdate.errors.activationTargetMissing'))
|
||||
updateError.value = error.message
|
||||
setPhase({ kind: 'failed' })
|
||||
throw error
|
||||
}
|
||||
|
||||
statusGeneration += 1
|
||||
statusPoll.pause()
|
||||
setPhase({ kind: 'restarting' })
|
||||
@@ -507,18 +500,28 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
disconnectUpdateEvents()
|
||||
|
||||
try {
|
||||
// 进程可能在返回响应前退出,由下面的目标版本探测判定是否完成。
|
||||
await restartSystem({ confirmation }, { silent: true })
|
||||
// 提交前重新读取实例,避免页面缓存把此前发生的外部重启误判为本次完成
|
||||
const runningVersion = await getSystemVersion({ timeout: restartProbeTimeoutMs, silent: true })
|
||||
const expectedVersion = normalizeSystemVersion(confirmation.targetVersion ?? runningVersion.version)
|
||||
if (!expectedVersion)
|
||||
throw new Error(t('systemUpdate.errors.activationTargetMissing'))
|
||||
|
||||
try {
|
||||
await restartSystem({ confirmation }, { silent: true })
|
||||
}
|
||||
catch (error: unknown) {
|
||||
// 仅在响应因进程退出而丢失时继续探测,不重试重启请求
|
||||
if (!(error instanceof ApiError) || error.status > 0)
|
||||
throw error
|
||||
}
|
||||
|
||||
await waitForServiceAndReload(expectedVersion, runningVersion.instanceId)
|
||||
}
|
||||
catch (error: unknown) {
|
||||
if (error instanceof ApiError && error.status > 0) {
|
||||
setPhase({ kind: 'failed' })
|
||||
updateError.value = errorMessage(error)
|
||||
throw error
|
||||
}
|
||||
setPhase({ kind: 'failed' })
|
||||
updateError.value = errorMessage(error)
|
||||
throw error
|
||||
}
|
||||
|
||||
await waitForServiceAndReload()
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -531,7 +534,6 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
|
||||
selectedChannel,
|
||||
availableChannels,
|
||||
canChangeChannel,
|
||||
restartTargetVersion,
|
||||
updating,
|
||||
restarting,
|
||||
updateError,
|
||||
|
||||
@@ -41,10 +41,17 @@ const recentUsageEntry = computed(() => recentlyUsedQuotaEntry(
|
||||
const currentUsageWindow = computed(() => representativeQuotaWindow(recentUsageEntry.value))
|
||||
const tokenDisplay = computed(() => {
|
||||
const window = currentUsageWindow.value ?? recentUsageEntry.value?.windows[0]
|
||||
if (window && !localUsageOnly.value)
|
||||
return quotaWindowTokens(window)?.display ?? '—'
|
||||
if (window && !localUsageOnly.value) {
|
||||
const tokens = quotaWindowTokens(window)
|
||||
return tokens?.total === 0
|
||||
? null
|
||||
: tokens?.display ?? '—'
|
||||
}
|
||||
|
||||
const usage = props.account.usage
|
||||
if (usage.totalTokens === 0)
|
||||
return null
|
||||
|
||||
return localUsageOnly.value || (usage.totalTokens ?? 0) > 0
|
||||
? usage.totalTokensDisplay
|
||||
: null
|
||||
|
||||
@@ -11,6 +11,7 @@ defineProps<{
|
||||
testing: boolean
|
||||
batchTesting: boolean
|
||||
updating: boolean
|
||||
dialogActive: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -26,13 +27,13 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
<template>
|
||||
<div class="flex items-center gap-0.5">
|
||||
<ZIconButton size="small" :aria-label="t('proxies.actions.test')" :loading="testing && !batchTesting" :disabled="batchTesting || testing || updating" @click="emit('test', proxy)">
|
||||
<ZIconButton size="small" :aria-label="t('proxies.actions.test')" :loading="testing && !batchTesting && !dialogActive" :disabled="batchTesting || testing || updating" @click="emit('test', proxy)">
|
||||
<Wifi class="size-3.5 text-z-link" />
|
||||
</ZIconButton>
|
||||
<ZIconButton size="small" :aria-label="t('proxies.actions.edit')" :disabled="testing || updating" @click="emit('edit', proxy)">
|
||||
<Pencil class="size-3.5 text-z-link" />
|
||||
</ZIconButton>
|
||||
<RowActionMenu :label="t('proxies.actions.moreActionsFor', { name: proxy.name })" menu-class="w-36 p-1.5" :disabled="testing || updating" :loading="updating">
|
||||
<RowActionMenu :label="t('proxies.actions.moreActionsFor', { name: proxy.name })" menu-class="w-36 p-1.5" :disabled="testing || updating" :loading="updating && !dialogActive">
|
||||
<ZMenuItem :disabled="batchTesting || testing || updating" @click="emit('testTarget')">
|
||||
<template #icon>
|
||||
<Globe class="size-3.5 text-z-text-quaternary" />
|
||||
|
||||
@@ -166,7 +166,6 @@ watch([
|
||||
size="small"
|
||||
:aria-label="t('proxies.accounts.removeAction')"
|
||||
:disabled="removing"
|
||||
:loading="removing && pendingRemove?.id === row.id"
|
||||
@click="requestRemove(row)"
|
||||
>
|
||||
<Unlink class="size-3.5 text-z-error" />
|
||||
|
||||
@@ -167,7 +167,18 @@ watch(search, () => {
|
||||
{{ row.lastTestAtDisplay ?? '-' }}
|
||||
</template>
|
||||
<template #actions="{ row }">
|
||||
<ProxyActions :proxy="row" :testing="testingIds.has(row.id)" :batch-testing="batchTesting" :updating="updatingIds.has(row.id)" @test-target="openTargetTest(row)" @test="checkProxy" @edit="openForm" @toggle="toggleEnabled" @delete="requestDelete" />
|
||||
<ProxyActions
|
||||
:proxy="row"
|
||||
:testing="testingIds.has(row.id)"
|
||||
:batch-testing="batchTesting"
|
||||
:updating="updatingIds.has(row.id)"
|
||||
:dialog-active="(showForm && editing?.id === row.id) || (showDisable && pendingDisable?.id === row.id)"
|
||||
@test-target="openTargetTest(row)"
|
||||
@test="checkProxy"
|
||||
@edit="openForm"
|
||||
@toggle="toggleEnabled"
|
||||
@delete="requestDelete"
|
||||
/>
|
||||
</template>
|
||||
</ZTable>
|
||||
<ZPagination v-bind="pagination" :disabled="loading" @current-change="setPage" @size-change="setPageSize" />
|
||||
|
||||
@@ -35,6 +35,7 @@ const fixedValue = computed({
|
||||
const localError = shallowRef('')
|
||||
const preview = usePrivacyPreview()
|
||||
const { loading, result } = preview
|
||||
const previewAction = shallowRef<'test' | 'apply'>('test')
|
||||
const processed = computed(() => result.value
|
||||
? JSON.stringify({ body: result.value.body, headers: result.value.headers, turnMetadata: result.value.turnMetadata }, null, 2)
|
||||
: '')
|
||||
@@ -100,6 +101,9 @@ function preparedRule() {
|
||||
return rule
|
||||
}
|
||||
async function test() {
|
||||
if (props.disabled || loading.value || !open.value)
|
||||
return
|
||||
previewAction.value = 'test'
|
||||
try {
|
||||
const rule = preparedRule()
|
||||
const value: PrivacySample = JSON.parse(sample.value)
|
||||
@@ -118,8 +122,9 @@ async function test() {
|
||||
}
|
||||
}
|
||||
async function apply() {
|
||||
if (props.disabled)
|
||||
if (props.disabled || loading.value || !open.value)
|
||||
return
|
||||
previewAction.value = 'apply'
|
||||
try {
|
||||
const rule = preparedRule()
|
||||
const validated = await preview.run({
|
||||
@@ -168,7 +173,7 @@ async function apply() {
|
||||
</h3>
|
||||
<div class="flex items-center gap-2">
|
||||
<span v-if="outcome" class="text-z-xs text-z-text-quaternary">{{ outcome.status === 'skipped' ? t('settings.privacy.rules.ruleSkipped') : t('settings.privacy.rules.matches', { matches: outcome.matches }) }}</span>
|
||||
<ZButton size="small" variant="text" :loading="loading" :aria-label="t('settings.privacy.rules.testThisRule')" @click="test">
|
||||
<ZButton size="small" variant="text" :loading="loading && previewAction === 'test'" :disabled="disabled || loading" :aria-label="t('settings.privacy.rules.testThisRule')" @click="test">
|
||||
<template #icon>
|
||||
<Play class="size-3.5" />
|
||||
</template>{{ t('settings.privacy.rules.test') }}
|
||||
@@ -195,7 +200,7 @@ async function apply() {
|
||||
<ZButton @click="open = false">
|
||||
{{ t('common.actions.cancel') }}
|
||||
</ZButton>
|
||||
<ZButton type="primary" :loading="loading" :disabled="disabled" @click="apply">
|
||||
<ZButton type="primary" :loading="loading && previewAction === 'apply'" :disabled="disabled || loading" @click="apply">
|
||||
{{ t('settings.privacy.rules.applyToDraft') }}
|
||||
</ZButton>
|
||||
</template>
|
||||
|
||||
+16
-2
@@ -1,3 +1,17 @@
|
||||
# v3.61.1-rc.1
|
||||
# v3.61.1-rc.2
|
||||
|
||||
Codex OAuth 的 SSE 请求复用同一条上游 WebSocket 时,若本轮配置与历史前缀匹配,网关只发送新增输入,无需跨轮缓存对话正文
|
||||
## 新增功能
|
||||
|
||||
- 启用在线重启的部署可在管理端「系统更新」中手动重启服务,确认前可查看请求中断影响和插件风险
|
||||
|
||||
## 优化改进
|
||||
|
||||
- Codex OAuth 的 SSE 请求在应用隐私规则后仍可复用匹配的历史,只向同一上游 WebSocket 发送新增输入
|
||||
- 管理端仅在当前操作按钮显示加载状态,账号列表隐藏为零的 Token 用量
|
||||
|
||||
## 问题修复
|
||||
|
||||
- Fast 模式按本次选中的账号和模型应用分组策略,重试切换账号时重新匹配
|
||||
- Chat Completions 可处理历史中的空占位消息和可空字段,转发到 Messages 和 GenAI 时保留停止序列
|
||||
- OpenAI 额度桶提前重置后,从观察到归零时起等待五分钟,再复查是否需要预热
|
||||
- HTTP 和 WebSocket 错误保留可识别的上游请求 ID,账号选择失败时区分额度耗尽和传输方式不匹配
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.61.1-rc.1
|
||||
version: 3.61.1-rc.2
|
||||
published:
|
||||
'3':
|
||||
stable: 3.61.0
|
||||
rc: 3.61.0
|
||||
beta: 3.61.0
|
||||
alpha: 3.61.0
|
||||
rc: 3.61.1-rc.1
|
||||
beta: 3.61.1-rc.1
|
||||
alpha: 3.61.1-rc.1
|
||||
|
||||
Reference in New Issue
Block a user