diff --git a/backend/crates/gateway-api/src/admin/client_keys.rs b/backend/crates/gateway-api/src/admin/client_keys.rs index 4ca66912b..08dae98ed 100644 --- a/backend/crates/gateway-api/src/admin/client_keys.rs +++ b/backend/crates/gateway-api/src/admin/client_keys.rs @@ -484,7 +484,6 @@ impl TryFrom<(ClientKeyPage, crate::time::TimePresenter)> for ClientKeyListData let next_cursor = page .next_cursor .map(wire_cursor) - .transpose()? .as_ref() .map(encode_client_key_cursor) .transpose()?; @@ -597,7 +596,8 @@ impl From for MutatedClientKeyData { } /// 解码后的 Client Key 游标字段 -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ClientKeyCursorData { pub sort: ClientKeySort, pub value: ClientKeyCursorValue, @@ -614,25 +614,12 @@ pub enum ClientKeyCursorValue { LastUsedAt(Option>), } -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct CursorWire { - sort: ClientKeySort, - value: ClientKeyCursorValue, - id: String, -} - /// 把 owner 游标编码为不透明 wire 值 pub fn encode_client_key_cursor( cursor: &ClientKeyCursorData, ) -> Result { validate_client_key_cursor(cursor)?; - let bytes = serde_json::to_vec(&CursorWire { - sort: cursor.sort, - value: cursor.value.clone(), - id: cursor.id.clone(), - }) - .map_err(|_| WireValidationError::new("cursor"))?; + let bytes = serde_json::to_vec(cursor).map_err(|_| WireValidationError::new("cursor"))?; Ok(URL_SAFE_NO_PAD.encode(bytes)) } @@ -644,13 +631,8 @@ pub fn decode_client_key_cursor(encoded: &str) -> Result Result Result { +fn wire_cursor(cursor: ClientKeyCursor) -> ClientKeyCursorData { let value = match cursor.value { DomainCursorValue::Name(value) => ClientKeyCursorValue::Name(value), DomainCursorValue::Enabled(value) => ClientKeyCursorValue::Enabled(value), DomainCursorValue::CreatedAt(value) => ClientKeyCursorValue::CreatedAt(value), DomainCursorValue::LastUsedAt(value) => ClientKeyCursorValue::LastUsedAt(value), }; - let cursor = ClientKeyCursorData { + ClientKeyCursorData { sort: wire_sort(cursor.sort), value, id: cursor.id.to_string(), - }; - validate_client_key_cursor(&cursor)?; - Ok(cursor) + } } fn client_key_id( diff --git a/backend/crates/gateway-api/tests/admin/client_keys.rs b/backend/crates/gateway-api/tests/admin/client_keys.rs index 73a6486b5..2dea9c2a1 100644 --- a/backend/crates/gateway-api/tests/admin/client_keys.rs +++ b/backend/crates/gateway-api/tests/admin/client_keys.rs @@ -1,5 +1,6 @@ //! 验证 Client Key 管理接口的预算、密钥输入与查询合同 +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use chrono::{DateTime, TimeZone as _, Utc}; use gateway_api::admin::client_keys::{ self, ClientKeyCursorData, ClientKeyCursorValue, ClientKeyListData, ClientKeyMutationRequest, @@ -475,12 +476,41 @@ fn client_key_cursor_should_round_trip_and_reject_noncanonical_input() { }; let encoded = encode_client_key_cursor(&cursor).expect("encode cursor"); let decoded = decode_client_key_cursor(&encoded).expect("decode cursor"); + let wire = json!({ + "sort": { "field": "createdAt", "direction": "desc" }, + "value": { "kind": "createdAt", "value": "2026-07-18T08:00:00Z" }, + "id": "key_cursor" + }); assert_eq!(decoded, cursor); + assert_eq!( + serde_json::from_slice::(&URL_SAFE_NO_PAD.decode(&encoded).unwrap()) + .unwrap(), + wire + ); assert!(!encoded.contains("key_cursor")); for invalid in ["", "not-base64!", "e30"] { assert!(decode_client_key_cursor(invalid).is_err()); } + for (field, value) in [ + ("unknownField", json!(true)), + ("id", json!(" ")), + ("value", json!({ "kind": "enabled", "value": true })), + ( + "sort", + json!({ "field": "createdAt", "direction": "desc", "unknownField": true }), + ), + ] { + let mut invalid = wire.clone(); + invalid[field] = value; + let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&invalid).unwrap()); + assert_eq!( + decode_client_key_cursor(&encoded) + .expect_err("reject invalid cursor fields") + .field(), + "cursor" + ); + } } #[test] diff --git a/backend/crates/gateway-host/src/outbound/http.rs b/backend/crates/gateway-host/src/outbound/http.rs index 03683a772..2bffaf86d 100644 --- a/backend/crates/gateway-host/src/outbound/http.rs +++ b/backend/crates/gateway-host/src/outbound/http.rs @@ -416,6 +416,11 @@ impl HttpBody { return Err(HttpError::sent("read size")); } loop { + if self.received > 32 * 1024 * 1024 { + // 累计量封存超限结果,后续读取不能交付已拒绝的缓冲 + self.pending = Bytes::new(); + return Err(HttpError::sent("response size")); + } // 已缓冲的数据和就绪帧也受本次期限约束,不能绕过 owner 的读取预算 if Instant::now() >= deadline { return Err(HttpError::sent("response deadline").with_kind(HttpErrorKind::Timeout)); @@ -445,9 +450,6 @@ impl HttpBody { } }; self.received = self.received.saturating_add(self.pending.len()); - if self.received > 32 * 1024 * 1024 { - return Err(HttpError::sent("response size")); - } } } } diff --git a/backend/crates/gateway-host/tests/outbound/http.rs b/backend/crates/gateway-host/tests/outbound/http.rs index 3abff40e0..ab4e070f6 100644 --- a/backend/crates/gateway-host/tests/outbound/http.rs +++ b/backend/crates/gateway-host/tests/outbound/http.rs @@ -158,6 +158,60 @@ async fn managed_http_caps_chunks_and_recovers_capacity_after_body_drop() { ); } +#[tokio::test] +async fn managed_http_body_limit_rejects_all_reads_after_exceeding_capacity() { + let limit = 32 * 1024 * 1024; + let server = MockServer::start().await; + let client = HttpClient::new().unwrap(); + for size in [limit, limit + 1] { + server.reset().await; + Mock::given(any()) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![42; size])) + .expect(1) + .mount(&server) + .await; + let mut response = client + .open( + request(server.uri()), + None, + &local_network(), + Duration::from_secs(10), + ) + .await + .unwrap(); + let mut received = 0; + let result = loop { + match response.body.read(64 * 1024).await { + Ok(Some(chunk)) => received += chunk.len(), + result => break result, + } + }; + if size == limit { + assert!(result.unwrap().is_none()); + assert_eq!(received, limit); + } else { + assert!(received <= limit); + let error = result.unwrap_err(); + assert_eq!(error.kind(), HttpErrorKind::Response); + assert_eq!(error.send_state, UpstreamSendState::Sent); + assert_eq!(error.reason(), "response size"); + assert_eq!( + response.body.read(1).await.unwrap_err().reason(), + "response size" + ); + assert_eq!( + response + .body + .read_with_timeout(1, Duration::from_secs(1)) + .await + .unwrap_err() + .reason(), + "response size" + ); + } + } +} + #[tokio::test] async fn managed_http_deadline_and_invalid_headers_preserve_send_facts() { let server = MockServer::start().await; diff --git a/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs b/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs index 2fcc67463..4d84205c3 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs @@ -1,4 +1,4 @@ -//! Chat 到 Responses 的字段、媒体和工具映射回归 +//! Chat 到 Responses 的字段、媒体和工具映射 use gateway_protocol::chat_completions::responses::convert_request; use serde_json::{Value, json}; diff --git a/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs b/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs index 12d49fac2..bb970cd53 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs @@ -1,4 +1,4 @@ -//! Responses 到 Chat 的完整响应、SSE增量及历史字段回归 +//! Responses 到 Chat 的完整响应、流式增量、用量与错误投影 use gateway_protocol::chat_completions::{ ChatAccumulator, ChatError, ChatIdentity, @@ -7,86 +7,67 @@ use gateway_protocol::chat_completions::{ use serde_json::{Value, json}; use std::collections::BTreeMap; -struct Session(Vec); -impl Session { - fn new(events: Vec) -> Self { - Self(events) - } - fn with_batch(mut self, events: Vec) -> Self { - self.0.extend(events); - self - } -} -struct Fixture(Session); struct Projection { json: Option, chunks: Vec, error: Option, } -impl Fixture { - fn new(events: Session) -> Self { - Self(events) - } - fn post(&self, request: Value) -> Projection { - let identity = chat_identity(); - let mut result = Projection { - json: None, - chunks: Vec::new(), - error: None, - }; - if request["stream"] == true { - let mut encoder = ChatStreamEncoder::new( - identity, - request["stream_options"]["include_usage"] == true, - ); - for event in &self.0.0 { - match encoder.push_event(event["type"].as_str(), event) { - Ok(chunks) => result.chunks.extend(chunks), - Err(error) => { - result.error = Some(error); - return result; - } +fn project_events(events: &[Value], streaming: bool, include_usage: bool) -> Projection { + let identity = chat_identity(); + let mut result = Projection { + json: None, + chunks: Vec::new(), + error: None, + }; + if streaming { + let mut encoder = ChatStreamEncoder::new(identity, include_usage); + for event in events { + match encoder.push_event(event["type"].as_str(), event) { + Ok(chunks) => result.chunks.extend(chunks), + Err(error) => { + result.error = Some(error); + return result; } } - match encoder.finish() { - Ok(chunks) => result.chunks.extend(chunks), - Err(error) => result.error = Some(error), - } + } + match encoder.finish() { + Ok(chunks) => result.chunks.extend(chunks), + Err(error) => result.error = Some(error), + } + } else { + let projected = if events.len() == 1 { + events[0] + .get("response") + .ok_or(ChatError::IncompleteStream) + .and_then(|value| project_response(value, &identity)) } else { - let projected = if self.0.0.len() == 1 { - self.0.0[0] - .get("response") - .ok_or(ChatError::IncompleteStream) - .and_then(|value| project_response(value, &identity)) - } else { - let mut encoder = ChatStreamEncoder::new(identity, true); - let mut accumulator = ChatAccumulator::default(); - let mut collect = || { - for event in &self.0.0 { - for chunk in encoder.push_event(event["type"].as_str(), event)? { - accumulator.push(&chunk)?; - } - } - for chunk in encoder.finish()? { + let mut encoder = ChatStreamEncoder::new(identity, true); + let mut accumulator = ChatAccumulator::default(); + let mut collect = || { + for event in events { + for chunk in encoder.push_event(event["type"].as_str(), event)? { accumulator.push(&chunk)?; } - Ok::<_, ChatError>(()) - }; - collect().and_then(|()| accumulator.finish()) + } + for chunk in encoder.finish()? { + accumulator.push(&chunk)?; + } + Ok::<_, ChatError>(()) }; - match projected { - Ok(value) => result.json = Some(value), - Err(error) => result.error = Some(error), - } + collect().and_then(|()| accumulator.finish()) + }; + match projected { + Ok(value) => result.json = Some(value), + Err(error) => result.error = Some(error), } - result } + result } fn json_body(response: Projection) -> Value { assert!(response.error.is_none(), "{:?}", response.error); response.json.unwrap() } -fn sse_body(response: Projection) -> (String, Vec) { +fn stream_chunks(response: Projection) -> (String, Vec) { assert!(response.error.is_none(), "{:?}", response.error); ( serde_json::to_string(&response.chunks).unwrap(), @@ -100,9 +81,6 @@ fn chat_identity() -> ChatIdentity { model: "model-a".to_owned(), } } -fn chat_request(stream: bool) -> Value { - json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream}) -} fn wire(kind: &str, mut value: Value) -> Value { value["type"] = json!(kind); value @@ -135,8 +113,8 @@ fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value { #[test] fn json_projects_public_identity_text_and_actual_usage() { - let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))])); - let response = fixture.post(chat_request(false)); + let events = vec![completed(json!([message("你好 🌍")]))]; + let response = project_events(&events, false, false); let body = json_body(response); assert_eq!(body["object"], "chat.completion"); assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-")); @@ -164,7 +142,7 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() { let mut answer = message(&text); answer["content"][0]["annotations"] = json!([citation]); for stream in [false, true] { - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_item.done", @@ -189,13 +167,11 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() { json!({"output_index":2,"item":answer}), ), completed(json!([])), - ])); - let mut request = chat_request(stream); - request["web_search_options"] = json!({}); - let response = fixture.post(request); + ]; + let response = project_events(&events, stream, false); let expected = format!("🌍 {text}"); if stream { - let (_, chunks) = sse_body(response); + let (_, chunks) = stream_chunks(response); assert_eq!(combined(&chunks, "content"), expected); assert_eq!( chunks.last().unwrap()["choices"][0]["finish_reason"], @@ -223,8 +199,8 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() { {"type":"message","id":"refusal1","role":"assistant","status":"completed", "content":[{"type":"refusal","refusal":"cannot help"}]}]), ] { - let fixture = Fixture::new(Session::new(vec![completed(output.clone())])); - let response = fixture.post(chat_request(false)); + let events = vec![completed(output.clone())]; + let response = project_events(&events, false, false); let body = json_body(response); let choice = &body["choices"][0]; assert_eq!(choice["message"]["content"], Value::Null); @@ -245,7 +221,7 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() { } #[test] -fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { +fn stream_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { for include_usage in [false, true] { let terminal = completed(json!([message("你好 🌍")])); let events = [ @@ -316,7 +292,7 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { } #[test] -fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() { +fn stream_preserves_interleaved_tools_and_reordered_terminal_snapshots() { let first = tool( "fc_first", "call_first", @@ -324,7 +300,7 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() { "{ \"city\": \"北京\" }", ); let second = tool("fc_second", "call_second", "search", "{\"query\":\"Rust\"}"); - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_item.added", @@ -355,8 +331,8 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() { json!({"output_index":2,"item":first}), ), completed(json!([second, first])), - ])); - let (_, chunks) = sse_body(fixture.post(chat_request(true))); + ]; + let (_, chunks) = stream_chunks(project_events(&events, true, false)); let mut tools = BTreeMap::::new(); for chunk in &chunks { if let Some(calls) = chunk["choices"][0]["delta"]["tool_calls"].as_array() { @@ -406,7 +382,7 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() { let mut text = message("preserved"); text["future_optional"] = json!({"opaque":true}); text["content"][0]["future_attribute"] = json!([1, 2, 3]); - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ wire("response.future_auxiliary", json!({"future":true})), wire( "response.future_reasoning.delta", @@ -414,8 +390,8 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() { ), created(), completed(json!([text])), - ])); - let (_, chunks) = sse_body(fixture.post(chat_request(true))); + ]; + let (_, chunks) = stream_chunks(project_events(&events, true, false)); assert_eq!(combined(&chunks, "content"), "preserved"); assert!( !chunks @@ -430,7 +406,7 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() { for streaming in [false, true] { let state = json!({"type":kind,"id":"ctx_1","encrypted_content":"opaque-private-state"}); - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_item.added", @@ -441,10 +417,10 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() { json!({"output_index":0,"item":state}), ), completed(json!([state, message("preserved")])), - ])); - let response = fixture.post(chat_request(streaming)); + ]; + let response = project_events(&events, streaming, false); if streaming { - let (text, chunks) = sse_body(response); + let (text, chunks) = stream_chunks(response); assert_eq!(combined(&chunks, "content"), "preserved"); assert!(!text.contains("opaque-private-state")); assert_eq!( @@ -474,10 +450,10 @@ fn incomplete_projects_only_supported_finish_reasons() { "id":"resp_chat_test","status":"incomplete","output":[message("partial")], "incomplete_details":{"reason":reason}}}), ); - let fixture = Fixture::new(Session::new(vec![created(), event])); - let response = fixture.post(chat_request(streaming)); + let events = vec![created(), event]; + let response = project_events(&events, streaming, false); if streaming { - let (_, chunks) = sse_body(response); + let (_, chunks) = stream_chunks(response); assert_eq!( chunks.last().unwrap()["choices"][0]["finish_reason"], expected @@ -497,7 +473,7 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected() "encrypted_content":"OPAQUE_ENCRYPTED_REASONING_MARKER" }); for streaming in [false, true] { - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_item.added", @@ -525,14 +501,10 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected() "output_tokens_details":{"reasoning_tokens":2,"accepted_prediction_tokens":1}} }}), ), - ])); - let mut request = chat_request(streaming); - if streaming { - request["stream_options"] = json!({"include_usage":true}); - } - let response = fixture.post(request); + ]; + let response = project_events(&events, streaming, true); let (body, content, usage) = if streaming { - let (body, chunks) = sse_body(response); + let (body, chunks) = stream_chunks(response); let usage = chunks .iter() .find(|chunk| chunk["choices"] == json!([])) @@ -572,12 +544,8 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() { json!({"id":"action_native","type":"computer_call","status":"completed","call_id":"call_action","action":{"type":"click","x":1,"y":2}}), ] { for streaming in [false, true] { - let fixture = Fixture::new(Session::new(vec![created(), completed(json!([output]))])); - let mut request = chat_request(streaming); - if streaming { - request["stream_options"] = json!({"include_usage":true}); - } - let response = fixture.post(request); + let events = vec![created(), completed(json!([output]))]; + let response = project_events(&events, streaming, true); assert_eq!(response.error, Some(ChatError::InvalidResponse)); assert!( !response @@ -592,16 +560,15 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() { #[test] fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() { - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_text.delta", json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"partial"}), ), - ])); - let mut body = chat_request(true); - body["stream_options"] = json!({"include_usage":true}); - let response = fixture.post(body); + ]; + + let response = project_events(&events, true, true); assert_eq!(response.error, Some(ChatError::IncompleteStream)); assert!( !response @@ -618,16 +585,15 @@ fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() { } #[test] -fn first_batch_terminal_can_finish_without_creating_usage_facts() { - let fixture = Fixture::new(Session::new(vec![wire( +fn completed_event_without_usage_does_not_invent_usage() { + let events = vec![wire( "response.completed", json!({"response":{ "id":"resp_chat_test","status":"completed","output":[message("done only")] }}), - )])); - let mut body = chat_request(true); - body["stream_options"] = json!({"include_usage":true}); - let (_, chunks) = sse_body(fixture.post(body)); + )]; + + let (_, chunks) = stream_chunks(project_events(&events, true, true)); assert_eq!(combined(&chunks, "content"), "done only"); assert_eq!( chunks @@ -643,7 +609,7 @@ fn first_batch_terminal_can_finish_without_creating_usage_facts() { fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() { let output = json!({"id":"msg_refusal","type":"message","role":"assistant","status":"completed", "content":[{"type":"refusal","refusal":"cannot help"}]}); - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.refusal.delta", @@ -654,8 +620,8 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() { json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"}), ), completed(json!([output])), - ])); - let (_, chunks) = sse_body(fixture.post(chat_request(true))); + ]; + let (_, chunks) = stream_chunks(project_events(&events, true, false)); assert_eq!(combined(&chunks, "refusal"), "cannot help"); assert_eq!(combined(&chunks, "content"), ""); assert_eq!( @@ -667,23 +633,20 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() { #[test] fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() { for with_created in [false, true] { - // 终态与辅助事件同属一批 Core 交付 不构造已终结会话继续产出事件的另一种异常 - let session = Session::new(if with_created { + let mut events = if with_created { vec![created()] } else { Vec::new() - }) - .with_batch(vec![ + }; + events.extend([ completed(json!([message("completed text")])), wire( "response.future_metadata", json!({"response_id":"resp_chat_test","future":{"kept":true}}), ), ]); - let fixture = Fixture::new(session); - let mut body = chat_request(true); - body["stream_options"] = json!({"include_usage":true}); - let (_, chunks) = sse_body(fixture.post(body)); + + let (_, chunks) = stream_chunks(project_events(&events, true, true)); assert_eq!(combined(&chunks, "content"), "completed text"); assert_eq!( chunks @@ -727,10 +690,9 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() { failure } }; - let fixture = Fixture::new(Session::new(vec![created(), failure])); - let mut body = chat_request(true); - body["stream_options"] = json!({"include_usage":true}); - let (_, chunks) = sse_body(fixture.post(body)); + let events = vec![created(), failure]; + + let (_, chunks) = stream_chunks(project_events(&events, true, true)); let errors = chunks .iter() .filter_map(|chunk| chunk.get("error")) @@ -749,15 +711,15 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() { #[test] fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() { - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_text.delta", json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"}), ), completed(json!([message("different result")])), - ])); - let response = fixture.post(chat_request(true)); + ]; + let response = project_events(&events, true, false); assert_eq!(response.error, Some(ChatError::InvalidResponse)); assert_eq!(combined(&response.chunks, "content"), "already sent"); assert!( @@ -795,7 +757,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream initial_custom["input"] = json!(""); let mut initial_function = function.clone(); initial_function["arguments"] = json!(""); - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_item.added", @@ -818,10 +780,10 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream json!({"output_index":0,"item_id":"ct_1","input":"first\nsecond"}), ), completed(output.clone()), - ])); - let response = fixture.post(chat_request(streaming)); + ]; + let response = project_events(&events, streaming, false); if streaming { - let (body, chunks) = sse_body(response); + let (body, chunks) = stream_chunks(response); assert_eq!(combined(&chunks, "refusal"), "no"); assert_eq!(combined(&chunks, "reasoning_content"), "thought"); assert!(!body.contains("PRIVATE_REASONING")); @@ -870,7 +832,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() { let image = json!({"id":"ig_one","type":"image_generation_call","status":"completed","result":"ZmluYWw=","output_format":"webp"}); for streaming in [false, true] { - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.image_generation_call.partial_image", @@ -881,10 +843,10 @@ fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() { json!({"output_index":0,"item":image}), ), completed(json!([image, message("created")])), - ])); - let response = fixture.post(chat_request(streaming)); + ]; + let response = project_events(&events, streaming, false); if streaming { - let (_, chunks) = sse_body(response); + let (_, chunks) = stream_chunks(response); let images = chunks .iter() .filter_map(|chunk| chunk["choices"][0]["delta"]["images"].as_array()) @@ -913,7 +875,7 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() { let mut output = message("hello"); output["content"][0]["logprobs"] = probabilities.clone(); for streaming in [false, true] { - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_text.delta", @@ -924,10 +886,10 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() { json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","text":"hello","logprobs":probabilities}), ), completed(json!([output])), - ])); - let response = fixture.post(chat_request(streaming)); + ]; + let response = project_events(&events, streaming, false); if streaming { - let (_, chunks) = sse_body(response); + let (_, chunks) = stream_chunks(response); let values = chunks .iter() .filter_map(|chunk| chunk["choices"][0]["logprobs"]["content"].as_array()) @@ -951,7 +913,7 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() { first["content"][0]["annotations"] = json!([citation]); let mut second = message("xy"); second["id"] = json!("msg_second"); - let fixture = Fixture::new(Session::new(vec![ + let events = vec![ created(), wire( "response.output_text.delta", @@ -970,8 +932,8 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() { json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","annotation_index":0,"annotation":citation}), ), completed(json!([first, second])), - ])); - let (_, chunks) = sse_body(fixture.post(chat_request(true))); + ]; + let (_, chunks) = stream_chunks(project_events(&events, true, false)); assert_eq!(combined(&chunks, "content"), "abxycd"); let annotations = chunks .iter() diff --git a/backend/crates/providers/openai/tests/admin/provider.rs b/backend/crates/providers/openai/tests/admin/provider.rs index d4ef5f8a8..f02d9b75d 100644 --- a/backend/crates/providers/openai/tests/admin/provider.rs +++ b/backend/crates/providers/openai/tests/admin/provider.rs @@ -603,7 +603,7 @@ async fn openai_admin_provider_exposes_live_wire_profile_and_validated_billing() } #[tokio::test] -async fn openai_legacy_billing_should_not_infer_long_context_flag() { +async fn openai_billing_reconstruction_does_not_infer_long_context_flag() { let config = valid_config(); let bundle = provider_openai::initialize( config.config.clone(), @@ -626,7 +626,7 @@ async fn openai_legacy_billing_should_not_infer_long_context_flag() { amount: "1.5".parse().expect("stored total"), }, }) - .expect("legacy billing") + .expect("reconstructed billing") .expect("matching billing breakdown"); assert_eq!(billing.total_amount.amount.as_str(), "1.5"); diff --git a/backend/crates/providers/openai/tests/credential/quota/bucket_warmup.rs b/backend/crates/providers/openai/tests/credential/quota/bucket_warmup.rs index 0fb506843..41a72afe4 100644 --- a/backend/crates/providers/openai/tests/credential/quota/bucket_warmup.rs +++ b/backend/crates/providers/openai/tests/credential/quota/bucket_warmup.rs @@ -112,7 +112,7 @@ async fn mount_warmup(server: &MockServer, expected: u64) { } #[tokio::test] -async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart() { +async fn second_precision_progress_waits_five_minutes_and_claim_survives_restart() { let (store, server, now, reset) = setup().await; let quota = service(&store, &server); mount_usage(&server, reset + 604800, 0, 1).await; @@ -128,13 +128,13 @@ async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart() ); assert!(server.received_requests().await.unwrap().is_empty()); let account = store.account("acct_bucket_warmup").unwrap(); - let mut legacy = store + let mut stored = store .load_quota_warmup_state(&account) .await .unwrap() .unwrap(); - // 升级前的进度以整秒持久化,新读取器仍须沿用该边界与并发领取约束。 - legacy.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset); + // 整秒时间戳沿用同一预热边界与并发领取约束 + stored.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset); let observed_at = store .get_quotas(std::slice::from_ref(account.id())) .await @@ -144,9 +144,9 @@ async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart() store .compare_and_swap_quota_warmup_state(QuotaWarmupStateUpdate { account: &account, - expected_version: legacy.version, + expected_version: stored.version, expected_quota_observed_at: Some(observed_at), - data: legacy.data, + data: stored.data, }) .await .unwrap() diff --git a/backend/crates/providers/openai/tests/credential/quota/slots.rs b/backend/crates/providers/openai/tests/credential/quota/slots.rs index e3f62b172..38e55fa29 100644 --- a/backend/crates/providers/openai/tests/credential/quota/slots.rs +++ b/backend/crates/providers/openai/tests/credential/quota/slots.rs @@ -486,13 +486,13 @@ async fn a_new_exhaustion_cannot_reuse_partial_recovery_from_the_previous_failur } #[tokio::test] -async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() { +async fn stored_weekly_exhaustion_uses_window_evidence_over_account_reset() { let store = Arc::new(MemoryAccountStore::default()); - create_account(&store, "acct_old_weekly").await; - let account = store.account("acct_old_weekly").expect("account"); + create_account(&store, "acct_weekly_reset").await; + let account = store.account("acct_weekly_reset").expect("account"); let observed_at = SystemTime::now(); - let mut old = usage((88, SHORT_RESET), (100, WEEK_RESET)); - old["rate_limit"]["allowed"] = json!(false); + let mut stored = usage((88, SHORT_RESET), (100, WEEK_RESET)); + stored["rate_limit"]["allowed"] = json!(false); store .compare_and_swap_quota(gateway_core::account::QuotaObservation { quota_pause: None, @@ -501,7 +501,7 @@ async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() { account_id: account.id().clone(), expected_revision: account.revision(), quota: gateway_core::account::OpaqueProviderData::new( - old.as_object().expect("document").clone(), + stored.as_object().expect("document").clone(), ), observed_at, state: QuotaState::exhausted( @@ -511,7 +511,7 @@ async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() { ), }) .await - .expect("seed old persisted quota"); + .expect("seed stored quota"); let server = MockServer::start().await; let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri()); mount_usage(&server, usage((88, SHORT_RESET), (0, WEEK_RESET + 604_800))).await; @@ -565,7 +565,7 @@ async fn an_unknown_slot_establishes_a_baseline_before_it_can_recover() { } #[tokio::test] -async fn legacy_exhaustion_recovers_after_two_nonfull_observations_despite_reset_drift() { +async fn exhaustion_without_reset_recovers_after_two_nonfull_observations_despite_reset_drift() { for (first, second) in [(0, 1), (1, 1), (2, 2), (2, 60), (3600, 7200)] { let store = Arc::new(MemoryAccountStore::default()); let id = "acct_drifting_reset"; @@ -579,7 +579,7 @@ async fn legacy_exhaustion_recovers_after_two_nonfull_observations_despite_reset old["rate_limit"]["allowed"] = json!(true); mount_usage(&server, old).await; service.refresh_account(account.id()).await.unwrap(); - // 旧版流内拒绝保留最近的用量,但未记录错误 reset,两个窗口都需复核 + // 拒绝状态缺少重置时间时,两个窗口都需复核 persist_quota_state(&store, &account, exhausted_quota(None)).await; for (offset, exhausted) in [(first, true), (second, false)] { let mut fresh = usage((0, now + 18_000), (16, week + offset)); diff --git a/backend/crates/providers/xai/tests/admin/provider.rs b/backend/crates/providers/xai/tests/admin/provider.rs index f3c71324e..880a02fa1 100644 --- a/backend/crates/providers/xai/tests/admin/provider.rs +++ b/backend/crates/providers/xai/tests/admin/provider.rs @@ -261,7 +261,7 @@ async fn xai_admin_provider_validates_known_billing_breakdown() { } #[tokio::test] -async fn xai_legacy_billing_should_not_infer_long_context_flag() { +async fn xai_billing_reconstruction_does_not_infer_long_context_flag() { let bundle = provider_xai::initialize(provider_ports()) .await .expect("xAI bundle"); @@ -279,7 +279,7 @@ async fn xai_legacy_billing_should_not_infer_long_context_flag() { amount: "0.8".parse().expect("stored total"), }, }) - .expect("legacy billing") + .expect("reconstructed billing") .expect("matching billing breakdown"); assert_eq!(billing.total_amount.amount.as_str(), "0.8"); diff --git a/backend/migrations/README.md b/backend/migrations/README.md index 785d9fb13..d295cd916 100644 --- a/backend/migrations/README.md +++ b/backend/migrations/README.md @@ -32,20 +32,27 @@ sha256sum --check --strict .frozen-sha256 ## 本地测试库 -`gateway-store` 的 PostgreSQL/Redis 集成测试使用以下环境变量;所需测试服务未配置时,本地相关测试跳过,CI 直接失败: +为集成测试准备专用 PostgreSQL 与 Redis 实例,服务启动方式见[开发指南](../../docs/development.md#启动宿主)。测试会创建随机 schema、Redis key 和临时认证用户,不能连接生产实例 + +- PostgreSQL 测试用户需要创建、删除 schema 和角色的权限 +- Redis 测试用户需要读写测试键、执行脚本及创建、删除 ACL 用户的权限 +- 备份恢复测试需要在测试进程的 `PATH` 中提供与 PostgreSQL 服务端版本匹配的 `pg_dump` 和 `psql` + +在运行测试的终端设置连接信息,两条 URL 都须包含符合 [Store 密码要求](../../deploy/README.md#手动安装)的密码。测试凭据可使用 `openssl rand -hex 24` 生成的十六进制值,避免 URL 转义 ```bash export CPR_TEST_DATABASE_URL='postgres://:@127.0.0.1:5432/' export CPR_TEST_REDIS_URL='redis://:@127.0.0.1:6379' +unset CPR_DATABASE_URL CPR_REDIS_URL CPR_DATABASE_PASSWORD CPR_REDIS_PASSWORD ``` -插件 Runtime 的真实子进程与持久化测试可使用专用的 `CPR_PLUGIN_TEST_DATABASE_URL`,此时须同时设置 `CPR_PLUGIN_TEST_REDIS_URL`。省略插件数据库 URL 时使用上面的测试服务 +将占位值替换为测试服务的实际用户、密码和数据库名。测试 URL 携带密码;部署配置仍将 URL 与密码分开,清除上述部署环境变量可避免它们覆盖测试配置 -使用专用开发或测试实例,测试通过随机 schema 和 Redis key 前缀隔离数据。凭据取自部署配置或 CI Secret,不要分享未脱敏的 `docker inspect` 输出 +插件 Runtime 的真实子进程与持久化测试默认复用这组服务。需要单独实例时,同时设置 `CPR_PLUGIN_TEST_DATABASE_URL` 与 `CPR_PLUGIN_TEST_REDIS_URL`,密码要求相同 -PostgreSQL 的临时 schema 测试连接使用异步提交,保留事务可见性、回滚和完整迁移检查 -需要验证数据库崩溃后的持久性时,使用独立数据库与生产连接配置,不复用这类 fixture +按[后端验证命令](../../docs/architecture.md#验证命令)运行测试。Store 用例在所需 URL 缺失时本地提前返回;插件 Runtime 用例在两组数据库 URL 均未设置时本地提前返回,选定数据库后缺少对应 Redis URL 会失败。CI 要求配置测试服务 -运行包含 `StoreBundle` 初始化的完整集成测试时,两条测试 URL 都须包含密码,原始密码须满足 -[Store 密码要求](../../deploy/README.md#手动安装),在测试 URL 中按 URL 规则编码。 -在测试进程中清除 `CPR_DATABASE_URL`、`CPR_REDIS_URL`、`CPR_DATABASE_PASSWORD` 和 `CPR_REDIS_PASSWORD`,避免部署环境覆盖测试配置 +提前返回的用例可能仍显示通过,不能据此认定 PostgreSQL / Redis 行为已验证。URL 已设置但连接失败时,用例会失败,不按未配置处理 + +Store 的 PostgreSQL 临时 schema 夹具执行完整迁移集,并为这些测试连接设置异步提交,验证现行读写、事务可见性与回滚。 +验证数据库崩溃后的持久性须使用独立数据库与生产连接配置,不复用这类夹具 diff --git a/docs/api.md b/docs/api.md index 8a2498b72..b63149a82 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1278,7 +1278,7 @@ call 与账号的绑定保存在网关进程内,未连接时一小时过期; | `GET` | `/api/key-usage/overview` | `period?`、`asOf?` 或 `startTime?`、`endTime?`,另含 `model?` | 用量汇总、趋势、当前额度和锚点所在日期的健康时间线 | | `GET` | `/api/key-usage/records` | 同上,另含 `kind?`、`currentPage?`、`pageSize?` | 当前 Key 的请求记录 | | `GET` | `/api/key-usage/config` | 无 | 当前 Key 的客户端配置凭据 | -| `GET` | `/api/key-usage/version` | 无 | “关于”弹窗使用的当前版本号和提交号 | +| `GET` | `/api/key-usage/version` | 无 | 当前版本号和提交号 | 用量查询支持[页面时间合同](#页面时间合同),默认 `period=7d`,一次最多 31 天。模型按字面量包含匹配,区分大小写,通配符按普通字符处理 不接受 Key ID、账号、Provider 等范围参数或其他未知字段。页码默认 1,每页默认 20,允许 1–100 条; @@ -1512,11 +1512,7 @@ Key 预算及其访问状态随互联默认公开,不要求开启 `shareQuota` 最多 256 项,每个 ID 最多 256 字节;重复 ID 去重,不接受空白、控制字符、`__` 前缀或 `*` 通配符。 允许保存当前上游目录尚未返回的 ID。限制按全局模型映射后的上游 ID 判断,不扩大账号本身的上游权限。 -管理端刷新目录只更新目录,不修改模型限制。全选与取消全选只作用于上游目录中符合当前搜索条件的模型。 -账号和分组白名单均可一键勾选 `gpt-image-2` 和 `gpt-image-1.5`。 -自定义模型取消勾选后在本次编辑期间保留,可再次勾选。保存时以最终选中项更新限制,关闭或取消编辑会丢弃草稿。 -白名单的清理按钮列出当前目录未返回的已选 ID,默认不选中任何项, -由管理员确认后从当前表单移除,保存账号后生效。目录未就绪、刷新失败或返回空目录时不能清理,清理也不能将白名单置空。 +刷新模型目录不修改已保存的模型限制。 图像、搜索、插件适配模型和映射目标可能不在目录中,目录缺失本身不代表模型失效。 例如 Plus 设置 `allowlist` 并选中 luna 的实际 ID,Pro 设置 `denylist` 并选中同一 ID,即可严格分流; Pro 使用 `all` 时也能参与 luna 调度。套餐名称不自动生成或修改规则 @@ -2271,12 +2267,51 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c | `POST` | `/api/admin/client-keys/disable` | `{ id }` | 禁用 | | `POST` | `/api/admin/client-keys/delete` | `{ id }` | 删除 | +### 列表查询 + +`GET /api/admin/client-keys` 接受以下可选参数: + +| 参数 | 默认值 | 约束 | +| --- | --- | --- | +| `limit` | `50` | 每页数量,整数 `1`–`65535` | +| `search` | 不筛选 | 去除首尾空白后最多 256 字节,不能包含控制字符;空字符串等同于未提供 | +| `sortBy` | `createdAt` | `name`、`enabled`、`createdAt` 或 `lastUsedAt` | +| `sortDirection` | `desc` | `asc` 或 `desc` | +| `cursor` | 从第一页开始 | 原样传入上次返回的 `nextCursor`;非空且最多 512 字节,不自行构造或解析 | + +响应 `data` 为 `{ items, nextCursor, total }`。`total` 为满足搜索条件的总数,`nextCursor: null` 表示已到末尾。 +翻页时保持搜索和排序条件,`limit` 可调整;切换搜索或排序时省略 `cursor`,重新读取第一页。 +游标绑定排序字段和方向;非法参数、未知查询字段、无效游标或排序不匹配均返回 `400` / `40001` + +搜索仅匹配名称和标签,不匹配密钥值或可见前缀;不区分大小写,使用字面量包含匹配,`%`、`_` 和 `\` 按普通字符处理。 +名称排序不区分大小写,`lastUsedAt` 为空的记录始终排在最后;排序值相同时按 Key ID 同方向排序 + +### 统计与窗口对齐 + 两个统计接口按部署时区和请求开始时间统计近 7 天(`7d`,默认)或 30 天(`30d`)。概览返回截止时间 `asOf`(Unix 毫秒),切换指标与读取明细时可用其固定统计区间。趋势按 `metric`(`costUsd`、`tokens`、`requests`)返回周期排名前五的模型,其余合为一条曲线(`model: null`)。模型优先取上游实际模型,缺失时回退到请求模型,两者都缺失时为空字符串 模型和周期合计包含请求数、已知 Token、已知 USD 费用,以及费用是否含本地估算或存在缺失。无已知数值时对应金额或 Token 为 `null`,费用占比以该 Key 周期内的已知 USD 总额为分母 手动对齐使用密钥可访问分组内账号的当前整账号 24 小时或七天窗口。确认时复核预览边界和密钥窗口版本,按完成时间重算本期消费。窗口到期后密钥恢复原生日历规则。已失效的预览或不足以重算的费用历史返回冲突 +### 创建与更新密钥 + +创建字段为 `name`、可选 `label`、`groupIds`、`maxConcurrency`、`requestsPerMinute`、可选 +`dailyLimitUsd`、`weeklyLimitUsd`、`customKey`、`providerRequestProfileOverrides`、`peerSharing` 和 `validity`。更新请求携带 `id`,不接受 `customKey`。 +`groupIds` 必须显式提交:空数组派生 `routingScope: "all"`,非空数组派生 +`routingScope: "groups"`。列表项返回分组引用 `groups`,以及从当前有效账号池派生、仅供展示的 `providerKinds` + +创建成功返回 `201`,`data` 为 `{ id, prefix, plaintextKey }`;reveal 返回 `{ id, plaintextKey }`。 +这两个响应包含完整明文 Key,调用方须安全保存。单个 Key 的更新、启用、禁用和删除返回 `{ id }`,完整配置通过列表查询读取 + +`peerSharing` 为 `{ enabled, sharePool, shareQuota, sharePlans }`,各项均为布尔值且默认 `false`。 +创建时省略保持关闭;更新时省略或 `null` 保留整个配置,提交对象时替换完整配置,对象内省略项为 `false`。 +列表项返回完整对象。`sharePlans` 需要 `sharePool`;开启 `enabled` 必须提交非空 `groupIds`, +推理允许使用这些组内的 OAuth 和 API Key 账号,[CPR 互联导出](#cpr-互联只读协议) 仅公开本地直连账号的观测。 +账号池、原生额度窗口、套餐分布分别按对应开关公开;关闭共享不改变已保存的其他开关值 + +### 批量更新 + 批量更新只提交要修改的字段,各密钥保留其余配置。任一密钥或分组不存在、任一密钥的最终配置无效时,整批回滚 - `enabled` 设置启用状态。`groupIds` 替换全部分组,显式传空数组授权全部当前及未来账号 @@ -2284,19 +2319,6 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c - `peerSharing` 可单独修改 `enabled`、`sharePool`、`shareQuota`、`sharePlans`。开启互联需要绑定分组,共享套餐构成需要开启账号池概览 - `providerRequestProfileOverrides` 按 Provider 更新,显式传入某个 Provider 为 `null` 时恢复其全局配置。`installationSeed` 单独接受 UUID;仅修改身份配置时保留各密钥原有种子,仅修改种子时保留各自的身份配置 -创建字段为 `name`、可选 `label`、`groupIds`、`maxConcurrency`、`requestsPerMinute`、可选 -`dailyLimitUsd`、`weeklyLimitUsd`、`customKey`、`providerRequestProfileOverrides` 和 `peerSharing`。更新请求携带 `id`,不接受 `customKey`。 -`groupIds` 必须显式提交:空数组派生 `routingScope: "all"`,非空数组派生 -`routingScope: "groups"`。响应同时返回分组引用 `groups`,以及从当前有效账号池派生、仅供展示的 -`providerKinds`。创建和 reveal 响应会返回完整明文 Key,调用方 -必须立即安全保存 - -`peerSharing` 为 `{ enabled, sharePool, shareQuota, sharePlans }`,各项均为布尔值且默认 `false`。 -创建时省略保持关闭;更新时省略或 `null` 保留整个配置,提交对象时替换完整配置,对象内省略项为 `false`。 -列表、创建及更新响应均返回完整对象。`sharePlans` 需要 `sharePool`;开启 `enabled` 必须提交非空 `groupIds`, -推理允许使用这些组内的 OAuth 和 API Key 账号,[CPR 互联导出](#cpr-互联只读协议) 仅公开本地直连账号的观测。 -账号池、原生额度窗口、套餐分布分别按对应开关公开;关闭共享不改变已保存的其他开关值 - ### Key 客户端身份 `providerRequestProfileOverrides` 按 Provider ID 保存身份选择,列表返回同名对象。创建时各项为完整配置对象, @@ -2313,7 +2335,6 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范 ### 名称与密钥值 -密钥列表的 `search` 仅匹配名称和标签,不匹配密钥值或可见前缀;搜索不区分大小写,使用字面量包含匹配,`%`、`_` 和 `\` 按普通字符处理。 创建和更新时去除名称首尾空白,并按忽略大小写、首尾空格的名称查重,重复返回 `409`。 更新排除当前记录,并发写入同样执行查重;失败不会留下审计或配置版本变更。 已有同名 Key 的凭据有效,编辑时须使用未被其他 Key 占用的名称 @@ -2324,7 +2345,7 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范 应用不另设 Key 长度上限;创建请求和 `Authorization` 头仍受 Web 服务器及反向代理的通用大小限制。 更新接口不接受 `customKey`,防止修改策略时意外替换正在使用的凭据。 列表仅展示最多前 10 个字符,且至少隐藏一半字符;单字符 Key 的可见前缀为空。 -完整值仍只通过创建和显式 reveal 返回,不进入普通 Debug 或审计 +完整密钥不进入普通 Debug 或审计 自定义 Key 创建示例: @@ -2340,7 +2361,6 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范 创建、更新可传 `validity`,其中 `startsAt`、`expiresAt` 为带时区的 RFC3339 时间点。起点包含在有效期内,到达终点即失效。起止时间须成对填写,终点须晚于起点。 创建时默认立即生效且长期有效;更新时省略整个对象保留原有效期,传入对象会替换两个边界,两者同时为空可恢复长期有效。 -管理页面使用浏览器本地时间选择起止日期和时分秒。新建默认留空,选择日期时默认 00:00:00;7 天和 30 天从今天零点起按日历日计算。 列表提供 `validity`、查询时的 `validityStatus`(`scheduled`、`active`、`expired`)和按部署时区格式化的 `startsAtDisplay`、`expiresAtDisplay`。手动重置额度保留密钥有效期 自定义 Key 的分组权限、日/周限额和并发规则按本平台配置执行,不导入其他平台的历史用量 diff --git a/docs/architecture.md b/docs/architecture.md index 24c94f50b..066e70726 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -347,7 +347,7 @@ Provider 可为模型提供来源账号集合;Core 在公开目录查询时结 客户端原生模型目录同样由 Provider 拥有,通过 `ExecutionService` 和现有 Registry 的只读调用传递。 `routing::catalog` 的原生条目只包含模型 ID 与不透明协议正文,Core 负责冻结账号范围和整对象模型映射, 不解析上游字段;API 负责协议输出,不直接依赖具体 Provider。原生目录失败不会退回通用画像,只有不提供 -该协议原生目录的 Provider才走画像转换。目录读取不创建计量请求或推理 attempt。 +该协议原生目录的 Provider 才走画像转换。目录读取不创建计量请求或推理 attempt 请求位置、隐私、Fast 和生图的跨层策略见[请求策略与事实](#请求策略与事实),Provider 目录的刷新与凭据隔离见[账号模型目录](#账号模型目录) @@ -508,23 +508,7 @@ Client Key 鉴权完成后,API adapter 从有界请求头识别客户端,Cor 生成请求按模型目录编译候选;全局模型映射是精确映射,未命中时模型名原样交给候选 Provider。 Responses、Messages、GenAI 和 Chat 保留各自的正文与协议事实进入共用 Generate 执行链。 HTTP、request 与 attempt 中间件处理当前入站协议,endpoint 保留客户端路由。 -原生请求只匹配声明同协议能力的候选;Chat 由 Provider 选定账号后直接转换到目标协议,`outbound` 处理实际发送的请求 - -Core 独占路由、重试、交付事实与结算;Provider 独占上游身份、账号相关适配、隐私策略及账号隔离。 -`gateway-protocol` 的 `openai/`、`anthropic/`、`genai/` 保留原生解析; -`chat_completions/{responses,messages,genai}/` 分别直接映射请求、完整响应和流事件,不借另一平台协议中转。 -转换器只保留本次响应身份、增量状态及工具名称映射,不持有输入历史、账号、连接或调度状态。 -API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。 -Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果 - -运行设置快照编译并共享提示词改写匹配器,支持字面前缀和正则,按配置顺序索引全局规则和各上游规则。路由计划冻结快照,每次尝试只取所选平台的适用规则。attempt 中间件提交后,协议层定位系统文本,Core 匹配开头;管理端预览复用同一匹配器。生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串。计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则 - -原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。 -内置转换只能从 Chat 来源调用;显式插件仍按现有能力声明与中间件合同运行。 -字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt) - -Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。 -Core 按原始协议提取搜索能力要求,Chat 的 `web_search_options` 同样参与候选筛选;Provider 校验实际目标是否支持声明的搜索选项 +Provider 选定账号后完成适配,`outbound` 处理实际发送的请求;原生协议和 Chat 转换的职责见[生成协议与转换](#生成协议与转换) Images 与 standalone Search 是 OpenAI Provider 自有端点:两者都不参与文本模型映射,只在 Client Key 的账号范围确实包含 Codex 账号时生成单一 OpenAI 候选。Images 的图片模型由 Provider 从正文旁路 @@ -543,6 +527,14 @@ API 暂存的下一轮请求和连接泵接收队列共用容量名额,控制 `GenerateRequest` 在构造或替换正文时重算事实,仅改上下文不重复扫描正文;跨协议转换保留来源请求的能力约束和生图事实。 Core 将这些事实转为路由能力要求与生图权限判断,协议解析不决定是否允许请求 +Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。 +Core 按原始协议提取搜索能力要求,Chat 的 `web_search_options` 同样参与候选筛选;Provider 校验实际目标是否支持声明的搜索选项 + +运行设置快照编译并共享提示词改写匹配器,按配置顺序索引全局规则和各上游规则,路由计划冻结快照,每次尝试只取所选平台的适用规则。 +attempt 中间件提交后,协议层定位系统文本,Core 匹配开头;管理端预览复用同一匹配器。 +生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串;计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则。 +规则格式与匹配行为见[提示词改写](api.md#提示词改写) + 全局请求位置及开关由运行设置持久化,快照仅在开关开启时生成全局覆盖,并随 `RuntimeSnapshot → RoutingPlan → AttemptContext` 冻结传递。Provider 在选定账号后优先应用代理位置, 出站字段遵循[请求位置合同](api.md#独立代理管理--managed-proxies)。请求期间不额外查询全局设置,配置发布不改变已开始请求的全局值 @@ -573,10 +565,11 @@ WS 路由提示属于握手,连接复用时不重发;档位变化不重建 ## 5. Provider 与协议边界 -Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 canonical event,不读取 Provider SDK -类型。Provider 独占 credential schema、OAuth、账号选择、模型目录、额度投影和上游 transport +Core 独占路由、重试、交付事实与结算,只理解 `Operation`、能力要求、Provider 候选、稳定错误和 canonical event, +不读取 Provider SDK 类型。Provider 独占 credential schema、OAuth、账号选择、模型目录、额度投影、上游身份与 transport, +负责选中账号的协议适配、隐私规则解释与执行,以及账号隔离 -三个内置 Provider 在各自的 `lib.rs` 返回同一个 `ProviderBundle`。组合根从这一组 Bundle 注册执行器、管理端口和后台任务。共同职责使用一致目录: +三个内置 Provider 分别在各自的 `lib.rs` 构造 `ProviderBundle`。组合根从这一组 Bundle 注册执行器、管理端口和后台任务。共同职责使用一致目录: | 目录 | 职责 | | --- | --- | @@ -587,8 +580,6 @@ Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 ca | `provider/` | 推理执行和 worker 装配 | | `transport/` | 出站协议与上游响应采集 | -Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号;OAuth 使用该账号的授权项目,API Key 直接请求配置的 GenAI 地址,停用账号仍可接受探测 - 数据面入口位于 `gateway-api/src/data_plane`,按协议、客户端扩展和平台专属端点划分职责: - `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期 @@ -597,11 +588,38 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模 - `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有 - `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者 +### 生成协议与转换 + +`gateway-protocol` 的 `openai/`、`anthropic/`、`genai/` 保留原生解析; +`chat_completions/{responses,messages,genai}/` 分别直接映射请求、完整响应和流事件,不借另一平台协议中转。 +原生请求只匹配声明同协议能力的候选,Chat 由 Provider 选定账号后直接转换到目标协议 + +原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。 +内置转换只能从 Chat 来源调用;显式插件仍按其能力声明与中间件合同运行 + +Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。 +选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段 + +Chat 响应在 Core 的响应中间件阶段之间直接转换。转换器只保留本次响应身份、增量状态及工具名称映射, +不持有输入历史、账号、连接或调度状态,也不增加账号级签名缓存或对话副本。 +正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态,转换状态随单次流释放 + +API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。 +Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果。 +字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt) + +### GenAI 目录与原生传输 + +Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号;OAuth 使用该账号的授权项目,API Key 直接请求配置的 GenAI 地址,停用账号仍可接受探测 + GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity OAuth 将选中的 GenAI 请求封装为 Cloud Code 上游请求,API Key 直接请求公开 GenAI 路径 -Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。 +GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。 +API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录 -GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录。Antigravity 声明生成与输入计数能力,API Key 目录按 `supportedGenerationMethods` 区分生成与计数,选号再次核对所选账号的声明。计数复用选号、中间件及资源释放流程;OAuth 调用 Cloud Code `countTokens`,API Key 调用原生模型的 `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算 +Antigravity 声明生成与输入计数能力,API Key 目录按 `supportedGenerationMethods` 区分生成与计数,选号再次核对所选账号的声明。 +计数复用选号、中间件及资源释放流程;OAuth 调用 Cloud Code `countTokens`,API Key 调用原生模型的 `countTokens`。 +计数响应不产生生成用量或费用事实,失败不切换为本地估算 Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。 `provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实, @@ -617,8 +635,6 @@ Antigravity 的 Cloud Code 传输按下游生成模式选择普通 JSON 或 SSE Cloud Code 连接使用 rustls 与 HTTP/1.1,gzip 协商和流式解压由本 Provider 持有,不启用会影响其他 Provider 的 reqwest 全局压缩特性。解压后的流继续遵循控制面和推理消费方的大小限制、取消及截止时间 -Chat 响应在 Core 的响应中间件阶段之间直接转换。转换器在正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态。转换状态随单次流释放,不增加账号级签名缓存或对话副本 - ### 连接与上游身份 Responses 下游连接的心跳和退出由 API 拥有,每条 WS 使用独立取消信号,沿 Core 的 `ResponseControl` 传到 Provider 请求上下文。 diff --git a/docs/development.md b/docs/development.md index 04fff5b0b..050268b66 100644 --- a/docs/development.md +++ b/docs/development.md @@ -6,6 +6,7 @@ | --- | --- | | 修改宿主前后端 | [环境与依赖](#环境与依赖) → [启动宿主](#启动宿主) | | 定位模块与共享实现 | [源码入口](#源码入口) | +| 验证后端改动 | [测试环境](../backend/migrations/README.md#本地测试库) → [验证命令](architecture.md#验证命令) | | 同时修改 UI 或插件 | [源码联调](#源码联调) → [启动与检查](#启动与检查) | | 验证本地 SDK | [本地 SDK 验证](#本地-sdk-验证) | | 提交跨仓库改动 | [编辑与提交](#编辑与提交) | @@ -31,10 +32,10 @@ pnpm --dir frontend install --frozen-lockfile 使用源码仓库自带的 Compose 与配置模板,按[手动安装](../deploy/README.md#手动安装)中的配置与权限要求准备 `deploy/config.yaml` 和 `.runtime/` 目录 -数据库及 Redis 可由 Compose 启动: +启动数据库与 Redis,等待健康检查通过后运行后端: ```bash -docker compose -f deploy/compose.yaml up -d postgres redis +docker compose -f deploy/compose.yaml up -d --wait postgres redis cargo +1.99.1 run --manifest-path backend/Cargo.toml -p codex-proxy-rs --locked ``` @@ -48,7 +49,7 @@ cargo +1.99.1 run --manifest-path backend/Cargo.toml -p codex-proxy-rs --locked pnpm --dir frontend dev ``` -后端代理由 `frontend/vite.config.ts` 配置,验证 WebSocket 时直接连接后端 +访问管理端开发服务输出的地址。HTTP 请求由 `frontend/vite.config.ts` 代理至后端,验证 WebSocket 时直接连接后端 前后端检查见 [贡献与审查](../CONTRIBUTING.md#验证),数据库集成测试使用[专用测试库](../backend/migrations/README.md#本地测试库) @@ -56,15 +57,13 @@ pnpm --dir frontend dev [后端 Workspace 边界](architecture.md#3-workspace-边界) · [前端模块职责](architecture.md#34-前端模块职责) · [共享 UI 组件架构](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/guide/architecture.md) -Chat Completions 到 Responses、Messages、GenAI 的纯协议转换位于 `backend/crates/gateway-protocol/src/chat_completions/`, -Chat HTTP 入口位于 `backend/crates/gateway-api/src/data_plane/chat_completions/`,各 Provider 的 `provider/chat/` 或 `provider/chat.rs` 负责调用获准的转换。 -Messages 原生类型位于 `backend/crates/gateway-protocol/src/anthropic/`,账号协议分派、HTTP 执行和计数位于 `backend/crates/providers/openai/src/provider/messages/`。 -模块职责见 [Provider 与协议边界](architecture.md#5-provider-与协议边界) +协议转换、原生类型和 Provider 执行入口见 [Provider 与协议边界](architecture.md#5-provider-与协议边界),请求格式与支持范围见 [模型数据面](api.md#3-模型数据面与模型目录) -联调协议时为各 Provider 准备对应的原生账号,并通过账号分组与 Client Key 固定上游范围;OpenAI 的 Responses 与 Messages API Key 账号应分组验证。 -分别检查各账号的原生入口与 Chat 入口的 JSON、SSE、工具往返、取消和错误;支持计数的账号另测原生计数入口,并确认其他原生协议入口不会触发内置转换。 -请求格式与支持范围见 [模型数据面](api.md#3-模型数据面与模型目录)。 -Messages 账号只配置 HTTP;本地计数估算不能替代上游计费核对 +联调协议时: + +1. 为各 Provider 准备对应的原生账号,通过账号分组与 Client Key 固定上游范围;OpenAI 的 Responses 与 Messages API Key 账号分组验证 +2. 分别检查原生入口与 Chat 入口的 JSON、SSE、工具往返、取消和错误,确认其他原生协议入口不会触发内置转换 +3. 支持计数的账号另测原生计数入口;本地计数估算不能替代上游计费核对 OpenAI 的 `transport::tls::` 测试在本机回环地址采集 ClientHello,覆盖默认 HTTP、自定义 CA 的 HTTP 和 WebSocket。运行方式见[后端验证命令](architecture.md#验证命令)