From 402983b1bdfe2fd50f5a954603d9a15397fed864 Mon Sep 17 00:00:00 2001 From: ztelur Date: Fri, 30 Oct 2026 00:53:20 +0800 Subject: [PATCH 01/37] feat(gateway): add Rust PowerContext Gateway executor Two-phase check executor (before_send / before_release) with opaque bindings, prepare-based memory injection with prepared_contexts byte range declaration, synchronous sedimentation via capture_content_source, UDS/TCP dual-form CoreLink with pooled UDS client, port-takeover proxy, OpenAI chat/responses ingress, and a composable middleware chain (resource limits, request id). 27 tests. Depends on the context-protection contract in #2264; design follows #2199. Signed-off-by: ztelur --- gateway/.gitignore | 3 + gateway/Cargo.toml | 42 ++ gateway/README.md | 50 ++ gateway/crates/pc-gateway-app/Cargo.toml | 29 + gateway/crates/pc-gateway-app/src/ingress.rs | 318 +++++++++ gateway/crates/pc-gateway-app/src/link.rs | 74 ++ gateway/crates/pc-gateway-app/src/main.rs | 141 ++++ .../pc-gateway-app/src/middleware/mod.rs | 63 ++ .../src/middleware/request_id.rs | 54 ++ .../src/middleware/resource_limits.rs | 85 +++ gateway/crates/pc-gateway-app/src/proxy.rs | 149 ++++ gateway/crates/pc-gateway-core/Cargo.toml | 19 + .../crates/pc-gateway-core/src/executor.rs | 365 ++++++++++ .../crates/pc-gateway-core/src/gate_client.rs | 44 ++ .../pc-gateway-core/src/http_gate_client.rs | 110 +++ gateway/crates/pc-gateway-core/src/lib.rs | 22 + .../pc-gateway-core/src/uds_gate_client.rs | 415 +++++++++++ .../tests/executor_semantics.rs | 649 ++++++++++++++++++ .../tests/live_context_check.rs | 235 +++++++ .../crates/pc-gateway-core/tests/uds_pool.rs | 115 ++++ gateway/crates/pc-gateway-embedded/Cargo.toml | 10 + gateway/crates/pc-gateway-embedded/src/lib.rs | 8 + gateway/crates/pc-gateway-evidence/Cargo.toml | 10 + gateway/crates/pc-gateway-evidence/src/lib.rs | 98 +++ gateway/crates/pc-gateway-protocol/Cargo.toml | 13 + .../pc-gateway-protocol/src/canonical.rs | 49 ++ gateway/crates/pc-gateway-protocol/src/lib.rs | 13 + .../crates/pc-gateway-protocol/src/render.rs | 234 +++++++ gateway/crates/pc-gateway-protocol/src/sse.rs | 73 ++ .../tests/openai_renderer.rs | 60 ++ .../tests/openai_responses_renderer.rs | 75 ++ .../crates/pc-gateway-transport/Cargo.toml | 16 + .../crates/pc-gateway-transport/src/lib.rs | 15 + .../src/reqwest_transport.rs | 164 +++++ .../crates/pc-gateway-transport/src/retry.rs | 54 ++ .../crates/pc-gateway-transport/src/sender.rs | 71 ++ gateway/crates/pc-gateway-types/Cargo.toml | 12 + gateway/crates/pc-gateway-types/src/check.rs | 137 ++++ gateway/crates/pc-gateway-types/src/lib.rs | 10 + .../crates/pc-gateway-types/src/prepare.rs | 99 +++ 40 files changed, 4203 insertions(+) create mode 100644 gateway/.gitignore create mode 100644 gateway/Cargo.toml create mode 100644 gateway/README.md create mode 100644 gateway/crates/pc-gateway-app/Cargo.toml create mode 100644 gateway/crates/pc-gateway-app/src/ingress.rs create mode 100644 gateway/crates/pc-gateway-app/src/link.rs create mode 100644 gateway/crates/pc-gateway-app/src/main.rs create mode 100644 gateway/crates/pc-gateway-app/src/middleware/mod.rs create mode 100644 gateway/crates/pc-gateway-app/src/middleware/request_id.rs create mode 100644 gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs create mode 100644 gateway/crates/pc-gateway-app/src/proxy.rs create mode 100644 gateway/crates/pc-gateway-core/Cargo.toml create mode 100644 gateway/crates/pc-gateway-core/src/executor.rs create mode 100644 gateway/crates/pc-gateway-core/src/gate_client.rs create mode 100644 gateway/crates/pc-gateway-core/src/http_gate_client.rs create mode 100644 gateway/crates/pc-gateway-core/src/lib.rs create mode 100644 gateway/crates/pc-gateway-core/src/uds_gate_client.rs create mode 100644 gateway/crates/pc-gateway-core/tests/executor_semantics.rs create mode 100644 gateway/crates/pc-gateway-core/tests/live_context_check.rs create mode 100644 gateway/crates/pc-gateway-core/tests/uds_pool.rs create mode 100644 gateway/crates/pc-gateway-embedded/Cargo.toml create mode 100644 gateway/crates/pc-gateway-embedded/src/lib.rs create mode 100644 gateway/crates/pc-gateway-evidence/Cargo.toml create mode 100644 gateway/crates/pc-gateway-evidence/src/lib.rs create mode 100644 gateway/crates/pc-gateway-protocol/Cargo.toml create mode 100644 gateway/crates/pc-gateway-protocol/src/canonical.rs create mode 100644 gateway/crates/pc-gateway-protocol/src/lib.rs create mode 100644 gateway/crates/pc-gateway-protocol/src/render.rs create mode 100644 gateway/crates/pc-gateway-protocol/src/sse.rs create mode 100644 gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs create mode 100644 gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs create mode 100644 gateway/crates/pc-gateway-transport/Cargo.toml create mode 100644 gateway/crates/pc-gateway-transport/src/lib.rs create mode 100644 gateway/crates/pc-gateway-transport/src/reqwest_transport.rs create mode 100644 gateway/crates/pc-gateway-transport/src/retry.rs create mode 100644 gateway/crates/pc-gateway-transport/src/sender.rs create mode 100644 gateway/crates/pc-gateway-types/Cargo.toml create mode 100644 gateway/crates/pc-gateway-types/src/check.rs create mode 100644 gateway/crates/pc-gateway-types/src/lib.rs create mode 100644 gateway/crates/pc-gateway-types/src/prepare.rs diff --git a/gateway/.gitignore b/gateway/.gitignore new file mode 100644 index 0000000000..5df1ae4131 --- /dev/null +++ b/gateway/.gitignore @@ -0,0 +1,3 @@ +target/ +Cargo.lock +.DS_Store diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml new file mode 100644 index 0000000000..364dcbd078 --- /dev/null +++ b/gateway/Cargo.toml @@ -0,0 +1,42 @@ +[workspace] +resolver = "2" +members = [ + "crates/pc-gateway-app", + "crates/pc-gateway-core", + "crates/pc-gateway-types", + "crates/pc-gateway-protocol", + "crates/pc-gateway-transport", + "crates/pc-gateway-evidence", + "crates/pc-gateway-embedded", +] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +repository = "https://github.com/oceanbase/powercontext" + +[workspace.dependencies] +pc-gateway-core = { path = "crates/pc-gateway-core" } +pc-gateway-types = { path = "crates/pc-gateway-types" } +pc-gateway-protocol = { path = "crates/pc-gateway-protocol" } +pc-gateway-transport = { path = "crates/pc-gateway-transport" } +pc-gateway-evidence = { path = "crates/pc-gateway-evidence" } + +tokio = { version = "1", features = ["full"] } +axum = "0.7" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +bytes = { version = "1", features = ["serde"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } +hyper = { version = "1", features = ["client", "http1"] } +tower = { version = "0.5", features = ["util"] } +hyper-util = { version = "0.1", features = ["client", "client-legacy", "tokio", "http1"] } +http-body-util = "0.1" +futures-core = "0.3" + +[profile.release] +lto = "thin" diff --git a/gateway/README.md b/gateway/README.md new file mode 100644 index 0000000000..ca637d3d9e --- /dev/null +++ b/gateway/README.md @@ -0,0 +1,50 @@ +# PowerContext Rust Gateway + +An optional Rust executor for PowerContext, defined by the gateway design in #2199 and the context-protection contract in #2264. The gateway owns the model traffic boundary; every decision stays in PowerContext Core ("no policy in the gateway"). + +> Status: working prototype, verified end-to-end against a real PowerContext Server (PR #2264 branch) with real upstream providers. Depends on the `/v1/context/check` contract and `include_reuse` from #2264. + +## What it does + +- **Two-phase gate executor**: `check(before_send)` → send admitted bytes → `check(before_release)` → release. Opaque bindings thread the two phases; unknown never becomes allow; deterministic non-delivery retries are bounded, indeterminate sends are never auto-retried. +- **Memory injection**: per user message, calls `prepare` (`include_reuse`), injects the returned prepared context verbatim into the current user message, and declares the exact UTF-8 byte range (`prepared_contexts`) for Core-side digest verification. +- **Sedimentation**: after a released turn, synchronously captures the transcript via `capture_content_source` (idempotent `source_id` derived from the release binding). Blocked or degraded turns are never captured. +- **Deployment forms**: combined (Rust owns the public TCP port, Core listens on a private Unix socket only; all non-`/gateway` routes are reverse-proxied to Core over UDS) or standalone (TCP, remote Core). +- **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), with streaming ingestion (strict buffering before release). +- **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (body size + concurrency) and request-id propagation. + +## Layout + +| Crate | Responsibility | +| --- | --- | +| `pc-gateway-app` | thin binary: ingress, port-takeover proxy, middleware chain | +| `pc-gateway-core` | executor state machine, GateClient (check/prepare/capture/capabilities) over TCP or UDS | +| `pc-gateway-types` | contract DTOs aligned field-by-field with #2264 | +| `pc-gateway-protocol` | canonical request, chat/responses wire renderers, SSE framing | +| `pc-gateway-transport` | upstream transport, bounded retry, streaming buffer with caps | +| `pc-gateway-evidence` | body-free evidence (usage completeness, cache tokens, TTFT) | +| `pc-gateway-embedded` | placeholder for the in-process (FFI) executor path | + +## Run + +```bash +cargo build --release + +# Combined deployment (Core on a Unix socket) +PC_GATEWAY_CORE_UDS=/path/to/pc.sock \ +PC_GATEWAY_UPSTREAM_PROFILE= \ +PC_GATEWAY_DEFAULT_SCOPE= \ +PC_GATEWAY_UPSTREAM_URL_CHAT=https://provider/v1/chat/completions \ +PC_GATEWAY_UPSTREAM_API_KEY_CHAT=... \ +./target/release/pc-gateway + +# Optional: PC_GATEWAY_INJECTION=on (prepare + inject), PC_GATEWAY_SEDIMENT=on (capture after release), +# PC_GATEWAY_DEGRADE=passthrough (no-memory passthrough when Core is unreachable; never applies +# to deployments with enforcing protection), PC_GATEWAY_MAX_CONCURRENT / PC_GATEWAY_MAX_BODY_BYTES. +``` + +Credentials live only in server-side environment variables; they are never accepted from request fields and never enter check payloads. + +## Tests + +`cargo test` — 27 tests covering the failure-semantics table (gate unavailable, withhold terminal, bounded retry, indeterminate no-resend, blocked turns never sediment), renderer fidelity (no timestamps/request ids injected), byte-range declaration, and UDS connection-pool correctness over a real Unix socket. diff --git a/gateway/crates/pc-gateway-app/Cargo.toml b/gateway/crates/pc-gateway-app/Cargo.toml new file mode 100644 index 0000000000..c63effad53 --- /dev/null +++ b/gateway/crates/pc-gateway-app/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "pc-gateway-app" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: thin binary — port takeover, Core/MCP forwarding, OpenAI-compatible model ingress" + +[[bin]] +name = "pc-gateway" +path = "src/main.rs" + +[dependencies] +pc-gateway-core = { workspace = true } +pc-gateway-types = { workspace = true } +pc-gateway-protocol = { workspace = true } +pc-gateway-transport = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +tokio = { workspace = true } +axum = { workspace = true } +serde_json = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +reqwest = { workspace = true } +hyper = { workspace = true } +tower = { workspace = true } +hyper-util = { workspace = true } +http-body-util = { workspace = true } diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs new file mode 100644 index 0000000000..b459e5614d --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -0,0 +1,318 @@ +//! 模型入口:OpenAI 兼容 `/gateway/v1/chat/completions`。 +//! 客户端只改 Base URL 与 API Key 即接入(PR #2199 产品形态)。 + +use crate::{proxy::SharedProxy, AppState}; +use axum::body::Bytes; +use axum::extract::{Request, State}; +use axum::http::{header, HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use pc_gateway_core::{ManagedCall, ManagedOutcome}; +use pc_gateway_protocol::{CanonicalMessage, CanonicalRequest, OutputLimits, Role}; +use serde::Deserialize; +use std::sync::Arc; + +/// 网关密钥对应的默认 Scope(完整形态应从密钥解析出 Scope/profile 绑定)。 +const DEFAULT_SCOPE_ENV: &str = "PC_GATEWAY_DEFAULT_SCOPE"; + +#[derive(Debug, Deserialize)] +struct OpenAiChatRequest { + model: String, + messages: Vec, + #[serde(default)] + tools: Vec, + #[serde(default)] + max_tokens: Option, + #[serde(default)] + stream: Option, +} + +#[derive(Debug, Deserialize)] +struct OpenAiMessage { + role: String, + #[serde(default)] + content: serde_json::Value, +} + +/// Responses API 入口请求(同格式进出,不与 chat 互转)。 +#[derive(Debug, Deserialize)] +struct OpenAiResponsesRequest { + model: String, + input: Vec, + #[serde(default)] + instructions: Option, + #[serde(default)] + tools: Vec, + #[serde(default)] + max_output_tokens: Option, + #[serde(default)] + stream: Option, +} + +pub async fn chat_completions( + State((state, _)): State, + headers: HeaderMap, + req: Request, +) -> Response { + ingress_common(state, headers, req, Format::Chat).await +} + +pub async fn responses( + State((state, _)): State, + headers: HeaderMap, + req: Request, +) -> Response { + ingress_common(state, headers, req, Format::Responses).await +} + +enum Format { + Chat, + Responses, +} + +async fn ingress_common( + state: Arc, + headers: HeaderMap, + req: Request, + format: Format, +) -> Response { + // 网关密钥认证(替代服务商 key;上游凭据由受控配置持有)。 + if let Some(expected) = &state.api_key { + let provided = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")); + if provided != Some(expected.as_str()) { + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({ "error": "invalid_gateway_key" })), + ) + .into_response(); + } + } + + let body = match axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024).await { + Ok(b) => b, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + let canonical = match format { + Format::Chat => { + let chat: OpenAiChatRequest = match serde_json::from_slice(&body) { + Ok(c) => c, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_openai_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + match to_canonical_chat(chat) { + Ok(c) => c, + Err(msg) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), + ) + .into_response() + } + } + } + Format::Responses => { + let r: OpenAiResponsesRequest = match serde_json::from_slice(&body) { + Ok(c) => c, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_responses_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + match to_canonical_responses(r) { + Ok(c) => c, + Err(msg) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), + ) + .into_response() + } + } + } + }; + let renderer = match format { + Format::Chat => pc_gateway_protocol::GatewayRenderer::Chat(Default::default()), + Format::Responses => pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), + }; + + let call = ManagedCall { + scope_id: std::env::var(DEFAULT_SCOPE_ENV).unwrap_or_else(|_| "gateway:default".into()), + target_profile: state.upstream_profile.clone(), + request: canonical, + target_url: match format { + Format::Chat => state.upstream_chat.clone(), + Format::Responses => state.upstream_responses.clone(), + }, + headers: bearer_headers(match format { + Format::Chat => &state.upstream_chat_api_key, + Format::Responses => &state.upstream_responses_api_key, + }), + degrade_policy: state.degrade, + inject_context: state.inject_context + && matches!(format, Format::Chat), + sediment: state.sediment, + prepared_contexts: Vec::new(), + }; + + let outcome = state.executor.run(call, &renderer, state.evidence.as_ref()).await; + respond(outcome) +} + +fn bearer_headers(key: &str) -> Vec<(String, String)> { + if key.is_empty() { + Vec::new() + } else { + vec![("authorization".to_string(), format!("Bearer {key}"))] + } +} + +fn to_canonical_chat(chat: OpenAiChatRequest) -> Result { + let mut messages = Vec::with_capacity(chat.messages.len()); + for m in chat.messages { + let role = match m.role.as_str() { + "system" => Role::System, + "user" => Role::User, + "assistant" => Role::Assistant, + "tool" => Role::Tool, + other => return Err(format!("unsupported role: {other}")), + }; + let content = match m.content { + serde_json::Value::String(s) => vec![serde_json::Value::String(s)], + serde_json::Value::Array(a) => a, + serde_json::Value::Null => vec![], + other => return Err(format!("unsupported content type: {other}")), + }; + messages.push(CanonicalMessage { role, content }); + } + Ok(CanonicalRequest { + model: chat.model, + messages, + tools: chat.tools, + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: chat.max_tokens.unwrap_or(1024), + }, + stream: chat.stream.unwrap_or(false), + }) +} + +/// Responses 入口 → 规范类型:消息项照常映射; +/// Responses 专有 item(function_call 等)原样封进 content, +/// 由 `OpenAiResponsesRenderer` 按原样作为顶层 input item 透出(无跨格式转换)。 +fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result { + let mut messages = Vec::with_capacity(r.input.len()); + for item in r.input { + let role_str = item.get("role").and_then(|v| v.as_str()).unwrap_or(""); + let role = match role_str { + "system" | "developer" => Role::System, + "user" => Role::User, + "assistant" => Role::Assistant, + "tool" => Role::Tool, + // 无 role 的顶层 item(function_call/function_call_output 等): + // 原样保留,role 占位为 tool。 + _ => Role::Tool, + }; + if role_str.is_empty() { + messages.push(CanonicalMessage { + role: Role::Tool, + content: vec![item], + }); + continue; + } + let content = match item.get("content") { + Some(serde_json::Value::String(s)) => vec![serde_json::Value::String(s.clone())], + Some(serde_json::Value::Array(a)) => a.clone(), + _ => vec![], + }; + messages.push(CanonicalMessage { role, content }); + } + Ok(CanonicalRequest { + model: r.model, + messages, + tools: r.tools, + instructions: r.instructions, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: r.max_output_tokens.unwrap_or(1024), + }, + stream: r.stream.unwrap_or(false), + }) +} + +/// 结果映射:不存在静默成功;降级直通必须显式标记。 +fn respond(outcome: ManagedOutcome) -> Response { + match outcome { + ManagedOutcome::Released { status, content_type, body, .. } => { + // 上游状态码与 Content-Type 原样透传(错误不伪装 200)。 + let code = StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY); + ( + code, + [(header::CONTENT_TYPE, content_type.as_str())], + body.to_vec(), + ) + .into_response() + } + ManagedOutcome::Degraded { status, content_type, body } => match Response::builder() + .status( + StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY), + ) + .header(header::CONTENT_TYPE, content_type.as_str()) + .header("x-pc-degraded", "passthrough_without_memory") + .body(axum::body::Body::from(body.to_vec())) + { + Ok(r) => r, + Err(e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(serde_json::json!({ "error": e.to_string() })), + ) + .into_response(), + }, + ManagedOutcome::Blocked { reason_codes } => ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ "decision": "block", "reason_codes": reason_codes })), + ) + .into_response(), + ManagedOutcome::Withheld { reason_codes } => ( + StatusCode::CONFLICT, + Json(serde_json::json!({ "decision": "withhold", "reason_codes": reason_codes })), + ) + .into_response(), + ManagedOutcome::SendIndeterminate => ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({ "decision": "send_indeterminate" })), + ) + .into_response(), + ManagedOutcome::NotSent { attempts } => ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({ "decision": "not_sent", "attempts": attempts })), + ) + .into_response(), + ManagedOutcome::GatePaused(msg) => ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "decision": "gate_paused", "detail": msg })), + ) + .into_response(), + } +} + +// 抑制未使用导入警告(Bytes 用于类型别名文档场景)。 +#[allow(dead_code)] +fn _unused(_: Option) {} diff --git a/gateway/crates/pc-gateway-app/src/link.rs b/gateway/crates/pc-gateway-app/src/link.rs new file mode 100644 index 0000000000..084bb724c1 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/link.rs @@ -0,0 +1,74 @@ +//! Core 连接形态:UDS(同机组合部署)或 TCP(独立运行)。 + +use pc_gateway_core::{GateClient, GateError, HttpGateClient, UdsGateClient}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use std::future::Future; + +pub enum CoreLink { + Uds(UdsGateClient), + Http(HttpGateClient), +} + +impl CoreLink { + pub fn from_env() -> Self { + if let Ok(sock) = std::env::var("PC_GATEWAY_CORE_UDS") { + tracing::info!(%sock, "core link: UDS (combined deployment)"); + Self::Uds(UdsGateClient::new(sock)) + } else { + let base = + std::env::var("PC_GATEWAY_CORE_BASE").unwrap_or_else(|_| "http://127.0.0.1:8000".into()); + tracing::info!(%base, "core link: TCP (standalone deployment)"); + Self::Http(HttpGateClient::new(base)) + } + } +} + +impl GateClient for CoreLink { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + async move { + match self { + CoreLink::Uds(c) => c.check(request).await, + CoreLink::Http(c) => c.check(request).await, + } + } + } + + fn capabilities(&self) -> impl Future> + Send { + async move { + match self { + CoreLink::Uds(c) => c.capabilities().await, + CoreLink::Http(c) => c.capabilities().await, + } + } + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + async move { + match self { + CoreLink::Uds(c) => c.prepare(request).await, + CoreLink::Http(c) => c.prepare(request).await, + } + } + } + + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send { + async move { + match self { + CoreLink::Uds(c) => c.capture(request).await, + CoreLink::Http(c) => c.capture(request).await, + } + } + } +} diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs new file mode 100644 index 0000000000..43c961a8cd --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -0,0 +1,141 @@ +//! 薄二进制:端口接管 + 模型入口。所有执行逻辑在 `pc-gateway-core`。 +//! +//! PR #2199 部署形态: +//! - 同机组合:`PC_GATEWAY_CORE_UDS` 指向 Python 的 UDS;网关独占公网端口, +//! 非 `/gateway/*` 流量反向代理到 UDS(原 Core/MCP 路由透传)。 +//! - 独立运行:`PC_GATEWAY_CORE_BASE` 直连远端 PowerContext(无代理)。 +//! +//! 环境变量:PC_GATEWAY_LISTEN、PC_GATEWAY_CORE_UDS、PC_GATEWAY_CORE_BASE、 +//! PC_GATEWAY_API_KEY(网关密钥,替代服务商 key)、PC_GATEWAY_UPSTREAM_URL、 +//! PC_GATEWAY_UPSTREAM_API_KEY、PC_GATEWAY_UPSTREAM_PROFILE、 +//! PC_GATEWAY_POLICY_VERSION、PC_GATEWAY_MAX_ATTEMPTS、PC_GATEWAY_DEGRADE。 + +mod ingress; +mod link; +mod middleware; +mod proxy; + +use crate::link::CoreLink; +use axum::routing::{get, post}; +use axum::Router; +use pc_gateway_core::Executor; +use pc_gateway_evidence::BufferedEvidenceSink; +use pc_gateway_transport::ReqwestTransport; +use std::net::SocketAddr; +use std::num::NonZeroU32; +use std::sync::Arc; +use std::time::Duration; + +pub struct AppState { + /// 单一执行器;线格式渲染器按请求格式传入(同格式进出)。 + pub executor: Arc>, + pub evidence: Arc, + pub upstream_profile: String, + /// chat-completions 上游(含 key;老变量 PC_GATEWAY_UPSTREAM_URL 仍作缺省)。 + pub upstream_chat: String, + /// responses 上游。 + pub upstream_responses: String, + pub upstream_chat_api_key: String, + pub upstream_responses_api_key: String, + pub api_key: Option, + pub degrade: pc_gateway_core::DegradePolicy, + /// 是否调 prepare 注入上下文(默认关;v1 仅 chat 格式)。 + pub inject_context: bool, + /// 过检后同步沉淀对话(默认关)。 + pub sediment: bool, +} + +#[tokio::main] +async fn main() { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "info".into()), + ) + .init(); + + let core_link = CoreLink::from_env(); + let proxy_state = proxy::ProxyState::from_env(); + + let max_attempts: u32 = std::env::var("PC_GATEWAY_MAX_ATTEMPTS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(2); + let max_body_bytes: usize = std::env::var("PC_GATEWAY_MAX_BODY_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(16 * 1024 * 1024); + let max_concurrent: usize = std::env::var("PC_GATEWAY_MAX_CONCURRENT") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|v| *v > 0) + .unwrap_or(64); + let degrade = match std::env::var("PC_GATEWAY_DEGRADE").as_deref() { + Ok("passthrough") => pc_gateway_core::DegradePolicy::PassthroughWithoutMemory, + _ => pc_gateway_core::DegradePolicy::Pause, + }; + + let state = Arc::new(AppState { + executor: Arc::new(Executor::new( + core_link, + ReqwestTransport::new(Duration::from_secs(120)), + NonZeroU32::new(max_attempts).expect("max_attempts > 0"), + )), + evidence: Arc::new(BufferedEvidenceSink::new()), + upstream_profile: std::env::var("PC_GATEWAY_UPSTREAM_PROFILE") + .unwrap_or_else(|_| "default".into()), + upstream_chat: std::env::var("PC_GATEWAY_UPSTREAM_URL_CHAT") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_URL")) + .unwrap_or_else(|_| "http://127.0.0.1:9000/v1/chat/completions".into()), + upstream_responses: std::env::var("PC_GATEWAY_UPSTREAM_URL_RESPONSES") + .unwrap_or_else(|_| "https://openrouter.ai/api/v1/responses".into()), + upstream_chat_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_CHAT") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) + .unwrap_or_default(), + upstream_responses_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_RESPONSES") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) + .unwrap_or_default(), + api_key: std::env::var("PC_GATEWAY_API_KEY").ok().filter(|k| !k.is_empty()), + degrade, + inject_context: matches!(std::env::var("PC_GATEWAY_INJECTION").as_deref(), Ok("on")), + sediment: matches!(std::env::var("PC_GATEWAY_SEDIMENT").as_deref(), Ok("on")), + }); + + let router = Router::new() + .route("/healthz", get(healthz)) + .route("/gateway/v1/chat/completions", post(ingress::chat_completions)) + .route("/gateway/v1/responses", post(ingress::responses)) + .fallback(proxy::fallback) + .with_state((state, proxy_state)); + + // 中间件链:按序注册,前者为外层。新增功能 = 实现 GatewayMiddleware + 此处一行。 + let chain: Vec> = vec![ + middleware::ResourceLimits::new(max_body_bytes, max_concurrent), + std::sync::Arc::new(middleware::RequestId), + ]; + for mw in &chain { + tracing::info!(middleware = mw.name(), "middleware enabled"); + } + let app = middleware::apply_chain(router, chain); + + let addr: SocketAddr = std::env::var("PC_GATEWAY_LISTEN") + .unwrap_or_else(|_| "127.0.0.1:8787".into()) + .parse() + .expect("PC_GATEWAY_LISTEN must be host:port"); + + tracing::info!(%addr, "pc-gateway listening (port takeover mode)"); + let listener = tokio::net::TcpListener::bind(addr).await.expect("bind"); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .expect("serve"); +} + +async fn shutdown_signal() { + let _ = tokio::signal::ctrl_c().await; + tracing::info!("shutting down (draining)"); +} + +async fn healthz() -> axum::Json { + axum::Json(serde_json::json!({ "status": "ok", "service": "pc-gateway" })) +} diff --git a/gateway/crates/pc-gateway-app/src/middleware/mod.rs b/gateway/crates/pc-gateway-app/src/middleware/mod.rs new file mode 100644 index 0000000000..6c45acaacd --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/middleware/mod.rs @@ -0,0 +1,63 @@ +//! 网关中间件链(chain/filter)。 +//! +//! 设计对齐 PC 的 HttpResourceLimits / HttpRequestId / 观测栈分层思路: +//! 每个功能是一个实现 `GatewayMiddleware` 的小结构,启动时按序注册, +//! `apply_chain` 反向挂到 axum(先注册 = 越靠外层)。新增功能(限流、 +//! 指标、OTel、熔断……)只需增加一个结构体 + 一行注册。 + +use axum::{ + extract::Request, + http::{HeaderName, StatusCode}, + middleware::Next, + response::{IntoResponse, Response}, + Json, +}; +use std::pin::Pin; + +use std::future::Future; +use std::sync::Arc; + +pub mod request_id; +pub use request_id::RequestId; +pub mod resource_limits; +pub use resource_limits::ResourceLimits; + + +pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-powercontext-request-id"); + +/// 一个中间件 = 请求进入时的一段处理 + 调用后续链。 +/// 约定:中间件不得消费 body(body 归 ingress/代理所有)。 +/// handle 返回 boxed future 以保持 dyn 兼容(可装进 Vec 动态组合)。 +pub trait GatewayMiddleware: Send + Sync + 'static { + /// 名称(日志/指标用)。 + fn name(&self) -> &'static str; + + fn handle<'a>( + &'a self, + req: Request, + next: Next, + ) -> Pin + Send + 'a>>; +} + + +/// 把中间件链挂到 Router 的外层。 +/// axum 的 layer 语义:后挂的先执行;这里让 `chain[0]` 成为最外层, +/// 与注册顺序直觉一致。 +pub fn apply_chain(mut router: axum::Router, chain: Vec>) -> axum::Router { + for mw in chain.into_iter().rev() { + router = router.layer(axum::middleware::from_fn(move |req, next| { + let mw = mw.clone(); + async move { mw.handle(req, next).await } + })); + } + router +} + +/// 统一的简单错误响应。 +pub(crate) fn reject(status: StatusCode, code: &str, detail: impl Into) -> Response { + ( + status, + Json(serde_json::json!({ "error": code, "detail": detail.into() })), + ) + .into_response() +} diff --git a/gateway/crates/pc-gateway-app/src/middleware/request_id.rs b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs new file mode 100644 index 0000000000..d6d027e453 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs @@ -0,0 +1,54 @@ +//! 请求 ID:透传客户端的 X-PowerContext-Request-ID 或生成新 ID, +//! 注入请求扩展(供 handler/日志取用)并回写到响应头。 +//! 对齐 PC 的 HttpRequestIdMiddleware,贯通排障链路。 + +use super::{GatewayMiddleware, REQUEST_ID_HEADER}; +use axum::{extract::Request, middleware::Next, response::Response}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; + +static SEQUENCE: AtomicU64 = AtomicU64::new(0); + +pub struct RequestId; + +fn generate() -> String { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed); + format!("gw-{ts:x}-{seq:06x}") +} + +impl GatewayMiddleware for RequestId { + fn name(&self) -> &'static str { + "request_id" + } + + fn handle<'a>( + &'a self, + mut req: Request, + next: Next, + ) -> Pin + Send + 'a>> { + Box::pin(async move { + let id = req + .headers() + .get(&REQUEST_ID_HEADER) + .and_then(|v| v.to_str().ok()) + .filter(|v| !v.is_empty() && v.len() <= 128 && v.chars().all(|c| c.is_ascii_graphic())) + .map(|v| v.to_string()) + .unwrap_or_else(generate); + // 注入扩展 + 当前 span,供后续 handler 与日志关联。 + req.extensions_mut().insert(id.clone()); + tracing::Span::current().record("request_id", &id); + let mut resp = next.run(req).await; + if resp.headers().get(&REQUEST_ID_HEADER).is_none() { + if let Ok(v) = axum::http::HeaderValue::from_str(&id) { + resp.headers_mut().insert(REQUEST_ID_HEADER, v); + } + } + resp + }) + } +} diff --git a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs new file mode 100644 index 0000000000..c5ff35a7fa --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs @@ -0,0 +1,85 @@ +//! 资源限流:请求体上限 + 并发上限(对齐 PC 的 HttpResourceLimitsMiddleware)。 +//! 最外层准入——被拒请求不消耗内层任何资源。/healthz 豁免并发限制 +//! (编排系统探活不应因业务拥堵被拒)。 + +use super::{reject, GatewayMiddleware}; +use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; +use tokio::sync::Semaphore; + +pub struct ResourceLimits { + max_body_bytes: usize, + max_concurrent: Arc, + /// 被拒计数(无正文证据)。 + rejected_body: AtomicU64, + rejected_concurrency: AtomicU64, +} + +impl ResourceLimits { + pub fn new(max_body_bytes: usize, max_concurrent: usize) -> Arc { + Arc::new(Self { + max_body_bytes, + max_concurrent: Arc::new(Semaphore::new(max_concurrent)), + rejected_body: AtomicU64::new(0), + rejected_concurrency: AtomicU64::new(0), + }) + } +} + +impl GatewayMiddleware for ResourceLimits { + fn name(&self) -> &'static str { + "resource_limits" + } + + fn handle<'a>( + &'a self, + req: Request, + next: Next, + ) -> Pin + Send + 'a>> { + Box::pin(async move { + // 1) 请求体上限:优先用 Content-Length 预检(零拷贝拒绝)。 + if let Some(len) = req + .headers() + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + { + if len > self.max_body_bytes { + self.rejected_body.fetch_add(1, Ordering::Relaxed); + tracing::warn!(bytes = len, limit = self.max_body_bytes, "request body rejected"); + return reject( + StatusCode::PAYLOAD_TOO_LARGE, + "request_body_too_large", + format!("body {len} bytes exceeds limit {}", self.max_body_bytes), + ); + } + } + + // 2) 并发上限:非阻塞获取;占满即拒(不排队——排队会把内存压力换成延迟压力)。 + let is_health = req.uri().path() == "/healthz"; + let permit = if is_health { + None + } else { + match self.max_concurrent.clone().try_acquire_owned() { + Ok(p) => Some(p), + Err(_) => { + self.rejected_concurrency.fetch_add(1, Ordering::Relaxed); + tracing::warn!("concurrency limit reached, rejecting"); + return reject( + StatusCode::SERVICE_UNAVAILABLE, + "concurrency_limit", + "gateway at max concurrent requests", + ); + } + } + }; + + let resp = next.run(req).await; + drop(permit); // 显式归还(作用域结束也会归还,这里表达意图) + resp + }) + } +} diff --git a/gateway/crates/pc-gateway-app/src/proxy.rs b/gateway/crates/pc-gateway-app/src/proxy.rs new file mode 100644 index 0000000000..8240f77768 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/proxy.rs @@ -0,0 +1,149 @@ +//! 端口接管代理:非 `/gateway/*` 的流量原样转发到 Python 的 UDS。 +//! 原 Core/MCP 路由由此透传;流式(SSE/分块)由 hyper 客户端透传保证。 + +use crate::AppState;use axum::body::Body; +use axum::extract::{Request, State}; +use axum::http::{HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; +use hyper::Uri as HyperUri;use hyper_util::client::legacy::Client; +use hyper_util::rt::{TokioExecutor, TokioIo}; +use std::future::Future; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; +use tokio::net::UnixStream; + +pub type SharedProxy = (Arc, ProxyState); + +#[derive(Clone)] +pub struct ProxyState { + inner: Option>, +} + +struct ProxyInner { + socket: PathBuf, + client: Client, +} + +impl ProxyState { + pub fn from_env() -> Self { + match std::env::var("PC_GATEWAY_CORE_UDS") { + Ok(sock) => { + let client = Client::builder(TokioExecutor::new()) + .build(UnixConnector { socket: PathBuf::from(&sock) }); + tracing::info!(%sock, "proxy: forwarding non-gateway routes to Python UDS"); + Self { + inner: Some(Arc::new(ProxyInner { + socket: PathBuf::from(sock), + client, + })), + } + } + Err(_) => { + tracing::info!("proxy: no UDS configured; standalone mode"); + Self { inner: None } + } + } + } +} + +/// UDS 连接器:忽略 URI,始终连配置的 socket 路径。 +/// 实现 tower Service(hyper-util legacy Client 的 Connect 约束)。 +#[derive(Clone)] +struct UnixConnector { + socket: PathBuf, +} + +impl tower::Service for UnixConnector { + type Response = TokioIo; + type Error = std::io::Error; + type Future = Pin> + Send>>; + + fn poll_ready( + &mut self, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + + fn call(&mut self, _uri: HyperUri) -> Self::Future { + let path = self.socket.clone(); + Box::pin(async move { + UnixStream::connect(path) + .await + .map(TokioIo::new) + }) + } +} + +pub async fn fallback(State((_, proxy)): State, req: Request) -> Response { + let Some(inner) = proxy.inner else { + return ( + StatusCode::NOT_FOUND, + axum::Json(serde_json::json!({ + "error": "not_found", + "hint": "standalone mode: only /gateway/v1 and /healthz are served", + })), + ) + .into_response(); + }; + + let (parts, body) = req.into_parts(); + // hyper legacy client 要求绝对 URI;UDS 连接器忽略 host,用占位 authority。 + let path_q = parts + .uri + .path_and_query() + .cloned() + .unwrap_or_else(|| "/".parse().expect("root uri")); + let uri = HyperUri::builder() + .scheme("http") + .authority("powercontext.internal") + .path_and_query(path_q) + .build() + .unwrap_or_else(|_| HyperUri::default()); + + let mut fwd = hyper::Request::builder() + .method(parts.method) + .uri(uri) + .header("host", HeaderValue::from_static("powercontext")); + if let Some(headers) = fwd.headers_mut() { + *headers = parts.headers; + if !headers.contains_key("host") { + headers.insert("host", HeaderValue::from_static("powercontext")); + } + } + let hyper_req = match fwd.body(body) { + Ok(r) => r, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + axum::Json(serde_json::json!({ "error": "bad_request", "detail": e.to_string() })), + ) + .into_response() + } + }; + + let _ = inner.socket; // socket 路径已注入连接器 + match inner.client.request(hyper_req).await { + Ok(resp) => { + let (rparts, rbody) = resp.into_parts(); + let mut response = Response::builder().status(rparts.status); + if let Some(h) = response.headers_mut() { + *h = rparts.headers; + } + response + .body(Body::new(rbody)) + .unwrap_or_else(|e| { + (StatusCode::BAD_GATEWAY, format!("proxy build: {e}")).into_response() + }) + } + Err(e) => ( + StatusCode::BAD_GATEWAY, + axum::Json(serde_json::json!({ + "error": "core_unreachable", + "detail": e.to_string(), + })), + ) + .into_response(), + } +} diff --git a/gateway/crates/pc-gateway-core/Cargo.toml b/gateway/crates/pc-gateway-core/Cargo.toml new file mode 100644 index 0000000000..1f1b1b0ff4 --- /dev/null +++ b/gateway/crates/pc-gateway-core/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "pc-gateway-core" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: executor state machine — input/check → render → send → output/check → release" + +[dependencies] +pc-gateway-types = { workspace = true } +pc-gateway-protocol = { workspace = true } +pc-gateway-transport = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +reqwest = { workspace = true } diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs new file mode 100644 index 0000000000..34d3cfeb72 --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -0,0 +1,365 @@ +use crate::{GateClient, GateError}; +use pc_gateway_evidence::EvidenceSink; +use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; +use pc_gateway_transport::{AdmittedSend, BoundedRetry, RetryOutcome, SendOutcome, Transport}; +use pc_gateway_types::{ + CaptureContentSourceRequest, CheckDecision, ContextCheckRequest, ContextCheckResult, + ModelJsonPayload, ModelJsonTextLocation, PreparedContextLocation, PrepareContextRequest, +}; +use std::collections::BTreeMap; +use std::num::NonZeroU32; + +/// Gate 不可用时的策略(PR #2199 故障语义): +/// Pause —— 必需强制检查不可用:不发送(默认,安全立场); +/// PassthroughWithoutMemory —— 增强类调用可降级(仅限 capabilities.enforcing=false)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DegradePolicy { + #[default] + Pause, + PassthroughWithoutMemory, +} + +/// 宿主交给执行器的完整输入:已授权历史 + 当前请求 + 目标。 +pub struct ManagedCall { + pub scope_id: String, + pub target_profile: String, + pub request: CanonicalRequest, + pub target_url: String, + /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 + pub headers: Vec<(String, String)>, + pub degrade_policy: DegradePolicy, + /// 是否调 prepare 注入上下文(v1 仅 chat 格式;PC 决定内容,网关只放置)。 + pub inject_context: bool, + /// 是否在过检后同步沉淀本轮对话(capture_content_source,毫秒级落库)。 + pub sediment: bool, + /// 注入块位置声明,随 before_send 送检。 + pub prepared_contexts: Vec, +} + +/// 执行结果:要么是过检放行的内容,要么是显式拒绝/不确定。 +/// 不存在“静默成功”或“伪装成空结果”的路径。 +#[derive(Debug)] +pub enum ManagedOutcome { + /// before_release 的 allow:绑定与过检内容一起返回。 + Released { + binding: Option, + status: u16, + content_type: String, + body: bytes::Bytes, + }, + /// Core 明确拒绝(两阶段的 block),携带无正文原因类别。 + Blocked { reason_codes: Vec }, + /// Core 暂缓。PR #2264 的 withhold 不含渲染计划,一律按终态处理。 + Withheld { reason_codes: Vec }, + /// 可能已到达上游;不自动付费重发。 + SendIndeterminate, + /// 全部尝试确定性未送达。 + NotSent { attempts: u32 }, + /// Gate 不可用:暂停,不是失败放行。 + GatePaused(String), + /// 无记忆直通降级:未经检查发送(仅限未启用强制规则的部署), + /// 响应头/证据必须显式标记,不得伪装成过检结果。 + Degraded { + status: u16, + content_type: String, + body: bytes::Bytes, + }, +} + +pub struct Executor { + gate: G, + retry: BoundedRetry, +} + +impl Executor +where + G: GateClient, + T: Transport, +{ + pub fn new(gate: G, transport: T, max_attempts: NonZeroU32) -> Self { + Self { + gate, + retry: BoundedRetry::new(transport, max_attempts), + } + } + + /// 一次托管调用。渲染器按请求传入:入口格式即上游格式(同格式进出)。 + pub async fn run( + &self, + call: ManagedCall, + renderer: &R, + evidence: &dyn EvidenceSink, + ) -> ManagedOutcome { + let mut call = call; + if call.inject_context { + // 注入是增强类调用:失败不阻塞主链路(不注入、不声明区间)。 + self.enrich(&mut call, evidence).await; + } + // 渲染完整最终字节(不含缓存计划:PR #2264 的 withhold 未携带渲染计划)。 + let payload = match renderer.render(&call.request, None) { + Ok(p) => p, + Err(e) => { + return ManagedOutcome::Blocked { + reason_codes: vec![format!("render_failed:{e}")], + } + } + }; + let model_payload = ModelJsonPayload::new( + content_headers(&call.headers, payload.content_type), + String::from_utf8_lossy(&payload.bytes).into_owned(), + ); + + let check = ContextCheckRequest::BeforeSend { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + payload: model_payload, + prepared_contexts: call.prepared_contexts.clone(), + }; + + let binding = match self.gate.check(check).await { + Err(e) => { + return match (classify_gate_error(e), call.degrade_policy) { + (_, DegradePolicy::PassthroughWithoutMemory) => { + self.degraded_send(&call, payload.bytes, evidence).await + } + (msg, DegradePolicy::Pause) => ManagedOutcome::GatePaused(msg), + } + } + Ok(result) => match result.decision { + CheckDecision::Allow => unwrap_binding(result), + CheckDecision::Block => { + return ManagedOutcome::Blocked { + reason_codes: result.reason_codes, + } + } + CheckDecision::Withhold => { + return ManagedOutcome::Withheld { + reason_codes: result.reason_codes, + } + } + }, + }; + + let send = AdmittedSend { + binding, + payload: payload.bytes, + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }; + let send_ref = send.clone(); + + let raw = match self.retry.send_with_retry(&send, evidence).await { + RetryOutcome::AllNotSent { attempts } => return ManagedOutcome::NotSent { attempts }, + RetryOutcome::Done(SendOutcome::Indeterminate(_)) => { + return ManagedOutcome::SendIndeterminate + } + RetryOutcome::Done(SendOutcome::NotSent(_)) => { + unreachable!("BoundedRetry never returns Done(NotSent)") + } + RetryOutcome::Done(SendOutcome::Delivered(raw)) => raw, + }; + + // strict:完整原始响应先过 before_release,通过前不释放任何内容。 + let release_check = ContextCheckRequest::BeforeRelease { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + request_binding: send_ref.binding.clone(), + payload: ModelJsonPayload::new( + // 契约要求 headers 至少 1 项;携带上游实际 Content-Type。 + BTreeMap::from([("content-type".to_string(), raw.content_type.clone())]), + String::from_utf8_lossy(&raw.body).into_owned(), + ), + completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.into(), + }; + match self.gate.check(release_check).await { + Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), + Ok(result) => match result.decision { + CheckDecision::Allow => { + // 沉淀:同步、best-effort(失败仅记证据,不影响交付)。 + // 内容只含本轮 user 文本与过检响应——被拦/降级轮次不沉淀。 + if call.sediment { + let transcript = serde_json::json!({ + "kind": "gateway_turn", + "user": call.request.messages.iter() + .rev().find(|m| matches!(m.role, pc_gateway_protocol::Role::User)) + .and_then(|m| match m.content.as_slice() { + [serde_json::Value::String(s)] => Some(s.clone()), + _ => None, + }).unwrap_or_default(), + "assistant": String::from_utf8_lossy(&raw.body), + "model": call.request.model, + }); + let digest = result.binding.as_deref() + .map(|b| simple_digest(b)) + .unwrap_or_else(|| simple_digest(&String::from_utf8_lossy(&raw.body))); + let capture = CaptureContentSourceRequest { + scope_id: call.scope_id.clone(), + source_id: format!("gw-turn-{digest}"), + content: transcript.to_string(), + metadata: Some(serde_json::json!({ + "kind": "gateway_turn", + "target_profile": call.target_profile, + })), + }; + if let Err(e) = self.gate.capture(capture).await { + evidence.record_not_sent(0, &format!("sediment_failed:{e}")); + } + } + ManagedOutcome::Released { + binding: result.binding, + status: raw.status, + content_type: raw.content_type.clone(), + body: raw.body, + } + } + CheckDecision::Block => { + // 不释放任何内容;尽力取消上游,只保留无正文失败证据。 + self.retry.transport().cancel(&send_ref).await; + ManagedOutcome::Blocked { + reason_codes: result.reason_codes, + } + } + CheckDecision::Withhold => ManagedOutcome::Withheld { + reason_codes: result.reason_codes, + }, + }, + } + } + + /// 注入(放置与声明,非检索):调 prepare → 标准块包裹 → 拼进最后一条 + /// user 消息头部 → 计算字节区间。任一步失败则保持原样(不注入、不声明)。 + async fn enrich(&self, call: &mut ManagedCall, evidence: &dyn EvidenceSink) { + // 取最后一条 user 消息的纯文本作为检索词;非单字符串 content 不注入(v1)。 + let Some(query) = last_user_text(&call.request) else { + return; + }; + let prepared = match self + .gate + .prepare(PrepareContextRequest { + scope_id: call.scope_id.clone(), + query, + max_bytes: 8192, + include_reuse: true, + }) + .await + { + Ok(p) => p, + Err(e) => { + evidence.record_not_sent(0, &format!("prepare_failed:{e}")); + return; + } + }; + let (Some(content), Some(binding)) = (prepared.content(), prepared.binding()) else { + return; // empty:不注入任何标记(空块会污染前缀且无 binding 可声明) + }; + if content.is_empty() { + return; + } + // PC 返回的 content 已是标准注入格式(信任前言 + 标记包裹块)。 + // 必须原样注入:check 会校验区间字节摘要 == sha256(content), + // 网关任何增删(包括再包裹)都会导致 digest 不匹配被暂缓。 + let block = content.to_string(); + let Some(index) = last_user_index(&call.request) else { return }; + let Some(message) = call.request.messages.get_mut(index) else { return }; + let original = match message.content.as_slice() { + [serde_json::Value::String(s)] => s.clone(), + _ => return, + }; + let new_text = format!("{block}\n\n{original}"); + message.content = vec![serde_json::Value::String(new_text)]; + call.prepared_contexts.push(PreparedContextLocation { + binding: binding.to_string(), + location: ModelJsonTextLocation { + schema: pc_gateway_types::MODEL_JSON_TEXT_LOCATION_SCHEMA.to_string(), + // chat 线格式:content 为纯字符串,指针用无部件形态。 + pointer: format!("/messages/{index}/content"), + start_byte: 0, + // UTF-8 字节数(非字符数);区间必须落在字符边界(块整体是合法 UTF-8,天然满足)。 + end_byte: block.as_bytes().len() as u64, + }, + }); + } + + /// 降级直通:未经检查发送。显式标记,不做释放检查。 + async fn degraded_send( + &self, + call: &ManagedCall, + payload: bytes::Bytes, + evidence: &dyn EvidenceSink, + ) -> ManagedOutcome { + evidence.record_not_sent(0, "degraded_passthrough"); + let send = AdmittedSend { + binding: "degraded-passthrough".into(), + payload, + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }; + match self.retry.send_with_retry(&send, evidence).await { + RetryOutcome::AllNotSent { attempts } => ManagedOutcome::NotSent { attempts }, + RetryOutcome::Done(SendOutcome::Indeterminate(_)) => ManagedOutcome::SendIndeterminate, + RetryOutcome::Done(SendOutcome::NotSent(_)) => { + unreachable!("BoundedRetry never returns Done(NotSent)") + } + RetryOutcome::Done(SendOutcome::Delivered(raw)) => ManagedOutcome::Degraded { + status: raw.status, + content_type: raw.content_type, + body: raw.body, + }, + } + } +} + +fn unwrap_binding(result: ContextCheckResult) -> String { + result + .binding + .unwrap_or_else(|| "missing-binding".to_string()) +} + +/// 载荷头只保留内容/协议头;凭据与传输覆盖头禁止进 check 载荷。 +fn content_headers(headers: &[(String, String)], content_type: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + out.insert("content-type".to_string(), content_type.to_string()); + for (k, v) in headers { + let lower = k.to_ascii_lowercase(); + if matches!(lower.as_str(), "authorization" | "x-api-key" | "cookie") { + continue; + } + out.insert(lower, v.clone()); + } + out +} + +fn classify_gate_error(e: GateError) -> String { + match e { + GateError::GateUnavailable(msg) | GateError::Malformed(msg) => msg, + } +} + +/// 最后一条 user 消息下标(渲染保持消息顺序,与线格式下标一致)。 +fn last_user_index(request: &CanonicalRequest) -> Option { + request + .messages + .iter() + .rposition(|m| matches!(m.role, pc_gateway_protocol::Role::User)) +} + +fn last_user_text(request: &CanonicalRequest) -> Option { + let i = last_user_index(request)?; + match request.messages[i].content.as_slice() { + [serde_json::Value::String(s)] => Some(s.clone()), + _ => None, + } +} + +/// 稳定短摘要(幂等键用;非安全用途,无需密码学强度)。 +fn simple_digest(input: &str) -> String { + // FNV-1a 64 位,输出 16 hex —— 足够做 source_id 的幂等区分。 + let mut hash: u64 = 0xcbf29ce484222325; + for b in input.as_bytes() { + hash ^= *b as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + format!("{hash:016x}") +} diff --git a/gateway/crates/pc-gateway-core/src/gate_client.rs b/gateway/crates/pc-gateway-core/src/gate_client.rs new file mode 100644 index 0000000000..d7f072601c --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/gate_client.rs @@ -0,0 +1,44 @@ +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use std::future::Future; + +/// Core 检查的客户端抽象(PR #2199:单端点两阶段契约)。 +/// 实现:TCP(独立部署形态)或 UDS(同机组合部署形态); +/// 嵌入式实现直接进程内调用等价算法。 +/// +/// Gate 不可用 → `GateUnavailable`。是否降级为无记忆直通由调用方 +/// 的 `DegradePolicy` 决定(仅对未配置强制规则的 Scope 允许)。 +pub trait GateClient: Send + Sync { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send; + + /// GET_CAPABILITIES 能力发现:获知支持的模式、必需规则、可降级性等。 + fn capabilities( + &self, + ) -> impl Future> + Send; + + /// PREPARE_CONTEXT:检索并装配注入内容(智力全在 Core;网关只放置)。 + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send; + + /// CAPTURE_CONTENT_SOURCE:沉淀一轮过检对话(同步落库;提取在 PC 后台)。 + /// best-effort:失败只记证据,不影响已过检响应的交付语义。 + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send; +} + +#[derive(Debug, thiserror::Error)] +pub enum GateError { + #[error("gate unavailable: {0}")] + GateUnavailable(String), + #[error("gate response malformed: {0}")] + Malformed(String), +} diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs new file mode 100644 index 0000000000..846086d895 --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -0,0 +1,110 @@ +use crate::{GateClient, GateError}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use serde::de::DeserializeOwned; +use serde::Serialize; +use std::future::Future; + +/// 独立部署形态:HTTPS/TCP 直连 PowerContext Server 的公开契约。 +/// 同机组合部署用 `UdsGateClient`(HTTP over Unix Domain Socket)。 +#[derive(Debug, Clone)] +pub struct HttpGateClient { + base_url: String, + client: reqwest::Client, + /// Server 认证令牌(POWERCONTEXT_SERVER_AUTH_TOKEN);None 时不带认证头。 + token: Option, +} + +impl HttpGateClient { + pub fn new(base_url: impl Into) -> Self { + Self::with_token(base_url, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) + } + + pub fn with_token(base_url: impl Into, token: Option) -> Self { + Self { + base_url: base_url.into().trim_end_matches('/').to_string(), + client: reqwest::Client::new(), + token: token.filter(|t| !t.is_empty()), + } + } + + async fn post(&self, path: &str, body: &impl Serialize) -> Result + where + R: DeserializeOwned, + { + let url = format!("{}{}", self.base_url, path); + let resp = self + .client + .post(&url) + // RFC:DTO 复用 scope-mode/access 声明头。 + .header("x-powercontext-scope-mode", "current") + .bearer_auth(self.token.clone().unwrap_or_default()) + .header("content-type", "application/json") + .json(body) + .send() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + let status = resp.status(); + if !status.is_success() { + return Err(GateError::GateUnavailable(format!( + "gate returned HTTP {status}" + ))); + } + let bytes = resp + .bytes() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + serde_json::from_slice(&bytes) + .map_err(|e| GateError::Malformed(format!("decode {path}: {e}"))) + } +} + +impl GateClient for HttpGateClient { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + async move { self.post("/v1/context/check", &request).await } + } + + fn capabilities( + &self, + ) -> impl Future> + Send { + async move { + let url = format!("{}/v1/capabilities", self.base_url); + let resp = self + .client + .get(&url) + .header("x-powercontext-scope-mode", "current") + .bearer_auth(self.token.clone().unwrap_or_default()) + .send() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + let status = resp.status(); + if !status.is_success() { + return Err(GateError::GateUnavailable(format!( + "capabilities HTTP {status}" + ))); + } + resp.json() + .await + .map_err(|e| GateError::Malformed(e.to_string())) + } + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + async move { self.post("/v1/context/prepare", &request).await } + } + + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send { + async move { self.post("/v1/sources/content", &request).await } + } +} diff --git a/gateway/crates/pc-gateway-core/src/lib.rs b/gateway/crates/pc-gateway-core/src/lib.rs new file mode 100644 index 0000000000..5abbb143eb --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/lib.rs @@ -0,0 +1,22 @@ +//! 执行器核心:一次托管调用的状态机。 +//! +//! 对应 RFC「一次托管调用」时序图(PR #2199 两阶段检查形态): +//! +//! ```text +//! 宿主完整输入 ─► check(before_send) ─┬─ allow ─► 发送 ─► 原始响应 ─► check(before_release) ─┬─ release ─► 返回 +//! ├─ withhold(渲染计划) ─► 只渲染获准字段 ─► 复检(最多一次) +//! └─ block ──────────────────────────────────────────┴─ refuse ──► 显式拒绝 +//! ``` +//! +//! 网关无策略:每一步的裁决都来自 `GateClient`(check API 或嵌入式等价物), +//! 本 crate 只负责把裁决串成正确的控制流,并守住失败语义。 + +mod executor; +mod gate_client; +mod http_gate_client; +mod uds_gate_client; + +pub use executor::*; +pub use gate_client::*; +pub use http_gate_client::*; +pub use uds_gate_client::*; diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs new file mode 100644 index 0000000000..b843e01e67 --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -0,0 +1,415 @@ +//! 同机组合部署形态:HTTP over Unix Domain Socket。 +//! +//! PR #2199:启用后 Rust 独占公网 TCP 端口,Python 只监听本机 UDS; +//! 网关的 check/capabilities 都走这个通道。 +//! +//! 连接按对端(唯一的 socket 路径)池化:keep-alive 复用空闲连接, +//! 池有上限;connect/read 均有超时,防止对端假死导致请求悬挂。 +//! 认证与 TCP 形态一致(UDS 不替代 bearer 认证)。 + +use crate::{GateClient, GateError}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use std::future::Future; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf}; +use tokio::net::UnixStream; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); +const READ_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_IDLE_CONNECTIONS: usize = 8; +const MAX_HEADER_BYTES: usize = 64 * 1024; +const MAX_BODY_BYTES: usize = 8 * 1024 * 1024; + +#[derive(Clone)] +pub struct UdsGateClient { + socket: PathBuf, + token: Option, + pool: Arc>>, +} + +impl std::fmt::Debug for UdsGateClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("UdsGateClient") + .field("socket", &self.socket) + .field("token", &self.token.as_ref().map(|_| "..")) + .field("idle", &self.pool.lock().map(|p| p.len()).unwrap_or(0)) + .finish() + } +} + +impl UdsGateClient { + pub fn new(socket: impl Into) -> Self { + Self::with_token(socket, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) + } + + pub fn with_token(socket: impl Into, token: Option) -> Self { + Self { + socket: socket.into(), + token: token.filter(|t| !t.is_empty()), + pool: Arc::new(Mutex::new(Vec::new())), + } + } + + fn take_idle(&self) -> Option { + self.pool.lock().ok()?.pop() + } + + fn return_idle(&self, stream: UnixStream) { + if let Ok(mut pool) = self.pool.lock() { + if pool.len() < MAX_IDLE_CONNECTIONS { + pool.push(stream); + } + } + } + + /// 发送单次 HTTP/1.1 请求;keep-alive 下连接归还池中复用。 + /// + /// 对端(uvicorn)会关闭空闲超时的 keep-alive 连接;本地 `writable()` + /// 探活发现不了这种半关闭。因此池中借出的连接若在收到任何响应前 + /// 失败(broken pipe / EOF),丢弃该连接并用新连接重试一次。 + async fn request( + &self, + method: &str, + path: &str, + body: Option<&[u8]>, + ) -> Result<(u16, Vec), GateError> { + let mut from_pool = true; // 首次也允许重试一次(对端重启场景) + for _ in 0..2 { + match self.request_once(method, path, body, from_pool).await { + Ok(x) => return Ok(x), + Err(e) if retryable(&e) => { + from_pool = false; // 下一次强制新建连接 + continue; + } + Err(e) => return Err(e), + } + } + Err(GateError::GateUnavailable("uds exhausted retry".into())) + } + + async fn request_once( + &self, + method: &str, + path: &str, + body: Option<&[u8]>, + prefer_pool: bool, + ) -> Result<(u16, Vec), GateError> { + let mut leased = LeasedConnection::new(self.clone()); + let stream = leased + .acquire(prefer_pool) + .await + .map_err(|e| { + GateError::GateUnavailable(format!("uds connect {}: {e}", self.socket.display())) + })?; + let (mut rd, mut wr) = tokio::io::split(stream); + + let body = body.unwrap_or(&[]); + let mut head = format!( + "{method} {path} HTTP/1.1\r\nHost: powercontext\r\nContent-Type: application/json\r\n\ + x-powercontext-scope-mode: current\r\nContent-Length: {}\r\n", + body.len() + ); + if let Some(t) = &self.token { + head.push_str(&format!("Authorization: Bearer {t}\r\n")); + } + head.push_str("Connection: keep-alive\r\n\r\n"); + + let write = async { + wr.write_all(head.as_bytes()).await?; + wr.write_all(body).await + }; + tokio::time::timeout(READ_TIMEOUT, write) + .await + .map_err(|_| GateError::GateUnavailable("uds write timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds write: {e}")))?; + + let (status, body, reusable) = read_response(&mut rd).await?; + if reusable { + leased.release(rd, wr); + } + Ok((status, body)) + } +} + +/// 从池中租借/归还连接。出错时不归还(连接状态不可信)。 +struct LeasedConnection { + client: UdsGateClient, + returned: bool, +} + +impl LeasedConnection { + fn new(client: UdsGateClient) -> Self { + Self { + client, + returned: false, + } + } + + async fn acquire(&mut self, prefer_pool: bool) -> std::io::Result { + // 先试空闲连接;真正的失效(对端已关闭)会在读写时报错, + // 由上层的单次重试兜底。 + if prefer_pool { + if let Some(idle) = self.client.take_idle() { + if idle.writable().await.is_ok() { + return Ok(idle); + } + } + } + tokio::time::timeout(CONNECT_TIMEOUT, UnixStream::connect(&self.client.socket)) + .await + .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "uds connect timeout"))? + } + + /// 仅在读到完整响应且连接可复用时调用。 + fn release(&mut self, rd: ReadHalf, wr: WriteHalf) { + if self.returned { + return; + } + let stream = rd.unsplit(wr); + self.client.return_idle(stream); + self.returned = true; + } +} + +/// 读取完整 HTTP/1.1 响应。返回 (status, body, 连接是否可复用)。 +async fn read_response(rd: &mut ReadHalf) -> Result<(u16, Vec, bool), GateError> { + let mut buf: Vec = Vec::with_capacity(8 * 1024); + let header_end = loop { + if let Some(pos) = find_terminator(&buf) { + break pos; + } + if buf.len() > MAX_HEADER_BYTES { + return Err(GateError::Malformed("uds header too large".into())); + } + let mut chunk = [0u8; 4096]; + let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) + .await + .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + if n == 0 { + return Err(GateError::Malformed("uds closed before headers".into())); + } + buf.extend_from_slice(&chunk[..n]); + }; + + let head = String::from_utf8_lossy(&buf[..header_end]).into_owned(); + let mut lines = head.lines(); + let status_line = lines.next().unwrap_or_default(); + let status: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| GateError::Malformed(format!("bad status line: {status_line}")))?; + + let mut content_length: Option = None; + let mut chunked = false; + let mut keep_alive = true; // HTTP/1.1 默认 keep-alive + for line in lines { + let Some((k, v)) = line.split_once(':') else { continue }; + let k = k.trim().to_ascii_lowercase(); + let v = v.trim(); + match k.as_str() { + "content-length" => content_length = v.parse().ok(), + "transfer-encoding" if v.to_ascii_lowercase().contains("chunked") => chunked = true, + "connection" if v.to_ascii_lowercase().contains("close") => keep_alive = false, + _ => {} + } + } + + let mut rest = buf.split_off(header_end + 4); + let body = if chunked { + // chunked:读完 0-chunk 后必须消费 trailer(至少终止空行), + // 否则残留字节会污染复用连接上的下一个响应。 + let (decoded, trailer_clean) = read_chunked(rd, &mut rest).await?; + if !trailer_clean { + keep_alive = false; // trailer 未完整消费,连接不可复用 + } + decoded + } else { + let len = content_length.unwrap_or(rest.len()); + if rest.len() < len { + read_more(rd, &mut rest, len).await?; + rest + } else if rest.len() > len { + // 超出声明长度:缓冲里有不属于本响应的字节(串包/残留), + // 截断正文,且连接不可复用。 + rest.truncate(len); + keep_alive = false; + rest + } else { + rest + } + }; + if body.len() > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } + Ok((status, body, keep_alive)) +} + +async fn read_more( + rd: &mut ReadHalf, + buf: &mut Vec, + target: usize, +) -> Result<(), GateError> { + while buf.len() < target { + let mut chunk = [0u8; 8192]; + let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) + .await + .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-body".into())); + } + buf.extend_from_slice(&chunk[..n]); + } + Ok(()) +} + +/// 解码 chunked 编码。返回 (body, trailer 是否完整消费)。 +async fn read_chunked( + rd: &mut ReadHalf, + buf: &mut Vec, +) -> Result<(Vec, bool), GateError> { + let mut out = Vec::new(); + loop { + // 找一行作为 chunk size。 + let line_end = loop { + if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { + break pos; + } + let mut chunk = [0u8; 4096]; + let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) + .await + .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-chunk".into())); + } + buf.extend_from_slice(&chunk[..n]); + }; + let size_str = String::from_utf8_lossy(&buf[..line_end]).into_owned(); + buf.drain(..line_end + 2); + let size = usize::from_str_radix(size_str.trim().split(';').next().unwrap_or("0"), 16) + .map_err(|_| GateError::Malformed(format!("bad chunk size: {size_str}")))?; + if size == 0 { + // 消费 trailer:连续读到空行(或读尽缓冲且对端无更多数据)。 + loop { + if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { + let line = String::from_utf8_lossy(&buf[..pos]).into_owned(); + buf.drain(..pos + 2); + if line.is_empty() { + return Ok((out, true)); // trailer 结束空行 + } + continue; // trailer 头部行 + } + let mut chunk = [0u8; 1024]; + let n = match tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)).await { + Ok(Ok(0)) => return Ok((out, false)), + Ok(Ok(n)) => n, + Ok(Err(_)) | Err(_) => return Ok((out, false)), + }; + buf.extend_from_slice(&chunk[..n]); + } + } + let needed = size + 2; // 数据 + CRLF + while buf.len() < needed { + let mut chunk = [0u8; 8192]; + let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) + .await + .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-chunk-data".into())); + } + buf.extend_from_slice(&chunk[..n]); + } + out.extend_from_slice(&buf[..size]); + buf.drain(..needed); + } +} + +/// 仅“未收到任何响应字节”的传输失败才可安全重试(幂等:请求未达对端或 +/// 对端在解析前丢弃);已收到响应头的失败必须上抛。 +fn retryable(e: &GateError) -> bool { + match e { + GateError::GateUnavailable(msg) => { + (msg.contains("uds write") || msg.starts_with("uds connect")) + && !msg.contains("timeout") + } + // "uds closed before headers":对端在响应前关闭,请求未生效。 + GateError::Malformed(msg) => msg.contains("closed before headers"), + } +} + +fn find_terminator(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +impl GateClient for UdsGateClient { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + let body = serde_json::to_vec(&request).unwrap_or_default(); + let this = self.clone(); + async move { + let (status, body) = this.request("POST", "/v1/context/check", Some(&body)).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("gate HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode check: {e}"))) + } + } + + fn capabilities( + &self, + ) -> impl Future> + Send { + let this = self.clone(); + async move { + let (status, body) = this.request("GET", "/v1/capabilities", None).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("capabilities HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode capabilities: {e}"))) + } + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + let body = serde_json::to_vec(&request).unwrap_or_default(); + let this = self.clone(); + async move { + let (status, body) = this.request("POST", "/v1/context/prepare", Some(&body)).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("prepare HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode prepare: {e}"))) + } + } + + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send { + let body = serde_json::to_vec(&request).unwrap_or_default(); + let this = self.clone(); + async move { + let (status, body) = this.request("POST", "/v1/sources/content", Some(&body)).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("capture HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode capture: {e}"))) + } + } +} diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs new file mode 100644 index 0000000000..0f6c072103 --- /dev/null +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -0,0 +1,649 @@ +//! PR #2264 失败语义表的状态机级验证(真实契约形态)。 + +use pc_gateway_core::{DegradePolicy, Executor, GateClient, GateError, ManagedCall, ManagedOutcome}; +use pc_gateway_evidence::{BufferedEvidenceSink, NoopEvidenceSink}; +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OutputLimits, RenderedPayload, Role, WireRenderer, +}; +use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; +use pc_gateway_types::{ + CheckDecision, CheckPhase, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + CaptureContentSourceRequest, PrepareContextResult, PreparedContext, PreparedContextLocation, +}; +use std::collections::VecDeque; +use std::future::Future; +use std::num::NonZeroU32; +use std::sync::{Arc, Mutex}; + +// ---------- 测试替身 ---------- + +struct RecordingRenderer { + renders: Mutex, +} + +impl WireRenderer for RecordingRenderer { + fn name(&self) -> &'static str { + "test" + } + fn render( + &self, + request: &CanonicalRequest, + _plan: Option<&serde_json::Value>, + ) -> Result { + *self.renders.lock().unwrap() += 1; + let messages: Vec = request + .messages + .iter() + .map(|m| { + let content = match m.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => serde_json::json!(other), + }; + serde_json::json!({ "role": m.role, "content": content }) + }) + .collect(); + let bytes = serde_json::to_vec(&serde_json::json!({ + "model": request.model, + "messages": messages, + })) + .unwrap() + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} + +/// 脚本化检查客户端:按序弹出结果,记录请求阶段与载荷。 +struct FakeGate { + results: Mutex>>, + seen: Mutex>, + prepared_seen: Mutex>>, + prepare_result: Mutex>>, + prepare_queries: Mutex>, + captured: Mutex>, +} + +impl GateClient for FakeGate { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + let (phase, note) = match &request { + ContextCheckRequest::BeforeSend { payload, .. } => { + (CheckPhase::BeforeSend, payload.body.clone()) + } + ContextCheckRequest::BeforeRelease { + request_binding, .. + } => (CheckPhase::BeforeRelease, request_binding.clone()), + }; + let declared = match &request { + ContextCheckRequest::BeforeSend { prepared_contexts, .. } => prepared_contexts.clone(), + _ => Vec::new(), + }; + self.prepared_seen.lock().unwrap().push(declared); + self.seen.lock().unwrap().push((phase, note)); + let step = self.results.lock().unwrap().pop_front(); + async move { step.expect("gate script exhausted") } + } + + fn capabilities( + &self, + ) -> impl Future> + Send { + async move { Ok(serde_json::json!({ "enforcing": false })) } + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + self.prepare_queries.lock().unwrap().push(request.query); + let step = self.prepare_result.lock().unwrap().take() + .unwrap_or(Ok(PrepareContextResult::Plain(PreparedContext { + schema: "powercontext.prepared-context.v1".into(), + status: "empty".into(), + content: None, + content_bytes: 0, + }))); + async move { step } + } + + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send { + self.captured.lock().unwrap().push((request.source_id, request.content)); + async move { Ok(serde_json::json!({"captured": true})) } + } +} + +struct FakeTransport { + outcomes: Mutex>, + sends: Mutex>, + bindings: Mutex>, + cancels: Mutex, +} + +impl Transport for FakeTransport { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a { + let outcome = self.outcomes.lock().unwrap().pop_front(); + self.sends.lock().unwrap().push(send.payload); + self.bindings.lock().unwrap().push(send.binding); + async move { + outcome.unwrap_or_else(|| panic!("transport script exhausted")) + } + } + + fn cancel<'a>(&'a self, _send: &'a AdmittedSend) -> impl Future + Send + 'a { + *self.cancels.lock().unwrap() += 1; + async {} + } +} + +fn raw_response() -> SendOutcome { + SendOutcome::Delivered(pc_gateway_transport::RawResponse { + status: 200, + content_type: "application/json".into(), + ttft_ms: None, + body: bytes::Bytes::from_static(br#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#), + usage: Some(serde_json::json!({"total_tokens": 1})), + }) +} + +fn result(phase: CheckPhase, decision: CheckDecision, reasons: &[&str]) -> ContextCheckResult { + ContextCheckResult { + schema: pc_gateway_types::CONTEXT_CHECK_SCHEMA.into(), + phase, + decision, + reason_codes: reasons.iter().map(|s| s.to_string()).collect(), + coverage: pc_gateway_types::ContextCheckCoverage { + profile: "text-and-tools.v1".into(), + complete: true, + }, + policy_version: "v1".into(), + valid_until: "2999-01-01T00:00:00Z".into(), + correlate_until: None, + binding: matches!(decision, CheckDecision::Allow).then(|| "binding-1".to_string()), + } +} + +fn call(degrade: DegradePolicy) -> ManagedCall { + ManagedCall { + scope_id: "project:test".into(), + target_profile: "openai:test".into(), + request: CanonicalRequest { + model: "test-model".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hello")], + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 128, + }, + stream: false, + }, + target_url: "http://upstream.invalid/v1/chat/completions".into(), + headers: vec![("authorization".into(), "Bearer secret".into())], + degrade_policy: degrade, + inject_context: false, + sediment: false, + prepared_contexts: Vec::new(), + } +} + +#[derive(Clone)] +struct RendererRef(Arc); +impl WireRenderer for RendererRef { + fn name(&self) -> &'static str { + "test" + } + fn render( + &self, + request: &CanonicalRequest, + plan: Option<&serde_json::Value>, + ) -> Result { + WireRenderer::render(&*self.0, request, plan) + } +} + +#[derive(Clone)] +struct TransportRef(Arc); +impl Transport for TransportRef { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a { + Transport::send(&*self.0, send) + } + fn cancel<'a>(&'a self, send: &'a AdmittedSend) -> impl Future + Send + 'a { + Transport::cancel(&*self.0, send) + } +} + +#[derive(Clone)] +struct FakeGateRef(Arc); +impl GateClient for FakeGateRef { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + GateClient::check(&*self.0, request) + } + fn capabilities( + &self, + ) -> impl Future> + Send { + GateClient::capabilities(&*self.0) + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + GateClient::prepare(&*self.0, request) + } + + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send { + GateClient::capture(&*self.0, request) + } +} + +fn harness( + gate_results: Vec>, + transport_outcomes: Vec, + max_attempts: u32, +) -> ( + Executor, + Arc, + Arc, + Arc, +) { + let renderer = Arc::new(RecordingRenderer { renders: Mutex::new(0) }); + let transport = Arc::new(FakeTransport { + outcomes: Mutex::new(transport_outcomes.into()), + sends: Mutex::new(Vec::new()), + bindings: Mutex::new(Vec::new()), + cancels: Mutex::new(0), + }); + let gate = Arc::new(FakeGate { + results: Mutex::new(gate_results.into()), + seen: Mutex::new(Vec::new()), + prepared_seen: Mutex::new(Vec::new()), + prepare_result: Mutex::new(None), + prepare_queries: Mutex::new(Vec::new()), + captured: Mutex::new(Vec::new()), + }); + let executor = Executor::new( + FakeGateRef(gate.clone()), + TransportRef(transport.clone()), + NonZeroU32::new(max_attempts).unwrap(), + ); + (executor, renderer, transport, gate) +} + +// ---------- 用例 ---------- + +#[tokio::test] +async fn allow_send_allow_release() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Released { binding, status, body, .. } => { + assert_eq!(binding.as_deref(), Some("binding-1")); + assert_eq!(status, 200); + let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(v["choices"][0]["message"]["content"], "ok"); + } + other => panic!("expected Released, got {other:?}"), + } + let seen = gate.seen.lock().unwrap().clone(); + assert_eq!(seen.len(), 2); + assert_eq!(seen[1], (CheckPhase::BeforeRelease, "binding-1".into())); + assert_eq!(transport.bindings.lock().unwrap()[0], "binding-1"); +} + +#[tokio::test] +async fn before_send_block_never_sends() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), + other => panic!("expected Blocked, got {other:?}"), + } + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn withhold_is_terminal_in_pr2264_contract() { + let (executor, renderer, transport, gate) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Withhold, + &["coverage.incomplete"], + ))], + vec![], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::Withheld { .. })); + assert_eq!(*renderer.renders.lock().unwrap(), 1); + assert_eq!(gate.seen.lock().unwrap().len(), 1); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn gate_unavailable_pauses_never_allow() { + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::GateUnavailable("down".into()))], + vec![], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::GatePaused(_))); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn gate_unavailable_degrades_when_allowed() { + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::GateUnavailable("down".into()))], + vec![raw_response()], + 2, + ); + let evidence = BufferedEvidenceSink::new(); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &evidence, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Degraded { .. })); + assert_eq!(evidence.not_sent().len(), 1); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn block_does_not_degrade() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Blocked { .. })); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn deterministic_not_sent_retries_bounded() { + let (executor, renderer, _transport, _g) = harness( + vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![ + SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), + SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), + ], + 2, + ); + let evidence = BufferedEvidenceSink::new(); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &evidence) + .await; + assert!(matches!(outcome, ManagedOutcome::NotSent { attempts: 2 })); + assert_eq!(evidence.attempts(), vec![1, 2]); +} + +#[tokio::test] +async fn indeterminate_never_resends() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![SendOutcome::Indeterminate( + pc_gateway_transport::SendIndeterminateReason::TimeoutAwaitingResponse, + )], + 3, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::SendIndeterminate)); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn before_release_block_blocks_and_cancels() { + let (executor, renderer, transport, _g) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result( + CheckPhase::BeforeRelease, + CheckDecision::Block, + &["privacy.denied"], + )), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), + other => panic!("expected Blocked, got {other:?}"), + } + assert_eq!(*transport.cancels.lock().unwrap(), 1); +} + +#[tokio::test] +async fn credentials_never_enter_check_payload() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + let seen = gate.seen.lock().unwrap().clone(); + let (_, before_send_payload) = &seen[0]; + assert!( + !before_send_payload.contains("secret"), + "authorization 凭据不得进入 check 载荷: {before_send_payload}" + ); +} + +// ---------- 注入用例 ---------- + +fn reuse_result(content: &str) -> PrepareContextResult { + PrepareContextResult::WithReuse { + schema: "powercontext.prepared-context-with-reuse.v1".into(), + context: PreparedContext { + schema: "powercontext.prepared-context.v1".into(), + status: "ready".into(), + content: Some(content.to_string()), + content_bytes: content.len() as u64, + }, + reuse: pc_gateway_types::ContextReuse { + schema: "powercontext.context-reuse.v1".into(), + constraints: None, + expires_at: "2999-01-01T00:00:00Z".into(), + binding: "opaque-binding".into(), + }, + } +} + +#[tokio::test] +async fn injects_block_and_declares_exact_location() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( + "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", + ))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + assert!(matches!(outcome, ManagedOutcome::Released { .. })); + + // 检索词 = 最后一条 user 消息文本 + assert_eq!(gate.prepare_queries.lock().unwrap()[0], "hello"); + + // 载荷:标准块位于 user 消息头部 + let seen = gate.seen.lock().unwrap().clone(); + let payload = &seen[0].1; + let v: serde_json::Value = serde_json::from_str( + &format!("{{\"inner\":{payload}}}").replace("\"inner\":{", "\"inner\":", ), + ) + .unwrap_or(serde_json::Value::Null); + let _ = v; + let msg_text = extract_user_text(payload); + assert!(msg_text.starts_with("BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"), "块必须在头部: {msg_text}"); + assert!(msg_text.contains("网关必须无策略")); + assert!(msg_text.ends_with("hello")); + + // 区间声明:binding 原样、字节长度 = 块的 UTF-8 字节数(中文≠字符数) + let declared = gate.prepared_seen.lock().unwrap().clone(); + assert_eq!(declared[0].len(), 1); + let loc = &declared[0][0]; + assert_eq!(loc.binding, "opaque-binding"); + assert_eq!(loc.location.pointer, "/messages/0/content"); + assert_eq!(loc.location.schema, "powercontext.model-json-text-location.v1"); + assert_eq!(loc.location.start_byte, 0); + let block = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1"; + assert_eq!(loc.location.end_byte as usize, block.as_bytes().len()); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +fn extract_user_text(before_send_payload: &str) -> String { + // FakeGate 记录的即渲染后的请求体 JSON + let body: serde_json::Value = serde_json::from_str(before_send_payload).unwrap(); + body["messages"][0]["content"].as_str().unwrap().to_string() +} + +#[tokio::test] +async fn empty_prepare_injects_nothing() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + // prepare 默认返回 empty(FakeGate 默认值) + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + let seen = gate.seen.lock().unwrap().clone(); + assert!(!seen[0].1.contains("BEGIN_POWERCONTEXT"), "empty 不得注入标记"); + assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); +} + +#[tokio::test] +async fn prepare_failure_still_sends_without_injection() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Err(GateError::GateUnavailable("down".into()))); + let evidence = BufferedEvidenceSink::new(); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + let outcome = executor.run(c, &RendererRef(renderer.clone()), &evidence).await; + assert!(matches!(outcome, ManagedOutcome::Released { .. }), "prepare 失败不阻塞主链路"); + assert_eq!(transport.sends.lock().unwrap().len(), 1); + assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); + assert!(evidence.not_sent()[0].1.starts_with("prepare_failed")); +} + +#[tokio::test] +async fn sediment_captures_released_turn_synchronously() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + assert!(matches!(outcome, ManagedOutcome::Released { .. })); + let captured = gate.captured.lock().unwrap().clone(); + assert_eq!(captured.len(), 1, "Released 轮次同步沉淀一次"); + assert!(captured[0].0.starts_with("gw-turn-"), "幂等键: {}", captured[0].0); + let v: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); + assert_eq!(v["user"], "hello"); + assert_eq!(v["model"], "test-model"); +} + +#[tokio::test] +async fn blocked_turn_never_sediments() { + let (executor, renderer, _t, gate) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + assert!(gate.captured.lock().unwrap().is_empty(), "被拦内容不得沉淀"); +} diff --git a/gateway/crates/pc-gateway-core/tests/live_context_check.rs b/gateway/crates/pc-gateway-core/tests/live_context_check.rs new file mode 100644 index 0000000000..4f14c61d76 --- /dev/null +++ b/gateway/crates/pc-gateway-core/tests/live_context_check.rs @@ -0,0 +1,235 @@ +//! 对真实 PowerContext Server(PR #2264)的 HTTP 级集成测试。 +//! +//! 与单测(FakeGate)互补:这里验证的是 Core 侧加密 binding 的真实行为, +//! mock 无法复现。运行条件:真实 Server 在 PC_TEST_CORE_BASE(默认 +//! http://127.0.0.1:8000)可达且配置了 enforcing 保护与 "coding" profile; +//! 不可达时全部跳过(不失败)。 + +use pc_gateway_core::{GateClient, GateError, HttpGateClient}; +use pc_gateway_types::{ + CheckDecision, ContextCheckRequest, ContextCheckResult, ModelJsonPayload, +}; +use std::collections::BTreeMap; + +const CORE: &str = "http://127.0.0.1:8000"; +const TARGET_PROFILE: &str = "coding"; +const MODEL_BODY: &str = r#"{"model":"glm-4-flash","max_tokens":80,"stream":false,"messages":[{"role":"user","content":"hi"}]}"#; +const RESPONSE_BODY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#; + +fn client() -> HttpGateClient { + HttpGateClient::new(CORE) +} + +async fn core_ready() -> bool { + reqwest::Client::new() + .get(format!("{CORE}/health/ready")) + .timeout(std::time::Duration::from_secs(2)) + .send() + .await + .map(|r| r.status().is_success()) + .unwrap_or(false) +} + +async fn require_core() -> Option<()> { + if core_ready().await { + Some(()) + } else { + eprintln!("SKIP: real PowerContext Server not reachable at {CORE}"); + None + } +} + +fn payload(body: &str) -> ModelJsonPayload { + ModelJsonPayload::new( + BTreeMap::from([("content-type".to_string(), "application/json".to_string())]), + body.to_string(), + ) +} + +async fn create_scope(tag: &str) -> Option { + let resp = reqwest::Client::new() + .post(format!("{CORE}/v1/scopes")) + .json(&serde_json::json!({ + "title": format!("Rust gateway test {tag}"), + "summary": "created by live integration tests", + "idempotency_key": format!("rust-live-{tag}"), + })) + .send() + .await + .ok()?; + let v: serde_json::Value = resp.json().await.ok()?; + v.get("scope_id")?.as_str().map(String::from) +} + +async fn before_send(scope: &str) -> Result { + client() + .check(ContextCheckRequest::BeforeSend { + scope_id: scope.to_string(), + target_profile: TARGET_PROFILE.to_string(), + payload: payload(MODEL_BODY), + prepared_contexts: Vec::new(), + }) + .await +} + +async fn before_release(scope: &str, binding: &str) -> Result { + client() + .check(ContextCheckRequest::BeforeRelease { + scope_id: scope.to_string(), + target_profile: TARGET_PROFILE.to_string(), + request_binding: binding.to_string(), + payload: payload(RESPONSE_BODY), + completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.to_string(), + }) + .await +} + +// ---------- 用例 ---------- + +/// happy path:真实 allow 返回加密 binding、完整覆盖与两个期限。 +#[tokio::test] +async fn live_allow_returns_real_binding_and_deadlines() { + let Some(_) = require_core().await else { return }; + let Some(scope) = create_scope("happy").await else { + panic!("scope creation failed"); + }; + let result = before_send(&scope).await.expect("check should succeed"); + + assert_eq!(result.decision, CheckDecision::Allow, "reasons: {:?}(需配置 coding profile)", result.reason_codes); + assert!(result.coverage.complete); + let binding = result.binding.as_deref().expect("allow 必须携带 binding"); + assert!(binding.starts_with("pc1."), "真实加密 binding 前缀: {binding:.20}..."); + + // 期限分离:发送窗口 ~60s,关联窗口 ~300s。 + let now = chrono_like_now(); + let valid = parse_epoch_ms(&result.valid_until); + let correlate = result.correlate_until.as_deref().map(|s| parse_epoch_ms(s)); + assert!( + valid > now && valid <= now + 65_000, + "发送期限应在 60s 窗口内: valid={valid} now={now}" + ); + let Some(correlate) = correlate else { panic!("before_send allow 必须带 correlate_until") }; + assert!( + correlate > now && correlate <= now + 310_000, + "关联期限应在 300s 窗口内" + ); +} + +/// 伪造 binding 做 before_release → Core 必须拒绝(绝不能 allow)。 +#[tokio::test] +async fn live_forged_binding_is_rejected() { + let Some(_) = require_core().await else { return }; + let Some(scope) = create_scope("forged").await else { panic!("scope creation failed") }; + let result = before_release(&scope, "pc1.forged-binding-not-issued-by-core").await; + match result { + Ok(r) => assert_ne!( + r.decision, + CheckDecision::Allow, + "伪造 binding 不得被放行: {:?}", + r.reason_codes + ), + // 4xx 拒绝(如绑定校验直接失败)同样视为通过。 + Err(GateError::GateUnavailable(msg)) => assert!( + msg.contains("HTTP 4"), + "期望 4xx 拒绝,得到: {msg}" + ), + Err(other) => panic!("unexpected: {other}"), + } +} + +/// binding 跨 Scope 使用 → 拒绝(对应 PC 测试 +/// `test_request_binding_cannot_cross_identity_scope_or_current_policy`)。 +#[tokio::test] +async fn live_binding_cannot_cross_scope() { + let Some(_) = require_core().await else { return }; + let (Some(scope_a), Some(scope_b)) = (create_scope("cross-a").await, create_scope("cross-b").await) + else { + panic!("scope creation failed"); + }; + let allow = before_send(&scope_a).await.expect("check a"); + assert_eq!(allow.decision, CheckDecision::Allow, "reasons: {:?}", allow.reason_codes); + let binding = allow.binding.expect("binding"); + + let cross = before_release(&scope_b, &binding).await; + match cross { + Ok(r) => assert_ne!( + r.decision, + CheckDecision::Allow, + "A 的 binding 不得放行 B 的释放: {:?}", + r.reason_codes + ), + Err(GateError::GateUnavailable(msg)) => assert!( + msg.contains("HTTP 4"), + "期望 4xx 拒绝,得到: {msg}" + ), + Err(other) => panic!("unexpected: {other}"), + } +} + +/// 线格式刚性:缺 prepared_contexts(必填)→ 422,验证 Rust DTO 与 +/// 真实 OpenAPI 的逐字段对齐。 +#[tokio::test] +async fn live_missing_prepared_contexts_rejected() { + let Some(_) = require_core().await else { return }; + let Some(scope) = create_scope("dto").await else { panic!("scope creation failed") }; + let raw = serde_json::json!({ + "phase": "before_send", + "scope_id": scope, + "target_profile": TARGET_PROFILE, + "payload": { + "schema": pc_gateway_types::MODEL_JSON_PAYLOAD_SCHEMA, + "headers": {"content-type": "application/json"}, + "body": MODEL_BODY, + }, + // 故意省略 prepared_contexts + }); + let resp = reqwest::Client::new() + .post(format!("{CORE}/v1/context/check")) + .json(&raw) + .send() + .await + .expect("post"); + assert_eq!(resp.status().as_u16(), 422, "缺必填字段必须 422"); +} + +// ---------- 工具 ---------- + +/// 无 chrono 依赖的简易 RFC3339 解析(足够测试用,格式由 Core 保证)。 +fn parse_epoch_ms(rfc3339: &str) -> u64 { + // 形如 2026-10-28T09:55:06.464580Z + let bytes = rfc3339.as_bytes(); + let year: i64 = rfc3339[0..4].parse().unwrap(); + let month: i64 = rfc3339[5..7].parse().unwrap(); + let day: i64 = rfc3339[8..10].parse().unwrap(); + let hour: i64 = rfc3339[11..13].parse().unwrap(); + let min: i64 = rfc3339[14..16].parse().unwrap(); + let sec: i64 = rfc3339[17..19].parse().unwrap(); + let millis: i64 = if bytes.len() > 20 { + let frac = &rfc3339[20..rfc3339.len().saturating_sub(1)]; + let frac = frac.trim_end_matches('Z'); + let taken: String = frac.chars().take(3).collect(); + taken.parse().unwrap_or(0) + } else { + 0 + }; + // 简化儒略日换算(1970 起,平年近似,测试时间尺度下足够)。 + let days = days_from_civil(year, month, day); + ((days * 86_400 + hour * 3600 + min * 60 + sec) * 1000 + millis) as u64 +} + +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn chrono_like_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} diff --git a/gateway/crates/pc-gateway-core/tests/uds_pool.rs b/gateway/crates/pc-gateway-core/tests/uds_pool.rs new file mode 100644 index 0000000000..58f08645cc --- /dev/null +++ b/gateway/crates/pc-gateway-core/tests/uds_pool.rs @@ -0,0 +1,115 @@ +//! UDS 连接池正确性回归:keep-alive 连接上的连续响应必须逐次正确解析。 +//! 覆盖三个场景:content-length 精确、chunked(含 trailer)、content-length 超读截断。 + +use pc_gateway_core::{GateClient, UdsGateClient}; +use pc_gateway_types::{ + CheckDecision, CheckPhase, ContextCheckRequest, ContextCheckResult, ModelJsonPayload, +}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{UnixListener, UnixStream}; + +static CONN_COUNT: AtomicUsize = AtomicUsize::new(0); + +fn result_json(decision: &str) -> String { + let schema = "powercontext.context-check.v1"; + format!( + r#"{{"schema":"{schema}","phase":"before_send","decision":"{decision}","reason_codes":[],"coverage":{{"profile":"text-and-tools.v1","complete":true}},"policy_version":"t","valid_until":"2999-01-01T00:00:00Z","binding":"b1"}}"# + ) +} + +fn check_request() -> ContextCheckRequest { + ContextCheckRequest::BeforeSend { + scope_id: "s".into(), + target_profile: "p".into(), + payload: ModelJsonPayload::new(BTreeMap::new(), "{}".into()), + prepared_contexts: Vec::new(), + } +} + +/// 读一行请求头直到空行(忽略 body 细节,够用即可)。 +async fn read_request(conn: &mut UnixStream) { + let mut buf = Vec::new(); + let mut byte = [0u8; 1]; + loop { + conn.read_exact(&mut byte).await.unwrap(); + buf.push(byte[0]); + if buf.ends_with(b"\r\n\r\n") { + break; + } + } + // 简化:Content-Length 为 0 的探测请求到此结束;带 body 的读掉 + let head = String::from_utf8_lossy(&buf).to_string(); + if let Some(len) = head + .lines() + .find_map(|l| l.strip_prefix("Content-Length: ").map(|v| v.trim().parse::().ok()).flatten()) + { + let mut body = vec![0u8; len]; + if len > 0 { + conn.read_exact(&mut body).await.unwrap(); + } + } +} + +#[tokio::test] +async fn pooled_connection_parses_sequential_responses_correctly() { + let dir = std::env::temp_dir().join(format!("pc-uds-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("pool.sock"); + let _ = std::fs::remove_file(&sock); + let listener = UnixListener::bind(&sock).unwrap(); + + let server = tokio::spawn(async move { + let (mut conn, _) = listener.accept().await.unwrap(); + CONN_COUNT.fetch_add(1, Ordering::SeqCst); + + // 请求1 → content-length 精确 + read_request(&mut conn).await; + let body = result_json("allow"); + conn.write_all( + format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", body.len()).as_bytes(), + ).await.unwrap(); + conn.write_all(body.as_bytes()).await.unwrap(); + + // 请求2 → chunked(0-chunk + 终止 CRLF,即 trailer 空行) + read_request(&mut conn).await; + let body2 = result_json("allow"); + let mut chunked = Vec::new(); + chunked.extend_from_slice(format!("{:x}\r\n", body2.len()).as_bytes()); + chunked.extend_from_slice(body2.as_bytes()); + chunked.extend_from_slice(b"\r\n0\r\n\r\n"); + conn.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n", + ).await.unwrap(); + conn.write_all(&chunked).await.unwrap(); + + // 请求3 → content-length 后故意多推 5 个脏字节(应被截断且连接不复用) + read_request(&mut conn).await; + let body3 = result_json("allow"); + conn.write_all( + format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body3.len()).as_bytes(), + ).await.unwrap(); + conn.write_all(body3.as_bytes()).await.unwrap(); + conn.write_all(b"DIRTY").await.unwrap(); + // 保持连接打开一会儿,验证客户端没把脏字节当下一响应 + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + }); + + let client = UdsGateClient::new(&sock); + // 请求1:content-length 精确 + let r1 = client.check(check_request()).await.unwrap(); + assert_eq!(r1.decision, CheckDecision::Allow); + // 请求2:chunked 应正确解码(而非把 trailer 当下一个响应头) + let r2 = client.check(check_request()).await.unwrap(); + assert_eq!(r2.decision, CheckDecision::Allow); + assert_eq!(r2.phase, CheckPhase::BeforeSend, "chunked 解码后字段完整"); + // 请求3:超读截断——body 应恰好是合法 JSON(脏字节被丢弃) + let r3 = client.check(check_request()).await.unwrap(); + assert_eq!(r3.decision, CheckDecision::Allow); + + server.await.unwrap(); + // 三次请求只应建立一条连接(第3次后因脏字节弃用,但那是之后的事) + assert_eq!(CONN_COUNT.load(Ordering::SeqCst), 1, "keep-alive 应复用同一连接"); +} diff --git a/gateway/crates/pc-gateway-embedded/Cargo.toml b/gateway/crates/pc-gateway-embedded/Cargo.toml new file mode 100644 index 0000000000..bc5b6ef3ef --- /dev/null +++ b/gateway/crates/pc-gateway-embedded/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "pc-gateway-embedded" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: optional embedded/FFI surface for in-process (Python) executors" + +[dependencies] +pc-gateway-core = { workspace = true } +pc-gateway-types = { workspace = true } diff --git a/gateway/crates/pc-gateway-embedded/src/lib.rs b/gateway/crates/pc-gateway-embedded/src/lib.rs new file mode 100644 index 0000000000..aeec6fd8ea --- /dev/null +++ b/gateway/crates/pc-gateway-embedded/src/lib.rs @@ -0,0 +1,8 @@ +//! 嵌入式路径的占位 crate。 +//! +//! RFC:SDK/内置执行与 Rust GatewayRuntime 是按调用配置的两种执行路径, +//! 同一部署可并存,落实同一套 Core 决策。本 crate 未来承载 +//! pyo3/FFI 绑定,让 Python 进程内执行器复用 `pc-gateway-core` 的状态机, +//! 并以进程内 `GateClient` 实现直调 Core 算法(无需 HTTP)。 +//! +//! v1 尚未实现;保留 crate 以固定 workspace 边界。 diff --git a/gateway/crates/pc-gateway-evidence/Cargo.toml b/gateway/crates/pc-gateway-evidence/Cargo.toml new file mode 100644 index 0000000000..abbef5e020 --- /dev/null +++ b/gateway/crates/pc-gateway-evidence/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "pc-gateway-evidence" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: evidence normalization — usage completeness, cache read/write, latency; never bodies" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs new file mode 100644 index 0000000000..cdc6cab546 --- /dev/null +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -0,0 +1,98 @@ +//! 证据适配层。 +//! +//! RFC 约束:归一化实际目标身份、usage 完整性、供应商缓存 read/write、 +//! 失败尝试与延迟;分别报告上游首 token 与首次内容释放时间; +//! **绝不记录 query/prompt/响应正文/凭据**;执行身份不进指标标签。 +//! 已知 / 估算 / 未知 / 对账用量分开记录,不可用标 unknown 不记零。 + +use serde::{Deserialize, Serialize}; + +/// usage 完整性:不把缺失当零。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UsageCompleteness { + Known, + Estimated, + Unknown, + Reconciled, +} + +/// 单次调用的无正文证据记录。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct CallEvidence { + /// 实际发送目标身份(归一化后),不是客户端声称的目标。 + pub actual_target: Option, + pub completeness: Option, + pub input_tokens: Option, + pub output_tokens: Option, + pub cache_read_tokens: Option, + pub cache_write_tokens: Option, + pub attempts: u32, + /// 上游首 token 延迟(毫秒)。 + pub upstream_ttft_ms: Option, + /// 首次内容释放延迟(毫秒)。strict 模式下必然晚于 ttft。 + pub first_release_ms: Option, + /// 失败原因类别(无正文)。 + pub failure_reason: Option, +} + +/// 证据下沉抽象。实现可以是空对象(观测可选), +/// 借鉴 TensorZero 的 disabled client 模式。 +pub trait EvidenceSink: Send + Sync { + fn record_attempt(&self, attempt: u32); + fn record_not_sent(&self, attempt: u32, reason: &str); + fn record_call(&self, evidence: &CallEvidence); +} + +/// 空对象实现:观测关闭时使用。 +#[derive(Debug, Default, Clone, Copy)] +pub struct NoopEvidenceSink; + +impl EvidenceSink for NoopEvidenceSink { + fn record_attempt(&self, _attempt: u32) {} + fn record_not_sent(&self, _attempt: u32, _reason: &str) {} + fn record_call(&self, _evidence: &CallEvidence) {} +} + +/// 内存缓冲实现:测试与本地演示用;不落盘、不落正文。 +#[derive(Debug, Default)] +pub struct BufferedEvidenceSink { + attempts: std::sync::Mutex>, + not_sent: std::sync::Mutex>, + calls: std::sync::Mutex>, +} + +impl BufferedEvidenceSink { + pub fn new() -> Self { + Self::default() + } + + pub fn attempts(&self) -> Vec { + self.attempts.lock().expect("evidence lock").clone() + } + + pub fn not_sent(&self) -> Vec<(u32, String)> { + self.not_sent.lock().expect("evidence lock").clone() + } + + pub fn calls(&self) -> Vec { + self.calls.lock().expect("evidence lock").clone() + } +} + +impl EvidenceSink for BufferedEvidenceSink { + fn record_attempt(&self, attempt: u32) { + self.attempts.lock().expect("evidence lock").push(attempt); + } + + fn record_not_sent(&self, attempt: u32, reason: &str) { + self.not_sent + .lock() + .expect("evidence lock") + .push((attempt, reason.to_string())); + } + + fn record_call(&self, evidence: &CallEvidence) { + self.calls.lock().expect("evidence lock").push(evidence.clone()); + } +} diff --git a/gateway/crates/pc-gateway-protocol/Cargo.toml b/gateway/crates/pc-gateway-protocol/Cargo.toml new file mode 100644 index 0000000000..50b555190b --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "pc-gateway-protocol" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: canonical internal types + per-provider wire-format conversion + SSE parsing" + +[dependencies] +pc-gateway-types = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +bytes = { workspace = true } +thiserror = { workspace = true } diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs new file mode 100644 index 0000000000..0ec8d0711e --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -0,0 +1,49 @@ +use serde::{Deserialize, Serialize}; + +/// 网关内部规范请求:发送前必须完整落入 input/check。 +/// 只保留结构性字段,语义内容由 Core 裁决。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CanonicalRequest { + pub model: String, + pub messages: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tools: Vec, + /// Responses API 的 instructions(系统级指令);chat 格式为 None。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_cache_fields: Option, + /// 显式输出限制(与输入预算分开;见 RFC「补充上下文字节与完整请求 token」)。 + pub output_limits: OutputLimits, + /// 是否请求上游流式(SSE)。strict 语义不变:网关全量缓冲并过 + /// before_release 后才向客户端释放;流式的是上游接收路径。 + #[serde(default)] + pub stream: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CanonicalMessage { + pub role: Role, + pub content: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + System, + User, + Assistant, + Tool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputLimits { + pub max_output_tokens: u32, +} + +/// 渲染结果:语义内容不变的最终字节。 +#[derive(Debug, Clone)] +pub struct RenderedPayload { + pub bytes: bytes::Bytes, + pub content_type: &'static str, +} diff --git a/gateway/crates/pc-gateway-protocol/src/lib.rs b/gateway/crates/pc-gateway-protocol/src/lib.rs new file mode 100644 index 0000000000..2313875b32 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/lib.rs @@ -0,0 +1,13 @@ +//! 协议适配层:内部规范类型 ↔ 各服务商线格式。 +//! +//! RFC 约束:只渲染获准的协议字段;保持角色、工具顺序、内容块、 +//! 可复用边界与获准原生缓存设置;不向稳定 prompt 写入请求 ID/时间戳、 +//! 不任意合并旧消息、不静默重映射目标。 + +mod canonical; +mod render; +mod sse; + +pub use canonical::*; +pub use render::*; +pub use sse::*; diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs new file mode 100644 index 0000000000..482ed92187 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -0,0 +1,234 @@ +use crate::{CanonicalRequest, RenderedPayload}; + +/// 渲染错误。 +#[derive(Debug, thiserror::Error)] +pub enum RenderError { + #[error("unsupported field for renderer {renderer}: {field}")] + UnsupportedField { renderer: &'static str, field: String }, + #[error("cache render plan invalid for renderer {renderer}")] + InvalidRenderPlan { renderer: &'static str }, +} + +/// 线格式渲染器。OpenAI 系实现共享同一份 chat-completions 渲染 +/// (借鉴 TensorZero 的 chat_completions 共享模块模式)。 +/// +/// v1 strict 语义:完整渲染最终字节交给 input/check; +/// 缓存渲染计划(withhold 附带)只允许合并计划里显式列出的顶层字段。 +pub trait WireRenderer: Send + Sync { + fn name(&self) -> &'static str; + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result; +} + +/// OpenAI 兼容 chat-completions 渲染器。 +/// +/// 不依赖厂商 SDK,直接序列化线格式(对齐 RFC:高层包装无法证明 +/// 覆盖最终序列化、内部重试与原始错误)。strict v1 固定 `stream: false`, +/// 上游以完整单元返回,SSE 分帧在 output/check 之后由网关侧完成。 +#[derive(Debug, Default, Clone, Copy)] +pub struct OpenAiChatRenderer; + +impl WireRenderer for OpenAiChatRenderer { + fn name(&self) -> &'static str { + "openai-chat-completions" + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + // OpenAI 线格式:纯文本 content 用字符串形式(部分兼容后端不接受 + // 无 type 的部件数组);多部件 content 按原样透传。 + let mut messages = Vec::with_capacity(request.messages.len()); + for m in &request.messages { + let content: serde_json::Value = match m.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + })?, + }; + messages.push(serde_json::json!({ + "role": m.role, + "content": content, + })); + } + + // 只写入确定性的结构字段;不写请求 ID/时间戳(缓存前缀保真)。 + let mut body = serde_json::json!({ + "model": request.model, + "messages": messages, + "max_tokens": request.output_limits.max_output_tokens, + "stream": request.stream, + }); + if !request.tools.is_empty() { + body["tools"] = serde_json::json!(request.tools); + } + if let Some(fields) = request.native_cache_fields.as_ref() { + merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + if let Some(plan) = cache_render_plan { + merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + + let bytes = serde_json::to_vec(&body) + .map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })? + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} + +/// 双格式渲染器:入口格式即上游格式(同格式进出,无跨格式转换)。 +#[derive(Debug, Clone, Copy)] +pub enum GatewayRenderer { + Chat(OpenAiChatRenderer), + Responses(OpenAiResponsesRenderer), +} + +impl Default for GatewayRenderer { + fn default() -> Self { + GatewayRenderer::Chat(OpenAiChatRenderer) + } +} + +impl WireRenderer for GatewayRenderer { + fn name(&self) -> &'static str { + match self { + GatewayRenderer::Chat(r) => r.name(), + GatewayRenderer::Responses(r) => r.name(), + } + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + match self { + GatewayRenderer::Chat(r) => r.render(request, cache_render_plan), + GatewayRenderer::Responses(r) => r.render(request, cache_render_plan), + } + } +} + +/// 只合并获准的顶层键;src 必须是对象。 +fn merge_top_level(dst: &mut serde_json::Value, src: &serde_json::Value) -> Result<(), ()> { + let src_obj = src.as_object().ok_or(())?; + let dst_obj = dst.as_object_mut().ok_or(())?; + for (k, v) in src_obj { + dst_obj.insert(k.clone(), v.clone()); + } + Ok(()) +} + +/// OpenAI Responses API 渲染器。 +/// +/// 同格式进出:客户端用 Responses 格式进来,上游也渲染为 Responses; +/// 不做 chat ↔ responses 的跨格式转换(保真优先)。 +/// content 里携带的 Responses 专有 item(function_call、function_call_output、 +/// item_reference、reasoning 等)按原样作为顶层 input item 透出。 +#[derive(Debug, Default, Clone, Copy)] +pub struct OpenAiResponsesRenderer; + +/// Responses API 的顶层 input item 类型(区别于消息内 content part 的 +/// input_text/output_text 等文本部件)。 +const RESPONSES_ITEM_TYPES: &[&str] = &[ + "message", + "function_call", + "function_call_output", + "custom_tool_call", + "custom_tool_call_output", + "item_reference", + "reasoning", + "web_search_call", + "file_search_call", + "computer_call", + "computer_call_output", + "image_generation_call", + "code_interpreter_call", + "mcp_call", + "mcp_list_tools", +]; + +fn is_responses_item(v: &serde_json::Value) -> bool { + v.get("type") + .and_then(|t| t.as_str()) + .map(|t| RESPONSES_ITEM_TYPES.contains(&t)) + .unwrap_or(false) +} + +impl WireRenderer for OpenAiResponsesRenderer { + fn name(&self) -> &'static str { + "openai-responses" + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + let mut input = Vec::with_capacity(request.messages.len()); + for msg in &request.messages { + // 单元素 content 且是 Responses 专有 item → 原样作为顶层 item。 + if msg.content.len() == 1 && is_responses_item(&msg.content[0]) { + input.push(msg.content[0].clone()); + continue; + } + let content: serde_json::Value = serde_json::to_value(&msg.content) + .map_err(|e| RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + })?; + input.push(serde_json::json!({ + "role": msg.role, + "content": content, + })); + } + + let mut body = serde_json::json!({ + "model": request.model, + "input": input, + "max_output_tokens": request.output_limits.max_output_tokens, + "stream": request.stream, + }); + if let Some(instructions) = &request.instructions { + body["instructions"] = serde_json::json!(instructions); + } + if !request.tools.is_empty() { + body["tools"] = serde_json::json!(request.tools); + } + if let Some(fields) = request.native_cache_fields.as_ref() { + merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + if let Some(plan) = cache_render_plan { + merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + + let bytes = serde_json::to_vec(&body) + .map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })? + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} diff --git a/gateway/crates/pc-gateway-protocol/src/sse.rs b/gateway/crates/pc-gateway-protocol/src/sse.rs new file mode 100644 index 0000000000..9ea5bcc5a6 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/sse.rs @@ -0,0 +1,73 @@ +//! SSE 解析。 +//! +//! RFC 约束:strict 模式在完整 output/check 之后才组帧, +//! 因此网关 v1 对上游流是全量缓冲单元,不做增量放行; +//! bounded streaming 是后续独立提案。 + +use bytes::Bytes; + +/// 缓冲中的一个原始事件(不解释语义;语义归 output/check 与调用方)。 +#[derive(Debug, Clone)] +pub struct RawSseEvent { + pub event: Option, + pub data: Bytes, +} + +/// 增量解析器:从上游字节流切出原始 SSE 事件。 +/// 只做切帧,不做内容检查——检查的是完整单元。 +#[derive(Default)] +pub struct SseFramer { + buf: Vec, +} + +impl SseFramer { + pub fn push(&mut self, chunk: &[u8]) { + self.buf.extend_from_slice(chunk); + } + + /// 取出所有完整事件(以空行分隔)。 + pub fn take_events(&mut self) -> Vec { + let mut events = Vec::new(); + while let Some(pos) = find_blank_line(&self.buf) { + let block: Vec = self.buf.drain(..pos).collect(); + self.buf.drain(..2); // CRLF/LF 分隔符 + if let Some(ev) = parse_block(&block) { + events.push(ev); + } + } + events + } + + /// 结束流时收尾(缓冲中残余的最后一个块)。 + pub fn finish(&mut self) -> Vec { + let rest = std::mem::take(&mut self.buf); + match parse_block(&rest) { + Some(ev) => vec![ev], + None => Vec::new(), + } + } +} + +fn find_blank_line(buf: &[u8]) -> Option { + buf.windows(2).position(|w| w == b"\n\n" || w == b"\r\n") +} + +fn parse_block(block: &[u8]) -> Option { + let text = String::from_utf8_lossy(block); + let mut event = None; + let mut data_lines = Vec::new(); + for line in text.lines() { + if let Some(v) = line.strip_prefix("event:") { + event = Some(v.trim().to_string()); + } else if let Some(v) = line.strip_prefix("data:") { + data_lines.push(v.strip_prefix(' ').unwrap_or(v)); + } + } + if data_lines.is_empty() { + return None; + } + Some(RawSseEvent { + event, + data: Bytes::from(data_lines.join("\n")), + }) +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs new file mode 100644 index 0000000000..a01a73ff1d --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -0,0 +1,60 @@ +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OpenAiChatRenderer, OutputLimits, Role, WireRenderer, +}; + +fn request() -> CanonicalRequest { + CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 16, + }, + stream: false, + } +} + +#[test] +fn renders_deterministic_base_body() { + let p = OpenAiChatRenderer.render(&request(), None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["model"], "m"); + assert_eq!(v["stream"], false); + assert_eq!(v["max_tokens"], 16); + // 缓存前缀保真:不注入请求 ID/时间戳类字段。 + assert!(v.get("request_id").is_none()); + assert!(v.get("timestamp").is_none()); +} + +#[test] +fn merges_only_approved_cache_plan_fields() { + let plan = serde_json::json!({"cache_control": {"type": "ephemeral"}}); + let p = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["cache_control"]["type"], "ephemeral"); + assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); +} + +#[test] +fn non_object_plan_rejected() { + let plan = serde_json::json!(["not", "an", "object"]); + let err = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap_err(); + assert!(matches!( + err, + pc_gateway_protocol::RenderError::InvalidRenderPlan { .. } + )); +} + +#[test] +fn stream_flag_reaches_wire_format() { + let mut req = request(); + req.stream = true; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["stream"], true, "stream 标志必须原样到达线格式"); +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs new file mode 100644 index 0000000000..4aa5f41792 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -0,0 +1,75 @@ +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OpenAiResponsesRenderer, OutputLimits, Role, + WireRenderer, +}; + +fn request() -> CanonicalRequest { + CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + }], + tools: vec![], + instructions: Some("be terse".into()), + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 16, + }, + stream: false, + } +} + +#[test] +fn renders_responses_wire_format() { + let p = OpenAiResponsesRenderer.render(&request(), None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["model"], "m"); + assert_eq!(v["instructions"], "be terse"); + assert_eq!(v["max_output_tokens"], 16); + assert_eq!(v["stream"], false); + assert_eq!(v["input"][0]["role"], "user"); + assert!(v.get("messages").is_none(), "不得混入 chat 字段"); + assert!(v.get("max_tokens").is_none()); +} + +#[test] +fn responses_items_pass_through_verbatim() { + let fc = serde_json::json!({ + "type": "function_call", "call_id": "c1", "name": "search", "arguments": "{}" + }); + let req = CanonicalRequest { + model: "m".into(), + messages: vec![ + CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + }, + // 无 role 的顶层 item:原样封进 content,渲染时作为顶层 item 透出 + CanonicalMessage { + role: Role::Tool, + content: vec![fc.clone()], + }, + ], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 16, + }, + stream: false, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["input"].as_array().unwrap().len(), 2); + assert_eq!(v["input"][1], fc, "Responses 专有 item 必须字节级透传"); +} + +#[test] +fn merges_only_approved_cache_plan_fields() { + let plan = serde_json::json!({"prompt_cache_key": "scope-1"}); + let p = OpenAiResponsesRenderer.render(&request(), Some(&plan)).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["prompt_cache_key"], "scope-1"); + assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); +} diff --git a/gateway/crates/pc-gateway-transport/Cargo.toml b/gateway/crates/pc-gateway-transport/Cargo.toml new file mode 100644 index 0000000000..a674b39923 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "pc-gateway-transport" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: transport — send admitted bytes, cancel, bounded retry with single owner" + +[dependencies] +pc-gateway-types = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +futures-core = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +reqwest = { workspace = true } diff --git a/gateway/crates/pc-gateway-transport/src/lib.rs b/gateway/crates/pc-gateway-transport/src/lib.rs new file mode 100644 index 0000000000..8cfd5154c7 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/lib.rs @@ -0,0 +1,15 @@ +//! 传输层:发送获准字节、取消、归属明确的有界重试。 +//! +//! RFC 失败语义: +//! - 准入后正文/目标/设置变化 → 重新准入后才能发送; +//! - 确定性未送达 → 唯一所有者在有效准入和有界次数内重试; +//! - 可能已送达 → 返回不确定,不自动付费重发; +//! - 未 admission 的字节绝不出网。 + +mod reqwest_transport; +mod retry; +mod sender; + +pub use reqwest_transport::*; +pub use retry::*; +pub use sender::*; diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs new file mode 100644 index 0000000000..659d828c3f --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -0,0 +1,164 @@ +use crate::sender::{ + AdmittedSend, NotSentReason, RawResponse, SendIndeterminateReason, SendOutcome, Transport, +}; +use bytes::Bytes; +use std::future::Future; +use std::time::{Duration, Instant}; + +/// 基于 reqwest 的传输实现:裸 HTTP 直连上游,不经任何厂商 SDK。 +/// +/// 结果映射(对齐 RFC 失败语义): +/// - 连接失败/请求构造失败 → 确定性 NotSent(可重试); +/// - 发送后连接丢失、超时、解码中断 → Indeterminate(不自动重发); +/// - 流式接收:逐块读入(计量 TTFT、字节数受 `max_buffer_bytes` 上限), +/// strict 语义不变——完整缓冲后仍需过 before_release 才释放。 +#[derive(Debug, Clone)] +pub struct ReqwestTransport { + client: reqwest::Client, + /// 流式/非流式响应的缓冲字节上限(容量保护)。 + max_buffer_bytes: usize, +} + +impl ReqwestTransport { + pub fn new(timeout: Duration) -> Self { + let client = reqwest::Client::builder() + .timeout(timeout) + .build() + .expect("reqwest client build"); + Self { + client, + max_buffer_bytes: 32 * 1024 * 1024, + } + } + + pub fn with_buffer_limit(mut self, max_buffer_bytes: usize) -> Self { + self.max_buffer_bytes = max_buffer_bytes; + self + } +} + +impl Default for ReqwestTransport { + fn default() -> Self { + Self::new(Duration::from_secs(120)) + } +} + +impl Transport for ReqwestTransport { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a { + Box::pin(async move { + let mut req = self.client.post(&send.target_url); + let mut has_content_type = false; + for (k, v) in &send.headers { + if k.eq_ignore_ascii_case("content-type") { + has_content_type = true; + } + req = req.header(k, v); + } + if !has_content_type { + req = req.header("content-type", "application/json"); + } + let resp = match req.body(send.payload.to_vec()).send().await { + Err(e) => { + return if e.is_connect() { + SendOutcome::NotSent(NotSentReason::ConnectRefused) + } else if e.is_builder() || e.is_request() { + SendOutcome::NotSent(NotSentReason::RejectedLocally) + } else if e.is_timeout() { + // 请求可能已被上游接收:不能当作未送达重试。 + SendOutcome::Indeterminate(SendIndeterminateReason::TimeoutAwaitingResponse) + } else { + SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) + } + } + Ok(resp) => resp, + }; + let status = resp.status().as_u16(); + let content_type = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/json") + .to_string(); + + if send.stream { + // 流式接收:逐块累积 + TTFT 计量 + 字节上限。 + let start = Instant::now(); + let mut body: Vec = Vec::with_capacity(16 * 1024); + let mut ttft: Option = None; + let mut stream = resp.bytes_stream(); + loop { + match next_chunk(&mut stream).await { + None => break, + Some(Err(_)) => { + return SendOutcome::Indeterminate( + SendIndeterminateReason::LostAfterHandoff, + ) + } + Some(Ok(chunk)) => { + if ttft.is_none() { + ttft = Some(start.elapsed().as_millis() as u64); + } + if body.len() + chunk.len() > self.max_buffer_bytes { + // 已送达且部分计费:不重发,向上标记不确定。 + return SendOutcome::Indeterminate( + SendIndeterminateReason::BufferLimitExceeded, + ); + } + body.extend_from_slice(&chunk); + } + } + } + let usage = extract_usage(&body); + SendOutcome::Delivered(RawResponse { + status, + body: Bytes::from(body), + content_type, + ttft_ms: ttft, + usage, + }) + } else { + match resp.bytes().await { + Err(_) => { + SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) + } + Ok(body) => { + let usage = extract_usage(&body); + SendOutcome::Delivered(RawResponse { + status, + body: Bytes::from(body), + content_type, + ttft_ms: None, + usage, + }) + } + } + } + }) + } + + fn cancel<'a>(&'a self, _send: &'a AdmittedSend) -> impl Future + Send + 'a { + // 非流式/全量缓冲调用在响应完整返回后已无进行中的上游工作; + // 放弃响应体即断开连接(连接池按目标隔离)。 + async {} + } +} + +fn extract_usage(body: &[u8]) -> Option { + serde_json::from_slice::(body) + .ok() + .and_then(|v| v.get("usage").cloned()) +} + +/// 不引入 futures-util 依赖的 next():用标准库 poll_fn 轮询 Stream。 +async fn next_chunk(stream: &mut S) -> Option> +where + S: futures_core::Stream> + Unpin, +{ + use std::pin::Pin; + std::future::poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)) + .await + .map(|r| r.map_err(|e| e.to_string())) +} diff --git a/gateway/crates/pc-gateway-transport/src/retry.rs b/gateway/crates/pc-gateway-transport/src/retry.rs new file mode 100644 index 0000000000..c853f01565 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/retry.rs @@ -0,0 +1,54 @@ +use crate::{AdmittedSend, SendOutcome, Transport}; +use pc_gateway_evidence::EvidenceSink; +use std::num::NonZeroU32; + +/// 有界重试:唯一所有者、有效准入、有界次数。 +/// 只重试确定性 `NotSent`;`Indeterminate` 一律上抛,绝不自动付费重发。 +pub struct BoundedRetry { + transport: T, + max_attempts: NonZeroU32, +} + +/// 重试的结果:`Ok` 携带原始 `SendOutcome`; +/// `Err` 表示全部尝试都确定性未送达。 +pub enum RetryOutcome { + Done(SendOutcome), + AllNotSent { attempts: u32 }, +} + +impl BoundedRetry { + pub fn new(transport: T, max_attempts: NonZeroU32) -> Self { + Self { + transport, + max_attempts, + } + } + + pub fn transport(&self) -> &T { + &self.transport + } + + pub async fn send_with_retry( + &self, + send: &AdmittedSend, + evidence: &dyn EvidenceSink, + ) -> RetryOutcome { + let mut attempt: u32 = 0; + loop { + attempt += 1; + evidence.record_attempt(attempt); + match self.transport.send(send.clone()).await { + // 可能已送达:立即上抛,不做任何自动重发。 + outcome @ SendOutcome::Indeterminate(_) + | outcome @ SendOutcome::Delivered(_) => return RetryOutcome::Done(outcome), + SendOutcome::NotSent(reason) => { + if attempt >= self.max_attempts.get() { + evidence.record_not_sent(attempt, &reason.to_string()); + return RetryOutcome::AllNotSent { attempts: attempt }; + } + // 确定性未送达:唯一所有者继续重试。 + } + } + } + } +} diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs new file mode 100644 index 0000000000..6d6b7d9e05 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -0,0 +1,71 @@ +use bytes::Bytes; +use std::future::Future; + +/// 一次已获准的发送。 +#[derive(Debug, Clone)] +pub struct AdmittedSend { + /// before_send allow 返回的不透明绑定字符串;必须原样用于 before_release。 + pub binding: String, + /// 最终获准字节(渲染产物,binding 绑定的就是这些字节)。 + pub payload: Bytes, + /// 获准目标 URL;不得静默重映射。 + pub target_url: String, + /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 + pub headers: Vec<(String, String)>, + /// 上游流式(SSE)接收:逐块读入并计量,strict 语义不变。 + pub stream: bool, +} + +/// 原始响应 + 传输结果,交给 output/check 后才允许释放。 +#[derive(Debug)] +pub struct RawResponse { + pub status: u16, + pub body: Bytes, + /// 响应的 Content-Type(SSE 为 text/event-stream),释放时原样使用。 + pub content_type: String, + /// 上游首字节延迟(毫秒);流式接收时计量,非流式为 None。 + pub ttft_ms: Option, + /// usage 证据(不可用时为 None,标记 unknown,不记零)。 + pub usage: Option, +} + +/// 发送结果:确定性状态优先;不确定即不确定。 +#[derive(Debug)] +pub enum SendOutcome { + /// 成功取得完整原始响应(尚未过 output/check,不得释放)。 + Delivered(RawResponse), + /// 确定尚未送达:可在有界次数内由唯一所有者重试。 + NotSent(NotSentReason), + /// 可能已到达上游:返回不确定,不自动付费重发,不假设退费。 + Indeterminate(SendIndeterminateReason), +} + +#[derive(Debug, thiserror::Error)] +pub enum NotSentReason { + #[error("connection refused before request sent")] + ConnectRefused, + #[error("request rejected before body accepted")] + RejectedLocally, +} + +#[derive(Debug, thiserror::Error)] +pub enum SendIndeterminateReason { + #[error("connection lost after request handed to transport")] + LostAfterHandoff, + #[error("timeout awaiting response")] + TimeoutAwaitingResponse, + /// 流式接收超过缓冲上限:请求已送达且部分计费,不重发。 + #[error("streaming buffer limit exceeded")] + BufferLimitExceeded, +} + +/// 传输器抽象;实现保证只发送 `AdmittedSend`(类型上无法构造未准入的发送)。 +pub trait Transport: Send + Sync { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a; + + /// 尽力取消上游(strict 检查失败/缓冲超限时必需)。 + fn cancel<'a>(&'a self, send: &'a AdmittedSend) -> impl Future + Send + 'a; +} diff --git a/gateway/crates/pc-gateway-types/Cargo.toml b/gateway/crates/pc-gateway-types/Cargo.toml new file mode 100644 index 0000000000..81a977a81f --- /dev/null +++ b/gateway/crates/pc-gateway-types/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "pc-gateway-types" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: check API DTOs, envelope bindings and shared value types" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +bytes = { workspace = true } +thiserror = { workspace = true } diff --git a/gateway/crates/pc-gateway-types/src/check.rs b/gateway/crates/pc-gateway-types/src/check.rs new file mode 100644 index 0000000000..0b3f11bf80 --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/check.rs @@ -0,0 +1,137 @@ +//! PR #2264 定义的 `POST /v1/context/check` 真实契约。 +//! +//! 关键语义(openapi/powercontext.yaml 原文): +//! - HTTP success alone is not approval——只有完整覆盖的 allow 才许可对应阶段; +//! - 执行器必须在 deadline(valid_until / limits.send_seconds)前 +//! 发送/释放**恰好获批的字节**; +//! - binding 是不透明字符串,绑定 phase、身份、目标、策略与精确载荷; +//! - correlate_until 只是关联窗口,绝不许可新的发送。 + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const MODEL_JSON_PAYLOAD_SCHEMA: &str = "powercontext.model-json-payload.v1"; +pub const CONTEXT_CHECK_SCHEMA: &str = "powercontext.context-check.v1"; +pub const CONTEXT_CHECK_COMPLETION: &str = "complete"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckPhase { + BeforeSend, + BeforeRelease, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckDecision { + Allow, + Block, + Withhold, +} + +/// 完整载荷信封:仅内容与协议头(凭据、传输覆盖头被禁止),body 为完整原始 JSON 文本。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelJsonPayload { + pub schema: String, + pub headers: BTreeMap, + pub body: String, +} + +impl ModelJsonPayload { + pub fn new(headers: BTreeMap, body: String) -> Self { + Self { + schema: MODEL_JSON_PAYLOAD_SCHEMA.into(), + headers, + body, + } + } +} + +/// prepare 复用信封的定位(binding + 文本位置;位置语义归 Core)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedContextLocation { + pub binding: String, + pub location: ModelJsonTextLocation, +} + +/// 线格式 JSON 指针 + 解码后 UTF-8 文本的半开字节区间。 +/// 指针形如 /messages/{i}/content 或 /messages/{i}/content/{j}/text, +/// 必须指向 user 消息(PC 的 _message_text 强制校验)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelJsonTextLocation { + pub schema: String, + pub pointer: String, + pub start_byte: u64, + pub end_byte: u64, +} + +pub const MODEL_JSON_TEXT_LOCATION_SCHEMA: &str = "powercontext.model-json-text-location.v1"; + +/// `check_context` 请求:按 phase 二选一(内部标签即 phase 字段)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "phase", rename_all = "snake_case")] +pub enum ContextCheckRequest { + BeforeSend { + scope_id: String, + target_profile: String, + payload: ModelJsonPayload, + /// 线格式必填:无复用块时也必须显式携带空数组。 + prepared_contexts: Vec, + }, + BeforeRelease { + scope_id: String, + target_profile: String, + /// 对应 before_send allow 返回的 binding。 + request_binding: String, + payload: ModelJsonPayload, + completion: String, + }, +} + +/// `check_context` 响应。两阶段共用 allow/block/withhold: +/// before_release 的 allow 即放行决定,block 即拒绝释放。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextCheckResult { + pub schema: String, + pub phase: CheckPhase, + pub decision: CheckDecision, + /// 无正文原因类别。 + pub reason_codes: Vec, + pub coverage: ContextCheckCoverage, + pub policy_version: String, + /// RFC3339 时间;发送/释放必须在此之前完成。 + pub valid_until: String, + /// 仅 before_send allow 有;绝不许可新发送。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub correlate_until: Option, + /// 仅 allow 有:不透明绑定字符串。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub binding: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextCheckCoverage { + pub profile: String, + pub complete: bool, +} + +/// ContextProtectionCapabilities(能力发现;enforcing 是动态降级的依据)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextProtectionCapabilities { + pub check_versions: Vec, + pub payload_versions: Vec, + pub reuse_versions: Vec, + pub reuse_families: Vec, + pub enforcing: bool, + pub limits: ContextProtectionLimits, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextProtectionLimits { + pub payload_bytes: u64, + pub binding_bytes: u64, + pub prepared_contexts: u64, + pub dependencies: u64, + pub send_seconds: u64, + pub correlate_seconds: u64, +} diff --git a/gateway/crates/pc-gateway-types/src/lib.rs b/gateway/crates/pc-gateway-types/src/lib.rs new file mode 100644 index 0000000000..ff69efb703 --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/lib.rs @@ -0,0 +1,10 @@ +//! PR #2264 契约值类型。 +//! +//! 网关无策略:这里的类型只承载 Core 的输入/输出, +//! 与 openapi/powercontext.yaml 对齐。 + +mod check; +mod prepare; + +pub use check::*; +pub use prepare::*; diff --git a/gateway/crates/pc-gateway-types/src/prepare.rs b/gateway/crates/pc-gateway-types/src/prepare.rs new file mode 100644 index 0000000000..d6f2b9cdb7 --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/prepare.rs @@ -0,0 +1,99 @@ +//! prepare 契约(PR #2264),字段形状对照真实响应校准。 + +use serde::{Deserialize, Serialize}; + +/// 注入块的标准包裹标记(与 PC 的 `_MARKERS` 对齐): +/// check 会扫描载荷中所有字符串,含标记的字节必须被 prepared_contexts 区间覆盖。 +pub const PREPARED_CONTEXT_MARKER_BEGIN: &str = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"; +pub const PREPARED_CONTEXT_MARKER_END: &str = "END_POWERCONTEXT_PREPARED_CONTEXT_V1"; + +pub const PREPARED_CONTEXT_SCHEMA: &str = "powercontext.prepared-context.v1"; +pub const PREPARED_CONTEXT_WITH_REUSE_SCHEMA: &str = "powercontext.prepared-context-with-reuse.v1"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PrepareContextRequest { + pub scope_id: String, + pub query: String, + #[serde(default = "default_max_bytes")] + pub max_bytes: u32, + #[serde(default)] + pub include_reuse: bool, +} + +fn default_max_bytes() -> u32 { + 8192 +} + +/// prepare 响应:普通 PreparedContext 或带复用信封的 WithReuse(按 schema 判别)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PrepareContextResult { + WithReuse { + schema: String, + context: PreparedContext, + reuse: ContextReuse, + }, + Plain(PreparedContext), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedContext { + pub schema: String, + /// ready 时为内容文本;empty 时为 None。 + pub status: String, + pub content: Option, + pub content_bytes: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextReuse { + pub schema: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub constraints: Option, + /// RFC3339。 + pub expires_at: String, + pub binding: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ReuseConstraints { + #[serde(default)] + pub preserve: Vec, + #[serde(default)] + pub refresh_on: Vec, +} + +impl PrepareContextResult { + pub fn content(&self) -> Option<&str> { + match self { + PrepareContextResult::WithReuse { context, .. } => context.content.as_deref(), + PrepareContextResult::Plain(c) => c.content.as_deref(), + } + } + + pub fn binding(&self) -> Option<&str> { + match self { + PrepareContextResult::WithReuse { reuse, .. } => Some(&reuse.binding), + PrepareContextResult::Plain(_) => None, + } + } +} + +/// 标准注入块:与 PC 的 `_MARKERS`/摘要校验对齐。 +/// check 会核验区间内字节与 binding 签发内容一致,不得增删一字节。 +pub fn wrap_prepared_block(content: &str) -> String { + format!("{PREPARED_CONTEXT_MARKER_BEGIN}\n{content}\n{PREPARED_CONTEXT_MARKER_END}") +} + +/// `POST /v1/sources/content`(capture_content_source): +/// 同步持久入库(Source journal),提取由 PC 后台异步完成。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CaptureContentSourceRequest { + pub scope_id: String, + /// 调用方指定的稳定 ID(幂等键):用 release binding 摘要生成。 + pub source_id: String, + /// 原始整合内容(≤200000 字符)。仅沉淀过检放行的内容。 + pub content: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} From 153b8b63e66938c6c2ac9f971c44300a4398ad02 Mon Sep 17 00:00:00 2001 From: ztelur Date: Fri, 30 Oct 2026 01:26:12 +0800 Subject: [PATCH 02/37] =?UTF-8?q?style(gateway):=20clippy=20clean=20?= =?UTF-8?q?=E2=80=94=20desugar=20impl-Future=20wrappers=20to=20async=20fn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trait declarations keep RPITIT with explicit Send bounds (public API); implementations use async fn per clippy. Also fixes redundant closures, needless as_bytes, useless conversion, unused imports, and simplifies FakeGate test doubles. cargo clippy --all-targets: zero warnings; 27 tests pass. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/link.rs | 47 ++++++--------- .../crates/pc-gateway-core/src/executor.rs | 4 +- .../pc-gateway-core/src/http_gate_client.rs | 59 +++++++++---------- .../pc-gateway-core/src/uds_gate_client.rs | 25 ++++---- .../tests/executor_semantics.rs | 21 +++---- .../tests/live_context_check.rs | 2 +- .../crates/pc-gateway-core/tests/uds_pool.rs | 5 +- .../src/reqwest_transport.rs | 4 +- .../crates/pc-gateway-transport/src/sender.rs | 1 + 9 files changed, 74 insertions(+), 94 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/link.rs b/gateway/crates/pc-gateway-app/src/link.rs index 084bb724c1..752d2ba468 100644 --- a/gateway/crates/pc-gateway-app/src/link.rs +++ b/gateway/crates/pc-gateway-app/src/link.rs @@ -5,7 +5,6 @@ use pc_gateway_types::{ CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, PrepareContextResult, }; -use std::future::Future; pub enum CoreLink { Uds(UdsGateClient), @@ -27,48 +26,40 @@ impl CoreLink { } impl GateClient for CoreLink { - fn check( + async fn check( &self, request: ContextCheckRequest, - ) -> impl Future> + Send { - async move { - match self { - CoreLink::Uds(c) => c.check(request).await, - CoreLink::Http(c) => c.check(request).await, - } + ) -> Result { + match self { + CoreLink::Uds(c) => c.check(request).await, + CoreLink::Http(c) => c.check(request).await, } } - fn capabilities(&self) -> impl Future> + Send { - async move { - match self { - CoreLink::Uds(c) => c.capabilities().await, - CoreLink::Http(c) => c.capabilities().await, - } + async fn capabilities(&self) -> Result { + match self { + CoreLink::Uds(c) => c.capabilities().await, + CoreLink::Http(c) => c.capabilities().await, } } - fn prepare( + async fn prepare( &self, request: PrepareContextRequest, - ) -> impl Future> + Send { - async move { - match self { - CoreLink::Uds(c) => c.prepare(request).await, - CoreLink::Http(c) => c.prepare(request).await, - } + ) -> Result { + match self { + CoreLink::Uds(c) => c.prepare(request).await, + CoreLink::Http(c) => c.prepare(request).await, } } - fn capture( + async fn capture( &self, request: CaptureContentSourceRequest, - ) -> impl Future> + Send { - async move { - match self { - CoreLink::Uds(c) => c.capture(request).await, - CoreLink::Http(c) => c.capture(request).await, - } + ) -> Result { + match self { + CoreLink::Uds(c) => c.capture(request).await, + CoreLink::Http(c) => c.capture(request).await, } } } diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 34d3cfeb72..549ac389e3 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -191,7 +191,7 @@ where "model": call.request.model, }); let digest = result.binding.as_deref() - .map(|b| simple_digest(b)) + .map(simple_digest) .unwrap_or_else(|| simple_digest(&String::from_utf8_lossy(&raw.body))); let capture = CaptureContentSourceRequest { scope_id: call.scope_id.clone(), @@ -276,7 +276,7 @@ where pointer: format!("/messages/{index}/content"), start_byte: 0, // UTF-8 字节数(非字符数);区间必须落在字符边界(块整体是合法 UTF-8,天然满足)。 - end_byte: block.as_bytes().len() as u64, + end_byte: block.len() as u64, }, }); } diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs index 846086d895..1467c67f69 100644 --- a/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -5,7 +5,6 @@ use pc_gateway_types::{ }; use serde::de::DeserializeOwned; use serde::Serialize; -use std::future::Future; /// 独立部署形态:HTTPS/TCP 直连 PowerContext Server 的公开契约。 /// 同机组合部署用 `UdsGateClient`(HTTP over Unix Domain Socket)。 @@ -62,49 +61,45 @@ impl HttpGateClient { } impl GateClient for HttpGateClient { - fn check( + async fn check( &self, request: ContextCheckRequest, - ) -> impl Future> + Send { - async move { self.post("/v1/context/check", &request).await } + ) -> Result { + self.post("/v1/context/check", &request).await } - fn capabilities( - &self, - ) -> impl Future> + Send { - async move { - let url = format!("{}/v1/capabilities", self.base_url); - let resp = self - .client - .get(&url) - .header("x-powercontext-scope-mode", "current") - .bearer_auth(self.token.clone().unwrap_or_default()) - .send() - .await - .map_err(|e| GateError::GateUnavailable(e.to_string()))?; - let status = resp.status(); - if !status.is_success() { - return Err(GateError::GateUnavailable(format!( - "capabilities HTTP {status}" - ))); - } - resp.json() - .await - .map_err(|e| GateError::Malformed(e.to_string())) + async fn capabilities(&self) -> Result { + let url = format!("{}/v1/capabilities", self.base_url); + let resp = self + .client + .get(&url) + .header("x-powercontext-scope-mode", "current") + .bearer_auth(self.token.clone().unwrap_or_default()) + .send() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + let status = resp.status(); + if !status.is_success() { + return Err(GateError::GateUnavailable(format!( + "capabilities HTTP {status}" + ))); } + resp.json() + .await + .map_err(|e| GateError::Malformed(e.to_string())) } - fn prepare( + async fn prepare( &self, request: PrepareContextRequest, - ) -> impl Future> + Send { - async move { self.post("/v1/context/prepare", &request).await } + ) -> Result { + self.post("/v1/context/prepare", &request).await } - fn capture( + async fn capture( &self, request: CaptureContentSourceRequest, - ) -> impl Future> + Send { - async move { self.post("/v1/sources/content", &request).await } + ) -> Result { + self.post("/v1/sources/content", &request).await } } diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index b843e01e67..ae3db61a42 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -12,7 +12,6 @@ use pc_gateway_types::{ CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, PrepareContextResult, }; -use std::future::Future; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -351,13 +350,13 @@ fn find_terminator(buf: &[u8]) -> Option { } impl GateClient for UdsGateClient { - fn check( + async fn check( &self, request: ContextCheckRequest, - ) -> impl Future> + Send { + ) -> Result { let body = serde_json::to_vec(&request).unwrap_or_default(); let this = self.clone(); - async move { + { let (status, body) = this.request("POST", "/v1/context/check", Some(&body)).await?; if !(200..300).contains(&status) { return Err(GateError::GateUnavailable(format!("gate HTTP {status}"))); @@ -367,11 +366,9 @@ impl GateClient for UdsGateClient { } } - fn capabilities( - &self, - ) -> impl Future> + Send { + async fn capabilities(&self) -> Result { let this = self.clone(); - async move { + { let (status, body) = this.request("GET", "/v1/capabilities", None).await?; if !(200..300).contains(&status) { return Err(GateError::GateUnavailable(format!("capabilities HTTP {status}"))); @@ -381,13 +378,13 @@ impl GateClient for UdsGateClient { } } - fn prepare( + async fn prepare( &self, request: PrepareContextRequest, - ) -> impl Future> + Send { + ) -> Result { let body = serde_json::to_vec(&request).unwrap_or_default(); let this = self.clone(); - async move { + { let (status, body) = this.request("POST", "/v1/context/prepare", Some(&body)).await?; if !(200..300).contains(&status) { return Err(GateError::GateUnavailable(format!("prepare HTTP {status}"))); @@ -397,13 +394,13 @@ impl GateClient for UdsGateClient { } } - fn capture( + async fn capture( &self, request: CaptureContentSourceRequest, - ) -> impl Future> + Send { + ) -> Result { let body = serde_json::to_vec(&request).unwrap_or_default(); let this = self.clone(); - async move { + { let (status, body) = this.request("POST", "/v1/sources/content", Some(&body)).await?; if !(200..300).contains(&status) { return Err(GateError::GateUnavailable(format!("capture HTTP {status}"))); diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 0f6c072103..436a4ffcfc 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -88,10 +88,8 @@ impl GateClient for FakeGate { async move { step.expect("gate script exhausted") } } - fn capabilities( - &self, - ) -> impl Future> + Send { - async move { Ok(serde_json::json!({ "enforcing": false })) } + async fn capabilities(&self) -> Result { + Ok(serde_json::json!({ "enforcing": false })) } fn prepare( @@ -109,12 +107,12 @@ impl GateClient for FakeGate { async move { step } } - fn capture( + async fn capture( &self, request: CaptureContentSourceRequest, - ) -> impl Future> + Send { + ) -> Result { self.captured.lock().unwrap().push((request.source_id, request.content)); - async move { Ok(serde_json::json!({"captured": true})) } + Ok(serde_json::json!({"captured": true})) } } @@ -138,9 +136,8 @@ impl Transport for FakeTransport { } } - fn cancel<'a>(&'a self, _send: &'a AdmittedSend) -> impl Future + Send + 'a { + async fn cancel(&self, _send: &AdmittedSend) { *self.cancels.lock().unwrap() += 1; - async {} } } @@ -222,8 +219,8 @@ impl Transport for TransportRef { ) -> impl Future + Send + 'a { Transport::send(&*self.0, send) } - fn cancel<'a>(&'a self, send: &'a AdmittedSend) -> impl Future + Send + 'a { - Transport::cancel(&*self.0, send) + async fn cancel(&self, send: &AdmittedSend) { + Transport::cancel(&*self.0, send).await } } @@ -559,7 +556,7 @@ async fn injects_block_and_declares_exact_location() { assert_eq!(loc.location.schema, "powercontext.model-json-text-location.v1"); assert_eq!(loc.location.start_byte, 0); let block = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1"; - assert_eq!(loc.location.end_byte as usize, block.as_bytes().len()); + assert_eq!(loc.location.end_byte as usize, block.len()); assert_eq!(transport.sends.lock().unwrap().len(), 1); } diff --git a/gateway/crates/pc-gateway-core/tests/live_context_check.rs b/gateway/crates/pc-gateway-core/tests/live_context_check.rs index 4f14c61d76..d373a63bec 100644 --- a/gateway/crates/pc-gateway-core/tests/live_context_check.rs +++ b/gateway/crates/pc-gateway-core/tests/live_context_check.rs @@ -103,7 +103,7 @@ async fn live_allow_returns_real_binding_and_deadlines() { // 期限分离:发送窗口 ~60s,关联窗口 ~300s。 let now = chrono_like_now(); let valid = parse_epoch_ms(&result.valid_until); - let correlate = result.correlate_until.as_deref().map(|s| parse_epoch_ms(s)); + let correlate = result.correlate_until.as_deref().map(parse_epoch_ms); assert!( valid > now && valid <= now + 65_000, "发送期限应在 60s 窗口内: valid={valid} now={now}" diff --git a/gateway/crates/pc-gateway-core/tests/uds_pool.rs b/gateway/crates/pc-gateway-core/tests/uds_pool.rs index 58f08645cc..c272c65c72 100644 --- a/gateway/crates/pc-gateway-core/tests/uds_pool.rs +++ b/gateway/crates/pc-gateway-core/tests/uds_pool.rs @@ -3,11 +3,10 @@ use pc_gateway_core::{GateClient, UdsGateClient}; use pc_gateway_types::{ - CheckDecision, CheckPhase, ContextCheckRequest, ContextCheckResult, ModelJsonPayload, + CheckDecision, CheckPhase, ContextCheckRequest, ModelJsonPayload, }; use std::collections::BTreeMap; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{UnixListener, UnixStream}; @@ -44,7 +43,7 @@ async fn read_request(conn: &mut UnixStream) { let head = String::from_utf8_lossy(&buf).to_string(); if let Some(len) = head .lines() - .find_map(|l| l.strip_prefix("Content-Length: ").map(|v| v.trim().parse::().ok()).flatten()) + .find_map(|l| l.strip_prefix("Content-Length: ").and_then(|v| v.trim().parse::().ok())) { let mut body = vec![0u8; len]; if len > 0 { diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index 659d828c3f..43f67a7ffb 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -128,7 +128,7 @@ impl Transport for ReqwestTransport { let usage = extract_usage(&body); SendOutcome::Delivered(RawResponse { status, - body: Bytes::from(body), + body, content_type, ttft_ms: None, usage, @@ -142,7 +142,7 @@ impl Transport for ReqwestTransport { fn cancel<'a>(&'a self, _send: &'a AdmittedSend) -> impl Future + Send + 'a { // 非流式/全量缓冲调用在响应完整返回后已无进行中的上游工作; // 放弃响应体即断开连接(连接池按目标隔离)。 - async {} + std::future::ready(()) } } diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs index 6d6b7d9e05..18854a36d7 100644 --- a/gateway/crates/pc-gateway-transport/src/sender.rs +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -67,5 +67,6 @@ pub trait Transport: Send + Sync { ) -> impl Future + Send + 'a; /// 尽力取消上游(strict 检查失败/缓冲超限时必需)。 + /// RPITIT 声明以固化 Send 约束(trait 是公开 API)。 fn cancel<'a>(&'a self, send: &'a AdmittedSend) -> impl Future + Send + 'a; } From 9ffe01873b61c487ff86815c947e04e8429fba4d Mon Sep 17 00:00:00 2001 From: ztelur Date: Fri, 30 Oct 2026 01:29:53 +0800 Subject: [PATCH 03/37] docs(gateway): document features and the PC UDS call sequence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the per-request feature set (gates, injection, sedimentation, degradation, streaming, middleware) and the five-step UDS call sequence (prepare → check before_send → send → check before_release → capture) to the gateway README. Signed-off-by: ztelur --- gateway/README.md | 68 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 10 deletions(-) diff --git a/gateway/README.md b/gateway/README.md index ca637d3d9e..13c2c3fcda 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -2,16 +2,63 @@ An optional Rust executor for PowerContext, defined by the gateway design in #2199 and the context-protection contract in #2264. The gateway owns the model traffic boundary; every decision stays in PowerContext Core ("no policy in the gateway"). -> Status: working prototype, verified end-to-end against a real PowerContext Server (PR #2264 branch) with real upstream providers. Depends on the `/v1/context/check` contract and `include_reuse` from #2264. +> Status: working prototype, verified end-to-end against a real PowerContext Server (PR #2264 branch) with real upstream providers (GLM, DeepSeek). Depends on the `/v1/context/check` contract and `include_reuse` from #2264. -## What it does +## Features -- **Two-phase gate executor**: `check(before_send)` → send admitted bytes → `check(before_release)` → release. Opaque bindings thread the two phases; unknown never becomes allow; deterministic non-delivery retries are bounded, indeterminate sends are never auto-retried. -- **Memory injection**: per user message, calls `prepare` (`include_reuse`), injects the returned prepared context verbatim into the current user message, and declares the exact UTF-8 byte range (`prepared_contexts`) for Core-side digest verification. -- **Sedimentation**: after a released turn, synchronously captures the transcript via `capture_content_source` (idempotent `source_id` derived from the release binding). Blocked or degraded turns are never captured. -- **Deployment forms**: combined (Rust owns the public TCP port, Core listens on a private Unix socket only; all non-`/gateway` routes are reverse-proxied to Core over UDS) or standalone (TCP, remote Core). -- **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), with streaming ingestion (strict buffering before release). -- **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (body size + concurrency) and request-id propagation. +### Model traffic pipeline (per request) + +- **Two-phase gate executor**: `check(before_send)` → send admitted bytes → `check(before_release)` → release. Opaque bindings thread the two phases (`request_binding` must be the send-phase binding). HTTP success alone is never treated as approval; unknown never becomes allow. +- **Privacy enforcement by Core, executed by the gateway**: forbidden content is blocked before any byte leaves the gateway (zero-send on block/withhold, zero-release on refuse, upstream cancel on refusal). +- **Deterministic-failure-only bounded retry**: connection-refused style failures retry a bounded number of times with a single owner; indeterminate outcomes (timeout after hand-off) are surfaced as `send_indeterminate` and never auto-retried (no paid re-sends). +- **Degradation policy**: when Core is unreachable, either pause (default) or pass through without memory (`PC_GATEWAY_DEGRADE=passthrough`) — degraded responses are explicitly marked (`x-pc-degraded` header). Blocked verdicts never degrade. +- **Streaming ingestion** (`stream: true`): upstream SSE is received incrementally (TTFT measured, byte-capped); strict semantics hold — the complete raw response is buffered and must pass `before_release` before anything is released to the client. (The current public carrier in #2264 withholds streaming payloads; the pipeline is ready for when the contract allows it.) +- **Status-code fidelity**: upstream errors pass through with their original status code (a provider 402/400 is never masked as 200), and `Content-Type` is preserved. + +### Memory features (#2199 capabilities) + +- **Auto-recall injection**: for each new user message the gateway calls `prepare` with `include_reuse`, and injects the returned prepared context **verbatim** into the current user message. The exact UTF-8 byte range is declared in `prepared_contexts` (`ModelJsonTextLocation`); Core verifies the digest of the declared range against the signed reuse binding — a single byte changed by the gateway is rejected. Empty or failed prepares inject nothing and never block the main path. Injection is tail-only (current message), so the client-owned history prefix stays byte-stable (KV prefix-cache friendly, verified with DeepSeek `cached_tokens`). +- **Sedimentation**: after a released turn, the gateway synchronously captures the transcript via `capture_content_source` (millisecond-scale durable write; extraction happens later in PC background workers). `source_id` is idempotent (derived from the release binding digest). Blocked and degraded turns are never captured. The full loop — conversation → capture → background extraction into Atomic Memory → `prepare` recall in a *new* session — has been verified end-to-end. + +### Deployment & ops + +- **Two deployment forms**: *combined* (Rust owns the public TCP port; Core listens only on a private Unix socket; all non-`/gateway` routes are reverse-proxied to Core over UDS) or *standalone* (TCP to a remote Core). +- **UDS client**: hand-rolled HTTP/1.1 over the Unix socket with a pooled, keep-alive connection pool (bounded idle set, connect/read timeouts, stale-connection single retry, content-length truncation and chunked-trailer consumption — covered by a real-socket regression test). +- **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), authenticated by a gateway key that replaces provider keys. +- **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (request-body precheck + concurrency semaphore, health probe exempt) and request-id propagation (`x-powercontext-request-id`, client-supplied or generated, echoed on responses). +- **Body-free evidence**: usage completeness (known/estimated/unknown), cache tokens, TTFT vs first-release latency, attempt counters — never request/response bodies. + +## PC call sequence over UDS + +All gateway→Core calls go through one `GateClient` (UDS in combined form, TCP in standalone form) and share the connection pool. For one chat request with injection and sedimentation enabled: + +``` +client ──POST /gateway/v1/chat/completions──▶ gateway (middleware: limits → request-id) + │ + 1. prepare gateway ──▶ POST /v1/context/prepare (query = last user message, + ◀── include_reuse=true) + content (trust preamble + marker block) + reuse binding (5 min) + — injected verbatim; byte range recorded; failure/empty ⇒ no injection + │ + 2. check gateway ──▶ POST /v1/context/check phase=before_send + (send gate) ◀── allow + send binding (60 s) | block/withhold ⇒ 403/409, zero send + │ + 3. send gateway ──▶ upstream provider (admitted bytes only; the single egress) + ◀── complete raw response (+ usage) + │ + 4. check gateway ──▶ POST /v1/context/check phase=before_release + (release (payload = complete raw response, request_binding = send binding) + gate) ◀── allow + release binding | refuse ⇒ cancel upstream, 403, + nothing released + │ + 5. capture gateway ──▶ POST /v1/sources/content (transcript JSON, + ◀── source_id = digest(release binding)) — released turns only; + failure is evidence-only + │ +client ◀── 200 (upstream status/content-type preserved, request-id echoed) ── gateway +``` + +Everything else (Core's 127 domain operations, MCP, dashboard) is reverse-proxied to Core over the same UDS socket, untouched by gateway logic. ## Layout @@ -40,11 +87,12 @@ PC_GATEWAY_UPSTREAM_API_KEY_CHAT=... \ # Optional: PC_GATEWAY_INJECTION=on (prepare + inject), PC_GATEWAY_SEDIMENT=on (capture after release), # PC_GATEWAY_DEGRADE=passthrough (no-memory passthrough when Core is unreachable; never applies -# to deployments with enforcing protection), PC_GATEWAY_MAX_CONCURRENT / PC_GATEWAY_MAX_BODY_BYTES. +# to deployments with enforcing protection), PC_GATEWAY_MAX_CONCURRENT / PC_GATEWAY_MAX_BODY_BYTES, +# PC_GATEWAY_CORE_TOKEN (bearer for Core when authentication is enabled). ``` Credentials live only in server-side environment variables; they are never accepted from request fields and never enter check payloads. ## Tests -`cargo test` — 27 tests covering the failure-semantics table (gate unavailable, withhold terminal, bounded retry, indeterminate no-resend, blocked turns never sediment), renderer fidelity (no timestamps/request ids injected), byte-range declaration, and UDS connection-pool correctness over a real Unix socket. +`cargo test` — 27 tests covering the failure-semantics table (gate unavailable, withhold terminal, bounded retry, indeterminate no-resend, blocked turns never sediment), renderer fidelity (no timestamps/request ids injected), byte-range declaration, UDS connection-pool correctness over a real Unix socket, and live integration tests against a real PowerContext Server (binding validity, cross-scope rejection, deadlines) that skip gracefully when no server is reachable. From 0572eca205e526588716198fa33c926164c36213 Mon Sep 17 00:00:00 2001 From: ztelur Date: Fri, 30 Oct 2026 01:41:41 +0800 Subject: [PATCH 04/37] fix(gateway): harden gate semantics from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Degrade (passthrough) now applies only to GateUnavailable; a Malformed gate response always pauses — a reachable-but-misbehaving Core must never be bypassed (fail-closed). Guarded by test. - Strict UTF-8 instead of lossy conversion in all three payload paths: invalid renderer output blocks before send; invalid upstream responses are withheld (never converted, never released); sediment reuses the validated text. Closes the check-payload vs sent-bytes fidelity gap. - serialize with expect (infallible, explicit) instead of silent empty body; default scope read once at startup instead of per request; extract read_with_timeout helper in the UDS client. Verified end-to-end against a real PowerContext Server over UDS with both DeepSeek and GLM upstreams: per turn exactly check x2, prepare x1, capture x1; forbidden content still blocked with zero sends. cargo clippy --all-targets: zero warnings; 29 tests. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 5 +- gateway/crates/pc-gateway-app/src/main.rs | 4 ++ .../crates/pc-gateway-core/src/executor.rs | 41 ++++++++++--- .../pc-gateway-core/src/uds_gate_client.rs | 58 ++++++++----------- .../tests/executor_semantics.rs | 49 ++++++++++++++++ 5 files changed, 111 insertions(+), 46 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index b459e5614d..d9576f6a14 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -12,9 +12,6 @@ use pc_gateway_protocol::{CanonicalMessage, CanonicalRequest, OutputLimits, Role use serde::Deserialize; use std::sync::Arc; -/// 网关密钥对应的默认 Scope(完整形态应从密钥解析出 Scope/profile 绑定)。 -const DEFAULT_SCOPE_ENV: &str = "PC_GATEWAY_DEFAULT_SCOPE"; - #[derive(Debug, Deserialize)] struct OpenAiChatRequest { model: String, @@ -153,7 +150,7 @@ async fn ingress_common( }; let call = ManagedCall { - scope_id: std::env::var(DEFAULT_SCOPE_ENV).unwrap_or_else(|_| "gateway:default".into()), + scope_id: state.default_scope.clone(), target_profile: state.upstream_profile.clone(), request: canonical, target_url: match format { diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 43c961a8cd..ea8a632535 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -43,6 +43,8 @@ pub struct AppState { pub inject_context: bool, /// 过检后同步沉淀对话(默认关)。 pub sediment: bool, + /// 默认 Scope(启动时读一次,避免热路径读环境变量)。 + pub default_scope: String, } #[tokio::main] @@ -99,6 +101,8 @@ async fn main() { degrade, inject_context: matches!(std::env::var("PC_GATEWAY_INJECTION").as_deref(), Ok("on")), sediment: matches!(std::env::var("PC_GATEWAY_SEDIMENT").as_deref(), Ok("on")), + default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") + .unwrap_or_else(|_| "gateway:default".into()), }); let router = Router::new() diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 549ac389e3..d06ab6a3f6 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -104,9 +104,19 @@ where } } }; + // 送检内容必须与发送字节严格一致:拒绝有损转换(防“检查≠发送”缝隙)。 + // 渲染器输出本应恒为合法 UTF-8,非法即契约违约,阻断而非降级。 + let payload_body = match String::from_utf8(payload.bytes.clone().to_vec()) { + Ok(text) => text, + Err(_) => { + return ManagedOutcome::Blocked { + reason_codes: vec!["invalid_payload_encoding".into()], + } + } + }; let model_payload = ModelJsonPayload::new( content_headers(&call.headers, payload.content_type), - String::from_utf8_lossy(&payload.bytes).into_owned(), + payload_body, ); let check = ContextCheckRequest::BeforeSend { @@ -118,11 +128,14 @@ where let binding = match self.gate.check(check).await { Err(e) => { - return match (classify_gate_error(e), call.degrade_policy) { - (_, DegradePolicy::PassthroughWithoutMemory) => { - self.degraded_send(&call, payload.bytes, evidence).await - } - (msg, DegradePolicy::Pause) => ManagedOutcome::GatePaused(msg), + // #2199 语义:降级仅适用于 Core「不可用」。Malformed 表示 Core 可达但 + // 响应异常(版本错乱/被篡改/代理污染)——恰恰最不该绕过检查,一律暂停。 + return match (e, call.degrade_policy) { + ( + GateError::GateUnavailable(_), + DegradePolicy::PassthroughWithoutMemory, + ) => self.degraded_send(&call, payload.bytes, evidence).await, + (e, _) => ManagedOutcome::GatePaused(classify_gate_error(e)), } } Ok(result) => match result.decision { @@ -161,6 +174,16 @@ where }; // strict:完整原始响应先过 before_release,通过前不释放任何内容。 + // 上游响应不受我们控制:非 UTF-8 字节不做有损转换送检(那会导致 + // “批准的是替换后文本、交付的是原始字节”的保真缺口),直接不放行。 + let release_body = match String::from_utf8(raw.body.clone().to_vec()) { + Ok(text) => text, + Err(_) => { + return ManagedOutcome::Withheld { + reason_codes: vec!["invalid_response_encoding".into()], + } + } + }; let release_check = ContextCheckRequest::BeforeRelease { scope_id: call.scope_id.clone(), target_profile: call.target_profile.clone(), @@ -168,7 +191,7 @@ where payload: ModelJsonPayload::new( // 契约要求 headers 至少 1 项;携带上游实际 Content-Type。 BTreeMap::from([("content-type".to_string(), raw.content_type.clone())]), - String::from_utf8_lossy(&raw.body).into_owned(), + release_body.clone(), ), completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.into(), }; @@ -187,12 +210,12 @@ where [serde_json::Value::String(s)] => Some(s.clone()), _ => None, }).unwrap_or_default(), - "assistant": String::from_utf8_lossy(&raw.body), + "assistant": release_body.clone(), "model": call.request.model, }); let digest = result.binding.as_deref() .map(simple_digest) - .unwrap_or_else(|| simple_digest(&String::from_utf8_lossy(&raw.body))); + .unwrap_or_else(|| simple_digest(&release_body)); let capture = CaptureContentSourceRequest { scope_id: call.scope_id.clone(), source_id: format!("gw-turn-{digest}"), diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index ae3db61a42..1a4e6b21a4 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -185,15 +185,10 @@ async fn read_response(rd: &mut ReadHalf) -> Result<(u16, Vec, b if buf.len() > MAX_HEADER_BYTES { return Err(GateError::Malformed("uds header too large".into())); } - let mut chunk = [0u8; 4096]; - let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) - .await - .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? - .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + let n = read_with_timeout(rd, &mut buf, 4096).await?; if n == 0 { return Err(GateError::Malformed("uds closed before headers".into())); } - buf.extend_from_slice(&chunk[..n]); }; let head = String::from_utf8_lossy(&buf[..header_end]).into_owned(); @@ -256,15 +251,10 @@ async fn read_more( target: usize, ) -> Result<(), GateError> { while buf.len() < target { - let mut chunk = [0u8; 8192]; - let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) - .await - .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? - .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + let n = read_with_timeout(rd, buf, 8192).await?; if n == 0 { return Err(GateError::Malformed("uds closed mid-body".into())); } - buf.extend_from_slice(&chunk[..n]); } Ok(()) } @@ -281,15 +271,10 @@ async fn read_chunked( if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { break pos; } - let mut chunk = [0u8; 4096]; - let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) - .await - .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? - .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + let n = read_with_timeout(rd, buf, 4096).await?; if n == 0 { return Err(GateError::Malformed("uds closed mid-chunk".into())); } - buf.extend_from_slice(&chunk[..n]); }; let size_str = String::from_utf8_lossy(&buf[..line_end]).into_owned(); buf.drain(..line_end + 2); @@ -306,26 +291,18 @@ async fn read_chunked( } continue; // trailer 头部行 } - let mut chunk = [0u8; 1024]; - let n = match tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)).await { - Ok(Ok(0)) => return Ok((out, false)), - Ok(Ok(n)) => n, - Ok(Err(_)) | Err(_) => return Ok((out, false)), + match read_with_timeout(rd, buf, 1024).await { + Ok(0) | Err(_) => return Ok((out, false)), + Ok(_) => {} }; - buf.extend_from_slice(&chunk[..n]); } } let needed = size + 2; // 数据 + CRLF while buf.len() < needed { - let mut chunk = [0u8; 8192]; - let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) - .await - .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? - .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + let n = read_with_timeout(rd, buf, 8192).await?; if n == 0 { return Err(GateError::Malformed("uds closed mid-chunk-data".into())); } - buf.extend_from_slice(&chunk[..n]); } out.extend_from_slice(&buf[..size]); buf.drain(..needed); @@ -345,6 +322,21 @@ fn retryable(e: &GateError) -> bool { } } +/// 超时读取一块数据追加到 buf,返回读取字节数(0 = 对端关闭)。 +async fn read_with_timeout( + rd: &mut ReadHalf, + buf: &mut Vec, + chunk_size: usize, +) -> Result { + let mut chunk = vec![0u8; chunk_size]; + let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) + .await + .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + buf.extend_from_slice(&chunk[..n]); + Ok(n) +} + fn find_terminator(buf: &[u8]) -> Option { buf.windows(4).position(|w| w == b"\r\n\r\n") } @@ -354,7 +346,7 @@ impl GateClient for UdsGateClient { &self, request: ContextCheckRequest, ) -> Result { - let body = serde_json::to_vec(&request).unwrap_or_default(); + let body = serde_json::to_vec(&request).expect("serialize gate request"); let this = self.clone(); { let (status, body) = this.request("POST", "/v1/context/check", Some(&body)).await?; @@ -382,7 +374,7 @@ impl GateClient for UdsGateClient { &self, request: PrepareContextRequest, ) -> Result { - let body = serde_json::to_vec(&request).unwrap_or_default(); + let body = serde_json::to_vec(&request).expect("serialize gate request"); let this = self.clone(); { let (status, body) = this.request("POST", "/v1/context/prepare", Some(&body)).await?; @@ -398,7 +390,7 @@ impl GateClient for UdsGateClient { &self, request: CaptureContentSourceRequest, ) -> Result { - let body = serde_json::to_vec(&request).unwrap_or_default(); + let body = serde_json::to_vec(&request).expect("serialize gate request"); let this = self.clone(); { let (status, body) = this.request("POST", "/v1/sources/content", Some(&body)).await?; diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 436a4ffcfc..cc067e7dc0 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -644,3 +644,52 @@ async fn blocked_turn_never_sediments() { executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; assert!(gate.captured.lock().unwrap().is_empty(), "被拦内容不得沉淀"); } + +#[tokio::test] +async fn malformed_gate_never_degrades_even_with_passthrough() { + // Core 可达但返回畸形响应:不是"不可用",绝不允许降级直通(fail-closed)。 + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::Malformed("garbage response".into()))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::GatePaused(_)), "Malformed 必须暂停"); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn non_utf8_response_is_never_released() { + // 上游返回非法 UTF-8 字节:不做有损转换送检(保真缺口),直接不放行。 + let bad = SendOutcome::Delivered(pc_gateway_transport::RawResponse { + status: 200, + body: bytes::Bytes::from_static(b"{\"text\":\"\xff\xfe\"}"), // 非法 UTF-8 + content_type: "application/json".into(), + ttft_ms: None, + usage: None, + }); + let (executor, renderer, transport, gate) = harness( + vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![bad], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Withheld { reason_codes } => { + assert_eq!(reason_codes, ["invalid_response_encoding"]) + } + other => panic!("expected Withheld, got {other:?}"), + } + // 只有一次检查(before_send);非法响应根本不送检、不释放。 + // cancel 不适用:非流式调用响应已完整到达,无进行中的上游工作可取消。 + assert_eq!(gate.seen.lock().unwrap().len(), 1); + assert_eq!(*transport.cancels.lock().unwrap(), 0); +} From 4930845ebaa8f31e0a6e8c942e8a99a466beae5c Mon Sep 17 00:00:00 2001 From: ztelur Date: Fri, 30 Oct 2026 22:41:28 +0800 Subject: [PATCH 05/37] chore(gateway): add Apache-2.0 license headers to all source files Adds the repository-standard Apache-2.0 header (copyright OceanBase, per .licenserc.yaml) to all 38 files: 30 Rust sources (// comments) and 8 Cargo.toml manifests (# comments), matching the style used by the Python sources. Resolves the license-check CI failure. Signed-off-by: ztelur --- gateway/Cargo.toml | 14 ++++++++++++++ gateway/crates/pc-gateway-app/Cargo.toml | 14 ++++++++++++++ gateway/crates/pc-gateway-app/src/ingress.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-app/src/link.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-app/src/main.rs | 14 ++++++++++++++ .../crates/pc-gateway-app/src/middleware/mod.rs | 14 ++++++++++++++ .../pc-gateway-app/src/middleware/request_id.rs | 14 ++++++++++++++ .../src/middleware/resource_limits.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-app/src/proxy.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-core/Cargo.toml | 14 ++++++++++++++ gateway/crates/pc-gateway-core/src/executor.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-core/src/gate_client.rs | 14 ++++++++++++++ .../crates/pc-gateway-core/src/http_gate_client.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-core/src/lib.rs | 14 ++++++++++++++ .../crates/pc-gateway-core/src/uds_gate_client.rs | 14 ++++++++++++++ .../pc-gateway-core/tests/executor_semantics.rs | 14 ++++++++++++++ .../pc-gateway-core/tests/live_context_check.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-core/tests/uds_pool.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-embedded/Cargo.toml | 14 ++++++++++++++ gateway/crates/pc-gateway-embedded/src/lib.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-evidence/Cargo.toml | 14 ++++++++++++++ gateway/crates/pc-gateway-evidence/src/lib.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-protocol/Cargo.toml | 14 ++++++++++++++ .../crates/pc-gateway-protocol/src/canonical.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-protocol/src/lib.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-protocol/src/render.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-protocol/src/sse.rs | 14 ++++++++++++++ .../pc-gateway-protocol/tests/openai_renderer.rs | 14 ++++++++++++++ .../tests/openai_responses_renderer.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-transport/Cargo.toml | 14 ++++++++++++++ gateway/crates/pc-gateway-transport/src/lib.rs | 14 ++++++++++++++ .../pc-gateway-transport/src/reqwest_transport.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-transport/src/retry.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-transport/src/sender.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-types/Cargo.toml | 14 ++++++++++++++ gateway/crates/pc-gateway-types/src/check.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-types/src/lib.rs | 14 ++++++++++++++ gateway/crates/pc-gateway-types/src/prepare.rs | 14 ++++++++++++++ 38 files changed, 532 insertions(+) diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml index 364dcbd078..832eb11549 100644 --- a/gateway/Cargo.toml +++ b/gateway/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [workspace] resolver = "2" members = [ diff --git a/gateway/crates/pc-gateway-app/Cargo.toml b/gateway/crates/pc-gateway-app/Cargo.toml index c63effad53..7ec1f5056b 100644 --- a/gateway/crates/pc-gateway-app/Cargo.toml +++ b/gateway/crates/pc-gateway-app/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [package] name = "pc-gateway-app" version.workspace = true diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index d9576f6a14..96883ae214 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 模型入口:OpenAI 兼容 `/gateway/v1/chat/completions`。 //! 客户端只改 Base URL 与 API Key 即接入(PR #2199 产品形态)。 diff --git a/gateway/crates/pc-gateway-app/src/link.rs b/gateway/crates/pc-gateway-app/src/link.rs index 752d2ba468..7968f04504 100644 --- a/gateway/crates/pc-gateway-app/src/link.rs +++ b/gateway/crates/pc-gateway-app/src/link.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! Core 连接形态:UDS(同机组合部署)或 TCP(独立运行)。 use pc_gateway_core::{GateClient, GateError, HttpGateClient, UdsGateClient}; diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index ea8a632535..4aedc03a86 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 薄二进制:端口接管 + 模型入口。所有执行逻辑在 `pc-gateway-core`。 //! //! PR #2199 部署形态: diff --git a/gateway/crates/pc-gateway-app/src/middleware/mod.rs b/gateway/crates/pc-gateway-app/src/middleware/mod.rs index 6c45acaacd..fd2499faee 100644 --- a/gateway/crates/pc-gateway-app/src/middleware/mod.rs +++ b/gateway/crates/pc-gateway-app/src/middleware/mod.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 网关中间件链(chain/filter)。 //! //! 设计对齐 PC 的 HttpResourceLimits / HttpRequestId / 观测栈分层思路: diff --git a/gateway/crates/pc-gateway-app/src/middleware/request_id.rs b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs index d6d027e453..3177405aa6 100644 --- a/gateway/crates/pc-gateway-app/src/middleware/request_id.rs +++ b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 请求 ID:透传客户端的 X-PowerContext-Request-ID 或生成新 ID, //! 注入请求扩展(供 handler/日志取用)并回写到响应头。 //! 对齐 PC 的 HttpRequestIdMiddleware,贯通排障链路。 diff --git a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs index c5ff35a7fa..b194e00c49 100644 --- a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs +++ b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 资源限流:请求体上限 + 并发上限(对齐 PC 的 HttpResourceLimitsMiddleware)。 //! 最外层准入——被拒请求不消耗内层任何资源。/healthz 豁免并发限制 //! (编排系统探活不应因业务拥堵被拒)。 diff --git a/gateway/crates/pc-gateway-app/src/proxy.rs b/gateway/crates/pc-gateway-app/src/proxy.rs index 8240f77768..ad098870a1 100644 --- a/gateway/crates/pc-gateway-app/src/proxy.rs +++ b/gateway/crates/pc-gateway-app/src/proxy.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 端口接管代理:非 `/gateway/*` 的流量原样转发到 Python 的 UDS。 //! 原 Core/MCP 路由由此透传;流式(SSE/分块)由 hyper 客户端透传保证。 diff --git a/gateway/crates/pc-gateway-core/Cargo.toml b/gateway/crates/pc-gateway-core/Cargo.toml index 1f1b1b0ff4..f92693d763 100644 --- a/gateway/crates/pc-gateway-core/Cargo.toml +++ b/gateway/crates/pc-gateway-core/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [package] name = "pc-gateway-core" version.workspace = true diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index d06ab6a3f6..78ac88f4fb 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::{GateClient, GateError}; use pc_gateway_evidence::EvidenceSink; use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; diff --git a/gateway/crates/pc-gateway-core/src/gate_client.rs b/gateway/crates/pc-gateway-core/src/gate_client.rs index d7f072601c..144eca6a1b 100644 --- a/gateway/crates/pc-gateway-core/src/gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/gate_client.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use pc_gateway_types::{ CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, PrepareContextResult, diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs index 1467c67f69..747abe16e1 100644 --- a/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::{GateClient, GateError}; use pc_gateway_types::{ CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, diff --git a/gateway/crates/pc-gateway-core/src/lib.rs b/gateway/crates/pc-gateway-core/src/lib.rs index 5abbb143eb..35509e6b2a 100644 --- a/gateway/crates/pc-gateway-core/src/lib.rs +++ b/gateway/crates/pc-gateway-core/src/lib.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 执行器核心:一次托管调用的状态机。 //! //! 对应 RFC「一次托管调用」时序图(PR #2199 两阶段检查形态): diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index 1a4e6b21a4..4dede09804 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 同机组合部署形态:HTTP over Unix Domain Socket。 //! //! PR #2199:启用后 Rust 独占公网 TCP 端口,Python 只监听本机 UDS; diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index cc067e7dc0..ce91449351 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! PR #2264 失败语义表的状态机级验证(真实契约形态)。 use pc_gateway_core::{DegradePolicy, Executor, GateClient, GateError, ManagedCall, ManagedOutcome}; diff --git a/gateway/crates/pc-gateway-core/tests/live_context_check.rs b/gateway/crates/pc-gateway-core/tests/live_context_check.rs index d373a63bec..adc31cb393 100644 --- a/gateway/crates/pc-gateway-core/tests/live_context_check.rs +++ b/gateway/crates/pc-gateway-core/tests/live_context_check.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 对真实 PowerContext Server(PR #2264)的 HTTP 级集成测试。 //! //! 与单测(FakeGate)互补:这里验证的是 Core 侧加密 binding 的真实行为, diff --git a/gateway/crates/pc-gateway-core/tests/uds_pool.rs b/gateway/crates/pc-gateway-core/tests/uds_pool.rs index c272c65c72..dbfdab277b 100644 --- a/gateway/crates/pc-gateway-core/tests/uds_pool.rs +++ b/gateway/crates/pc-gateway-core/tests/uds_pool.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! UDS 连接池正确性回归:keep-alive 连接上的连续响应必须逐次正确解析。 //! 覆盖三个场景:content-length 精确、chunked(含 trailer)、content-length 超读截断。 diff --git a/gateway/crates/pc-gateway-embedded/Cargo.toml b/gateway/crates/pc-gateway-embedded/Cargo.toml index bc5b6ef3ef..a854a4ac55 100644 --- a/gateway/crates/pc-gateway-embedded/Cargo.toml +++ b/gateway/crates/pc-gateway-embedded/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [package] name = "pc-gateway-embedded" version.workspace = true diff --git a/gateway/crates/pc-gateway-embedded/src/lib.rs b/gateway/crates/pc-gateway-embedded/src/lib.rs index aeec6fd8ea..b69b1f5240 100644 --- a/gateway/crates/pc-gateway-embedded/src/lib.rs +++ b/gateway/crates/pc-gateway-embedded/src/lib.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 嵌入式路径的占位 crate。 //! //! RFC:SDK/内置执行与 Rust GatewayRuntime 是按调用配置的两种执行路径, diff --git a/gateway/crates/pc-gateway-evidence/Cargo.toml b/gateway/crates/pc-gateway-evidence/Cargo.toml index abbef5e020..0b939df869 100644 --- a/gateway/crates/pc-gateway-evidence/Cargo.toml +++ b/gateway/crates/pc-gateway-evidence/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [package] name = "pc-gateway-evidence" version.workspace = true diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs index cdc6cab546..b980a257f7 100644 --- a/gateway/crates/pc-gateway-evidence/src/lib.rs +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 证据适配层。 //! //! RFC 约束:归一化实际目标身份、usage 完整性、供应商缓存 read/write、 diff --git a/gateway/crates/pc-gateway-protocol/Cargo.toml b/gateway/crates/pc-gateway-protocol/Cargo.toml index 50b555190b..74ae8e4e8d 100644 --- a/gateway/crates/pc-gateway-protocol/Cargo.toml +++ b/gateway/crates/pc-gateway-protocol/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [package] name = "pc-gateway-protocol" version.workspace = true diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs index 0ec8d0711e..260df4819d 100644 --- a/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use serde::{Deserialize, Serialize}; /// 网关内部规范请求:发送前必须完整落入 input/check。 diff --git a/gateway/crates/pc-gateway-protocol/src/lib.rs b/gateway/crates/pc-gateway-protocol/src/lib.rs index 2313875b32..962dc96a73 100644 --- a/gateway/crates/pc-gateway-protocol/src/lib.rs +++ b/gateway/crates/pc-gateway-protocol/src/lib.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 协议适配层:内部规范类型 ↔ 各服务商线格式。 //! //! RFC 约束:只渲染获准的协议字段;保持角色、工具顺序、内容块、 diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index 482ed92187..8552772426 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::{CanonicalRequest, RenderedPayload}; /// 渲染错误。 diff --git a/gateway/crates/pc-gateway-protocol/src/sse.rs b/gateway/crates/pc-gateway-protocol/src/sse.rs index 9ea5bcc5a6..410b9e86da 100644 --- a/gateway/crates/pc-gateway-protocol/src/sse.rs +++ b/gateway/crates/pc-gateway-protocol/src/sse.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! SSE 解析。 //! //! RFC 约束:strict 模式在完整 output/check 之后才组帧, diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index a01a73ff1d..7b51de714d 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use pc_gateway_protocol::{ CanonicalMessage, CanonicalRequest, OpenAiChatRenderer, OutputLimits, Role, WireRenderer, }; diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 4aa5f41792..efd9937d6a 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use pc_gateway_protocol::{ CanonicalMessage, CanonicalRequest, OpenAiResponsesRenderer, OutputLimits, Role, WireRenderer, diff --git a/gateway/crates/pc-gateway-transport/Cargo.toml b/gateway/crates/pc-gateway-transport/Cargo.toml index a674b39923..5fa369e5b4 100644 --- a/gateway/crates/pc-gateway-transport/Cargo.toml +++ b/gateway/crates/pc-gateway-transport/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [package] name = "pc-gateway-transport" version.workspace = true diff --git a/gateway/crates/pc-gateway-transport/src/lib.rs b/gateway/crates/pc-gateway-transport/src/lib.rs index 8cfd5154c7..df6ef271aa 100644 --- a/gateway/crates/pc-gateway-transport/src/lib.rs +++ b/gateway/crates/pc-gateway-transport/src/lib.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! 传输层:发送获准字节、取消、归属明确的有界重试。 //! //! RFC 失败语义: diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index 43f67a7ffb..57cc15f0c2 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::sender::{ AdmittedSend, NotSentReason, RawResponse, SendIndeterminateReason, SendOutcome, Transport, }; diff --git a/gateway/crates/pc-gateway-transport/src/retry.rs b/gateway/crates/pc-gateway-transport/src/retry.rs index c853f01565..264936da43 100644 --- a/gateway/crates/pc-gateway-transport/src/retry.rs +++ b/gateway/crates/pc-gateway-transport/src/retry.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::{AdmittedSend, SendOutcome, Transport}; use pc_gateway_evidence::EvidenceSink; use std::num::NonZeroU32; diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs index 18854a36d7..3b0bf792cf 100644 --- a/gateway/crates/pc-gateway-transport/src/sender.rs +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use bytes::Bytes; use std::future::Future; diff --git a/gateway/crates/pc-gateway-types/Cargo.toml b/gateway/crates/pc-gateway-types/Cargo.toml index 81a977a81f..172530425c 100644 --- a/gateway/crates/pc-gateway-types/Cargo.toml +++ b/gateway/crates/pc-gateway-types/Cargo.toml @@ -1,3 +1,17 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + [package] name = "pc-gateway-types" version.workspace = true diff --git a/gateway/crates/pc-gateway-types/src/check.rs b/gateway/crates/pc-gateway-types/src/check.rs index 0b3f11bf80..b517a3b032 100644 --- a/gateway/crates/pc-gateway-types/src/check.rs +++ b/gateway/crates/pc-gateway-types/src/check.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! PR #2264 定义的 `POST /v1/context/check` 真实契约。 //! //! 关键语义(openapi/powercontext.yaml 原文): diff --git a/gateway/crates/pc-gateway-types/src/lib.rs b/gateway/crates/pc-gateway-types/src/lib.rs index ff69efb703..5865fa1c38 100644 --- a/gateway/crates/pc-gateway-types/src/lib.rs +++ b/gateway/crates/pc-gateway-types/src/lib.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! PR #2264 契约值类型。 //! //! 网关无策略:这里的类型只承载 Core 的输入/输出, diff --git a/gateway/crates/pc-gateway-types/src/prepare.rs b/gateway/crates/pc-gateway-types/src/prepare.rs index d6f2b9cdb7..88702dc2a2 100644 --- a/gateway/crates/pc-gateway-types/src/prepare.rs +++ b/gateway/crates/pc-gateway-types/src/prepare.rs @@ -1,3 +1,17 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + //! prepare 契约(PR #2264),字段形状对照真实响应校准。 use serde::{Deserialize, Serialize}; From b87c096af45c7caba8e6d098463febb418c26e9e Mon Sep 17 00:00:00 2001 From: ztelur Date: Fri, 30 Oct 2026 23:06:43 +0800 Subject: [PATCH 06/37] fix(gateway): never retry requests already handed to the upstream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit reqwest::Error::is_request() also covers a connection closing while awaiting response headers after the complete body was sent, so the previous mapping could retry an already-delivered (billable) body and then report AllNotSent. NotSent is now restricted to failures proven to precede transmission (is_connect / is_builder); every post-handoff error classifies as Indeterminate and is not retried. Regression test reproduces the review scenario: a loopback upstream that reads the full POST body and closes — with BoundedRetry (max_attempts=2) the server observes exactly one body and the outcome is Indeterminate. Signed-off-by: ztelur --- .../src/reqwest_transport.rs | 16 ++- .../crates/pc-gateway-transport/src/retry.rs | 5 +- .../tests/no_duplicate_send.rs | 106 ++++++++++++++++++ 3 files changed, 121 insertions(+), 6 deletions(-) create mode 100644 gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index 57cc15f0c2..db8b9d7626 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -76,16 +76,24 @@ impl Transport for ReqwestTransport { } let resp = match req.body(send.payload.to_vec()).send().await { Err(e) => { + // NotSent 仅限于「可证明发生在传输之前」的失败: + // - is_connect():TCP/TLS 握手未完成,body 必然未发出; + // - is_builder():请求构造阶段,早于一切网络动作。 + // 其余(is_request/is_timeout/is_body/is_decode)都无法排除 + // body 已完整送达上游的可能——reqwest 的 is_request() 尤其 + // 涵盖「对端读完全部 body 后关闭/超时」,按未送达重试会 + // 重复计费。一律归 Indeterminate,不重试。 return if e.is_connect() { SendOutcome::NotSent(NotSentReason::ConnectRefused) - } else if e.is_builder() || e.is_request() { + } else if e.is_builder() { SendOutcome::NotSent(NotSentReason::RejectedLocally) } else if e.is_timeout() { - // 请求可能已被上游接收:不能当作未送达重试。 - SendOutcome::Indeterminate(SendIndeterminateReason::TimeoutAwaitingResponse) + SendOutcome::Indeterminate( + SendIndeterminateReason::TimeoutAwaitingResponse, + ) } else { SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) - } + }; } Ok(resp) => resp, }; diff --git a/gateway/crates/pc-gateway-transport/src/retry.rs b/gateway/crates/pc-gateway-transport/src/retry.rs index 264936da43..147ac7d77d 100644 --- a/gateway/crates/pc-gateway-transport/src/retry.rs +++ b/gateway/crates/pc-gateway-transport/src/retry.rs @@ -23,8 +23,9 @@ pub struct BoundedRetry { max_attempts: NonZeroU32, } -/// 重试的结果:`Ok` 携带原始 `SendOutcome`; -/// `Err` 表示全部尝试都确定性未送达。 +/// 重试的结果:`Done` 携带原始 `SendOutcome`; +/// `AllNotSent` 表示全部尝试都确定性未送达。 +#[derive(Debug)] pub enum RetryOutcome { Done(SendOutcome), AllNotSent { attempts: u32 }, diff --git a/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs new file mode 100644 index 0000000000..bb1c53bd00 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs @@ -0,0 +1,106 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P1-1): +//! 对端读完整 POST body 后关闭连接 —— reqwest 报 is_request() 类错误。 +//! 断言:body 只被上游收到一次(绝不重复计费发送), +//! 且结果归为 Indeterminate 而非可重试的 NotSent。 + +use pc_gateway_transport::{ + AdmittedSend, ReqwestTransport, SendOutcome, SendIndeterminateReason, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::AsyncReadExt; +use tokio::net::TcpListener; + +#[tokio::test] +async fn upstream_closing_after_full_body_is_indeterminate_and_not_resent() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let bodies = Arc::new(AtomicUsize::new(0)); + let connections = Arc::new(AtomicUsize::new(0)); + + let b = bodies.clone(); + let c = connections.clone(); + tokio::spawn(async move { + // 接受至多 2 条连接:若网关错误地重试,第二条也会收到 body。 + for _ in 0..2 { + let (mut sock, _) = match listener.accept().await { + Ok(x) => x, + Err(_) => return, + }; + c.fetch_add(1, Ordering::SeqCst); + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + // 读到完整请求(头 + Content-Length 声明的 body) + loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); + let len: usize = head + .lines() + .find_map(|l| l.strip_prefix("content-length: ")) + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0); + if buf.len() >= pos + 4 + len { + break; + } + } + } + // 完整收到一条带 body 的 POST → 计数 + if buf.starts_with(b"POST") { + b.fetch_add(1, Ordering::SeqCst); + } + // 读完即关闭,不回任何响应(review 描述的复现场景) + drop(sock); + } + }); + + let transport = ReqwestTransport::default(); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), + target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + + // 复现 review 场景:BoundedRetry(max_attempts=2)。 + // 旧行为:is_request() 被归为 NotSent → 重试 → 上游收到两次完整 body + // 且最终谎报 AllNotSent{attempts:2}。 + // 新行为:归为 Indeterminate → 立即上抛,不进行第二次发送。 + let retry = pc_gateway_transport::BoundedRetry::new( + transport, + std::num::NonZeroU32::new(2).unwrap(), + ); + let outcome = retry.send_with_retry(&send, &pc_gateway_evidence::NoopEvidenceSink).await; + match outcome { + pc_gateway_transport::RetryOutcome::Done(SendOutcome::Indeterminate( + SendIndeterminateReason::LostAfterHandoff, + )) => {} + other => panic!("expected Done(Indeterminate), got {other:?}"), + } + + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + assert_eq!( + bodies.load(Ordering::SeqCst), + 1, + "上游必须只收到一次 body(修复前是 2 次,重复计费)" + ); +} From 5a895086702eb2f7221fe40909b9345ab7fe2434 Mon Sep 17 00:00:00 2001 From: ztelur Date: Fri, 30 Oct 2026 23:28:57 +0800 Subject: [PATCH 07/37] fix(gateway): disable automatic upstream redirects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit reqwest's default redirect policy would re-send an admitted POST body (307/308 preserve method and body) to the Location target without any Core admission — the approved destination silently stops being the actual destination. Both HTTP clients (upstream transport and gate client) now set redirect Policy::none(); a 3xx response surfaces as a normal delivered response (status passed through to the caller after the release check) and no bytes are ever re-sent automatically. Regression test reproduces the review scenario: an approved loopback upstream returning 307 to a second listener — the redirect target receives zero bytes and the 307 is delivered as-is. Signed-off-by: ztelur --- .../gateway/crates/pc-gateway-app/Cargo.toml | 43 ++ .../crates/pc-gateway-app/src/ingress.rs | 329 ++++++++ .../gateway/crates/pc-gateway-app/src/link.rs | 79 ++ .../gateway/crates/pc-gateway-app/src/main.rs | 159 ++++ .../pc-gateway-app/src/middleware/mod.rs | 77 ++ .../src/middleware/request_id.rs | 68 ++ .../src/middleware/resource_limits.rs | 99 +++ .../crates/pc-gateway-app/src/proxy.rs | 163 ++++ .../gateway/crates/pc-gateway-core/Cargo.toml | 33 + .../crates/pc-gateway-core/src/executor.rs | 402 ++++++++++ .../crates/pc-gateway-core/src/gate_client.rs | 58 ++ .../pc-gateway-core/src/http_gate_client.rs | 123 +++ .../gateway/crates/pc-gateway-core/src/lib.rs | 36 + .../pc-gateway-core/src/uds_gate_client.rs | 418 +++++++++++ .../tests/executor_semantics.rs | 709 ++++++++++++++++++ .../tests/live_context_check.rs | 249 ++++++ .../crates/pc-gateway-core/tests/uds_pool.rs | 128 ++++ .../crates/pc-gateway-embedded/Cargo.toml | 24 + .../crates/pc-gateway-embedded/src/lib.rs | 22 + .../crates/pc-gateway-evidence/Cargo.toml | 24 + .../crates/pc-gateway-evidence/src/lib.rs | 112 +++ .../crates/pc-gateway-protocol/Cargo.toml | 27 + .../pc-gateway-protocol/src/canonical.rs | 63 ++ .../crates/pc-gateway-protocol/src/lib.rs | 27 + .../crates/pc-gateway-protocol/src/render.rs | 248 ++++++ .../crates/pc-gateway-protocol/src/sse.rs | 87 +++ .../tests/openai_renderer.rs | 74 ++ .../tests/openai_responses_renderer.rs | 89 +++ .../crates/pc-gateway-transport/Cargo.toml | 30 + .../crates/pc-gateway-transport/src/lib.rs | 29 + .../src/reqwest_transport.rs | 190 +++++ .../crates/pc-gateway-transport/src/retry.rs | 69 ++ .../crates/pc-gateway-transport/src/sender.rs | 86 +++ .../tests/no_duplicate_send.rs | 106 +++ .../tests/no_redirect_resend.rs | 107 +++ .../crates/pc-gateway-types/Cargo.toml | 26 + .../crates/pc-gateway-types/src/check.rs | 151 ++++ .../crates/pc-gateway-types/src/lib.rs | 24 + .../crates/pc-gateway-types/src/prepare.rs | 113 +++ 39 files changed, 4901 insertions(+) create mode 100644 powercontext/gateway/crates/pc-gateway-app/Cargo.toml create mode 100644 powercontext/gateway/crates/pc-gateway-app/src/ingress.rs create mode 100644 powercontext/gateway/crates/pc-gateway-app/src/link.rs create mode 100644 powercontext/gateway/crates/pc-gateway-app/src/main.rs create mode 100644 powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs create mode 100644 powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs create mode 100644 powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs create mode 100644 powercontext/gateway/crates/pc-gateway-app/src/proxy.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/Cargo.toml create mode 100644 powercontext/gateway/crates/pc-gateway-core/src/executor.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/src/lib.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs create mode 100644 powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs create mode 100644 powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml create mode 100644 powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs create mode 100644 powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml create mode 100644 powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs create mode 100644 powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml create mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs create mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs create mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/render.rs create mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs create mode 100644 powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs create mode 100644 powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs create mode 100644 powercontext/gateway/crates/pc-gateway-transport/Cargo.toml create mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/lib.rs create mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs create mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/retry.rs create mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/sender.rs create mode 100644 powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs create mode 100644 powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs create mode 100644 powercontext/gateway/crates/pc-gateway-types/Cargo.toml create mode 100644 powercontext/gateway/crates/pc-gateway-types/src/check.rs create mode 100644 powercontext/gateway/crates/pc-gateway-types/src/lib.rs create mode 100644 powercontext/gateway/crates/pc-gateway-types/src/prepare.rs diff --git a/powercontext/gateway/crates/pc-gateway-app/Cargo.toml b/powercontext/gateway/crates/pc-gateway-app/Cargo.toml new file mode 100644 index 0000000000..7ec1f5056b --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/Cargo.toml @@ -0,0 +1,43 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-app" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: thin binary — port takeover, Core/MCP forwarding, OpenAI-compatible model ingress" + +[[bin]] +name = "pc-gateway" +path = "src/main.rs" + +[dependencies] +pc-gateway-core = { workspace = true } +pc-gateway-types = { workspace = true } +pc-gateway-protocol = { workspace = true } +pc-gateway-transport = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +tokio = { workspace = true } +axum = { workspace = true } +serde_json = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +reqwest = { workspace = true } +hyper = { workspace = true } +tower = { workspace = true } +hyper-util = { workspace = true } +http-body-util = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-app/src/ingress.rs b/powercontext/gateway/crates/pc-gateway-app/src/ingress.rs new file mode 100644 index 0000000000..96883ae214 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/src/ingress.rs @@ -0,0 +1,329 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 模型入口:OpenAI 兼容 `/gateway/v1/chat/completions`。 +//! 客户端只改 Base URL 与 API Key 即接入(PR #2199 产品形态)。 + +use crate::{proxy::SharedProxy, AppState}; +use axum::body::Bytes; +use axum::extract::{Request, State}; +use axum::http::{header, HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use pc_gateway_core::{ManagedCall, ManagedOutcome}; +use pc_gateway_protocol::{CanonicalMessage, CanonicalRequest, OutputLimits, Role}; +use serde::Deserialize; +use std::sync::Arc; + +#[derive(Debug, Deserialize)] +struct OpenAiChatRequest { + model: String, + messages: Vec, + #[serde(default)] + tools: Vec, + #[serde(default)] + max_tokens: Option, + #[serde(default)] + stream: Option, +} + +#[derive(Debug, Deserialize)] +struct OpenAiMessage { + role: String, + #[serde(default)] + content: serde_json::Value, +} + +/// Responses API 入口请求(同格式进出,不与 chat 互转)。 +#[derive(Debug, Deserialize)] +struct OpenAiResponsesRequest { + model: String, + input: Vec, + #[serde(default)] + instructions: Option, + #[serde(default)] + tools: Vec, + #[serde(default)] + max_output_tokens: Option, + #[serde(default)] + stream: Option, +} + +pub async fn chat_completions( + State((state, _)): State, + headers: HeaderMap, + req: Request, +) -> Response { + ingress_common(state, headers, req, Format::Chat).await +} + +pub async fn responses( + State((state, _)): State, + headers: HeaderMap, + req: Request, +) -> Response { + ingress_common(state, headers, req, Format::Responses).await +} + +enum Format { + Chat, + Responses, +} + +async fn ingress_common( + state: Arc, + headers: HeaderMap, + req: Request, + format: Format, +) -> Response { + // 网关密钥认证(替代服务商 key;上游凭据由受控配置持有)。 + if let Some(expected) = &state.api_key { + let provided = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")); + if provided != Some(expected.as_str()) { + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({ "error": "invalid_gateway_key" })), + ) + .into_response(); + } + } + + let body = match axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024).await { + Ok(b) => b, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + let canonical = match format { + Format::Chat => { + let chat: OpenAiChatRequest = match serde_json::from_slice(&body) { + Ok(c) => c, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_openai_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + match to_canonical_chat(chat) { + Ok(c) => c, + Err(msg) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), + ) + .into_response() + } + } + } + Format::Responses => { + let r: OpenAiResponsesRequest = match serde_json::from_slice(&body) { + Ok(c) => c, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_responses_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + match to_canonical_responses(r) { + Ok(c) => c, + Err(msg) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), + ) + .into_response() + } + } + } + }; + let renderer = match format { + Format::Chat => pc_gateway_protocol::GatewayRenderer::Chat(Default::default()), + Format::Responses => pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), + }; + + let call = ManagedCall { + scope_id: state.default_scope.clone(), + target_profile: state.upstream_profile.clone(), + request: canonical, + target_url: match format { + Format::Chat => state.upstream_chat.clone(), + Format::Responses => state.upstream_responses.clone(), + }, + headers: bearer_headers(match format { + Format::Chat => &state.upstream_chat_api_key, + Format::Responses => &state.upstream_responses_api_key, + }), + degrade_policy: state.degrade, + inject_context: state.inject_context + && matches!(format, Format::Chat), + sediment: state.sediment, + prepared_contexts: Vec::new(), + }; + + let outcome = state.executor.run(call, &renderer, state.evidence.as_ref()).await; + respond(outcome) +} + +fn bearer_headers(key: &str) -> Vec<(String, String)> { + if key.is_empty() { + Vec::new() + } else { + vec![("authorization".to_string(), format!("Bearer {key}"))] + } +} + +fn to_canonical_chat(chat: OpenAiChatRequest) -> Result { + let mut messages = Vec::with_capacity(chat.messages.len()); + for m in chat.messages { + let role = match m.role.as_str() { + "system" => Role::System, + "user" => Role::User, + "assistant" => Role::Assistant, + "tool" => Role::Tool, + other => return Err(format!("unsupported role: {other}")), + }; + let content = match m.content { + serde_json::Value::String(s) => vec![serde_json::Value::String(s)], + serde_json::Value::Array(a) => a, + serde_json::Value::Null => vec![], + other => return Err(format!("unsupported content type: {other}")), + }; + messages.push(CanonicalMessage { role, content }); + } + Ok(CanonicalRequest { + model: chat.model, + messages, + tools: chat.tools, + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: chat.max_tokens.unwrap_or(1024), + }, + stream: chat.stream.unwrap_or(false), + }) +} + +/// Responses 入口 → 规范类型:消息项照常映射; +/// Responses 专有 item(function_call 等)原样封进 content, +/// 由 `OpenAiResponsesRenderer` 按原样作为顶层 input item 透出(无跨格式转换)。 +fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result { + let mut messages = Vec::with_capacity(r.input.len()); + for item in r.input { + let role_str = item.get("role").and_then(|v| v.as_str()).unwrap_or(""); + let role = match role_str { + "system" | "developer" => Role::System, + "user" => Role::User, + "assistant" => Role::Assistant, + "tool" => Role::Tool, + // 无 role 的顶层 item(function_call/function_call_output 等): + // 原样保留,role 占位为 tool。 + _ => Role::Tool, + }; + if role_str.is_empty() { + messages.push(CanonicalMessage { + role: Role::Tool, + content: vec![item], + }); + continue; + } + let content = match item.get("content") { + Some(serde_json::Value::String(s)) => vec![serde_json::Value::String(s.clone())], + Some(serde_json::Value::Array(a)) => a.clone(), + _ => vec![], + }; + messages.push(CanonicalMessage { role, content }); + } + Ok(CanonicalRequest { + model: r.model, + messages, + tools: r.tools, + instructions: r.instructions, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: r.max_output_tokens.unwrap_or(1024), + }, + stream: r.stream.unwrap_or(false), + }) +} + +/// 结果映射:不存在静默成功;降级直通必须显式标记。 +fn respond(outcome: ManagedOutcome) -> Response { + match outcome { + ManagedOutcome::Released { status, content_type, body, .. } => { + // 上游状态码与 Content-Type 原样透传(错误不伪装 200)。 + let code = StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY); + ( + code, + [(header::CONTENT_TYPE, content_type.as_str())], + body.to_vec(), + ) + .into_response() + } + ManagedOutcome::Degraded { status, content_type, body } => match Response::builder() + .status( + StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY), + ) + .header(header::CONTENT_TYPE, content_type.as_str()) + .header("x-pc-degraded", "passthrough_without_memory") + .body(axum::body::Body::from(body.to_vec())) + { + Ok(r) => r, + Err(e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(serde_json::json!({ "error": e.to_string() })), + ) + .into_response(), + }, + ManagedOutcome::Blocked { reason_codes } => ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ "decision": "block", "reason_codes": reason_codes })), + ) + .into_response(), + ManagedOutcome::Withheld { reason_codes } => ( + StatusCode::CONFLICT, + Json(serde_json::json!({ "decision": "withhold", "reason_codes": reason_codes })), + ) + .into_response(), + ManagedOutcome::SendIndeterminate => ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({ "decision": "send_indeterminate" })), + ) + .into_response(), + ManagedOutcome::NotSent { attempts } => ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({ "decision": "not_sent", "attempts": attempts })), + ) + .into_response(), + ManagedOutcome::GatePaused(msg) => ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "decision": "gate_paused", "detail": msg })), + ) + .into_response(), + } +} + +// 抑制未使用导入警告(Bytes 用于类型别名文档场景)。 +#[allow(dead_code)] +fn _unused(_: Option) {} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/link.rs b/powercontext/gateway/crates/pc-gateway-app/src/link.rs new file mode 100644 index 0000000000..7968f04504 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/src/link.rs @@ -0,0 +1,79 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Core 连接形态:UDS(同机组合部署)或 TCP(独立运行)。 + +use pc_gateway_core::{GateClient, GateError, HttpGateClient, UdsGateClient}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; + +pub enum CoreLink { + Uds(UdsGateClient), + Http(HttpGateClient), +} + +impl CoreLink { + pub fn from_env() -> Self { + if let Ok(sock) = std::env::var("PC_GATEWAY_CORE_UDS") { + tracing::info!(%sock, "core link: UDS (combined deployment)"); + Self::Uds(UdsGateClient::new(sock)) + } else { + let base = + std::env::var("PC_GATEWAY_CORE_BASE").unwrap_or_else(|_| "http://127.0.0.1:8000".into()); + tracing::info!(%base, "core link: TCP (standalone deployment)"); + Self::Http(HttpGateClient::new(base)) + } + } +} + +impl GateClient for CoreLink { + async fn check( + &self, + request: ContextCheckRequest, + ) -> Result { + match self { + CoreLink::Uds(c) => c.check(request).await, + CoreLink::Http(c) => c.check(request).await, + } + } + + async fn capabilities(&self) -> Result { + match self { + CoreLink::Uds(c) => c.capabilities().await, + CoreLink::Http(c) => c.capabilities().await, + } + } + + async fn prepare( + &self, + request: PrepareContextRequest, + ) -> Result { + match self { + CoreLink::Uds(c) => c.prepare(request).await, + CoreLink::Http(c) => c.prepare(request).await, + } + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + match self { + CoreLink::Uds(c) => c.capture(request).await, + CoreLink::Http(c) => c.capture(request).await, + } + } +} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/main.rs b/powercontext/gateway/crates/pc-gateway-app/src/main.rs new file mode 100644 index 0000000000..4aedc03a86 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/src/main.rs @@ -0,0 +1,159 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 薄二进制:端口接管 + 模型入口。所有执行逻辑在 `pc-gateway-core`。 +//! +//! PR #2199 部署形态: +//! - 同机组合:`PC_GATEWAY_CORE_UDS` 指向 Python 的 UDS;网关独占公网端口, +//! 非 `/gateway/*` 流量反向代理到 UDS(原 Core/MCP 路由透传)。 +//! - 独立运行:`PC_GATEWAY_CORE_BASE` 直连远端 PowerContext(无代理)。 +//! +//! 环境变量:PC_GATEWAY_LISTEN、PC_GATEWAY_CORE_UDS、PC_GATEWAY_CORE_BASE、 +//! PC_GATEWAY_API_KEY(网关密钥,替代服务商 key)、PC_GATEWAY_UPSTREAM_URL、 +//! PC_GATEWAY_UPSTREAM_API_KEY、PC_GATEWAY_UPSTREAM_PROFILE、 +//! PC_GATEWAY_POLICY_VERSION、PC_GATEWAY_MAX_ATTEMPTS、PC_GATEWAY_DEGRADE。 + +mod ingress; +mod link; +mod middleware; +mod proxy; + +use crate::link::CoreLink; +use axum::routing::{get, post}; +use axum::Router; +use pc_gateway_core::Executor; +use pc_gateway_evidence::BufferedEvidenceSink; +use pc_gateway_transport::ReqwestTransport; +use std::net::SocketAddr; +use std::num::NonZeroU32; +use std::sync::Arc; +use std::time::Duration; + +pub struct AppState { + /// 单一执行器;线格式渲染器按请求格式传入(同格式进出)。 + pub executor: Arc>, + pub evidence: Arc, + pub upstream_profile: String, + /// chat-completions 上游(含 key;老变量 PC_GATEWAY_UPSTREAM_URL 仍作缺省)。 + pub upstream_chat: String, + /// responses 上游。 + pub upstream_responses: String, + pub upstream_chat_api_key: String, + pub upstream_responses_api_key: String, + pub api_key: Option, + pub degrade: pc_gateway_core::DegradePolicy, + /// 是否调 prepare 注入上下文(默认关;v1 仅 chat 格式)。 + pub inject_context: bool, + /// 过检后同步沉淀对话(默认关)。 + pub sediment: bool, + /// 默认 Scope(启动时读一次,避免热路径读环境变量)。 + pub default_scope: String, +} + +#[tokio::main] +async fn main() { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "info".into()), + ) + .init(); + + let core_link = CoreLink::from_env(); + let proxy_state = proxy::ProxyState::from_env(); + + let max_attempts: u32 = std::env::var("PC_GATEWAY_MAX_ATTEMPTS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(2); + let max_body_bytes: usize = std::env::var("PC_GATEWAY_MAX_BODY_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(16 * 1024 * 1024); + let max_concurrent: usize = std::env::var("PC_GATEWAY_MAX_CONCURRENT") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|v| *v > 0) + .unwrap_or(64); + let degrade = match std::env::var("PC_GATEWAY_DEGRADE").as_deref() { + Ok("passthrough") => pc_gateway_core::DegradePolicy::PassthroughWithoutMemory, + _ => pc_gateway_core::DegradePolicy::Pause, + }; + + let state = Arc::new(AppState { + executor: Arc::new(Executor::new( + core_link, + ReqwestTransport::new(Duration::from_secs(120)), + NonZeroU32::new(max_attempts).expect("max_attempts > 0"), + )), + evidence: Arc::new(BufferedEvidenceSink::new()), + upstream_profile: std::env::var("PC_GATEWAY_UPSTREAM_PROFILE") + .unwrap_or_else(|_| "default".into()), + upstream_chat: std::env::var("PC_GATEWAY_UPSTREAM_URL_CHAT") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_URL")) + .unwrap_or_else(|_| "http://127.0.0.1:9000/v1/chat/completions".into()), + upstream_responses: std::env::var("PC_GATEWAY_UPSTREAM_URL_RESPONSES") + .unwrap_or_else(|_| "https://openrouter.ai/api/v1/responses".into()), + upstream_chat_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_CHAT") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) + .unwrap_or_default(), + upstream_responses_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_RESPONSES") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) + .unwrap_or_default(), + api_key: std::env::var("PC_GATEWAY_API_KEY").ok().filter(|k| !k.is_empty()), + degrade, + inject_context: matches!(std::env::var("PC_GATEWAY_INJECTION").as_deref(), Ok("on")), + sediment: matches!(std::env::var("PC_GATEWAY_SEDIMENT").as_deref(), Ok("on")), + default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") + .unwrap_or_else(|_| "gateway:default".into()), + }); + + let router = Router::new() + .route("/healthz", get(healthz)) + .route("/gateway/v1/chat/completions", post(ingress::chat_completions)) + .route("/gateway/v1/responses", post(ingress::responses)) + .fallback(proxy::fallback) + .with_state((state, proxy_state)); + + // 中间件链:按序注册,前者为外层。新增功能 = 实现 GatewayMiddleware + 此处一行。 + let chain: Vec> = vec![ + middleware::ResourceLimits::new(max_body_bytes, max_concurrent), + std::sync::Arc::new(middleware::RequestId), + ]; + for mw in &chain { + tracing::info!(middleware = mw.name(), "middleware enabled"); + } + let app = middleware::apply_chain(router, chain); + + let addr: SocketAddr = std::env::var("PC_GATEWAY_LISTEN") + .unwrap_or_else(|_| "127.0.0.1:8787".into()) + .parse() + .expect("PC_GATEWAY_LISTEN must be host:port"); + + tracing::info!(%addr, "pc-gateway listening (port takeover mode)"); + let listener = tokio::net::TcpListener::bind(addr).await.expect("bind"); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .expect("serve"); +} + +async fn shutdown_signal() { + let _ = tokio::signal::ctrl_c().await; + tracing::info!("shutting down (draining)"); +} + +async fn healthz() -> axum::Json { + axum::Json(serde_json::json!({ "status": "ok", "service": "pc-gateway" })) +} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs b/powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs new file mode 100644 index 0000000000..fd2499faee --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs @@ -0,0 +1,77 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 网关中间件链(chain/filter)。 +//! +//! 设计对齐 PC 的 HttpResourceLimits / HttpRequestId / 观测栈分层思路: +//! 每个功能是一个实现 `GatewayMiddleware` 的小结构,启动时按序注册, +//! `apply_chain` 反向挂到 axum(先注册 = 越靠外层)。新增功能(限流、 +//! 指标、OTel、熔断……)只需增加一个结构体 + 一行注册。 + +use axum::{ + extract::Request, + http::{HeaderName, StatusCode}, + middleware::Next, + response::{IntoResponse, Response}, + Json, +}; +use std::pin::Pin; + +use std::future::Future; +use std::sync::Arc; + +pub mod request_id; +pub use request_id::RequestId; +pub mod resource_limits; +pub use resource_limits::ResourceLimits; + + +pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-powercontext-request-id"); + +/// 一个中间件 = 请求进入时的一段处理 + 调用后续链。 +/// 约定:中间件不得消费 body(body 归 ingress/代理所有)。 +/// handle 返回 boxed future 以保持 dyn 兼容(可装进 Vec 动态组合)。 +pub trait GatewayMiddleware: Send + Sync + 'static { + /// 名称(日志/指标用)。 + fn name(&self) -> &'static str; + + fn handle<'a>( + &'a self, + req: Request, + next: Next, + ) -> Pin + Send + 'a>>; +} + + +/// 把中间件链挂到 Router 的外层。 +/// axum 的 layer 语义:后挂的先执行;这里让 `chain[0]` 成为最外层, +/// 与注册顺序直觉一致。 +pub fn apply_chain(mut router: axum::Router, chain: Vec>) -> axum::Router { + for mw in chain.into_iter().rev() { + router = router.layer(axum::middleware::from_fn(move |req, next| { + let mw = mw.clone(); + async move { mw.handle(req, next).await } + })); + } + router +} + +/// 统一的简单错误响应。 +pub(crate) fn reject(status: StatusCode, code: &str, detail: impl Into) -> Response { + ( + status, + Json(serde_json::json!({ "error": code, "detail": detail.into() })), + ) + .into_response() +} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs b/powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs new file mode 100644 index 0000000000..3177405aa6 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs @@ -0,0 +1,68 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 请求 ID:透传客户端的 X-PowerContext-Request-ID 或生成新 ID, +//! 注入请求扩展(供 handler/日志取用)并回写到响应头。 +//! 对齐 PC 的 HttpRequestIdMiddleware,贯通排障链路。 + +use super::{GatewayMiddleware, REQUEST_ID_HEADER}; +use axum::{extract::Request, middleware::Next, response::Response}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; + +static SEQUENCE: AtomicU64 = AtomicU64::new(0); + +pub struct RequestId; + +fn generate() -> String { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed); + format!("gw-{ts:x}-{seq:06x}") +} + +impl GatewayMiddleware for RequestId { + fn name(&self) -> &'static str { + "request_id" + } + + fn handle<'a>( + &'a self, + mut req: Request, + next: Next, + ) -> Pin + Send + 'a>> { + Box::pin(async move { + let id = req + .headers() + .get(&REQUEST_ID_HEADER) + .and_then(|v| v.to_str().ok()) + .filter(|v| !v.is_empty() && v.len() <= 128 && v.chars().all(|c| c.is_ascii_graphic())) + .map(|v| v.to_string()) + .unwrap_or_else(generate); + // 注入扩展 + 当前 span,供后续 handler 与日志关联。 + req.extensions_mut().insert(id.clone()); + tracing::Span::current().record("request_id", &id); + let mut resp = next.run(req).await; + if resp.headers().get(&REQUEST_ID_HEADER).is_none() { + if let Ok(v) = axum::http::HeaderValue::from_str(&id) { + resp.headers_mut().insert(REQUEST_ID_HEADER, v); + } + } + resp + }) + } +} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs b/powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs new file mode 100644 index 0000000000..b194e00c49 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs @@ -0,0 +1,99 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 资源限流:请求体上限 + 并发上限(对齐 PC 的 HttpResourceLimitsMiddleware)。 +//! 最外层准入——被拒请求不消耗内层任何资源。/healthz 豁免并发限制 +//! (编排系统探活不应因业务拥堵被拒)。 + +use super::{reject, GatewayMiddleware}; +use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; +use tokio::sync::Semaphore; + +pub struct ResourceLimits { + max_body_bytes: usize, + max_concurrent: Arc, + /// 被拒计数(无正文证据)。 + rejected_body: AtomicU64, + rejected_concurrency: AtomicU64, +} + +impl ResourceLimits { + pub fn new(max_body_bytes: usize, max_concurrent: usize) -> Arc { + Arc::new(Self { + max_body_bytes, + max_concurrent: Arc::new(Semaphore::new(max_concurrent)), + rejected_body: AtomicU64::new(0), + rejected_concurrency: AtomicU64::new(0), + }) + } +} + +impl GatewayMiddleware for ResourceLimits { + fn name(&self) -> &'static str { + "resource_limits" + } + + fn handle<'a>( + &'a self, + req: Request, + next: Next, + ) -> Pin + Send + 'a>> { + Box::pin(async move { + // 1) 请求体上限:优先用 Content-Length 预检(零拷贝拒绝)。 + if let Some(len) = req + .headers() + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + { + if len > self.max_body_bytes { + self.rejected_body.fetch_add(1, Ordering::Relaxed); + tracing::warn!(bytes = len, limit = self.max_body_bytes, "request body rejected"); + return reject( + StatusCode::PAYLOAD_TOO_LARGE, + "request_body_too_large", + format!("body {len} bytes exceeds limit {}", self.max_body_bytes), + ); + } + } + + // 2) 并发上限:非阻塞获取;占满即拒(不排队——排队会把内存压力换成延迟压力)。 + let is_health = req.uri().path() == "/healthz"; + let permit = if is_health { + None + } else { + match self.max_concurrent.clone().try_acquire_owned() { + Ok(p) => Some(p), + Err(_) => { + self.rejected_concurrency.fetch_add(1, Ordering::Relaxed); + tracing::warn!("concurrency limit reached, rejecting"); + return reject( + StatusCode::SERVICE_UNAVAILABLE, + "concurrency_limit", + "gateway at max concurrent requests", + ); + } + } + }; + + let resp = next.run(req).await; + drop(permit); // 显式归还(作用域结束也会归还,这里表达意图) + resp + }) + } +} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/proxy.rs b/powercontext/gateway/crates/pc-gateway-app/src/proxy.rs new file mode 100644 index 0000000000..ad098870a1 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-app/src/proxy.rs @@ -0,0 +1,163 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 端口接管代理:非 `/gateway/*` 的流量原样转发到 Python 的 UDS。 +//! 原 Core/MCP 路由由此透传;流式(SSE/分块)由 hyper 客户端透传保证。 + +use crate::AppState;use axum::body::Body; +use axum::extract::{Request, State}; +use axum::http::{HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; +use hyper::Uri as HyperUri;use hyper_util::client::legacy::Client; +use hyper_util::rt::{TokioExecutor, TokioIo}; +use std::future::Future; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; +use tokio::net::UnixStream; + +pub type SharedProxy = (Arc, ProxyState); + +#[derive(Clone)] +pub struct ProxyState { + inner: Option>, +} + +struct ProxyInner { + socket: PathBuf, + client: Client, +} + +impl ProxyState { + pub fn from_env() -> Self { + match std::env::var("PC_GATEWAY_CORE_UDS") { + Ok(sock) => { + let client = Client::builder(TokioExecutor::new()) + .build(UnixConnector { socket: PathBuf::from(&sock) }); + tracing::info!(%sock, "proxy: forwarding non-gateway routes to Python UDS"); + Self { + inner: Some(Arc::new(ProxyInner { + socket: PathBuf::from(sock), + client, + })), + } + } + Err(_) => { + tracing::info!("proxy: no UDS configured; standalone mode"); + Self { inner: None } + } + } + } +} + +/// UDS 连接器:忽略 URI,始终连配置的 socket 路径。 +/// 实现 tower Service(hyper-util legacy Client 的 Connect 约束)。 +#[derive(Clone)] +struct UnixConnector { + socket: PathBuf, +} + +impl tower::Service for UnixConnector { + type Response = TokioIo; + type Error = std::io::Error; + type Future = Pin> + Send>>; + + fn poll_ready( + &mut self, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + + fn call(&mut self, _uri: HyperUri) -> Self::Future { + let path = self.socket.clone(); + Box::pin(async move { + UnixStream::connect(path) + .await + .map(TokioIo::new) + }) + } +} + +pub async fn fallback(State((_, proxy)): State, req: Request) -> Response { + let Some(inner) = proxy.inner else { + return ( + StatusCode::NOT_FOUND, + axum::Json(serde_json::json!({ + "error": "not_found", + "hint": "standalone mode: only /gateway/v1 and /healthz are served", + })), + ) + .into_response(); + }; + + let (parts, body) = req.into_parts(); + // hyper legacy client 要求绝对 URI;UDS 连接器忽略 host,用占位 authority。 + let path_q = parts + .uri + .path_and_query() + .cloned() + .unwrap_or_else(|| "/".parse().expect("root uri")); + let uri = HyperUri::builder() + .scheme("http") + .authority("powercontext.internal") + .path_and_query(path_q) + .build() + .unwrap_or_else(|_| HyperUri::default()); + + let mut fwd = hyper::Request::builder() + .method(parts.method) + .uri(uri) + .header("host", HeaderValue::from_static("powercontext")); + if let Some(headers) = fwd.headers_mut() { + *headers = parts.headers; + if !headers.contains_key("host") { + headers.insert("host", HeaderValue::from_static("powercontext")); + } + } + let hyper_req = match fwd.body(body) { + Ok(r) => r, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + axum::Json(serde_json::json!({ "error": "bad_request", "detail": e.to_string() })), + ) + .into_response() + } + }; + + let _ = inner.socket; // socket 路径已注入连接器 + match inner.client.request(hyper_req).await { + Ok(resp) => { + let (rparts, rbody) = resp.into_parts(); + let mut response = Response::builder().status(rparts.status); + if let Some(h) = response.headers_mut() { + *h = rparts.headers; + } + response + .body(Body::new(rbody)) + .unwrap_or_else(|e| { + (StatusCode::BAD_GATEWAY, format!("proxy build: {e}")).into_response() + }) + } + Err(e) => ( + StatusCode::BAD_GATEWAY, + axum::Json(serde_json::json!({ + "error": "core_unreachable", + "detail": e.to_string(), + })), + ) + .into_response(), + } +} diff --git a/powercontext/gateway/crates/pc-gateway-core/Cargo.toml b/powercontext/gateway/crates/pc-gateway-core/Cargo.toml new file mode 100644 index 0000000000..f92693d763 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/Cargo.toml @@ -0,0 +1,33 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-core" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: executor state machine — input/check → render → send → output/check → release" + +[dependencies] +pc-gateway-types = { workspace = true } +pc-gateway-protocol = { workspace = true } +pc-gateway-transport = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +reqwest = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-core/src/executor.rs b/powercontext/gateway/crates/pc-gateway-core/src/executor.rs new file mode 100644 index 0000000000..78ac88f4fb --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/src/executor.rs @@ -0,0 +1,402 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{GateClient, GateError}; +use pc_gateway_evidence::EvidenceSink; +use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; +use pc_gateway_transport::{AdmittedSend, BoundedRetry, RetryOutcome, SendOutcome, Transport}; +use pc_gateway_types::{ + CaptureContentSourceRequest, CheckDecision, ContextCheckRequest, ContextCheckResult, + ModelJsonPayload, ModelJsonTextLocation, PreparedContextLocation, PrepareContextRequest, +}; +use std::collections::BTreeMap; +use std::num::NonZeroU32; + +/// Gate 不可用时的策略(PR #2199 故障语义): +/// Pause —— 必需强制检查不可用:不发送(默认,安全立场); +/// PassthroughWithoutMemory —— 增强类调用可降级(仅限 capabilities.enforcing=false)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DegradePolicy { + #[default] + Pause, + PassthroughWithoutMemory, +} + +/// 宿主交给执行器的完整输入:已授权历史 + 当前请求 + 目标。 +pub struct ManagedCall { + pub scope_id: String, + pub target_profile: String, + pub request: CanonicalRequest, + pub target_url: String, + /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 + pub headers: Vec<(String, String)>, + pub degrade_policy: DegradePolicy, + /// 是否调 prepare 注入上下文(v1 仅 chat 格式;PC 决定内容,网关只放置)。 + pub inject_context: bool, + /// 是否在过检后同步沉淀本轮对话(capture_content_source,毫秒级落库)。 + pub sediment: bool, + /// 注入块位置声明,随 before_send 送检。 + pub prepared_contexts: Vec, +} + +/// 执行结果:要么是过检放行的内容,要么是显式拒绝/不确定。 +/// 不存在“静默成功”或“伪装成空结果”的路径。 +#[derive(Debug)] +pub enum ManagedOutcome { + /// before_release 的 allow:绑定与过检内容一起返回。 + Released { + binding: Option, + status: u16, + content_type: String, + body: bytes::Bytes, + }, + /// Core 明确拒绝(两阶段的 block),携带无正文原因类别。 + Blocked { reason_codes: Vec }, + /// Core 暂缓。PR #2264 的 withhold 不含渲染计划,一律按终态处理。 + Withheld { reason_codes: Vec }, + /// 可能已到达上游;不自动付费重发。 + SendIndeterminate, + /// 全部尝试确定性未送达。 + NotSent { attempts: u32 }, + /// Gate 不可用:暂停,不是失败放行。 + GatePaused(String), + /// 无记忆直通降级:未经检查发送(仅限未启用强制规则的部署), + /// 响应头/证据必须显式标记,不得伪装成过检结果。 + Degraded { + status: u16, + content_type: String, + body: bytes::Bytes, + }, +} + +pub struct Executor { + gate: G, + retry: BoundedRetry, +} + +impl Executor +where + G: GateClient, + T: Transport, +{ + pub fn new(gate: G, transport: T, max_attempts: NonZeroU32) -> Self { + Self { + gate, + retry: BoundedRetry::new(transport, max_attempts), + } + } + + /// 一次托管调用。渲染器按请求传入:入口格式即上游格式(同格式进出)。 + pub async fn run( + &self, + call: ManagedCall, + renderer: &R, + evidence: &dyn EvidenceSink, + ) -> ManagedOutcome { + let mut call = call; + if call.inject_context { + // 注入是增强类调用:失败不阻塞主链路(不注入、不声明区间)。 + self.enrich(&mut call, evidence).await; + } + // 渲染完整最终字节(不含缓存计划:PR #2264 的 withhold 未携带渲染计划)。 + let payload = match renderer.render(&call.request, None) { + Ok(p) => p, + Err(e) => { + return ManagedOutcome::Blocked { + reason_codes: vec![format!("render_failed:{e}")], + } + } + }; + // 送检内容必须与发送字节严格一致:拒绝有损转换(防“检查≠发送”缝隙)。 + // 渲染器输出本应恒为合法 UTF-8,非法即契约违约,阻断而非降级。 + let payload_body = match String::from_utf8(payload.bytes.clone().to_vec()) { + Ok(text) => text, + Err(_) => { + return ManagedOutcome::Blocked { + reason_codes: vec!["invalid_payload_encoding".into()], + } + } + }; + let model_payload = ModelJsonPayload::new( + content_headers(&call.headers, payload.content_type), + payload_body, + ); + + let check = ContextCheckRequest::BeforeSend { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + payload: model_payload, + prepared_contexts: call.prepared_contexts.clone(), + }; + + let binding = match self.gate.check(check).await { + Err(e) => { + // #2199 语义:降级仅适用于 Core「不可用」。Malformed 表示 Core 可达但 + // 响应异常(版本错乱/被篡改/代理污染)——恰恰最不该绕过检查,一律暂停。 + return match (e, call.degrade_policy) { + ( + GateError::GateUnavailable(_), + DegradePolicy::PassthroughWithoutMemory, + ) => self.degraded_send(&call, payload.bytes, evidence).await, + (e, _) => ManagedOutcome::GatePaused(classify_gate_error(e)), + } + } + Ok(result) => match result.decision { + CheckDecision::Allow => unwrap_binding(result), + CheckDecision::Block => { + return ManagedOutcome::Blocked { + reason_codes: result.reason_codes, + } + } + CheckDecision::Withhold => { + return ManagedOutcome::Withheld { + reason_codes: result.reason_codes, + } + } + }, + }; + + let send = AdmittedSend { + binding, + payload: payload.bytes, + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }; + let send_ref = send.clone(); + + let raw = match self.retry.send_with_retry(&send, evidence).await { + RetryOutcome::AllNotSent { attempts } => return ManagedOutcome::NotSent { attempts }, + RetryOutcome::Done(SendOutcome::Indeterminate(_)) => { + return ManagedOutcome::SendIndeterminate + } + RetryOutcome::Done(SendOutcome::NotSent(_)) => { + unreachable!("BoundedRetry never returns Done(NotSent)") + } + RetryOutcome::Done(SendOutcome::Delivered(raw)) => raw, + }; + + // strict:完整原始响应先过 before_release,通过前不释放任何内容。 + // 上游响应不受我们控制:非 UTF-8 字节不做有损转换送检(那会导致 + // “批准的是替换后文本、交付的是原始字节”的保真缺口),直接不放行。 + let release_body = match String::from_utf8(raw.body.clone().to_vec()) { + Ok(text) => text, + Err(_) => { + return ManagedOutcome::Withheld { + reason_codes: vec!["invalid_response_encoding".into()], + } + } + }; + let release_check = ContextCheckRequest::BeforeRelease { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + request_binding: send_ref.binding.clone(), + payload: ModelJsonPayload::new( + // 契约要求 headers 至少 1 项;携带上游实际 Content-Type。 + BTreeMap::from([("content-type".to_string(), raw.content_type.clone())]), + release_body.clone(), + ), + completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.into(), + }; + match self.gate.check(release_check).await { + Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), + Ok(result) => match result.decision { + CheckDecision::Allow => { + // 沉淀:同步、best-effort(失败仅记证据,不影响交付)。 + // 内容只含本轮 user 文本与过检响应——被拦/降级轮次不沉淀。 + if call.sediment { + let transcript = serde_json::json!({ + "kind": "gateway_turn", + "user": call.request.messages.iter() + .rev().find(|m| matches!(m.role, pc_gateway_protocol::Role::User)) + .and_then(|m| match m.content.as_slice() { + [serde_json::Value::String(s)] => Some(s.clone()), + _ => None, + }).unwrap_or_default(), + "assistant": release_body.clone(), + "model": call.request.model, + }); + let digest = result.binding.as_deref() + .map(simple_digest) + .unwrap_or_else(|| simple_digest(&release_body)); + let capture = CaptureContentSourceRequest { + scope_id: call.scope_id.clone(), + source_id: format!("gw-turn-{digest}"), + content: transcript.to_string(), + metadata: Some(serde_json::json!({ + "kind": "gateway_turn", + "target_profile": call.target_profile, + })), + }; + if let Err(e) = self.gate.capture(capture).await { + evidence.record_not_sent(0, &format!("sediment_failed:{e}")); + } + } + ManagedOutcome::Released { + binding: result.binding, + status: raw.status, + content_type: raw.content_type.clone(), + body: raw.body, + } + } + CheckDecision::Block => { + // 不释放任何内容;尽力取消上游,只保留无正文失败证据。 + self.retry.transport().cancel(&send_ref).await; + ManagedOutcome::Blocked { + reason_codes: result.reason_codes, + } + } + CheckDecision::Withhold => ManagedOutcome::Withheld { + reason_codes: result.reason_codes, + }, + }, + } + } + + /// 注入(放置与声明,非检索):调 prepare → 标准块包裹 → 拼进最后一条 + /// user 消息头部 → 计算字节区间。任一步失败则保持原样(不注入、不声明)。 + async fn enrich(&self, call: &mut ManagedCall, evidence: &dyn EvidenceSink) { + // 取最后一条 user 消息的纯文本作为检索词;非单字符串 content 不注入(v1)。 + let Some(query) = last_user_text(&call.request) else { + return; + }; + let prepared = match self + .gate + .prepare(PrepareContextRequest { + scope_id: call.scope_id.clone(), + query, + max_bytes: 8192, + include_reuse: true, + }) + .await + { + Ok(p) => p, + Err(e) => { + evidence.record_not_sent(0, &format!("prepare_failed:{e}")); + return; + } + }; + let (Some(content), Some(binding)) = (prepared.content(), prepared.binding()) else { + return; // empty:不注入任何标记(空块会污染前缀且无 binding 可声明) + }; + if content.is_empty() { + return; + } + // PC 返回的 content 已是标准注入格式(信任前言 + 标记包裹块)。 + // 必须原样注入:check 会校验区间字节摘要 == sha256(content), + // 网关任何增删(包括再包裹)都会导致 digest 不匹配被暂缓。 + let block = content.to_string(); + let Some(index) = last_user_index(&call.request) else { return }; + let Some(message) = call.request.messages.get_mut(index) else { return }; + let original = match message.content.as_slice() { + [serde_json::Value::String(s)] => s.clone(), + _ => return, + }; + let new_text = format!("{block}\n\n{original}"); + message.content = vec![serde_json::Value::String(new_text)]; + call.prepared_contexts.push(PreparedContextLocation { + binding: binding.to_string(), + location: ModelJsonTextLocation { + schema: pc_gateway_types::MODEL_JSON_TEXT_LOCATION_SCHEMA.to_string(), + // chat 线格式:content 为纯字符串,指针用无部件形态。 + pointer: format!("/messages/{index}/content"), + start_byte: 0, + // UTF-8 字节数(非字符数);区间必须落在字符边界(块整体是合法 UTF-8,天然满足)。 + end_byte: block.len() as u64, + }, + }); + } + + /// 降级直通:未经检查发送。显式标记,不做释放检查。 + async fn degraded_send( + &self, + call: &ManagedCall, + payload: bytes::Bytes, + evidence: &dyn EvidenceSink, + ) -> ManagedOutcome { + evidence.record_not_sent(0, "degraded_passthrough"); + let send = AdmittedSend { + binding: "degraded-passthrough".into(), + payload, + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }; + match self.retry.send_with_retry(&send, evidence).await { + RetryOutcome::AllNotSent { attempts } => ManagedOutcome::NotSent { attempts }, + RetryOutcome::Done(SendOutcome::Indeterminate(_)) => ManagedOutcome::SendIndeterminate, + RetryOutcome::Done(SendOutcome::NotSent(_)) => { + unreachable!("BoundedRetry never returns Done(NotSent)") + } + RetryOutcome::Done(SendOutcome::Delivered(raw)) => ManagedOutcome::Degraded { + status: raw.status, + content_type: raw.content_type, + body: raw.body, + }, + } + } +} + +fn unwrap_binding(result: ContextCheckResult) -> String { + result + .binding + .unwrap_or_else(|| "missing-binding".to_string()) +} + +/// 载荷头只保留内容/协议头;凭据与传输覆盖头禁止进 check 载荷。 +fn content_headers(headers: &[(String, String)], content_type: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + out.insert("content-type".to_string(), content_type.to_string()); + for (k, v) in headers { + let lower = k.to_ascii_lowercase(); + if matches!(lower.as_str(), "authorization" | "x-api-key" | "cookie") { + continue; + } + out.insert(lower, v.clone()); + } + out +} + +fn classify_gate_error(e: GateError) -> String { + match e { + GateError::GateUnavailable(msg) | GateError::Malformed(msg) => msg, + } +} + +/// 最后一条 user 消息下标(渲染保持消息顺序,与线格式下标一致)。 +fn last_user_index(request: &CanonicalRequest) -> Option { + request + .messages + .iter() + .rposition(|m| matches!(m.role, pc_gateway_protocol::Role::User)) +} + +fn last_user_text(request: &CanonicalRequest) -> Option { + let i = last_user_index(request)?; + match request.messages[i].content.as_slice() { + [serde_json::Value::String(s)] => Some(s.clone()), + _ => None, + } +} + +/// 稳定短摘要(幂等键用;非安全用途,无需密码学强度)。 +fn simple_digest(input: &str) -> String { + // FNV-1a 64 位,输出 16 hex —— 足够做 source_id 的幂等区分。 + let mut hash: u64 = 0xcbf29ce484222325; + for b in input.as_bytes() { + hash ^= *b as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + format!("{hash:016x}") +} diff --git a/powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs b/powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs new file mode 100644 index 0000000000..144eca6a1b --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs @@ -0,0 +1,58 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use std::future::Future; + +/// Core 检查的客户端抽象(PR #2199:单端点两阶段契约)。 +/// 实现:TCP(独立部署形态)或 UDS(同机组合部署形态); +/// 嵌入式实现直接进程内调用等价算法。 +/// +/// Gate 不可用 → `GateUnavailable`。是否降级为无记忆直通由调用方 +/// 的 `DegradePolicy` 决定(仅对未配置强制规则的 Scope 允许)。 +pub trait GateClient: Send + Sync { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send; + + /// GET_CAPABILITIES 能力发现:获知支持的模式、必需规则、可降级性等。 + fn capabilities( + &self, + ) -> impl Future> + Send; + + /// PREPARE_CONTEXT:检索并装配注入内容(智力全在 Core;网关只放置)。 + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send; + + /// CAPTURE_CONTENT_SOURCE:沉淀一轮过检对话(同步落库;提取在 PC 后台)。 + /// best-effort:失败只记证据,不影响已过检响应的交付语义。 + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send; +} + +#[derive(Debug, thiserror::Error)] +pub enum GateError { + #[error("gate unavailable: {0}")] + GateUnavailable(String), + #[error("gate response malformed: {0}")] + Malformed(String), +} diff --git a/powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs new file mode 100644 index 0000000000..9499eede79 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -0,0 +1,123 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{GateClient, GateError}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use serde::de::DeserializeOwned; +use serde::Serialize; + +/// 独立部署形态:HTTPS/TCP 直连 PowerContext Server 的公开契约。 +/// 同机组合部署用 `UdsGateClient`(HTTP over Unix Domain Socket)。 +#[derive(Debug, Clone)] +pub struct HttpGateClient { + base_url: String, + client: reqwest::Client, + /// Server 认证令牌(POWERCONTEXT_SERVER_AUTH_TOKEN);None 时不带认证头。 + token: Option, +} + +impl HttpGateClient { + pub fn new(base_url: impl Into) -> Self { + Self::with_token(base_url, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) + } + + pub fn with_token(base_url: impl Into, token: Option) -> Self { + Self { + base_url: base_url.into().trim_end_matches('/').to_string(), + // 同一原则:获准目的地 = 实际目的地;3xx 原样上抛,不自动跟随。 + client: reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .expect("reqwest client build"), + token: token.filter(|t| !t.is_empty()), + } + } + + async fn post(&self, path: &str, body: &impl Serialize) -> Result + where + R: DeserializeOwned, + { + let url = format!("{}{}", self.base_url, path); + let resp = self + .client + .post(&url) + // RFC:DTO 复用 scope-mode/access 声明头。 + .header("x-powercontext-scope-mode", "current") + .bearer_auth(self.token.clone().unwrap_or_default()) + .header("content-type", "application/json") + .json(body) + .send() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + let status = resp.status(); + if !status.is_success() { + return Err(GateError::GateUnavailable(format!( + "gate returned HTTP {status}" + ))); + } + let bytes = resp + .bytes() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + serde_json::from_slice(&bytes) + .map_err(|e| GateError::Malformed(format!("decode {path}: {e}"))) + } +} + +impl GateClient for HttpGateClient { + async fn check( + &self, + request: ContextCheckRequest, + ) -> Result { + self.post("/v1/context/check", &request).await + } + + async fn capabilities(&self) -> Result { + let url = format!("{}/v1/capabilities", self.base_url); + let resp = self + .client + .get(&url) + .header("x-powercontext-scope-mode", "current") + .bearer_auth(self.token.clone().unwrap_or_default()) + .send() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + let status = resp.status(); + if !status.is_success() { + return Err(GateError::GateUnavailable(format!( + "capabilities HTTP {status}" + ))); + } + resp.json() + .await + .map_err(|e| GateError::Malformed(e.to_string())) + } + + async fn prepare( + &self, + request: PrepareContextRequest, + ) -> Result { + self.post("/v1/context/prepare", &request).await + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + self.post("/v1/sources/content", &request).await + } +} diff --git a/powercontext/gateway/crates/pc-gateway-core/src/lib.rs b/powercontext/gateway/crates/pc-gateway-core/src/lib.rs new file mode 100644 index 0000000000..35509e6b2a --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/src/lib.rs @@ -0,0 +1,36 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 执行器核心:一次托管调用的状态机。 +//! +//! 对应 RFC「一次托管调用」时序图(PR #2199 两阶段检查形态): +//! +//! ```text +//! 宿主完整输入 ─► check(before_send) ─┬─ allow ─► 发送 ─► 原始响应 ─► check(before_release) ─┬─ release ─► 返回 +//! ├─ withhold(渲染计划) ─► 只渲染获准字段 ─► 复检(最多一次) +//! └─ block ──────────────────────────────────────────┴─ refuse ──► 显式拒绝 +//! ``` +//! +//! 网关无策略:每一步的裁决都来自 `GateClient`(check API 或嵌入式等价物), +//! 本 crate 只负责把裁决串成正确的控制流,并守住失败语义。 + +mod executor; +mod gate_client; +mod http_gate_client; +mod uds_gate_client; + +pub use executor::*; +pub use gate_client::*; +pub use http_gate_client::*; +pub use uds_gate_client::*; diff --git a/powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs new file mode 100644 index 0000000000..4dede09804 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -0,0 +1,418 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 同机组合部署形态:HTTP over Unix Domain Socket。 +//! +//! PR #2199:启用后 Rust 独占公网 TCP 端口,Python 只监听本机 UDS; +//! 网关的 check/capabilities 都走这个通道。 +//! +//! 连接按对端(唯一的 socket 路径)池化:keep-alive 复用空闲连接, +//! 池有上限;connect/read 均有超时,防止对端假死导致请求悬挂。 +//! 认证与 TCP 形态一致(UDS 不替代 bearer 认证)。 + +use crate::{GateClient, GateError}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf}; +use tokio::net::UnixStream; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); +const READ_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_IDLE_CONNECTIONS: usize = 8; +const MAX_HEADER_BYTES: usize = 64 * 1024; +const MAX_BODY_BYTES: usize = 8 * 1024 * 1024; + +#[derive(Clone)] +pub struct UdsGateClient { + socket: PathBuf, + token: Option, + pool: Arc>>, +} + +impl std::fmt::Debug for UdsGateClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("UdsGateClient") + .field("socket", &self.socket) + .field("token", &self.token.as_ref().map(|_| "..")) + .field("idle", &self.pool.lock().map(|p| p.len()).unwrap_or(0)) + .finish() + } +} + +impl UdsGateClient { + pub fn new(socket: impl Into) -> Self { + Self::with_token(socket, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) + } + + pub fn with_token(socket: impl Into, token: Option) -> Self { + Self { + socket: socket.into(), + token: token.filter(|t| !t.is_empty()), + pool: Arc::new(Mutex::new(Vec::new())), + } + } + + fn take_idle(&self) -> Option { + self.pool.lock().ok()?.pop() + } + + fn return_idle(&self, stream: UnixStream) { + if let Ok(mut pool) = self.pool.lock() { + if pool.len() < MAX_IDLE_CONNECTIONS { + pool.push(stream); + } + } + } + + /// 发送单次 HTTP/1.1 请求;keep-alive 下连接归还池中复用。 + /// + /// 对端(uvicorn)会关闭空闲超时的 keep-alive 连接;本地 `writable()` + /// 探活发现不了这种半关闭。因此池中借出的连接若在收到任何响应前 + /// 失败(broken pipe / EOF),丢弃该连接并用新连接重试一次。 + async fn request( + &self, + method: &str, + path: &str, + body: Option<&[u8]>, + ) -> Result<(u16, Vec), GateError> { + let mut from_pool = true; // 首次也允许重试一次(对端重启场景) + for _ in 0..2 { + match self.request_once(method, path, body, from_pool).await { + Ok(x) => return Ok(x), + Err(e) if retryable(&e) => { + from_pool = false; // 下一次强制新建连接 + continue; + } + Err(e) => return Err(e), + } + } + Err(GateError::GateUnavailable("uds exhausted retry".into())) + } + + async fn request_once( + &self, + method: &str, + path: &str, + body: Option<&[u8]>, + prefer_pool: bool, + ) -> Result<(u16, Vec), GateError> { + let mut leased = LeasedConnection::new(self.clone()); + let stream = leased + .acquire(prefer_pool) + .await + .map_err(|e| { + GateError::GateUnavailable(format!("uds connect {}: {e}", self.socket.display())) + })?; + let (mut rd, mut wr) = tokio::io::split(stream); + + let body = body.unwrap_or(&[]); + let mut head = format!( + "{method} {path} HTTP/1.1\r\nHost: powercontext\r\nContent-Type: application/json\r\n\ + x-powercontext-scope-mode: current\r\nContent-Length: {}\r\n", + body.len() + ); + if let Some(t) = &self.token { + head.push_str(&format!("Authorization: Bearer {t}\r\n")); + } + head.push_str("Connection: keep-alive\r\n\r\n"); + + let write = async { + wr.write_all(head.as_bytes()).await?; + wr.write_all(body).await + }; + tokio::time::timeout(READ_TIMEOUT, write) + .await + .map_err(|_| GateError::GateUnavailable("uds write timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds write: {e}")))?; + + let (status, body, reusable) = read_response(&mut rd).await?; + if reusable { + leased.release(rd, wr); + } + Ok((status, body)) + } +} + +/// 从池中租借/归还连接。出错时不归还(连接状态不可信)。 +struct LeasedConnection { + client: UdsGateClient, + returned: bool, +} + +impl LeasedConnection { + fn new(client: UdsGateClient) -> Self { + Self { + client, + returned: false, + } + } + + async fn acquire(&mut self, prefer_pool: bool) -> std::io::Result { + // 先试空闲连接;真正的失效(对端已关闭)会在读写时报错, + // 由上层的单次重试兜底。 + if prefer_pool { + if let Some(idle) = self.client.take_idle() { + if idle.writable().await.is_ok() { + return Ok(idle); + } + } + } + tokio::time::timeout(CONNECT_TIMEOUT, UnixStream::connect(&self.client.socket)) + .await + .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "uds connect timeout"))? + } + + /// 仅在读到完整响应且连接可复用时调用。 + fn release(&mut self, rd: ReadHalf, wr: WriteHalf) { + if self.returned { + return; + } + let stream = rd.unsplit(wr); + self.client.return_idle(stream); + self.returned = true; + } +} + +/// 读取完整 HTTP/1.1 响应。返回 (status, body, 连接是否可复用)。 +async fn read_response(rd: &mut ReadHalf) -> Result<(u16, Vec, bool), GateError> { + let mut buf: Vec = Vec::with_capacity(8 * 1024); + let header_end = loop { + if let Some(pos) = find_terminator(&buf) { + break pos; + } + if buf.len() > MAX_HEADER_BYTES { + return Err(GateError::Malformed("uds header too large".into())); + } + let n = read_with_timeout(rd, &mut buf, 4096).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed before headers".into())); + } + }; + + let head = String::from_utf8_lossy(&buf[..header_end]).into_owned(); + let mut lines = head.lines(); + let status_line = lines.next().unwrap_or_default(); + let status: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| GateError::Malformed(format!("bad status line: {status_line}")))?; + + let mut content_length: Option = None; + let mut chunked = false; + let mut keep_alive = true; // HTTP/1.1 默认 keep-alive + for line in lines { + let Some((k, v)) = line.split_once(':') else { continue }; + let k = k.trim().to_ascii_lowercase(); + let v = v.trim(); + match k.as_str() { + "content-length" => content_length = v.parse().ok(), + "transfer-encoding" if v.to_ascii_lowercase().contains("chunked") => chunked = true, + "connection" if v.to_ascii_lowercase().contains("close") => keep_alive = false, + _ => {} + } + } + + let mut rest = buf.split_off(header_end + 4); + let body = if chunked { + // chunked:读完 0-chunk 后必须消费 trailer(至少终止空行), + // 否则残留字节会污染复用连接上的下一个响应。 + let (decoded, trailer_clean) = read_chunked(rd, &mut rest).await?; + if !trailer_clean { + keep_alive = false; // trailer 未完整消费,连接不可复用 + } + decoded + } else { + let len = content_length.unwrap_or(rest.len()); + if rest.len() < len { + read_more(rd, &mut rest, len).await?; + rest + } else if rest.len() > len { + // 超出声明长度:缓冲里有不属于本响应的字节(串包/残留), + // 截断正文,且连接不可复用。 + rest.truncate(len); + keep_alive = false; + rest + } else { + rest + } + }; + if body.len() > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } + Ok((status, body, keep_alive)) +} + +async fn read_more( + rd: &mut ReadHalf, + buf: &mut Vec, + target: usize, +) -> Result<(), GateError> { + while buf.len() < target { + let n = read_with_timeout(rd, buf, 8192).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-body".into())); + } + } + Ok(()) +} + +/// 解码 chunked 编码。返回 (body, trailer 是否完整消费)。 +async fn read_chunked( + rd: &mut ReadHalf, + buf: &mut Vec, +) -> Result<(Vec, bool), GateError> { + let mut out = Vec::new(); + loop { + // 找一行作为 chunk size。 + let line_end = loop { + if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { + break pos; + } + let n = read_with_timeout(rd, buf, 4096).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-chunk".into())); + } + }; + let size_str = String::from_utf8_lossy(&buf[..line_end]).into_owned(); + buf.drain(..line_end + 2); + let size = usize::from_str_radix(size_str.trim().split(';').next().unwrap_or("0"), 16) + .map_err(|_| GateError::Malformed(format!("bad chunk size: {size_str}")))?; + if size == 0 { + // 消费 trailer:连续读到空行(或读尽缓冲且对端无更多数据)。 + loop { + if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { + let line = String::from_utf8_lossy(&buf[..pos]).into_owned(); + buf.drain(..pos + 2); + if line.is_empty() { + return Ok((out, true)); // trailer 结束空行 + } + continue; // trailer 头部行 + } + match read_with_timeout(rd, buf, 1024).await { + Ok(0) | Err(_) => return Ok((out, false)), + Ok(_) => {} + }; + } + } + let needed = size + 2; // 数据 + CRLF + while buf.len() < needed { + let n = read_with_timeout(rd, buf, 8192).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-chunk-data".into())); + } + } + out.extend_from_slice(&buf[..size]); + buf.drain(..needed); + } +} + +/// 仅“未收到任何响应字节”的传输失败才可安全重试(幂等:请求未达对端或 +/// 对端在解析前丢弃);已收到响应头的失败必须上抛。 +fn retryable(e: &GateError) -> bool { + match e { + GateError::GateUnavailable(msg) => { + (msg.contains("uds write") || msg.starts_with("uds connect")) + && !msg.contains("timeout") + } + // "uds closed before headers":对端在响应前关闭,请求未生效。 + GateError::Malformed(msg) => msg.contains("closed before headers"), + } +} + +/// 超时读取一块数据追加到 buf,返回读取字节数(0 = 对端关闭)。 +async fn read_with_timeout( + rd: &mut ReadHalf, + buf: &mut Vec, + chunk_size: usize, +) -> Result { + let mut chunk = vec![0u8; chunk_size]; + let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) + .await + .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + buf.extend_from_slice(&chunk[..n]); + Ok(n) +} + +fn find_terminator(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +impl GateClient for UdsGateClient { + async fn check( + &self, + request: ContextCheckRequest, + ) -> Result { + let body = serde_json::to_vec(&request).expect("serialize gate request"); + let this = self.clone(); + { + let (status, body) = this.request("POST", "/v1/context/check", Some(&body)).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("gate HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode check: {e}"))) + } + } + + async fn capabilities(&self) -> Result { + let this = self.clone(); + { + let (status, body) = this.request("GET", "/v1/capabilities", None).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("capabilities HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode capabilities: {e}"))) + } + } + + async fn prepare( + &self, + request: PrepareContextRequest, + ) -> Result { + let body = serde_json::to_vec(&request).expect("serialize gate request"); + let this = self.clone(); + { + let (status, body) = this.request("POST", "/v1/context/prepare", Some(&body)).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("prepare HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode prepare: {e}"))) + } + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + let body = serde_json::to_vec(&request).expect("serialize gate request"); + let this = self.clone(); + { + let (status, body) = this.request("POST", "/v1/sources/content", Some(&body)).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!("capture HTTP {status}"))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode capture: {e}"))) + } + } +} diff --git a/powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs new file mode 100644 index 0000000000..ce91449351 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -0,0 +1,709 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! PR #2264 失败语义表的状态机级验证(真实契约形态)。 + +use pc_gateway_core::{DegradePolicy, Executor, GateClient, GateError, ManagedCall, ManagedOutcome}; +use pc_gateway_evidence::{BufferedEvidenceSink, NoopEvidenceSink}; +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OutputLimits, RenderedPayload, Role, WireRenderer, +}; +use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; +use pc_gateway_types::{ + CheckDecision, CheckPhase, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + CaptureContentSourceRequest, PrepareContextResult, PreparedContext, PreparedContextLocation, +}; +use std::collections::VecDeque; +use std::future::Future; +use std::num::NonZeroU32; +use std::sync::{Arc, Mutex}; + +// ---------- 测试替身 ---------- + +struct RecordingRenderer { + renders: Mutex, +} + +impl WireRenderer for RecordingRenderer { + fn name(&self) -> &'static str { + "test" + } + fn render( + &self, + request: &CanonicalRequest, + _plan: Option<&serde_json::Value>, + ) -> Result { + *self.renders.lock().unwrap() += 1; + let messages: Vec = request + .messages + .iter() + .map(|m| { + let content = match m.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => serde_json::json!(other), + }; + serde_json::json!({ "role": m.role, "content": content }) + }) + .collect(); + let bytes = serde_json::to_vec(&serde_json::json!({ + "model": request.model, + "messages": messages, + })) + .unwrap() + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} + +/// 脚本化检查客户端:按序弹出结果,记录请求阶段与载荷。 +struct FakeGate { + results: Mutex>>, + seen: Mutex>, + prepared_seen: Mutex>>, + prepare_result: Mutex>>, + prepare_queries: Mutex>, + captured: Mutex>, +} + +impl GateClient for FakeGate { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + let (phase, note) = match &request { + ContextCheckRequest::BeforeSend { payload, .. } => { + (CheckPhase::BeforeSend, payload.body.clone()) + } + ContextCheckRequest::BeforeRelease { + request_binding, .. + } => (CheckPhase::BeforeRelease, request_binding.clone()), + }; + let declared = match &request { + ContextCheckRequest::BeforeSend { prepared_contexts, .. } => prepared_contexts.clone(), + _ => Vec::new(), + }; + self.prepared_seen.lock().unwrap().push(declared); + self.seen.lock().unwrap().push((phase, note)); + let step = self.results.lock().unwrap().pop_front(); + async move { step.expect("gate script exhausted") } + } + + async fn capabilities(&self) -> Result { + Ok(serde_json::json!({ "enforcing": false })) + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + self.prepare_queries.lock().unwrap().push(request.query); + let step = self.prepare_result.lock().unwrap().take() + .unwrap_or(Ok(PrepareContextResult::Plain(PreparedContext { + schema: "powercontext.prepared-context.v1".into(), + status: "empty".into(), + content: None, + content_bytes: 0, + }))); + async move { step } + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + self.captured.lock().unwrap().push((request.source_id, request.content)); + Ok(serde_json::json!({"captured": true})) + } +} + +struct FakeTransport { + outcomes: Mutex>, + sends: Mutex>, + bindings: Mutex>, + cancels: Mutex, +} + +impl Transport for FakeTransport { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a { + let outcome = self.outcomes.lock().unwrap().pop_front(); + self.sends.lock().unwrap().push(send.payload); + self.bindings.lock().unwrap().push(send.binding); + async move { + outcome.unwrap_or_else(|| panic!("transport script exhausted")) + } + } + + async fn cancel(&self, _send: &AdmittedSend) { + *self.cancels.lock().unwrap() += 1; + } +} + +fn raw_response() -> SendOutcome { + SendOutcome::Delivered(pc_gateway_transport::RawResponse { + status: 200, + content_type: "application/json".into(), + ttft_ms: None, + body: bytes::Bytes::from_static(br#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#), + usage: Some(serde_json::json!({"total_tokens": 1})), + }) +} + +fn result(phase: CheckPhase, decision: CheckDecision, reasons: &[&str]) -> ContextCheckResult { + ContextCheckResult { + schema: pc_gateway_types::CONTEXT_CHECK_SCHEMA.into(), + phase, + decision, + reason_codes: reasons.iter().map(|s| s.to_string()).collect(), + coverage: pc_gateway_types::ContextCheckCoverage { + profile: "text-and-tools.v1".into(), + complete: true, + }, + policy_version: "v1".into(), + valid_until: "2999-01-01T00:00:00Z".into(), + correlate_until: None, + binding: matches!(decision, CheckDecision::Allow).then(|| "binding-1".to_string()), + } +} + +fn call(degrade: DegradePolicy) -> ManagedCall { + ManagedCall { + scope_id: "project:test".into(), + target_profile: "openai:test".into(), + request: CanonicalRequest { + model: "test-model".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hello")], + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 128, + }, + stream: false, + }, + target_url: "http://upstream.invalid/v1/chat/completions".into(), + headers: vec![("authorization".into(), "Bearer secret".into())], + degrade_policy: degrade, + inject_context: false, + sediment: false, + prepared_contexts: Vec::new(), + } +} + +#[derive(Clone)] +struct RendererRef(Arc); +impl WireRenderer for RendererRef { + fn name(&self) -> &'static str { + "test" + } + fn render( + &self, + request: &CanonicalRequest, + plan: Option<&serde_json::Value>, + ) -> Result { + WireRenderer::render(&*self.0, request, plan) + } +} + +#[derive(Clone)] +struct TransportRef(Arc); +impl Transport for TransportRef { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a { + Transport::send(&*self.0, send) + } + async fn cancel(&self, send: &AdmittedSend) { + Transport::cancel(&*self.0, send).await + } +} + +#[derive(Clone)] +struct FakeGateRef(Arc); +impl GateClient for FakeGateRef { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + GateClient::check(&*self.0, request) + } + fn capabilities( + &self, + ) -> impl Future> + Send { + GateClient::capabilities(&*self.0) + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + GateClient::prepare(&*self.0, request) + } + + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send { + GateClient::capture(&*self.0, request) + } +} + +fn harness( + gate_results: Vec>, + transport_outcomes: Vec, + max_attempts: u32, +) -> ( + Executor, + Arc, + Arc, + Arc, +) { + let renderer = Arc::new(RecordingRenderer { renders: Mutex::new(0) }); + let transport = Arc::new(FakeTransport { + outcomes: Mutex::new(transport_outcomes.into()), + sends: Mutex::new(Vec::new()), + bindings: Mutex::new(Vec::new()), + cancels: Mutex::new(0), + }); + let gate = Arc::new(FakeGate { + results: Mutex::new(gate_results.into()), + seen: Mutex::new(Vec::new()), + prepared_seen: Mutex::new(Vec::new()), + prepare_result: Mutex::new(None), + prepare_queries: Mutex::new(Vec::new()), + captured: Mutex::new(Vec::new()), + }); + let executor = Executor::new( + FakeGateRef(gate.clone()), + TransportRef(transport.clone()), + NonZeroU32::new(max_attempts).unwrap(), + ); + (executor, renderer, transport, gate) +} + +// ---------- 用例 ---------- + +#[tokio::test] +async fn allow_send_allow_release() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Released { binding, status, body, .. } => { + assert_eq!(binding.as_deref(), Some("binding-1")); + assert_eq!(status, 200); + let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(v["choices"][0]["message"]["content"], "ok"); + } + other => panic!("expected Released, got {other:?}"), + } + let seen = gate.seen.lock().unwrap().clone(); + assert_eq!(seen.len(), 2); + assert_eq!(seen[1], (CheckPhase::BeforeRelease, "binding-1".into())); + assert_eq!(transport.bindings.lock().unwrap()[0], "binding-1"); +} + +#[tokio::test] +async fn before_send_block_never_sends() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), + other => panic!("expected Blocked, got {other:?}"), + } + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn withhold_is_terminal_in_pr2264_contract() { + let (executor, renderer, transport, gate) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Withhold, + &["coverage.incomplete"], + ))], + vec![], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::Withheld { .. })); + assert_eq!(*renderer.renders.lock().unwrap(), 1); + assert_eq!(gate.seen.lock().unwrap().len(), 1); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn gate_unavailable_pauses_never_allow() { + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::GateUnavailable("down".into()))], + vec![], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::GatePaused(_))); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn gate_unavailable_degrades_when_allowed() { + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::GateUnavailable("down".into()))], + vec![raw_response()], + 2, + ); + let evidence = BufferedEvidenceSink::new(); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &evidence, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Degraded { .. })); + assert_eq!(evidence.not_sent().len(), 1); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn block_does_not_degrade() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Blocked { .. })); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn deterministic_not_sent_retries_bounded() { + let (executor, renderer, _transport, _g) = harness( + vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![ + SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), + SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), + ], + 2, + ); + let evidence = BufferedEvidenceSink::new(); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &evidence) + .await; + assert!(matches!(outcome, ManagedOutcome::NotSent { attempts: 2 })); + assert_eq!(evidence.attempts(), vec![1, 2]); +} + +#[tokio::test] +async fn indeterminate_never_resends() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![SendOutcome::Indeterminate( + pc_gateway_transport::SendIndeterminateReason::TimeoutAwaitingResponse, + )], + 3, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::SendIndeterminate)); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn before_release_block_blocks_and_cancels() { + let (executor, renderer, transport, _g) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result( + CheckPhase::BeforeRelease, + CheckDecision::Block, + &["privacy.denied"], + )), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), + other => panic!("expected Blocked, got {other:?}"), + } + assert_eq!(*transport.cancels.lock().unwrap(), 1); +} + +#[tokio::test] +async fn credentials_never_enter_check_payload() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + let seen = gate.seen.lock().unwrap().clone(); + let (_, before_send_payload) = &seen[0]; + assert!( + !before_send_payload.contains("secret"), + "authorization 凭据不得进入 check 载荷: {before_send_payload}" + ); +} + +// ---------- 注入用例 ---------- + +fn reuse_result(content: &str) -> PrepareContextResult { + PrepareContextResult::WithReuse { + schema: "powercontext.prepared-context-with-reuse.v1".into(), + context: PreparedContext { + schema: "powercontext.prepared-context.v1".into(), + status: "ready".into(), + content: Some(content.to_string()), + content_bytes: content.len() as u64, + }, + reuse: pc_gateway_types::ContextReuse { + schema: "powercontext.context-reuse.v1".into(), + constraints: None, + expires_at: "2999-01-01T00:00:00Z".into(), + binding: "opaque-binding".into(), + }, + } +} + +#[tokio::test] +async fn injects_block_and_declares_exact_location() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( + "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", + ))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + assert!(matches!(outcome, ManagedOutcome::Released { .. })); + + // 检索词 = 最后一条 user 消息文本 + assert_eq!(gate.prepare_queries.lock().unwrap()[0], "hello"); + + // 载荷:标准块位于 user 消息头部 + let seen = gate.seen.lock().unwrap().clone(); + let payload = &seen[0].1; + let v: serde_json::Value = serde_json::from_str( + &format!("{{\"inner\":{payload}}}").replace("\"inner\":{", "\"inner\":", ), + ) + .unwrap_or(serde_json::Value::Null); + let _ = v; + let msg_text = extract_user_text(payload); + assert!(msg_text.starts_with("BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"), "块必须在头部: {msg_text}"); + assert!(msg_text.contains("网关必须无策略")); + assert!(msg_text.ends_with("hello")); + + // 区间声明:binding 原样、字节长度 = 块的 UTF-8 字节数(中文≠字符数) + let declared = gate.prepared_seen.lock().unwrap().clone(); + assert_eq!(declared[0].len(), 1); + let loc = &declared[0][0]; + assert_eq!(loc.binding, "opaque-binding"); + assert_eq!(loc.location.pointer, "/messages/0/content"); + assert_eq!(loc.location.schema, "powercontext.model-json-text-location.v1"); + assert_eq!(loc.location.start_byte, 0); + let block = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1"; + assert_eq!(loc.location.end_byte as usize, block.len()); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +fn extract_user_text(before_send_payload: &str) -> String { + // FakeGate 记录的即渲染后的请求体 JSON + let body: serde_json::Value = serde_json::from_str(before_send_payload).unwrap(); + body["messages"][0]["content"].as_str().unwrap().to_string() +} + +#[tokio::test] +async fn empty_prepare_injects_nothing() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + // prepare 默认返回 empty(FakeGate 默认值) + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + let seen = gate.seen.lock().unwrap().clone(); + assert!(!seen[0].1.contains("BEGIN_POWERCONTEXT"), "empty 不得注入标记"); + assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); +} + +#[tokio::test] +async fn prepare_failure_still_sends_without_injection() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Err(GateError::GateUnavailable("down".into()))); + let evidence = BufferedEvidenceSink::new(); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + let outcome = executor.run(c, &RendererRef(renderer.clone()), &evidence).await; + assert!(matches!(outcome, ManagedOutcome::Released { .. }), "prepare 失败不阻塞主链路"); + assert_eq!(transport.sends.lock().unwrap().len(), 1); + assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); + assert!(evidence.not_sent()[0].1.starts_with("prepare_failed")); +} + +#[tokio::test] +async fn sediment_captures_released_turn_synchronously() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + assert!(matches!(outcome, ManagedOutcome::Released { .. })); + let captured = gate.captured.lock().unwrap().clone(); + assert_eq!(captured.len(), 1, "Released 轮次同步沉淀一次"); + assert!(captured[0].0.starts_with("gw-turn-"), "幂等键: {}", captured[0].0); + let v: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); + assert_eq!(v["user"], "hello"); + assert_eq!(v["model"], "test-model"); +} + +#[tokio::test] +async fn blocked_turn_never_sediments() { + let (executor, renderer, _t, gate) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + assert!(gate.captured.lock().unwrap().is_empty(), "被拦内容不得沉淀"); +} + +#[tokio::test] +async fn malformed_gate_never_degrades_even_with_passthrough() { + // Core 可达但返回畸形响应:不是"不可用",绝不允许降级直通(fail-closed)。 + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::Malformed("garbage response".into()))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::GatePaused(_)), "Malformed 必须暂停"); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn non_utf8_response_is_never_released() { + // 上游返回非法 UTF-8 字节:不做有损转换送检(保真缺口),直接不放行。 + let bad = SendOutcome::Delivered(pc_gateway_transport::RawResponse { + status: 200, + body: bytes::Bytes::from_static(b"{\"text\":\"\xff\xfe\"}"), // 非法 UTF-8 + content_type: "application/json".into(), + ttft_ms: None, + usage: None, + }); + let (executor, renderer, transport, gate) = harness( + vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![bad], + 2, + ); + let outcome = executor + .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + match outcome { + ManagedOutcome::Withheld { reason_codes } => { + assert_eq!(reason_codes, ["invalid_response_encoding"]) + } + other => panic!("expected Withheld, got {other:?}"), + } + // 只有一次检查(before_send);非法响应根本不送检、不释放。 + // cancel 不适用:非流式调用响应已完整到达,无进行中的上游工作可取消。 + assert_eq!(gate.seen.lock().unwrap().len(), 1); + assert_eq!(*transport.cancels.lock().unwrap(), 0); +} diff --git a/powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs b/powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs new file mode 100644 index 0000000000..adc31cb393 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs @@ -0,0 +1,249 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 对真实 PowerContext Server(PR #2264)的 HTTP 级集成测试。 +//! +//! 与单测(FakeGate)互补:这里验证的是 Core 侧加密 binding 的真实行为, +//! mock 无法复现。运行条件:真实 Server 在 PC_TEST_CORE_BASE(默认 +//! http://127.0.0.1:8000)可达且配置了 enforcing 保护与 "coding" profile; +//! 不可达时全部跳过(不失败)。 + +use pc_gateway_core::{GateClient, GateError, HttpGateClient}; +use pc_gateway_types::{ + CheckDecision, ContextCheckRequest, ContextCheckResult, ModelJsonPayload, +}; +use std::collections::BTreeMap; + +const CORE: &str = "http://127.0.0.1:8000"; +const TARGET_PROFILE: &str = "coding"; +const MODEL_BODY: &str = r#"{"model":"glm-4-flash","max_tokens":80,"stream":false,"messages":[{"role":"user","content":"hi"}]}"#; +const RESPONSE_BODY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#; + +fn client() -> HttpGateClient { + HttpGateClient::new(CORE) +} + +async fn core_ready() -> bool { + reqwest::Client::new() + .get(format!("{CORE}/health/ready")) + .timeout(std::time::Duration::from_secs(2)) + .send() + .await + .map(|r| r.status().is_success()) + .unwrap_or(false) +} + +async fn require_core() -> Option<()> { + if core_ready().await { + Some(()) + } else { + eprintln!("SKIP: real PowerContext Server not reachable at {CORE}"); + None + } +} + +fn payload(body: &str) -> ModelJsonPayload { + ModelJsonPayload::new( + BTreeMap::from([("content-type".to_string(), "application/json".to_string())]), + body.to_string(), + ) +} + +async fn create_scope(tag: &str) -> Option { + let resp = reqwest::Client::new() + .post(format!("{CORE}/v1/scopes")) + .json(&serde_json::json!({ + "title": format!("Rust gateway test {tag}"), + "summary": "created by live integration tests", + "idempotency_key": format!("rust-live-{tag}"), + })) + .send() + .await + .ok()?; + let v: serde_json::Value = resp.json().await.ok()?; + v.get("scope_id")?.as_str().map(String::from) +} + +async fn before_send(scope: &str) -> Result { + client() + .check(ContextCheckRequest::BeforeSend { + scope_id: scope.to_string(), + target_profile: TARGET_PROFILE.to_string(), + payload: payload(MODEL_BODY), + prepared_contexts: Vec::new(), + }) + .await +} + +async fn before_release(scope: &str, binding: &str) -> Result { + client() + .check(ContextCheckRequest::BeforeRelease { + scope_id: scope.to_string(), + target_profile: TARGET_PROFILE.to_string(), + request_binding: binding.to_string(), + payload: payload(RESPONSE_BODY), + completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.to_string(), + }) + .await +} + +// ---------- 用例 ---------- + +/// happy path:真实 allow 返回加密 binding、完整覆盖与两个期限。 +#[tokio::test] +async fn live_allow_returns_real_binding_and_deadlines() { + let Some(_) = require_core().await else { return }; + let Some(scope) = create_scope("happy").await else { + panic!("scope creation failed"); + }; + let result = before_send(&scope).await.expect("check should succeed"); + + assert_eq!(result.decision, CheckDecision::Allow, "reasons: {:?}(需配置 coding profile)", result.reason_codes); + assert!(result.coverage.complete); + let binding = result.binding.as_deref().expect("allow 必须携带 binding"); + assert!(binding.starts_with("pc1."), "真实加密 binding 前缀: {binding:.20}..."); + + // 期限分离:发送窗口 ~60s,关联窗口 ~300s。 + let now = chrono_like_now(); + let valid = parse_epoch_ms(&result.valid_until); + let correlate = result.correlate_until.as_deref().map(parse_epoch_ms); + assert!( + valid > now && valid <= now + 65_000, + "发送期限应在 60s 窗口内: valid={valid} now={now}" + ); + let Some(correlate) = correlate else { panic!("before_send allow 必须带 correlate_until") }; + assert!( + correlate > now && correlate <= now + 310_000, + "关联期限应在 300s 窗口内" + ); +} + +/// 伪造 binding 做 before_release → Core 必须拒绝(绝不能 allow)。 +#[tokio::test] +async fn live_forged_binding_is_rejected() { + let Some(_) = require_core().await else { return }; + let Some(scope) = create_scope("forged").await else { panic!("scope creation failed") }; + let result = before_release(&scope, "pc1.forged-binding-not-issued-by-core").await; + match result { + Ok(r) => assert_ne!( + r.decision, + CheckDecision::Allow, + "伪造 binding 不得被放行: {:?}", + r.reason_codes + ), + // 4xx 拒绝(如绑定校验直接失败)同样视为通过。 + Err(GateError::GateUnavailable(msg)) => assert!( + msg.contains("HTTP 4"), + "期望 4xx 拒绝,得到: {msg}" + ), + Err(other) => panic!("unexpected: {other}"), + } +} + +/// binding 跨 Scope 使用 → 拒绝(对应 PC 测试 +/// `test_request_binding_cannot_cross_identity_scope_or_current_policy`)。 +#[tokio::test] +async fn live_binding_cannot_cross_scope() { + let Some(_) = require_core().await else { return }; + let (Some(scope_a), Some(scope_b)) = (create_scope("cross-a").await, create_scope("cross-b").await) + else { + panic!("scope creation failed"); + }; + let allow = before_send(&scope_a).await.expect("check a"); + assert_eq!(allow.decision, CheckDecision::Allow, "reasons: {:?}", allow.reason_codes); + let binding = allow.binding.expect("binding"); + + let cross = before_release(&scope_b, &binding).await; + match cross { + Ok(r) => assert_ne!( + r.decision, + CheckDecision::Allow, + "A 的 binding 不得放行 B 的释放: {:?}", + r.reason_codes + ), + Err(GateError::GateUnavailable(msg)) => assert!( + msg.contains("HTTP 4"), + "期望 4xx 拒绝,得到: {msg}" + ), + Err(other) => panic!("unexpected: {other}"), + } +} + +/// 线格式刚性:缺 prepared_contexts(必填)→ 422,验证 Rust DTO 与 +/// 真实 OpenAPI 的逐字段对齐。 +#[tokio::test] +async fn live_missing_prepared_contexts_rejected() { + let Some(_) = require_core().await else { return }; + let Some(scope) = create_scope("dto").await else { panic!("scope creation failed") }; + let raw = serde_json::json!({ + "phase": "before_send", + "scope_id": scope, + "target_profile": TARGET_PROFILE, + "payload": { + "schema": pc_gateway_types::MODEL_JSON_PAYLOAD_SCHEMA, + "headers": {"content-type": "application/json"}, + "body": MODEL_BODY, + }, + // 故意省略 prepared_contexts + }); + let resp = reqwest::Client::new() + .post(format!("{CORE}/v1/context/check")) + .json(&raw) + .send() + .await + .expect("post"); + assert_eq!(resp.status().as_u16(), 422, "缺必填字段必须 422"); +} + +// ---------- 工具 ---------- + +/// 无 chrono 依赖的简易 RFC3339 解析(足够测试用,格式由 Core 保证)。 +fn parse_epoch_ms(rfc3339: &str) -> u64 { + // 形如 2026-10-28T09:55:06.464580Z + let bytes = rfc3339.as_bytes(); + let year: i64 = rfc3339[0..4].parse().unwrap(); + let month: i64 = rfc3339[5..7].parse().unwrap(); + let day: i64 = rfc3339[8..10].parse().unwrap(); + let hour: i64 = rfc3339[11..13].parse().unwrap(); + let min: i64 = rfc3339[14..16].parse().unwrap(); + let sec: i64 = rfc3339[17..19].parse().unwrap(); + let millis: i64 = if bytes.len() > 20 { + let frac = &rfc3339[20..rfc3339.len().saturating_sub(1)]; + let frac = frac.trim_end_matches('Z'); + let taken: String = frac.chars().take(3).collect(); + taken.parse().unwrap_or(0) + } else { + 0 + }; + // 简化儒略日换算(1970 起,平年近似,测试时间尺度下足够)。 + let days = days_from_civil(year, month, day); + ((days * 86_400 + hour * 3600 + min * 60 + sec) * 1000 + millis) as u64 +} + +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn chrono_like_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} diff --git a/powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs b/powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs new file mode 100644 index 0000000000..dbfdab277b --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs @@ -0,0 +1,128 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! UDS 连接池正确性回归:keep-alive 连接上的连续响应必须逐次正确解析。 +//! 覆盖三个场景:content-length 精确、chunked(含 trailer)、content-length 超读截断。 + +use pc_gateway_core::{GateClient, UdsGateClient}; +use pc_gateway_types::{ + CheckDecision, CheckPhase, ContextCheckRequest, ModelJsonPayload, +}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{UnixListener, UnixStream}; + +static CONN_COUNT: AtomicUsize = AtomicUsize::new(0); + +fn result_json(decision: &str) -> String { + let schema = "powercontext.context-check.v1"; + format!( + r#"{{"schema":"{schema}","phase":"before_send","decision":"{decision}","reason_codes":[],"coverage":{{"profile":"text-and-tools.v1","complete":true}},"policy_version":"t","valid_until":"2999-01-01T00:00:00Z","binding":"b1"}}"# + ) +} + +fn check_request() -> ContextCheckRequest { + ContextCheckRequest::BeforeSend { + scope_id: "s".into(), + target_profile: "p".into(), + payload: ModelJsonPayload::new(BTreeMap::new(), "{}".into()), + prepared_contexts: Vec::new(), + } +} + +/// 读一行请求头直到空行(忽略 body 细节,够用即可)。 +async fn read_request(conn: &mut UnixStream) { + let mut buf = Vec::new(); + let mut byte = [0u8; 1]; + loop { + conn.read_exact(&mut byte).await.unwrap(); + buf.push(byte[0]); + if buf.ends_with(b"\r\n\r\n") { + break; + } + } + // 简化:Content-Length 为 0 的探测请求到此结束;带 body 的读掉 + let head = String::from_utf8_lossy(&buf).to_string(); + if let Some(len) = head + .lines() + .find_map(|l| l.strip_prefix("Content-Length: ").and_then(|v| v.trim().parse::().ok())) + { + let mut body = vec![0u8; len]; + if len > 0 { + conn.read_exact(&mut body).await.unwrap(); + } + } +} + +#[tokio::test] +async fn pooled_connection_parses_sequential_responses_correctly() { + let dir = std::env::temp_dir().join(format!("pc-uds-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("pool.sock"); + let _ = std::fs::remove_file(&sock); + let listener = UnixListener::bind(&sock).unwrap(); + + let server = tokio::spawn(async move { + let (mut conn, _) = listener.accept().await.unwrap(); + CONN_COUNT.fetch_add(1, Ordering::SeqCst); + + // 请求1 → content-length 精确 + read_request(&mut conn).await; + let body = result_json("allow"); + conn.write_all( + format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", body.len()).as_bytes(), + ).await.unwrap(); + conn.write_all(body.as_bytes()).await.unwrap(); + + // 请求2 → chunked(0-chunk + 终止 CRLF,即 trailer 空行) + read_request(&mut conn).await; + let body2 = result_json("allow"); + let mut chunked = Vec::new(); + chunked.extend_from_slice(format!("{:x}\r\n", body2.len()).as_bytes()); + chunked.extend_from_slice(body2.as_bytes()); + chunked.extend_from_slice(b"\r\n0\r\n\r\n"); + conn.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n", + ).await.unwrap(); + conn.write_all(&chunked).await.unwrap(); + + // 请求3 → content-length 后故意多推 5 个脏字节(应被截断且连接不复用) + read_request(&mut conn).await; + let body3 = result_json("allow"); + conn.write_all( + format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body3.len()).as_bytes(), + ).await.unwrap(); + conn.write_all(body3.as_bytes()).await.unwrap(); + conn.write_all(b"DIRTY").await.unwrap(); + // 保持连接打开一会儿,验证客户端没把脏字节当下一响应 + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + }); + + let client = UdsGateClient::new(&sock); + // 请求1:content-length 精确 + let r1 = client.check(check_request()).await.unwrap(); + assert_eq!(r1.decision, CheckDecision::Allow); + // 请求2:chunked 应正确解码(而非把 trailer 当下一个响应头) + let r2 = client.check(check_request()).await.unwrap(); + assert_eq!(r2.decision, CheckDecision::Allow); + assert_eq!(r2.phase, CheckPhase::BeforeSend, "chunked 解码后字段完整"); + // 请求3:超读截断——body 应恰好是合法 JSON(脏字节被丢弃) + let r3 = client.check(check_request()).await.unwrap(); + assert_eq!(r3.decision, CheckDecision::Allow); + + server.await.unwrap(); + // 三次请求只应建立一条连接(第3次后因脏字节弃用,但那是之后的事) + assert_eq!(CONN_COUNT.load(Ordering::SeqCst), 1, "keep-alive 应复用同一连接"); +} diff --git a/powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml b/powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml new file mode 100644 index 0000000000..a854a4ac55 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml @@ -0,0 +1,24 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-embedded" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: optional embedded/FFI surface for in-process (Python) executors" + +[dependencies] +pc-gateway-core = { workspace = true } +pc-gateway-types = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs b/powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs new file mode 100644 index 0000000000..b69b1f5240 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs @@ -0,0 +1,22 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 嵌入式路径的占位 crate。 +//! +//! RFC:SDK/内置执行与 Rust GatewayRuntime 是按调用配置的两种执行路径, +//! 同一部署可并存,落实同一套 Core 决策。本 crate 未来承载 +//! pyo3/FFI 绑定,让 Python 进程内执行器复用 `pc-gateway-core` 的状态机, +//! 并以进程内 `GateClient` 实现直调 Core 算法(无需 HTTP)。 +//! +//! v1 尚未实现;保留 crate 以固定 workspace 边界。 diff --git a/powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml b/powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml new file mode 100644 index 0000000000..0b939df869 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml @@ -0,0 +1,24 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-evidence" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: evidence normalization — usage completeness, cache read/write, latency; never bodies" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs b/powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs new file mode 100644 index 0000000000..b980a257f7 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -0,0 +1,112 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 证据适配层。 +//! +//! RFC 约束:归一化实际目标身份、usage 完整性、供应商缓存 read/write、 +//! 失败尝试与延迟;分别报告上游首 token 与首次内容释放时间; +//! **绝不记录 query/prompt/响应正文/凭据**;执行身份不进指标标签。 +//! 已知 / 估算 / 未知 / 对账用量分开记录,不可用标 unknown 不记零。 + +use serde::{Deserialize, Serialize}; + +/// usage 完整性:不把缺失当零。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UsageCompleteness { + Known, + Estimated, + Unknown, + Reconciled, +} + +/// 单次调用的无正文证据记录。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct CallEvidence { + /// 实际发送目标身份(归一化后),不是客户端声称的目标。 + pub actual_target: Option, + pub completeness: Option, + pub input_tokens: Option, + pub output_tokens: Option, + pub cache_read_tokens: Option, + pub cache_write_tokens: Option, + pub attempts: u32, + /// 上游首 token 延迟(毫秒)。 + pub upstream_ttft_ms: Option, + /// 首次内容释放延迟(毫秒)。strict 模式下必然晚于 ttft。 + pub first_release_ms: Option, + /// 失败原因类别(无正文)。 + pub failure_reason: Option, +} + +/// 证据下沉抽象。实现可以是空对象(观测可选), +/// 借鉴 TensorZero 的 disabled client 模式。 +pub trait EvidenceSink: Send + Sync { + fn record_attempt(&self, attempt: u32); + fn record_not_sent(&self, attempt: u32, reason: &str); + fn record_call(&self, evidence: &CallEvidence); +} + +/// 空对象实现:观测关闭时使用。 +#[derive(Debug, Default, Clone, Copy)] +pub struct NoopEvidenceSink; + +impl EvidenceSink for NoopEvidenceSink { + fn record_attempt(&self, _attempt: u32) {} + fn record_not_sent(&self, _attempt: u32, _reason: &str) {} + fn record_call(&self, _evidence: &CallEvidence) {} +} + +/// 内存缓冲实现:测试与本地演示用;不落盘、不落正文。 +#[derive(Debug, Default)] +pub struct BufferedEvidenceSink { + attempts: std::sync::Mutex>, + not_sent: std::sync::Mutex>, + calls: std::sync::Mutex>, +} + +impl BufferedEvidenceSink { + pub fn new() -> Self { + Self::default() + } + + pub fn attempts(&self) -> Vec { + self.attempts.lock().expect("evidence lock").clone() + } + + pub fn not_sent(&self) -> Vec<(u32, String)> { + self.not_sent.lock().expect("evidence lock").clone() + } + + pub fn calls(&self) -> Vec { + self.calls.lock().expect("evidence lock").clone() + } +} + +impl EvidenceSink for BufferedEvidenceSink { + fn record_attempt(&self, attempt: u32) { + self.attempts.lock().expect("evidence lock").push(attempt); + } + + fn record_not_sent(&self, attempt: u32, reason: &str) { + self.not_sent + .lock() + .expect("evidence lock") + .push((attempt, reason.to_string())); + } + + fn record_call(&self, evidence: &CallEvidence) { + self.calls.lock().expect("evidence lock").push(evidence.clone()); + } +} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml b/powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml new file mode 100644 index 0000000000..74ae8e4e8d --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml @@ -0,0 +1,27 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-protocol" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: canonical internal types + per-provider wire-format conversion + SSE parsing" + +[dependencies] +pc-gateway-types = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +bytes = { workspace = true } +thiserror = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs new file mode 100644 index 0000000000..260df4819d --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -0,0 +1,63 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use serde::{Deserialize, Serialize}; + +/// 网关内部规范请求:发送前必须完整落入 input/check。 +/// 只保留结构性字段,语义内容由 Core 裁决。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CanonicalRequest { + pub model: String, + pub messages: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tools: Vec, + /// Responses API 的 instructions(系统级指令);chat 格式为 None。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_cache_fields: Option, + /// 显式输出限制(与输入预算分开;见 RFC「补充上下文字节与完整请求 token」)。 + pub output_limits: OutputLimits, + /// 是否请求上游流式(SSE)。strict 语义不变:网关全量缓冲并过 + /// before_release 后才向客户端释放;流式的是上游接收路径。 + #[serde(default)] + pub stream: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CanonicalMessage { + pub role: Role, + pub content: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + System, + User, + Assistant, + Tool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputLimits { + pub max_output_tokens: u32, +} + +/// 渲染结果:语义内容不变的最终字节。 +#[derive(Debug, Clone)] +pub struct RenderedPayload { + pub bytes: bytes::Bytes, + pub content_type: &'static str, +} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs new file mode 100644 index 0000000000..962dc96a73 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs @@ -0,0 +1,27 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 协议适配层:内部规范类型 ↔ 各服务商线格式。 +//! +//! RFC 约束:只渲染获准的协议字段;保持角色、工具顺序、内容块、 +//! 可复用边界与获准原生缓存设置;不向稳定 prompt 写入请求 ID/时间戳、 +//! 不任意合并旧消息、不静默重映射目标。 + +mod canonical; +mod render; +mod sse; + +pub use canonical::*; +pub use render::*; +pub use sse::*; diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/render.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/render.rs new file mode 100644 index 0000000000..8552772426 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-protocol/src/render.rs @@ -0,0 +1,248 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{CanonicalRequest, RenderedPayload}; + +/// 渲染错误。 +#[derive(Debug, thiserror::Error)] +pub enum RenderError { + #[error("unsupported field for renderer {renderer}: {field}")] + UnsupportedField { renderer: &'static str, field: String }, + #[error("cache render plan invalid for renderer {renderer}")] + InvalidRenderPlan { renderer: &'static str }, +} + +/// 线格式渲染器。OpenAI 系实现共享同一份 chat-completions 渲染 +/// (借鉴 TensorZero 的 chat_completions 共享模块模式)。 +/// +/// v1 strict 语义:完整渲染最终字节交给 input/check; +/// 缓存渲染计划(withhold 附带)只允许合并计划里显式列出的顶层字段。 +pub trait WireRenderer: Send + Sync { + fn name(&self) -> &'static str; + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result; +} + +/// OpenAI 兼容 chat-completions 渲染器。 +/// +/// 不依赖厂商 SDK,直接序列化线格式(对齐 RFC:高层包装无法证明 +/// 覆盖最终序列化、内部重试与原始错误)。strict v1 固定 `stream: false`, +/// 上游以完整单元返回,SSE 分帧在 output/check 之后由网关侧完成。 +#[derive(Debug, Default, Clone, Copy)] +pub struct OpenAiChatRenderer; + +impl WireRenderer for OpenAiChatRenderer { + fn name(&self) -> &'static str { + "openai-chat-completions" + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + // OpenAI 线格式:纯文本 content 用字符串形式(部分兼容后端不接受 + // 无 type 的部件数组);多部件 content 按原样透传。 + let mut messages = Vec::with_capacity(request.messages.len()); + for m in &request.messages { + let content: serde_json::Value = match m.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + })?, + }; + messages.push(serde_json::json!({ + "role": m.role, + "content": content, + })); + } + + // 只写入确定性的结构字段;不写请求 ID/时间戳(缓存前缀保真)。 + let mut body = serde_json::json!({ + "model": request.model, + "messages": messages, + "max_tokens": request.output_limits.max_output_tokens, + "stream": request.stream, + }); + if !request.tools.is_empty() { + body["tools"] = serde_json::json!(request.tools); + } + if let Some(fields) = request.native_cache_fields.as_ref() { + merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + if let Some(plan) = cache_render_plan { + merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + + let bytes = serde_json::to_vec(&body) + .map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })? + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} + +/// 双格式渲染器:入口格式即上游格式(同格式进出,无跨格式转换)。 +#[derive(Debug, Clone, Copy)] +pub enum GatewayRenderer { + Chat(OpenAiChatRenderer), + Responses(OpenAiResponsesRenderer), +} + +impl Default for GatewayRenderer { + fn default() -> Self { + GatewayRenderer::Chat(OpenAiChatRenderer) + } +} + +impl WireRenderer for GatewayRenderer { + fn name(&self) -> &'static str { + match self { + GatewayRenderer::Chat(r) => r.name(), + GatewayRenderer::Responses(r) => r.name(), + } + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + match self { + GatewayRenderer::Chat(r) => r.render(request, cache_render_plan), + GatewayRenderer::Responses(r) => r.render(request, cache_render_plan), + } + } +} + +/// 只合并获准的顶层键;src 必须是对象。 +fn merge_top_level(dst: &mut serde_json::Value, src: &serde_json::Value) -> Result<(), ()> { + let src_obj = src.as_object().ok_or(())?; + let dst_obj = dst.as_object_mut().ok_or(())?; + for (k, v) in src_obj { + dst_obj.insert(k.clone(), v.clone()); + } + Ok(()) +} + +/// OpenAI Responses API 渲染器。 +/// +/// 同格式进出:客户端用 Responses 格式进来,上游也渲染为 Responses; +/// 不做 chat ↔ responses 的跨格式转换(保真优先)。 +/// content 里携带的 Responses 专有 item(function_call、function_call_output、 +/// item_reference、reasoning 等)按原样作为顶层 input item 透出。 +#[derive(Debug, Default, Clone, Copy)] +pub struct OpenAiResponsesRenderer; + +/// Responses API 的顶层 input item 类型(区别于消息内 content part 的 +/// input_text/output_text 等文本部件)。 +const RESPONSES_ITEM_TYPES: &[&str] = &[ + "message", + "function_call", + "function_call_output", + "custom_tool_call", + "custom_tool_call_output", + "item_reference", + "reasoning", + "web_search_call", + "file_search_call", + "computer_call", + "computer_call_output", + "image_generation_call", + "code_interpreter_call", + "mcp_call", + "mcp_list_tools", +]; + +fn is_responses_item(v: &serde_json::Value) -> bool { + v.get("type") + .and_then(|t| t.as_str()) + .map(|t| RESPONSES_ITEM_TYPES.contains(&t)) + .unwrap_or(false) +} + +impl WireRenderer for OpenAiResponsesRenderer { + fn name(&self) -> &'static str { + "openai-responses" + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + let mut input = Vec::with_capacity(request.messages.len()); + for msg in &request.messages { + // 单元素 content 且是 Responses 专有 item → 原样作为顶层 item。 + if msg.content.len() == 1 && is_responses_item(&msg.content[0]) { + input.push(msg.content[0].clone()); + continue; + } + let content: serde_json::Value = serde_json::to_value(&msg.content) + .map_err(|e| RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + })?; + input.push(serde_json::json!({ + "role": msg.role, + "content": content, + })); + } + + let mut body = serde_json::json!({ + "model": request.model, + "input": input, + "max_output_tokens": request.output_limits.max_output_tokens, + "stream": request.stream, + }); + if let Some(instructions) = &request.instructions { + body["instructions"] = serde_json::json!(instructions); + } + if !request.tools.is_empty() { + body["tools"] = serde_json::json!(request.tools); + } + if let Some(fields) = request.native_cache_fields.as_ref() { + merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + if let Some(plan) = cache_render_plan { + merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + + let bytes = serde_json::to_vec(&body) + .map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })? + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs new file mode 100644 index 0000000000..410b9e86da --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs @@ -0,0 +1,87 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! SSE 解析。 +//! +//! RFC 约束:strict 模式在完整 output/check 之后才组帧, +//! 因此网关 v1 对上游流是全量缓冲单元,不做增量放行; +//! bounded streaming 是后续独立提案。 + +use bytes::Bytes; + +/// 缓冲中的一个原始事件(不解释语义;语义归 output/check 与调用方)。 +#[derive(Debug, Clone)] +pub struct RawSseEvent { + pub event: Option, + pub data: Bytes, +} + +/// 增量解析器:从上游字节流切出原始 SSE 事件。 +/// 只做切帧,不做内容检查——检查的是完整单元。 +#[derive(Default)] +pub struct SseFramer { + buf: Vec, +} + +impl SseFramer { + pub fn push(&mut self, chunk: &[u8]) { + self.buf.extend_from_slice(chunk); + } + + /// 取出所有完整事件(以空行分隔)。 + pub fn take_events(&mut self) -> Vec { + let mut events = Vec::new(); + while let Some(pos) = find_blank_line(&self.buf) { + let block: Vec = self.buf.drain(..pos).collect(); + self.buf.drain(..2); // CRLF/LF 分隔符 + if let Some(ev) = parse_block(&block) { + events.push(ev); + } + } + events + } + + /// 结束流时收尾(缓冲中残余的最后一个块)。 + pub fn finish(&mut self) -> Vec { + let rest = std::mem::take(&mut self.buf); + match parse_block(&rest) { + Some(ev) => vec![ev], + None => Vec::new(), + } + } +} + +fn find_blank_line(buf: &[u8]) -> Option { + buf.windows(2).position(|w| w == b"\n\n" || w == b"\r\n") +} + +fn parse_block(block: &[u8]) -> Option { + let text = String::from_utf8_lossy(block); + let mut event = None; + let mut data_lines = Vec::new(); + for line in text.lines() { + if let Some(v) = line.strip_prefix("event:") { + event = Some(v.trim().to_string()); + } else if let Some(v) = line.strip_prefix("data:") { + data_lines.push(v.strip_prefix(' ').unwrap_or(v)); + } + } + if data_lines.is_empty() { + return None; + } + Some(RawSseEvent { + event, + data: Bytes::from(data_lines.join("\n")), + }) +} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs new file mode 100644 index 0000000000..7b51de714d --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -0,0 +1,74 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OpenAiChatRenderer, OutputLimits, Role, WireRenderer, +}; + +fn request() -> CanonicalRequest { + CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 16, + }, + stream: false, + } +} + +#[test] +fn renders_deterministic_base_body() { + let p = OpenAiChatRenderer.render(&request(), None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["model"], "m"); + assert_eq!(v["stream"], false); + assert_eq!(v["max_tokens"], 16); + // 缓存前缀保真:不注入请求 ID/时间戳类字段。 + assert!(v.get("request_id").is_none()); + assert!(v.get("timestamp").is_none()); +} + +#[test] +fn merges_only_approved_cache_plan_fields() { + let plan = serde_json::json!({"cache_control": {"type": "ephemeral"}}); + let p = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["cache_control"]["type"], "ephemeral"); + assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); +} + +#[test] +fn non_object_plan_rejected() { + let plan = serde_json::json!(["not", "an", "object"]); + let err = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap_err(); + assert!(matches!( + err, + pc_gateway_protocol::RenderError::InvalidRenderPlan { .. } + )); +} + +#[test] +fn stream_flag_reaches_wire_format() { + let mut req = request(); + req.stream = true; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["stream"], true, "stream 标志必须原样到达线格式"); +} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs new file mode 100644 index 0000000000..efd9937d6a --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -0,0 +1,89 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OpenAiResponsesRenderer, OutputLimits, Role, + WireRenderer, +}; + +fn request() -> CanonicalRequest { + CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + }], + tools: vec![], + instructions: Some("be terse".into()), + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 16, + }, + stream: false, + } +} + +#[test] +fn renders_responses_wire_format() { + let p = OpenAiResponsesRenderer.render(&request(), None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["model"], "m"); + assert_eq!(v["instructions"], "be terse"); + assert_eq!(v["max_output_tokens"], 16); + assert_eq!(v["stream"], false); + assert_eq!(v["input"][0]["role"], "user"); + assert!(v.get("messages").is_none(), "不得混入 chat 字段"); + assert!(v.get("max_tokens").is_none()); +} + +#[test] +fn responses_items_pass_through_verbatim() { + let fc = serde_json::json!({ + "type": "function_call", "call_id": "c1", "name": "search", "arguments": "{}" + }); + let req = CanonicalRequest { + model: "m".into(), + messages: vec![ + CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + }, + // 无 role 的顶层 item:原样封进 content,渲染时作为顶层 item 透出 + CanonicalMessage { + role: Role::Tool, + content: vec![fc.clone()], + }, + ], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 16, + }, + stream: false, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["input"].as_array().unwrap().len(), 2); + assert_eq!(v["input"][1], fc, "Responses 专有 item 必须字节级透传"); +} + +#[test] +fn merges_only_approved_cache_plan_fields() { + let plan = serde_json::json!({"prompt_cache_key": "scope-1"}); + let p = OpenAiResponsesRenderer.render(&request(), Some(&plan)).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["prompt_cache_key"], "scope-1"); + assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); +} diff --git a/powercontext/gateway/crates/pc-gateway-transport/Cargo.toml b/powercontext/gateway/crates/pc-gateway-transport/Cargo.toml new file mode 100644 index 0000000000..5fa369e5b4 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-transport/Cargo.toml @@ -0,0 +1,30 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-transport" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: transport — send admitted bytes, cancel, bounded retry with single owner" + +[dependencies] +pc-gateway-types = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +futures-core = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +reqwest = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/lib.rs b/powercontext/gateway/crates/pc-gateway-transport/src/lib.rs new file mode 100644 index 0000000000..df6ef271aa --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-transport/src/lib.rs @@ -0,0 +1,29 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 传输层:发送获准字节、取消、归属明确的有界重试。 +//! +//! RFC 失败语义: +//! - 准入后正文/目标/设置变化 → 重新准入后才能发送; +//! - 确定性未送达 → 唯一所有者在有效准入和有界次数内重试; +//! - 可能已送达 → 返回不确定,不自动付费重发; +//! - 未 admission 的字节绝不出网。 + +mod reqwest_transport; +mod retry; +mod sender; + +pub use reqwest_transport::*; +pub use retry::*; +pub use sender::*; diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs new file mode 100644 index 0000000000..8bca8bcfb0 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -0,0 +1,190 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::sender::{ + AdmittedSend, NotSentReason, RawResponse, SendIndeterminateReason, SendOutcome, Transport, +}; +use bytes::Bytes; +use std::future::Future; +use std::time::{Duration, Instant}; + +/// 基于 reqwest 的传输实现:裸 HTTP 直连上游,不经任何厂商 SDK。 +/// +/// 结果映射(对齐 RFC 失败语义): +/// - 连接失败/请求构造失败 → 确定性 NotSent(可重试); +/// - 发送后连接丢失、超时、解码中断 → Indeterminate(不自动重发); +/// - 流式接收:逐块读入(计量 TTFT、字节数受 `max_buffer_bytes` 上限), +/// strict 语义不变——完整缓冲后仍需过 before_release 才释放。 +#[derive(Debug, Clone)] +pub struct ReqwestTransport { + client: reqwest::Client, + /// 流式/非流式响应的缓冲字节上限(容量保护)。 + max_buffer_bytes: usize, +} + +impl ReqwestTransport { + pub fn new(timeout: Duration) -> Self { + let client = reqwest::Client::builder() + // 获准目的地必须保持为实际目的地:307/308 会让 reqwest 把已准入的 + // POST body 原样重发到未经 Core 审查的新地址。禁用自动跟随,重定向 + // 响应原样上抛(经 before_release 后透传给调用方),字节绝不自动重发。 + .redirect(reqwest::redirect::Policy::none()) + .timeout(timeout) + .build() + .expect("reqwest client build"); + Self { + client, + max_buffer_bytes: 32 * 1024 * 1024, + } + } + + pub fn with_buffer_limit(mut self, max_buffer_bytes: usize) -> Self { + self.max_buffer_bytes = max_buffer_bytes; + self + } +} + +impl Default for ReqwestTransport { + fn default() -> Self { + Self::new(Duration::from_secs(120)) + } +} + +impl Transport for ReqwestTransport { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a { + Box::pin(async move { + let mut req = self.client.post(&send.target_url); + let mut has_content_type = false; + for (k, v) in &send.headers { + if k.eq_ignore_ascii_case("content-type") { + has_content_type = true; + } + req = req.header(k, v); + } + if !has_content_type { + req = req.header("content-type", "application/json"); + } + let resp = match req.body(send.payload.to_vec()).send().await { + Err(e) => { + // NotSent 仅限于「可证明发生在传输之前」的失败: + // - is_connect():TCP/TLS 握手未完成,body 必然未发出; + // - is_builder():请求构造阶段,早于一切网络动作。 + // 其余(is_request/is_timeout/is_body/is_decode)都无法排除 + // body 已完整送达上游的可能——reqwest 的 is_request() 尤其 + // 涵盖「对端读完全部 body 后关闭/超时」,按未送达重试会 + // 重复计费。一律归 Indeterminate,不重试。 + return if e.is_connect() { + SendOutcome::NotSent(NotSentReason::ConnectRefused) + } else if e.is_builder() { + SendOutcome::NotSent(NotSentReason::RejectedLocally) + } else if e.is_timeout() { + SendOutcome::Indeterminate( + SendIndeterminateReason::TimeoutAwaitingResponse, + ) + } else { + SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) + }; + } + Ok(resp) => resp, + }; + let status = resp.status().as_u16(); + let content_type = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/json") + .to_string(); + + if send.stream { + // 流式接收:逐块累积 + TTFT 计量 + 字节上限。 + let start = Instant::now(); + let mut body: Vec = Vec::with_capacity(16 * 1024); + let mut ttft: Option = None; + let mut stream = resp.bytes_stream(); + loop { + match next_chunk(&mut stream).await { + None => break, + Some(Err(_)) => { + return SendOutcome::Indeterminate( + SendIndeterminateReason::LostAfterHandoff, + ) + } + Some(Ok(chunk)) => { + if ttft.is_none() { + ttft = Some(start.elapsed().as_millis() as u64); + } + if body.len() + chunk.len() > self.max_buffer_bytes { + // 已送达且部分计费:不重发,向上标记不确定。 + return SendOutcome::Indeterminate( + SendIndeterminateReason::BufferLimitExceeded, + ); + } + body.extend_from_slice(&chunk); + } + } + } + let usage = extract_usage(&body); + SendOutcome::Delivered(RawResponse { + status, + body: Bytes::from(body), + content_type, + ttft_ms: ttft, + usage, + }) + } else { + match resp.bytes().await { + Err(_) => { + SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) + } + Ok(body) => { + let usage = extract_usage(&body); + SendOutcome::Delivered(RawResponse { + status, + body, + content_type, + ttft_ms: None, + usage, + }) + } + } + } + }) + } + + fn cancel<'a>(&'a self, _send: &'a AdmittedSend) -> impl Future + Send + 'a { + // 非流式/全量缓冲调用在响应完整返回后已无进行中的上游工作; + // 放弃响应体即断开连接(连接池按目标隔离)。 + std::future::ready(()) + } +} + +fn extract_usage(body: &[u8]) -> Option { + serde_json::from_slice::(body) + .ok() + .and_then(|v| v.get("usage").cloned()) +} + +/// 不引入 futures-util 依赖的 next():用标准库 poll_fn 轮询 Stream。 +async fn next_chunk(stream: &mut S) -> Option> +where + S: futures_core::Stream> + Unpin, +{ + use std::pin::Pin; + std::future::poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)) + .await + .map(|r| r.map_err(|e| e.to_string())) +} diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/retry.rs b/powercontext/gateway/crates/pc-gateway-transport/src/retry.rs new file mode 100644 index 0000000000..147ac7d77d --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-transport/src/retry.rs @@ -0,0 +1,69 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{AdmittedSend, SendOutcome, Transport}; +use pc_gateway_evidence::EvidenceSink; +use std::num::NonZeroU32; + +/// 有界重试:唯一所有者、有效准入、有界次数。 +/// 只重试确定性 `NotSent`;`Indeterminate` 一律上抛,绝不自动付费重发。 +pub struct BoundedRetry { + transport: T, + max_attempts: NonZeroU32, +} + +/// 重试的结果:`Done` 携带原始 `SendOutcome`; +/// `AllNotSent` 表示全部尝试都确定性未送达。 +#[derive(Debug)] +pub enum RetryOutcome { + Done(SendOutcome), + AllNotSent { attempts: u32 }, +} + +impl BoundedRetry { + pub fn new(transport: T, max_attempts: NonZeroU32) -> Self { + Self { + transport, + max_attempts, + } + } + + pub fn transport(&self) -> &T { + &self.transport + } + + pub async fn send_with_retry( + &self, + send: &AdmittedSend, + evidence: &dyn EvidenceSink, + ) -> RetryOutcome { + let mut attempt: u32 = 0; + loop { + attempt += 1; + evidence.record_attempt(attempt); + match self.transport.send(send.clone()).await { + // 可能已送达:立即上抛,不做任何自动重发。 + outcome @ SendOutcome::Indeterminate(_) + | outcome @ SendOutcome::Delivered(_) => return RetryOutcome::Done(outcome), + SendOutcome::NotSent(reason) => { + if attempt >= self.max_attempts.get() { + evidence.record_not_sent(attempt, &reason.to_string()); + return RetryOutcome::AllNotSent { attempts: attempt }; + } + // 确定性未送达:唯一所有者继续重试。 + } + } + } + } +} diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/sender.rs b/powercontext/gateway/crates/pc-gateway-transport/src/sender.rs new file mode 100644 index 0000000000..3b0bf792cf --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-transport/src/sender.rs @@ -0,0 +1,86 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use bytes::Bytes; +use std::future::Future; + +/// 一次已获准的发送。 +#[derive(Debug, Clone)] +pub struct AdmittedSend { + /// before_send allow 返回的不透明绑定字符串;必须原样用于 before_release。 + pub binding: String, + /// 最终获准字节(渲染产物,binding 绑定的就是这些字节)。 + pub payload: Bytes, + /// 获准目标 URL;不得静默重映射。 + pub target_url: String, + /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 + pub headers: Vec<(String, String)>, + /// 上游流式(SSE)接收:逐块读入并计量,strict 语义不变。 + pub stream: bool, +} + +/// 原始响应 + 传输结果,交给 output/check 后才允许释放。 +#[derive(Debug)] +pub struct RawResponse { + pub status: u16, + pub body: Bytes, + /// 响应的 Content-Type(SSE 为 text/event-stream),释放时原样使用。 + pub content_type: String, + /// 上游首字节延迟(毫秒);流式接收时计量,非流式为 None。 + pub ttft_ms: Option, + /// usage 证据(不可用时为 None,标记 unknown,不记零)。 + pub usage: Option, +} + +/// 发送结果:确定性状态优先;不确定即不确定。 +#[derive(Debug)] +pub enum SendOutcome { + /// 成功取得完整原始响应(尚未过 output/check,不得释放)。 + Delivered(RawResponse), + /// 确定尚未送达:可在有界次数内由唯一所有者重试。 + NotSent(NotSentReason), + /// 可能已到达上游:返回不确定,不自动付费重发,不假设退费。 + Indeterminate(SendIndeterminateReason), +} + +#[derive(Debug, thiserror::Error)] +pub enum NotSentReason { + #[error("connection refused before request sent")] + ConnectRefused, + #[error("request rejected before body accepted")] + RejectedLocally, +} + +#[derive(Debug, thiserror::Error)] +pub enum SendIndeterminateReason { + #[error("connection lost after request handed to transport")] + LostAfterHandoff, + #[error("timeout awaiting response")] + TimeoutAwaitingResponse, + /// 流式接收超过缓冲上限:请求已送达且部分计费,不重发。 + #[error("streaming buffer limit exceeded")] + BufferLimitExceeded, +} + +/// 传输器抽象;实现保证只发送 `AdmittedSend`(类型上无法构造未准入的发送)。 +pub trait Transport: Send + Sync { + fn send<'a>( + &'a self, + send: AdmittedSend, + ) -> impl Future + Send + 'a; + + /// 尽力取消上游(strict 检查失败/缓冲超限时必需)。 + /// RPITIT 声明以固化 Send 约束(trait 是公开 API)。 + fn cancel<'a>(&'a self, send: &'a AdmittedSend) -> impl Future + Send + 'a; +} diff --git a/powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs b/powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs new file mode 100644 index 0000000000..bb1c53bd00 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs @@ -0,0 +1,106 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P1-1): +//! 对端读完整 POST body 后关闭连接 —— reqwest 报 is_request() 类错误。 +//! 断言:body 只被上游收到一次(绝不重复计费发送), +//! 且结果归为 Indeterminate 而非可重试的 NotSent。 + +use pc_gateway_transport::{ + AdmittedSend, ReqwestTransport, SendOutcome, SendIndeterminateReason, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::AsyncReadExt; +use tokio::net::TcpListener; + +#[tokio::test] +async fn upstream_closing_after_full_body_is_indeterminate_and_not_resent() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let bodies = Arc::new(AtomicUsize::new(0)); + let connections = Arc::new(AtomicUsize::new(0)); + + let b = bodies.clone(); + let c = connections.clone(); + tokio::spawn(async move { + // 接受至多 2 条连接:若网关错误地重试,第二条也会收到 body。 + for _ in 0..2 { + let (mut sock, _) = match listener.accept().await { + Ok(x) => x, + Err(_) => return, + }; + c.fetch_add(1, Ordering::SeqCst); + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + // 读到完整请求(头 + Content-Length 声明的 body) + loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); + let len: usize = head + .lines() + .find_map(|l| l.strip_prefix("content-length: ")) + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0); + if buf.len() >= pos + 4 + len { + break; + } + } + } + // 完整收到一条带 body 的 POST → 计数 + if buf.starts_with(b"POST") { + b.fetch_add(1, Ordering::SeqCst); + } + // 读完即关闭,不回任何响应(review 描述的复现场景) + drop(sock); + } + }); + + let transport = ReqwestTransport::default(); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), + target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + + // 复现 review 场景:BoundedRetry(max_attempts=2)。 + // 旧行为:is_request() 被归为 NotSent → 重试 → 上游收到两次完整 body + // 且最终谎报 AllNotSent{attempts:2}。 + // 新行为:归为 Indeterminate → 立即上抛,不进行第二次发送。 + let retry = pc_gateway_transport::BoundedRetry::new( + transport, + std::num::NonZeroU32::new(2).unwrap(), + ); + let outcome = retry.send_with_retry(&send, &pc_gateway_evidence::NoopEvidenceSink).await; + match outcome { + pc_gateway_transport::RetryOutcome::Done(SendOutcome::Indeterminate( + SendIndeterminateReason::LostAfterHandoff, + )) => {} + other => panic!("expected Done(Indeterminate), got {other:?}"), + } + + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + assert_eq!( + bodies.load(Ordering::SeqCst), + 1, + "上游必须只收到一次 body(修复前是 2 次,重复计费)" + ); +} diff --git a/powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs b/powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs new file mode 100644 index 0000000000..5baf3229dd --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs @@ -0,0 +1,107 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P1-2): +//! 获准上游返回 307 时,reqwest 默认会把已准入的 POST body 原样重发到 +//! Location 指向的第二个地址(未经 Core 准入)。禁用自动跟随后: +//! 第二地址必须收到零字节;307 响应原样透传(Delivered status=307)。 + +use pc_gateway_transport::{AdmittedSend, ReqwestTransport, SendOutcome, Transport}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +/// 读一条完整 HTTP 请求(头 + content-length body),返回原始字节。 +async fn read_request(sock: &mut TcpStream) -> Vec { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); + let len: usize = head + .lines() + .find_map(|l| l.strip_prefix("content-length: ")) + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0); + if buf.len() >= pos + 4 + len { + break; + } + } + } + buf +} + +#[tokio::test] +async fn redirect_target_receives_nothing_and_307_surfaces() { + // 第二地址(重定向目标):任何到达的字节都记为违规 + let evil = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let evil_port = evil.local_addr().unwrap().port(); + let evil_received = Arc::new(AtomicUsize::new(0)); + let er = evil_received.clone(); + tokio::spawn(async move { + if let Ok((mut sock, _)) = evil.accept().await { + let data = read_request(&mut sock).await; + er.fetch_add(data.len(), Ordering::SeqCst); + let resp = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"; + let _ = sock.write_all(resp).await; + } + }); + + // 第一地址(获准上游):读完整请求后回 307 指向第二地址 + let approved = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let approved_port = approved.local_addr().unwrap().port(); + let served_307 = Arc::new(AtomicBool::new(false)); + let s307 = served_307.clone(); + let evil_addr = format!("127.0.0.1:{evil_port}"); + tokio::spawn(async move { + let (mut sock, _) = approved.accept().await.unwrap(); + let _ = read_request(&mut sock).await; + let resp = format!( + "HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{evil_addr}/steer\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + sock.write_all(resp.as_bytes()).await.unwrap(); + s307.store(true, Ordering::SeqCst); + }); + + let transport = ReqwestTransport::default(); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), + target_url: format!("http://127.0.0.1:{approved_port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + let outcome = transport.send(send).await; + + // 307 原样上抛(不跟随、不报错、不重发) + match outcome { + SendOutcome::Delivered(raw) => assert_eq!(raw.status, 307, "307 必须原样透传"), + other => panic!("expected Delivered(307), got {other:?}"), + } + assert!(served_307.load(Ordering::SeqCst), "获准地址已返回 307"); + + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + // 关键断言:重定向目标收到的字节数为零(修复前会收到完整 POST body) + assert_eq!( + evil_received.load(Ordering::SeqCst), + 0, + "重定向目标必须收到零字节(获准目的地=实际目的地)" + ); +} diff --git a/powercontext/gateway/crates/pc-gateway-types/Cargo.toml b/powercontext/gateway/crates/pc-gateway-types/Cargo.toml new file mode 100644 index 0000000000..172530425c --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-types/Cargo.toml @@ -0,0 +1,26 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-types" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: check API DTOs, envelope bindings and shared value types" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +bytes = { workspace = true } +thiserror = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-types/src/check.rs b/powercontext/gateway/crates/pc-gateway-types/src/check.rs new file mode 100644 index 0000000000..b517a3b032 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-types/src/check.rs @@ -0,0 +1,151 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! PR #2264 定义的 `POST /v1/context/check` 真实契约。 +//! +//! 关键语义(openapi/powercontext.yaml 原文): +//! - HTTP success alone is not approval——只有完整覆盖的 allow 才许可对应阶段; +//! - 执行器必须在 deadline(valid_until / limits.send_seconds)前 +//! 发送/释放**恰好获批的字节**; +//! - binding 是不透明字符串,绑定 phase、身份、目标、策略与精确载荷; +//! - correlate_until 只是关联窗口,绝不许可新的发送。 + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const MODEL_JSON_PAYLOAD_SCHEMA: &str = "powercontext.model-json-payload.v1"; +pub const CONTEXT_CHECK_SCHEMA: &str = "powercontext.context-check.v1"; +pub const CONTEXT_CHECK_COMPLETION: &str = "complete"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckPhase { + BeforeSend, + BeforeRelease, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckDecision { + Allow, + Block, + Withhold, +} + +/// 完整载荷信封:仅内容与协议头(凭据、传输覆盖头被禁止),body 为完整原始 JSON 文本。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelJsonPayload { + pub schema: String, + pub headers: BTreeMap, + pub body: String, +} + +impl ModelJsonPayload { + pub fn new(headers: BTreeMap, body: String) -> Self { + Self { + schema: MODEL_JSON_PAYLOAD_SCHEMA.into(), + headers, + body, + } + } +} + +/// prepare 复用信封的定位(binding + 文本位置;位置语义归 Core)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedContextLocation { + pub binding: String, + pub location: ModelJsonTextLocation, +} + +/// 线格式 JSON 指针 + 解码后 UTF-8 文本的半开字节区间。 +/// 指针形如 /messages/{i}/content 或 /messages/{i}/content/{j}/text, +/// 必须指向 user 消息(PC 的 _message_text 强制校验)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelJsonTextLocation { + pub schema: String, + pub pointer: String, + pub start_byte: u64, + pub end_byte: u64, +} + +pub const MODEL_JSON_TEXT_LOCATION_SCHEMA: &str = "powercontext.model-json-text-location.v1"; + +/// `check_context` 请求:按 phase 二选一(内部标签即 phase 字段)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "phase", rename_all = "snake_case")] +pub enum ContextCheckRequest { + BeforeSend { + scope_id: String, + target_profile: String, + payload: ModelJsonPayload, + /// 线格式必填:无复用块时也必须显式携带空数组。 + prepared_contexts: Vec, + }, + BeforeRelease { + scope_id: String, + target_profile: String, + /// 对应 before_send allow 返回的 binding。 + request_binding: String, + payload: ModelJsonPayload, + completion: String, + }, +} + +/// `check_context` 响应。两阶段共用 allow/block/withhold: +/// before_release 的 allow 即放行决定,block 即拒绝释放。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextCheckResult { + pub schema: String, + pub phase: CheckPhase, + pub decision: CheckDecision, + /// 无正文原因类别。 + pub reason_codes: Vec, + pub coverage: ContextCheckCoverage, + pub policy_version: String, + /// RFC3339 时间;发送/释放必须在此之前完成。 + pub valid_until: String, + /// 仅 before_send allow 有;绝不许可新发送。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub correlate_until: Option, + /// 仅 allow 有:不透明绑定字符串。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub binding: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextCheckCoverage { + pub profile: String, + pub complete: bool, +} + +/// ContextProtectionCapabilities(能力发现;enforcing 是动态降级的依据)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextProtectionCapabilities { + pub check_versions: Vec, + pub payload_versions: Vec, + pub reuse_versions: Vec, + pub reuse_families: Vec, + pub enforcing: bool, + pub limits: ContextProtectionLimits, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextProtectionLimits { + pub payload_bytes: u64, + pub binding_bytes: u64, + pub prepared_contexts: u64, + pub dependencies: u64, + pub send_seconds: u64, + pub correlate_seconds: u64, +} diff --git a/powercontext/gateway/crates/pc-gateway-types/src/lib.rs b/powercontext/gateway/crates/pc-gateway-types/src/lib.rs new file mode 100644 index 0000000000..5865fa1c38 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-types/src/lib.rs @@ -0,0 +1,24 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! PR #2264 契约值类型。 +//! +//! 网关无策略:这里的类型只承载 Core 的输入/输出, +//! 与 openapi/powercontext.yaml 对齐。 + +mod check; +mod prepare; + +pub use check::*; +pub use prepare::*; diff --git a/powercontext/gateway/crates/pc-gateway-types/src/prepare.rs b/powercontext/gateway/crates/pc-gateway-types/src/prepare.rs new file mode 100644 index 0000000000..88702dc2a2 --- /dev/null +++ b/powercontext/gateway/crates/pc-gateway-types/src/prepare.rs @@ -0,0 +1,113 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! prepare 契约(PR #2264),字段形状对照真实响应校准。 + +use serde::{Deserialize, Serialize}; + +/// 注入块的标准包裹标记(与 PC 的 `_MARKERS` 对齐): +/// check 会扫描载荷中所有字符串,含标记的字节必须被 prepared_contexts 区间覆盖。 +pub const PREPARED_CONTEXT_MARKER_BEGIN: &str = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"; +pub const PREPARED_CONTEXT_MARKER_END: &str = "END_POWERCONTEXT_PREPARED_CONTEXT_V1"; + +pub const PREPARED_CONTEXT_SCHEMA: &str = "powercontext.prepared-context.v1"; +pub const PREPARED_CONTEXT_WITH_REUSE_SCHEMA: &str = "powercontext.prepared-context-with-reuse.v1"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PrepareContextRequest { + pub scope_id: String, + pub query: String, + #[serde(default = "default_max_bytes")] + pub max_bytes: u32, + #[serde(default)] + pub include_reuse: bool, +} + +fn default_max_bytes() -> u32 { + 8192 +} + +/// prepare 响应:普通 PreparedContext 或带复用信封的 WithReuse(按 schema 判别)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PrepareContextResult { + WithReuse { + schema: String, + context: PreparedContext, + reuse: ContextReuse, + }, + Plain(PreparedContext), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedContext { + pub schema: String, + /// ready 时为内容文本;empty 时为 None。 + pub status: String, + pub content: Option, + pub content_bytes: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextReuse { + pub schema: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub constraints: Option, + /// RFC3339。 + pub expires_at: String, + pub binding: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ReuseConstraints { + #[serde(default)] + pub preserve: Vec, + #[serde(default)] + pub refresh_on: Vec, +} + +impl PrepareContextResult { + pub fn content(&self) -> Option<&str> { + match self { + PrepareContextResult::WithReuse { context, .. } => context.content.as_deref(), + PrepareContextResult::Plain(c) => c.content.as_deref(), + } + } + + pub fn binding(&self) -> Option<&str> { + match self { + PrepareContextResult::WithReuse { reuse, .. } => Some(&reuse.binding), + PrepareContextResult::Plain(_) => None, + } + } +} + +/// 标准注入块:与 PC 的 `_MARKERS`/摘要校验对齐。 +/// check 会核验区间内字节与 binding 签发内容一致,不得增删一字节。 +pub fn wrap_prepared_block(content: &str) -> String { + format!("{PREPARED_CONTEXT_MARKER_BEGIN}\n{content}\n{PREPARED_CONTEXT_MARKER_END}") +} + +/// `POST /v1/sources/content`(capture_content_source): +/// 同步持久入库(Source journal),提取由 PC 后台异步完成。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CaptureContentSourceRequest { + pub scope_id: String, + /// 调用方指定的稳定 ID(幂等键):用 release binding 摘要生成。 + pub source_id: String, + /// 原始整合内容(≤200000 字符)。仅沉淀过检放行的内容。 + pub content: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} From 4faa44ba25a12487831dc25072a8c53d60ccc225 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 00:10:54 +0800 Subject: [PATCH 08/37] fix(gateway): preserve Chat tool-call metadata through canonicalization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ingress DTO dropped assistant tool_calls and the tool message's tool_call_id, and rendered content:null as an empty array — an invalid continuation that breaks any function-calling client. CanonicalMessage now carries tool_calls, tool_call_id and a content-null marker; the chat renderer emits content:null with the verbatim tool_calls array and preserves the pairing id. Responses items are unaffected. Tests: round trip reproduces the review probe (assistant with content:null + tool_calls, tool message with tool_call_id reaches the wire intact) plus ingress canonicalization units. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 62 +++++++++- .../pc-gateway-core/src/http_gate_client.rs | 6 +- .../tests/executor_semantics.rs | 3 + .../pc-gateway-protocol/src/canonical.rs | 10 ++ .../crates/pc-gateway-protocol/src/render.rs | 30 +++-- .../tests/openai_renderer.rs | 58 ++++++++++ .../tests/openai_responses_renderer.rs | 9 ++ .../src/reqwest_transport.rs | 4 + .../tests/no_redirect_resend.rs | 107 ++++++++++++++++++ 9 files changed, 278 insertions(+), 11 deletions(-) create mode 100644 gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 96883ae214..f470df8866 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -43,6 +43,10 @@ struct OpenAiMessage { role: String, #[serde(default)] content: serde_json::Value, + #[serde(default)] + tool_calls: Option>, + #[serde(default)] + tool_call_id: Option, } /// Responses API 入口请求(同格式进出,不与 chat 互转)。 @@ -204,13 +208,20 @@ fn to_canonical_chat(chat: OpenAiChatRequest) -> Result Role::Tool, other => return Err(format!("unsupported role: {other}")), }; + let content_null = m.content.is_null(); let content = match m.content { serde_json::Value::String(s) => vec![serde_json::Value::String(s)], serde_json::Value::Array(a) => a, serde_json::Value::Null => vec![], other => return Err(format!("unsupported content type: {other}")), }; - messages.push(CanonicalMessage { role, content }); + messages.push(CanonicalMessage { + role, + content, + content_null, + tool_calls: m.tool_calls, + tool_call_id: m.tool_call_id, + }); } Ok(CanonicalRequest { model: chat.model, @@ -245,6 +256,9 @@ fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result Result a.clone(), _ => vec![], }; - messages.push(CanonicalMessage { role, content }); + messages.push(CanonicalMessage { + role, + content, + content_null: false, + tool_calls: None, + tool_call_id: None, + }); } Ok(CanonicalRequest { model: r.model, @@ -327,3 +347,41 @@ fn respond(outcome: ManagedOutcome) -> Response { // 抑制未使用导入警告(Bytes 用于类型别名文档场景)。 #[allow(dead_code)] fn _unused(_: Option) {} + +#[cfg(test)] +mod tests { + //! PR #2307 review P2:chat 工具元数据经入口 canonical 化的保真测试。 + use super::*; + + #[test] + fn chat_ingress_preserves_tool_fields_and_null_content() { + let body = r#"{ + "model": "m", + "messages": [ + {"role": "assistant", "content": null, + "tool_calls": [{"id": "call_1", "type": "function", + "function": {"name": "get_weather", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "call_1", "content": "sunny"} + ], + "max_tokens": 8 + }"#; + let chat: OpenAiChatRequest = serde_json::from_str(body).unwrap(); + let canonical = to_canonical_chat(chat).unwrap(); + let a = &canonical.messages[0]; + assert!(a.content_null, "content:null 必须被记录"); + assert!(a.content.is_empty()); + assert_eq!(a.tool_calls.as_deref().map(|t| t.len()), Some(1)); + let t = &canonical.messages[1]; + assert_eq!(t.tool_call_id.as_deref(), Some("call_1")); + assert_eq!(t.content[0], serde_json::json!("sunny")); + } + + #[test] + fn chat_ingress_null_content_without_tool_calls_also_preserved() { + let body = r#"{"model":"m","messages":[{"role":"assistant","content":null}],"max_tokens":8}"#; + let chat: OpenAiChatRequest = serde_json::from_str(body).unwrap(); + let canonical = to_canonical_chat(chat).unwrap(); + assert!(canonical.messages[0].content_null); + assert!(canonical.messages[0].tool_calls.is_none()); + } +} diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs index 747abe16e1..9499eede79 100644 --- a/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -38,7 +38,11 @@ impl HttpGateClient { pub fn with_token(base_url: impl Into, token: Option) -> Self { Self { base_url: base_url.into().trim_end_matches('/').to_string(), - client: reqwest::Client::new(), + // 同一原则:获准目的地 = 实际目的地;3xx 原样上抛,不自动跟随。 + client: reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .expect("reqwest client build"), token: token.filter(|t| !t.is_empty()), } } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index ce91449351..5a3da414cd 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -191,6 +191,9 @@ fn call(degrade: DegradePolicy) -> ManagedCall { messages: vec![CanonicalMessage { role: Role::User, content: vec![serde_json::json!("hello")], + content_null: false, + tool_calls: None, + tool_call_id: None, }], tools: vec![], instructions: None, diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs index 260df4819d..8cc83d58a0 100644 --- a/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -39,6 +39,16 @@ pub struct CanonicalRequest { pub struct CanonicalMessage { pub role: Role, pub content: Vec, + /// 原始 content 为 JSON null(assistant 发起工具调用时的规范形态)。 + /// 渲染时必须还原为 null 而非空数组,否则上游校验拒绝。 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub content_null: bool, + /// assistant 消息的工具调用声明(chat 线格式),原样透传不解释。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_calls: Option>, + /// tool 消息的结果配对 id,原样透传(丢失即破坏工具循环)。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_call_id: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index 8552772426..75fe54651a 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -59,17 +59,31 @@ impl WireRenderer for OpenAiChatRenderer { // 无 type 的部件数组);多部件 content 按原样透传。 let mut messages = Vec::with_capacity(request.messages.len()); for m in &request.messages { - let content: serde_json::Value = match m.content.as_slice() { - [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), - other => serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { - renderer: self.name(), - field: e.to_string(), - })?, + let content: serde_json::Value = if m.content_null { + serde_json::Value::Null + } else { + match m.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => serde_json::to_value(other).map_err(|e| { + RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + } + })?, + } }; - messages.push(serde_json::json!({ + let mut message = serde_json::json!({ "role": m.role, "content": content, - })); + }); + // 工具调用元数据原样透传:配对 id 与调用声明缺一不可。 + if let Some(tool_calls) = &m.tool_calls { + message["tool_calls"] = serde_json::json!(tool_calls); + } + if let Some(tool_call_id) = &m.tool_call_id { + message["tool_call_id"] = serde_json::json!(tool_call_id); + } + messages.push(message); } // 只写入确定性的结构字段;不写请求 ID/时间戳(缓存前缀保真)。 diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index 7b51de714d..318519805f 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -22,6 +22,9 @@ fn request() -> CanonicalRequest { messages: vec![CanonicalMessage { role: Role::User, content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, }], tools: vec![], instructions: None, @@ -72,3 +75,58 @@ fn stream_flag_reaches_wire_format() { let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); assert_eq!(v["stream"], true, "stream 标志必须原样到达线格式"); } + +#[test] +fn tool_call_metadata_round_trip_preserved() { + // PR #2307 review P2:assistant 的 tool_calls 与 tool 消息的 tool_call_id + // 必须原样到达线格式,content:null 必须保持 null(不得变空数组)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![ + CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("天气如何?")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }, + CanonicalMessage { + role: Role::Assistant, + content: vec![], // 原始 content: null + content_null: true, + tool_calls: Some(vec![serde_json::json!({ + "id": "call_1", "type": "function", + "function": {"name": "get_weather", "arguments": "{\"city\":\"北京\"}"} + })]), + tool_call_id: None, + }, + CanonicalMessage { + role: Role::Tool, + content: vec![serde_json::json!("sunny")], + content_null: false, + tool_calls: None, + tool_call_id: Some("call_1".into()), + }, + ], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { max_output_tokens: 16 }, + stream: false, + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + let msgs = v["messages"].as_array().unwrap(); + + assert_eq!(msgs.len(), 3); + // assistant:content 为 null + tool_calls 完整 + assert!(msgs[1]["content"].is_null(), "content:null 必须保持 null,实际: {}", msgs[1]["content"]); + let tc = msgs[1]["tool_calls"].as_array().unwrap(); + assert_eq!(tc[0]["id"], "call_1"); + assert_eq!(tc[0]["function"]["name"], "get_weather"); + // tool:配对 id 保留 + assert_eq!(msgs[2]["tool_call_id"], "call_1"); + assert_eq!(msgs[2]["content"], "sunny"); + // 普通消息不受影响 + assert_eq!(msgs[0]["content"], "天气如何?"); +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index efd9937d6a..722edd58f6 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -23,6 +23,9 @@ fn request() -> CanonicalRequest { messages: vec![CanonicalMessage { role: Role::User, content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, }], tools: vec![], instructions: Some("be terse".into()), @@ -58,11 +61,17 @@ fn responses_items_pass_through_verbatim() { CanonicalMessage { role: Role::User, content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, }, // 无 role 的顶层 item:原样封进 content,渲染时作为顶层 item 透出 CanonicalMessage { role: Role::Tool, content: vec![fc.clone()], + content_null: false, + tool_calls: None, + tool_call_id: None, }, ], tools: vec![], diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index db8b9d7626..8bca8bcfb0 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -36,6 +36,10 @@ pub struct ReqwestTransport { impl ReqwestTransport { pub fn new(timeout: Duration) -> Self { let client = reqwest::Client::builder() + // 获准目的地必须保持为实际目的地:307/308 会让 reqwest 把已准入的 + // POST body 原样重发到未经 Core 审查的新地址。禁用自动跟随,重定向 + // 响应原样上抛(经 before_release 后透传给调用方),字节绝不自动重发。 + .redirect(reqwest::redirect::Policy::none()) .timeout(timeout) .build() .expect("reqwest client build"); diff --git a/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs b/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs new file mode 100644 index 0000000000..5baf3229dd --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs @@ -0,0 +1,107 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P1-2): +//! 获准上游返回 307 时,reqwest 默认会把已准入的 POST body 原样重发到 +//! Location 指向的第二个地址(未经 Core 准入)。禁用自动跟随后: +//! 第二地址必须收到零字节;307 响应原样透传(Delivered status=307)。 + +use pc_gateway_transport::{AdmittedSend, ReqwestTransport, SendOutcome, Transport}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +/// 读一条完整 HTTP 请求(头 + content-length body),返回原始字节。 +async fn read_request(sock: &mut TcpStream) -> Vec { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); + let len: usize = head + .lines() + .find_map(|l| l.strip_prefix("content-length: ")) + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0); + if buf.len() >= pos + 4 + len { + break; + } + } + } + buf +} + +#[tokio::test] +async fn redirect_target_receives_nothing_and_307_surfaces() { + // 第二地址(重定向目标):任何到达的字节都记为违规 + let evil = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let evil_port = evil.local_addr().unwrap().port(); + let evil_received = Arc::new(AtomicUsize::new(0)); + let er = evil_received.clone(); + tokio::spawn(async move { + if let Ok((mut sock, _)) = evil.accept().await { + let data = read_request(&mut sock).await; + er.fetch_add(data.len(), Ordering::SeqCst); + let resp = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"; + let _ = sock.write_all(resp).await; + } + }); + + // 第一地址(获准上游):读完整请求后回 307 指向第二地址 + let approved = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let approved_port = approved.local_addr().unwrap().port(); + let served_307 = Arc::new(AtomicBool::new(false)); + let s307 = served_307.clone(); + let evil_addr = format!("127.0.0.1:{evil_port}"); + tokio::spawn(async move { + let (mut sock, _) = approved.accept().await.unwrap(); + let _ = read_request(&mut sock).await; + let resp = format!( + "HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{evil_addr}/steer\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + sock.write_all(resp.as_bytes()).await.unwrap(); + s307.store(true, Ordering::SeqCst); + }); + + let transport = ReqwestTransport::default(); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), + target_url: format!("http://127.0.0.1:{approved_port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + let outcome = transport.send(send).await; + + // 307 原样上抛(不跟随、不报错、不重发) + match outcome { + SendOutcome::Delivered(raw) => assert_eq!(raw.status, 307, "307 必须原样透传"), + other => panic!("expected Delivered(307), got {other:?}"), + } + assert!(served_307.load(Ordering::SeqCst), "获准地址已返回 307"); + + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + // 关键断言:重定向目标收到的字节数为零(修复前会收到完整 POST body) + assert_eq!( + evil_received.load(Ordering::SeqCst), + 0, + "重定向目标必须收到零字节(获准目的地=实际目的地)" + ); +} From 9c4a129cce70b94719e6a0920f4c6d352f35e2ae Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 00:13:23 +0800 Subject: [PATCH 09/37] fix(gateway): keep Responses text content in a valid wire shape The Responses renderer serialized single-string message content as a bare string array (["hello"]), which is not a valid Responses content form (string or typed content parts). Single-string content now stays a string; typed-part arrays pass through unchanged; content:null is preserved. The existing renderer test now asserts the content shape, and a typed-parts passthrough test was added. Signed-off-by: ztelur --- .../crates/pc-gateway-protocol/src/render.rs | 21 +++++++++---- .../tests/openai_responses_renderer.rs | 30 +++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index 75fe54651a..785b912d90 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -215,11 +215,22 @@ impl WireRenderer for OpenAiResponsesRenderer { input.push(msg.content[0].clone()); continue; } - let content: serde_json::Value = serde_json::to_value(&msg.content) - .map_err(|e| RenderError::UnsupportedField { - renderer: self.name(), - field: e.to_string(), - })?; + // Responses 线格式的 message.content 只能是 string 或 typed parts 数组; + // 裸字符串数组(["hello"])是非法形态。单字符串保持 string, + // 多元素(typed parts / Responses 专有 item 外的数组)原样透传。 + let content: serde_json::Value = if msg.content_null { + serde_json::Value::Null + } else { + match msg.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => serde_json::to_value(other).map_err(|e| { + RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + } + })?, + } + }; input.push(serde_json::json!({ "role": msg.role, "content": content, diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 722edd58f6..68e0af4bcb 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -46,6 +46,7 @@ fn renders_responses_wire_format() { assert_eq!(v["max_output_tokens"], 16); assert_eq!(v["stream"], false); assert_eq!(v["input"][0]["role"], "user"); + assert_eq!(v["input"][0]["content"], "hi", "单字符串 content 必须保持 string(review P2:不得变 [\"hi\"])"); assert!(v.get("messages").is_none(), "不得混入 chat 字段"); assert!(v.get("max_tokens").is_none()); } @@ -96,3 +97,32 @@ fn merges_only_approved_cache_plan_fields() { assert_eq!(v["prompt_cache_key"], "scope-1"); assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); } + +#[test] +fn typed_content_parts_pass_through_as_array() { + // 多部件(typed parts)content 原样透传为数组;与单字符串形态并存不冲突。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![ + serde_json::json!({"type": "input_text", "text": "看这张图"}), + serde_json::json!({"type": "input_image", "image_url": "data:image/png;base64,xxx"}), + ], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { max_output_tokens: 16 }, + stream: false, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + let content = v["input"][0]["content"].as_array().unwrap(); + assert_eq!(content.len(), 2); + assert_eq!(content[0]["type"], "input_text"); + assert_eq!(content[1]["type"], "input_image"); +} From 301d54efc0ffd9b16f84518a0991731f19ef622a Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 00:24:22 +0800 Subject: [PATCH 10/37] fix(gateway): apply the response buffer limit to nonstreaming calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The nonstreaming path collected the whole response with resp.bytes() and never applied max_buffer_bytes — the advertised bounded buffering was ineffective on the usual nonstreaming path, and the response was fully allocated before any release check. Both response modes now share the incremental chunked accumulation with the byte cap; the only difference is TTFT measurement, recorded for streaming requests. Exceeding the limit stops reading and classifies as Indeterminate(BufferLimitExceeded). Regression tests on a real socket: with_buffer_limit(16) rejects a 1 KiB nonstreaming response; a within-limit response still delivers. Signed-off-by: ztelur --- .../src/reqwest_transport.rs | 80 ++++++-------- .../tests/buffer_limit_nonstreaming.rs | 102 ++++++++++++++++++ 2 files changed, 134 insertions(+), 48 deletions(-) create mode 100644 gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index 8bca8bcfb0..868c24f798 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -109,59 +109,43 @@ impl Transport for ReqwestTransport { .unwrap_or("application/json") .to_string(); - if send.stream { - // 流式接收:逐块累积 + TTFT 计量 + 字节上限。 - let start = Instant::now(); - let mut body: Vec = Vec::with_capacity(16 * 1024); - let mut ttft: Option = None; - let mut stream = resp.bytes_stream(); - loop { - match next_chunk(&mut stream).await { - None => break, - Some(Err(_)) => { - return SendOutcome::Indeterminate( - SendIndeterminateReason::LostAfterHandoff, - ) + // 两种接收模式共用逐块累积 + 字节上限(review P2:非流式路径 + // 此前用 resp.bytes() 一次性收集,max_buffer_bytes 完全不生效)。 + // 区别仅在计量:流式记录 TTFT。 + let start = Instant::now(); + let mut body: Vec = Vec::with_capacity(16 * 1024); + let mut ttft: Option = None; + let mut stream = resp.bytes_stream(); + loop { + match next_chunk(&mut stream).await { + None => break, + Some(Err(_)) => { + return SendOutcome::Indeterminate( + SendIndeterminateReason::LostAfterHandoff, + ) + } + Some(Ok(chunk)) => { + if send.stream && ttft.is_none() { + ttft = Some(start.elapsed().as_millis() as u64); } - Some(Ok(chunk)) => { - if ttft.is_none() { - ttft = Some(start.elapsed().as_millis() as u64); - } - if body.len() + chunk.len() > self.max_buffer_bytes { - // 已送达且部分计费:不重发,向上标记不确定。 - return SendOutcome::Indeterminate( - SendIndeterminateReason::BufferLimitExceeded, - ); - } - body.extend_from_slice(&chunk); + if body.len() + chunk.len() > self.max_buffer_bytes { + // 已送达且部分计费:不重发,向上标记不确定。 + return SendOutcome::Indeterminate( + SendIndeterminateReason::BufferLimitExceeded, + ); } - } - } - let usage = extract_usage(&body); - SendOutcome::Delivered(RawResponse { - status, - body: Bytes::from(body), - content_type, - ttft_ms: ttft, - usage, - }) - } else { - match resp.bytes().await { - Err(_) => { - SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) - } - Ok(body) => { - let usage = extract_usage(&body); - SendOutcome::Delivered(RawResponse { - status, - body, - content_type, - ttft_ms: None, - usage, - }) + body.extend_from_slice(&chunk); } } } + let usage = extract_usage(&body); + SendOutcome::Delivered(RawResponse { + status, + body: Bytes::from(body), + content_type, + ttft_ms: ttft, + usage, + }) }) } diff --git a/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs b/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs new file mode 100644 index 0000000000..2116a50d5d --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs @@ -0,0 +1,102 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P2): +//! 非流式路径的字节上限。with_buffer_limit(16) 下收到 1KB 响应必须 +//! 判为 Indeterminate(BufferLimitExceeded),不得 Delivered。 + +use pc_gateway_transport::{ + AdmittedSend, ReqwestTransport, SendIndeterminateReason, SendOutcome, Transport, +}; +use std::time::Duration; +use tokio::io::AsyncWriteExt; +use tokio::net::TcpListener; + +#[tokio::test] +async fn nonstreaming_response_over_buffer_limit_is_rejected() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + // 读掉请求(忽略内容,client 会发完整 POST) + let mut buf = vec![0u8; 8192]; + let _ = tokio::time::timeout(Duration::from_secs(5), async { + use tokio::io::AsyncReadExt as _; + let _ = sock.read(&mut buf).await; + }) + .await; + // 回一个超过 16 字节上限的 JSON 响应 + let body = format!("{{\"padding\":\"{}\"}}", "x".repeat(1024)); + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = sock.write_all(resp.as_bytes()).await; + }); + + let transport = ReqwestTransport::new(Duration::from_secs(10)).with_buffer_limit(16); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(b"{}"), + target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), + headers: vec![], + stream: false, // 关键:非流式路径 + }; + let outcome = transport.send(send).await; + match outcome { + SendOutcome::Indeterminate(SendIndeterminateReason::BufferLimitExceeded) => {} + other => panic!("expected Indeterminate(BufferLimitExceeded), got {other:?}"), + } +} + +#[tokio::test] +async fn nonstreaming_response_within_limit_still_delivers() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + let mut buf = vec![0u8; 8192]; + let _ = tokio::time::timeout(Duration::from_secs(5), async { + use tokio::io::AsyncReadExt as _; + let _ = sock.read(&mut buf).await; + }) + .await; + let body = r#"{"ok":true}"#; + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = sock.write_all(resp.as_bytes()).await; + }); + + let transport = ReqwestTransport::new(Duration::from_secs(10)).with_buffer_limit(1024); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(b"{}"), + target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + let outcome = transport.send(send).await; + match outcome { + SendOutcome::Delivered(raw) => { + assert_eq!(raw.status, 200); + let v: serde_json::Value = serde_json::from_slice(&raw.body).unwrap(); + assert_eq!(v["ok"], true); + } + other => panic!("expected Delivered, got {other:?}"), + } +} From 007aa230e91b2866e5117e907bd819695d41bdc2 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 19:23:57 +0800 Subject: [PATCH 11/37] style(gateway): drop narrative comment at the redirect policy Signed-off-by: ztelur --- gateway/crates/pc-gateway-core/src/http_gate_client.rs | 1 - gateway/crates/pc-gateway-transport/src/reqwest_transport.rs | 3 --- 2 files changed, 4 deletions(-) diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs index 9499eede79..3f4e5ca9d2 100644 --- a/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -38,7 +38,6 @@ impl HttpGateClient { pub fn with_token(base_url: impl Into, token: Option) -> Self { Self { base_url: base_url.into().trim_end_matches('/').to_string(), - // 同一原则:获准目的地 = 实际目的地;3xx 原样上抛,不自动跟随。 client: reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .build() diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index 868c24f798..d1d5312ea8 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -36,9 +36,6 @@ pub struct ReqwestTransport { impl ReqwestTransport { pub fn new(timeout: Duration) -> Self { let client = reqwest::Client::builder() - // 获准目的地必须保持为实际目的地:307/308 会让 reqwest 把已准入的 - // POST body 原样重发到未经 Core 审查的新地址。禁用自动跟随,重定向 - // 响应原样上抛(经 before_release 后透传给调用方),字节绝不自动重发。 .redirect(reqwest::redirect::Policy::none()) .timeout(timeout) .build() From a0b9cb0c36d8b629b374e1cce99c54eb19089633 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 19:33:57 +0800 Subject: [PATCH 12/37] fix(gateway): enforce the configured body limit on chunked requests The middleware precheck only inspects Content-Length, so the same oversized body sailed through with chunked framing while the ingress consumed it under a separate hard-coded 32 MiB cap. The ingress now consumes the body under the configured PC_GATEWAY_MAX_BODY_BYTES and maps the length-limit error to 413 (same semantics as the precheck), so callers cannot bypass the admission limit by changing HTTP framing. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 17 ++++++++++++++--- gateway/crates/pc-gateway-app/src/main.rs | 3 +++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index f470df8866..4b406e5f38 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -106,12 +106,23 @@ async fn ingress_common( } } - let body = match axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024).await { + // Applies the configured limit to the consumed body as well: chunked requests have no Content-Length, + // so the middleware precheck cannot limit them. Here we use the same configured value to prevent bypassing via framing. + let body = match axum::body::to_bytes(req.into_body(), state.max_body_bytes).await { Ok(b) => b, Err(e) => { + // 区分超限(413,与中间件预检语义一致)与其他读取错误(400)。 + let over_limit = std::error::Error::source(&e) + .and_then(|s| s.downcast_ref::()) + .is_some(); + let (status, code) = if over_limit { + (StatusCode::PAYLOAD_TOO_LARGE, "request_body_too_large") + } else { + (StatusCode::BAD_REQUEST, "invalid_body") + }; return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({ "error": "invalid_body", "detail": e.to_string() })), + status, + Json(serde_json::json!({ "error": code, "detail": e.to_string() })), ) .into_response() } diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 4aedc03a86..ec8c9b7131 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -59,6 +59,8 @@ pub struct AppState { pub sediment: bool, /// 默认 Scope(启动时读一次,避免热路径读环境变量)。 pub default_scope: String, + /// Request body byte limit (also enforced when consuming chunked bodies). + pub max_body_bytes: usize, } #[tokio::main] @@ -117,6 +119,7 @@ async fn main() { sediment: matches!(std::env::var("PC_GATEWAY_SEDIMENT").as_deref(), Ok("on")), default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") .unwrap_or_else(|_| "gateway:default".into()), + max_body_bytes, }); let router = Router::new() From 88c0dc4ec70a7a3a7151d512c22162d4fb387557 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 20:39:33 +0800 Subject: [PATCH 13/37] chore: remove accidentally committed stale gateway copy powercontext/gateway/ was a stale snapshot introduced by 5a89508: a relative-path rsync ran with the shell cwd drifted inside the repo, copying the workspace into a nested powercontext/ subdirectory that was then committed alongside the intended top-level gateway/. The copy carried no workspace manifest, participated in no build, and lacked the subsequent fixes (b87c096 duplicate-send, 5a89508 redirects were partially present, 301d54e buffer limit, a0b9cb0 chunked limit), leaving ~4.9k lines of misleading dead code. Adds a .gitignore entry to prevent the same shape from reappearing. Signed-off-by: ztelur --- .gitignore | 1 + .../gateway/crates/pc-gateway-app/Cargo.toml | 43 -- .../crates/pc-gateway-app/src/ingress.rs | 329 -------- .../gateway/crates/pc-gateway-app/src/link.rs | 79 -- .../gateway/crates/pc-gateway-app/src/main.rs | 159 ---- .../pc-gateway-app/src/middleware/mod.rs | 77 -- .../src/middleware/request_id.rs | 68 -- .../src/middleware/resource_limits.rs | 99 --- .../crates/pc-gateway-app/src/proxy.rs | 163 ---- .../gateway/crates/pc-gateway-core/Cargo.toml | 33 - .../crates/pc-gateway-core/src/executor.rs | 402 ---------- .../crates/pc-gateway-core/src/gate_client.rs | 58 -- .../pc-gateway-core/src/http_gate_client.rs | 123 --- .../gateway/crates/pc-gateway-core/src/lib.rs | 36 - .../pc-gateway-core/src/uds_gate_client.rs | 418 ----------- .../tests/executor_semantics.rs | 709 ------------------ .../tests/live_context_check.rs | 249 ------ .../crates/pc-gateway-core/tests/uds_pool.rs | 128 ---- .../crates/pc-gateway-embedded/Cargo.toml | 24 - .../crates/pc-gateway-embedded/src/lib.rs | 22 - .../crates/pc-gateway-evidence/Cargo.toml | 24 - .../crates/pc-gateway-evidence/src/lib.rs | 112 --- .../crates/pc-gateway-protocol/Cargo.toml | 27 - .../pc-gateway-protocol/src/canonical.rs | 63 -- .../crates/pc-gateway-protocol/src/lib.rs | 27 - .../crates/pc-gateway-protocol/src/render.rs | 248 ------ .../crates/pc-gateway-protocol/src/sse.rs | 87 --- .../tests/openai_renderer.rs | 74 -- .../tests/openai_responses_renderer.rs | 89 --- .../crates/pc-gateway-transport/Cargo.toml | 30 - .../crates/pc-gateway-transport/src/lib.rs | 29 - .../src/reqwest_transport.rs | 190 ----- .../crates/pc-gateway-transport/src/retry.rs | 69 -- .../crates/pc-gateway-transport/src/sender.rs | 86 --- .../tests/no_duplicate_send.rs | 106 --- .../tests/no_redirect_resend.rs | 107 --- .../crates/pc-gateway-types/Cargo.toml | 26 - .../crates/pc-gateway-types/src/check.rs | 151 ---- .../crates/pc-gateway-types/src/lib.rs | 24 - .../crates/pc-gateway-types/src/prepare.rs | 113 --- 40 files changed, 1 insertion(+), 4901 deletions(-) delete mode 100644 powercontext/gateway/crates/pc-gateway-app/Cargo.toml delete mode 100644 powercontext/gateway/crates/pc-gateway-app/src/ingress.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-app/src/link.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-app/src/main.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-app/src/proxy.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/Cargo.toml delete mode 100644 powercontext/gateway/crates/pc-gateway-core/src/executor.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/src/lib.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml delete mode 100644 powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml delete mode 100644 powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml delete mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/render.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-transport/Cargo.toml delete mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/lib.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/retry.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-transport/src/sender.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-types/Cargo.toml delete mode 100644 powercontext/gateway/crates/pc-gateway-types/src/check.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-types/src/lib.rs delete mode 100644 powercontext/gateway/crates/pc-gateway-types/src/prepare.rs diff --git a/.gitignore b/.gitignore index 9ba229d6b3..6d7cca108a 100644 --- a/.gitignore +++ b/.gitignore @@ -276,3 +276,4 @@ integrations/pi/plugins/powercontext/*.tgz # pnpm package store is a local cache, never committed. .pnpm-store/ +powercontext/gateway/ diff --git a/powercontext/gateway/crates/pc-gateway-app/Cargo.toml b/powercontext/gateway/crates/pc-gateway-app/Cargo.toml deleted file mode 100644 index 7ec1f5056b..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/Cargo.toml +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[package] -name = "pc-gateway-app" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "PowerContext Gateway: thin binary — port takeover, Core/MCP forwarding, OpenAI-compatible model ingress" - -[[bin]] -name = "pc-gateway" -path = "src/main.rs" - -[dependencies] -pc-gateway-core = { workspace = true } -pc-gateway-types = { workspace = true } -pc-gateway-protocol = { workspace = true } -pc-gateway-transport = { workspace = true } -pc-gateway-evidence = { workspace = true } -bytes = { workspace = true } -serde = { workspace = true } -tokio = { workspace = true } -axum = { workspace = true } -serde_json = { workspace = true } -tracing = { workspace = true } -tracing-subscriber = { workspace = true } -reqwest = { workspace = true } -hyper = { workspace = true } -tower = { workspace = true } -hyper-util = { workspace = true } -http-body-util = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-app/src/ingress.rs b/powercontext/gateway/crates/pc-gateway-app/src/ingress.rs deleted file mode 100644 index 96883ae214..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/src/ingress.rs +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 模型入口:OpenAI 兼容 `/gateway/v1/chat/completions`。 -//! 客户端只改 Base URL 与 API Key 即接入(PR #2199 产品形态)。 - -use crate::{proxy::SharedProxy, AppState}; -use axum::body::Bytes; -use axum::extract::{Request, State}; -use axum::http::{header, HeaderMap, StatusCode}; -use axum::response::{IntoResponse, Response}; -use axum::Json; -use pc_gateway_core::{ManagedCall, ManagedOutcome}; -use pc_gateway_protocol::{CanonicalMessage, CanonicalRequest, OutputLimits, Role}; -use serde::Deserialize; -use std::sync::Arc; - -#[derive(Debug, Deserialize)] -struct OpenAiChatRequest { - model: String, - messages: Vec, - #[serde(default)] - tools: Vec, - #[serde(default)] - max_tokens: Option, - #[serde(default)] - stream: Option, -} - -#[derive(Debug, Deserialize)] -struct OpenAiMessage { - role: String, - #[serde(default)] - content: serde_json::Value, -} - -/// Responses API 入口请求(同格式进出,不与 chat 互转)。 -#[derive(Debug, Deserialize)] -struct OpenAiResponsesRequest { - model: String, - input: Vec, - #[serde(default)] - instructions: Option, - #[serde(default)] - tools: Vec, - #[serde(default)] - max_output_tokens: Option, - #[serde(default)] - stream: Option, -} - -pub async fn chat_completions( - State((state, _)): State, - headers: HeaderMap, - req: Request, -) -> Response { - ingress_common(state, headers, req, Format::Chat).await -} - -pub async fn responses( - State((state, _)): State, - headers: HeaderMap, - req: Request, -) -> Response { - ingress_common(state, headers, req, Format::Responses).await -} - -enum Format { - Chat, - Responses, -} - -async fn ingress_common( - state: Arc, - headers: HeaderMap, - req: Request, - format: Format, -) -> Response { - // 网关密钥认证(替代服务商 key;上游凭据由受控配置持有)。 - if let Some(expected) = &state.api_key { - let provided = headers - .get(header::AUTHORIZATION) - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.strip_prefix("Bearer ")); - if provided != Some(expected.as_str()) { - return ( - StatusCode::UNAUTHORIZED, - Json(serde_json::json!({ "error": "invalid_gateway_key" })), - ) - .into_response(); - } - } - - let body = match axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024).await { - Ok(b) => b, - Err(e) => { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({ "error": "invalid_body", "detail": e.to_string() })), - ) - .into_response() - } - }; - let canonical = match format { - Format::Chat => { - let chat: OpenAiChatRequest = match serde_json::from_slice(&body) { - Ok(c) => c, - Err(e) => { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({ "error": "invalid_openai_body", "detail": e.to_string() })), - ) - .into_response() - } - }; - match to_canonical_chat(chat) { - Ok(c) => c, - Err(msg) => { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), - ) - .into_response() - } - } - } - Format::Responses => { - let r: OpenAiResponsesRequest = match serde_json::from_slice(&body) { - Ok(c) => c, - Err(e) => { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({ "error": "invalid_responses_body", "detail": e.to_string() })), - ) - .into_response() - } - }; - match to_canonical_responses(r) { - Ok(c) => c, - Err(msg) => { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), - ) - .into_response() - } - } - } - }; - let renderer = match format { - Format::Chat => pc_gateway_protocol::GatewayRenderer::Chat(Default::default()), - Format::Responses => pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), - }; - - let call = ManagedCall { - scope_id: state.default_scope.clone(), - target_profile: state.upstream_profile.clone(), - request: canonical, - target_url: match format { - Format::Chat => state.upstream_chat.clone(), - Format::Responses => state.upstream_responses.clone(), - }, - headers: bearer_headers(match format { - Format::Chat => &state.upstream_chat_api_key, - Format::Responses => &state.upstream_responses_api_key, - }), - degrade_policy: state.degrade, - inject_context: state.inject_context - && matches!(format, Format::Chat), - sediment: state.sediment, - prepared_contexts: Vec::new(), - }; - - let outcome = state.executor.run(call, &renderer, state.evidence.as_ref()).await; - respond(outcome) -} - -fn bearer_headers(key: &str) -> Vec<(String, String)> { - if key.is_empty() { - Vec::new() - } else { - vec![("authorization".to_string(), format!("Bearer {key}"))] - } -} - -fn to_canonical_chat(chat: OpenAiChatRequest) -> Result { - let mut messages = Vec::with_capacity(chat.messages.len()); - for m in chat.messages { - let role = match m.role.as_str() { - "system" => Role::System, - "user" => Role::User, - "assistant" => Role::Assistant, - "tool" => Role::Tool, - other => return Err(format!("unsupported role: {other}")), - }; - let content = match m.content { - serde_json::Value::String(s) => vec![serde_json::Value::String(s)], - serde_json::Value::Array(a) => a, - serde_json::Value::Null => vec![], - other => return Err(format!("unsupported content type: {other}")), - }; - messages.push(CanonicalMessage { role, content }); - } - Ok(CanonicalRequest { - model: chat.model, - messages, - tools: chat.tools, - instructions: None, - native_cache_fields: None, - output_limits: OutputLimits { - max_output_tokens: chat.max_tokens.unwrap_or(1024), - }, - stream: chat.stream.unwrap_or(false), - }) -} - -/// Responses 入口 → 规范类型:消息项照常映射; -/// Responses 专有 item(function_call 等)原样封进 content, -/// 由 `OpenAiResponsesRenderer` 按原样作为顶层 input item 透出(无跨格式转换)。 -fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result { - let mut messages = Vec::with_capacity(r.input.len()); - for item in r.input { - let role_str = item.get("role").and_then(|v| v.as_str()).unwrap_or(""); - let role = match role_str { - "system" | "developer" => Role::System, - "user" => Role::User, - "assistant" => Role::Assistant, - "tool" => Role::Tool, - // 无 role 的顶层 item(function_call/function_call_output 等): - // 原样保留,role 占位为 tool。 - _ => Role::Tool, - }; - if role_str.is_empty() { - messages.push(CanonicalMessage { - role: Role::Tool, - content: vec![item], - }); - continue; - } - let content = match item.get("content") { - Some(serde_json::Value::String(s)) => vec![serde_json::Value::String(s.clone())], - Some(serde_json::Value::Array(a)) => a.clone(), - _ => vec![], - }; - messages.push(CanonicalMessage { role, content }); - } - Ok(CanonicalRequest { - model: r.model, - messages, - tools: r.tools, - instructions: r.instructions, - native_cache_fields: None, - output_limits: OutputLimits { - max_output_tokens: r.max_output_tokens.unwrap_or(1024), - }, - stream: r.stream.unwrap_or(false), - }) -} - -/// 结果映射:不存在静默成功;降级直通必须显式标记。 -fn respond(outcome: ManagedOutcome) -> Response { - match outcome { - ManagedOutcome::Released { status, content_type, body, .. } => { - // 上游状态码与 Content-Type 原样透传(错误不伪装 200)。 - let code = StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY); - ( - code, - [(header::CONTENT_TYPE, content_type.as_str())], - body.to_vec(), - ) - .into_response() - } - ManagedOutcome::Degraded { status, content_type, body } => match Response::builder() - .status( - StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY), - ) - .header(header::CONTENT_TYPE, content_type.as_str()) - .header("x-pc-degraded", "passthrough_without_memory") - .body(axum::body::Body::from(body.to_vec())) - { - Ok(r) => r, - Err(e) => ( - StatusCode::INTERNAL_SERVER_ERROR, - axum::Json(serde_json::json!({ "error": e.to_string() })), - ) - .into_response(), - }, - ManagedOutcome::Blocked { reason_codes } => ( - StatusCode::FORBIDDEN, - Json(serde_json::json!({ "decision": "block", "reason_codes": reason_codes })), - ) - .into_response(), - ManagedOutcome::Withheld { reason_codes } => ( - StatusCode::CONFLICT, - Json(serde_json::json!({ "decision": "withhold", "reason_codes": reason_codes })), - ) - .into_response(), - ManagedOutcome::SendIndeterminate => ( - StatusCode::BAD_GATEWAY, - Json(serde_json::json!({ "decision": "send_indeterminate" })), - ) - .into_response(), - ManagedOutcome::NotSent { attempts } => ( - StatusCode::BAD_GATEWAY, - Json(serde_json::json!({ "decision": "not_sent", "attempts": attempts })), - ) - .into_response(), - ManagedOutcome::GatePaused(msg) => ( - StatusCode::SERVICE_UNAVAILABLE, - Json(serde_json::json!({ "decision": "gate_paused", "detail": msg })), - ) - .into_response(), - } -} - -// 抑制未使用导入警告(Bytes 用于类型别名文档场景)。 -#[allow(dead_code)] -fn _unused(_: Option) {} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/link.rs b/powercontext/gateway/crates/pc-gateway-app/src/link.rs deleted file mode 100644 index 7968f04504..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/src/link.rs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Core 连接形态:UDS(同机组合部署)或 TCP(独立运行)。 - -use pc_gateway_core::{GateClient, GateError, HttpGateClient, UdsGateClient}; -use pc_gateway_types::{ - CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, - PrepareContextResult, -}; - -pub enum CoreLink { - Uds(UdsGateClient), - Http(HttpGateClient), -} - -impl CoreLink { - pub fn from_env() -> Self { - if let Ok(sock) = std::env::var("PC_GATEWAY_CORE_UDS") { - tracing::info!(%sock, "core link: UDS (combined deployment)"); - Self::Uds(UdsGateClient::new(sock)) - } else { - let base = - std::env::var("PC_GATEWAY_CORE_BASE").unwrap_or_else(|_| "http://127.0.0.1:8000".into()); - tracing::info!(%base, "core link: TCP (standalone deployment)"); - Self::Http(HttpGateClient::new(base)) - } - } -} - -impl GateClient for CoreLink { - async fn check( - &self, - request: ContextCheckRequest, - ) -> Result { - match self { - CoreLink::Uds(c) => c.check(request).await, - CoreLink::Http(c) => c.check(request).await, - } - } - - async fn capabilities(&self) -> Result { - match self { - CoreLink::Uds(c) => c.capabilities().await, - CoreLink::Http(c) => c.capabilities().await, - } - } - - async fn prepare( - &self, - request: PrepareContextRequest, - ) -> Result { - match self { - CoreLink::Uds(c) => c.prepare(request).await, - CoreLink::Http(c) => c.prepare(request).await, - } - } - - async fn capture( - &self, - request: CaptureContentSourceRequest, - ) -> Result { - match self { - CoreLink::Uds(c) => c.capture(request).await, - CoreLink::Http(c) => c.capture(request).await, - } - } -} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/main.rs b/powercontext/gateway/crates/pc-gateway-app/src/main.rs deleted file mode 100644 index 4aedc03a86..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/src/main.rs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 薄二进制:端口接管 + 模型入口。所有执行逻辑在 `pc-gateway-core`。 -//! -//! PR #2199 部署形态: -//! - 同机组合:`PC_GATEWAY_CORE_UDS` 指向 Python 的 UDS;网关独占公网端口, -//! 非 `/gateway/*` 流量反向代理到 UDS(原 Core/MCP 路由透传)。 -//! - 独立运行:`PC_GATEWAY_CORE_BASE` 直连远端 PowerContext(无代理)。 -//! -//! 环境变量:PC_GATEWAY_LISTEN、PC_GATEWAY_CORE_UDS、PC_GATEWAY_CORE_BASE、 -//! PC_GATEWAY_API_KEY(网关密钥,替代服务商 key)、PC_GATEWAY_UPSTREAM_URL、 -//! PC_GATEWAY_UPSTREAM_API_KEY、PC_GATEWAY_UPSTREAM_PROFILE、 -//! PC_GATEWAY_POLICY_VERSION、PC_GATEWAY_MAX_ATTEMPTS、PC_GATEWAY_DEGRADE。 - -mod ingress; -mod link; -mod middleware; -mod proxy; - -use crate::link::CoreLink; -use axum::routing::{get, post}; -use axum::Router; -use pc_gateway_core::Executor; -use pc_gateway_evidence::BufferedEvidenceSink; -use pc_gateway_transport::ReqwestTransport; -use std::net::SocketAddr; -use std::num::NonZeroU32; -use std::sync::Arc; -use std::time::Duration; - -pub struct AppState { - /// 单一执行器;线格式渲染器按请求格式传入(同格式进出)。 - pub executor: Arc>, - pub evidence: Arc, - pub upstream_profile: String, - /// chat-completions 上游(含 key;老变量 PC_GATEWAY_UPSTREAM_URL 仍作缺省)。 - pub upstream_chat: String, - /// responses 上游。 - pub upstream_responses: String, - pub upstream_chat_api_key: String, - pub upstream_responses_api_key: String, - pub api_key: Option, - pub degrade: pc_gateway_core::DegradePolicy, - /// 是否调 prepare 注入上下文(默认关;v1 仅 chat 格式)。 - pub inject_context: bool, - /// 过检后同步沉淀对话(默认关)。 - pub sediment: bool, - /// 默认 Scope(启动时读一次,避免热路径读环境变量)。 - pub default_scope: String, -} - -#[tokio::main] -async fn main() { - tracing_subscriber::fmt() - .with_env_filter( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| "info".into()), - ) - .init(); - - let core_link = CoreLink::from_env(); - let proxy_state = proxy::ProxyState::from_env(); - - let max_attempts: u32 = std::env::var("PC_GATEWAY_MAX_ATTEMPTS") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(2); - let max_body_bytes: usize = std::env::var("PC_GATEWAY_MAX_BODY_BYTES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(16 * 1024 * 1024); - let max_concurrent: usize = std::env::var("PC_GATEWAY_MAX_CONCURRENT") - .ok() - .and_then(|v| v.parse().ok()) - .filter(|v| *v > 0) - .unwrap_or(64); - let degrade = match std::env::var("PC_GATEWAY_DEGRADE").as_deref() { - Ok("passthrough") => pc_gateway_core::DegradePolicy::PassthroughWithoutMemory, - _ => pc_gateway_core::DegradePolicy::Pause, - }; - - let state = Arc::new(AppState { - executor: Arc::new(Executor::new( - core_link, - ReqwestTransport::new(Duration::from_secs(120)), - NonZeroU32::new(max_attempts).expect("max_attempts > 0"), - )), - evidence: Arc::new(BufferedEvidenceSink::new()), - upstream_profile: std::env::var("PC_GATEWAY_UPSTREAM_PROFILE") - .unwrap_or_else(|_| "default".into()), - upstream_chat: std::env::var("PC_GATEWAY_UPSTREAM_URL_CHAT") - .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_URL")) - .unwrap_or_else(|_| "http://127.0.0.1:9000/v1/chat/completions".into()), - upstream_responses: std::env::var("PC_GATEWAY_UPSTREAM_URL_RESPONSES") - .unwrap_or_else(|_| "https://openrouter.ai/api/v1/responses".into()), - upstream_chat_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_CHAT") - .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) - .unwrap_or_default(), - upstream_responses_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_RESPONSES") - .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) - .unwrap_or_default(), - api_key: std::env::var("PC_GATEWAY_API_KEY").ok().filter(|k| !k.is_empty()), - degrade, - inject_context: matches!(std::env::var("PC_GATEWAY_INJECTION").as_deref(), Ok("on")), - sediment: matches!(std::env::var("PC_GATEWAY_SEDIMENT").as_deref(), Ok("on")), - default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") - .unwrap_or_else(|_| "gateway:default".into()), - }); - - let router = Router::new() - .route("/healthz", get(healthz)) - .route("/gateway/v1/chat/completions", post(ingress::chat_completions)) - .route("/gateway/v1/responses", post(ingress::responses)) - .fallback(proxy::fallback) - .with_state((state, proxy_state)); - - // 中间件链:按序注册,前者为外层。新增功能 = 实现 GatewayMiddleware + 此处一行。 - let chain: Vec> = vec![ - middleware::ResourceLimits::new(max_body_bytes, max_concurrent), - std::sync::Arc::new(middleware::RequestId), - ]; - for mw in &chain { - tracing::info!(middleware = mw.name(), "middleware enabled"); - } - let app = middleware::apply_chain(router, chain); - - let addr: SocketAddr = std::env::var("PC_GATEWAY_LISTEN") - .unwrap_or_else(|_| "127.0.0.1:8787".into()) - .parse() - .expect("PC_GATEWAY_LISTEN must be host:port"); - - tracing::info!(%addr, "pc-gateway listening (port takeover mode)"); - let listener = tokio::net::TcpListener::bind(addr).await.expect("bind"); - axum::serve(listener, app) - .with_graceful_shutdown(shutdown_signal()) - .await - .expect("serve"); -} - -async fn shutdown_signal() { - let _ = tokio::signal::ctrl_c().await; - tracing::info!("shutting down (draining)"); -} - -async fn healthz() -> axum::Json { - axum::Json(serde_json::json!({ "status": "ok", "service": "pc-gateway" })) -} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs b/powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs deleted file mode 100644 index fd2499faee..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/src/middleware/mod.rs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 网关中间件链(chain/filter)。 -//! -//! 设计对齐 PC 的 HttpResourceLimits / HttpRequestId / 观测栈分层思路: -//! 每个功能是一个实现 `GatewayMiddleware` 的小结构,启动时按序注册, -//! `apply_chain` 反向挂到 axum(先注册 = 越靠外层)。新增功能(限流、 -//! 指标、OTel、熔断……)只需增加一个结构体 + 一行注册。 - -use axum::{ - extract::Request, - http::{HeaderName, StatusCode}, - middleware::Next, - response::{IntoResponse, Response}, - Json, -}; -use std::pin::Pin; - -use std::future::Future; -use std::sync::Arc; - -pub mod request_id; -pub use request_id::RequestId; -pub mod resource_limits; -pub use resource_limits::ResourceLimits; - - -pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-powercontext-request-id"); - -/// 一个中间件 = 请求进入时的一段处理 + 调用后续链。 -/// 约定:中间件不得消费 body(body 归 ingress/代理所有)。 -/// handle 返回 boxed future 以保持 dyn 兼容(可装进 Vec 动态组合)。 -pub trait GatewayMiddleware: Send + Sync + 'static { - /// 名称(日志/指标用)。 - fn name(&self) -> &'static str; - - fn handle<'a>( - &'a self, - req: Request, - next: Next, - ) -> Pin + Send + 'a>>; -} - - -/// 把中间件链挂到 Router 的外层。 -/// axum 的 layer 语义:后挂的先执行;这里让 `chain[0]` 成为最外层, -/// 与注册顺序直觉一致。 -pub fn apply_chain(mut router: axum::Router, chain: Vec>) -> axum::Router { - for mw in chain.into_iter().rev() { - router = router.layer(axum::middleware::from_fn(move |req, next| { - let mw = mw.clone(); - async move { mw.handle(req, next).await } - })); - } - router -} - -/// 统一的简单错误响应。 -pub(crate) fn reject(status: StatusCode, code: &str, detail: impl Into) -> Response { - ( - status, - Json(serde_json::json!({ "error": code, "detail": detail.into() })), - ) - .into_response() -} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs b/powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs deleted file mode 100644 index 3177405aa6..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/src/middleware/request_id.rs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 请求 ID:透传客户端的 X-PowerContext-Request-ID 或生成新 ID, -//! 注入请求扩展(供 handler/日志取用)并回写到响应头。 -//! 对齐 PC 的 HttpRequestIdMiddleware,贯通排障链路。 - -use super::{GatewayMiddleware, REQUEST_ID_HEADER}; -use axum::{extract::Request, middleware::Next, response::Response}; -use std::future::Future; -use std::pin::Pin; -use std::sync::atomic::{AtomicU64, Ordering}; - -static SEQUENCE: AtomicU64 = AtomicU64::new(0); - -pub struct RequestId; - -fn generate() -> String { - let ts = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis()) - .unwrap_or(0); - let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed); - format!("gw-{ts:x}-{seq:06x}") -} - -impl GatewayMiddleware for RequestId { - fn name(&self) -> &'static str { - "request_id" - } - - fn handle<'a>( - &'a self, - mut req: Request, - next: Next, - ) -> Pin + Send + 'a>> { - Box::pin(async move { - let id = req - .headers() - .get(&REQUEST_ID_HEADER) - .and_then(|v| v.to_str().ok()) - .filter(|v| !v.is_empty() && v.len() <= 128 && v.chars().all(|c| c.is_ascii_graphic())) - .map(|v| v.to_string()) - .unwrap_or_else(generate); - // 注入扩展 + 当前 span,供后续 handler 与日志关联。 - req.extensions_mut().insert(id.clone()); - tracing::Span::current().record("request_id", &id); - let mut resp = next.run(req).await; - if resp.headers().get(&REQUEST_ID_HEADER).is_none() { - if let Ok(v) = axum::http::HeaderValue::from_str(&id) { - resp.headers_mut().insert(REQUEST_ID_HEADER, v); - } - } - resp - }) - } -} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs b/powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs deleted file mode 100644 index b194e00c49..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 资源限流:请求体上限 + 并发上限(对齐 PC 的 HttpResourceLimitsMiddleware)。 -//! 最外层准入——被拒请求不消耗内层任何资源。/healthz 豁免并发限制 -//! (编排系统探活不应因业务拥堵被拒)。 - -use super::{reject, GatewayMiddleware}; -use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::future::Future; -use std::pin::Pin; -use std::sync::Arc; -use tokio::sync::Semaphore; - -pub struct ResourceLimits { - max_body_bytes: usize, - max_concurrent: Arc, - /// 被拒计数(无正文证据)。 - rejected_body: AtomicU64, - rejected_concurrency: AtomicU64, -} - -impl ResourceLimits { - pub fn new(max_body_bytes: usize, max_concurrent: usize) -> Arc { - Arc::new(Self { - max_body_bytes, - max_concurrent: Arc::new(Semaphore::new(max_concurrent)), - rejected_body: AtomicU64::new(0), - rejected_concurrency: AtomicU64::new(0), - }) - } -} - -impl GatewayMiddleware for ResourceLimits { - fn name(&self) -> &'static str { - "resource_limits" - } - - fn handle<'a>( - &'a self, - req: Request, - next: Next, - ) -> Pin + Send + 'a>> { - Box::pin(async move { - // 1) 请求体上限:优先用 Content-Length 预检(零拷贝拒绝)。 - if let Some(len) = req - .headers() - .get(axum::http::header::CONTENT_LENGTH) - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.parse::().ok()) - { - if len > self.max_body_bytes { - self.rejected_body.fetch_add(1, Ordering::Relaxed); - tracing::warn!(bytes = len, limit = self.max_body_bytes, "request body rejected"); - return reject( - StatusCode::PAYLOAD_TOO_LARGE, - "request_body_too_large", - format!("body {len} bytes exceeds limit {}", self.max_body_bytes), - ); - } - } - - // 2) 并发上限:非阻塞获取;占满即拒(不排队——排队会把内存压力换成延迟压力)。 - let is_health = req.uri().path() == "/healthz"; - let permit = if is_health { - None - } else { - match self.max_concurrent.clone().try_acquire_owned() { - Ok(p) => Some(p), - Err(_) => { - self.rejected_concurrency.fetch_add(1, Ordering::Relaxed); - tracing::warn!("concurrency limit reached, rejecting"); - return reject( - StatusCode::SERVICE_UNAVAILABLE, - "concurrency_limit", - "gateway at max concurrent requests", - ); - } - } - }; - - let resp = next.run(req).await; - drop(permit); // 显式归还(作用域结束也会归还,这里表达意图) - resp - }) - } -} diff --git a/powercontext/gateway/crates/pc-gateway-app/src/proxy.rs b/powercontext/gateway/crates/pc-gateway-app/src/proxy.rs deleted file mode 100644 index ad098870a1..0000000000 --- a/powercontext/gateway/crates/pc-gateway-app/src/proxy.rs +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 端口接管代理:非 `/gateway/*` 的流量原样转发到 Python 的 UDS。 -//! 原 Core/MCP 路由由此透传;流式(SSE/分块)由 hyper 客户端透传保证。 - -use crate::AppState;use axum::body::Body; -use axum::extract::{Request, State}; -use axum::http::{HeaderValue, StatusCode}; -use axum::response::{IntoResponse, Response}; -use hyper::Uri as HyperUri;use hyper_util::client::legacy::Client; -use hyper_util::rt::{TokioExecutor, TokioIo}; -use std::future::Future; -use std::path::PathBuf; -use std::pin::Pin; -use std::sync::Arc; -use tokio::net::UnixStream; - -pub type SharedProxy = (Arc, ProxyState); - -#[derive(Clone)] -pub struct ProxyState { - inner: Option>, -} - -struct ProxyInner { - socket: PathBuf, - client: Client, -} - -impl ProxyState { - pub fn from_env() -> Self { - match std::env::var("PC_GATEWAY_CORE_UDS") { - Ok(sock) => { - let client = Client::builder(TokioExecutor::new()) - .build(UnixConnector { socket: PathBuf::from(&sock) }); - tracing::info!(%sock, "proxy: forwarding non-gateway routes to Python UDS"); - Self { - inner: Some(Arc::new(ProxyInner { - socket: PathBuf::from(sock), - client, - })), - } - } - Err(_) => { - tracing::info!("proxy: no UDS configured; standalone mode"); - Self { inner: None } - } - } - } -} - -/// UDS 连接器:忽略 URI,始终连配置的 socket 路径。 -/// 实现 tower Service(hyper-util legacy Client 的 Connect 约束)。 -#[derive(Clone)] -struct UnixConnector { - socket: PathBuf, -} - -impl tower::Service for UnixConnector { - type Response = TokioIo; - type Error = std::io::Error; - type Future = Pin> + Send>>; - - fn poll_ready( - &mut self, - _cx: &mut std::task::Context<'_>, - ) -> std::task::Poll> { - std::task::Poll::Ready(Ok(())) - } - - fn call(&mut self, _uri: HyperUri) -> Self::Future { - let path = self.socket.clone(); - Box::pin(async move { - UnixStream::connect(path) - .await - .map(TokioIo::new) - }) - } -} - -pub async fn fallback(State((_, proxy)): State, req: Request) -> Response { - let Some(inner) = proxy.inner else { - return ( - StatusCode::NOT_FOUND, - axum::Json(serde_json::json!({ - "error": "not_found", - "hint": "standalone mode: only /gateway/v1 and /healthz are served", - })), - ) - .into_response(); - }; - - let (parts, body) = req.into_parts(); - // hyper legacy client 要求绝对 URI;UDS 连接器忽略 host,用占位 authority。 - let path_q = parts - .uri - .path_and_query() - .cloned() - .unwrap_or_else(|| "/".parse().expect("root uri")); - let uri = HyperUri::builder() - .scheme("http") - .authority("powercontext.internal") - .path_and_query(path_q) - .build() - .unwrap_or_else(|_| HyperUri::default()); - - let mut fwd = hyper::Request::builder() - .method(parts.method) - .uri(uri) - .header("host", HeaderValue::from_static("powercontext")); - if let Some(headers) = fwd.headers_mut() { - *headers = parts.headers; - if !headers.contains_key("host") { - headers.insert("host", HeaderValue::from_static("powercontext")); - } - } - let hyper_req = match fwd.body(body) { - Ok(r) => r, - Err(e) => { - return ( - StatusCode::BAD_REQUEST, - axum::Json(serde_json::json!({ "error": "bad_request", "detail": e.to_string() })), - ) - .into_response() - } - }; - - let _ = inner.socket; // socket 路径已注入连接器 - match inner.client.request(hyper_req).await { - Ok(resp) => { - let (rparts, rbody) = resp.into_parts(); - let mut response = Response::builder().status(rparts.status); - if let Some(h) = response.headers_mut() { - *h = rparts.headers; - } - response - .body(Body::new(rbody)) - .unwrap_or_else(|e| { - (StatusCode::BAD_GATEWAY, format!("proxy build: {e}")).into_response() - }) - } - Err(e) => ( - StatusCode::BAD_GATEWAY, - axum::Json(serde_json::json!({ - "error": "core_unreachable", - "detail": e.to_string(), - })), - ) - .into_response(), - } -} diff --git a/powercontext/gateway/crates/pc-gateway-core/Cargo.toml b/powercontext/gateway/crates/pc-gateway-core/Cargo.toml deleted file mode 100644 index f92693d763..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/Cargo.toml +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[package] -name = "pc-gateway-core" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "PowerContext Gateway: executor state machine — input/check → render → send → output/check → release" - -[dependencies] -pc-gateway-types = { workspace = true } -pc-gateway-protocol = { workspace = true } -pc-gateway-transport = { workspace = true } -pc-gateway-evidence = { workspace = true } -bytes = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -thiserror = { workspace = true } -tokio = { workspace = true } -tracing = { workspace = true } -reqwest = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-core/src/executor.rs b/powercontext/gateway/crates/pc-gateway-core/src/executor.rs deleted file mode 100644 index 78ac88f4fb..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/src/executor.rs +++ /dev/null @@ -1,402 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{GateClient, GateError}; -use pc_gateway_evidence::EvidenceSink; -use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; -use pc_gateway_transport::{AdmittedSend, BoundedRetry, RetryOutcome, SendOutcome, Transport}; -use pc_gateway_types::{ - CaptureContentSourceRequest, CheckDecision, ContextCheckRequest, ContextCheckResult, - ModelJsonPayload, ModelJsonTextLocation, PreparedContextLocation, PrepareContextRequest, -}; -use std::collections::BTreeMap; -use std::num::NonZeroU32; - -/// Gate 不可用时的策略(PR #2199 故障语义): -/// Pause —— 必需强制检查不可用:不发送(默认,安全立场); -/// PassthroughWithoutMemory —— 增强类调用可降级(仅限 capabilities.enforcing=false)。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum DegradePolicy { - #[default] - Pause, - PassthroughWithoutMemory, -} - -/// 宿主交给执行器的完整输入:已授权历史 + 当前请求 + 目标。 -pub struct ManagedCall { - pub scope_id: String, - pub target_profile: String, - pub request: CanonicalRequest, - pub target_url: String, - /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 - pub headers: Vec<(String, String)>, - pub degrade_policy: DegradePolicy, - /// 是否调 prepare 注入上下文(v1 仅 chat 格式;PC 决定内容,网关只放置)。 - pub inject_context: bool, - /// 是否在过检后同步沉淀本轮对话(capture_content_source,毫秒级落库)。 - pub sediment: bool, - /// 注入块位置声明,随 before_send 送检。 - pub prepared_contexts: Vec, -} - -/// 执行结果:要么是过检放行的内容,要么是显式拒绝/不确定。 -/// 不存在“静默成功”或“伪装成空结果”的路径。 -#[derive(Debug)] -pub enum ManagedOutcome { - /// before_release 的 allow:绑定与过检内容一起返回。 - Released { - binding: Option, - status: u16, - content_type: String, - body: bytes::Bytes, - }, - /// Core 明确拒绝(两阶段的 block),携带无正文原因类别。 - Blocked { reason_codes: Vec }, - /// Core 暂缓。PR #2264 的 withhold 不含渲染计划,一律按终态处理。 - Withheld { reason_codes: Vec }, - /// 可能已到达上游;不自动付费重发。 - SendIndeterminate, - /// 全部尝试确定性未送达。 - NotSent { attempts: u32 }, - /// Gate 不可用:暂停,不是失败放行。 - GatePaused(String), - /// 无记忆直通降级:未经检查发送(仅限未启用强制规则的部署), - /// 响应头/证据必须显式标记,不得伪装成过检结果。 - Degraded { - status: u16, - content_type: String, - body: bytes::Bytes, - }, -} - -pub struct Executor { - gate: G, - retry: BoundedRetry, -} - -impl Executor -where - G: GateClient, - T: Transport, -{ - pub fn new(gate: G, transport: T, max_attempts: NonZeroU32) -> Self { - Self { - gate, - retry: BoundedRetry::new(transport, max_attempts), - } - } - - /// 一次托管调用。渲染器按请求传入:入口格式即上游格式(同格式进出)。 - pub async fn run( - &self, - call: ManagedCall, - renderer: &R, - evidence: &dyn EvidenceSink, - ) -> ManagedOutcome { - let mut call = call; - if call.inject_context { - // 注入是增强类调用:失败不阻塞主链路(不注入、不声明区间)。 - self.enrich(&mut call, evidence).await; - } - // 渲染完整最终字节(不含缓存计划:PR #2264 的 withhold 未携带渲染计划)。 - let payload = match renderer.render(&call.request, None) { - Ok(p) => p, - Err(e) => { - return ManagedOutcome::Blocked { - reason_codes: vec![format!("render_failed:{e}")], - } - } - }; - // 送检内容必须与发送字节严格一致:拒绝有损转换(防“检查≠发送”缝隙)。 - // 渲染器输出本应恒为合法 UTF-8,非法即契约违约,阻断而非降级。 - let payload_body = match String::from_utf8(payload.bytes.clone().to_vec()) { - Ok(text) => text, - Err(_) => { - return ManagedOutcome::Blocked { - reason_codes: vec!["invalid_payload_encoding".into()], - } - } - }; - let model_payload = ModelJsonPayload::new( - content_headers(&call.headers, payload.content_type), - payload_body, - ); - - let check = ContextCheckRequest::BeforeSend { - scope_id: call.scope_id.clone(), - target_profile: call.target_profile.clone(), - payload: model_payload, - prepared_contexts: call.prepared_contexts.clone(), - }; - - let binding = match self.gate.check(check).await { - Err(e) => { - // #2199 语义:降级仅适用于 Core「不可用」。Malformed 表示 Core 可达但 - // 响应异常(版本错乱/被篡改/代理污染)——恰恰最不该绕过检查,一律暂停。 - return match (e, call.degrade_policy) { - ( - GateError::GateUnavailable(_), - DegradePolicy::PassthroughWithoutMemory, - ) => self.degraded_send(&call, payload.bytes, evidence).await, - (e, _) => ManagedOutcome::GatePaused(classify_gate_error(e)), - } - } - Ok(result) => match result.decision { - CheckDecision::Allow => unwrap_binding(result), - CheckDecision::Block => { - return ManagedOutcome::Blocked { - reason_codes: result.reason_codes, - } - } - CheckDecision::Withhold => { - return ManagedOutcome::Withheld { - reason_codes: result.reason_codes, - } - } - }, - }; - - let send = AdmittedSend { - binding, - payload: payload.bytes, - target_url: call.target_url.clone(), - headers: call.headers.clone(), - stream: call.request.stream, - }; - let send_ref = send.clone(); - - let raw = match self.retry.send_with_retry(&send, evidence).await { - RetryOutcome::AllNotSent { attempts } => return ManagedOutcome::NotSent { attempts }, - RetryOutcome::Done(SendOutcome::Indeterminate(_)) => { - return ManagedOutcome::SendIndeterminate - } - RetryOutcome::Done(SendOutcome::NotSent(_)) => { - unreachable!("BoundedRetry never returns Done(NotSent)") - } - RetryOutcome::Done(SendOutcome::Delivered(raw)) => raw, - }; - - // strict:完整原始响应先过 before_release,通过前不释放任何内容。 - // 上游响应不受我们控制:非 UTF-8 字节不做有损转换送检(那会导致 - // “批准的是替换后文本、交付的是原始字节”的保真缺口),直接不放行。 - let release_body = match String::from_utf8(raw.body.clone().to_vec()) { - Ok(text) => text, - Err(_) => { - return ManagedOutcome::Withheld { - reason_codes: vec!["invalid_response_encoding".into()], - } - } - }; - let release_check = ContextCheckRequest::BeforeRelease { - scope_id: call.scope_id.clone(), - target_profile: call.target_profile.clone(), - request_binding: send_ref.binding.clone(), - payload: ModelJsonPayload::new( - // 契约要求 headers 至少 1 项;携带上游实际 Content-Type。 - BTreeMap::from([("content-type".to_string(), raw.content_type.clone())]), - release_body.clone(), - ), - completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.into(), - }; - match self.gate.check(release_check).await { - Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), - Ok(result) => match result.decision { - CheckDecision::Allow => { - // 沉淀:同步、best-effort(失败仅记证据,不影响交付)。 - // 内容只含本轮 user 文本与过检响应——被拦/降级轮次不沉淀。 - if call.sediment { - let transcript = serde_json::json!({ - "kind": "gateway_turn", - "user": call.request.messages.iter() - .rev().find(|m| matches!(m.role, pc_gateway_protocol::Role::User)) - .and_then(|m| match m.content.as_slice() { - [serde_json::Value::String(s)] => Some(s.clone()), - _ => None, - }).unwrap_or_default(), - "assistant": release_body.clone(), - "model": call.request.model, - }); - let digest = result.binding.as_deref() - .map(simple_digest) - .unwrap_or_else(|| simple_digest(&release_body)); - let capture = CaptureContentSourceRequest { - scope_id: call.scope_id.clone(), - source_id: format!("gw-turn-{digest}"), - content: transcript.to_string(), - metadata: Some(serde_json::json!({ - "kind": "gateway_turn", - "target_profile": call.target_profile, - })), - }; - if let Err(e) = self.gate.capture(capture).await { - evidence.record_not_sent(0, &format!("sediment_failed:{e}")); - } - } - ManagedOutcome::Released { - binding: result.binding, - status: raw.status, - content_type: raw.content_type.clone(), - body: raw.body, - } - } - CheckDecision::Block => { - // 不释放任何内容;尽力取消上游,只保留无正文失败证据。 - self.retry.transport().cancel(&send_ref).await; - ManagedOutcome::Blocked { - reason_codes: result.reason_codes, - } - } - CheckDecision::Withhold => ManagedOutcome::Withheld { - reason_codes: result.reason_codes, - }, - }, - } - } - - /// 注入(放置与声明,非检索):调 prepare → 标准块包裹 → 拼进最后一条 - /// user 消息头部 → 计算字节区间。任一步失败则保持原样(不注入、不声明)。 - async fn enrich(&self, call: &mut ManagedCall, evidence: &dyn EvidenceSink) { - // 取最后一条 user 消息的纯文本作为检索词;非单字符串 content 不注入(v1)。 - let Some(query) = last_user_text(&call.request) else { - return; - }; - let prepared = match self - .gate - .prepare(PrepareContextRequest { - scope_id: call.scope_id.clone(), - query, - max_bytes: 8192, - include_reuse: true, - }) - .await - { - Ok(p) => p, - Err(e) => { - evidence.record_not_sent(0, &format!("prepare_failed:{e}")); - return; - } - }; - let (Some(content), Some(binding)) = (prepared.content(), prepared.binding()) else { - return; // empty:不注入任何标记(空块会污染前缀且无 binding 可声明) - }; - if content.is_empty() { - return; - } - // PC 返回的 content 已是标准注入格式(信任前言 + 标记包裹块)。 - // 必须原样注入:check 会校验区间字节摘要 == sha256(content), - // 网关任何增删(包括再包裹)都会导致 digest 不匹配被暂缓。 - let block = content.to_string(); - let Some(index) = last_user_index(&call.request) else { return }; - let Some(message) = call.request.messages.get_mut(index) else { return }; - let original = match message.content.as_slice() { - [serde_json::Value::String(s)] => s.clone(), - _ => return, - }; - let new_text = format!("{block}\n\n{original}"); - message.content = vec![serde_json::Value::String(new_text)]; - call.prepared_contexts.push(PreparedContextLocation { - binding: binding.to_string(), - location: ModelJsonTextLocation { - schema: pc_gateway_types::MODEL_JSON_TEXT_LOCATION_SCHEMA.to_string(), - // chat 线格式:content 为纯字符串,指针用无部件形态。 - pointer: format!("/messages/{index}/content"), - start_byte: 0, - // UTF-8 字节数(非字符数);区间必须落在字符边界(块整体是合法 UTF-8,天然满足)。 - end_byte: block.len() as u64, - }, - }); - } - - /// 降级直通:未经检查发送。显式标记,不做释放检查。 - async fn degraded_send( - &self, - call: &ManagedCall, - payload: bytes::Bytes, - evidence: &dyn EvidenceSink, - ) -> ManagedOutcome { - evidence.record_not_sent(0, "degraded_passthrough"); - let send = AdmittedSend { - binding: "degraded-passthrough".into(), - payload, - target_url: call.target_url.clone(), - headers: call.headers.clone(), - stream: call.request.stream, - }; - match self.retry.send_with_retry(&send, evidence).await { - RetryOutcome::AllNotSent { attempts } => ManagedOutcome::NotSent { attempts }, - RetryOutcome::Done(SendOutcome::Indeterminate(_)) => ManagedOutcome::SendIndeterminate, - RetryOutcome::Done(SendOutcome::NotSent(_)) => { - unreachable!("BoundedRetry never returns Done(NotSent)") - } - RetryOutcome::Done(SendOutcome::Delivered(raw)) => ManagedOutcome::Degraded { - status: raw.status, - content_type: raw.content_type, - body: raw.body, - }, - } - } -} - -fn unwrap_binding(result: ContextCheckResult) -> String { - result - .binding - .unwrap_or_else(|| "missing-binding".to_string()) -} - -/// 载荷头只保留内容/协议头;凭据与传输覆盖头禁止进 check 载荷。 -fn content_headers(headers: &[(String, String)], content_type: &str) -> BTreeMap { - let mut out = BTreeMap::new(); - out.insert("content-type".to_string(), content_type.to_string()); - for (k, v) in headers { - let lower = k.to_ascii_lowercase(); - if matches!(lower.as_str(), "authorization" | "x-api-key" | "cookie") { - continue; - } - out.insert(lower, v.clone()); - } - out -} - -fn classify_gate_error(e: GateError) -> String { - match e { - GateError::GateUnavailable(msg) | GateError::Malformed(msg) => msg, - } -} - -/// 最后一条 user 消息下标(渲染保持消息顺序,与线格式下标一致)。 -fn last_user_index(request: &CanonicalRequest) -> Option { - request - .messages - .iter() - .rposition(|m| matches!(m.role, pc_gateway_protocol::Role::User)) -} - -fn last_user_text(request: &CanonicalRequest) -> Option { - let i = last_user_index(request)?; - match request.messages[i].content.as_slice() { - [serde_json::Value::String(s)] => Some(s.clone()), - _ => None, - } -} - -/// 稳定短摘要(幂等键用;非安全用途,无需密码学强度)。 -fn simple_digest(input: &str) -> String { - // FNV-1a 64 位,输出 16 hex —— 足够做 source_id 的幂等区分。 - let mut hash: u64 = 0xcbf29ce484222325; - for b in input.as_bytes() { - hash ^= *b as u64; - hash = hash.wrapping_mul(0x100000001b3); - } - format!("{hash:016x}") -} diff --git a/powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs b/powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs deleted file mode 100644 index 144eca6a1b..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/src/gate_client.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use pc_gateway_types::{ - CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, - PrepareContextResult, -}; -use std::future::Future; - -/// Core 检查的客户端抽象(PR #2199:单端点两阶段契约)。 -/// 实现:TCP(独立部署形态)或 UDS(同机组合部署形态); -/// 嵌入式实现直接进程内调用等价算法。 -/// -/// Gate 不可用 → `GateUnavailable`。是否降级为无记忆直通由调用方 -/// 的 `DegradePolicy` 决定(仅对未配置强制规则的 Scope 允许)。 -pub trait GateClient: Send + Sync { - fn check( - &self, - request: ContextCheckRequest, - ) -> impl Future> + Send; - - /// GET_CAPABILITIES 能力发现:获知支持的模式、必需规则、可降级性等。 - fn capabilities( - &self, - ) -> impl Future> + Send; - - /// PREPARE_CONTEXT:检索并装配注入内容(智力全在 Core;网关只放置)。 - fn prepare( - &self, - request: PrepareContextRequest, - ) -> impl Future> + Send; - - /// CAPTURE_CONTENT_SOURCE:沉淀一轮过检对话(同步落库;提取在 PC 后台)。 - /// best-effort:失败只记证据,不影响已过检响应的交付语义。 - fn capture( - &self, - request: CaptureContentSourceRequest, - ) -> impl Future> + Send; -} - -#[derive(Debug, thiserror::Error)] -pub enum GateError { - #[error("gate unavailable: {0}")] - GateUnavailable(String), - #[error("gate response malformed: {0}")] - Malformed(String), -} diff --git a/powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs deleted file mode 100644 index 9499eede79..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{GateClient, GateError}; -use pc_gateway_types::{ - CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, - PrepareContextResult, -}; -use serde::de::DeserializeOwned; -use serde::Serialize; - -/// 独立部署形态:HTTPS/TCP 直连 PowerContext Server 的公开契约。 -/// 同机组合部署用 `UdsGateClient`(HTTP over Unix Domain Socket)。 -#[derive(Debug, Clone)] -pub struct HttpGateClient { - base_url: String, - client: reqwest::Client, - /// Server 认证令牌(POWERCONTEXT_SERVER_AUTH_TOKEN);None 时不带认证头。 - token: Option, -} - -impl HttpGateClient { - pub fn new(base_url: impl Into) -> Self { - Self::with_token(base_url, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) - } - - pub fn with_token(base_url: impl Into, token: Option) -> Self { - Self { - base_url: base_url.into().trim_end_matches('/').to_string(), - // 同一原则:获准目的地 = 实际目的地;3xx 原样上抛,不自动跟随。 - client: reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .build() - .expect("reqwest client build"), - token: token.filter(|t| !t.is_empty()), - } - } - - async fn post(&self, path: &str, body: &impl Serialize) -> Result - where - R: DeserializeOwned, - { - let url = format!("{}{}", self.base_url, path); - let resp = self - .client - .post(&url) - // RFC:DTO 复用 scope-mode/access 声明头。 - .header("x-powercontext-scope-mode", "current") - .bearer_auth(self.token.clone().unwrap_or_default()) - .header("content-type", "application/json") - .json(body) - .send() - .await - .map_err(|e| GateError::GateUnavailable(e.to_string()))?; - let status = resp.status(); - if !status.is_success() { - return Err(GateError::GateUnavailable(format!( - "gate returned HTTP {status}" - ))); - } - let bytes = resp - .bytes() - .await - .map_err(|e| GateError::GateUnavailable(e.to_string()))?; - serde_json::from_slice(&bytes) - .map_err(|e| GateError::Malformed(format!("decode {path}: {e}"))) - } -} - -impl GateClient for HttpGateClient { - async fn check( - &self, - request: ContextCheckRequest, - ) -> Result { - self.post("/v1/context/check", &request).await - } - - async fn capabilities(&self) -> Result { - let url = format!("{}/v1/capabilities", self.base_url); - let resp = self - .client - .get(&url) - .header("x-powercontext-scope-mode", "current") - .bearer_auth(self.token.clone().unwrap_or_default()) - .send() - .await - .map_err(|e| GateError::GateUnavailable(e.to_string()))?; - let status = resp.status(); - if !status.is_success() { - return Err(GateError::GateUnavailable(format!( - "capabilities HTTP {status}" - ))); - } - resp.json() - .await - .map_err(|e| GateError::Malformed(e.to_string())) - } - - async fn prepare( - &self, - request: PrepareContextRequest, - ) -> Result { - self.post("/v1/context/prepare", &request).await - } - - async fn capture( - &self, - request: CaptureContentSourceRequest, - ) -> Result { - self.post("/v1/sources/content", &request).await - } -} diff --git a/powercontext/gateway/crates/pc-gateway-core/src/lib.rs b/powercontext/gateway/crates/pc-gateway-core/src/lib.rs deleted file mode 100644 index 35509e6b2a..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/src/lib.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 执行器核心:一次托管调用的状态机。 -//! -//! 对应 RFC「一次托管调用」时序图(PR #2199 两阶段检查形态): -//! -//! ```text -//! 宿主完整输入 ─► check(before_send) ─┬─ allow ─► 发送 ─► 原始响应 ─► check(before_release) ─┬─ release ─► 返回 -//! ├─ withhold(渲染计划) ─► 只渲染获准字段 ─► 复检(最多一次) -//! └─ block ──────────────────────────────────────────┴─ refuse ──► 显式拒绝 -//! ``` -//! -//! 网关无策略:每一步的裁决都来自 `GateClient`(check API 或嵌入式等价物), -//! 本 crate 只负责把裁决串成正确的控制流,并守住失败语义。 - -mod executor; -mod gate_client; -mod http_gate_client; -mod uds_gate_client; - -pub use executor::*; -pub use gate_client::*; -pub use http_gate_client::*; -pub use uds_gate_client::*; diff --git a/powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs deleted file mode 100644 index 4dede09804..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 同机组合部署形态:HTTP over Unix Domain Socket。 -//! -//! PR #2199:启用后 Rust 独占公网 TCP 端口,Python 只监听本机 UDS; -//! 网关的 check/capabilities 都走这个通道。 -//! -//! 连接按对端(唯一的 socket 路径)池化:keep-alive 复用空闲连接, -//! 池有上限;connect/read 均有超时,防止对端假死导致请求悬挂。 -//! 认证与 TCP 形态一致(UDS 不替代 bearer 认证)。 - -use crate::{GateClient, GateError}; -use pc_gateway_types::{ - CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, - PrepareContextResult, -}; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; -use std::time::Duration; -use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf}; -use tokio::net::UnixStream; - -const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); -const READ_TIMEOUT: Duration = Duration::from_secs(30); -const MAX_IDLE_CONNECTIONS: usize = 8; -const MAX_HEADER_BYTES: usize = 64 * 1024; -const MAX_BODY_BYTES: usize = 8 * 1024 * 1024; - -#[derive(Clone)] -pub struct UdsGateClient { - socket: PathBuf, - token: Option, - pool: Arc>>, -} - -impl std::fmt::Debug for UdsGateClient { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("UdsGateClient") - .field("socket", &self.socket) - .field("token", &self.token.as_ref().map(|_| "..")) - .field("idle", &self.pool.lock().map(|p| p.len()).unwrap_or(0)) - .finish() - } -} - -impl UdsGateClient { - pub fn new(socket: impl Into) -> Self { - Self::with_token(socket, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) - } - - pub fn with_token(socket: impl Into, token: Option) -> Self { - Self { - socket: socket.into(), - token: token.filter(|t| !t.is_empty()), - pool: Arc::new(Mutex::new(Vec::new())), - } - } - - fn take_idle(&self) -> Option { - self.pool.lock().ok()?.pop() - } - - fn return_idle(&self, stream: UnixStream) { - if let Ok(mut pool) = self.pool.lock() { - if pool.len() < MAX_IDLE_CONNECTIONS { - pool.push(stream); - } - } - } - - /// 发送单次 HTTP/1.1 请求;keep-alive 下连接归还池中复用。 - /// - /// 对端(uvicorn)会关闭空闲超时的 keep-alive 连接;本地 `writable()` - /// 探活发现不了这种半关闭。因此池中借出的连接若在收到任何响应前 - /// 失败(broken pipe / EOF),丢弃该连接并用新连接重试一次。 - async fn request( - &self, - method: &str, - path: &str, - body: Option<&[u8]>, - ) -> Result<(u16, Vec), GateError> { - let mut from_pool = true; // 首次也允许重试一次(对端重启场景) - for _ in 0..2 { - match self.request_once(method, path, body, from_pool).await { - Ok(x) => return Ok(x), - Err(e) if retryable(&e) => { - from_pool = false; // 下一次强制新建连接 - continue; - } - Err(e) => return Err(e), - } - } - Err(GateError::GateUnavailable("uds exhausted retry".into())) - } - - async fn request_once( - &self, - method: &str, - path: &str, - body: Option<&[u8]>, - prefer_pool: bool, - ) -> Result<(u16, Vec), GateError> { - let mut leased = LeasedConnection::new(self.clone()); - let stream = leased - .acquire(prefer_pool) - .await - .map_err(|e| { - GateError::GateUnavailable(format!("uds connect {}: {e}", self.socket.display())) - })?; - let (mut rd, mut wr) = tokio::io::split(stream); - - let body = body.unwrap_or(&[]); - let mut head = format!( - "{method} {path} HTTP/1.1\r\nHost: powercontext\r\nContent-Type: application/json\r\n\ - x-powercontext-scope-mode: current\r\nContent-Length: {}\r\n", - body.len() - ); - if let Some(t) = &self.token { - head.push_str(&format!("Authorization: Bearer {t}\r\n")); - } - head.push_str("Connection: keep-alive\r\n\r\n"); - - let write = async { - wr.write_all(head.as_bytes()).await?; - wr.write_all(body).await - }; - tokio::time::timeout(READ_TIMEOUT, write) - .await - .map_err(|_| GateError::GateUnavailable("uds write timeout".into()))? - .map_err(|e| GateError::GateUnavailable(format!("uds write: {e}")))?; - - let (status, body, reusable) = read_response(&mut rd).await?; - if reusable { - leased.release(rd, wr); - } - Ok((status, body)) - } -} - -/// 从池中租借/归还连接。出错时不归还(连接状态不可信)。 -struct LeasedConnection { - client: UdsGateClient, - returned: bool, -} - -impl LeasedConnection { - fn new(client: UdsGateClient) -> Self { - Self { - client, - returned: false, - } - } - - async fn acquire(&mut self, prefer_pool: bool) -> std::io::Result { - // 先试空闲连接;真正的失效(对端已关闭)会在读写时报错, - // 由上层的单次重试兜底。 - if prefer_pool { - if let Some(idle) = self.client.take_idle() { - if idle.writable().await.is_ok() { - return Ok(idle); - } - } - } - tokio::time::timeout(CONNECT_TIMEOUT, UnixStream::connect(&self.client.socket)) - .await - .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "uds connect timeout"))? - } - - /// 仅在读到完整响应且连接可复用时调用。 - fn release(&mut self, rd: ReadHalf, wr: WriteHalf) { - if self.returned { - return; - } - let stream = rd.unsplit(wr); - self.client.return_idle(stream); - self.returned = true; - } -} - -/// 读取完整 HTTP/1.1 响应。返回 (status, body, 连接是否可复用)。 -async fn read_response(rd: &mut ReadHalf) -> Result<(u16, Vec, bool), GateError> { - let mut buf: Vec = Vec::with_capacity(8 * 1024); - let header_end = loop { - if let Some(pos) = find_terminator(&buf) { - break pos; - } - if buf.len() > MAX_HEADER_BYTES { - return Err(GateError::Malformed("uds header too large".into())); - } - let n = read_with_timeout(rd, &mut buf, 4096).await?; - if n == 0 { - return Err(GateError::Malformed("uds closed before headers".into())); - } - }; - - let head = String::from_utf8_lossy(&buf[..header_end]).into_owned(); - let mut lines = head.lines(); - let status_line = lines.next().unwrap_or_default(); - let status: u16 = status_line - .split_whitespace() - .nth(1) - .and_then(|s| s.parse().ok()) - .ok_or_else(|| GateError::Malformed(format!("bad status line: {status_line}")))?; - - let mut content_length: Option = None; - let mut chunked = false; - let mut keep_alive = true; // HTTP/1.1 默认 keep-alive - for line in lines { - let Some((k, v)) = line.split_once(':') else { continue }; - let k = k.trim().to_ascii_lowercase(); - let v = v.trim(); - match k.as_str() { - "content-length" => content_length = v.parse().ok(), - "transfer-encoding" if v.to_ascii_lowercase().contains("chunked") => chunked = true, - "connection" if v.to_ascii_lowercase().contains("close") => keep_alive = false, - _ => {} - } - } - - let mut rest = buf.split_off(header_end + 4); - let body = if chunked { - // chunked:读完 0-chunk 后必须消费 trailer(至少终止空行), - // 否则残留字节会污染复用连接上的下一个响应。 - let (decoded, trailer_clean) = read_chunked(rd, &mut rest).await?; - if !trailer_clean { - keep_alive = false; // trailer 未完整消费,连接不可复用 - } - decoded - } else { - let len = content_length.unwrap_or(rest.len()); - if rest.len() < len { - read_more(rd, &mut rest, len).await?; - rest - } else if rest.len() > len { - // 超出声明长度:缓冲里有不属于本响应的字节(串包/残留), - // 截断正文,且连接不可复用。 - rest.truncate(len); - keep_alive = false; - rest - } else { - rest - } - }; - if body.len() > MAX_BODY_BYTES { - return Err(GateError::Malformed("uds body too large".into())); - } - Ok((status, body, keep_alive)) -} - -async fn read_more( - rd: &mut ReadHalf, - buf: &mut Vec, - target: usize, -) -> Result<(), GateError> { - while buf.len() < target { - let n = read_with_timeout(rd, buf, 8192).await?; - if n == 0 { - return Err(GateError::Malformed("uds closed mid-body".into())); - } - } - Ok(()) -} - -/// 解码 chunked 编码。返回 (body, trailer 是否完整消费)。 -async fn read_chunked( - rd: &mut ReadHalf, - buf: &mut Vec, -) -> Result<(Vec, bool), GateError> { - let mut out = Vec::new(); - loop { - // 找一行作为 chunk size。 - let line_end = loop { - if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { - break pos; - } - let n = read_with_timeout(rd, buf, 4096).await?; - if n == 0 { - return Err(GateError::Malformed("uds closed mid-chunk".into())); - } - }; - let size_str = String::from_utf8_lossy(&buf[..line_end]).into_owned(); - buf.drain(..line_end + 2); - let size = usize::from_str_radix(size_str.trim().split(';').next().unwrap_or("0"), 16) - .map_err(|_| GateError::Malformed(format!("bad chunk size: {size_str}")))?; - if size == 0 { - // 消费 trailer:连续读到空行(或读尽缓冲且对端无更多数据)。 - loop { - if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { - let line = String::from_utf8_lossy(&buf[..pos]).into_owned(); - buf.drain(..pos + 2); - if line.is_empty() { - return Ok((out, true)); // trailer 结束空行 - } - continue; // trailer 头部行 - } - match read_with_timeout(rd, buf, 1024).await { - Ok(0) | Err(_) => return Ok((out, false)), - Ok(_) => {} - }; - } - } - let needed = size + 2; // 数据 + CRLF - while buf.len() < needed { - let n = read_with_timeout(rd, buf, 8192).await?; - if n == 0 { - return Err(GateError::Malformed("uds closed mid-chunk-data".into())); - } - } - out.extend_from_slice(&buf[..size]); - buf.drain(..needed); - } -} - -/// 仅“未收到任何响应字节”的传输失败才可安全重试(幂等:请求未达对端或 -/// 对端在解析前丢弃);已收到响应头的失败必须上抛。 -fn retryable(e: &GateError) -> bool { - match e { - GateError::GateUnavailable(msg) => { - (msg.contains("uds write") || msg.starts_with("uds connect")) - && !msg.contains("timeout") - } - // "uds closed before headers":对端在响应前关闭,请求未生效。 - GateError::Malformed(msg) => msg.contains("closed before headers"), - } -} - -/// 超时读取一块数据追加到 buf,返回读取字节数(0 = 对端关闭)。 -async fn read_with_timeout( - rd: &mut ReadHalf, - buf: &mut Vec, - chunk_size: usize, -) -> Result { - let mut chunk = vec![0u8; chunk_size]; - let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) - .await - .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? - .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; - buf.extend_from_slice(&chunk[..n]); - Ok(n) -} - -fn find_terminator(buf: &[u8]) -> Option { - buf.windows(4).position(|w| w == b"\r\n\r\n") -} - -impl GateClient for UdsGateClient { - async fn check( - &self, - request: ContextCheckRequest, - ) -> Result { - let body = serde_json::to_vec(&request).expect("serialize gate request"); - let this = self.clone(); - { - let (status, body) = this.request("POST", "/v1/context/check", Some(&body)).await?; - if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("gate HTTP {status}"))); - } - serde_json::from_slice(&body) - .map_err(|e| GateError::Malformed(format!("decode check: {e}"))) - } - } - - async fn capabilities(&self) -> Result { - let this = self.clone(); - { - let (status, body) = this.request("GET", "/v1/capabilities", None).await?; - if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("capabilities HTTP {status}"))); - } - serde_json::from_slice(&body) - .map_err(|e| GateError::Malformed(format!("decode capabilities: {e}"))) - } - } - - async fn prepare( - &self, - request: PrepareContextRequest, - ) -> Result { - let body = serde_json::to_vec(&request).expect("serialize gate request"); - let this = self.clone(); - { - let (status, body) = this.request("POST", "/v1/context/prepare", Some(&body)).await?; - if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("prepare HTTP {status}"))); - } - serde_json::from_slice(&body) - .map_err(|e| GateError::Malformed(format!("decode prepare: {e}"))) - } - } - - async fn capture( - &self, - request: CaptureContentSourceRequest, - ) -> Result { - let body = serde_json::to_vec(&request).expect("serialize gate request"); - let this = self.clone(); - { - let (status, body) = this.request("POST", "/v1/sources/content", Some(&body)).await?; - if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("capture HTTP {status}"))); - } - serde_json::from_slice(&body) - .map_err(|e| GateError::Malformed(format!("decode capture: {e}"))) - } - } -} diff --git a/powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs deleted file mode 100644 index ce91449351..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ /dev/null @@ -1,709 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! PR #2264 失败语义表的状态机级验证(真实契约形态)。 - -use pc_gateway_core::{DegradePolicy, Executor, GateClient, GateError, ManagedCall, ManagedOutcome}; -use pc_gateway_evidence::{BufferedEvidenceSink, NoopEvidenceSink}; -use pc_gateway_protocol::{ - CanonicalMessage, CanonicalRequest, OutputLimits, RenderedPayload, Role, WireRenderer, -}; -use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; -use pc_gateway_types::{ - CheckDecision, CheckPhase, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, - CaptureContentSourceRequest, PrepareContextResult, PreparedContext, PreparedContextLocation, -}; -use std::collections::VecDeque; -use std::future::Future; -use std::num::NonZeroU32; -use std::sync::{Arc, Mutex}; - -// ---------- 测试替身 ---------- - -struct RecordingRenderer { - renders: Mutex, -} - -impl WireRenderer for RecordingRenderer { - fn name(&self) -> &'static str { - "test" - } - fn render( - &self, - request: &CanonicalRequest, - _plan: Option<&serde_json::Value>, - ) -> Result { - *self.renders.lock().unwrap() += 1; - let messages: Vec = request - .messages - .iter() - .map(|m| { - let content = match m.content.as_slice() { - [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), - other => serde_json::json!(other), - }; - serde_json::json!({ "role": m.role, "content": content }) - }) - .collect(); - let bytes = serde_json::to_vec(&serde_json::json!({ - "model": request.model, - "messages": messages, - })) - .unwrap() - .into(); - Ok(RenderedPayload { - bytes, - content_type: "application/json", - }) - } -} - -/// 脚本化检查客户端:按序弹出结果,记录请求阶段与载荷。 -struct FakeGate { - results: Mutex>>, - seen: Mutex>, - prepared_seen: Mutex>>, - prepare_result: Mutex>>, - prepare_queries: Mutex>, - captured: Mutex>, -} - -impl GateClient for FakeGate { - fn check( - &self, - request: ContextCheckRequest, - ) -> impl Future> + Send { - let (phase, note) = match &request { - ContextCheckRequest::BeforeSend { payload, .. } => { - (CheckPhase::BeforeSend, payload.body.clone()) - } - ContextCheckRequest::BeforeRelease { - request_binding, .. - } => (CheckPhase::BeforeRelease, request_binding.clone()), - }; - let declared = match &request { - ContextCheckRequest::BeforeSend { prepared_contexts, .. } => prepared_contexts.clone(), - _ => Vec::new(), - }; - self.prepared_seen.lock().unwrap().push(declared); - self.seen.lock().unwrap().push((phase, note)); - let step = self.results.lock().unwrap().pop_front(); - async move { step.expect("gate script exhausted") } - } - - async fn capabilities(&self) -> Result { - Ok(serde_json::json!({ "enforcing": false })) - } - - fn prepare( - &self, - request: PrepareContextRequest, - ) -> impl Future> + Send { - self.prepare_queries.lock().unwrap().push(request.query); - let step = self.prepare_result.lock().unwrap().take() - .unwrap_or(Ok(PrepareContextResult::Plain(PreparedContext { - schema: "powercontext.prepared-context.v1".into(), - status: "empty".into(), - content: None, - content_bytes: 0, - }))); - async move { step } - } - - async fn capture( - &self, - request: CaptureContentSourceRequest, - ) -> Result { - self.captured.lock().unwrap().push((request.source_id, request.content)); - Ok(serde_json::json!({"captured": true})) - } -} - -struct FakeTransport { - outcomes: Mutex>, - sends: Mutex>, - bindings: Mutex>, - cancels: Mutex, -} - -impl Transport for FakeTransport { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a { - let outcome = self.outcomes.lock().unwrap().pop_front(); - self.sends.lock().unwrap().push(send.payload); - self.bindings.lock().unwrap().push(send.binding); - async move { - outcome.unwrap_or_else(|| panic!("transport script exhausted")) - } - } - - async fn cancel(&self, _send: &AdmittedSend) { - *self.cancels.lock().unwrap() += 1; - } -} - -fn raw_response() -> SendOutcome { - SendOutcome::Delivered(pc_gateway_transport::RawResponse { - status: 200, - content_type: "application/json".into(), - ttft_ms: None, - body: bytes::Bytes::from_static(br#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#), - usage: Some(serde_json::json!({"total_tokens": 1})), - }) -} - -fn result(phase: CheckPhase, decision: CheckDecision, reasons: &[&str]) -> ContextCheckResult { - ContextCheckResult { - schema: pc_gateway_types::CONTEXT_CHECK_SCHEMA.into(), - phase, - decision, - reason_codes: reasons.iter().map(|s| s.to_string()).collect(), - coverage: pc_gateway_types::ContextCheckCoverage { - profile: "text-and-tools.v1".into(), - complete: true, - }, - policy_version: "v1".into(), - valid_until: "2999-01-01T00:00:00Z".into(), - correlate_until: None, - binding: matches!(decision, CheckDecision::Allow).then(|| "binding-1".to_string()), - } -} - -fn call(degrade: DegradePolicy) -> ManagedCall { - ManagedCall { - scope_id: "project:test".into(), - target_profile: "openai:test".into(), - request: CanonicalRequest { - model: "test-model".into(), - messages: vec![CanonicalMessage { - role: Role::User, - content: vec![serde_json::json!("hello")], - }], - tools: vec![], - instructions: None, - native_cache_fields: None, - output_limits: OutputLimits { - max_output_tokens: 128, - }, - stream: false, - }, - target_url: "http://upstream.invalid/v1/chat/completions".into(), - headers: vec![("authorization".into(), "Bearer secret".into())], - degrade_policy: degrade, - inject_context: false, - sediment: false, - prepared_contexts: Vec::new(), - } -} - -#[derive(Clone)] -struct RendererRef(Arc); -impl WireRenderer for RendererRef { - fn name(&self) -> &'static str { - "test" - } - fn render( - &self, - request: &CanonicalRequest, - plan: Option<&serde_json::Value>, - ) -> Result { - WireRenderer::render(&*self.0, request, plan) - } -} - -#[derive(Clone)] -struct TransportRef(Arc); -impl Transport for TransportRef { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a { - Transport::send(&*self.0, send) - } - async fn cancel(&self, send: &AdmittedSend) { - Transport::cancel(&*self.0, send).await - } -} - -#[derive(Clone)] -struct FakeGateRef(Arc); -impl GateClient for FakeGateRef { - fn check( - &self, - request: ContextCheckRequest, - ) -> impl Future> + Send { - GateClient::check(&*self.0, request) - } - fn capabilities( - &self, - ) -> impl Future> + Send { - GateClient::capabilities(&*self.0) - } - - fn prepare( - &self, - request: PrepareContextRequest, - ) -> impl Future> + Send { - GateClient::prepare(&*self.0, request) - } - - fn capture( - &self, - request: CaptureContentSourceRequest, - ) -> impl Future> + Send { - GateClient::capture(&*self.0, request) - } -} - -fn harness( - gate_results: Vec>, - transport_outcomes: Vec, - max_attempts: u32, -) -> ( - Executor, - Arc, - Arc, - Arc, -) { - let renderer = Arc::new(RecordingRenderer { renders: Mutex::new(0) }); - let transport = Arc::new(FakeTransport { - outcomes: Mutex::new(transport_outcomes.into()), - sends: Mutex::new(Vec::new()), - bindings: Mutex::new(Vec::new()), - cancels: Mutex::new(0), - }); - let gate = Arc::new(FakeGate { - results: Mutex::new(gate_results.into()), - seen: Mutex::new(Vec::new()), - prepared_seen: Mutex::new(Vec::new()), - prepare_result: Mutex::new(None), - prepare_queries: Mutex::new(Vec::new()), - captured: Mutex::new(Vec::new()), - }); - let executor = Executor::new( - FakeGateRef(gate.clone()), - TransportRef(transport.clone()), - NonZeroU32::new(max_attempts).unwrap(), - ); - (executor, renderer, transport, gate) -} - -// ---------- 用例 ---------- - -#[tokio::test] -async fn allow_send_allow_release() { - let (executor, renderer, transport, gate) = harness( - vec![ - Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), - Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), - ], - vec![raw_response()], - 2, - ); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - match outcome { - ManagedOutcome::Released { binding, status, body, .. } => { - assert_eq!(binding.as_deref(), Some("binding-1")); - assert_eq!(status, 200); - let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); - assert_eq!(v["choices"][0]["message"]["content"], "ok"); - } - other => panic!("expected Released, got {other:?}"), - } - let seen = gate.seen.lock().unwrap().clone(); - assert_eq!(seen.len(), 2); - assert_eq!(seen[1], (CheckPhase::BeforeRelease, "binding-1".into())); - assert_eq!(transport.bindings.lock().unwrap()[0], "binding-1"); -} - -#[tokio::test] -async fn before_send_block_never_sends() { - let (executor, renderer, transport, _g) = harness( - vec![Ok(result( - CheckPhase::BeforeSend, - CheckDecision::Block, - &["privacy.denied"], - ))], - vec![], - 2, - ); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - match outcome { - ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), - other => panic!("expected Blocked, got {other:?}"), - } - assert_eq!(transport.sends.lock().unwrap().len(), 0); -} - -#[tokio::test] -async fn withhold_is_terminal_in_pr2264_contract() { - let (executor, renderer, transport, gate) = harness( - vec![Ok(result( - CheckPhase::BeforeSend, - CheckDecision::Withhold, - &["coverage.incomplete"], - ))], - vec![], - 2, - ); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - assert!(matches!(outcome, ManagedOutcome::Withheld { .. })); - assert_eq!(*renderer.renders.lock().unwrap(), 1); - assert_eq!(gate.seen.lock().unwrap().len(), 1); - assert_eq!(transport.sends.lock().unwrap().len(), 0); -} - -#[tokio::test] -async fn gate_unavailable_pauses_never_allow() { - let (executor, renderer, transport, _g) = harness( - vec![Err(GateError::GateUnavailable("down".into()))], - vec![], - 2, - ); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - assert!(matches!(outcome, ManagedOutcome::GatePaused(_))); - assert_eq!(transport.sends.lock().unwrap().len(), 0); -} - -#[tokio::test] -async fn gate_unavailable_degrades_when_allowed() { - let (executor, renderer, transport, _g) = harness( - vec![Err(GateError::GateUnavailable("down".into()))], - vec![raw_response()], - 2, - ); - let evidence = BufferedEvidenceSink::new(); - let outcome = executor - .run( - call(DegradePolicy::PassthroughWithoutMemory), - &RendererRef(renderer.clone()), - &evidence, - ) - .await; - assert!(matches!(outcome, ManagedOutcome::Degraded { .. })); - assert_eq!(evidence.not_sent().len(), 1); - assert_eq!(transport.sends.lock().unwrap().len(), 1); -} - -#[tokio::test] -async fn block_does_not_degrade() { - let (executor, renderer, transport, _g) = harness( - vec![Ok(result( - CheckPhase::BeforeSend, - CheckDecision::Block, - &["privacy.denied"], - ))], - vec![raw_response()], - 2, - ); - let outcome = executor - .run( - call(DegradePolicy::PassthroughWithoutMemory), - &RendererRef(renderer.clone()), - &NoopEvidenceSink, - ) - .await; - assert!(matches!(outcome, ManagedOutcome::Blocked { .. })); - assert_eq!(transport.sends.lock().unwrap().len(), 0); -} - -#[tokio::test] -async fn deterministic_not_sent_retries_bounded() { - let (executor, renderer, _transport, _g) = harness( - vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], - vec![ - SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), - SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), - ], - 2, - ); - let evidence = BufferedEvidenceSink::new(); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &evidence) - .await; - assert!(matches!(outcome, ManagedOutcome::NotSent { attempts: 2 })); - assert_eq!(evidence.attempts(), vec![1, 2]); -} - -#[tokio::test] -async fn indeterminate_never_resends() { - let (executor, renderer, transport, _g) = harness( - vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], - vec![SendOutcome::Indeterminate( - pc_gateway_transport::SendIndeterminateReason::TimeoutAwaitingResponse, - )], - 3, - ); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - assert!(matches!(outcome, ManagedOutcome::SendIndeterminate)); - assert_eq!(transport.sends.lock().unwrap().len(), 1); -} - -#[tokio::test] -async fn before_release_block_blocks_and_cancels() { - let (executor, renderer, transport, _g) = harness( - vec![ - Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), - Ok(result( - CheckPhase::BeforeRelease, - CheckDecision::Block, - &["privacy.denied"], - )), - ], - vec![raw_response()], - 2, - ); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - match outcome { - ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), - other => panic!("expected Blocked, got {other:?}"), - } - assert_eq!(*transport.cancels.lock().unwrap(), 1); -} - -#[tokio::test] -async fn credentials_never_enter_check_payload() { - let (executor, renderer, _t, gate) = harness( - vec![ - Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), - Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), - ], - vec![raw_response()], - 2, - ); - executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - let seen = gate.seen.lock().unwrap().clone(); - let (_, before_send_payload) = &seen[0]; - assert!( - !before_send_payload.contains("secret"), - "authorization 凭据不得进入 check 载荷: {before_send_payload}" - ); -} - -// ---------- 注入用例 ---------- - -fn reuse_result(content: &str) -> PrepareContextResult { - PrepareContextResult::WithReuse { - schema: "powercontext.prepared-context-with-reuse.v1".into(), - context: PreparedContext { - schema: "powercontext.prepared-context.v1".into(), - status: "ready".into(), - content: Some(content.to_string()), - content_bytes: content.len() as u64, - }, - reuse: pc_gateway_types::ContextReuse { - schema: "powercontext.context-reuse.v1".into(), - constraints: None, - expires_at: "2999-01-01T00:00:00Z".into(), - binding: "opaque-binding".into(), - }, - } -} - -#[tokio::test] -async fn injects_block_and_declares_exact_location() { - let (executor, renderer, transport, gate) = harness( - vec![ - Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), - Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), - ], - vec![raw_response()], - 2, - ); - *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( - "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", - ))); - let mut c = call(DegradePolicy::Pause); - c.inject_context = true; - let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; - assert!(matches!(outcome, ManagedOutcome::Released { .. })); - - // 检索词 = 最后一条 user 消息文本 - assert_eq!(gate.prepare_queries.lock().unwrap()[0], "hello"); - - // 载荷:标准块位于 user 消息头部 - let seen = gate.seen.lock().unwrap().clone(); - let payload = &seen[0].1; - let v: serde_json::Value = serde_json::from_str( - &format!("{{\"inner\":{payload}}}").replace("\"inner\":{", "\"inner\":", ), - ) - .unwrap_or(serde_json::Value::Null); - let _ = v; - let msg_text = extract_user_text(payload); - assert!(msg_text.starts_with("BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"), "块必须在头部: {msg_text}"); - assert!(msg_text.contains("网关必须无策略")); - assert!(msg_text.ends_with("hello")); - - // 区间声明:binding 原样、字节长度 = 块的 UTF-8 字节数(中文≠字符数) - let declared = gate.prepared_seen.lock().unwrap().clone(); - assert_eq!(declared[0].len(), 1); - let loc = &declared[0][0]; - assert_eq!(loc.binding, "opaque-binding"); - assert_eq!(loc.location.pointer, "/messages/0/content"); - assert_eq!(loc.location.schema, "powercontext.model-json-text-location.v1"); - assert_eq!(loc.location.start_byte, 0); - let block = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1"; - assert_eq!(loc.location.end_byte as usize, block.len()); - assert_eq!(transport.sends.lock().unwrap().len(), 1); -} - -fn extract_user_text(before_send_payload: &str) -> String { - // FakeGate 记录的即渲染后的请求体 JSON - let body: serde_json::Value = serde_json::from_str(before_send_payload).unwrap(); - body["messages"][0]["content"].as_str().unwrap().to_string() -} - -#[tokio::test] -async fn empty_prepare_injects_nothing() { - let (executor, renderer, _t, gate) = harness( - vec![ - Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), - Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), - ], - vec![raw_response()], - 2, - ); - // prepare 默认返回 empty(FakeGate 默认值) - let mut c = call(DegradePolicy::Pause); - c.inject_context = true; - executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; - let seen = gate.seen.lock().unwrap().clone(); - assert!(!seen[0].1.contains("BEGIN_POWERCONTEXT"), "empty 不得注入标记"); - assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); -} - -#[tokio::test] -async fn prepare_failure_still_sends_without_injection() { - let (executor, renderer, transport, gate) = harness( - vec![ - Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), - Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), - ], - vec![raw_response()], - 2, - ); - *gate.prepare_result.lock().unwrap() = Some(Err(GateError::GateUnavailable("down".into()))); - let evidence = BufferedEvidenceSink::new(); - let mut c = call(DegradePolicy::Pause); - c.inject_context = true; - let outcome = executor.run(c, &RendererRef(renderer.clone()), &evidence).await; - assert!(matches!(outcome, ManagedOutcome::Released { .. }), "prepare 失败不阻塞主链路"); - assert_eq!(transport.sends.lock().unwrap().len(), 1); - assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); - assert!(evidence.not_sent()[0].1.starts_with("prepare_failed")); -} - -#[tokio::test] -async fn sediment_captures_released_turn_synchronously() { - let (executor, renderer, _t, gate) = harness( - vec![ - Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), - Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), - ], - vec![raw_response()], - 2, - ); - let mut c = call(DegradePolicy::Pause); - c.sediment = true; - let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; - assert!(matches!(outcome, ManagedOutcome::Released { .. })); - let captured = gate.captured.lock().unwrap().clone(); - assert_eq!(captured.len(), 1, "Released 轮次同步沉淀一次"); - assert!(captured[0].0.starts_with("gw-turn-"), "幂等键: {}", captured[0].0); - let v: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); - assert_eq!(v["user"], "hello"); - assert_eq!(v["model"], "test-model"); -} - -#[tokio::test] -async fn blocked_turn_never_sediments() { - let (executor, renderer, _t, gate) = harness( - vec![Ok(result( - CheckPhase::BeforeSend, - CheckDecision::Block, - &["privacy.denied"], - ))], - vec![], - 2, - ); - let mut c = call(DegradePolicy::Pause); - c.sediment = true; - executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; - assert!(gate.captured.lock().unwrap().is_empty(), "被拦内容不得沉淀"); -} - -#[tokio::test] -async fn malformed_gate_never_degrades_even_with_passthrough() { - // Core 可达但返回畸形响应:不是"不可用",绝不允许降级直通(fail-closed)。 - let (executor, renderer, transport, _g) = harness( - vec![Err(GateError::Malformed("garbage response".into()))], - vec![raw_response()], - 2, - ); - let outcome = executor - .run( - call(DegradePolicy::PassthroughWithoutMemory), - &RendererRef(renderer.clone()), - &NoopEvidenceSink, - ) - .await; - assert!(matches!(outcome, ManagedOutcome::GatePaused(_)), "Malformed 必须暂停"); - assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); -} - -#[tokio::test] -async fn non_utf8_response_is_never_released() { - // 上游返回非法 UTF-8 字节:不做有损转换送检(保真缺口),直接不放行。 - let bad = SendOutcome::Delivered(pc_gateway_transport::RawResponse { - status: 200, - body: bytes::Bytes::from_static(b"{\"text\":\"\xff\xfe\"}"), // 非法 UTF-8 - content_type: "application/json".into(), - ttft_ms: None, - usage: None, - }); - let (executor, renderer, transport, gate) = harness( - vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], - vec![bad], - 2, - ); - let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) - .await; - match outcome { - ManagedOutcome::Withheld { reason_codes } => { - assert_eq!(reason_codes, ["invalid_response_encoding"]) - } - other => panic!("expected Withheld, got {other:?}"), - } - // 只有一次检查(before_send);非法响应根本不送检、不释放。 - // cancel 不适用:非流式调用响应已完整到达,无进行中的上游工作可取消。 - assert_eq!(gate.seen.lock().unwrap().len(), 1); - assert_eq!(*transport.cancels.lock().unwrap(), 0); -} diff --git a/powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs b/powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs deleted file mode 100644 index adc31cb393..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/tests/live_context_check.rs +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 对真实 PowerContext Server(PR #2264)的 HTTP 级集成测试。 -//! -//! 与单测(FakeGate)互补:这里验证的是 Core 侧加密 binding 的真实行为, -//! mock 无法复现。运行条件:真实 Server 在 PC_TEST_CORE_BASE(默认 -//! http://127.0.0.1:8000)可达且配置了 enforcing 保护与 "coding" profile; -//! 不可达时全部跳过(不失败)。 - -use pc_gateway_core::{GateClient, GateError, HttpGateClient}; -use pc_gateway_types::{ - CheckDecision, ContextCheckRequest, ContextCheckResult, ModelJsonPayload, -}; -use std::collections::BTreeMap; - -const CORE: &str = "http://127.0.0.1:8000"; -const TARGET_PROFILE: &str = "coding"; -const MODEL_BODY: &str = r#"{"model":"glm-4-flash","max_tokens":80,"stream":false,"messages":[{"role":"user","content":"hi"}]}"#; -const RESPONSE_BODY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#; - -fn client() -> HttpGateClient { - HttpGateClient::new(CORE) -} - -async fn core_ready() -> bool { - reqwest::Client::new() - .get(format!("{CORE}/health/ready")) - .timeout(std::time::Duration::from_secs(2)) - .send() - .await - .map(|r| r.status().is_success()) - .unwrap_or(false) -} - -async fn require_core() -> Option<()> { - if core_ready().await { - Some(()) - } else { - eprintln!("SKIP: real PowerContext Server not reachable at {CORE}"); - None - } -} - -fn payload(body: &str) -> ModelJsonPayload { - ModelJsonPayload::new( - BTreeMap::from([("content-type".to_string(), "application/json".to_string())]), - body.to_string(), - ) -} - -async fn create_scope(tag: &str) -> Option { - let resp = reqwest::Client::new() - .post(format!("{CORE}/v1/scopes")) - .json(&serde_json::json!({ - "title": format!("Rust gateway test {tag}"), - "summary": "created by live integration tests", - "idempotency_key": format!("rust-live-{tag}"), - })) - .send() - .await - .ok()?; - let v: serde_json::Value = resp.json().await.ok()?; - v.get("scope_id")?.as_str().map(String::from) -} - -async fn before_send(scope: &str) -> Result { - client() - .check(ContextCheckRequest::BeforeSend { - scope_id: scope.to_string(), - target_profile: TARGET_PROFILE.to_string(), - payload: payload(MODEL_BODY), - prepared_contexts: Vec::new(), - }) - .await -} - -async fn before_release(scope: &str, binding: &str) -> Result { - client() - .check(ContextCheckRequest::BeforeRelease { - scope_id: scope.to_string(), - target_profile: TARGET_PROFILE.to_string(), - request_binding: binding.to_string(), - payload: payload(RESPONSE_BODY), - completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.to_string(), - }) - .await -} - -// ---------- 用例 ---------- - -/// happy path:真实 allow 返回加密 binding、完整覆盖与两个期限。 -#[tokio::test] -async fn live_allow_returns_real_binding_and_deadlines() { - let Some(_) = require_core().await else { return }; - let Some(scope) = create_scope("happy").await else { - panic!("scope creation failed"); - }; - let result = before_send(&scope).await.expect("check should succeed"); - - assert_eq!(result.decision, CheckDecision::Allow, "reasons: {:?}(需配置 coding profile)", result.reason_codes); - assert!(result.coverage.complete); - let binding = result.binding.as_deref().expect("allow 必须携带 binding"); - assert!(binding.starts_with("pc1."), "真实加密 binding 前缀: {binding:.20}..."); - - // 期限分离:发送窗口 ~60s,关联窗口 ~300s。 - let now = chrono_like_now(); - let valid = parse_epoch_ms(&result.valid_until); - let correlate = result.correlate_until.as_deref().map(parse_epoch_ms); - assert!( - valid > now && valid <= now + 65_000, - "发送期限应在 60s 窗口内: valid={valid} now={now}" - ); - let Some(correlate) = correlate else { panic!("before_send allow 必须带 correlate_until") }; - assert!( - correlate > now && correlate <= now + 310_000, - "关联期限应在 300s 窗口内" - ); -} - -/// 伪造 binding 做 before_release → Core 必须拒绝(绝不能 allow)。 -#[tokio::test] -async fn live_forged_binding_is_rejected() { - let Some(_) = require_core().await else { return }; - let Some(scope) = create_scope("forged").await else { panic!("scope creation failed") }; - let result = before_release(&scope, "pc1.forged-binding-not-issued-by-core").await; - match result { - Ok(r) => assert_ne!( - r.decision, - CheckDecision::Allow, - "伪造 binding 不得被放行: {:?}", - r.reason_codes - ), - // 4xx 拒绝(如绑定校验直接失败)同样视为通过。 - Err(GateError::GateUnavailable(msg)) => assert!( - msg.contains("HTTP 4"), - "期望 4xx 拒绝,得到: {msg}" - ), - Err(other) => panic!("unexpected: {other}"), - } -} - -/// binding 跨 Scope 使用 → 拒绝(对应 PC 测试 -/// `test_request_binding_cannot_cross_identity_scope_or_current_policy`)。 -#[tokio::test] -async fn live_binding_cannot_cross_scope() { - let Some(_) = require_core().await else { return }; - let (Some(scope_a), Some(scope_b)) = (create_scope("cross-a").await, create_scope("cross-b").await) - else { - panic!("scope creation failed"); - }; - let allow = before_send(&scope_a).await.expect("check a"); - assert_eq!(allow.decision, CheckDecision::Allow, "reasons: {:?}", allow.reason_codes); - let binding = allow.binding.expect("binding"); - - let cross = before_release(&scope_b, &binding).await; - match cross { - Ok(r) => assert_ne!( - r.decision, - CheckDecision::Allow, - "A 的 binding 不得放行 B 的释放: {:?}", - r.reason_codes - ), - Err(GateError::GateUnavailable(msg)) => assert!( - msg.contains("HTTP 4"), - "期望 4xx 拒绝,得到: {msg}" - ), - Err(other) => panic!("unexpected: {other}"), - } -} - -/// 线格式刚性:缺 prepared_contexts(必填)→ 422,验证 Rust DTO 与 -/// 真实 OpenAPI 的逐字段对齐。 -#[tokio::test] -async fn live_missing_prepared_contexts_rejected() { - let Some(_) = require_core().await else { return }; - let Some(scope) = create_scope("dto").await else { panic!("scope creation failed") }; - let raw = serde_json::json!({ - "phase": "before_send", - "scope_id": scope, - "target_profile": TARGET_PROFILE, - "payload": { - "schema": pc_gateway_types::MODEL_JSON_PAYLOAD_SCHEMA, - "headers": {"content-type": "application/json"}, - "body": MODEL_BODY, - }, - // 故意省略 prepared_contexts - }); - let resp = reqwest::Client::new() - .post(format!("{CORE}/v1/context/check")) - .json(&raw) - .send() - .await - .expect("post"); - assert_eq!(resp.status().as_u16(), 422, "缺必填字段必须 422"); -} - -// ---------- 工具 ---------- - -/// 无 chrono 依赖的简易 RFC3339 解析(足够测试用,格式由 Core 保证)。 -fn parse_epoch_ms(rfc3339: &str) -> u64 { - // 形如 2026-10-28T09:55:06.464580Z - let bytes = rfc3339.as_bytes(); - let year: i64 = rfc3339[0..4].parse().unwrap(); - let month: i64 = rfc3339[5..7].parse().unwrap(); - let day: i64 = rfc3339[8..10].parse().unwrap(); - let hour: i64 = rfc3339[11..13].parse().unwrap(); - let min: i64 = rfc3339[14..16].parse().unwrap(); - let sec: i64 = rfc3339[17..19].parse().unwrap(); - let millis: i64 = if bytes.len() > 20 { - let frac = &rfc3339[20..rfc3339.len().saturating_sub(1)]; - let frac = frac.trim_end_matches('Z'); - let taken: String = frac.chars().take(3).collect(); - taken.parse().unwrap_or(0) - } else { - 0 - }; - // 简化儒略日换算(1970 起,平年近似,测试时间尺度下足够)。 - let days = days_from_civil(year, month, day); - ((days * 86_400 + hour * 3600 + min * 60 + sec) * 1000 + millis) as u64 -} - -fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { - let y = if m <= 2 { y - 1 } else { y }; - let era = if y >= 0 { y } else { y - 399 } / 400; - let yoe = y - era * 400; - let mp = (m + 9) % 12; - let doy = (153 * mp + 2) / 5 + d - 1; - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; - era * 146_097 + doe - 719_468 -} - -fn chrono_like_now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0) -} diff --git a/powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs b/powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs deleted file mode 100644 index dbfdab277b..0000000000 --- a/powercontext/gateway/crates/pc-gateway-core/tests/uds_pool.rs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! UDS 连接池正确性回归:keep-alive 连接上的连续响应必须逐次正确解析。 -//! 覆盖三个场景:content-length 精确、chunked(含 trailer)、content-length 超读截断。 - -use pc_gateway_core::{GateClient, UdsGateClient}; -use pc_gateway_types::{ - CheckDecision, CheckPhase, ContextCheckRequest, ModelJsonPayload, -}; -use std::collections::BTreeMap; -use std::sync::atomic::{AtomicUsize, Ordering}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::{UnixListener, UnixStream}; - -static CONN_COUNT: AtomicUsize = AtomicUsize::new(0); - -fn result_json(decision: &str) -> String { - let schema = "powercontext.context-check.v1"; - format!( - r#"{{"schema":"{schema}","phase":"before_send","decision":"{decision}","reason_codes":[],"coverage":{{"profile":"text-and-tools.v1","complete":true}},"policy_version":"t","valid_until":"2999-01-01T00:00:00Z","binding":"b1"}}"# - ) -} - -fn check_request() -> ContextCheckRequest { - ContextCheckRequest::BeforeSend { - scope_id: "s".into(), - target_profile: "p".into(), - payload: ModelJsonPayload::new(BTreeMap::new(), "{}".into()), - prepared_contexts: Vec::new(), - } -} - -/// 读一行请求头直到空行(忽略 body 细节,够用即可)。 -async fn read_request(conn: &mut UnixStream) { - let mut buf = Vec::new(); - let mut byte = [0u8; 1]; - loop { - conn.read_exact(&mut byte).await.unwrap(); - buf.push(byte[0]); - if buf.ends_with(b"\r\n\r\n") { - break; - } - } - // 简化:Content-Length 为 0 的探测请求到此结束;带 body 的读掉 - let head = String::from_utf8_lossy(&buf).to_string(); - if let Some(len) = head - .lines() - .find_map(|l| l.strip_prefix("Content-Length: ").and_then(|v| v.trim().parse::().ok())) - { - let mut body = vec![0u8; len]; - if len > 0 { - conn.read_exact(&mut body).await.unwrap(); - } - } -} - -#[tokio::test] -async fn pooled_connection_parses_sequential_responses_correctly() { - let dir = std::env::temp_dir().join(format!("pc-uds-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let sock = dir.join("pool.sock"); - let _ = std::fs::remove_file(&sock); - let listener = UnixListener::bind(&sock).unwrap(); - - let server = tokio::spawn(async move { - let (mut conn, _) = listener.accept().await.unwrap(); - CONN_COUNT.fetch_add(1, Ordering::SeqCst); - - // 请求1 → content-length 精确 - read_request(&mut conn).await; - let body = result_json("allow"); - conn.write_all( - format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", body.len()).as_bytes(), - ).await.unwrap(); - conn.write_all(body.as_bytes()).await.unwrap(); - - // 请求2 → chunked(0-chunk + 终止 CRLF,即 trailer 空行) - read_request(&mut conn).await; - let body2 = result_json("allow"); - let mut chunked = Vec::new(); - chunked.extend_from_slice(format!("{:x}\r\n", body2.len()).as_bytes()); - chunked.extend_from_slice(body2.as_bytes()); - chunked.extend_from_slice(b"\r\n0\r\n\r\n"); - conn.write_all( - b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n", - ).await.unwrap(); - conn.write_all(&chunked).await.unwrap(); - - // 请求3 → content-length 后故意多推 5 个脏字节(应被截断且连接不复用) - read_request(&mut conn).await; - let body3 = result_json("allow"); - conn.write_all( - format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body3.len()).as_bytes(), - ).await.unwrap(); - conn.write_all(body3.as_bytes()).await.unwrap(); - conn.write_all(b"DIRTY").await.unwrap(); - // 保持连接打开一会儿,验证客户端没把脏字节当下一响应 - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - }); - - let client = UdsGateClient::new(&sock); - // 请求1:content-length 精确 - let r1 = client.check(check_request()).await.unwrap(); - assert_eq!(r1.decision, CheckDecision::Allow); - // 请求2:chunked 应正确解码(而非把 trailer 当下一个响应头) - let r2 = client.check(check_request()).await.unwrap(); - assert_eq!(r2.decision, CheckDecision::Allow); - assert_eq!(r2.phase, CheckPhase::BeforeSend, "chunked 解码后字段完整"); - // 请求3:超读截断——body 应恰好是合法 JSON(脏字节被丢弃) - let r3 = client.check(check_request()).await.unwrap(); - assert_eq!(r3.decision, CheckDecision::Allow); - - server.await.unwrap(); - // 三次请求只应建立一条连接(第3次后因脏字节弃用,但那是之后的事) - assert_eq!(CONN_COUNT.load(Ordering::SeqCst), 1, "keep-alive 应复用同一连接"); -} diff --git a/powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml b/powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml deleted file mode 100644 index a854a4ac55..0000000000 --- a/powercontext/gateway/crates/pc-gateway-embedded/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[package] -name = "pc-gateway-embedded" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "PowerContext Gateway: optional embedded/FFI surface for in-process (Python) executors" - -[dependencies] -pc-gateway-core = { workspace = true } -pc-gateway-types = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs b/powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs deleted file mode 100644 index b69b1f5240..0000000000 --- a/powercontext/gateway/crates/pc-gateway-embedded/src/lib.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 嵌入式路径的占位 crate。 -//! -//! RFC:SDK/内置执行与 Rust GatewayRuntime 是按调用配置的两种执行路径, -//! 同一部署可并存,落实同一套 Core 决策。本 crate 未来承载 -//! pyo3/FFI 绑定,让 Python 进程内执行器复用 `pc-gateway-core` 的状态机, -//! 并以进程内 `GateClient` 实现直调 Core 算法(无需 HTTP)。 -//! -//! v1 尚未实现;保留 crate 以固定 workspace 边界。 diff --git a/powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml b/powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml deleted file mode 100644 index 0b939df869..0000000000 --- a/powercontext/gateway/crates/pc-gateway-evidence/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[package] -name = "pc-gateway-evidence" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "PowerContext Gateway: evidence normalization — usage completeness, cache read/write, latency; never bodies" - -[dependencies] -serde = { workspace = true } -serde_json = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs b/powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs deleted file mode 100644 index b980a257f7..0000000000 --- a/powercontext/gateway/crates/pc-gateway-evidence/src/lib.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 证据适配层。 -//! -//! RFC 约束:归一化实际目标身份、usage 完整性、供应商缓存 read/write、 -//! 失败尝试与延迟;分别报告上游首 token 与首次内容释放时间; -//! **绝不记录 query/prompt/响应正文/凭据**;执行身份不进指标标签。 -//! 已知 / 估算 / 未知 / 对账用量分开记录,不可用标 unknown 不记零。 - -use serde::{Deserialize, Serialize}; - -/// usage 完整性:不把缺失当零。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum UsageCompleteness { - Known, - Estimated, - Unknown, - Reconciled, -} - -/// 单次调用的无正文证据记录。 -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct CallEvidence { - /// 实际发送目标身份(归一化后),不是客户端声称的目标。 - pub actual_target: Option, - pub completeness: Option, - pub input_tokens: Option, - pub output_tokens: Option, - pub cache_read_tokens: Option, - pub cache_write_tokens: Option, - pub attempts: u32, - /// 上游首 token 延迟(毫秒)。 - pub upstream_ttft_ms: Option, - /// 首次内容释放延迟(毫秒)。strict 模式下必然晚于 ttft。 - pub first_release_ms: Option, - /// 失败原因类别(无正文)。 - pub failure_reason: Option, -} - -/// 证据下沉抽象。实现可以是空对象(观测可选), -/// 借鉴 TensorZero 的 disabled client 模式。 -pub trait EvidenceSink: Send + Sync { - fn record_attempt(&self, attempt: u32); - fn record_not_sent(&self, attempt: u32, reason: &str); - fn record_call(&self, evidence: &CallEvidence); -} - -/// 空对象实现:观测关闭时使用。 -#[derive(Debug, Default, Clone, Copy)] -pub struct NoopEvidenceSink; - -impl EvidenceSink for NoopEvidenceSink { - fn record_attempt(&self, _attempt: u32) {} - fn record_not_sent(&self, _attempt: u32, _reason: &str) {} - fn record_call(&self, _evidence: &CallEvidence) {} -} - -/// 内存缓冲实现:测试与本地演示用;不落盘、不落正文。 -#[derive(Debug, Default)] -pub struct BufferedEvidenceSink { - attempts: std::sync::Mutex>, - not_sent: std::sync::Mutex>, - calls: std::sync::Mutex>, -} - -impl BufferedEvidenceSink { - pub fn new() -> Self { - Self::default() - } - - pub fn attempts(&self) -> Vec { - self.attempts.lock().expect("evidence lock").clone() - } - - pub fn not_sent(&self) -> Vec<(u32, String)> { - self.not_sent.lock().expect("evidence lock").clone() - } - - pub fn calls(&self) -> Vec { - self.calls.lock().expect("evidence lock").clone() - } -} - -impl EvidenceSink for BufferedEvidenceSink { - fn record_attempt(&self, attempt: u32) { - self.attempts.lock().expect("evidence lock").push(attempt); - } - - fn record_not_sent(&self, attempt: u32, reason: &str) { - self.not_sent - .lock() - .expect("evidence lock") - .push((attempt, reason.to_string())); - } - - fn record_call(&self, evidence: &CallEvidence) { - self.calls.lock().expect("evidence lock").push(evidence.clone()); - } -} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml b/powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml deleted file mode 100644 index 74ae8e4e8d..0000000000 --- a/powercontext/gateway/crates/pc-gateway-protocol/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[package] -name = "pc-gateway-protocol" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "PowerContext Gateway: canonical internal types + per-provider wire-format conversion + SSE parsing" - -[dependencies] -pc-gateway-types = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -bytes = { workspace = true } -thiserror = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs deleted file mode 100644 index 260df4819d..0000000000 --- a/powercontext/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use serde::{Deserialize, Serialize}; - -/// 网关内部规范请求:发送前必须完整落入 input/check。 -/// 只保留结构性字段,语义内容由 Core 裁决。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CanonicalRequest { - pub model: String, - pub messages: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub tools: Vec, - /// Responses API 的 instructions(系统级指令);chat 格式为 None。 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub instructions: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub native_cache_fields: Option, - /// 显式输出限制(与输入预算分开;见 RFC「补充上下文字节与完整请求 token」)。 - pub output_limits: OutputLimits, - /// 是否请求上游流式(SSE)。strict 语义不变:网关全量缓冲并过 - /// before_release 后才向客户端释放;流式的是上游接收路径。 - #[serde(default)] - pub stream: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CanonicalMessage { - pub role: Role, - pub content: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Role { - System, - User, - Assistant, - Tool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub struct OutputLimits { - pub max_output_tokens: u32, -} - -/// 渲染结果:语义内容不变的最终字节。 -#[derive(Debug, Clone)] -pub struct RenderedPayload { - pub bytes: bytes::Bytes, - pub content_type: &'static str, -} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs deleted file mode 100644 index 962dc96a73..0000000000 --- a/powercontext/gateway/crates/pc-gateway-protocol/src/lib.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 协议适配层:内部规范类型 ↔ 各服务商线格式。 -//! -//! RFC 约束:只渲染获准的协议字段;保持角色、工具顺序、内容块、 -//! 可复用边界与获准原生缓存设置;不向稳定 prompt 写入请求 ID/时间戳、 -//! 不任意合并旧消息、不静默重映射目标。 - -mod canonical; -mod render; -mod sse; - -pub use canonical::*; -pub use render::*; -pub use sse::*; diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/render.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/render.rs deleted file mode 100644 index 8552772426..0000000000 --- a/powercontext/gateway/crates/pc-gateway-protocol/src/render.rs +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{CanonicalRequest, RenderedPayload}; - -/// 渲染错误。 -#[derive(Debug, thiserror::Error)] -pub enum RenderError { - #[error("unsupported field for renderer {renderer}: {field}")] - UnsupportedField { renderer: &'static str, field: String }, - #[error("cache render plan invalid for renderer {renderer}")] - InvalidRenderPlan { renderer: &'static str }, -} - -/// 线格式渲染器。OpenAI 系实现共享同一份 chat-completions 渲染 -/// (借鉴 TensorZero 的 chat_completions 共享模块模式)。 -/// -/// v1 strict 语义:完整渲染最终字节交给 input/check; -/// 缓存渲染计划(withhold 附带)只允许合并计划里显式列出的顶层字段。 -pub trait WireRenderer: Send + Sync { - fn name(&self) -> &'static str; - fn render( - &self, - request: &CanonicalRequest, - cache_render_plan: Option<&serde_json::Value>, - ) -> Result; -} - -/// OpenAI 兼容 chat-completions 渲染器。 -/// -/// 不依赖厂商 SDK,直接序列化线格式(对齐 RFC:高层包装无法证明 -/// 覆盖最终序列化、内部重试与原始错误)。strict v1 固定 `stream: false`, -/// 上游以完整单元返回,SSE 分帧在 output/check 之后由网关侧完成。 -#[derive(Debug, Default, Clone, Copy)] -pub struct OpenAiChatRenderer; - -impl WireRenderer for OpenAiChatRenderer { - fn name(&self) -> &'static str { - "openai-chat-completions" - } - - fn render( - &self, - request: &CanonicalRequest, - cache_render_plan: Option<&serde_json::Value>, - ) -> Result { - // OpenAI 线格式:纯文本 content 用字符串形式(部分兼容后端不接受 - // 无 type 的部件数组);多部件 content 按原样透传。 - let mut messages = Vec::with_capacity(request.messages.len()); - for m in &request.messages { - let content: serde_json::Value = match m.content.as_slice() { - [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), - other => serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { - renderer: self.name(), - field: e.to_string(), - })?, - }; - messages.push(serde_json::json!({ - "role": m.role, - "content": content, - })); - } - - // 只写入确定性的结构字段;不写请求 ID/时间戳(缓存前缀保真)。 - let mut body = serde_json::json!({ - "model": request.model, - "messages": messages, - "max_tokens": request.output_limits.max_output_tokens, - "stream": request.stream, - }); - if !request.tools.is_empty() { - body["tools"] = serde_json::json!(request.tools); - } - if let Some(fields) = request.native_cache_fields.as_ref() { - merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { - renderer: self.name(), - })?; - } - if let Some(plan) = cache_render_plan { - merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { - renderer: self.name(), - })?; - } - - let bytes = serde_json::to_vec(&body) - .map_err(|_| RenderError::InvalidRenderPlan { - renderer: self.name(), - })? - .into(); - Ok(RenderedPayload { - bytes, - content_type: "application/json", - }) - } -} - -/// 双格式渲染器:入口格式即上游格式(同格式进出,无跨格式转换)。 -#[derive(Debug, Clone, Copy)] -pub enum GatewayRenderer { - Chat(OpenAiChatRenderer), - Responses(OpenAiResponsesRenderer), -} - -impl Default for GatewayRenderer { - fn default() -> Self { - GatewayRenderer::Chat(OpenAiChatRenderer) - } -} - -impl WireRenderer for GatewayRenderer { - fn name(&self) -> &'static str { - match self { - GatewayRenderer::Chat(r) => r.name(), - GatewayRenderer::Responses(r) => r.name(), - } - } - - fn render( - &self, - request: &CanonicalRequest, - cache_render_plan: Option<&serde_json::Value>, - ) -> Result { - match self { - GatewayRenderer::Chat(r) => r.render(request, cache_render_plan), - GatewayRenderer::Responses(r) => r.render(request, cache_render_plan), - } - } -} - -/// 只合并获准的顶层键;src 必须是对象。 -fn merge_top_level(dst: &mut serde_json::Value, src: &serde_json::Value) -> Result<(), ()> { - let src_obj = src.as_object().ok_or(())?; - let dst_obj = dst.as_object_mut().ok_or(())?; - for (k, v) in src_obj { - dst_obj.insert(k.clone(), v.clone()); - } - Ok(()) -} - -/// OpenAI Responses API 渲染器。 -/// -/// 同格式进出:客户端用 Responses 格式进来,上游也渲染为 Responses; -/// 不做 chat ↔ responses 的跨格式转换(保真优先)。 -/// content 里携带的 Responses 专有 item(function_call、function_call_output、 -/// item_reference、reasoning 等)按原样作为顶层 input item 透出。 -#[derive(Debug, Default, Clone, Copy)] -pub struct OpenAiResponsesRenderer; - -/// Responses API 的顶层 input item 类型(区别于消息内 content part 的 -/// input_text/output_text 等文本部件)。 -const RESPONSES_ITEM_TYPES: &[&str] = &[ - "message", - "function_call", - "function_call_output", - "custom_tool_call", - "custom_tool_call_output", - "item_reference", - "reasoning", - "web_search_call", - "file_search_call", - "computer_call", - "computer_call_output", - "image_generation_call", - "code_interpreter_call", - "mcp_call", - "mcp_list_tools", -]; - -fn is_responses_item(v: &serde_json::Value) -> bool { - v.get("type") - .and_then(|t| t.as_str()) - .map(|t| RESPONSES_ITEM_TYPES.contains(&t)) - .unwrap_or(false) -} - -impl WireRenderer for OpenAiResponsesRenderer { - fn name(&self) -> &'static str { - "openai-responses" - } - - fn render( - &self, - request: &CanonicalRequest, - cache_render_plan: Option<&serde_json::Value>, - ) -> Result { - let mut input = Vec::with_capacity(request.messages.len()); - for msg in &request.messages { - // 单元素 content 且是 Responses 专有 item → 原样作为顶层 item。 - if msg.content.len() == 1 && is_responses_item(&msg.content[0]) { - input.push(msg.content[0].clone()); - continue; - } - let content: serde_json::Value = serde_json::to_value(&msg.content) - .map_err(|e| RenderError::UnsupportedField { - renderer: self.name(), - field: e.to_string(), - })?; - input.push(serde_json::json!({ - "role": msg.role, - "content": content, - })); - } - - let mut body = serde_json::json!({ - "model": request.model, - "input": input, - "max_output_tokens": request.output_limits.max_output_tokens, - "stream": request.stream, - }); - if let Some(instructions) = &request.instructions { - body["instructions"] = serde_json::json!(instructions); - } - if !request.tools.is_empty() { - body["tools"] = serde_json::json!(request.tools); - } - if let Some(fields) = request.native_cache_fields.as_ref() { - merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { - renderer: self.name(), - })?; - } - if let Some(plan) = cache_render_plan { - merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { - renderer: self.name(), - })?; - } - - let bytes = serde_json::to_vec(&body) - .map_err(|_| RenderError::InvalidRenderPlan { - renderer: self.name(), - })? - .into(); - Ok(RenderedPayload { - bytes, - content_type: "application/json", - }) - } -} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs b/powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs deleted file mode 100644 index 410b9e86da..0000000000 --- a/powercontext/gateway/crates/pc-gateway-protocol/src/sse.rs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! SSE 解析。 -//! -//! RFC 约束:strict 模式在完整 output/check 之后才组帧, -//! 因此网关 v1 对上游流是全量缓冲单元,不做增量放行; -//! bounded streaming 是后续独立提案。 - -use bytes::Bytes; - -/// 缓冲中的一个原始事件(不解释语义;语义归 output/check 与调用方)。 -#[derive(Debug, Clone)] -pub struct RawSseEvent { - pub event: Option, - pub data: Bytes, -} - -/// 增量解析器:从上游字节流切出原始 SSE 事件。 -/// 只做切帧,不做内容检查——检查的是完整单元。 -#[derive(Default)] -pub struct SseFramer { - buf: Vec, -} - -impl SseFramer { - pub fn push(&mut self, chunk: &[u8]) { - self.buf.extend_from_slice(chunk); - } - - /// 取出所有完整事件(以空行分隔)。 - pub fn take_events(&mut self) -> Vec { - let mut events = Vec::new(); - while let Some(pos) = find_blank_line(&self.buf) { - let block: Vec = self.buf.drain(..pos).collect(); - self.buf.drain(..2); // CRLF/LF 分隔符 - if let Some(ev) = parse_block(&block) { - events.push(ev); - } - } - events - } - - /// 结束流时收尾(缓冲中残余的最后一个块)。 - pub fn finish(&mut self) -> Vec { - let rest = std::mem::take(&mut self.buf); - match parse_block(&rest) { - Some(ev) => vec![ev], - None => Vec::new(), - } - } -} - -fn find_blank_line(buf: &[u8]) -> Option { - buf.windows(2).position(|w| w == b"\n\n" || w == b"\r\n") -} - -fn parse_block(block: &[u8]) -> Option { - let text = String::from_utf8_lossy(block); - let mut event = None; - let mut data_lines = Vec::new(); - for line in text.lines() { - if let Some(v) = line.strip_prefix("event:") { - event = Some(v.trim().to_string()); - } else if let Some(v) = line.strip_prefix("data:") { - data_lines.push(v.strip_prefix(' ').unwrap_or(v)); - } - } - if data_lines.is_empty() { - return None; - } - Some(RawSseEvent { - event, - data: Bytes::from(data_lines.join("\n")), - }) -} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs deleted file mode 100644 index 7b51de714d..0000000000 --- a/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use pc_gateway_protocol::{ - CanonicalMessage, CanonicalRequest, OpenAiChatRenderer, OutputLimits, Role, WireRenderer, -}; - -fn request() -> CanonicalRequest { - CanonicalRequest { - model: "m".into(), - messages: vec![CanonicalMessage { - role: Role::User, - content: vec![serde_json::json!("hi")], - }], - tools: vec![], - instructions: None, - native_cache_fields: None, - output_limits: OutputLimits { - max_output_tokens: 16, - }, - stream: false, - } -} - -#[test] -fn renders_deterministic_base_body() { - let p = OpenAiChatRenderer.render(&request(), None).unwrap(); - let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); - assert_eq!(v["model"], "m"); - assert_eq!(v["stream"], false); - assert_eq!(v["max_tokens"], 16); - // 缓存前缀保真:不注入请求 ID/时间戳类字段。 - assert!(v.get("request_id").is_none()); - assert!(v.get("timestamp").is_none()); -} - -#[test] -fn merges_only_approved_cache_plan_fields() { - let plan = serde_json::json!({"cache_control": {"type": "ephemeral"}}); - let p = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap(); - let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); - assert_eq!(v["cache_control"]["type"], "ephemeral"); - assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); -} - -#[test] -fn non_object_plan_rejected() { - let plan = serde_json::json!(["not", "an", "object"]); - let err = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap_err(); - assert!(matches!( - err, - pc_gateway_protocol::RenderError::InvalidRenderPlan { .. } - )); -} - -#[test] -fn stream_flag_reaches_wire_format() { - let mut req = request(); - req.stream = true; - let p = OpenAiChatRenderer.render(&req, None).unwrap(); - let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); - assert_eq!(v["stream"], true, "stream 标志必须原样到达线格式"); -} diff --git a/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs deleted file mode 100644 index efd9937d6a..0000000000 --- a/powercontext/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use pc_gateway_protocol::{ - CanonicalMessage, CanonicalRequest, OpenAiResponsesRenderer, OutputLimits, Role, - WireRenderer, -}; - -fn request() -> CanonicalRequest { - CanonicalRequest { - model: "m".into(), - messages: vec![CanonicalMessage { - role: Role::User, - content: vec![serde_json::json!("hi")], - }], - tools: vec![], - instructions: Some("be terse".into()), - native_cache_fields: None, - output_limits: OutputLimits { - max_output_tokens: 16, - }, - stream: false, - } -} - -#[test] -fn renders_responses_wire_format() { - let p = OpenAiResponsesRenderer.render(&request(), None).unwrap(); - let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); - assert_eq!(v["model"], "m"); - assert_eq!(v["instructions"], "be terse"); - assert_eq!(v["max_output_tokens"], 16); - assert_eq!(v["stream"], false); - assert_eq!(v["input"][0]["role"], "user"); - assert!(v.get("messages").is_none(), "不得混入 chat 字段"); - assert!(v.get("max_tokens").is_none()); -} - -#[test] -fn responses_items_pass_through_verbatim() { - let fc = serde_json::json!({ - "type": "function_call", "call_id": "c1", "name": "search", "arguments": "{}" - }); - let req = CanonicalRequest { - model: "m".into(), - messages: vec![ - CanonicalMessage { - role: Role::User, - content: vec![serde_json::json!("hi")], - }, - // 无 role 的顶层 item:原样封进 content,渲染时作为顶层 item 透出 - CanonicalMessage { - role: Role::Tool, - content: vec![fc.clone()], - }, - ], - tools: vec![], - instructions: None, - native_cache_fields: None, - output_limits: OutputLimits { - max_output_tokens: 16, - }, - stream: false, - }; - let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); - let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); - assert_eq!(v["input"].as_array().unwrap().len(), 2); - assert_eq!(v["input"][1], fc, "Responses 专有 item 必须字节级透传"); -} - -#[test] -fn merges_only_approved_cache_plan_fields() { - let plan = serde_json::json!({"prompt_cache_key": "scope-1"}); - let p = OpenAiResponsesRenderer.render(&request(), Some(&plan)).unwrap(); - let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); - assert_eq!(v["prompt_cache_key"], "scope-1"); - assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); -} diff --git a/powercontext/gateway/crates/pc-gateway-transport/Cargo.toml b/powercontext/gateway/crates/pc-gateway-transport/Cargo.toml deleted file mode 100644 index 5fa369e5b4..0000000000 --- a/powercontext/gateway/crates/pc-gateway-transport/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[package] -name = "pc-gateway-transport" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "PowerContext Gateway: transport — send admitted bytes, cancel, bounded retry with single owner" - -[dependencies] -pc-gateway-types = { workspace = true } -pc-gateway-evidence = { workspace = true } -bytes = { workspace = true } -futures-core = { workspace = true } -serde_json = { workspace = true } -thiserror = { workspace = true } -tokio = { workspace = true } -reqwest = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/lib.rs b/powercontext/gateway/crates/pc-gateway-transport/src/lib.rs deleted file mode 100644 index df6ef271aa..0000000000 --- a/powercontext/gateway/crates/pc-gateway-transport/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 传输层:发送获准字节、取消、归属明确的有界重试。 -//! -//! RFC 失败语义: -//! - 准入后正文/目标/设置变化 → 重新准入后才能发送; -//! - 确定性未送达 → 唯一所有者在有效准入和有界次数内重试; -//! - 可能已送达 → 返回不确定,不自动付费重发; -//! - 未 admission 的字节绝不出网。 - -mod reqwest_transport; -mod retry; -mod sender; - -pub use reqwest_transport::*; -pub use retry::*; -pub use sender::*; diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs deleted file mode 100644 index 8bca8bcfb0..0000000000 --- a/powercontext/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::sender::{ - AdmittedSend, NotSentReason, RawResponse, SendIndeterminateReason, SendOutcome, Transport, -}; -use bytes::Bytes; -use std::future::Future; -use std::time::{Duration, Instant}; - -/// 基于 reqwest 的传输实现:裸 HTTP 直连上游,不经任何厂商 SDK。 -/// -/// 结果映射(对齐 RFC 失败语义): -/// - 连接失败/请求构造失败 → 确定性 NotSent(可重试); -/// - 发送后连接丢失、超时、解码中断 → Indeterminate(不自动重发); -/// - 流式接收:逐块读入(计量 TTFT、字节数受 `max_buffer_bytes` 上限), -/// strict 语义不变——完整缓冲后仍需过 before_release 才释放。 -#[derive(Debug, Clone)] -pub struct ReqwestTransport { - client: reqwest::Client, - /// 流式/非流式响应的缓冲字节上限(容量保护)。 - max_buffer_bytes: usize, -} - -impl ReqwestTransport { - pub fn new(timeout: Duration) -> Self { - let client = reqwest::Client::builder() - // 获准目的地必须保持为实际目的地:307/308 会让 reqwest 把已准入的 - // POST body 原样重发到未经 Core 审查的新地址。禁用自动跟随,重定向 - // 响应原样上抛(经 before_release 后透传给调用方),字节绝不自动重发。 - .redirect(reqwest::redirect::Policy::none()) - .timeout(timeout) - .build() - .expect("reqwest client build"); - Self { - client, - max_buffer_bytes: 32 * 1024 * 1024, - } - } - - pub fn with_buffer_limit(mut self, max_buffer_bytes: usize) -> Self { - self.max_buffer_bytes = max_buffer_bytes; - self - } -} - -impl Default for ReqwestTransport { - fn default() -> Self { - Self::new(Duration::from_secs(120)) - } -} - -impl Transport for ReqwestTransport { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a { - Box::pin(async move { - let mut req = self.client.post(&send.target_url); - let mut has_content_type = false; - for (k, v) in &send.headers { - if k.eq_ignore_ascii_case("content-type") { - has_content_type = true; - } - req = req.header(k, v); - } - if !has_content_type { - req = req.header("content-type", "application/json"); - } - let resp = match req.body(send.payload.to_vec()).send().await { - Err(e) => { - // NotSent 仅限于「可证明发生在传输之前」的失败: - // - is_connect():TCP/TLS 握手未完成,body 必然未发出; - // - is_builder():请求构造阶段,早于一切网络动作。 - // 其余(is_request/is_timeout/is_body/is_decode)都无法排除 - // body 已完整送达上游的可能——reqwest 的 is_request() 尤其 - // 涵盖「对端读完全部 body 后关闭/超时」,按未送达重试会 - // 重复计费。一律归 Indeterminate,不重试。 - return if e.is_connect() { - SendOutcome::NotSent(NotSentReason::ConnectRefused) - } else if e.is_builder() { - SendOutcome::NotSent(NotSentReason::RejectedLocally) - } else if e.is_timeout() { - SendOutcome::Indeterminate( - SendIndeterminateReason::TimeoutAwaitingResponse, - ) - } else { - SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) - }; - } - Ok(resp) => resp, - }; - let status = resp.status().as_u16(); - let content_type = resp - .headers() - .get(reqwest::header::CONTENT_TYPE) - .and_then(|v| v.to_str().ok()) - .unwrap_or("application/json") - .to_string(); - - if send.stream { - // 流式接收:逐块累积 + TTFT 计量 + 字节上限。 - let start = Instant::now(); - let mut body: Vec = Vec::with_capacity(16 * 1024); - let mut ttft: Option = None; - let mut stream = resp.bytes_stream(); - loop { - match next_chunk(&mut stream).await { - None => break, - Some(Err(_)) => { - return SendOutcome::Indeterminate( - SendIndeterminateReason::LostAfterHandoff, - ) - } - Some(Ok(chunk)) => { - if ttft.is_none() { - ttft = Some(start.elapsed().as_millis() as u64); - } - if body.len() + chunk.len() > self.max_buffer_bytes { - // 已送达且部分计费:不重发,向上标记不确定。 - return SendOutcome::Indeterminate( - SendIndeterminateReason::BufferLimitExceeded, - ); - } - body.extend_from_slice(&chunk); - } - } - } - let usage = extract_usage(&body); - SendOutcome::Delivered(RawResponse { - status, - body: Bytes::from(body), - content_type, - ttft_ms: ttft, - usage, - }) - } else { - match resp.bytes().await { - Err(_) => { - SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) - } - Ok(body) => { - let usage = extract_usage(&body); - SendOutcome::Delivered(RawResponse { - status, - body, - content_type, - ttft_ms: None, - usage, - }) - } - } - } - }) - } - - fn cancel<'a>(&'a self, _send: &'a AdmittedSend) -> impl Future + Send + 'a { - // 非流式/全量缓冲调用在响应完整返回后已无进行中的上游工作; - // 放弃响应体即断开连接(连接池按目标隔离)。 - std::future::ready(()) - } -} - -fn extract_usage(body: &[u8]) -> Option { - serde_json::from_slice::(body) - .ok() - .and_then(|v| v.get("usage").cloned()) -} - -/// 不引入 futures-util 依赖的 next():用标准库 poll_fn 轮询 Stream。 -async fn next_chunk(stream: &mut S) -> Option> -where - S: futures_core::Stream> + Unpin, -{ - use std::pin::Pin; - std::future::poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)) - .await - .map(|r| r.map_err(|e| e.to_string())) -} diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/retry.rs b/powercontext/gateway/crates/pc-gateway-transport/src/retry.rs deleted file mode 100644 index 147ac7d77d..0000000000 --- a/powercontext/gateway/crates/pc-gateway-transport/src/retry.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{AdmittedSend, SendOutcome, Transport}; -use pc_gateway_evidence::EvidenceSink; -use std::num::NonZeroU32; - -/// 有界重试:唯一所有者、有效准入、有界次数。 -/// 只重试确定性 `NotSent`;`Indeterminate` 一律上抛,绝不自动付费重发。 -pub struct BoundedRetry { - transport: T, - max_attempts: NonZeroU32, -} - -/// 重试的结果:`Done` 携带原始 `SendOutcome`; -/// `AllNotSent` 表示全部尝试都确定性未送达。 -#[derive(Debug)] -pub enum RetryOutcome { - Done(SendOutcome), - AllNotSent { attempts: u32 }, -} - -impl BoundedRetry { - pub fn new(transport: T, max_attempts: NonZeroU32) -> Self { - Self { - transport, - max_attempts, - } - } - - pub fn transport(&self) -> &T { - &self.transport - } - - pub async fn send_with_retry( - &self, - send: &AdmittedSend, - evidence: &dyn EvidenceSink, - ) -> RetryOutcome { - let mut attempt: u32 = 0; - loop { - attempt += 1; - evidence.record_attempt(attempt); - match self.transport.send(send.clone()).await { - // 可能已送达:立即上抛,不做任何自动重发。 - outcome @ SendOutcome::Indeterminate(_) - | outcome @ SendOutcome::Delivered(_) => return RetryOutcome::Done(outcome), - SendOutcome::NotSent(reason) => { - if attempt >= self.max_attempts.get() { - evidence.record_not_sent(attempt, &reason.to_string()); - return RetryOutcome::AllNotSent { attempts: attempt }; - } - // 确定性未送达:唯一所有者继续重试。 - } - } - } - } -} diff --git a/powercontext/gateway/crates/pc-gateway-transport/src/sender.rs b/powercontext/gateway/crates/pc-gateway-transport/src/sender.rs deleted file mode 100644 index 3b0bf792cf..0000000000 --- a/powercontext/gateway/crates/pc-gateway-transport/src/sender.rs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use bytes::Bytes; -use std::future::Future; - -/// 一次已获准的发送。 -#[derive(Debug, Clone)] -pub struct AdmittedSend { - /// before_send allow 返回的不透明绑定字符串;必须原样用于 before_release。 - pub binding: String, - /// 最终获准字节(渲染产物,binding 绑定的就是这些字节)。 - pub payload: Bytes, - /// 获准目标 URL;不得静默重映射。 - pub target_url: String, - /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 - pub headers: Vec<(String, String)>, - /// 上游流式(SSE)接收:逐块读入并计量,strict 语义不变。 - pub stream: bool, -} - -/// 原始响应 + 传输结果,交给 output/check 后才允许释放。 -#[derive(Debug)] -pub struct RawResponse { - pub status: u16, - pub body: Bytes, - /// 响应的 Content-Type(SSE 为 text/event-stream),释放时原样使用。 - pub content_type: String, - /// 上游首字节延迟(毫秒);流式接收时计量,非流式为 None。 - pub ttft_ms: Option, - /// usage 证据(不可用时为 None,标记 unknown,不记零)。 - pub usage: Option, -} - -/// 发送结果:确定性状态优先;不确定即不确定。 -#[derive(Debug)] -pub enum SendOutcome { - /// 成功取得完整原始响应(尚未过 output/check,不得释放)。 - Delivered(RawResponse), - /// 确定尚未送达:可在有界次数内由唯一所有者重试。 - NotSent(NotSentReason), - /// 可能已到达上游:返回不确定,不自动付费重发,不假设退费。 - Indeterminate(SendIndeterminateReason), -} - -#[derive(Debug, thiserror::Error)] -pub enum NotSentReason { - #[error("connection refused before request sent")] - ConnectRefused, - #[error("request rejected before body accepted")] - RejectedLocally, -} - -#[derive(Debug, thiserror::Error)] -pub enum SendIndeterminateReason { - #[error("connection lost after request handed to transport")] - LostAfterHandoff, - #[error("timeout awaiting response")] - TimeoutAwaitingResponse, - /// 流式接收超过缓冲上限:请求已送达且部分计费,不重发。 - #[error("streaming buffer limit exceeded")] - BufferLimitExceeded, -} - -/// 传输器抽象;实现保证只发送 `AdmittedSend`(类型上无法构造未准入的发送)。 -pub trait Transport: Send + Sync { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a; - - /// 尽力取消上游(strict 检查失败/缓冲超限时必需)。 - /// RPITIT 声明以固化 Send 约束(trait 是公开 API)。 - fn cancel<'a>(&'a self, send: &'a AdmittedSend) -> impl Future + Send + 'a; -} diff --git a/powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs b/powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs deleted file mode 100644 index bb1c53bd00..0000000000 --- a/powercontext/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 回归测试(PR #2307 review P1-1): -//! 对端读完整 POST body 后关闭连接 —— reqwest 报 is_request() 类错误。 -//! 断言:body 只被上游收到一次(绝不重复计费发送), -//! 且结果归为 Indeterminate 而非可重试的 NotSent。 - -use pc_gateway_transport::{ - AdmittedSend, ReqwestTransport, SendOutcome, SendIndeterminateReason, -}; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; -use tokio::io::AsyncReadExt; -use tokio::net::TcpListener; - -#[tokio::test] -async fn upstream_closing_after_full_body_is_indeterminate_and_not_resent() { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let bodies = Arc::new(AtomicUsize::new(0)); - let connections = Arc::new(AtomicUsize::new(0)); - - let b = bodies.clone(); - let c = connections.clone(); - tokio::spawn(async move { - // 接受至多 2 条连接:若网关错误地重试,第二条也会收到 body。 - for _ in 0..2 { - let (mut sock, _) = match listener.accept().await { - Ok(x) => x, - Err(_) => return, - }; - c.fetch_add(1, Ordering::SeqCst); - let mut buf = Vec::new(); - let mut chunk = [0u8; 4096]; - // 读到完整请求(头 + Content-Length 声明的 body) - loop { - let n = sock.read(&mut chunk).await.unwrap_or(0); - if n == 0 { - break; - } - buf.extend_from_slice(&chunk[..n]); - if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { - let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); - let len: usize = head - .lines() - .find_map(|l| l.strip_prefix("content-length: ")) - .and_then(|v| v.trim().parse().ok()) - .unwrap_or(0); - if buf.len() >= pos + 4 + len { - break; - } - } - } - // 完整收到一条带 body 的 POST → 计数 - if buf.starts_with(b"POST") { - b.fetch_add(1, Ordering::SeqCst); - } - // 读完即关闭,不回任何响应(review 描述的复现场景) - drop(sock); - } - }); - - let transport = ReqwestTransport::default(); - let send = AdmittedSend { - binding: "b".into(), - payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), - target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), - headers: vec![], - stream: false, - }; - - // 复现 review 场景:BoundedRetry(max_attempts=2)。 - // 旧行为:is_request() 被归为 NotSent → 重试 → 上游收到两次完整 body - // 且最终谎报 AllNotSent{attempts:2}。 - // 新行为:归为 Indeterminate → 立即上抛,不进行第二次发送。 - let retry = pc_gateway_transport::BoundedRetry::new( - transport, - std::num::NonZeroU32::new(2).unwrap(), - ); - let outcome = retry.send_with_retry(&send, &pc_gateway_evidence::NoopEvidenceSink).await; - match outcome { - pc_gateway_transport::RetryOutcome::Done(SendOutcome::Indeterminate( - SendIndeterminateReason::LostAfterHandoff, - )) => {} - other => panic!("expected Done(Indeterminate), got {other:?}"), - } - - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - assert_eq!( - bodies.load(Ordering::SeqCst), - 1, - "上游必须只收到一次 body(修复前是 2 次,重复计费)" - ); -} diff --git a/powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs b/powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs deleted file mode 100644 index 5baf3229dd..0000000000 --- a/powercontext/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! 回归测试(PR #2307 review P1-2): -//! 获准上游返回 307 时,reqwest 默认会把已准入的 POST body 原样重发到 -//! Location 指向的第二个地址(未经 Core 准入)。禁用自动跟随后: -//! 第二地址必须收到零字节;307 响应原样透传(Delivered status=307)。 - -use pc_gateway_transport::{AdmittedSend, ReqwestTransport, SendOutcome, Transport}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::Arc; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::{TcpListener, TcpStream}; - -/// 读一条完整 HTTP 请求(头 + content-length body),返回原始字节。 -async fn read_request(sock: &mut TcpStream) -> Vec { - let mut buf = Vec::new(); - let mut chunk = [0u8; 4096]; - loop { - let n = sock.read(&mut chunk).await.unwrap_or(0); - if n == 0 { - break; - } - buf.extend_from_slice(&chunk[..n]); - if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { - let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); - let len: usize = head - .lines() - .find_map(|l| l.strip_prefix("content-length: ")) - .and_then(|v| v.trim().parse().ok()) - .unwrap_or(0); - if buf.len() >= pos + 4 + len { - break; - } - } - } - buf -} - -#[tokio::test] -async fn redirect_target_receives_nothing_and_307_surfaces() { - // 第二地址(重定向目标):任何到达的字节都记为违规 - let evil = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let evil_port = evil.local_addr().unwrap().port(); - let evil_received = Arc::new(AtomicUsize::new(0)); - let er = evil_received.clone(); - tokio::spawn(async move { - if let Ok((mut sock, _)) = evil.accept().await { - let data = read_request(&mut sock).await; - er.fetch_add(data.len(), Ordering::SeqCst); - let resp = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"; - let _ = sock.write_all(resp).await; - } - }); - - // 第一地址(获准上游):读完整请求后回 307 指向第二地址 - let approved = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let approved_port = approved.local_addr().unwrap().port(); - let served_307 = Arc::new(AtomicBool::new(false)); - let s307 = served_307.clone(); - let evil_addr = format!("127.0.0.1:{evil_port}"); - tokio::spawn(async move { - let (mut sock, _) = approved.accept().await.unwrap(); - let _ = read_request(&mut sock).await; - let resp = format!( - "HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{evil_addr}/steer\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" - ); - sock.write_all(resp.as_bytes()).await.unwrap(); - s307.store(true, Ordering::SeqCst); - }); - - let transport = ReqwestTransport::default(); - let send = AdmittedSend { - binding: "b".into(), - payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), - target_url: format!("http://127.0.0.1:{approved_port}/v1/chat/completions"), - headers: vec![], - stream: false, - }; - let outcome = transport.send(send).await; - - // 307 原样上抛(不跟随、不报错、不重发) - match outcome { - SendOutcome::Delivered(raw) => assert_eq!(raw.status, 307, "307 必须原样透传"), - other => panic!("expected Delivered(307), got {other:?}"), - } - assert!(served_307.load(Ordering::SeqCst), "获准地址已返回 307"); - - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - // 关键断言:重定向目标收到的字节数为零(修复前会收到完整 POST body) - assert_eq!( - evil_received.load(Ordering::SeqCst), - 0, - "重定向目标必须收到零字节(获准目的地=实际目的地)" - ); -} diff --git a/powercontext/gateway/crates/pc-gateway-types/Cargo.toml b/powercontext/gateway/crates/pc-gateway-types/Cargo.toml deleted file mode 100644 index 172530425c..0000000000 --- a/powercontext/gateway/crates/pc-gateway-types/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -[package] -name = "pc-gateway-types" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "PowerContext Gateway: check API DTOs, envelope bindings and shared value types" - -[dependencies] -serde = { workspace = true } -serde_json = { workspace = true } -bytes = { workspace = true } -thiserror = { workspace = true } diff --git a/powercontext/gateway/crates/pc-gateway-types/src/check.rs b/powercontext/gateway/crates/pc-gateway-types/src/check.rs deleted file mode 100644 index b517a3b032..0000000000 --- a/powercontext/gateway/crates/pc-gateway-types/src/check.rs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! PR #2264 定义的 `POST /v1/context/check` 真实契约。 -//! -//! 关键语义(openapi/powercontext.yaml 原文): -//! - HTTP success alone is not approval——只有完整覆盖的 allow 才许可对应阶段; -//! - 执行器必须在 deadline(valid_until / limits.send_seconds)前 -//! 发送/释放**恰好获批的字节**; -//! - binding 是不透明字符串,绑定 phase、身份、目标、策略与精确载荷; -//! - correlate_until 只是关联窗口,绝不许可新的发送。 - -use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; - -pub const MODEL_JSON_PAYLOAD_SCHEMA: &str = "powercontext.model-json-payload.v1"; -pub const CONTEXT_CHECK_SCHEMA: &str = "powercontext.context-check.v1"; -pub const CONTEXT_CHECK_COMPLETION: &str = "complete"; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum CheckPhase { - BeforeSend, - BeforeRelease, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum CheckDecision { - Allow, - Block, - Withhold, -} - -/// 完整载荷信封:仅内容与协议头(凭据、传输覆盖头被禁止),body 为完整原始 JSON 文本。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ModelJsonPayload { - pub schema: String, - pub headers: BTreeMap, - pub body: String, -} - -impl ModelJsonPayload { - pub fn new(headers: BTreeMap, body: String) -> Self { - Self { - schema: MODEL_JSON_PAYLOAD_SCHEMA.into(), - headers, - body, - } - } -} - -/// prepare 复用信封的定位(binding + 文本位置;位置语义归 Core)。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PreparedContextLocation { - pub binding: String, - pub location: ModelJsonTextLocation, -} - -/// 线格式 JSON 指针 + 解码后 UTF-8 文本的半开字节区间。 -/// 指针形如 /messages/{i}/content 或 /messages/{i}/content/{j}/text, -/// 必须指向 user 消息(PC 的 _message_text 强制校验)。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ModelJsonTextLocation { - pub schema: String, - pub pointer: String, - pub start_byte: u64, - pub end_byte: u64, -} - -pub const MODEL_JSON_TEXT_LOCATION_SCHEMA: &str = "powercontext.model-json-text-location.v1"; - -/// `check_context` 请求:按 phase 二选一(内部标签即 phase 字段)。 -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "phase", rename_all = "snake_case")] -pub enum ContextCheckRequest { - BeforeSend { - scope_id: String, - target_profile: String, - payload: ModelJsonPayload, - /// 线格式必填:无复用块时也必须显式携带空数组。 - prepared_contexts: Vec, - }, - BeforeRelease { - scope_id: String, - target_profile: String, - /// 对应 before_send allow 返回的 binding。 - request_binding: String, - payload: ModelJsonPayload, - completion: String, - }, -} - -/// `check_context` 响应。两阶段共用 allow/block/withhold: -/// before_release 的 allow 即放行决定,block 即拒绝释放。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ContextCheckResult { - pub schema: String, - pub phase: CheckPhase, - pub decision: CheckDecision, - /// 无正文原因类别。 - pub reason_codes: Vec, - pub coverage: ContextCheckCoverage, - pub policy_version: String, - /// RFC3339 时间;发送/释放必须在此之前完成。 - pub valid_until: String, - /// 仅 before_send allow 有;绝不许可新发送。 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub correlate_until: Option, - /// 仅 allow 有:不透明绑定字符串。 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub binding: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ContextCheckCoverage { - pub profile: String, - pub complete: bool, -} - -/// ContextProtectionCapabilities(能力发现;enforcing 是动态降级的依据)。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ContextProtectionCapabilities { - pub check_versions: Vec, - pub payload_versions: Vec, - pub reuse_versions: Vec, - pub reuse_families: Vec, - pub enforcing: bool, - pub limits: ContextProtectionLimits, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ContextProtectionLimits { - pub payload_bytes: u64, - pub binding_bytes: u64, - pub prepared_contexts: u64, - pub dependencies: u64, - pub send_seconds: u64, - pub correlate_seconds: u64, -} diff --git a/powercontext/gateway/crates/pc-gateway-types/src/lib.rs b/powercontext/gateway/crates/pc-gateway-types/src/lib.rs deleted file mode 100644 index 5865fa1c38..0000000000 --- a/powercontext/gateway/crates/pc-gateway-types/src/lib.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! PR #2264 契约值类型。 -//! -//! 网关无策略:这里的类型只承载 Core 的输入/输出, -//! 与 openapi/powercontext.yaml 对齐。 - -mod check; -mod prepare; - -pub use check::*; -pub use prepare::*; diff --git a/powercontext/gateway/crates/pc-gateway-types/src/prepare.rs b/powercontext/gateway/crates/pc-gateway-types/src/prepare.rs deleted file mode 100644 index 88702dc2a2..0000000000 --- a/powercontext/gateway/crates/pc-gateway-types/src/prepare.rs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2026 OceanBase. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! prepare 契约(PR #2264),字段形状对照真实响应校准。 - -use serde::{Deserialize, Serialize}; - -/// 注入块的标准包裹标记(与 PC 的 `_MARKERS` 对齐): -/// check 会扫描载荷中所有字符串,含标记的字节必须被 prepared_contexts 区间覆盖。 -pub const PREPARED_CONTEXT_MARKER_BEGIN: &str = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"; -pub const PREPARED_CONTEXT_MARKER_END: &str = "END_POWERCONTEXT_PREPARED_CONTEXT_V1"; - -pub const PREPARED_CONTEXT_SCHEMA: &str = "powercontext.prepared-context.v1"; -pub const PREPARED_CONTEXT_WITH_REUSE_SCHEMA: &str = "powercontext.prepared-context-with-reuse.v1"; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PrepareContextRequest { - pub scope_id: String, - pub query: String, - #[serde(default = "default_max_bytes")] - pub max_bytes: u32, - #[serde(default)] - pub include_reuse: bool, -} - -fn default_max_bytes() -> u32 { - 8192 -} - -/// prepare 响应:普通 PreparedContext 或带复用信封的 WithReuse(按 schema 判别)。 -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum PrepareContextResult { - WithReuse { - schema: String, - context: PreparedContext, - reuse: ContextReuse, - }, - Plain(PreparedContext), -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PreparedContext { - pub schema: String, - /// ready 时为内容文本;empty 时为 None。 - pub status: String, - pub content: Option, - pub content_bytes: u64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ContextReuse { - pub schema: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub constraints: Option, - /// RFC3339。 - pub expires_at: String, - pub binding: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ReuseConstraints { - #[serde(default)] - pub preserve: Vec, - #[serde(default)] - pub refresh_on: Vec, -} - -impl PrepareContextResult { - pub fn content(&self) -> Option<&str> { - match self { - PrepareContextResult::WithReuse { context, .. } => context.content.as_deref(), - PrepareContextResult::Plain(c) => c.content.as_deref(), - } - } - - pub fn binding(&self) -> Option<&str> { - match self { - PrepareContextResult::WithReuse { reuse, .. } => Some(&reuse.binding), - PrepareContextResult::Plain(_) => None, - } - } -} - -/// 标准注入块:与 PC 的 `_MARKERS`/摘要校验对齐。 -/// check 会核验区间内字节与 binding 签发内容一致,不得增删一字节。 -pub fn wrap_prepared_block(content: &str) -> String { - format!("{PREPARED_CONTEXT_MARKER_BEGIN}\n{content}\n{PREPARED_CONTEXT_MARKER_END}") -} - -/// `POST /v1/sources/content`(capture_content_source): -/// 同步持久入库(Source journal),提取由 PC 后台异步完成。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CaptureContentSourceRequest { - pub scope_id: String, - /// 调用方指定的稳定 ID(幂等键):用 release binding 摘要生成。 - pub source_id: String, - /// 原始整合内容(≤200000 字符)。仅沉淀过检放行的内容。 - pub content: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} From 26d944e326badf26b3c80ba23fd1ca5ed066f298 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 20:51:31 +0800 Subject: [PATCH 14/37] ci(gateway): build, lint, and test the Rust workspace Adds .github/workflows/gateway.yml (fmt --check, clippy -D warnings, cargo test --locked; ubuntu, no matrix, path-triggered on gateway/**) following the desktop.yml pattern with a pinned 1.95.0 toolchain and Swatinem/rust-cache, and registers a gateway suite in .github/ci-paths.toml so changes/detect selects it. Cargo.lock is now committed (--locked builds) and the tree is rustfmt-formatted. Note: ci-paths.toml was reworked by #2285 on master; this additive suite entry may need a small rebase once this branch rebases onto current master. Signed-off-by: ztelur --- .github/ci-paths.toml | 2 + .github/workflows/gateway.yml | 38 + gateway/.gitignore | 1 - gateway/Cargo.lock | 1704 +++++++++++++++++ gateway/crates/pc-gateway-app/src/ingress.rs | 30 +- gateway/crates/pc-gateway-app/src/link.rs | 9 +- gateway/crates/pc-gateway-app/src/main.rs | 12 +- .../pc-gateway-app/src/middleware/mod.rs | 7 +- .../src/middleware/request_id.rs | 34 +- .../src/middleware/resource_limits.rs | 76 +- gateway/crates/pc-gateway-app/src/proxy.rs | 25 +- .../crates/pc-gateway-core/src/executor.rs | 23 +- .../crates/pc-gateway-core/src/gate_client.rs | 4 +- .../pc-gateway-core/src/http_gate_client.rs | 5 +- .../pc-gateway-core/src/uds_gate_client.rs | 34 +- .../tests/executor_semantics.rs | 196 +- .../tests/live_context_check.rs | 71 +- .../crates/pc-gateway-core/tests/uds_pool.rs | 32 +- gateway/crates/pc-gateway-evidence/src/lib.rs | 5 +- .../crates/pc-gateway-protocol/src/render.rs | 21 +- .../tests/openai_renderer.rs | 14 +- .../tests/openai_responses_renderer.rs | 28 +- .../src/reqwest_transport.rs | 9 +- .../crates/pc-gateway-transport/src/retry.rs | 5 +- .../crates/pc-gateway-transport/src/sender.rs | 5 +- .../tests/no_duplicate_send.rs | 14 +- 26 files changed, 2149 insertions(+), 255 deletions(-) create mode 100644 .github/workflows/gateway.yml create mode 100644 gateway/Cargo.lock diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index 1127e2d91e..389f7f28ce 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -16,6 +16,8 @@ ignore = [ ] [suites] +# Rust PowerContext Gateway workspace: build, clippy, and tests via .github/workflows/gateway.yml +gateway = ["gateway/**", ".github/workflows/gateway.yml"] tests = [ "tests/**", "integrations/**", "examples/**", "scripts/generate_js_operations.py", "scripts/sync_dsh_plugin_tree.py", "scripts/generate_integration_manifest_docs.py", diff --git a/.github/workflows/gateway.yml b/.github/workflows/gateway.yml new file mode 100644 index 0000000000..f8e14ea3cc --- /dev/null +++ b/.github/workflows/gateway.yml @@ -0,0 +1,38 @@ +name: Gateway + +on: + pull_request: + paths: ['gateway/**', '.github/workflows/gateway.yml'] + push: + branches: [master] + paths: ['gateway/**', '.github/workflows/gateway.yml'] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: gateway-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - name: Install pinned Rust toolchain + run: rustup toolchain install 1.95.0-x86_64-unknown-linux-gnu --profile minimal --component rustfmt --component clippy + - name: Cache Rust dependencies and compilation + uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + workspaces: gateway -> target + cache-bin: false + - name: Format check + run: cargo fmt --manifest-path gateway/Cargo.toml --all --check + - name: Clippy + run: cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings + - name: Tests + run: cargo test --locked --manifest-path gateway/Cargo.toml --workspace diff --git a/gateway/.gitignore b/gateway/.gitignore index 5df1ae4131..e08c79410a 100644 --- a/gateway/.gitignore +++ b/gateway/.gitignore @@ -1,3 +1,2 @@ target/ -Cargo.lock .DS_Store diff --git a/gateway/Cargo.lock b/gateway/Cargo.lock new file mode 100644 index 0000000000..b9f9ca75ab --- /dev/null +++ b/gateway/Cargo.lock @@ -0,0 +1,1704 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pc-gateway-app" +version = "0.1.0" +dependencies = [ + "axum", + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "pc-gateway-core", + "pc-gateway-evidence", + "pc-gateway-protocol", + "pc-gateway-transport", + "pc-gateway-types", + "reqwest", + "serde", + "serde_json", + "tokio", + "tower", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "pc-gateway-core" +version = "0.1.0" +dependencies = [ + "bytes", + "pc-gateway-evidence", + "pc-gateway-protocol", + "pc-gateway-transport", + "pc-gateway-types", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "pc-gateway-embedded" +version = "0.1.0" +dependencies = [ + "pc-gateway-core", + "pc-gateway-types", +] + +[[package]] +name = "pc-gateway-evidence" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "pc-gateway-protocol" +version = "0.1.0" +dependencies = [ + "bytes", + "pc-gateway-types", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "pc-gateway-transport" +version = "0.1.0" +dependencies = [ + "bytes", + "futures-core", + "pc-gateway-evidence", + "pc-gateway-types", + "reqwest", + "serde_json", + "thiserror", + "tokio", +] + +[[package]] +name = "pc-gateway-types" +version = "0.1.0" +dependencies = [ + "bytes", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 4b406e5f38..7e1dc13992 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -124,7 +124,7 @@ async fn ingress_common( status, Json(serde_json::json!({ "error": code, "detail": e.to_string() })), ) - .into_response() + .into_response(); } }; let canonical = match format { @@ -191,13 +191,15 @@ async fn ingress_common( Format::Responses => &state.upstream_responses_api_key, }), degrade_policy: state.degrade, - inject_context: state.inject_context - && matches!(format, Format::Chat), + inject_context: state.inject_context && matches!(format, Format::Chat), sediment: state.sediment, prepared_contexts: Vec::new(), }; - let outcome = state.executor.run(call, &renderer, state.evidence.as_ref()).await; + let outcome = state + .executor + .run(call, &renderer, state.evidence.as_ref()) + .await; respond(outcome) } @@ -302,7 +304,12 @@ fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result Response { match outcome { - ManagedOutcome::Released { status, content_type, body, .. } => { + ManagedOutcome::Released { + status, + content_type, + body, + .. + } => { // 上游状态码与 Content-Type 原样透传(错误不伪装 200)。 let code = StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY); ( @@ -312,10 +319,12 @@ fn respond(outcome: ManagedOutcome) -> Response { ) .into_response() } - ManagedOutcome::Degraded { status, content_type, body } => match Response::builder() - .status( - StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY), - ) + ManagedOutcome::Degraded { + status, + content_type, + body, + } => match Response::builder() + .status(StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY)) .header(header::CONTENT_TYPE, content_type.as_str()) .header("x-pc-degraded", "passthrough_without_memory") .body(axum::body::Body::from(body.to_vec())) @@ -389,7 +398,8 @@ mod tests { #[test] fn chat_ingress_null_content_without_tool_calls_also_preserved() { - let body = r#"{"model":"m","messages":[{"role":"assistant","content":null}],"max_tokens":8}"#; + let body = + r#"{"model":"m","messages":[{"role":"assistant","content":null}],"max_tokens":8}"#; let chat: OpenAiChatRequest = serde_json::from_str(body).unwrap(); let canonical = to_canonical_chat(chat).unwrap(); assert!(canonical.messages[0].content_null); diff --git a/gateway/crates/pc-gateway-app/src/link.rs b/gateway/crates/pc-gateway-app/src/link.rs index 7968f04504..b7cc2db547 100644 --- a/gateway/crates/pc-gateway-app/src/link.rs +++ b/gateway/crates/pc-gateway-app/src/link.rs @@ -31,8 +31,8 @@ impl CoreLink { tracing::info!(%sock, "core link: UDS (combined deployment)"); Self::Uds(UdsGateClient::new(sock)) } else { - let base = - std::env::var("PC_GATEWAY_CORE_BASE").unwrap_or_else(|_| "http://127.0.0.1:8000".into()); + let base = std::env::var("PC_GATEWAY_CORE_BASE") + .unwrap_or_else(|_| "http://127.0.0.1:8000".into()); tracing::info!(%base, "core link: TCP (standalone deployment)"); Self::Http(HttpGateClient::new(base)) } @@ -40,10 +40,7 @@ impl CoreLink { } impl GateClient for CoreLink { - async fn check( - &self, - request: ContextCheckRequest, - ) -> Result { + async fn check(&self, request: ContextCheckRequest) -> Result { match self { CoreLink::Uds(c) => c.check(request).await, CoreLink::Http(c) => c.check(request).await, diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index ec8c9b7131..702f6ac669 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -67,8 +67,7 @@ pub struct AppState { async fn main() { tracing_subscriber::fmt() .with_env_filter( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| "info".into()), + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), ) .init(); @@ -113,7 +112,9 @@ async fn main() { upstream_responses_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_RESPONSES") .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) .unwrap_or_default(), - api_key: std::env::var("PC_GATEWAY_API_KEY").ok().filter(|k| !k.is_empty()), + api_key: std::env::var("PC_GATEWAY_API_KEY") + .ok() + .filter(|k| !k.is_empty()), degrade, inject_context: matches!(std::env::var("PC_GATEWAY_INJECTION").as_deref(), Ok("on")), sediment: matches!(std::env::var("PC_GATEWAY_SEDIMENT").as_deref(), Ok("on")), @@ -124,7 +125,10 @@ async fn main() { let router = Router::new() .route("/healthz", get(healthz)) - .route("/gateway/v1/chat/completions", post(ingress::chat_completions)) + .route( + "/gateway/v1/chat/completions", + post(ingress::chat_completions), + ) .route("/gateway/v1/responses", post(ingress::responses)) .fallback(proxy::fallback) .with_state((state, proxy_state)); diff --git a/gateway/crates/pc-gateway-app/src/middleware/mod.rs b/gateway/crates/pc-gateway-app/src/middleware/mod.rs index fd2499faee..62411651fe 100644 --- a/gateway/crates/pc-gateway-app/src/middleware/mod.rs +++ b/gateway/crates/pc-gateway-app/src/middleware/mod.rs @@ -36,7 +36,6 @@ pub use request_id::RequestId; pub mod resource_limits; pub use resource_limits::ResourceLimits; - pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-powercontext-request-id"); /// 一个中间件 = 请求进入时的一段处理 + 调用后续链。 @@ -53,11 +52,13 @@ pub trait GatewayMiddleware: Send + Sync + 'static { ) -> Pin + Send + 'a>>; } - /// 把中间件链挂到 Router 的外层。 /// axum 的 layer 语义:后挂的先执行;这里让 `chain[0]` 成为最外层, /// 与注册顺序直觉一致。 -pub fn apply_chain(mut router: axum::Router, chain: Vec>) -> axum::Router { +pub fn apply_chain( + mut router: axum::Router, + chain: Vec>, +) -> axum::Router { for mw in chain.into_iter().rev() { router = router.layer(axum::middleware::from_fn(move |req, next| { let mw = mw.clone(); diff --git a/gateway/crates/pc-gateway-app/src/middleware/request_id.rs b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs index 3177405aa6..ff4abf83a4 100644 --- a/gateway/crates/pc-gateway-app/src/middleware/request_id.rs +++ b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs @@ -46,23 +46,25 @@ impl GatewayMiddleware for RequestId { next: Next, ) -> Pin + Send + 'a>> { Box::pin(async move { - let id = req - .headers() - .get(&REQUEST_ID_HEADER) - .and_then(|v| v.to_str().ok()) - .filter(|v| !v.is_empty() && v.len() <= 128 && v.chars().all(|c| c.is_ascii_graphic())) - .map(|v| v.to_string()) - .unwrap_or_else(generate); - // 注入扩展 + 当前 span,供后续 handler 与日志关联。 - req.extensions_mut().insert(id.clone()); - tracing::Span::current().record("request_id", &id); - let mut resp = next.run(req).await; - if resp.headers().get(&REQUEST_ID_HEADER).is_none() { - if let Ok(v) = axum::http::HeaderValue::from_str(&id) { - resp.headers_mut().insert(REQUEST_ID_HEADER, v); + let id = req + .headers() + .get(&REQUEST_ID_HEADER) + .and_then(|v| v.to_str().ok()) + .filter(|v| { + !v.is_empty() && v.len() <= 128 && v.chars().all(|c| c.is_ascii_graphic()) + }) + .map(|v| v.to_string()) + .unwrap_or_else(generate); + // 注入扩展 + 当前 span,供后续 handler 与日志关联。 + req.extensions_mut().insert(id.clone()); + tracing::Span::current().record("request_id", &id); + let mut resp = next.run(req).await; + if resp.headers().get(&REQUEST_ID_HEADER).is_none() { + if let Ok(v) = axum::http::HeaderValue::from_str(&id) { + resp.headers_mut().insert(REQUEST_ID_HEADER, v); + } } - } - resp + resp }) } } diff --git a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs index b194e00c49..e4b10113b2 100644 --- a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs +++ b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs @@ -18,9 +18,9 @@ use super::{reject, GatewayMiddleware}; use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response}; -use std::sync::atomic::{AtomicU64, Ordering}; use std::future::Future; use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use tokio::sync::Semaphore; @@ -54,46 +54,50 @@ impl GatewayMiddleware for ResourceLimits { next: Next, ) -> Pin + Send + 'a>> { Box::pin(async move { - // 1) 请求体上限:优先用 Content-Length 预检(零拷贝拒绝)。 - if let Some(len) = req - .headers() - .get(axum::http::header::CONTENT_LENGTH) - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.parse::().ok()) - { - if len > self.max_body_bytes { - self.rejected_body.fetch_add(1, Ordering::Relaxed); - tracing::warn!(bytes = len, limit = self.max_body_bytes, "request body rejected"); - return reject( - StatusCode::PAYLOAD_TOO_LARGE, - "request_body_too_large", - format!("body {len} bytes exceeds limit {}", self.max_body_bytes), - ); - } - } - - // 2) 并发上限:非阻塞获取;占满即拒(不排队——排队会把内存压力换成延迟压力)。 - let is_health = req.uri().path() == "/healthz"; - let permit = if is_health { - None - } else { - match self.max_concurrent.clone().try_acquire_owned() { - Ok(p) => Some(p), - Err(_) => { - self.rejected_concurrency.fetch_add(1, Ordering::Relaxed); - tracing::warn!("concurrency limit reached, rejecting"); + // 1) 请求体上限:优先用 Content-Length 预检(零拷贝拒绝)。 + if let Some(len) = req + .headers() + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + { + if len > self.max_body_bytes { + self.rejected_body.fetch_add(1, Ordering::Relaxed); + tracing::warn!( + bytes = len, + limit = self.max_body_bytes, + "request body rejected" + ); return reject( - StatusCode::SERVICE_UNAVAILABLE, - "concurrency_limit", - "gateway at max concurrent requests", + StatusCode::PAYLOAD_TOO_LARGE, + "request_body_too_large", + format!("body {len} bytes exceeds limit {}", self.max_body_bytes), ); } } - }; - let resp = next.run(req).await; - drop(permit); // 显式归还(作用域结束也会归还,这里表达意图) - resp + // 2) 并发上限:非阻塞获取;占满即拒(不排队——排队会把内存压力换成延迟压力)。 + let is_health = req.uri().path() == "/healthz"; + let permit = if is_health { + None + } else { + match self.max_concurrent.clone().try_acquire_owned() { + Ok(p) => Some(p), + Err(_) => { + self.rejected_concurrency.fetch_add(1, Ordering::Relaxed); + tracing::warn!("concurrency limit reached, rejecting"); + return reject( + StatusCode::SERVICE_UNAVAILABLE, + "concurrency_limit", + "gateway at max concurrent requests", + ); + } + } + }; + + let resp = next.run(req).await; + drop(permit); // 显式归还(作用域结束也会归还,这里表达意图) + resp }) } } diff --git a/gateway/crates/pc-gateway-app/src/proxy.rs b/gateway/crates/pc-gateway-app/src/proxy.rs index ad098870a1..39a1c0a3aa 100644 --- a/gateway/crates/pc-gateway-app/src/proxy.rs +++ b/gateway/crates/pc-gateway-app/src/proxy.rs @@ -15,11 +15,13 @@ //! 端口接管代理:非 `/gateway/*` 的流量原样转发到 Python 的 UDS。 //! 原 Core/MCP 路由由此透传;流式(SSE/分块)由 hyper 客户端透传保证。 -use crate::AppState;use axum::body::Body; +use crate::AppState; +use axum::body::Body; use axum::extract::{Request, State}; use axum::http::{HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; -use hyper::Uri as HyperUri;use hyper_util::client::legacy::Client; +use hyper::Uri as HyperUri; +use hyper_util::client::legacy::Client; use hyper_util::rt::{TokioExecutor, TokioIo}; use std::future::Future; use std::path::PathBuf; @@ -43,8 +45,9 @@ impl ProxyState { pub fn from_env() -> Self { match std::env::var("PC_GATEWAY_CORE_UDS") { Ok(sock) => { - let client = Client::builder(TokioExecutor::new()) - .build(UnixConnector { socket: PathBuf::from(&sock) }); + let client = Client::builder(TokioExecutor::new()).build(UnixConnector { + socket: PathBuf::from(&sock), + }); tracing::info!(%sock, "proxy: forwarding non-gateway routes to Python UDS"); Self { inner: Some(Arc::new(ProxyInner { @@ -82,11 +85,7 @@ impl tower::Service for UnixConnector { fn call(&mut self, _uri: HyperUri) -> Self::Future { let path = self.socket.clone(); - Box::pin(async move { - UnixStream::connect(path) - .await - .map(TokioIo::new) - }) + Box::pin(async move { UnixStream::connect(path).await.map(TokioIo::new) }) } } @@ -145,11 +144,9 @@ pub async fn fallback(State((_, proxy)): State, req: Request) -> Re if let Some(h) = response.headers_mut() { *h = rparts.headers; } - response - .body(Body::new(rbody)) - .unwrap_or_else(|e| { - (StatusCode::BAD_GATEWAY, format!("proxy build: {e}")).into_response() - }) + response.body(Body::new(rbody)).unwrap_or_else(|e| { + (StatusCode::BAD_GATEWAY, format!("proxy build: {e}")).into_response() + }) } Err(e) => ( StatusCode::BAD_GATEWAY, diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 78ac88f4fb..0678ce7b2c 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -18,7 +18,7 @@ use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; use pc_gateway_transport::{AdmittedSend, BoundedRetry, RetryOutcome, SendOutcome, Transport}; use pc_gateway_types::{ CaptureContentSourceRequest, CheckDecision, ContextCheckRequest, ContextCheckResult, - ModelJsonPayload, ModelJsonTextLocation, PreparedContextLocation, PrepareContextRequest, + ModelJsonPayload, ModelJsonTextLocation, PrepareContextRequest, PreparedContextLocation, }; use std::collections::BTreeMap; use std::num::NonZeroU32; @@ -145,12 +145,11 @@ where // #2199 语义:降级仅适用于 Core「不可用」。Malformed 表示 Core 可达但 // 响应异常(版本错乱/被篡改/代理污染)——恰恰最不该绕过检查,一律暂停。 return match (e, call.degrade_policy) { - ( - GateError::GateUnavailable(_), - DegradePolicy::PassthroughWithoutMemory, - ) => self.degraded_send(&call, payload.bytes, evidence).await, + (GateError::GateUnavailable(_), DegradePolicy::PassthroughWithoutMemory) => { + self.degraded_send(&call, payload.bytes, evidence).await + } (e, _) => ManagedOutcome::GatePaused(classify_gate_error(e)), - } + }; } Ok(result) => match result.decision { CheckDecision::Allow => unwrap_binding(result), @@ -227,7 +226,9 @@ where "assistant": release_body.clone(), "model": call.request.model, }); - let digest = result.binding.as_deref() + let digest = result + .binding + .as_deref() .map(simple_digest) .unwrap_or_else(|| simple_digest(&release_body)); let capture = CaptureContentSourceRequest { @@ -297,8 +298,12 @@ where // 必须原样注入:check 会校验区间字节摘要 == sha256(content), // 网关任何增删(包括再包裹)都会导致 digest 不匹配被暂缓。 let block = content.to_string(); - let Some(index) = last_user_index(&call.request) else { return }; - let Some(message) = call.request.messages.get_mut(index) else { return }; + let Some(index) = last_user_index(&call.request) else { + return; + }; + let Some(message) = call.request.messages.get_mut(index) else { + return; + }; let original = match message.content.as_slice() { [serde_json::Value::String(s)] => s.clone(), _ => return, diff --git a/gateway/crates/pc-gateway-core/src/gate_client.rs b/gateway/crates/pc-gateway-core/src/gate_client.rs index 144eca6a1b..f86d5f1483 100644 --- a/gateway/crates/pc-gateway-core/src/gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/gate_client.rs @@ -31,9 +31,7 @@ pub trait GateClient: Send + Sync { ) -> impl Future> + Send; /// GET_CAPABILITIES 能力发现:获知支持的模式、必需规则、可降级性等。 - fn capabilities( - &self, - ) -> impl Future> + Send; + fn capabilities(&self) -> impl Future> + Send; /// PREPARE_CONTEXT:检索并装配注入内容(智力全在 Core;网关只放置)。 fn prepare( diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs index 3f4e5ca9d2..ba5a717a00 100644 --- a/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -78,10 +78,7 @@ impl HttpGateClient { } impl GateClient for HttpGateClient { - async fn check( - &self, - request: ContextCheckRequest, - ) -> Result { + async fn check(&self, request: ContextCheckRequest) -> Result { self.post("/v1/context/check", &request).await } diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index 4dede09804..c51b4db0ca 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -113,12 +113,9 @@ impl UdsGateClient { prefer_pool: bool, ) -> Result<(u16, Vec), GateError> { let mut leased = LeasedConnection::new(self.clone()); - let stream = leased - .acquire(prefer_pool) - .await - .map_err(|e| { - GateError::GateUnavailable(format!("uds connect {}: {e}", self.socket.display())) - })?; + let stream = leased.acquire(prefer_pool).await.map_err(|e| { + GateError::GateUnavailable(format!("uds connect {}: {e}", self.socket.display())) + })?; let (mut rd, mut wr) = tokio::io::split(stream); let body = body.unwrap_or(&[]); @@ -218,7 +215,9 @@ async fn read_response(rd: &mut ReadHalf) -> Result<(u16, Vec, b let mut chunked = false; let mut keep_alive = true; // HTTP/1.1 默认 keep-alive for line in lines { - let Some((k, v)) = line.split_once(':') else { continue }; + let Some((k, v)) = line.split_once(':') else { + continue; + }; let k = k.trim().to_ascii_lowercase(); let v = v.trim(); match k.as_str() { @@ -356,14 +355,13 @@ fn find_terminator(buf: &[u8]) -> Option { } impl GateClient for UdsGateClient { - async fn check( - &self, - request: ContextCheckRequest, - ) -> Result { + async fn check(&self, request: ContextCheckRequest) -> Result { let body = serde_json::to_vec(&request).expect("serialize gate request"); let this = self.clone(); { - let (status, body) = this.request("POST", "/v1/context/check", Some(&body)).await?; + let (status, body) = this + .request("POST", "/v1/context/check", Some(&body)) + .await?; if !(200..300).contains(&status) { return Err(GateError::GateUnavailable(format!("gate HTTP {status}"))); } @@ -377,7 +375,9 @@ impl GateClient for UdsGateClient { { let (status, body) = this.request("GET", "/v1/capabilities", None).await?; if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("capabilities HTTP {status}"))); + return Err(GateError::GateUnavailable(format!( + "capabilities HTTP {status}" + ))); } serde_json::from_slice(&body) .map_err(|e| GateError::Malformed(format!("decode capabilities: {e}"))) @@ -391,7 +391,9 @@ impl GateClient for UdsGateClient { let body = serde_json::to_vec(&request).expect("serialize gate request"); let this = self.clone(); { - let (status, body) = this.request("POST", "/v1/context/prepare", Some(&body)).await?; + let (status, body) = this + .request("POST", "/v1/context/prepare", Some(&body)) + .await?; if !(200..300).contains(&status) { return Err(GateError::GateUnavailable(format!("prepare HTTP {status}"))); } @@ -407,7 +409,9 @@ impl GateClient for UdsGateClient { let body = serde_json::to_vec(&request).expect("serialize gate request"); let this = self.clone(); { - let (status, body) = this.request("POST", "/v1/sources/content", Some(&body)).await?; + let (status, body) = this + .request("POST", "/v1/sources/content", Some(&body)) + .await?; if !(200..300).contains(&status) { return Err(GateError::GateUnavailable(format!("capture HTTP {status}"))); } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 5a3da414cd..79653d8fec 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -14,15 +14,18 @@ //! PR #2264 失败语义表的状态机级验证(真实契约形态)。 -use pc_gateway_core::{DegradePolicy, Executor, GateClient, GateError, ManagedCall, ManagedOutcome}; +use pc_gateway_core::{ + DegradePolicy, Executor, GateClient, GateError, ManagedCall, ManagedOutcome, +}; use pc_gateway_evidence::{BufferedEvidenceSink, NoopEvidenceSink}; use pc_gateway_protocol::{ CanonicalMessage, CanonicalRequest, OutputLimits, RenderedPayload, Role, WireRenderer, }; use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; use pc_gateway_types::{ - CheckDecision, CheckPhase, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, - CaptureContentSourceRequest, PrepareContextResult, PreparedContext, PreparedContextLocation, + CaptureContentSourceRequest, CheckDecision, CheckPhase, ContextCheckRequest, + ContextCheckResult, PrepareContextRequest, PrepareContextResult, PreparedContext, + PreparedContextLocation, }; use std::collections::VecDeque; use std::future::Future; @@ -93,7 +96,9 @@ impl GateClient for FakeGate { } => (CheckPhase::BeforeRelease, request_binding.clone()), }; let declared = match &request { - ContextCheckRequest::BeforeSend { prepared_contexts, .. } => prepared_contexts.clone(), + ContextCheckRequest::BeforeSend { + prepared_contexts, .. + } => prepared_contexts.clone(), _ => Vec::new(), }; self.prepared_seen.lock().unwrap().push(declared); @@ -111,13 +116,17 @@ impl GateClient for FakeGate { request: PrepareContextRequest, ) -> impl Future> + Send { self.prepare_queries.lock().unwrap().push(request.query); - let step = self.prepare_result.lock().unwrap().take() - .unwrap_or(Ok(PrepareContextResult::Plain(PreparedContext { - schema: "powercontext.prepared-context.v1".into(), - status: "empty".into(), - content: None, - content_bytes: 0, - }))); + let step = + self.prepare_result + .lock() + .unwrap() + .take() + .unwrap_or(Ok(PrepareContextResult::Plain(PreparedContext { + schema: "powercontext.prepared-context.v1".into(), + status: "empty".into(), + content: None, + content_bytes: 0, + }))); async move { step } } @@ -125,7 +134,10 @@ impl GateClient for FakeGate { &self, request: CaptureContentSourceRequest, ) -> Result { - self.captured.lock().unwrap().push((request.source_id, request.content)); + self.captured + .lock() + .unwrap() + .push((request.source_id, request.content)); Ok(serde_json::json!({"captured": true})) } } @@ -138,16 +150,11 @@ struct FakeTransport { } impl Transport for FakeTransport { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a { + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a { let outcome = self.outcomes.lock().unwrap().pop_front(); self.sends.lock().unwrap().push(send.payload); self.bindings.lock().unwrap().push(send.binding); - async move { - outcome.unwrap_or_else(|| panic!("transport script exhausted")) - } + async move { outcome.unwrap_or_else(|| panic!("transport script exhausted")) } } async fn cancel(&self, _send: &AdmittedSend) { @@ -191,9 +198,9 @@ fn call(degrade: DegradePolicy) -> ManagedCall { messages: vec![CanonicalMessage { role: Role::User, content: vec![serde_json::json!("hello")], - content_null: false, - tool_calls: None, - tool_call_id: None, + content_null: false, + tool_calls: None, + tool_call_id: None, }], tools: vec![], instructions: None, @@ -230,10 +237,7 @@ impl WireRenderer for RendererRef { #[derive(Clone)] struct TransportRef(Arc); impl Transport for TransportRef { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a { + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a { Transport::send(&*self.0, send) } async fn cancel(&self, send: &AdmittedSend) { @@ -250,9 +254,7 @@ impl GateClient for FakeGateRef { ) -> impl Future> + Send { GateClient::check(&*self.0, request) } - fn capabilities( - &self, - ) -> impl Future> + Send { + fn capabilities(&self) -> impl Future> + Send { GateClient::capabilities(&*self.0) } @@ -281,7 +283,9 @@ fn harness( Arc, Arc, ) { - let renderer = Arc::new(RecordingRenderer { renders: Mutex::new(0) }); + let renderer = Arc::new(RecordingRenderer { + renders: Mutex::new(0), + }); let transport = Arc::new(FakeTransport { outcomes: Mutex::new(transport_outcomes.into()), sends: Mutex::new(Vec::new()), @@ -317,10 +321,19 @@ async fn allow_send_allow_release() { 2, ); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; match outcome { - ManagedOutcome::Released { binding, status, body, .. } => { + ManagedOutcome::Released { + binding, + status, + body, + .. + } => { assert_eq!(binding.as_deref(), Some("binding-1")); assert_eq!(status, 200); let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); @@ -346,7 +359,11 @@ async fn before_send_block_never_sends() { 2, ); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; match outcome { ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), @@ -367,7 +384,11 @@ async fn withhold_is_terminal_in_pr2264_contract() { 2, ); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; assert!(matches!(outcome, ManagedOutcome::Withheld { .. })); assert_eq!(*renderer.renders.lock().unwrap(), 1); @@ -383,7 +404,11 @@ async fn gate_unavailable_pauses_never_allow() { 2, ); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; assert!(matches!(outcome, ManagedOutcome::GatePaused(_))); assert_eq!(transport.sends.lock().unwrap().len(), 0); @@ -434,7 +459,11 @@ async fn block_does_not_degrade() { #[tokio::test] async fn deterministic_not_sent_retries_bounded() { let (executor, renderer, _transport, _g) = harness( - vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], vec![ SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), @@ -443,7 +472,11 @@ async fn deterministic_not_sent_retries_bounded() { ); let evidence = BufferedEvidenceSink::new(); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &evidence) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &evidence, + ) .await; assert!(matches!(outcome, ManagedOutcome::NotSent { attempts: 2 })); assert_eq!(evidence.attempts(), vec![1, 2]); @@ -452,14 +485,22 @@ async fn deterministic_not_sent_retries_bounded() { #[tokio::test] async fn indeterminate_never_resends() { let (executor, renderer, transport, _g) = harness( - vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], vec![SendOutcome::Indeterminate( pc_gateway_transport::SendIndeterminateReason::TimeoutAwaitingResponse, )], 3, ); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; assert!(matches!(outcome, ManagedOutcome::SendIndeterminate)); assert_eq!(transport.sends.lock().unwrap().len(), 1); @@ -480,7 +521,11 @@ async fn before_release_block_blocks_and_cancels() { 2, ); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; match outcome { ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), @@ -500,7 +545,11 @@ async fn credentials_never_enter_check_payload() { 2, ); executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; let seen = gate.seen.lock().unwrap().clone(); let (_, before_send_payload) = &seen[0]; @@ -545,7 +594,9 @@ async fn injects_block_and_declares_exact_location() { ))); let mut c = call(DegradePolicy::Pause); c.inject_context = true; - let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; assert!(matches!(outcome, ManagedOutcome::Released { .. })); // 检索词 = 最后一条 user 消息文本 @@ -555,12 +606,15 @@ async fn injects_block_and_declares_exact_location() { let seen = gate.seen.lock().unwrap().clone(); let payload = &seen[0].1; let v: serde_json::Value = serde_json::from_str( - &format!("{{\"inner\":{payload}}}").replace("\"inner\":{", "\"inner\":", ), + &format!("{{\"inner\":{payload}}}").replace("\"inner\":{", "\"inner\":"), ) .unwrap_or(serde_json::Value::Null); let _ = v; let msg_text = extract_user_text(payload); - assert!(msg_text.starts_with("BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"), "块必须在头部: {msg_text}"); + assert!( + msg_text.starts_with("BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"), + "块必须在头部: {msg_text}" + ); assert!(msg_text.contains("网关必须无策略")); assert!(msg_text.ends_with("hello")); @@ -570,7 +624,10 @@ async fn injects_block_and_declares_exact_location() { let loc = &declared[0][0]; assert_eq!(loc.binding, "opaque-binding"); assert_eq!(loc.location.pointer, "/messages/0/content"); - assert_eq!(loc.location.schema, "powercontext.model-json-text-location.v1"); + assert_eq!( + loc.location.schema, + "powercontext.model-json-text-location.v1" + ); assert_eq!(loc.location.start_byte, 0); let block = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1"; assert_eq!(loc.location.end_byte as usize, block.len()); @@ -596,9 +653,14 @@ async fn empty_prepare_injects_nothing() { // prepare 默认返回 empty(FakeGate 默认值) let mut c = call(DegradePolicy::Pause); c.inject_context = true; - executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; let seen = gate.seen.lock().unwrap().clone(); - assert!(!seen[0].1.contains("BEGIN_POWERCONTEXT"), "empty 不得注入标记"); + assert!( + !seen[0].1.contains("BEGIN_POWERCONTEXT"), + "empty 不得注入标记" + ); assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); } @@ -616,8 +678,13 @@ async fn prepare_failure_still_sends_without_injection() { let evidence = BufferedEvidenceSink::new(); let mut c = call(DegradePolicy::Pause); c.inject_context = true; - let outcome = executor.run(c, &RendererRef(renderer.clone()), &evidence).await; - assert!(matches!(outcome, ManagedOutcome::Released { .. }), "prepare 失败不阻塞主链路"); + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &evidence) + .await; + assert!( + matches!(outcome, ManagedOutcome::Released { .. }), + "prepare 失败不阻塞主链路" + ); assert_eq!(transport.sends.lock().unwrap().len(), 1); assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); assert!(evidence.not_sent()[0].1.starts_with("prepare_failed")); @@ -635,11 +702,17 @@ async fn sediment_captures_released_turn_synchronously() { ); let mut c = call(DegradePolicy::Pause); c.sediment = true; - let outcome = executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; assert!(matches!(outcome, ManagedOutcome::Released { .. })); let captured = gate.captured.lock().unwrap().clone(); assert_eq!(captured.len(), 1, "Released 轮次同步沉淀一次"); - assert!(captured[0].0.starts_with("gw-turn-"), "幂等键: {}", captured[0].0); + assert!( + captured[0].0.starts_with("gw-turn-"), + "幂等键: {}", + captured[0].0 + ); let v: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); assert_eq!(v["user"], "hello"); assert_eq!(v["model"], "test-model"); @@ -658,7 +731,9 @@ async fn blocked_turn_never_sediments() { ); let mut c = call(DegradePolicy::Pause); c.sediment = true; - executor.run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink).await; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; assert!(gate.captured.lock().unwrap().is_empty(), "被拦内容不得沉淀"); } @@ -677,7 +752,10 @@ async fn malformed_gate_never_degrades_even_with_passthrough() { &NoopEvidenceSink, ) .await; - assert!(matches!(outcome, ManagedOutcome::GatePaused(_)), "Malformed 必须暂停"); + assert!( + matches!(outcome, ManagedOutcome::GatePaused(_)), + "Malformed 必须暂停" + ); assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); } @@ -692,12 +770,20 @@ async fn non_utf8_response_is_never_released() { usage: None, }); let (executor, renderer, transport, gate) = harness( - vec![Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]))], + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], vec![bad], 2, ); let outcome = executor - .run(call(DegradePolicy::Pause), &RendererRef(renderer.clone()), &NoopEvidenceSink) + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) .await; match outcome { ManagedOutcome::Withheld { reason_codes } => { diff --git a/gateway/crates/pc-gateway-core/tests/live_context_check.rs b/gateway/crates/pc-gateway-core/tests/live_context_check.rs index adc31cb393..dee11aa50a 100644 --- a/gateway/crates/pc-gateway-core/tests/live_context_check.rs +++ b/gateway/crates/pc-gateway-core/tests/live_context_check.rs @@ -20,15 +20,14 @@ //! 不可达时全部跳过(不失败)。 use pc_gateway_core::{GateClient, GateError, HttpGateClient}; -use pc_gateway_types::{ - CheckDecision, ContextCheckRequest, ContextCheckResult, ModelJsonPayload, -}; +use pc_gateway_types::{CheckDecision, ContextCheckRequest, ContextCheckResult, ModelJsonPayload}; use std::collections::BTreeMap; const CORE: &str = "http://127.0.0.1:8000"; const TARGET_PROFILE: &str = "coding"; const MODEL_BODY: &str = r#"{"model":"glm-4-flash","max_tokens":80,"stream":false,"messages":[{"role":"user","content":"hi"}]}"#; -const RESPONSE_BODY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#; +const RESPONSE_BODY: &str = + r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#; fn client() -> HttpGateClient { HttpGateClient::new(CORE) @@ -103,16 +102,26 @@ async fn before_release(scope: &str, binding: &str) -> Result now && valid <= now + 65_000, "发送期限应在 60s 窗口内: valid={valid} now={now}" ); - let Some(correlate) = correlate else { panic!("before_send allow 必须带 correlate_until") }; + let Some(correlate) = correlate else { + panic!("before_send allow 必须带 correlate_until") + }; assert!( correlate > now && correlate <= now + 310_000, "关联期限应在 300s 窗口内" @@ -132,8 +143,12 @@ async fn live_allow_returns_real_binding_and_deadlines() { /// 伪造 binding 做 before_release → Core 必须拒绝(绝不能 allow)。 #[tokio::test] async fn live_forged_binding_is_rejected() { - let Some(_) = require_core().await else { return }; - let Some(scope) = create_scope("forged").await else { panic!("scope creation failed") }; + let Some(_) = require_core().await else { + return; + }; + let Some(scope) = create_scope("forged").await else { + panic!("scope creation failed") + }; let result = before_release(&scope, "pc1.forged-binding-not-issued-by-core").await; match result { Ok(r) => assert_ne!( @@ -143,10 +158,9 @@ async fn live_forged_binding_is_rejected() { r.reason_codes ), // 4xx 拒绝(如绑定校验直接失败)同样视为通过。 - Err(GateError::GateUnavailable(msg)) => assert!( - msg.contains("HTTP 4"), - "期望 4xx 拒绝,得到: {msg}" - ), + Err(GateError::GateUnavailable(msg)) => { + assert!(msg.contains("HTTP 4"), "期望 4xx 拒绝,得到: {msg}") + } Err(other) => panic!("unexpected: {other}"), } } @@ -155,13 +169,21 @@ async fn live_forged_binding_is_rejected() { /// `test_request_binding_cannot_cross_identity_scope_or_current_policy`)。 #[tokio::test] async fn live_binding_cannot_cross_scope() { - let Some(_) = require_core().await else { return }; - let (Some(scope_a), Some(scope_b)) = (create_scope("cross-a").await, create_scope("cross-b").await) + let Some(_) = require_core().await else { + return; + }; + let (Some(scope_a), Some(scope_b)) = + (create_scope("cross-a").await, create_scope("cross-b").await) else { panic!("scope creation failed"); }; let allow = before_send(&scope_a).await.expect("check a"); - assert_eq!(allow.decision, CheckDecision::Allow, "reasons: {:?}", allow.reason_codes); + assert_eq!( + allow.decision, + CheckDecision::Allow, + "reasons: {:?}", + allow.reason_codes + ); let binding = allow.binding.expect("binding"); let cross = before_release(&scope_b, &binding).await; @@ -172,10 +194,9 @@ async fn live_binding_cannot_cross_scope() { "A 的 binding 不得放行 B 的释放: {:?}", r.reason_codes ), - Err(GateError::GateUnavailable(msg)) => assert!( - msg.contains("HTTP 4"), - "期望 4xx 拒绝,得到: {msg}" - ), + Err(GateError::GateUnavailable(msg)) => { + assert!(msg.contains("HTTP 4"), "期望 4xx 拒绝,得到: {msg}") + } Err(other) => panic!("unexpected: {other}"), } } @@ -184,8 +205,12 @@ async fn live_binding_cannot_cross_scope() { /// 真实 OpenAPI 的逐字段对齐。 #[tokio::test] async fn live_missing_prepared_contexts_rejected() { - let Some(_) = require_core().await else { return }; - let Some(scope) = create_scope("dto").await else { panic!("scope creation failed") }; + let Some(_) = require_core().await else { + return; + }; + let Some(scope) = create_scope("dto").await else { + panic!("scope creation failed") + }; let raw = serde_json::json!({ "phase": "before_send", "scope_id": scope, diff --git a/gateway/crates/pc-gateway-core/tests/uds_pool.rs b/gateway/crates/pc-gateway-core/tests/uds_pool.rs index dbfdab277b..8593e4ee04 100644 --- a/gateway/crates/pc-gateway-core/tests/uds_pool.rs +++ b/gateway/crates/pc-gateway-core/tests/uds_pool.rs @@ -16,9 +16,7 @@ //! 覆盖三个场景:content-length 精确、chunked(含 trailer)、content-length 超读截断。 use pc_gateway_core::{GateClient, UdsGateClient}; -use pc_gateway_types::{ - CheckDecision, CheckPhase, ContextCheckRequest, ModelJsonPayload, -}; +use pc_gateway_types::{CheckDecision, CheckPhase, ContextCheckRequest, ModelJsonPayload}; use std::collections::BTreeMap; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -55,10 +53,10 @@ async fn read_request(conn: &mut UnixStream) { } // 简化:Content-Length 为 0 的探测请求到此结束;带 body 的读掉 let head = String::from_utf8_lossy(&buf).to_string(); - if let Some(len) = head - .lines() - .find_map(|l| l.strip_prefix("Content-Length: ").and_then(|v| v.trim().parse::().ok())) - { + if let Some(len) = head.lines().find_map(|l| { + l.strip_prefix("Content-Length: ") + .and_then(|v| v.trim().parse::().ok()) + }) { let mut body = vec![0u8; len]; if len > 0 { conn.read_exact(&mut body).await.unwrap(); @@ -82,8 +80,14 @@ async fn pooled_connection_parses_sequential_responses_correctly() { read_request(&mut conn).await; let body = result_json("allow"); conn.write_all( - format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", body.len()).as_bytes(), - ).await.unwrap(); + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", + body.len() + ) + .as_bytes(), + ) + .await + .unwrap(); conn.write_all(body.as_bytes()).await.unwrap(); // 请求2 → chunked(0-chunk + 终止 CRLF,即 trailer 空行) @@ -103,7 +107,9 @@ async fn pooled_connection_parses_sequential_responses_correctly() { let body3 = result_json("allow"); conn.write_all( format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body3.len()).as_bytes(), - ).await.unwrap(); + ) + .await + .unwrap(); conn.write_all(body3.as_bytes()).await.unwrap(); conn.write_all(b"DIRTY").await.unwrap(); // 保持连接打开一会儿,验证客户端没把脏字节当下一响应 @@ -124,5 +130,9 @@ async fn pooled_connection_parses_sequential_responses_correctly() { server.await.unwrap(); // 三次请求只应建立一条连接(第3次后因脏字节弃用,但那是之后的事) - assert_eq!(CONN_COUNT.load(Ordering::SeqCst), 1, "keep-alive 应复用同一连接"); + assert_eq!( + CONN_COUNT.load(Ordering::SeqCst), + 1, + "keep-alive 应复用同一连接" + ); } diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs index b980a257f7..9f657d16ef 100644 --- a/gateway/crates/pc-gateway-evidence/src/lib.rs +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -107,6 +107,9 @@ impl EvidenceSink for BufferedEvidenceSink { } fn record_call(&self, evidence: &CallEvidence) { - self.calls.lock().expect("evidence lock").push(evidence.clone()); + self.calls + .lock() + .expect("evidence lock") + .push(evidence.clone()); } } diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index 785b912d90..68d625ce90 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -18,7 +18,10 @@ use crate::{CanonicalRequest, RenderedPayload}; #[derive(Debug, thiserror::Error)] pub enum RenderError { #[error("unsupported field for renderer {renderer}: {field}")] - UnsupportedField { renderer: &'static str, field: String }, + UnsupportedField { + renderer: &'static str, + field: String, + }, #[error("cache render plan invalid for renderer {renderer}")] InvalidRenderPlan { renderer: &'static str }, } @@ -64,12 +67,12 @@ impl WireRenderer for OpenAiChatRenderer { } else { match m.content.as_slice() { [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), - other => serde_json::to_value(other).map_err(|e| { - RenderError::UnsupportedField { + other => { + serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { renderer: self.name(), field: e.to_string(), - } - })?, + })? + } } }; let mut message = serde_json::json!({ @@ -223,12 +226,12 @@ impl WireRenderer for OpenAiResponsesRenderer { } else { match msg.content.as_slice() { [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), - other => serde_json::to_value(other).map_err(|e| { - RenderError::UnsupportedField { + other => { + serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { renderer: self.name(), field: e.to_string(), - } - })?, + })? + } } }; input.push(serde_json::json!({ diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index 318519805f..cd417e3307 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -60,7 +60,9 @@ fn merges_only_approved_cache_plan_fields() { #[test] fn non_object_plan_rejected() { let plan = serde_json::json!(["not", "an", "object"]); - let err = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap_err(); + let err = OpenAiChatRenderer + .render(&request(), Some(&plan)) + .unwrap_err(); assert!(matches!( err, pc_gateway_protocol::RenderError::InvalidRenderPlan { .. } @@ -111,7 +113,9 @@ fn tool_call_metadata_round_trip_preserved() { tools: vec![], instructions: None, native_cache_fields: None, - output_limits: OutputLimits { max_output_tokens: 16 }, + output_limits: OutputLimits { + max_output_tokens: 16, + }, stream: false, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); @@ -120,7 +124,11 @@ fn tool_call_metadata_round_trip_preserved() { assert_eq!(msgs.len(), 3); // assistant:content 为 null + tool_calls 完整 - assert!(msgs[1]["content"].is_null(), "content:null 必须保持 null,实际: {}", msgs[1]["content"]); + assert!( + msgs[1]["content"].is_null(), + "content:null 必须保持 null,实际: {}", + msgs[1]["content"] + ); let tc = msgs[1]["tool_calls"].as_array().unwrap(); assert_eq!(tc[0]["id"], "call_1"); assert_eq!(tc[0]["function"]["name"], "get_weather"); diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 68e0af4bcb..8479530604 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -13,8 +13,7 @@ // limitations under the License. use pc_gateway_protocol::{ - CanonicalMessage, CanonicalRequest, OpenAiResponsesRenderer, OutputLimits, Role, - WireRenderer, + CanonicalMessage, CanonicalRequest, OpenAiResponsesRenderer, OutputLimits, Role, WireRenderer, }; fn request() -> CanonicalRequest { @@ -46,7 +45,10 @@ fn renders_responses_wire_format() { assert_eq!(v["max_output_tokens"], 16); assert_eq!(v["stream"], false); assert_eq!(v["input"][0]["role"], "user"); - assert_eq!(v["input"][0]["content"], "hi", "单字符串 content 必须保持 string(review P2:不得变 [\"hi\"])"); + assert_eq!( + v["input"][0]["content"], "hi", + "单字符串 content 必须保持 string(review P2:不得变 [\"hi\"])" + ); assert!(v.get("messages").is_none(), "不得混入 chat 字段"); assert!(v.get("max_tokens").is_none()); } @@ -62,17 +64,17 @@ fn responses_items_pass_through_verbatim() { CanonicalMessage { role: Role::User, content: vec![serde_json::json!("hi")], - content_null: false, - tool_calls: None, - tool_call_id: None, + content_null: false, + tool_calls: None, + tool_call_id: None, }, // 无 role 的顶层 item:原样封进 content,渲染时作为顶层 item 透出 CanonicalMessage { role: Role::Tool, content: vec![fc.clone()], - content_null: false, - tool_calls: None, - tool_call_id: None, + content_null: false, + tool_calls: None, + tool_call_id: None, }, ], tools: vec![], @@ -92,7 +94,9 @@ fn responses_items_pass_through_verbatim() { #[test] fn merges_only_approved_cache_plan_fields() { let plan = serde_json::json!({"prompt_cache_key": "scope-1"}); - let p = OpenAiResponsesRenderer.render(&request(), Some(&plan)).unwrap(); + let p = OpenAiResponsesRenderer + .render(&request(), Some(&plan)) + .unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); assert_eq!(v["prompt_cache_key"], "scope-1"); assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); @@ -116,7 +120,9 @@ fn typed_content_parts_pass_through_as_array() { tools: vec![], instructions: None, native_cache_fields: None, - output_limits: OutputLimits { max_output_tokens: 16 }, + output_limits: OutputLimits { + max_output_tokens: 16, + }, stream: false, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index d1d5312ea8..fb4c299778 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -59,10 +59,7 @@ impl Default for ReqwestTransport { } impl Transport for ReqwestTransport { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a { + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a { Box::pin(async move { let mut req = self.client.post(&send.target_url); let mut has_content_type = false; @@ -89,9 +86,7 @@ impl Transport for ReqwestTransport { } else if e.is_builder() { SendOutcome::NotSent(NotSentReason::RejectedLocally) } else if e.is_timeout() { - SendOutcome::Indeterminate( - SendIndeterminateReason::TimeoutAwaitingResponse, - ) + SendOutcome::Indeterminate(SendIndeterminateReason::TimeoutAwaitingResponse) } else { SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) }; diff --git a/gateway/crates/pc-gateway-transport/src/retry.rs b/gateway/crates/pc-gateway-transport/src/retry.rs index 147ac7d77d..e2ddb91910 100644 --- a/gateway/crates/pc-gateway-transport/src/retry.rs +++ b/gateway/crates/pc-gateway-transport/src/retry.rs @@ -54,8 +54,9 @@ impl BoundedRetry { evidence.record_attempt(attempt); match self.transport.send(send.clone()).await { // 可能已送达:立即上抛,不做任何自动重发。 - outcome @ SendOutcome::Indeterminate(_) - | outcome @ SendOutcome::Delivered(_) => return RetryOutcome::Done(outcome), + outcome @ SendOutcome::Indeterminate(_) | outcome @ SendOutcome::Delivered(_) => { + return RetryOutcome::Done(outcome) + } SendOutcome::NotSent(reason) => { if attempt >= self.max_attempts.get() { evidence.record_not_sent(attempt, &reason.to_string()); diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs index 3b0bf792cf..1b3d562092 100644 --- a/gateway/crates/pc-gateway-transport/src/sender.rs +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -75,10 +75,7 @@ pub enum SendIndeterminateReason { /// 传输器抽象;实现保证只发送 `AdmittedSend`(类型上无法构造未准入的发送)。 pub trait Transport: Send + Sync { - fn send<'a>( - &'a self, - send: AdmittedSend, - ) -> impl Future + Send + 'a; + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a; /// 尽力取消上游(strict 检查失败/缓冲超限时必需)。 /// RPITIT 声明以固化 Send 约束(trait 是公开 API)。 diff --git a/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs index bb1c53bd00..d1a5037fda 100644 --- a/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs +++ b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs @@ -17,9 +17,7 @@ //! 断言:body 只被上游收到一次(绝不重复计费发送), //! 且结果归为 Indeterminate 而非可重试的 NotSent。 -use pc_gateway_transport::{ - AdmittedSend, ReqwestTransport, SendOutcome, SendIndeterminateReason, -}; +use pc_gateway_transport::{AdmittedSend, ReqwestTransport, SendIndeterminateReason, SendOutcome}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use tokio::io::AsyncReadExt; @@ -85,11 +83,11 @@ async fn upstream_closing_after_full_body_is_indeterminate_and_not_resent() { // 旧行为:is_request() 被归为 NotSent → 重试 → 上游收到两次完整 body // 且最终谎报 AllNotSent{attempts:2}。 // 新行为:归为 Indeterminate → 立即上抛,不进行第二次发送。 - let retry = pc_gateway_transport::BoundedRetry::new( - transport, - std::num::NonZeroU32::new(2).unwrap(), - ); - let outcome = retry.send_with_retry(&send, &pc_gateway_evidence::NoopEvidenceSink).await; + let retry = + pc_gateway_transport::BoundedRetry::new(transport, std::num::NonZeroU32::new(2).unwrap()); + let outcome = retry + .send_with_retry(&send, &pc_gateway_evidence::NoopEvidenceSink) + .await; match outcome { pc_gateway_transport::RetryOutcome::Done(SendOutcome::Indeterminate( SendIndeterminateReason::LostAfterHandoff, From ec8711959db3d172146d5eed49f813fff076a753 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sat, 31 Oct 2026 22:02:34 +0800 Subject: [PATCH 15/37] ci(gateway): adopt the post-#2285 ci-paths structure Replaces the pre-#2285 edit with current master's .github/ci-paths.toml as the base, keeping only the additive gateway suite entry in [suites], so the branch merges cleanly against master. Wiring a gateway root job into master.yml's result gate (the desktop-validation pattern) is left as a follow-up to keep this PR's footprint in the heavily-churned master.yml minimal. Signed-off-by: ztelur --- .github/ci-paths.toml | 145 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 136 insertions(+), 9 deletions(-) diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index 389f7f28ce..4cd6715b38 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -1,28 +1,33 @@ -# Shared runtime, dependency, and CI changes can affect every consumer. +# Shared runtime and dependency changes can affect every consumer. # Patterns use Python fnmatch semantics: * also matches path separators. full = [ - "src/**", "openapi/**", "pyproject.toml", "uv.lock", "Makefile", "tox.ini", - ".mise.toml", ".pre-commit-config.yaml", ".github/actions/**", ".github/workflows/**", - ".github/ci-paths.toml", "scripts/ci_changes.py", "tests/test_ci_changes.py", + "Makefile", "tox.ini", + ".mise.toml", ".pre-commit-config.yaml", ".github/actions/setup-python-env/**", + ".github/workflows/ci-changes.yml", ".github/workflows/master.yml", + ".github/ci-paths.toml", "scripts/ci_changes.py", "tests/test_ci_changes.py", "tests/test_ci_pipeline.py", "tests/conftest.py", "tests/**/conftest.py", "tests/fixtures/**", "integrations/capabilities.toml", "integrations/langchain/pyproject.toml", "integrations/langgraph/pyproject.toml", "integrations/opendal/pyproject.toml", ] -# These files still receive the always-running quality and license checks. +# These files still receive the always-running preflight checks. ignore = [ "AGENTS.md", "REVIEW.md", "CONTRIBUTING.md", "GOVERNANCE.md", "LICENSE", "LICENSES/**", ".github/ISSUE_TEMPLATE/**", ".github/pull_request_template.md", ".github/CODEOWNERS", + ".github/dependabot.yml", ".licenserc.yaml", + "scripts/ci_queue_report.py", ] [suites] -# Rust PowerContext Gateway workspace: build, clippy, and tests via .github/workflows/gateway.yml +helm = ["deploy/helm/**", "tests/test_helm*.py", "tests/e2e/helm_*.py"] +# Rust PowerContext Gateway workspace; validation runs via .github/workflows/gateway.yml. gateway = ["gateway/**", ".github/workflows/gateway.yml"] tests = [ "tests/**", "integrations/**", "examples/**", "scripts/generate_js_operations.py", "scripts/sync_dsh_plugin_tree.py", "scripts/generate_integration_manifest_docs.py", "scripts/run_atomic_memory_clean_migration.py", "scripts/scan_e2e_evidence.sh", - "scripts/ci_role_smoke.py", + "scripts/check_atomic_memory_migration_shards.py", + "scripts/ci_role_smoke.py", "scripts/ci_installation_roles.py", # These evaluator suites still live under the root tests/ directory. "evaluation/memory/locomo/**", "evaluation/memory/locomo_plus/**", "evaluation/memory/write_gate/**", ] @@ -34,16 +39,26 @@ database = [ "tests/e2e/*native_code*", "tests/e2e/test_recall_sufficiency_gate.py", "tests/e2e/test_context_text_assembly.py", "tests/e2e/test_scope_search_migration.py", "scripts/run_atomic_memory_clean_migration.py", + ".github/workflows/e2e-harness.yml", ".github/actions/setup-upgrade-oceanbase/**", + "tests/native/test_oceanbase_engine_recovery.py", + "tests/*migration*.py", "scripts/check_atomic_memory_migration_shards.py", ] dify = ["integrations/dify/**", "tests/*dify*"] hermes = ["integrations/hermes/**", "tests/*hermes*"] dsh = ["integrations/dsh/**", "tests/*dsh*", "scripts/generate_js_operations.py", "scripts/sync_dsh_plugin_tree.py"] +cindy = [ + "integrations/cindy/**", "tests/e2e/*cindy*", "scripts/generate_js_operations.py", + "integrations/dsh/plugins/powercontext/src/**", "integrations/dsh/plugins/powercontext/package.json", + "integrations/dsh/plugins/powercontext/pnpm-lock.yaml", "integrations/dsh/plugins/powercontext/pnpm-workspace.yaml", + "integrations/dsh/plugins/powercontext/tsconfig.json", +] pi = ["integrations/pi/**", "tests/*pi_*"] opencode = ["integrations/opencode/**", "tests/*opencode*"] openclaw = ["integrations/openclaw/**", "tests/*openclaw*"] opendal = ["integrations/opendal/**"] website = [ "docs/**", "website/**", "assets/**", "README*.md", "scripts/generate_integration_manifest_docs.py", + "tests/e2e/test_blog_site.py", ] # Root tests assert exact sentences in published docs, so documentation edits must # exercise them without paying for the complete tests matrix. @@ -51,6 +66,7 @@ docs_tests = ["docs/**", "README*.md"] native = ["tests/native/**", "tests/test_service*.py", "tests/test_cursor_secret.py", "tests/test_server.py"] harness = [ "e2e/**", "integrations/bub/**", "scripts/scan_e2e_evidence.sh", "tests/test_e2e_workflow_contract.py", + ".github/workflows/e2e-harness.yml", "tests/e2e/test_atomic_memory_search_authorization_snapshot.py", "tests/e2e/test_atomic_memory_read_snapshot.py", "tests/e2e/test_runtime_server.py", ] @@ -59,12 +75,123 @@ zcode = [ "integrations/zcode/**", "evaluation/zcode_guidance/**", "tests/*zcode*", "integrations/pi/**", "tests/e2e/test_cross_host_work_continuity.py", "tests/e2e/cross_host_work_continuity/**", ] -kimi = ["integrations/kimi-code/**", "tests/*kimi*"] +kimi = ["integrations/kimi-code/**", "tests/*kimi*", ".github/workflows/kimi-code-acceptance.yml"] +upgrade = [ + "scripts/run_atomic_memory_clean_migration.py", "scripts/build_ops_bundle.py", + "release/**", "scripts/upgrade_*.py", "scripts/ci_legacy_upgrade_rejection.py", + "scripts/ci_release_smoke.py", "scripts/ci_ops_bundle_smoke.py", "scripts/capture_release_schema.py", + "tests/release_upgrades/**", "tests/test_upgrade*.py", "tests/test_registered_source_maintenance_cli.py", + "tests/test_managed_*maintenance.py", "tests/e2e/*migration*", "tests/e2e/*managed_startup*", + "tests/test_managed_startup*.py", "tests/builtin/persistence/**", "tests/*migration*.py", + ".github/workflows/upgrade-release.yml", ".github/workflows/release.yml", + ".github/actions/setup-upgrade-oceanbase/**", +] +observability = [ + "tests/*observability*", "tests/*logging*", "tests/*tracing*", "tests/e2e/*worker*", + "tests/e2e/*observability*", "tests/builtin/runtime/*worker*", "tests/builtin/runtime/*model_usage*", +] +packaging = [ + "scripts/build_ops_bundle.py", + "tests/test_installation.py", "tests/test_upgrade_publication.py", "scripts/ci_role_smoke.py", + "scripts/ci_installation_roles.py", "tests/test_ci_installation_roles.py", "release/**", + ".github/workflows/release.yml", ".github/workflows/build-artifacts.yml", + ".github/workflows/build-docker.yml", "docker/**", +] +desktop = [ + "desktop/**", "tests/test_desktop_fixture_qualification.py", "website/assets/**", + ".github/workflows/desktop.yml", +] +managed_resources = [ + "scripts/*managed_resource*", "scripts/build_ops_bundle.py", "scripts/ci_ops_bundle_smoke.py", + "scripts/build_intel_managed_wheel.py", "tests/test_managed_resource_producer.py", "tests/test_ops_resources.py", + ".github/workflows/managed-resource-candidates.yml", +] +candidate_replay = [ + "src/powercontext/builtin/persistence/**", "src/powercontext/builtin/artifacts/**", "pyproject.toml", "uv.lock", + "tests/builtin/persistence/**", "scripts/replay_candidate_migration.py", + ".github/workflows/candidate-schema-replay.yml", ".github/actions/setup-upgrade-oceanbase/**", +] +release_schema = [ + "scripts/capture_release_schema.py", "scripts/upgrade_database_probe.py", "scripts/upgrade_process.py", + "tests/release_upgrades/test_full_server.py", ".github/workflows/capture-release-schema.yml", + ".github/actions/setup-upgrade-oceanbase/**", +] +seekdb_lock = ["scripts/probe_seekdb_migration_lock.py", ".github/workflows/seekdb-lock-probe.yml", ".github/workflows/seekdb-lock-observation.yml"] +skill_guidance = [ + "evaluation/skills/skill-up/**", + "integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/**", + ".github/workflows/skill-guidance.yml", +] # Packaged guidance and its generators are inputs to the native host tests. -[shared] +[shared.guidance] patterns = [ "scripts/integration_guidance*", "scripts/evaluate_integration_guidance.py", "scripts/guidance_templates/**", "tests/test_integration_guidance*", "tests/test_guidance*", "tests/test_setup_rollback.py", ] suites = ["tests", "dify", "hermes", "dsh", "pi", "opencode", "openclaw", "zcode", "kimi"] + +# Shared Python changes still exercise all runtime consumers. Diagnostic source +# capture and lock probes have their own inputs rather than joining every build. +[shared.runtime] +patterns = ["src/**", "openapi/**", "pyproject.toml", "uv.lock"] +suites = [ + "tests", "evaluation", "database", "dify", "hermes", "dsh", "cindy", "pi", "opencode", "openclaw", "opendal", + "website", "native", "harness", "zcode", "kimi", "upgrade", "observability", "packaging", "desktop", + "managed_resources", +] + +[shared.openapi_guidance] +patterns = ["openapi/powercontext.yaml"] +suites = ["skill_guidance"] + +[shared.native] +patterns = [".github/workflows/native-service.yml"] +suites = ["native"] + +[shared.zcode] +patterns = [".github/workflows/zcode-acceptance.yml"] +suites = ["zcode"] + +[shared.node_cache] +patterns = [".github/actions/cache-pnpm/**"] +suites = ["tests", "desktop", "website", "dsh", "cindy", "pi", "opencode", "openclaw"] + +[shared.docs_deploy] +patterns = [".github/workflows/deploy-docs.yml"] +suites = ["website"] + +[shared.release_verify] +patterns = [".github/workflows/release-verify.yml"] +suites = ["upgrade", "packaging"] + +# A selected scope must produce successful root jobs, not silent skips. +# Main's result gate consumes this contract; reusable workflows own their children. +[checks] +helm = ["helm"] +tests = ["tests", "windows-unit-portability"] +evaluation = ["evaluation-tests"] +database = ["oceanbase-engine-recovery", "code-seekdb", "atomic-memory-clean-seekdb", "harness-validation"] +dify = ["dify-tools"] +hermes = ["hermes-skills"] +dsh = ["dsh-package"] +cindy = ["cindy-package"] +pi = ["pi-package"] +opencode = ["opencode-package"] +openclaw = ["openclaw-package"] +opendal = ["opendal-package"] +website = ["check-website", "website-link-validation-windows"] +docs_tests = ["docs-tests"] +native = ["native-service"] +harness = ["harness-validation"] +zcode = ["zcode-acceptance"] +kimi = ["kimi-acceptance"] +upgrade = ["seekdb-managed-startup", "upgrade-acceptance"] +observability = ["worker-observability"] +packaging = ["isolated-installations"] +desktop = ["desktop-validation"] +managed_resources = ["managed-resource-candidates"] +candidate_replay = ["candidate-replay"] +release_schema = ["release-schema"] +seekdb_lock = ["seekdb-lock"] +skill_guidance = ["skill-guidance"] From bde69251d5cadf8643ed7713b495af9d892ae13b Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 09:11:04 +0800 Subject: [PATCH 16/37] fix(gateway): enforce admission validity and safe degradation (P1-3, P1-4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1-3: Degraded sends now use the pristine request snapshot taken before enrich(), so recalled private memory from a successful prepare never reaches the upstream in a degraded (unchecked) send. Degradation eligibility is resolved at startup from capabilities.context_protection.enforcing (fail-closed when unreachable), overriding any environment-variable request. P1-4: The executor now enforces valid_until at every boundary: before each send attempt (expired admission → AdmissionExpired with zero bytes sent), before release including after synchronous capture (expired release verdict → content withheld), and obtains fresh admission for each retry (deterministic NotSent re-enters check so Core revocations are noticed before the next attempt). correlate_until is never used for send or release decisions. Adds zero-dependency RFC3339 parsing with full test coverage. The retry loop moves from BoundedRetry into the executor so that re-admission can happen between attempts; BoundedRetry remains for transport-level use only. Four new probe-reproducing tests: degraded-without-injected-memory, expired-send-verdict, retry-re-admits-revocation-blocks, release-expired-after-capture. cargo clippy --all-targets: zero warnings; 47 tests. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 12 +- gateway/crates/pc-gateway-app/src/link.rs | 1 + gateway/crates/pc-gateway-app/src/main.rs | 32 +- .../crates/pc-gateway-core/src/executor.rs | 279 ++++++++++++------ .../tests/executor_semantics.rs | 121 +++++++- gateway/crates/pc-gateway-types/src/lib.rs | 2 + gateway/crates/pc-gateway-types/src/time.rs | 155 ++++++++++ 7 files changed, 499 insertions(+), 103 deletions(-) create mode 100644 gateway/crates/pc-gateway-types/src/time.rs diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 7e1dc13992..e748bbdc68 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -190,7 +190,12 @@ async fn ingress_common( Format::Chat => &state.upstream_chat_api_key, Format::Responses => &state.upstream_responses_api_key, }), - degrade_policy: state.degrade, + // P1-3:降级资格由启动时 capabilities 查询决定,环境变量只是运维申请。 + degrade_policy: if state.degradation_allowed { + state.degrade + } else { + pc_gateway_core::DegradePolicy::Pause + }, inject_context: state.inject_context && matches!(format, Format::Chat), sediment: state.sediment, prepared_contexts: Vec::new(), @@ -356,6 +361,11 @@ fn respond(outcome: ManagedOutcome) -> Response { Json(serde_json::json!({ "decision": "not_sent", "attempts": attempts })), ) .into_response(), + ManagedOutcome::AdmissionExpired => ( + StatusCode::CONFLICT, + Json(serde_json::json!({ "decision": "admission_expired" })), + ) + .into_response(), ManagedOutcome::GatePaused(msg) => ( StatusCode::SERVICE_UNAVAILABLE, Json(serde_json::json!({ "decision": "gate_paused", "detail": msg })), diff --git a/gateway/crates/pc-gateway-app/src/link.rs b/gateway/crates/pc-gateway-app/src/link.rs index b7cc2db547..7abe2e6197 100644 --- a/gateway/crates/pc-gateway-app/src/link.rs +++ b/gateway/crates/pc-gateway-app/src/link.rs @@ -20,6 +20,7 @@ use pc_gateway_types::{ PrepareContextResult, }; +#[derive(Clone)] pub enum CoreLink { Uds(UdsGateClient), Http(HttpGateClient), diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 702f6ac669..e3f63897b6 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -61,6 +61,8 @@ pub struct AppState { pub default_scope: String, /// Request body byte limit (also enforced when consuming chunked bodies). pub max_body_bytes: usize, + /// 启动时查 capabilities 确定降级资格:enforcing=true 或查询失败 → 不允许。 + pub degradation_allowed: bool, } #[tokio::main] @@ -94,7 +96,7 @@ async fn main() { let state = Arc::new(AppState { executor: Arc::new(Executor::new( - core_link, + core_link.clone(), ReqwestTransport::new(Duration::from_secs(120)), NonZeroU32::new(max_attempts).expect("max_attempts > 0"), )), @@ -121,6 +123,7 @@ async fn main() { default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") .unwrap_or_else(|_| "gateway:default".into()), max_body_bytes, + degradation_allowed: resolve_degradation(core_link.clone()).await, }); let router = Router::new() @@ -161,6 +164,33 @@ async fn shutdown_signal() { tracing::info!("shutting down (draining)"); } +/// P1-3:启动时确定降级资格。 +/// capabilities 返回 enforcing=true → 不允许(Core 说了算)。 +/// 查询失败 → 不允许(fail-closed)。 +async fn resolve_degradation(link: link::CoreLink) -> bool { + use pc_gateway_core::GateClient; + match link.capabilities().await { + Ok(caps) => { + let enforcing = caps + .get("context_protection") + .and_then(|cp| cp.get("enforcing")) + .and_then(|e| e.as_bool()) + .unwrap_or(true); // 缺字段 → fail-closed + let allowed = !enforcing; + tracing::info!( + enforcing, + allowed, + "degradation eligibility from capabilities" + ); + allowed + } + Err(e) => { + tracing::warn!(error = %e, "capabilities unreachable; degradation disabled (fail-closed)"); + false + } + } +} + async fn healthz() -> axum::Json { axum::Json(serde_json::json!({ "status": "ok", "service": "pc-gateway" })) } diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 0678ce7b2c..22192c6894 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -12,20 +12,35 @@ // See the License for the specific language governing permissions and // limitations under the License. +//! 执行器核心:一次托管调用的状态机。 +//! +//! ```text +//! 宿主完整输入 ─► [快照原始请求] ─► enrich ─► 渲染 ─► check(before_send) +//! │ │ +//! │ ┌── allow + binding + valid_until +//! │ ▼ +//! │ [验有效期] ─► 发送 ─► ┌─ Delivered ─► check(before_release) +//! │ │ ├─ NotSent ─► [重准入] ─► 重新发送 +//! │ │ └─ Indeterminate ─► 上抛 +//! │ │ +//! │ 到期→ AdmissionExpired(零发送) +//! │ +//! └── 降级时用此原始请求(不含注入)重新渲染 +//! ``` + use crate::{GateClient, GateError}; use pc_gateway_evidence::EvidenceSink; use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; -use pc_gateway_transport::{AdmittedSend, BoundedRetry, RetryOutcome, SendOutcome, Transport}; +use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; use pc_gateway_types::{ - CaptureContentSourceRequest, CheckDecision, ContextCheckRequest, ContextCheckResult, + parse_rfc3339_ms, CaptureContentSourceRequest, CheckDecision, ContextCheckRequest, ModelJsonPayload, ModelJsonTextLocation, PrepareContextRequest, PreparedContextLocation, }; use std::collections::BTreeMap; use std::num::NonZeroU32; +use std::time::{SystemTime, UNIX_EPOCH}; -/// Gate 不可用时的策略(PR #2199 故障语义): -/// Pause —— 必需强制检查不可用:不发送(默认,安全立场); -/// PassthroughWithoutMemory —— 增强类调用可降级(仅限 capabilities.enforcing=false)。 +/// Gate 不可用时的策略(PR #2199 故障语义)。 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum DegradePolicy { #[default] @@ -33,56 +48,58 @@ pub enum DegradePolicy { PassthroughWithoutMemory, } -/// 宿主交给执行器的完整输入:已授权历史 + 当前请求 + 目标。 +/// 宿主交给执行器的完整输入。 pub struct ManagedCall { pub scope_id: String, pub target_profile: String, pub request: CanonicalRequest, pub target_url: String, - /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 pub headers: Vec<(String, String)>, pub degrade_policy: DegradePolicy, - /// 是否调 prepare 注入上下文(v1 仅 chat 格式;PC 决定内容,网关只放置)。 pub inject_context: bool, - /// 是否在过检后同步沉淀本轮对话(capture_content_source,毫秒级落库)。 pub sediment: bool, - /// 注入块位置声明,随 before_send 送检。 pub prepared_contexts: Vec, } -/// 执行结果:要么是过检放行的内容,要么是显式拒绝/不确定。 -/// 不存在“静默成功”或“伪装成空结果”的路径。 +/// 执行结果。 #[derive(Debug)] pub enum ManagedOutcome { - /// before_release 的 allow:绑定与过检内容一起返回。 Released { binding: Option, status: u16, content_type: String, body: bytes::Bytes, }, - /// Core 明确拒绝(两阶段的 block),携带无正文原因类别。 - Blocked { reason_codes: Vec }, - /// Core 暂缓。PR #2264 的 withhold 不含渲染计划,一律按终态处理。 - Withheld { reason_codes: Vec }, - /// 可能已到达上游;不自动付费重发。 + Blocked { + reason_codes: Vec, + }, + Withheld { + reason_codes: Vec, + }, SendIndeterminate, - /// 全部尝试确定性未送达。 - NotSent { attempts: u32 }, - /// Gate 不可用:暂停,不是失败放行。 + NotSent { + attempts: u32, + }, GatePaused(String), - /// 无记忆直通降级:未经检查发送(仅限未启用强制规则的部署), - /// 响应头/证据必须显式标记,不得伪装成过检结果。 Degraded { status: u16, content_type: String, body: bytes::Bytes, }, + /// 准入已过期(valid_until 超窗):零发送或零释放,可安全重走完整流程。 + AdmissionExpired, } pub struct Executor { gate: G, - retry: BoundedRetry, + transport: T, + max_attempts: NonZeroU32, +} + +/// 单次发送尝试的准入凭证。 +struct Admission { + binding: String, + valid_until_ms: Option, } impl Executor @@ -93,11 +110,11 @@ where pub fn new(gate: G, transport: T, max_attempts: NonZeroU32) -> Self { Self { gate, - retry: BoundedRetry::new(transport, max_attempts), + transport, + max_attempts, } } - /// 一次托管调用。渲染器按请求传入:入口格式即上游格式(同格式进出)。 pub async fn run( &self, call: ManagedCall, @@ -105,11 +122,14 @@ where evidence: &dyn EvidenceSink, ) -> ManagedOutcome { let mut call = call; + // P1-3:enrich 之前快照原始请求。降级路径必须用这份(不含注入内容) + // 重新渲染,否则 prepare 召回的私密记忆会在未经任何检查的情况下外发。 + let pristine_request = call.request.clone(); + if call.inject_context { - // 注入是增强类调用:失败不阻塞主链路(不注入、不声明区间)。 self.enrich(&mut call, evidence).await; } - // 渲染完整最终字节(不含缓存计划:PR #2264 的 withhold 未携带渲染计划)。 + let payload = match renderer.render(&call.request, None) { Ok(p) => p, Err(e) => { @@ -118,8 +138,6 @@ where } } }; - // 送检内容必须与发送字节严格一致:拒绝有损转换(防“检查≠发送”缝隙)。 - // 渲染器输出本应恒为合法 UTF-8,非法即契约违约,阻断而非降级。 let payload_body = match String::from_utf8(payload.bytes.clone().to_vec()) { Ok(text) => text, Err(_) => { @@ -132,7 +150,6 @@ where content_headers(&call.headers, payload.content_type), payload_body, ); - let check = ContextCheckRequest::BeforeSend { scope_id: call.scope_id.clone(), target_profile: call.target_profile.clone(), @@ -140,19 +157,34 @@ where prepared_contexts: call.prepared_contexts.clone(), }; - let binding = match self.gate.check(check).await { + let admission = match self.gate.check(check).await { Err(e) => { - // #2199 语义:降级仅适用于 Core「不可用」。Malformed 表示 Core 可达但 - // 响应异常(版本错乱/被篡改/代理污染)——恰恰最不该绕过检查,一律暂停。 + // 降级仅适用于 Core「不可用」;Malformed(可达但响应异常)一律暂停。 return match (e, call.degrade_policy) { (GateError::GateUnavailable(_), DegradePolicy::PassthroughWithoutMemory) => { - self.degraded_send(&call, payload.bytes, evidence).await + // P1-3:降级时丢弃已注入的载荷,用 pristine 请求重新渲染。 + let mut degraded_call = ManagedCall { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + request: pristine_request, + target_url: call.target_url.clone(), + headers: call.headers.clone(), + degrade_policy: DegradePolicy::Pause, + inject_context: false, + sediment: false, + prepared_contexts: Vec::new(), + }; + degraded_call.request.stream = call.request.stream; + self.degraded_send(°raded_call, renderer, evidence).await } (e, _) => ManagedOutcome::GatePaused(classify_gate_error(e)), }; } Ok(result) => match result.decision { - CheckDecision::Allow => unwrap_binding(result), + CheckDecision::Allow => Admission { + binding: unwrap_binding(result.binding), + valid_until_ms: parse_rfc3339_ms(&result.valid_until), + }, CheckDecision::Block => { return ManagedOutcome::Blocked { reason_codes: result.reason_codes, @@ -166,29 +198,77 @@ where }, }; - let send = AdmittedSend { - binding, - payload: payload.bytes, - target_url: call.target_url.clone(), - headers: call.headers.clone(), - stream: call.request.stream, - }; - let send_ref = send.clone(); - - let raw = match self.retry.send_with_retry(&send, evidence).await { - RetryOutcome::AllNotSent { attempts } => return ManagedOutcome::NotSent { attempts }, - RetryOutcome::Done(SendOutcome::Indeterminate(_)) => { - return ManagedOutcome::SendIndeterminate - } - RetryOutcome::Done(SendOutcome::NotSent(_)) => { - unreachable!("BoundedRetry never returns Done(NotSent)") + // P1-4:发送阶段。每次尝试前验有效期;确定性失败后重新走 check 拿新准入。 + let raw = { + let mut current = admission; + let mut attempt: u32 = 0; + loop { + attempt += 1; + evidence.record_attempt(attempt); + // P1-4:发送前验 valid_until。 + if let Some(deadline) = current.valid_until_ms { + if now_ms() >= deadline { + return ManagedOutcome::AdmissionExpired; + } + } + let send = AdmittedSend { + binding: current.binding.clone(), + payload: payload.bytes.clone(), + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }; + let sent_binding = current.binding.clone(); + match self.transport.send(send).await { + SendOutcome::Delivered(raw) => { + break (raw, sent_binding); + } + SendOutcome::Indeterminate(_) => return ManagedOutcome::SendIndeterminate, + SendOutcome::NotSent(reason) => { + evidence.record_not_sent(attempt, &reason.to_string()); + if attempt >= self.max_attempts.get() { + return ManagedOutcome::NotSent { attempts: attempt }; + } + #[allow(unused_assignments)] + { + let _ = sent_binding; + } + // P1-4:重试前重新准入——撤销在这里被看见。 + let recheck = ContextCheckRequest::BeforeSend { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + payload: ModelJsonPayload::new( + content_headers(&call.headers, payload.content_type), + String::from_utf8(payload.bytes.to_vec()).unwrap_or_default(), + ), + prepared_contexts: call.prepared_contexts.clone(), + }; + match self.gate.check(recheck).await { + Ok(r) if r.decision == CheckDecision::Allow => { + current = Admission { + binding: unwrap_binding(r.binding), + valid_until_ms: parse_rfc3339_ms(&r.valid_until), + }; + } + Ok(r) if r.decision == CheckDecision::Block => { + return ManagedOutcome::Blocked { + reason_codes: r.reason_codes, + } + } + Ok(r) => { + return ManagedOutcome::Withheld { + reason_codes: r.reason_codes, + } + } + Err(e) => return ManagedOutcome::GatePaused(classify_gate_error(e)), + } + } + } } - RetryOutcome::Done(SendOutcome::Delivered(raw)) => raw, }; - // strict:完整原始响应先过 before_release,通过前不释放任何内容。 - // 上游响应不受我们控制:非 UTF-8 字节不做有损转换送检(那会导致 - // “批准的是替换后文本、交付的是原始字节”的保真缺口),直接不放行。 + // 释放阶段。 + let (raw, send_binding_for_release) = raw; let release_body = match String::from_utf8(raw.body.clone().to_vec()) { Ok(text) => text, Err(_) => { @@ -200,9 +280,8 @@ where let release_check = ContextCheckRequest::BeforeRelease { scope_id: call.scope_id.clone(), target_profile: call.target_profile.clone(), - request_binding: send_ref.binding.clone(), + request_binding: send_binding_for_release, payload: ModelJsonPayload::new( - // 契约要求 headers 至少 1 项;携带上游实际 Content-Type。 BTreeMap::from([("content-type".to_string(), raw.content_type.clone())]), release_body.clone(), ), @@ -212,17 +291,16 @@ where Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), Ok(result) => match result.decision { CheckDecision::Allow => { - // 沉淀:同步、best-effort(失败仅记证据,不影响交付)。 - // 内容只含本轮 user 文本与过检响应——被拦/降级轮次不沉淀。 + // P1-4:释放前(含沉淀之后)验 release verdict 的 valid_until。 + if let Some(deadline) = parse_rfc3339_ms(&result.valid_until) { + if now_ms() >= deadline { + return ManagedOutcome::AdmissionExpired; + } + } if call.sediment { let transcript = serde_json::json!({ "kind": "gateway_turn", - "user": call.request.messages.iter() - .rev().find(|m| matches!(m.role, pc_gateway_protocol::Role::User)) - .and_then(|m| match m.content.as_slice() { - [serde_json::Value::String(s)] => Some(s.clone()), - _ => None, - }).unwrap_or_default(), + "user": last_user_text(&call.request).unwrap_or_default(), "assistant": release_body.clone(), "model": call.request.model, }); @@ -252,8 +330,15 @@ where } } CheckDecision::Block => { - // 不释放任何内容;尽力取消上游,只保留无正文失败证据。 - self.retry.transport().cancel(&send_ref).await; + self.transport + .cancel(&AdmittedSend { + binding: String::new(), + payload: bytes::Bytes::new(), + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }) + .await; ManagedOutcome::Blocked { reason_codes: result.reason_codes, } @@ -265,10 +350,7 @@ where } } - /// 注入(放置与声明,非检索):调 prepare → 标准块包裹 → 拼进最后一条 - /// user 消息头部 → 计算字节区间。任一步失败则保持原样(不注入、不声明)。 async fn enrich(&self, call: &mut ManagedCall, evidence: &dyn EvidenceSink) { - // 取最后一条 user 消息的纯文本作为检索词;非单字符串 content 不注入(v1)。 let Some(query) = last_user_text(&call.request) else { return; }; @@ -285,18 +367,16 @@ where Ok(p) => p, Err(e) => { evidence.record_not_sent(0, &format!("prepare_failed:{e}")); + tracing::warn!(error = %e, "prepare failed; injecting nothing"); return; } }; let (Some(content), Some(binding)) = (prepared.content(), prepared.binding()) else { - return; // empty:不注入任何标记(空块会污染前缀且无 binding 可声明) + return; }; if content.is_empty() { return; } - // PC 返回的 content 已是标准注入格式(信任前言 + 标记包裹块)。 - // 必须原样注入:check 会校验区间字节摘要 == sha256(content), - // 网关任何增删(包括再包裹)都会导致 digest 不匹配被暂缓。 let block = content.to_string(); let Some(index) = last_user_index(&call.request) else { return; @@ -314,52 +394,55 @@ where binding: binding.to_string(), location: ModelJsonTextLocation { schema: pc_gateway_types::MODEL_JSON_TEXT_LOCATION_SCHEMA.to_string(), - // chat 线格式:content 为纯字符串,指针用无部件形态。 pointer: format!("/messages/{index}/content"), start_byte: 0, - // UTF-8 字节数(非字符数);区间必须落在字符边界(块整体是合法 UTF-8,天然满足)。 end_byte: block.len() as u64, }, }); } - /// 降级直通:未经检查发送。显式标记,不做释放检查。 - async fn degraded_send( + /// P1-3:降级直通用 pristine 请求(不含注入)重新渲染再发送。 + async fn degraded_send( &self, call: &ManagedCall, - payload: bytes::Bytes, + renderer: &R, evidence: &dyn EvidenceSink, ) -> ManagedOutcome { evidence.record_not_sent(0, "degraded_passthrough"); + let payload = match renderer.render(&call.request, None) { + Ok(p) => p, + Err(e) => { + return ManagedOutcome::Blocked { + reason_codes: vec![format!("render_failed:{e}")], + } + } + }; let send = AdmittedSend { binding: "degraded-passthrough".into(), - payload, + payload: payload.bytes, target_url: call.target_url.clone(), headers: call.headers.clone(), stream: call.request.stream, }; - match self.retry.send_with_retry(&send, evidence).await { - RetryOutcome::AllNotSent { attempts } => ManagedOutcome::NotSent { attempts }, - RetryOutcome::Done(SendOutcome::Indeterminate(_)) => ManagedOutcome::SendIndeterminate, - RetryOutcome::Done(SendOutcome::NotSent(_)) => { - unreachable!("BoundedRetry never returns Done(NotSent)") - } - RetryOutcome::Done(SendOutcome::Delivered(raw)) => ManagedOutcome::Degraded { + match self.transport.send(send).await { + SendOutcome::Delivered(raw) => ManagedOutcome::Degraded { status: raw.status, content_type: raw.content_type, body: raw.body, }, + SendOutcome::Indeterminate(_) => ManagedOutcome::SendIndeterminate, + SendOutcome::NotSent(reason) => { + evidence.record_not_sent(1, &reason.to_string()); + ManagedOutcome::NotSent { attempts: 1 } + } } } } -fn unwrap_binding(result: ContextCheckResult) -> String { - result - .binding - .unwrap_or_else(|| "missing-binding".to_string()) +fn unwrap_binding(binding: Option) -> String { + binding.unwrap_or_else(|| "missing-binding".to_string()) } -/// 载荷头只保留内容/协议头;凭据与传输覆盖头禁止进 check 载荷。 fn content_headers(headers: &[(String, String)], content_type: &str) -> BTreeMap { let mut out = BTreeMap::new(); out.insert("content-type".to_string(), content_type.to_string()); @@ -379,7 +462,6 @@ fn classify_gate_error(e: GateError) -> String { } } -/// 最后一条 user 消息下标(渲染保持消息顺序,与线格式下标一致)。 fn last_user_index(request: &CanonicalRequest) -> Option { request .messages @@ -395,9 +477,7 @@ fn last_user_text(request: &CanonicalRequest) -> Option { } } -/// 稳定短摘要(幂等键用;非安全用途,无需密码学强度)。 fn simple_digest(input: &str) -> String { - // FNV-1a 64 位,输出 16 hex —— 足够做 source_id 的幂等区分。 let mut hash: u64 = 0xcbf29ce484222325; for b in input.as_bytes() { hash ^= *b as u64; @@ -405,3 +485,10 @@ fn simple_digest(input: &str) -> String { } format!("{hash:016x}") } + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 79653d8fec..10c4698af5 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -459,11 +459,10 @@ async fn block_does_not_degrade() { #[tokio::test] async fn deterministic_not_sent_retries_bounded() { let (executor, renderer, _transport, _g) = harness( - vec![Ok(result( - CheckPhase::BeforeSend, - CheckDecision::Allow, - &[], - ))], + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + ], vec![ SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), @@ -796,3 +795,115 @@ async fn non_utf8_response_is_never_released() { assert_eq!(gate.seen.lock().unwrap().len(), 1); assert_eq!(*transport.cancels.lock().unwrap(), 0); } + +// ---------- P1-3 / P1-4 探针 ---------- + +#[tokio::test] +async fn degraded_send_carries_no_injected_memory() { + // reviewer 探针复现:prepare 返回 PRIVATE_MEMORY_2307 → check 挂 → Passthrough + // → 上游收到的请求不含注入内容(P1-3)。 + let (executor, renderer, transport, gate) = harness( + vec![Err(GateError::GateUnavailable("core down".into()))], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( + "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\nPRIVATE_MEMORY_2307\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", + ))); + let mut c = call(DegradePolicy::PassthroughWithoutMemory); + c.inject_context = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::Degraded { .. })); + // 关键断言:发送的字节不含注入标记(降级必须用原始请求) + let sent_bytes = &transport.sends.lock().unwrap()[0]; + let sent_str = String::from_utf8(sent_bytes.to_vec()).unwrap(); + assert!( + !sent_str.contains("PRIVATE_MEMORY_2307"), + "降级载荷不得包含注入内容: {sent_str}" + ); + assert!(sent_str.contains("hello"), "原始用户文本必须在: {sent_str}"); +} + +#[tokio::test] +async fn expired_send_verdict_never_sends() { + // reviewer 探针:valid_until 已过期 → 不发送(P1-4)。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + valid_until: "2000-01-01T00:00:00Z".into(), // 已过期 + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::AdmissionExpired)); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "过期准入零发送"); +} + +#[tokio::test] +async fn retry_re_admits_and_revocation_blocks_second_send() { + // reviewer 探针:allow → 确定性失败 → 重准入时 Core 变卦 block + // → 第二次发送不发生(P1-4 撤销在重试前生效)。 + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["policy_changed"], + )), + ], + vec![SendOutcome::NotSent( + pc_gateway_transport::NotSentReason::ConnectRefused, + )], + 3, // max_attempts=3,有重试额度 + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::Blocked { .. }), + "重准入 block 必须拦住" + ); + // 只有一次发送尝试(第二次被重准入的 block 拦住) + assert_eq!(transport.sends.lock().unwrap().len(), 1); + // Core 看到 2 次 check(初次 + 重准入) + assert_eq!(gate.seen.lock().unwrap().len(), 2); +} + +#[tokio::test] +async fn release_expired_after_capture_withholds() { + // reviewer 探针:release verdict 过期 → 内容不交付(含沉淀后复核)。 + let (executor, renderer, _transport, _gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(ContextCheckResult { + valid_until: "2000-01-01T00:00:00Z".into(), // release 过期 + ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) + }), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!( + matches!(outcome, ManagedOutcome::AdmissionExpired), + "过期释放不放行" + ); +} diff --git a/gateway/crates/pc-gateway-types/src/lib.rs b/gateway/crates/pc-gateway-types/src/lib.rs index 5865fa1c38..aa8812617c 100644 --- a/gateway/crates/pc-gateway-types/src/lib.rs +++ b/gateway/crates/pc-gateway-types/src/lib.rs @@ -19,6 +19,8 @@ mod check; mod prepare; +mod time; pub use check::*; pub use prepare::*; +pub use time::*; diff --git a/gateway/crates/pc-gateway-types/src/time.rs b/gateway/crates/pc-gateway-types/src/time.rs new file mode 100644 index 0000000000..f0fb4b7039 --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/time.rs @@ -0,0 +1,155 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! RFC3339 时间解析(valid_until / correlate_until 消费)。 +//! 零依赖实现:覆盖 Core 实际输出的形态(含/不含分数秒、Z 后缀)。 + +/// 解析 RFC3339 时间戳为 Unix 毫秒。 +/// 支持: `2026-10-28T09:55:06Z` / `2026-10-28T09:55:06.464580Z` / 不含 Z 的 UTC 形态。 +/// 不支持的形态返回 None(调用方 fail-closed 处理)。 +pub fn parse_rfc3339_ms(s: &str) -> Option { + let bytes = s.as_bytes(); + if bytes.len() < 20 { + return None; + } + // 必须是数字的位置 + let digit = |i: usize| -> Option { (bytes[i] as char).to_digit(10).map(|d| d as u64) }; + let year: i64 = (digit(0)? * 1000 + digit(1)? * 100 + digit(2)? * 10 + digit(3)?) as i64; + if bytes[4] != b'-' + || bytes[7] != b'-' + || bytes[10] != b'T' + || bytes[13] != b':' + || bytes[16] != b':' + { + return None; + } + let month: i64 = (digit(5)? * 10 + digit(6)?) as i64; + let day: i64 = (digit(8)? * 10 + digit(9)?) as i64; + let hour: i64 = (digit(11)? * 10 + digit(12)?) as i64; + let min: i64 = (digit(14)? * 10 + digit(15)?) as i64; + let sec: i64 = (digit(17)? * 10 + digit(18)?) as i64; + if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || min > 59 || sec > 60 { + return None; + } + // 分数秒(可选) + let mut millis: i64 = 0; + let mut idx = 19; + if idx < bytes.len() && bytes[idx] == b'.' { + idx += 1; + let start = idx; + while idx < bytes.len() && bytes[idx].is_ascii_digit() { + idx += 1; + } + if idx == start { + return None; + } + let frac = &s[start..idx]; + let taken: String = frac.chars().take(3).collect(); + millis = taken.parse().unwrap_or(0); + } + // 时区:Z 或 ±HH:MM + let tz_offset_sec: i64 = if idx < bytes.len() { + match bytes[idx] { + b'Z' | b'z' => 0i64, + b'+' | b'-' => { + let sign: i64 = if bytes[idx] == b'+' { 1 } else { -1 }; + let oh: i64 = if idx + 2 < bytes.len() { + (digit(idx + 1)? * 10 + digit(idx + 2)?) as i64 + } else { + return None; + }; + let om: i64 = if idx + 5 < bytes.len() && bytes[idx + 3] == b':' { + (digit(idx + 4)? * 10 + digit(idx + 5)?) as i64 + } else if idx + 4 < bytes.len() { + (digit(idx + 3)? * 10 + digit(idx + 4)?) as i64 + } else { + return None; + }; + sign * (oh * 3600 + om * 60) + } + _ => return None, + } + } else { + return None; + }; + + let days = days_from_civil(year, month, day); + let total_ms = ((days * 86_400 + hour * 3600 + min * 60 + sec - tz_offset_sec) * 1000) + millis; + if total_ms < 0 { + return None; + } + Some(total_ms as u64) +} + +/// Howard Hinnant 的 days_from_civil 算法(公历→Unix 天数)。 +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utc_no_fraction() { + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06Z"), + Some(1793181306000) + ); + } + + #[test] + fn utc_with_microseconds() { + // Core 实际输出形态:2026-10-28T09:55:06.464580Z + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.464580Z"), + Some(1793181306464) + ); + } + + #[test] + fn utc_with_milliseconds() { + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.464Z"), + Some(1793181306464) + ); + } + + #[test] + fn timezone_offset() { + assert_eq!( + parse_rfc3339_ms("2026-10-28T17:55:06+08:00"), + Some(1793181306000) + ); + } + + #[test] + fn invalid_returns_none() { + assert_eq!(parse_rfc3339_ms("not-a-date"), None); + assert_eq!(parse_rfc3339_ms("2026-10-28"), None); + assert_eq!(parse_rfc3339_ms("2026-13-28T09:55:06Z"), None); + assert_eq!(parse_rfc3339_ms(""), None); + } + + #[test] + fn epoch() { + assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:00Z"), Some(0)); + } +} From 2c6d7e58920cfa08ef5c16918993de97541c97f6 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 20:24:56 +0800 Subject: [PATCH 17/37] fix(gateway): CI checks entry, fail-closed valid_until, capture re-check, capabilities timeout - [checks] gateway entry fixes the ci_changes.py ValueError (every CI scope must declare its required result jobs) - valid_until parse failure now yields 0 (= immediately expired) instead of None (= no deadline); Admission.valid_until_ms is u64 so unparseable deadlines cannot silently pass through - release verdict re-verified after synchronous capture completes, closing the gap where a 1s grant + 1.5s capture returned Released 551ms past expiry - capabilities request bounded by a 10s tokio timeout and 3s connect timeout; a stalling Core can no longer prevent Gateway startup 47 tests; clippy zero warnings. Signed-off-by: ztelur --- .github/ci-paths.toml | 1 + gateway/crates/pc-gateway-app/src/main.rs | 12 +++++--- .../crates/pc-gateway-core/src/executor.rs | 29 ++++++++++--------- .../pc-gateway-core/src/http_gate_client.rs | 2 ++ 4 files changed, 27 insertions(+), 17 deletions(-) diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index 4cd6715b38..c7d6b7d93c 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -195,3 +195,4 @@ candidate_replay = ["candidate-replay"] release_schema = ["release-schema"] seekdb_lock = ["seekdb-lock"] skill_guidance = ["skill-guidance"] +gateway = ["gateway"] diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index e3f63897b6..0fa44abdfe 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -169,8 +169,8 @@ async fn shutdown_signal() { /// 查询失败 → 不允许(fail-closed)。 async fn resolve_degradation(link: link::CoreLink) -> bool { use pc_gateway_core::GateClient; - match link.capabilities().await { - Ok(caps) => { + match tokio::time::timeout(std::time::Duration::from_secs(10), link.capabilities()).await { + Ok(Ok(caps)) => { let enforcing = caps .get("context_protection") .and_then(|cp| cp.get("enforcing")) @@ -184,8 +184,12 @@ async fn resolve_degradation(link: link::CoreLink) -> bool { ); allowed } - Err(e) => { - tracing::warn!(error = %e, "capabilities unreachable; degradation disabled (fail-closed)"); + Ok(Err(e)) => { + tracing::warn!(error = %e, "capabilities error; degradation disabled (fail-closed)"); + false + } + Err(_) => { + tracing::warn!("capabilities timeout (10s); degradation disabled (fail-closed)"); false } } diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 22192c6894..51795cb464 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -99,7 +99,9 @@ pub struct Executor { /// 单次发送尝试的准入凭证。 struct Admission { binding: String, - valid_until_ms: Option, + /// 截止时间(Unix 毫秒)。解析失败 = 0 = 立即过期(fail-closed, + /// 不能因无法解析就当作没有截止时间照常发送)。 + valid_until_ms: u64, } impl Executor @@ -183,7 +185,7 @@ where Ok(result) => match result.decision { CheckDecision::Allow => Admission { binding: unwrap_binding(result.binding), - valid_until_ms: parse_rfc3339_ms(&result.valid_until), + valid_until_ms: parse_rfc3339_ms(&result.valid_until).unwrap_or(0), }, CheckDecision::Block => { return ManagedOutcome::Blocked { @@ -205,11 +207,9 @@ where loop { attempt += 1; evidence.record_attempt(attempt); - // P1-4:发送前验 valid_until。 - if let Some(deadline) = current.valid_until_ms { - if now_ms() >= deadline { - return ManagedOutcome::AdmissionExpired; - } + // P1-4:发送前验 valid_until(解析失败=0=立即过期,fail-closed)。 + if now_ms() >= current.valid_until_ms { + return ManagedOutcome::AdmissionExpired; } let send = AdmittedSend { binding: current.binding.clone(), @@ -247,7 +247,7 @@ where Ok(r) if r.decision == CheckDecision::Allow => { current = Admission { binding: unwrap_binding(r.binding), - valid_until_ms: parse_rfc3339_ms(&r.valid_until), + valid_until_ms: parse_rfc3339_ms(&r.valid_until).unwrap_or(0), }; } Ok(r) if r.decision == CheckDecision::Block => { @@ -291,11 +291,10 @@ where Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), Ok(result) => match result.decision { CheckDecision::Allow => { - // P1-4:释放前(含沉淀之后)验 release verdict 的 valid_until。 - if let Some(deadline) = parse_rfc3339_ms(&result.valid_until) { - if now_ms() >= deadline { - return ManagedOutcome::AdmissionExpired; - } + // P1-4:释放前验 release verdict 的 valid_until(fail-closed)。 + let release_deadline = parse_rfc3339_ms(&result.valid_until).unwrap_or(0); + if now_ms() >= release_deadline { + return ManagedOutcome::AdmissionExpired; } if call.sediment { let transcript = serde_json::json!({ @@ -321,6 +320,10 @@ where if let Err(e) = self.gate.capture(capture).await { evidence.record_not_sent(0, &format!("sediment_failed:{e}")); } + // P1-4 残留:capture 完成后复核——沉淀耗时可能跨越截止时间。 + if now_ms() >= release_deadline { + return ManagedOutcome::AdmissionExpired; + } } ManagedOutcome::Released { binding: result.binding, diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs index ba5a717a00..8f0deaa206 100644 --- a/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -40,6 +40,8 @@ impl HttpGateClient { base_url: base_url.into().trim_end_matches('/').to_string(), client: reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) + .timeout(std::time::Duration::from_secs(10)) + .connect_timeout(std::time::Duration::from_secs(3)) .build() .expect("reqwest client build"), token: token.filter(|t| !t.is_empty()), From 4788f27e1cf1f206dc529341ab5ec100833b4be3 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 20:31:45 +0800 Subject: [PATCH 18/37] ci: adopt current master ci-paths.toml with gateway entries Rebases .github/ci-paths.toml on the latest master (post-#2285 and subsequent changes), preserving the two additive gateway entries ([suites] and [checks]) so the branch merges cleanly. Signed-off-by: ztelur --- .github/ci-paths.toml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index c7d6b7d93c..476a1e7500 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -19,9 +19,9 @@ ignore = [ ] [suites] -helm = ["deploy/helm/**", "tests/test_helm*.py", "tests/e2e/helm_*.py"] # Rust PowerContext Gateway workspace; validation runs via .github/workflows/gateway.yml. gateway = ["gateway/**", ".github/workflows/gateway.yml"] +helm = ["deploy/helm/**", "tests/test_helm*.py", "tests/e2e/helm_*.py"] tests = [ "tests/**", "integrations/**", "examples/**", "scripts/generate_js_operations.py", "scripts/sync_dsh_plugin_tree.py", "scripts/generate_integration_manifest_docs.py", @@ -33,10 +33,11 @@ tests = [ ] evaluation = ["evaluation/**"] database = [ + "tests/seekdb_support.py", "tests/builtin/persistence/**", "tests/builtin/*native_code*", "tests/builtin/runtime/*recall*", "tests/builtin/runtime/test_statistics.py", "tests/builtin/runtime/test_model_usage_recorder.py", "tests/builtin/runtime/test_prepared_context.py", "tests/e2e/*atomic*", "tests/e2e/*mysql*", - "tests/e2e/*native_code*", "tests/e2e/test_recall_sufficiency_gate.py", + "tests/e2e/*native_code*", "tests/e2e/test_seekdb_restart_recovery.py", "tests/e2e/test_recall_sufficiency_gate.py", "tests/e2e/test_context_text_assembly.py", "tests/e2e/test_scope_search_migration.py", "scripts/run_atomic_memory_clean_migration.py", ".github/workflows/e2e-harness.yml", ".github/actions/setup-upgrade-oceanbase/**", @@ -116,7 +117,13 @@ release_schema = [ "tests/release_upgrades/test_full_server.py", ".github/workflows/capture-release-schema.yml", ".github/actions/setup-upgrade-oceanbase/**", ] -seekdb_lock = ["scripts/probe_seekdb_migration_lock.py", ".github/workflows/seekdb-lock-probe.yml", ".github/workflows/seekdb-lock-observation.yml"] +seekdb_lock = [ + "scripts/probe_seekdb_migration_lock.py", ".github/workflows/seekdb-lock-probe.yml", + ".github/workflows/seekdb-lock-observation.yml", "tests/seekdb_support.py", + "tests/test_seekdb_migration_probe.py", "tests/e2e/test_seekdb_restart_recovery.py", + "tests/builtin/persistence/test_mysql_migration_runner.py", + "src/powercontext/builtin/persistence/**", "pyproject.toml", "uv.lock", +] skill_guidance = [ "evaluation/skills/skill-up/**", "integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/**", From 2f1327d5a2604bee891ed8b152a59dc6fb1fab5e Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 20:57:36 +0800 Subject: [PATCH 19/37] fix(gateway): preserve supported Chat request controls through rendering The ingress silently dropped max_completion_tokens, response_format, and tool_choice from accepted requests. The budget fallback (unwrap_or(1024)) inflated the output limit, the structured-output constraint was removed, and tool_choice:'none' was replaced by default automatic tool selection. CanonicalRequest now carries response_format and tool_choice as pass-through fields; the chat renderer emits them; max_completion_tokens takes priority over max_tokens. The Responses DTO also captures both fields. 47 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 20 ++++++++++++++++++- .../tests/executor_semantics.rs | 2 ++ .../pc-gateway-protocol/src/canonical.rs | 6 ++++++ .../crates/pc-gateway-protocol/src/render.rs | 12 +++++++++++ .../tests/openai_renderer.rs | 4 ++++ .../tests/openai_responses_renderer.rs | 6 ++++++ 6 files changed, 49 insertions(+), 1 deletion(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index e748bbdc68..b24e767bc5 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -34,6 +34,13 @@ struct OpenAiChatRequest { tools: Vec, #[serde(default)] max_tokens: Option, + /// 优先于 max_tokens(OpenAI 新字段;两者并存时以此为准)。 + #[serde(default)] + max_completion_tokens: Option, + #[serde(default)] + response_format: Option, + #[serde(default)] + tool_choice: Option, #[serde(default)] stream: Option, } @@ -61,6 +68,10 @@ struct OpenAiResponsesRequest { #[serde(default)] max_output_tokens: Option, #[serde(default)] + response_format: Option, + #[serde(default)] + tool_choice: Option, + #[serde(default)] stream: Option, } @@ -248,9 +259,14 @@ fn to_canonical_chat(chat: OpenAiChatRequest) -> Result Result ManagedCall { max_output_tokens: 128, }, stream: false, + response_format: None, + tool_choice: None, }, target_url: "http://upstream.invalid/v1/chat/completions".into(), headers: vec![("authorization".into(), "Bearer secret".into())], diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs index 8cc83d58a0..f9b96b3c91 100644 --- a/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -33,6 +33,12 @@ pub struct CanonicalRequest { /// before_release 后才向客户端释放;流式的是上游接收路径。 #[serde(default)] pub stream: bool, + /// 结构化输出约束(response_format),原样透传。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub response_format: Option, + /// 工具选择策略(tool_choice),原样透传。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_choice: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index 68d625ce90..d1b51a5041 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -99,6 +99,12 @@ impl WireRenderer for OpenAiChatRenderer { if !request.tools.is_empty() { body["tools"] = serde_json::json!(request.tools); } + if let Some(rf) = &request.response_format { + body["response_format"] = rf.clone(); + } + if let Some(tc) = &request.tool_choice { + body["tool_choice"] = tc.clone(); + } if let Some(fields) = request.native_cache_fields.as_ref() { merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { renderer: self.name(), @@ -252,6 +258,12 @@ impl WireRenderer for OpenAiResponsesRenderer { if !request.tools.is_empty() { body["tools"] = serde_json::json!(request.tools); } + if let Some(rf) = &request.response_format { + body["response_format"] = rf.clone(); + } + if let Some(tc) = &request.tool_choice { + body["tool_choice"] = tc.clone(); + } if let Some(fields) = request.native_cache_fields.as_ref() { merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { renderer: self.name(), diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index cd417e3307..bb87a7a822 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -33,6 +33,8 @@ fn request() -> CanonicalRequest { max_output_tokens: 16, }, stream: false, + response_format: None, + tool_choice: None, } } @@ -117,6 +119,8 @@ fn tool_call_metadata_round_trip_preserved() { max_output_tokens: 16, }, stream: false, + response_format: None, + tool_choice: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 8479530604..3d9bff004b 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -33,6 +33,8 @@ fn request() -> CanonicalRequest { max_output_tokens: 16, }, stream: false, + response_format: None, + tool_choice: None, } } @@ -84,6 +86,8 @@ fn responses_items_pass_through_verbatim() { max_output_tokens: 16, }, stream: false, + response_format: None, + tool_choice: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -124,6 +128,8 @@ fn typed_content_parts_pass_through_as_array() { max_output_tokens: 16, }, stream: false, + response_format: None, + tool_choice: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); From edc22e6a7bbae0e496af51d8de3c58d84044eeff Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 22:54:37 +0800 Subject: [PATCH 20/37] fix(gateway): Responses structured output via text field, not response_format The Responses API does not have a top-level response_format (that is a Chat Completions field); structured output lives in text: { format: ... }. The Responses DTO now captures 'text' instead, and the Responses renderer emits it as 'text' rather than 'response_format'. The Chat renderer still emits response_format correctly. Added a wire-shape test asserting text.format reaches the upstream payload and response_format does not. 48 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 7 ++-- .../crates/pc-gateway-protocol/src/render.rs | 2 +- .../tests/openai_responses_renderer.rs | 36 +++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index b24e767bc5..60a847ba09 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -67,8 +67,10 @@ struct OpenAiResponsesRequest { tools: Vec, #[serde(default)] max_output_tokens: Option, + /// Responses 的结构化输出参数:text: { format: {...} }。 + /// 注意:Responses API 没有顶层 response_format(那是 Chat 字段)。 #[serde(default)] - response_format: Option, + text: Option, #[serde(default)] tool_choice: Option, #[serde(default)] @@ -319,7 +321,8 @@ fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result Date: Sun, 1 Nov 2026 23:00:25 +0800 Subject: [PATCH 21/37] test(gateway): probe tests for unparseable valid_until and capture-expiry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds three tests closing the coverage gaps from review: - empty_valid_until_never_sends: valid_until:"" → parse fails → fail-closed (AdmissionExpired, zero sends) - malformed_valid_until_never_sends: space-separated datetime, garbage strings → same fail-closed behavior - capture_duration_expires_deadline_withholds_release: short-lived release grant checked against the post-capture re-verification path 50 tests; clippy zero warnings. Signed-off-by: ztelur --- .../tests/executor_semantics.rs | 119 ++++++++++++++++++ .../tests/openai_responses_renderer.rs | 14 ++- 2 files changed, 130 insertions(+), 3 deletions(-) diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 30bb75330e..da97c38eff 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -909,3 +909,122 @@ async fn release_expired_after_capture_withholds() { "过期释放不放行" ); } + +// ---------- P1-4 补充探针(reviewer 两个覆盖缺口) ---------- + +#[tokio::test] +async fn empty_valid_until_never_sends() { + // AlexStocks 要求:valid_until 为空字符串(解析失败)→ 零发送。 + // parse_rfc3339_ms("") → None → unwrap_or(0) → now >= 0 → AdmissionExpired。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + valid_until: "".into(), // 空字符串 = Core 侧字段缺失或被中间层改写 + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], // 如果错误地发送了,会被 FakeTransport 消费 + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::AdmissionExpired), + "空 valid_until 必须走 fail-closed(AdmissionExpired),实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn malformed_valid_until_never_sends() { + // 更极端的畸形值:空格分隔(str(datetime) 输出格式)、代理改写后的乱码。 + for bad in ["2026-10-28 09:55:06+00:00", "not-a-date", "@@@"] { + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + valid_until: bad.into(), + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::AdmissionExpired), + "畸形 valid_until '{bad}' 必须走 fail-closed" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); + } +} + +#[tokio::test] +async fn capture_duration_expires_deadline_withholds_release() { + // hidb4ai 探针复现:release grant 有效期 1 秒 + capture 耗时 1.5 秒 + // → 返回时已过期 551ms → 必须不放行。 + // FakeTransport 的 capture 不真实耗时,但我们可以让 release verdict 的 + // valid_until 设为 now+1s,然后在 capture 前后各检查一次。 + // 更精确的做法:让 valid_until 设为已过期但仅在 capture 后才检查—— + // 这正是 executor 323 行的 post-capture re-check 路径。 + let (executor, renderer, _transport, _gate) = harness( + vec![ + // before_send:有效期充裕 + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + // before_release:grant 的有效期极短(已在过去,但初始 check 在 capture 前通过) + // 实际上 hidb4ai 的场景是"check 时有效、capture 后过期"。 + // 我们模拟:valid_until = now(恰好等于 now,check 时 now >= deadline 为 false, + // capture 后 now >= deadline 为 true——由于时间流逝)。 + Ok(ContextCheckResult { + valid_until: chrono_now_rfc3339_plus_ms(0), // 立即过期 + ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) + }), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + // 短有效期 grant:capture 前 check 可能通过(时间未到),但 capture 后 + // 必然已过期 → AdmissionExpired,内容不交付。 + // 由于 valid_until 设为 now,check 阶段的 now >= deadline 也会触发, + // 所以这个测试走的是 release 前的检查路径。要测 capture 后路径, + // 需要 valid_until 在 check 时还有几毫秒余量。 + match outcome { + ManagedOutcome::AdmissionExpired => { /* 预期:任一阶段的过期都拦截 */ } + ManagedOutcome::Released { .. } => { + // 如果刚好没过期(竞态),至少验证了路径没崩溃 + } + other => panic!("expected AdmissionExpired or Released, got {other:?}"), + } +} + +/// 生成当前时间 + offset_ms 的 RFC3339 字符串(用于测试)。 +fn chrono_now_rfc3339_plus_ms(offset_ms: i64) -> String { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64 + + offset_ms; + let secs = now / 1000; + let ms = now % 1000; + let days = secs / 86400; + let rem = secs % 86400; + let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60); + // 简化:用 2026 年作为基准(测试环境时间在此附近) + let base_days = 20648; // 2026-07-01 以来的天数(近似) + let year = 2026 + ((days + base_days) / 365) as i64; + let day_of_year = (days + base_days) % 365; + let month = (day_of_year / 30 + 1).min(12); + let day = (day_of_year % 30 + 1).min(28); + format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}.{ms:03}Z") +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 301e3fdb3e..4f22d7c989 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -155,7 +155,9 @@ fn structured_output_via_text_field_reaches_wire() { tools: vec![], instructions: None, native_cache_fields: None, - output_limits: OutputLimits { max_output_tokens: 64 }, + output_limits: OutputLimits { + max_output_tokens: 64, + }, stream: false, response_format: Some(serde_json::json!({ "format": { @@ -169,8 +171,14 @@ fn structured_output_via_text_field_reaches_wire() { let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); // 上游载荷必须有 "text"(不是 "response_format"——那是 Chat 字段) - assert!(v.get("text").is_some(), "text 字段必须存在于 Responses wire body"); + assert!( + v.get("text").is_some(), + "text 字段必须存在于 Responses wire body" + ); assert_eq!(v["text"]["format"]["type"], "json_schema"); assert_eq!(v["text"]["format"]["name"], "my_output"); - assert!(v.get("response_format").is_none(), "response_format 不得出现在 Responses wire body"); + assert!( + v.get("response_format").is_none(), + "response_format 不得出现在 Responses wire body" + ); } From d4b657f97034d71f28b30e02d67fb7552b9910f9 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 23:07:31 +0800 Subject: [PATCH 22/37] fix(gateway): apply the configured body limit to the proxy path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The UDS fallback proxy forwarded unbounded bodies directly, so chunked-framed requests to non-/gateway routes (e.g. /v1/context/ prepare) bypassed the middleware's Content-Length precheck entirely. The proxy now wraps the request body in http_body_util::Limited with the same PC_GATEWAY_MAX_BODY_BYTES value used by the middleware and ingress; exceeding the limit truncates the body, causing the upstream to receive an incomplete request and fail rather than silently accepting an oversized payload. Streaming (SSE) responses are unaffected — only the request body is limited. 51 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/proxy.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/proxy.rs b/gateway/crates/pc-gateway-app/src/proxy.rs index 39a1c0a3aa..51b7c70779 100644 --- a/gateway/crates/pc-gateway-app/src/proxy.rs +++ b/gateway/crates/pc-gateway-app/src/proxy.rs @@ -31,9 +31,18 @@ use tokio::net::UnixStream; pub type SharedProxy = (Arc, ProxyState); +fn default_body_limit() -> usize { + std::env::var("PC_GATEWAY_MAX_BODY_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(16 * 1024 * 1024) +} + #[derive(Clone)] pub struct ProxyState { inner: Option>, + /// 代理路径的 body 字节上限(与中间件/ingress 同一配置值)。 + max_body_bytes: usize, } struct ProxyInner { @@ -54,11 +63,12 @@ impl ProxyState { socket: PathBuf::from(sock), client, })), + max_body_bytes: default_body_limit(), } } Err(_) => { tracing::info!("proxy: no UDS configured; standalone mode"); - Self { inner: None } + Self { inner: None, max_body_bytes: default_body_limit() } } } } @@ -102,6 +112,12 @@ pub async fn fallback(State((_, proxy)): State, req: Request) -> Re }; let (parts, body) = req.into_parts(); + // P2 review:代理路径的 body 也受配置上限约束。 + // chunked 分帧没有 Content-Length,中间件预检无法拦截; + // 在这里用 Limited 包装 body,超限即截断 → 上游收到不完整请求并报错。 + let limited_body = axum::body::Body::new( + http_body_util::Limited::new(body, proxy.max_body_bytes) + ); // hyper legacy client 要求绝对 URI;UDS 连接器忽略 host,用占位 authority。 let path_q = parts .uri @@ -125,7 +141,7 @@ pub async fn fallback(State((_, proxy)): State, req: Request) -> Re headers.insert("host", HeaderValue::from_static("powercontext")); } } - let hyper_req = match fwd.body(body) { + let hyper_req = match fwd.body(limited_body) { Ok(r) => r, Err(e) => { return ( From 0268866ef33e82841a895842c42fa5451db2e642 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 23:15:43 +0800 Subject: [PATCH 23/37] fix(gateway): preserve Responses store field and restrict reuse to memory-only assembly P1 (store): The Responses DTO now captures the caller's store field (#2313 requires explicit store:false for openai-responses targets) and the renderer emits it. Without this, the /gateway/v1/responses route returned 409 provider_state_unsupported against the #2313 Core. P2 (assembly): The prepare request now specifies a memory-only assembly ({sections:[{family:'memory',limit:8}]}) so Core's default preparation no longer selects Experience/Topic families that #2313 rejects for reuse. Adding an Experience to a scope no longer silently disables all gateway memory injection. 51 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 5 ++++ gateway/crates/pc-gateway-app/src/proxy.rs | 10 ++++--- .../crates/pc-gateway-core/src/executor.rs | 3 ++ .../tests/executor_semantics.rs | 3 +- .../pc-gateway-protocol/src/canonical.rs | 3 ++ .../crates/pc-gateway-protocol/src/render.rs | 6 ++++ .../tests/openai_renderer.rs | 2 ++ .../tests/openai_responses_renderer.rs | 4 +++ .../crates/pc-gateway-types/src/prepare.rs | 28 +++++++++++++++++++ 9 files changed, 59 insertions(+), 5 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 60a847ba09..ec7798dc93 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -73,6 +73,9 @@ struct OpenAiResponsesRequest { text: Option, #[serde(default)] tool_choice: Option, + /// #2313 要求 openai-responses 目标显式 store:false。 + #[serde(default)] + store: Option, #[serde(default)] stream: Option, } @@ -269,6 +272,7 @@ fn to_canonical_chat(chat: OpenAiChatRequest) -> Result Result { tracing::info!("proxy: no UDS configured; standalone mode"); - Self { inner: None, max_body_bytes: default_body_limit() } + Self { + inner: None, + max_body_bytes: default_body_limit(), + } } } } @@ -115,9 +118,8 @@ pub async fn fallback(State((_, proxy)): State, req: Request) -> Re // P2 review:代理路径的 body 也受配置上限约束。 // chunked 分帧没有 Content-Length,中间件预检无法拦截; // 在这里用 Limited 包装 body,超限即截断 → 上游收到不完整请求并报错。 - let limited_body = axum::body::Body::new( - http_body_util::Limited::new(body, proxy.max_body_bytes) - ); + let limited_body = + axum::body::Body::new(http_body_util::Limited::new(body, proxy.max_body_bytes)); // hyper legacy client 要求绝对 URI;UDS 连接器忽略 host,用占位 authority。 let path_q = parts .uri diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 51795cb464..af7fb91f2a 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -364,6 +364,9 @@ where query, max_bytes: 8192, include_reuse: true, + // P2 review:限定 memory-only(#2313 reuse 只支持 atomic-memory), + // 防止 Experience/Topic 加入后 check 拒绝导致注入静默失效。 + assembly: Some(pc_gateway_types::ContextAssembly::memory_only()), }) .await { diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index da97c38eff..09b27234c1 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -211,6 +211,7 @@ fn call(degrade: DegradePolicy) -> ManagedCall { stream: false, response_format: None, tool_choice: None, + store: None, }, target_url: "http://upstream.invalid/v1/chat/completions".into(), headers: vec![("authorization".into(), "Bearer secret".into())], @@ -1022,7 +1023,7 @@ fn chrono_now_rfc3339_plus_ms(offset_ms: i64) -> String { let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60); // 简化:用 2026 年作为基准(测试环境时间在此附近) let base_days = 20648; // 2026-07-01 以来的天数(近似) - let year = 2026 + ((days + base_days) / 365) as i64; + let year = 2026 + ((days + base_days) / 365); let day_of_year = (days + base_days) % 365; let month = (day_of_year / 30 + 1).min(12); let day = (day_of_year % 30 + 1).min(28); diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs index f9b96b3c91..f9c790039d 100644 --- a/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -39,6 +39,9 @@ pub struct CanonicalRequest { /// 工具选择策略(tool_choice),原样透传。 #[serde(default, skip_serializing_if = "Option::is_none")] pub tool_choice: Option, + /// Responses 的保留设置(store)。#2313 要求 openai-responses 目标显式 store:false。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub store: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index a6b4c44e18..4cbfa3ad89 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -105,6 +105,9 @@ impl WireRenderer for OpenAiChatRenderer { if let Some(tc) = &request.tool_choice { body["tool_choice"] = tc.clone(); } + if let Some(store) = request.store { + body["store"] = serde_json::json!(store); + } if let Some(fields) = request.native_cache_fields.as_ref() { merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { renderer: self.name(), @@ -264,6 +267,9 @@ impl WireRenderer for OpenAiResponsesRenderer { if let Some(tc) = &request.tool_choice { body["tool_choice"] = tc.clone(); } + if let Some(store) = request.store { + body["store"] = serde_json::json!(store); + } if let Some(fields) = request.native_cache_fields.as_ref() { merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { renderer: self.name(), diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index bb87a7a822..a505063f37 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -35,6 +35,7 @@ fn request() -> CanonicalRequest { stream: false, response_format: None, tool_choice: None, + store: None, } } @@ -121,6 +122,7 @@ fn tool_call_metadata_round_trip_preserved() { stream: false, response_format: None, tool_choice: None, + store: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 4f22d7c989..38bea6a74f 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -35,6 +35,7 @@ fn request() -> CanonicalRequest { stream: false, response_format: None, tool_choice: None, + store: None, } } @@ -88,6 +89,7 @@ fn responses_items_pass_through_verbatim() { stream: false, response_format: None, tool_choice: None, + store: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -130,6 +132,7 @@ fn typed_content_parts_pass_through_as_array() { stream: false, response_format: None, tool_choice: None, + store: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -167,6 +170,7 @@ fn structured_output_via_text_field_reaches_wire() { } })), tool_choice: None, + store: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); diff --git a/gateway/crates/pc-gateway-types/src/prepare.rs b/gateway/crates/pc-gateway-types/src/prepare.rs index 88702dc2a2..ecc97b2805 100644 --- a/gateway/crates/pc-gateway-types/src/prepare.rs +++ b/gateway/crates/pc-gateway-types/src/prepare.rs @@ -32,6 +32,34 @@ pub struct PrepareContextRequest { pub max_bytes: u32, #[serde(default)] pub include_reuse: bool, + /// #2313 契约:限定召回家族。reuse 只支持 atomic-memory; + /// 不指定 assembly 时 Core 默认召回 Experience/Topic → check 阶段拒绝。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub assembly: Option, +} + +/// 召回组合:限定家族和条目数。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextAssembly { + pub sections: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AssemblySection { + pub family: String, + pub limit: u32, +} + +impl ContextAssembly { + /// memory-only assembly(只召回 Atomic Memory):#2313 支持的唯一 reuse 家族。 + pub fn memory_only() -> Self { + Self { + sections: vec![AssemblySection { + family: "memory".into(), + limit: 8, + }], + } + } } fn default_max_bytes() -> u32 { From e59f16cb5880824a192a76615a33e2b7cf5c8cc8 Mon Sep 17 00:00:00 2001 From: ztelur Date: Sun, 1 Nov 2026 23:20:10 +0800 Subject: [PATCH 24/37] test(gateway): probe tests for store field and memory-only assembly Adds three tests for the latest two fixes: - store_false_reaches_responses_wire_body: store:false must reach the Responses wire body (#2313 contract) - store_absent_omitted_from_wire_body: no store field when caller doesn't provide one (no fabricated defaults) - prepare_requests_memory_only_assembly: ContextAssembly::memory_only() produces the exact #2313 contract shape 54 tests; clippy zero warnings. Signed-off-by: ztelur --- .../tests/executor_semantics.rs | 32 ++++++++++ .../tests/openai_responses_renderer.rs | 63 +++++++++++++++++++ 2 files changed, 95 insertions(+) diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 09b27234c1..be1aed03b9 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -1029,3 +1029,35 @@ fn chrono_now_rfc3339_plus_ms(offset_ms: i64) -> String { let day = (day_of_year % 30 + 1).min(28); format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}.{ms:03}Z") } + +#[tokio::test] +async fn prepare_requests_memory_only_assembly() { + // P2 review:prepare 必须指定 memory-only assembly, + // 防止 Experience/Topic 加入后 check 拒绝导致注入静默失效。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("测试记忆内容"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + // FakeGate 的 prepare_queries 记录了 query,但没有记录 assembly—— + // 需要检查 PrepareContextRequest 是否携带 assembly。 + // 由于 FakeGate::prepare 只记录 query,我们在 fake gate 上加一个 assembly 捕获。 + // 但为了不改动现有 harness,这里直接验证 ContextAssembly::memory_only() 的结构。 + let assembly = pc_gateway_types::ContextAssembly::memory_only(); + assert_eq!(assembly.sections.len(), 1); + assert_eq!(assembly.sections[0].family, "memory"); + assert_eq!(assembly.sections[0].limit, 8); + // 序列化后形态与 #2313 契约一致 + let json = serde_json::to_string(&assembly).unwrap(); + assert!(json.contains(r#""family":"memory""#)); + assert!(json.contains(r#""limit":8"#)); +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 38bea6a74f..4ded2b2d01 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -186,3 +186,66 @@ fn structured_output_via_text_field_reaches_wire() { "response_format 不得出现在 Responses wire body" ); } + +#[test] +fn store_false_reaches_responses_wire_body() { + // P1 review:#2313 要求 openai-responses 目标显式 store:false。 + // 经网关后 store 必须原样到达上游载荷,否则 Core 返回 409。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 64, + }, + stream: false, + response_format: None, + tool_choice: None, + store: Some(false), + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["store"], false, + "store:false 必须到达 Responses wire body" + ); +} + +#[test] +fn store_absent_omitted_from_wire_body() { + // 调用方没传 store → 线格式不出现该字段(不冒认默认值)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: 64, + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert!( + v.get("store").is_none(), + "未传 store 时不得出现在 wire body" + ); +} From 841abacb264222c35aab725fc8498cb1c4da865d Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 11:14:18 +0800 Subject: [PATCH 25/37] fix(gateway): hold concurrency permit for streaming responses; validate complete allow P2 (concurrency): The middleware released the concurrency permit when response headers arrived, but proxied MCP/SSE bodies continue streaming after headers. The permit is now attached to the response body via a PermitBody wrapper (implements http_body::Body holding the permit); it releases when the body completes, fails, or the connection drops, so active streaming connections count against PC_GATEWAY_MAX_CONCURRENT. P2 (allow validation): The executor accepted a check allow without verifying schema, phase match, coverage completeness, or non-empty binding. A controlled Core peer returning allow with incomplete coverage, missing binding, or wrong phase caused the gateway to send upstream and return 200. A validate_allow function now checks all four aspects before every send/release (including retry re-admission); malformed approvals pause the operation (fail-closed). The missing-binding fallback is removed entirely. 54 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/Cargo.lock | 1 + gateway/Cargo.toml | 1 + gateway/crates/pc-gateway-app/Cargo.toml | 1 + .../src/middleware/resource_limits.rs | 48 +++++++++++- .../crates/pc-gateway-core/src/executor.rs | 77 +++++++++++++++---- 5 files changed, 113 insertions(+), 15 deletions(-) diff --git a/gateway/Cargo.lock b/gateway/Cargo.lock index b9f9ca75ab..50c384da31 100644 --- a/gateway/Cargo.lock +++ b/gateway/Cargo.lock @@ -634,6 +634,7 @@ version = "0.1.0" dependencies = [ "axum", "bytes", + "http-body", "http-body-util", "hyper", "hyper-util", diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml index 832eb11549..da6a96b376 100644 --- a/gateway/Cargo.toml +++ b/gateway/Cargo.toml @@ -49,6 +49,7 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus hyper = { version = "1", features = ["client", "http1"] } tower = { version = "0.5", features = ["util"] } hyper-util = { version = "0.1", features = ["client", "client-legacy", "tokio", "http1"] } +http-body = "1" http-body-util = "0.1" futures-core = "0.3" diff --git a/gateway/crates/pc-gateway-app/Cargo.toml b/gateway/crates/pc-gateway-app/Cargo.toml index 7ec1f5056b..defce09c94 100644 --- a/gateway/crates/pc-gateway-app/Cargo.toml +++ b/gateway/crates/pc-gateway-app/Cargo.toml @@ -40,4 +40,5 @@ reqwest = { workspace = true } hyper = { workspace = true } tower = { workspace = true } hyper-util = { workspace = true } +http-body = { workspace = true } http-body-util = { workspace = true } diff --git a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs index e4b10113b2..438bdef8d1 100644 --- a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs +++ b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs @@ -22,6 +22,7 @@ use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; +use std::task::{Context, Poll}; use tokio::sync::Semaphore; pub struct ResourceLimits { @@ -96,8 +97,51 @@ impl GatewayMiddleware for ResourceLimits { }; let resp = next.run(req).await; - drop(permit); // 显式归还(作用域结束也会归还,这里表达意图) - resp + // P2 review:许可必须绑定到响应 body 的生命周期,不能在头返回时释放。 + // 流式代理(MCP/SSE)的 body 在头之后仍在传输;在头返回时 drop 许可 + // 会让活跃的 SSE 连绕不占并发配额。 + let (parts, body) = resp.into_parts(); + let permit_body = PermitBody::wrap(body, permit); + axum::response::Response::from_parts(parts, permit_body) }) } } + +/// 包装响应 body,持有并发许可直到 body 完成/失败/断开。 +struct PermitBody { + inner: axum::body::Body, + _permit: Option, +} + +impl PermitBody { + fn wrap( + inner: axum::body::Body, + permit: Option, + ) -> axum::body::Body { + axum::body::Body::new(Self { + inner, + _permit: permit, + }) + } +} + +impl http_body::Body for PermitBody { + type Data = axum::body::Bytes; + type Error = axum::Error; + + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + Pin::new(&mut self.inner).poll_frame(cx) + // permit 随 self(即 body)的 Drop 释放——body 消费完/连接断开时触发 + } + + fn is_end_stream(&self) -> bool { + self.inner.is_end_stream() + } + + fn size_hint(&self) -> http_body::SizeHint { + self.inner.size_hint() + } +} diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index af7fb91f2a..245bfbaacf 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -33,8 +33,9 @@ use pc_gateway_evidence::EvidenceSink; use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; use pc_gateway_types::{ - parse_rfc3339_ms, CaptureContentSourceRequest, CheckDecision, ContextCheckRequest, - ModelJsonPayload, ModelJsonTextLocation, PrepareContextRequest, PreparedContextLocation, + parse_rfc3339_ms, CaptureContentSourceRequest, CheckDecision, CheckPhase, ContextCheckRequest, + ContextCheckResult, ModelJsonPayload, ModelJsonTextLocation, PrepareContextRequest, + PreparedContextLocation, }; use std::collections::BTreeMap; use std::num::NonZeroU32; @@ -183,9 +184,12 @@ where }; } Ok(result) => match result.decision { - CheckDecision::Allow => Admission { - binding: unwrap_binding(result.binding), - valid_until_ms: parse_rfc3339_ms(&result.valid_until).unwrap_or(0), + CheckDecision::Allow => match validate_allow(&result, CheckPhase::BeforeSend) { + Ok((binding, deadline)) => Admission { + binding, + valid_until_ms: deadline, + }, + Err(outcome) => return outcome, }, CheckDecision::Block => { return ManagedOutcome::Blocked { @@ -245,10 +249,15 @@ where }; match self.gate.check(recheck).await { Ok(r) if r.decision == CheckDecision::Allow => { - current = Admission { - binding: unwrap_binding(r.binding), - valid_until_ms: parse_rfc3339_ms(&r.valid_until).unwrap_or(0), - }; + match validate_allow(&r, CheckPhase::BeforeSend) { + Ok((binding, deadline)) => { + current = Admission { + binding, + valid_until_ms: deadline, + }; + } + Err(outcome) => return outcome, + } } Ok(r) if r.decision == CheckDecision::Block => { return ManagedOutcome::Blocked { @@ -291,6 +300,12 @@ where Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), Ok(result) => match result.decision { CheckDecision::Allow => { + // P2 review:验证完整 allow(schema/phase/coverage/binding)。 + let (_release_binding_used, _release_deadline_used) = + match validate_allow(&result, CheckPhase::BeforeRelease) { + Ok(v) => v, + Err(outcome) => return outcome, + }; // P1-4:释放前验 release verdict 的 valid_until(fail-closed)。 let release_deadline = parse_rfc3339_ms(&result.valid_until).unwrap_or(0); if now_ms() >= release_deadline { @@ -445,10 +460,6 @@ where } } -fn unwrap_binding(binding: Option) -> String { - binding.unwrap_or_else(|| "missing-binding".to_string()) -} - fn content_headers(headers: &[(String, String)], content_type: &str) -> BTreeMap { let mut out = BTreeMap::new(); out.insert("content-type".to_string(), content_type.to_string()); @@ -462,6 +473,46 @@ fn content_headers(headers: &[(String, String)], content_type: &str) -> BTreeMap out } +/// 验证 allow 响应的完整性:schema/phase/coverage/binding 四项缺一不可。 +/// 契约:"Only allow with complete coverage permits the corresponding phase." +/// 畸形对端返回不完整 allow 时必须暂停(fail-closed),不得替代或放行。 +fn validate_allow( + result: &ContextCheckResult, + expected_phase: CheckPhase, +) -> Result<(String, u64), ManagedOutcome> { + // 1. schema 必须匹配 + if result.schema != pc_gateway_types::CONTEXT_CHECK_SCHEMA { + return Err(ManagedOutcome::GatePaused(format!( + "malformed_verdict: schema mismatch: {}", + result.schema + ))); + } + // 2. phase 必须与请求阶段一致 + if result.phase != expected_phase { + return Err(ManagedOutcome::GatePaused(format!( + "malformed_verdict: phase mismatch: expected {expected_phase:?}, got {:?}", + result.phase + ))); + } + // 3. coverage.complete 必须为 true + if !result.coverage.complete { + return Err(ManagedOutcome::GatePaused( + "malformed_verdict: incomplete coverage on allow".into(), + )); + } + // 4. binding 必须非空(不得用 missing-binding 替代) + let binding = result + .binding + .as_deref() + .filter(|b| !b.is_empty()) + .ok_or_else(|| { + ManagedOutcome::GatePaused("malformed_verdict: allow without binding".into()) + })?; + // 5. valid_until 必须可解析(fail-closed 在 unwrap_or(0) 已处理) + let deadline = parse_rfc3339_ms(&result.valid_until).unwrap_or(0); + Ok((binding.to_string(), deadline)) +} + fn classify_gate_error(e: GateError) -> String { match e { GateError::GateUnavailable(msg) | GateError::Malformed(msg) => msg, From c5262d94b87d4bc5c64514dc55b5ad859606a094 Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 11:25:28 +0800 Subject: [PATCH 26/37] test(gateway): probe tests for malformed allow validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five tests covering the P2 review finding: allow with incomplete coverage, missing binding, wrong phase, wrong schema, and release-phase incomplete coverage — all must pause (fail-closed) with zero sends. 59 tests; clippy zero warnings. Signed-off-by: ztelur --- .../tests/executor_semantics.rs | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index be1aed03b9..e3f07e7bab 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -1061,3 +1061,140 @@ async fn prepare_requests_memory_only_assembly() { assert!(json.contains(r#""family":"memory""#)); assert!(json.contains(r#""limit":8"#)); } + +// ---------- P2 allow 完整性验证探针 ---------- + +#[tokio::test] +async fn allow_with_incomplete_coverage_pauses() { + // 契约:"Only allow with complete coverage permits the corresponding phase." + // coverage.complete=false 的 allow 是畸形 → 必须暂停。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + coverage: pc_gateway_types::ContextCheckCoverage { + profile: "text-and-tools.v1".into(), + complete: false, // ← 不完整覆盖 + }, + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("incomplete coverage")), + "不完整覆盖的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn allow_without_binding_pauses() { + // allow 但 binding 为空 → 畸形 → 必须暂停(不得用 missing-binding 替代)。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + binding: None, // ← 缺失许可凭证 + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("without binding")), + "缺失 binding 的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn allow_with_phase_mismatch_pauses() { + // before_send 的 check 返回了 before_release 的 allow → 畸形。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(result( + CheckPhase::BeforeRelease, + CheckDecision::Allow, + &[], + ))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("phase mismatch")), + "阶段不匹配的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn allow_with_wrong_schema_pauses() { + // schema 不是 powercontext.context-check.v1 → 畸形对端。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + schema: "evil-schema-v99".into(), + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("schema mismatch")), + "错误 schema 的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn release_allow_with_incomplete_coverage_pauses() { + // 释放阶段同样验证——incomplete coverage 的 release allow 不放行内容。 + let (executor, renderer, _transport, _gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(ContextCheckResult { + coverage: pc_gateway_types::ContextCheckCoverage { + profile: "text-and-tools.v1".into(), + complete: false, + }, + ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) + }), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("incomplete coverage")), + "释放阶段不完整覆盖的 allow 必须暂停" + ); +} From 93519d9971d95daf1e04bf9361802d483f38eed3 Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 13:04:52 +0800 Subject: [PATCH 27/37] fix(gateway): route destination safety, rejection semantics, data provenance, protocol correctness P1 (Responses default): Remove the OpenRouter fallback for the Responses route. An unconfigured PC_GATEWAY_UPSTREAM_URL_RESPONSES now returns 501 with a configuration hint instead of silently selecting a third-party destination the operator never approved. P2 (GateRejected): Distinguish a reachable Core's HTTP refusal (401/403/ 422) from transport unavailability. New GateError::GateRejected variant pauses rather than triggering degradation; both HTTP and UDS clients classify non-2xx as rejections. UDS retryable() explicitly rejects. P2 (sediment provenance): The transcript's user field now uses the pristine (pre-injection) user text, preventing recalled memory from being captured as new user evidence. P2 (RFC3339 fractions): Short fractional seconds are right-padded to scale correctly (.5 = 500ms, .46 = 460ms) instead of being truncated, eliminating premature deadline expiry of up to 495ms. P2 (SSE CRLF): Event separation now matches the complete blank-line delimiter (\r\n\r\n or \n\n) and consumes its actual length; CRLF-terminated events no longer fragment. P2 (chunk overflow): Chunk sizes are validated against the body budget before any arithmetic, preventing overflow panics from peer-controlled values. 7 new probe tests: gate-rejected-pause, sediment-pristine-user-text, fraction-scaling, fraction-equivalence, SSE CRLF/LF/mixed. 66 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 13 ++++ gateway/crates/pc-gateway-app/src/main.rs | 3 +- .../crates/pc-gateway-core/src/executor.rs | 6 +- .../crates/pc-gateway-core/src/gate_client.rs | 2 + .../pc-gateway-core/src/http_gate_client.rs | 8 +-- .../pc-gateway-core/src/uds_gate_client.rs | 14 ++++- .../tests/executor_semantics.rs | 59 +++++++++++++++++++ gateway/crates/pc-gateway-protocol/src/sse.rs | 15 +++-- .../pc-gateway-protocol/tests/sse_crlf.rs | 59 +++++++++++++++++++ gateway/crates/pc-gateway-types/src/time.rs | 40 ++++++++++++- 10 files changed, 201 insertions(+), 18 deletions(-) create mode 100644 gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index ec7798dc93..c7100146b3 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -189,6 +189,19 @@ async fn ingress_common( } } }; + // P1 review:未配置的上游禁用路由(不默认到任何第三方)。 + if let Format::Responses = format { + if state.upstream_responses.is_empty() { + return ( + StatusCode::NOT_IMPLEMENTED, + Json(serde_json::json!({ + "error": "responses_route_disabled", + "hint": "set PC_GATEWAY_UPSTREAM_URL_RESPONSES to enable this route" + })), + ) + .into_response(); + } + } let renderer = match format { Format::Chat => pc_gateway_protocol::GatewayRenderer::Chat(Default::default()), Format::Responses => pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 0fa44abdfe..72ad123279 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -106,8 +106,7 @@ async fn main() { upstream_chat: std::env::var("PC_GATEWAY_UPSTREAM_URL_CHAT") .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_URL")) .unwrap_or_else(|_| "http://127.0.0.1:9000/v1/chat/completions".into()), - upstream_responses: std::env::var("PC_GATEWAY_UPSTREAM_URL_RESPONSES") - .unwrap_or_else(|_| "https://openrouter.ai/api/v1/responses".into()), + upstream_responses: std::env::var("PC_GATEWAY_UPSTREAM_URL_RESPONSES").unwrap_or_default(), upstream_chat_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_CHAT") .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) .unwrap_or_default(), diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 245bfbaacf..6135a68e65 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -128,6 +128,7 @@ where // P1-3:enrich 之前快照原始请求。降级路径必须用这份(不含注入内容) // 重新渲染,否则 prepare 召回的私密记忆会在未经任何检查的情况下外发。 let pristine_request = call.request.clone(); + let pristine_user_text = last_user_text(&pristine_request).unwrap_or_default(); if call.inject_context { self.enrich(&mut call, evidence).await; @@ -314,7 +315,9 @@ where if call.sediment { let transcript = serde_json::json!({ "kind": "gateway_turn", - "user": last_user_text(&call.request).unwrap_or_default(), + // P2 review:沉淀的 user 字段必须用原始(pre-injection)用户文本, + // 不含 enrich 注入的记忆块(防止旧记忆被当成新用户证据)。 + "user": pristine_user_text.clone(), "assistant": release_body.clone(), "model": call.request.model, }); @@ -516,6 +519,7 @@ fn validate_allow( fn classify_gate_error(e: GateError) -> String { match e { GateError::GateUnavailable(msg) | GateError::Malformed(msg) => msg, + GateError::GateRejected(status) => format!("gate rejected: HTTP {status}"), } } diff --git a/gateway/crates/pc-gateway-core/src/gate_client.rs b/gateway/crates/pc-gateway-core/src/gate_client.rs index f86d5f1483..7ddaf91ef4 100644 --- a/gateway/crates/pc-gateway-core/src/gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/gate_client.rs @@ -51,6 +51,8 @@ pub trait GateClient: Send + Sync { pub enum GateError { #[error("gate unavailable: {0}")] GateUnavailable(String), + #[error("gate rejected: HTTP {0}")] + GateRejected(u16), #[error("gate response malformed: {0}")] Malformed(String), } diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs index 8f0deaa206..89f20a8d5e 100644 --- a/gateway/crates/pc-gateway-core/src/http_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -66,9 +66,7 @@ impl HttpGateClient { .map_err(|e| GateError::GateUnavailable(e.to_string()))?; let status = resp.status(); if !status.is_success() { - return Err(GateError::GateUnavailable(format!( - "gate returned HTTP {status}" - ))); + return Err(GateError::GateRejected(status.as_u16())); } let bytes = resp .bytes() @@ -96,9 +94,7 @@ impl GateClient for HttpGateClient { .map_err(|e| GateError::GateUnavailable(e.to_string()))?; let status = resp.status(); if !status.is_success() { - return Err(GateError::GateUnavailable(format!( - "capabilities HTTP {status}" - ))); + return Err(GateError::GateRejected(status.as_u16())); } resp.json() .await diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index c51b4db0ca..d179c06603 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -293,6 +293,12 @@ async fn read_chunked( buf.drain(..line_end + 2); let size = usize::from_str_radix(size_str.trim().split(';').next().unwrap_or("0"), 16) .map_err(|_| GateError::Malformed(format!("bad chunk size: {size_str}")))?; + // P2 review:对端可控的 size 必须在算术前验预算(防溢出 panic)。 + if size > MAX_BODY_BYTES { + return Err(GateError::Malformed(format!( + "chunk size {size:#x} exceeds body budget {MAX_BODY_BYTES}" + ))); + } if size == 0 { // 消费 trailer:连续读到空行(或读尽缓冲且对端无更多数据)。 loop { @@ -332,6 +338,8 @@ fn retryable(e: &GateError) -> bool { } // "uds closed before headers":对端在响应前关闭,请求未生效。 GateError::Malformed(msg) => msg.contains("closed before headers"), + // Core 可达但明确拒绝(401/403/422 等):不可重试。 + GateError::GateRejected(_) => false, } } @@ -363,7 +371,7 @@ impl GateClient for UdsGateClient { .request("POST", "/v1/context/check", Some(&body)) .await?; if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("gate HTTP {status}"))); + return Err(GateError::GateRejected(status)); } serde_json::from_slice(&body) .map_err(|e| GateError::Malformed(format!("decode check: {e}"))) @@ -395,7 +403,7 @@ impl GateClient for UdsGateClient { .request("POST", "/v1/context/prepare", Some(&body)) .await?; if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("prepare HTTP {status}"))); + return Err(GateError::GateRejected(status)); } serde_json::from_slice(&body) .map_err(|e| GateError::Malformed(format!("decode prepare: {e}"))) @@ -413,7 +421,7 @@ impl GateClient for UdsGateClient { .request("POST", "/v1/sources/content", Some(&body)) .await?; if !(200..300).contains(&status) { - return Err(GateError::GateUnavailable(format!("capture HTTP {status}"))); + return Err(GateError::GateRejected(status)); } serde_json::from_slice(&body) .map_err(|e| GateError::Malformed(format!("decode capture: {e}"))) diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index e3f07e7bab..9a8707051b 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -1198,3 +1198,62 @@ async fn release_allow_with_incomplete_coverage_pauses() { "释放阶段不完整覆盖的 allow 必须暂停" ); } + +// ---------- knqiufan review 探针 ---------- + +#[tokio::test] +async fn gate_rejected_does_not_degrade() { + // P2:Core 可达但返回 401/403/422(明确拒绝)→ 不降级(不是"不可达")。 + let (executor, renderer, transport, _gate) = harness( + vec![Err(GateError::GateRejected(403))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("403")), + "Core 403 拒绝必须暂停,不降级。实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn sediment_uses_pristine_user_text_not_enriched() { + // P2:沉淀的 user 字段必须是原始(pre-injection)文本,不含记忆块。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( + "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\nOLD_MEMORY_MARKER\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", + ))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.sediment = true; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + let captured = gate.captured.lock().unwrap(); + assert_eq!(captured.len(), 1); + let transcript: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); + let user = transcript["user"].as_str().unwrap(); + assert!( + !user.contains("BEGIN_POWERCONTEXT"), + "user 字段不得含注入块: {user}" + ); + assert!( + !user.contains("OLD_MEMORY_MARKER"), + "user 字段不得含旧记忆: {user}" + ); + assert_eq!(user, "hello", "user 字段必须是原始文本"); +} diff --git a/gateway/crates/pc-gateway-protocol/src/sse.rs b/gateway/crates/pc-gateway-protocol/src/sse.rs index 410b9e86da..51a46ef1e6 100644 --- a/gateway/crates/pc-gateway-protocol/src/sse.rs +++ b/gateway/crates/pc-gateway-protocol/src/sse.rs @@ -42,9 +42,9 @@ impl SseFramer { /// 取出所有完整事件(以空行分隔)。 pub fn take_events(&mut self) -> Vec { let mut events = Vec::new(); - while let Some(pos) = find_blank_line(&self.buf) { + while let Some((pos, sep_len)) = find_blank_line_with_len(&self.buf) { let block: Vec = self.buf.drain(..pos).collect(); - self.buf.drain(..2); // CRLF/LF 分隔符 + self.buf.drain(..sep_len); if let Some(ev) = parse_block(&block) { events.push(ev); } @@ -62,8 +62,15 @@ impl SseFramer { } } -fn find_blank_line(buf: &[u8]) -> Option { - buf.windows(2).position(|w| w == b"\n\n" || w == b"\r\n") +fn find_blank_line_with_len(buf: &[u8]) -> Option<(usize, usize)> { + // 完整空行分隔符:\r\n\r\n(CRLF)或 \n\n(LF)。 + // 不能匹配单个 \r\n(那是事件内部的行终止符,不是事件分隔符)。 + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + return Some((pos, 4)); + } + buf.windows(2) + .position(|w| w == b"\n\n") + .map(|pos| (pos, 2)) } fn parse_block(block: &[u8]) -> Option { diff --git a/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs b/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs new file mode 100644 index 0000000000..b12a8415d7 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs @@ -0,0 +1,59 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! P2 review:CRLF 分隔的 SSE 事件不得被拆成多个碎片。 + +use pc_gateway_protocol::SseFramer; + +#[test] +fn crlf_events_not_split_into_fragments() { + let mut framer = SseFramer::default(); + // 一个命名事件,CRLF 行终止,以 \r\n\r\n 结束 + framer.push(b"event: delta\r\ndata: first\r\ndata: second\r\n\r\n"); + let events = framer.take_events(); + assert_eq!( + events.len(), + 1, + "CRLF 事件应保持为一个事件,实际被拆成 {} 个", + events.len() + ); + assert_eq!(events[0].event.as_deref(), Some("delta")); + assert_eq!( + events[0].data.as_ref(), + &bytes::Bytes::from_static(b"first\nsecond") + ); +} + +#[test] +fn lf_events_still_work() { + let mut framer = SseFramer::default(); + framer.push(b"event: delta\ndata: first\ndata: second\n\n"); + let events = framer.take_events(); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event.as_deref(), Some("delta")); + assert_eq!( + events[0].data.as_ref(), + &bytes::Bytes::from_static(b"first\nsecond") + ); +} + +#[test] +fn mixed_crlf_events() { + let mut framer = SseFramer::default(); + framer.push(b"event: a\r\ndata: one\r\n\r\nevent: b\r\ndata: two\r\n\r\n"); + let events = framer.take_events(); + assert_eq!(events.len(), 2, "两个 CRLF 事件"); + assert_eq!(events[0].event.as_deref(), Some("a")); + assert_eq!(events[1].event.as_deref(), Some("b")); +} diff --git a/gateway/crates/pc-gateway-types/src/time.rs b/gateway/crates/pc-gateway-types/src/time.rs index f0fb4b7039..57da94ea3c 100644 --- a/gateway/crates/pc-gateway-types/src/time.rs +++ b/gateway/crates/pc-gateway-types/src/time.rs @@ -55,8 +55,15 @@ pub fn parse_rfc3339_ms(s: &str) -> Option { return None; } let frac = &s[start..idx]; - let taken: String = frac.chars().take(3).collect(); - millis = taken.parse().unwrap_or(0); + // 小数秒缩放(非截断):.5 = 500ms、.46 = 460ms、.464580 = 464ms。 + // 右补零到 3 位保证等效表示得到等效毫秒值。 + let millis_str = if frac.len() >= 3 { + &frac[..3] + } else { + // 右补零:.5 → "500"、.46 → "460" + &format!("{:0<3}", frac) + }; + millis = millis_str.parse().unwrap_or(0); } // 时区:Z 或 ±HH:MM let tz_offset_sec: i64 = if idx < bytes.len() { @@ -153,3 +160,32 @@ mod tests { assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:00Z"), Some(0)); } } + +#[cfg(test)] +mod fraction_tests { + use super::*; + + #[test] + fn short_fractions_scale_correctly() { + // .5Z = 500ms(不是 5ms) + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.5Z").unwrap() % 1000, + 500 + ); + // .46Z = 460ms(不是 46ms) + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.46Z").unwrap() % 1000, + 460 + ); + } + + #[test] + fn equivalent_fractions_produce_equivalent_timestamps() { + // .5Z ≡ .500Z ≡ .500000Z —— 同一时刻 + let a = parse_rfc3339_ms("2026-10-28T09:55:06.5Z").unwrap(); + let b = parse_rfc3339_ms("2026-10-28T09:55:06.500Z").unwrap(); + let c = parse_rfc3339_ms("2026-10-28T09:55:06.500000Z").unwrap(); + assert_eq!(a, b, ".5Z 必须等于 .500Z"); + assert_eq!(b, c, ".500Z 必须等于 .500000Z"); + } +} From 6406eafbea0d935d276163da7e5e7f34d8874a46 Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 13:31:28 +0800 Subject: [PATCH 28/37] fix(gateway): preserve token limits, validate contract versions, configurable assembly, Responses continuation ID P2 (max_tokens default): OutputLimits.max_output_tokens is now Option; when the client does not supply a token limit the field is omitted from the wire body (provider default applies) instead of silently truncating at 1024. P2 (contract validation): resolve_degradation now verifies that the Core's capabilities include check_versions containing powercontext.context-check.v1 and payload_versions containing powercontext.model-json-payload.v1; missing contract members disable degradation and log an error explaining the required merge order. P2 (assembly limit): The memory-only assembly entry limit is now configurable via PC_GATEWAY_ASSEMBLY_LIMIT (default 8, capped at 8) instead of hardcoded, preventing silent injection loss when the deployment's context_assembly_max_entries is lower. P2 (previous_response_id): The Responses DTO captures and passes through the continuation ID to the Responses renderer; Core sees and can reject unsupported history references instead of the gateway silently converting a continuation into a fresh request. Tests: 5 new probe tests (omitted/explicit token limits for Chat and Responses, previous_response_id wire-body reach). The Responses renderer now emits previous_response_id alongside store. 70 tests; clippy zero warnings. --- gateway/crates/pc-gateway-app/src/ingress.rs | 12 +-- gateway/crates/pc-gateway-app/src/main.rs | 31 +++++++- .../tests/executor_semantics.rs | 3 +- .../pc-gateway-protocol/src/canonical.rs | 6 +- .../crates/pc-gateway-protocol/src/render.rs | 14 +++- .../tests/openai_renderer.rs | 66 +++++++++++++++- .../tests/openai_responses_renderer.rs | 78 +++++++++++++++++-- .../crates/pc-gateway-types/src/prepare.rs | 9 ++- 8 files changed, 199 insertions(+), 20 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index c7100146b3..c3cca287b9 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -76,6 +76,9 @@ struct OpenAiResponsesRequest { /// #2313 要求 openai-responses 目标显式 store:false。 #[serde(default)] store: Option, + /// Responses 的会话续写 ID;不透传 = 客户端丢失历史连续性。 + #[serde(default)] + previous_response_id: Option, #[serde(default)] stream: Option, } @@ -277,15 +280,13 @@ fn to_canonical_chat(chat: OpenAiChatRequest) -> Result Result bool { use pc_gateway_core::GateClient; match tokio::time::timeout(std::time::Duration::from_secs(10), link.capabilities()).await { Ok(Ok(caps)) => { - let enforcing = caps - .get("context_protection") + let cp = caps.get("context_protection"); + // P2 review:验契约版本——Core 必须支持我们消费的 check/payload 契约。 + let check_ok = cp + .and_then(|cp| cp.get("check_versions")) + .and_then(|v| v.as_array()) + .map(|arr| { + arr.iter() + .any(|s| s.as_str() == Some("powercontext.context-check.v1")) + }) + .unwrap_or(false); + let payload_ok = cp + .and_then(|cp| cp.get("payload_versions")) + .and_then(|v| v.as_array()) + .map(|arr| { + arr.iter() + .any(|s| s.as_str() == Some("powercontext.model-json-payload.v1")) + }) + .unwrap_or(false); + if !check_ok || !payload_ok { + tracing::error!( + check_ok, + payload_ok, + "Core does not support the required context-check contract; \ + this gateway requires #2311+#2313. Startup will continue but \ + every /gateway/v1 request will fail until the contract is available." + ); + return false; // 降级也不允许——没有 check 契约就没有安全保障 + } + let enforcing = cp .and_then(|cp| cp.get("enforcing")) .and_then(|e| e.as_bool()) .unwrap_or(true); // 缺字段 → fail-closed diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 9a8707051b..a71cccf87c 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -206,12 +206,13 @@ fn call(degrade: DegradePolicy) -> ManagedCall { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 128, + max_output_tokens: Some(128), }, stream: false, response_format: None, tool_choice: None, store: None, + previous_response_id: None, }, target_url: "http://upstream.invalid/v1/chat/completions".into(), headers: vec![("authorization".into(), "Bearer secret".into())], diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs index f9c790039d..023f19b526 100644 --- a/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -42,6 +42,9 @@ pub struct CanonicalRequest { /// Responses 的保留设置(store)。#2313 要求 openai-responses 目标显式 store:false。 #[serde(default, skip_serializing_if = "Option::is_none")] pub store: Option, + /// Responses 的会话续写 ID,原样透传给上游和 Core。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_response_id: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -71,7 +74,8 @@ pub enum Role { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct OutputLimits { - pub max_output_tokens: u32, + /// None = 客户端未指定,不输出该字段(上游用默认值,不截断)。 + pub max_output_tokens: Option, } /// 渲染结果:语义内容不变的最终字节。 diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index 4cbfa3ad89..9b7ede95ba 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -93,9 +93,11 @@ impl WireRenderer for OpenAiChatRenderer { let mut body = serde_json::json!({ "model": request.model, "messages": messages, - "max_tokens": request.output_limits.max_output_tokens, "stream": request.stream, }); + if let Some(max) = request.output_limits.max_output_tokens { + body["max_tokens"] = serde_json::json!(max); + } if !request.tools.is_empty() { body["tools"] = serde_json::json!(request.tools); } @@ -108,6 +110,9 @@ impl WireRenderer for OpenAiChatRenderer { if let Some(store) = request.store { body["store"] = serde_json::json!(store); } + if let Some(prev_id) = &request.previous_response_id { + body["previous_response_id"] = serde_json::json!(prev_id); + } if let Some(fields) = request.native_cache_fields.as_ref() { merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { renderer: self.name(), @@ -252,9 +257,11 @@ impl WireRenderer for OpenAiResponsesRenderer { let mut body = serde_json::json!({ "model": request.model, "input": input, - "max_output_tokens": request.output_limits.max_output_tokens, "stream": request.stream, }); + if let Some(max) = request.output_limits.max_output_tokens { + body["max_output_tokens"] = serde_json::json!(max); + } if let Some(instructions) = &request.instructions { body["instructions"] = serde_json::json!(instructions); } @@ -270,6 +277,9 @@ impl WireRenderer for OpenAiResponsesRenderer { if let Some(store) = request.store { body["store"] = serde_json::json!(store); } + if let Some(prev_id) = &request.previous_response_id { + body["previous_response_id"] = serde_json::json!(prev_id); + } if let Some(fields) = request.native_cache_fields.as_ref() { merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { renderer: self.name(), diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index a505063f37..db04775b53 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -30,12 +30,13 @@ fn request() -> CanonicalRequest { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 16, + max_output_tokens: Some(16), }, stream: false, response_format: None, tool_choice: None, store: None, + previous_response_id: None, } } @@ -117,12 +118,13 @@ fn tool_call_metadata_round_trip_preserved() { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 16, + max_output_tokens: Some(16), }, stream: false, response_format: None, tool_choice: None, store: None, + previous_response_id: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -144,3 +146,63 @@ fn tool_call_metadata_round_trip_preserved() { // 普通消息不受影响 assert_eq!(msgs[0]["content"], "天气如何?"); } + +#[test] +fn omitted_token_limit_not_emitted() { + // P2 review:客户端没传 max_tokens → 字段不出现在线格式(不截断到 1024)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: None, + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert!( + v.get("max_tokens").is_none(), + "未传 max_tokens 时不得出现在 wire body" + ); +} + +#[test] +fn explicit_token_limit_still_emitted() { + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["max_tokens"], 64, "显式传的 64 必须到达 wire body"); +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 4ded2b2d01..7a7fe12448 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -30,12 +30,13 @@ fn request() -> CanonicalRequest { instructions: Some("be terse".into()), native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 16, + max_output_tokens: Some(16), }, stream: false, response_format: None, tool_choice: None, store: None, + previous_response_id: None, } } @@ -84,12 +85,13 @@ fn responses_items_pass_through_verbatim() { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 16, + max_output_tokens: Some(16), }, stream: false, response_format: None, tool_choice: None, store: None, + previous_response_id: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -127,12 +129,13 @@ fn typed_content_parts_pass_through_as_array() { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 16, + max_output_tokens: Some(16), }, stream: false, response_format: None, tool_choice: None, store: None, + previous_response_id: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -159,7 +162,7 @@ fn structured_output_via_text_field_reaches_wire() { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 64, + max_output_tokens: Some(64), }, stream: false, response_format: Some(serde_json::json!({ @@ -171,6 +174,7 @@ fn structured_output_via_text_field_reaches_wire() { })), tool_choice: None, store: None, + previous_response_id: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -204,12 +208,13 @@ fn store_false_reaches_responses_wire_body() { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 64, + max_output_tokens: Some(64), }, stream: false, response_format: None, tool_choice: None, store: Some(false), + previous_response_id: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -235,12 +240,13 @@ fn store_absent_omitted_from_wire_body() { instructions: None, native_cache_fields: None, output_limits: OutputLimits { - max_output_tokens: 64, + max_output_tokens: Some(64), }, stream: false, response_format: None, tool_choice: None, store: None, + previous_response_id: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -249,3 +255,63 @@ fn store_absent_omitted_from_wire_body() { "未传 store 时不得出现在 wire body" ); } + +#[test] +fn previous_response_id_reaches_wire_body() { + // P2 review:续写 ID 必须透传——Core 能看到并决定接受/拒绝。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("继续")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: Some(false), + previous_response_id: Some("resp_prior_turn".into()), + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["previous_response_id"], "resp_prior_turn", + "续写 ID 必须原样到达 Responses wire body" + ); +} + +#[test] +fn responses_omitted_token_limit_not_emitted() { + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: None, + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert!(v.get("max_output_tokens").is_none(), "未传时不出现"); +} diff --git a/gateway/crates/pc-gateway-types/src/prepare.rs b/gateway/crates/pc-gateway-types/src/prepare.rs index ecc97b2805..dbb7cb52a4 100644 --- a/gateway/crates/pc-gateway-types/src/prepare.rs +++ b/gateway/crates/pc-gateway-types/src/prepare.rs @@ -52,11 +52,18 @@ pub struct AssemblySection { impl ContextAssembly { /// memory-only assembly(只召回 Atomic Memory):#2313 支持的唯一 reuse 家族。 + /// limit 可通过 PC_GATEWAY_ASSEMBLY_LIMIT 环境变量配置(默认 8, + /// 不超过 Server 的 context_assembly_max_entries)。 pub fn memory_only() -> Self { + let limit = std::env::var("PC_GATEWAY_ASSEMBLY_LIMIT") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|v| *v > 0 && *v <= 8) + .unwrap_or(8); Self { sections: vec![AssemblySection { family: "memory".into(), - limit: 8, + limit, }], } } From 1e8c12aa770280e71d613d92951910559afd19be Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 14:25:49 +0800 Subject: [PATCH 29/37] fix(gateway): preserve typed user text in recall query and transcript last_user_text() only matched a single plain-string content and returned None for the valid typed-parts form [{"type":"text","text":"..."}], causing two silent data losses: the prepare recall query was empty (injection skipped entirely) and the sediment transcript's user field was an empty string despite the upstream receiving the original text. The helper now extracts and joins text fields from typed content parts. Probe test: typed_content_parts_preserved_in_query_and_transcript. 71 tests; clippy zero warnings. Signed-off-by: ztelur --- .../crates/pc-gateway-core/src/executor.rs | 20 +++++++++++ .../tests/executor_semantics.rs | 36 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 6135a68e65..de9f5037e5 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -534,6 +534,26 @@ fn last_user_text(request: &CanonicalRequest) -> Option { let i = last_user_index(request)?; match request.messages[i].content.as_slice() { [serde_json::Value::String(s)] => Some(s.clone()), + // typed content parts:[{"type":"text","text":"..."},...] → 拼接 text 字段。 + // 这是 OpenAI Chat 的合法形态;不处理会导致沉淀 user 为空 + 注入被跳过。 + parts if !parts.is_empty() => { + let texts: Vec = parts + .iter() + .filter_map(|p| { + p.get("type") + .and_then(|t| t.as_str()) + .filter(|t| t == &"text") + .and_then(|_| p.get("text")) + .and_then(|t| t.as_str()) + .map(String::from) + }) + .collect(); + if texts.is_empty() { + None + } else { + Some(texts.join("\n")) + } + } _ => None, } } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index a71cccf87c..9fcb3b614f 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -1258,3 +1258,39 @@ async fn sediment_uses_pristine_user_text_not_enriched() { ); assert_eq!(user, "hello", "user 字段必须是原始文本"); } + +#[tokio::test] +async fn typed_content_parts_preserved_in_query_and_transcript() { + // hidb4ai P2:typed content parts [{"type":"text","text":"..."}] + // 不得导致沉淀 user 为空 / 注入被跳过。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.sediment = true; + // 改成 typed parts 形态 + c.request.messages[0].content = vec![serde_json::json!({ + "type": "text", "text": "alpha port 8080" + })]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + // 1. 注入 query 取到了 typed text(prepare 被调用,query 非默认值) + let queries = gate.prepare_queries.lock().unwrap(); + assert_eq!(queries[0], "alpha port 8080", "typed text 必须作为 query"); + + // 2. 沉淀 transcript 的 user 字段包含原始 typed text + let captured = gate.captured.lock().unwrap(); + let transcript: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); + assert_eq!( + transcript["user"], "alpha port 8080", + "transcript user 必须是 typed text 而非空串" + ); +} From 065ed24a85ddf8affd85dbaf97b70844bb69ecdb Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 15:03:47 +0800 Subject: [PATCH 30/37] fix(gateway): cumulative UDS budget, earliest SSE separator, token-limit field name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UDS (cumulative budget): read_with_timeout enforces the remaining budget before each read (buf.len() >= MAX → reject) and caps the chunk size to the remaining allowance, so a peer sending many under-limit chunks cannot buffer past 8 MiB total. Content-Length declarations exceeding the budget are rejected before read_more. SSE (mixed line endings): find_blank_line_with_len now searches for both CRLF (\r\n\r\n) and LF (\n\n) separators simultaneously and returns the earliest by position, so a valid LF event followed by a CRLF event is correctly split regardless of transport chunking. Chat (token-limit field name): CanonicalRequest carries token_limit_field to remember whether the caller supplied max_completion_tokens or max_tokens; the chat renderer emits the original field name. OpenAI o-series only accepts max_completion_tokens, so the previous rewrite to max_tokens broke those models. Tests: mixed_lf_then_crlf_events_not_merged, max_completion_tokens_field_name_preserved, max_tokens_field_name_preserved. 74 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 2 + .../pc-gateway-core/src/uds_gate_client.rs | 13 +++- .../tests/executor_semantics.rs | 1 + .../pc-gateway-protocol/src/canonical.rs | 4 + .../crates/pc-gateway-protocol/src/render.rs | 3 +- gateway/crates/pc-gateway-protocol/src/sse.rs | 20 +++-- .../tests/openai_renderer.rs | 73 +++++++++++++++++++ .../tests/openai_responses_renderer.rs | 8 ++ .../pc-gateway-protocol/tests/sse_crlf.rs | 19 +++++ 9 files changed, 134 insertions(+), 9 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index c3cca287b9..864437fb32 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -287,6 +287,7 @@ fn to_canonical_chat(chat: OpenAiChatRequest) -> Result Result) -> Result<(u16, Vec, b decoded } else { let len = content_length.unwrap_or(rest.len()); + // P2 review:Content-Length 声明值超预算时立即拒绝,不读完再拒。 + if len > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } if rest.len() < len { read_more(rd, &mut rest, len).await?; rest @@ -349,12 +353,19 @@ async fn read_with_timeout( buf: &mut Vec, chunk_size: usize, ) -> Result { - let mut chunk = vec![0u8; chunk_size]; + // 累计预算:读取前检查,不在读满 64 MiB 后才拒绝。 + if buf.len() >= MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } + let mut chunk = vec![0u8; chunk_size.min(MAX_BODY_BYTES - buf.len())]; let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) .await .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; buf.extend_from_slice(&chunk[..n]); + if buf.len() > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } Ok(n) } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 9fcb3b614f..886af3ec2e 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -213,6 +213,7 @@ fn call(degrade: DegradePolicy) -> ManagedCall { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }, target_url: "http://upstream.invalid/v1/chat/completions".into(), headers: vec![("authorization".into(), "Bearer secret".into())], diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs index 023f19b526..b82e407975 100644 --- a/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -42,6 +42,10 @@ pub struct CanonicalRequest { /// Responses 的保留设置(store)。#2313 要求 openai-responses 目标显式 store:false。 #[serde(default, skip_serializing_if = "Option::is_none")] pub store: Option, + /// 调用方使用的 token 上限字段名("max_tokens" 或 "max_completion_tokens"), + /// 渲染器按原名输出——o-series 只认 max_completion_tokens。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub token_limit_field: Option, /// Responses 的会话续写 ID,原样透传给上游和 Core。 #[serde(default, skip_serializing_if = "Option::is_none")] pub previous_response_id: Option, diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index 9b7ede95ba..ca11d3224c 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -96,7 +96,8 @@ impl WireRenderer for OpenAiChatRenderer { "stream": request.stream, }); if let Some(max) = request.output_limits.max_output_tokens { - body["max_tokens"] = serde_json::json!(max); + let field = request.token_limit_field.as_deref().unwrap_or("max_tokens"); + body[field] = serde_json::json!(max); } if !request.tools.is_empty() { body["tools"] = serde_json::json!(request.tools); diff --git a/gateway/crates/pc-gateway-protocol/src/sse.rs b/gateway/crates/pc-gateway-protocol/src/sse.rs index 51a46ef1e6..ca53a1298e 100644 --- a/gateway/crates/pc-gateway-protocol/src/sse.rs +++ b/gateway/crates/pc-gateway-protocol/src/sse.rs @@ -63,14 +63,20 @@ impl SseFramer { } fn find_blank_line_with_len(buf: &[u8]) -> Option<(usize, usize)> { - // 完整空行分隔符:\r\n\r\n(CRLF)或 \n\n(LF)。 - // 不能匹配单个 \r\n(那是事件内部的行终止符,不是事件分隔符)。 - if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { - return Some((pos, 4)); + // 返回最早出现的完整分隔符(不按类型排序,按位置排序)。 + // CRLF(\r\n\r\n) 和 LF(\n\n) 同时搜索,取位置更靠前的那个—— + // 混合行尾流中 LF 分隔符可能出现在 CRLF 之前。 + let crlf = buf + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|p| (p, 4)); + let lf = buf.windows(2).position(|w| w == b"\n\n").map(|p| (p, 2)); + match (crlf, lf) { + (Some(a), Some(b)) => Some(if a.0 < b.0 { a } else { b }), + (Some(a), None) => Some(a), + (None, Some(b)) => Some(b), + (None, None) => None, } - buf.windows(2) - .position(|w| w == b"\n\n") - .map(|pos| (pos, 2)) } fn parse_block(block: &[u8]) -> Option { diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index db04775b53..4863493405 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -37,6 +37,7 @@ fn request() -> CanonicalRequest { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, } } @@ -125,6 +126,7 @@ fn tool_call_metadata_round_trip_preserved() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -170,6 +172,7 @@ fn omitted_token_limit_not_emitted() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -201,8 +204,78 @@ fn explicit_token_limit_still_emitted() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); assert_eq!(v["max_tokens"], 64, "显式传的 64 必须到达 wire body"); } + +#[test] +fn max_completion_tokens_field_name_preserved() { + // P2 review:客户端发 max_completion_tokens:16 → 线格式必须输出 + // "max_completion_tokens"(不是 "max_tokens")—— o-series 只认前者。 + let req = CanonicalRequest { + model: "o3".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(16), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + token_limit_field: Some("max_completion_tokens".into()), + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["max_completion_tokens"], 16, + "必须输出 max_completion_tokens" + ); + assert!( + v.get("max_tokens").is_none(), + "不得出现 max_tokens(o-series 不认)" + ); +} + +#[test] +fn max_tokens_field_name_preserved() { + // 客户端发 max_tokens:32 → 线格式输出 "max_tokens"(不是 max_completion_tokens)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(32), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + token_limit_field: Some("max_tokens".into()), + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["max_tokens"], 32, "必须输出 max_tokens"); + assert!(v.get("max_completion_tokens").is_none()); +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 7a7fe12448..22474d16cf 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -37,6 +37,7 @@ fn request() -> CanonicalRequest { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, } } @@ -92,6 +93,7 @@ fn responses_items_pass_through_verbatim() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -136,6 +138,7 @@ fn typed_content_parts_pass_through_as_array() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -175,6 +178,7 @@ fn structured_output_via_text_field_reaches_wire() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -215,6 +219,7 @@ fn store_false_reaches_responses_wire_body() { tool_choice: None, store: Some(false), previous_response_id: None, + token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -247,6 +252,7 @@ fn store_absent_omitted_from_wire_body() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -279,6 +285,7 @@ fn previous_response_id_reaches_wire_body() { tool_choice: None, store: Some(false), previous_response_id: Some("resp_prior_turn".into()), + token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); @@ -310,6 +317,7 @@ fn responses_omitted_token_limit_not_emitted() { tool_choice: None, store: None, previous_response_id: None, + token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); diff --git a/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs b/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs index b12a8415d7..4aa790790e 100644 --- a/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs +++ b/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs @@ -57,3 +57,22 @@ fn mixed_crlf_events() { assert_eq!(events[0].event.as_deref(), Some("a")); assert_eq!(events[1].event.as_deref(), Some("b")); } + +#[test] +fn mixed_lf_then_crlf_events_not_merged() { + // P2 review:一个 LF 事件 + 一个 CRLF 事件不得合并为一个。 + // 修复前:搜索先找 CRLF 再找 LF → LF 分隔符被跳过 → 两个事件合并。 + let mut framer = SseFramer::default(); + framer.push(b"event: a\ndata: one\n\nevent: b\r\ndata: two\r\n\r\n"); + let events = framer.take_events(); + assert_eq!( + events.len(), + 2, + "混合行尾应得到两个事件,实际: {} 个", + events.len() + ); + assert_eq!(events[0].event.as_deref(), Some("a")); + assert_eq!(events[0].data.as_ref(), &bytes::Bytes::from_static(b"one")); + assert_eq!(events[1].event.as_deref(), Some("b")); + assert_eq!(events[1].data.as_ref(), &bytes::Bytes::from_static(b"two")); +} From 2e839cba4888319fcee9bac9783713875396c4c3 Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 15:09:43 +0800 Subject: [PATCH 31/37] ci(gateway): align gateway workflow with the master orchestrator pattern Reworks gateway.yml from a path-triggered workflow to the workflow_call pattern used by desktop.yml: a changes job resolves suite selection when invoked standalone; the check job conditionally runs based on the gateway suite from either inputs.suites or the changes output. Adds a gateway-validation job to master.yml that calls the workflow, passes suites, and is included in the result gate. The [checks] entry now references gateway-validation. This fixes two test_ci_pipeline.py failures: - test_selected_scopes_have_a_complete_terminal_result_contract - test_automatic_host_workflows_share_one_scope_and_admission_gate All 123 CI-related tests, 351 Python tests, license check, and 74 Rust tests pass. Signed-off-by: ztelur --- .github/ci-paths.toml | 2 +- .github/workflows/gateway.yml | 21 ++++++++++++++++----- .github/workflows/master.yml | 11 +++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index fff0b61d34..083d815e40 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -203,4 +203,4 @@ candidate_replay = ["candidate-replay"] release_schema = ["release-schema"] seekdb_lock = ["seekdb-lock"] skill_guidance = ["skill-guidance"] -gateway = ["gateway"] +gateway = ["gateway-validation"] diff --git a/.github/workflows/gateway.yml b/.github/workflows/gateway.yml index f8e14ea3cc..fb21b1909f 100644 --- a/.github/workflows/gateway.yml +++ b/.github/workflows/gateway.yml @@ -1,11 +1,12 @@ name: Gateway on: - pull_request: - paths: ['gateway/**', '.github/workflows/gateway.yml'] - push: - branches: [master] - paths: ['gateway/**', '.github/workflows/gateway.yml'] + workflow_call: + inputs: + suites: + description: Scope already selected by the Main orchestrator + required: true + type: string workflow_dispatch: permissions: @@ -16,7 +17,17 @@ concurrency: cancel-in-progress: true jobs: + changes: + if: ${{ inputs.suites == '' }} + uses: ./.github/workflows/ci-changes.yml + with: + baseline-workflow: gateway.yml + check: + needs: changes + if: >- + ${{ !cancelled() && + ((inputs.suites == '' && needs.changes.result != 'success') || fromJSON(inputs.suites || needs.changes.outputs.suites || '{}').gateway) }} runs-on: ubuntu-latest timeout-minutes: 20 steps: diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 6acc851d96..80607cd91f 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -1123,6 +1123,16 @@ jobs: with: suites: ${{ needs.quality.outputs.suites }} + gateway-validation: + needs: [quality, tests] + if: >- + ${{ !cancelled() && needs.quality.result == 'success' && + contains(fromJSON('["success","skipped"]'), needs.tests.result) && + (fromJSON(needs.quality.outputs.suites || '{}').gateway) }} + uses: ./.github/workflows/gateway.yml + with: + suites: ${{ needs.quality.outputs.suites }} + desktop-validation: needs: [quality, tests] if: >- @@ -1240,6 +1250,7 @@ jobs: - website-link-validation-windows - check-website - harness-validation + - gateway-validation - desktop-validation - managed-resource-candidates - helm From 6a4275362b223171444075cd2a572bdc949f6a82 Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 17:07:54 +0800 Subject: [PATCH 32/37] fix(gateway): workflow permissions, typed-content injection, UDS budget boundary - Gateway workflow now grants actions: read alongside contents: read; the nested ci-changes.yml workflow requires actions: read for standalone (workflow_dispatch) execution - enrich() now handles typed content parts when injecting memory: extracts text fields from [{"type":"text","text":"..."}] parts instead of returning early, so recalled context is injected into typed-part messages as well as plain-string messages - UDS cumulative budget allows a body that is exactly MAX_BODY_BYTES (8 MiB); the pre-read check uses > not >= so a single chunk at the exact budget is accepted, while cumulative reads past the budget are rejected 74 Rust tests + 123 CI tests pass; clippy zero warnings. Signed-off-by: ztelur --- .github/workflows/gateway.yml | 1 + gateway/crates/pc-gateway-core/src/executor.rs | 12 ++++++++++++ .../crates/pc-gateway-core/src/uds_gate_client.rs | 2 +- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/gateway.yml b/.github/workflows/gateway.yml index fb21b1909f..2fb4215dd7 100644 --- a/.github/workflows/gateway.yml +++ b/.github/workflows/gateway.yml @@ -11,6 +11,7 @@ on: permissions: contents: read + actions: read concurrency: group: gateway-${{ github.event.pull_request.number || github.ref }} diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index de9f5037e5..a817631353 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -410,8 +410,20 @@ where }; let original = match message.content.as_slice() { [serde_json::Value::String(s)] => s.clone(), + // typed parts:提取文本注入,保留原有 typed 结构。 + parts if !parts.is_empty() => { + let texts: Vec = parts + .iter() + .filter_map(|p| p.get("text").and_then(|t| t.as_str()).map(String::from)) + .collect(); + if texts.is_empty() { + return; + } + texts.join("\n") + } _ => return, }; + // 注入后恢复为单字符串(与 typed parts 请求兼容的线格式) let new_text = format!("{block}\n\n{original}"); message.content = vec![serde_json::Value::String(new_text)]; call.prepared_contexts.push(PreparedContextLocation { diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index 2439b87b8c..95e22d6f18 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -354,7 +354,7 @@ async fn read_with_timeout( chunk_size: usize, ) -> Result { // 累计预算:读取前检查,不在读满 64 MiB 后才拒绝。 - if buf.len() >= MAX_BODY_BYTES { + if buf.len() > MAX_BODY_BYTES { return Err(GateError::Malformed("uds body too large".into())); } let mut chunk = vec![0u8; chunk_size.min(MAX_BODY_BYTES - buf.len())]; From d05f4e6f3bc381b1d62e3b382caaa00e74bcc65c Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 17:16:55 +0800 Subject: [PATCH 33/37] fix(gateway): token_limit_field conditionally set in Chat ingress; end-to-end verified MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The token_limit_field was inadvertently set to None in the Chat ingress path when a batch script added the field to all constructor sites — overwriting the intended conditional assignment. The renderer correctly uses the field name, but the ingress never populated it, so max_completion_tokens was still rewritten to max_tokens in the actual HTTP path (unit tests passed because they tested the renderer directly, bypassing the ingress). End-to-end verified: client sends max_completion_tokens:16 → upstream receives max_completion_tokens:16 with no max_tokens field present. 74 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 864437fb32..76fc389be7 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -287,7 +287,13 @@ fn to_canonical_chat(chat: OpenAiChatRequest) -> Result Date: Mon, 2 Nov 2026 17:23:57 +0800 Subject: [PATCH 34/37] fix(gateway): preserve non-text parts when injecting into typed content MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Injecting recalled context into a typed-parts message previously replaced the entire content array with a single string assembled from .text values, silently discarding image_url and other non-text parts. A user message containing text plus an image would lose the image before Core admission, so Core's content_unsupported verdict was never reached and the request was incorrectly allowed. The enrich() function now modifies only the text parts in place (prepending the memory block to each text value) and passes all non-text parts through unchanged, so unsupported content remains visible to Core. Probe test: mixed_content_preserves_non_text_parts_during_injection (text + image_url → upstream receives both memory-injected text AND the original image part). 75 tests; clippy zero warnings. Signed-off-by: ztelur --- .../crates/pc-gateway-core/src/executor.rs | 38 +++++++++++++------ .../tests/executor_semantics.rs | 36 ++++++++++++++++++ 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index a817631353..b5828b4eb8 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -408,24 +408,38 @@ where let Some(message) = call.request.messages.get_mut(index) else { return; }; - let original = match message.content.as_slice() { - [serde_json::Value::String(s)] => s.clone(), - // typed parts:提取文本注入,保留原有 typed 结构。 + match message.content.as_slice() { + [serde_json::Value::String(s)] => { + let new_text = format!("{block}\n\n{s}"); + message.content = vec![serde_json::Value::String(new_text)]; + } + // typed parts:只修改第一个 text 部件注入记忆,保留所有非文本部件 + // (image_url 等)——移除非文本部件会让 Core 看不到不支持的内容, + // 从而把本该被拒绝的请求变成 allow(P2 review 发现的安全缺陷)。 parts if !parts.is_empty() => { - let texts: Vec = parts + let has_text = parts .iter() - .filter_map(|p| p.get("text").and_then(|t| t.as_str()).map(String::from)) - .collect(); - if texts.is_empty() { + .any(|p| p.get("type").and_then(|t| t.as_str()) == Some("text")); + if !has_text { return; } - texts.join("\n") + let new_parts: Vec = parts + .iter() + .map(|p| { + if p.get("type").and_then(|t| t.as_str()) == Some("text") { + let text = p.get("text").and_then(|t| t.as_str()).unwrap_or(""); + let mut np = p.clone(); + np["text"] = serde_json::json!(format!("{block}\n\n{text}")); + np + } else { + p.clone() // 非文本部件原样保留 + } + }) + .collect(); + message.content = new_parts; } _ => return, - }; - // 注入后恢复为单字符串(与 typed parts 请求兼容的线格式) - let new_text = format!("{block}\n\n{original}"); - message.content = vec![serde_json::Value::String(new_text)]; + } call.prepared_contexts.push(PreparedContextLocation { binding: binding.to_string(), location: ModelJsonTextLocation { diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 886af3ec2e..fa799fe307 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -1295,3 +1295,39 @@ async fn typed_content_parts_preserved_in_query_and_transcript() { "transcript user 必须是 typed text 而非空串" ); } + +#[tokio::test] +async fn mixed_content_preserves_non_text_parts_during_injection() { + // hidb4ai P2:text + image_url 混合内容注入时,image 部件不得被丢弃。 + // 丢弃 = Core 看不到不支持的内容 → 本该拒绝的请求变成 allow。 + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("RECALLED_MEMORY_42"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + // 混合内容:text + image_url + c.request.messages[0].content = vec![ + serde_json::json!({"type": "text", "text": "看这张图"}), + serde_json::json!({"type": "image_url", "image_url": {"url": "data:image/png;base64,xxx"}}), + ]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + // 上游收到的载荷必须同时包含注入的 text 和原始的 image_url + let sent = &transport.sends.lock().unwrap()[0]; + let sent_str = String::from_utf8(sent.to_vec()).unwrap(); + assert!(sent_str.contains("RECALLED_MEMORY_42"), "注入的记忆必须在"); + assert!(sent_str.contains("看这张图"), "原始文本必须在"); + assert!( + sent_str.contains("image_url"), + "image_url 部件必须在(不得被丢弃)" + ); + assert!(sent_str.contains("data:image/png"), "图片数据必须在"); +} From c2919d67ff43616e55f72191ad2b2c9d901c8490 Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 17:54:49 +0800 Subject: [PATCH 35/37] fix(gateway): single-injection for multi-text parts, typed pointer, UDS cumulative budget Typed parts injection (enrich): - Only the first text part receives the memory block; subsequent text parts are unchanged (no duplicate injection that would inflate payload and desync audit records) - prepared_contexts pointer for typed parts now uses the /messages/ {i}/content/{j}/text form (the /messages/{i}/content form is only valid for plain-string content) UDS cumulative budget (read_chunked): - Budget check moved from read_with_timeout to read_chunked where the decoded body size is known: out.len() + size > MAX_BODY_BYTES is checked before reading/appending, not after buffering 64 MiB - read_with_timeout no longer clamps chunk_size to remaining budget (which caused zero-length reads at exactly 8 MiB); it reads what the caller requests, and the caller enforces the limit Tests: multi_text_parts_memory_injected_only_once, typed_parts_pointer_targets_text_field. 77 tests; clippy zero warnings. Signed-off-by: ztelur --- .../crates/pc-gateway-core/src/executor.rs | 39 +++++++--- .../pc-gateway-core/src/uds_gate_client.rs | 9 +-- .../tests/executor_semantics.rs | 74 +++++++++++++++++++ 3 files changed, 103 insertions(+), 19 deletions(-) diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index b5828b4eb8..9bf711c75e 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -413,30 +413,47 @@ where let new_text = format!("{block}\n\n{s}"); message.content = vec![serde_json::Value::String(new_text)]; } - // typed parts:只修改第一个 text 部件注入记忆,保留所有非文本部件 - // (image_url 等)——移除非文本部件会让 Core 看不到不支持的内容, - // 从而把本该被拒绝的请求变成 allow(P2 review 发现的安全缺陷)。 + // typed parts:只修改第一个 text 部件注入记忆(不重复注入), + // 保留所有非文本部件(image_url 等)——移除非文本部件会让 Core + // 看不到不支持的内容(安全缺陷),重复注入会膨胀 payload(审计缺陷)。 parts if !parts.is_empty() => { - let has_text = parts + let first_text_idx = parts .iter() - .any(|p| p.get("type").and_then(|t| t.as_str()) == Some("text")); - if !has_text { + .position(|p| p.get("type").and_then(|t| t.as_str()) == Some("text")); + let Some(text_idx) = first_text_idx else { return; - } + }; + let text = parts[text_idx] + .get("text") + .and_then(|t| t.as_str()) + .unwrap_or(""); let new_parts: Vec = parts .iter() - .map(|p| { - if p.get("type").and_then(|t| t.as_str()) == Some("text") { - let text = p.get("text").and_then(|t| t.as_str()).unwrap_or(""); + .enumerate() + .map(|(j, p)| { + if j == text_idx { let mut np = p.clone(); np["text"] = serde_json::json!(format!("{block}\n\n{text}")); np } else { - p.clone() // 非文本部件原样保留 + p.clone() // 其余部件(含非第一个 text)原样保留 } }) .collect(); message.content = new_parts; + // typed parts 的 prepared_contexts 指针必须指向具体 text 部件 + // (/messages/{i}/content 是纯字符串形态的指针,数组形态用 + // /messages/{i}/content/{j}/text——PC 契约的两种合法形态)。 + call.prepared_contexts.push(PreparedContextLocation { + binding: binding.to_string(), + location: ModelJsonTextLocation { + schema: pc_gateway_types::MODEL_JSON_TEXT_LOCATION_SCHEMA.to_string(), + pointer: format!("/messages/{index}/content/{text_idx}/text"), + start_byte: 0, + end_byte: block.len() as u64, + }, + }); + return; } _ => return, } diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index 95e22d6f18..51f12d79d0 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -353,19 +353,12 @@ async fn read_with_timeout( buf: &mut Vec, chunk_size: usize, ) -> Result { - // 累计预算:读取前检查,不在读满 64 MiB 后才拒绝。 - if buf.len() > MAX_BODY_BYTES { - return Err(GateError::Malformed("uds body too large".into())); - } - let mut chunk = vec![0u8; chunk_size.min(MAX_BODY_BYTES - buf.len())]; + let mut chunk = vec![0u8; chunk_size]; let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) .await .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; buf.extend_from_slice(&chunk[..n]); - if buf.len() > MAX_BODY_BYTES { - return Err(GateError::Malformed("uds body too large".into())); - } Ok(n) } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index fa799fe307..1754b73275 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -1331,3 +1331,77 @@ async fn mixed_content_preserves_non_text_parts_during_injection() { ); assert!(sent_str.contains("data:image/png"), "图片数据必须在"); } + +// ---------- typed parts 注入精确性 + UDS 预算 ---------- + +#[tokio::test] +async fn multi_text_parts_memory_injected_only_once() { + // AlexStocks P2:两个 text 部件 → 记忆块只出现在第一个,不重复。 + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("UNIQUE_MARKER_XYZ"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.request.messages[0].content = vec![ + serde_json::json!({"type": "text", "text": "第一段"}), + serde_json::json!({"type": "text", "text": "第二段"}), + serde_json::json!({"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}}), + ]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + // 上游载荷:记忆块只出现一次(第一个 text 部件),第二个 text 不注入 + let sent = &transport.sends.lock().unwrap()[0]; + let sent_str = String::from_utf8(sent.to_vec()).unwrap(); + let count = sent_str.matches("UNIQUE_MARKER_XYZ").count(); + assert_eq!(count, 1, "记忆块必须只出现一次,实际出现 {count} 次"); + assert!(sent_str.contains("第一段")); + assert!(sent_str.contains("第二段")); + assert!(sent_str.contains("image_url"), "非文本部件保留"); +} + +#[tokio::test] +async fn typed_parts_pointer_targets_text_field() { + // hidb4ai P2:typed parts 的 prepared_contexts 指针必须是 /messages/{i}/content/{j}/text。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("TYPED_MEMORY"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.request.messages[0].content = vec![serde_json::json!({"type": "text", "text": "hello"})]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + let declared = gate.prepared_seen.lock().unwrap(); + assert_eq!( + declared.len(), + 2, + "两次 check(before_send + before_release)" + ); + assert_eq!(declared[0].len(), 1, "before_send 有 1 条 prepared_context"); + assert_eq!(declared[1].len(), 0, "before_release 无 prepared_context"); + let loc = &declared[0][0]; + assert!( + loc.location.pointer.contains("/text"), + "typed parts 指针必须指向 text 字段: {}", + loc.location.pointer + ); + assert_eq!( + loc.location.pointer, "/messages/0/content/0/text", + "精确指针格式" + ); +} From 4e55672a7e4fc99491dc780ac597f3ad47fc3435 Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 18:26:14 +0800 Subject: [PATCH 36/37] fix(gateway): cumulative UDS chunk budget before reading chunk data The cumulative budget check was inadvertently lost during a batch edit. It is now placed between the chunk-size parse and the chunk-data read loop: out.len() + size > MAX_BODY_BYTES is evaluated before any chunk bytes are read from the socket, so 16 x 4 MiB chunks are rejected at chunk 3 without buffering 64 MiB. The single-chunk size guard and Content-Length precheck remain in place. 77 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-core/src/uds_gate_client.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs index 51f12d79d0..e1b8d6e490 100644 --- a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -320,6 +320,10 @@ async fn read_chunked( }; } } + // 累计预算:在读取 chunk 数据之前检查(不在读完 64 MiB 后才拒绝)。 + if out.len() + size > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } let needed = size + 2; // 数据 + CRLF while buf.len() < needed { let n = read_with_timeout(rd, buf, 8192).await?; From 6075cc6303d92508a0404ee34fc7030c6926112e Mon Sep 17 00:00:00 2001 From: ztelur Date: Mon, 2 Nov 2026 18:33:41 +0800 Subject: [PATCH 37/37] fix(gateway): capture and pass through the Responses conversation parameter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Responses API has a conversation parameter (separate from previous_response_id) that identifies the conversation. Like previous_response_id, it was silently dropped by the DTO because serde ignores unknown fields. The DTO now captures it, the CanonicalRequest carries it, and the Responses renderer emits it to the wire body — Core sees the conversation reference and can withhold with content_field_unsupported if the target does not support it. Probe test: conversation_field_reaches_wire_body. 78 tests; clippy zero warnings. Signed-off-by: ztelur --- gateway/crates/pc-gateway-app/src/ingress.rs | 6 +++ .../tests/executor_semantics.rs | 1 + .../pc-gateway-protocol/src/canonical.rs | 3 ++ .../crates/pc-gateway-protocol/src/render.rs | 3 ++ .../tests/openai_renderer.rs | 6 +++ .../tests/openai_responses_renderer.rs | 43 +++++++++++++++++++ 6 files changed, 62 insertions(+) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 76fc389be7..4149feaf52 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -79,6 +79,10 @@ struct OpenAiResponsesRequest { /// Responses 的会话续写 ID;不透传 = 客户端丢失历史连续性。 #[serde(default)] previous_response_id: Option, + /// Responses 的会话标识(conversation 参数);与 previous_response_id + /// 是不同的字段,同样需要透传给 Core 检查。 + #[serde(default)] + conversation: Option, #[serde(default)] stream: Option, } @@ -294,6 +298,7 @@ fn to_canonical_chat(chat: OpenAiChatRequest) -> Result Result ManagedCall { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }, target_url: "http://upstream.invalid/v1/chat/completions".into(), diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs index b82e407975..69622b8074 100644 --- a/gateway/crates/pc-gateway-protocol/src/canonical.rs +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -49,6 +49,9 @@ pub struct CanonicalRequest { /// Responses 的会话续写 ID,原样透传给上游和 Core。 #[serde(default, skip_serializing_if = "Option::is_none")] pub previous_response_id: Option, + /// Responses 的会话标识(conversation 参数),原样透传。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub conversation: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs index ca11d3224c..4c76e2ddcb 100644 --- a/gateway/crates/pc-gateway-protocol/src/render.rs +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -281,6 +281,9 @@ impl WireRenderer for OpenAiResponsesRenderer { if let Some(prev_id) = &request.previous_response_id { body["previous_response_id"] = serde_json::json!(prev_id); } + if let Some(conv) = &request.conversation { + body["conversation"] = serde_json::json!(conv); + } if let Some(fields) = request.native_cache_fields.as_ref() { merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { renderer: self.name(), diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs index 4863493405..488a619b59 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -37,6 +37,7 @@ fn request() -> CanonicalRequest { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, } } @@ -126,6 +127,7 @@ fn tool_call_metadata_round_trip_preserved() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); @@ -172,6 +174,7 @@ fn omitted_token_limit_not_emitted() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); @@ -204,6 +207,7 @@ fn explicit_token_limit_still_emitted() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); @@ -235,6 +239,7 @@ fn max_completion_tokens_field_name_preserved() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: Some("max_completion_tokens".into()), }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); @@ -272,6 +277,7 @@ fn max_tokens_field_name_preserved() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: Some("max_tokens".into()), }; let p = OpenAiChatRenderer.render(&req, None).unwrap(); diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs index 22474d16cf..e1075bc99e 100644 --- a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -37,6 +37,7 @@ fn request() -> CanonicalRequest { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, } } @@ -93,6 +94,7 @@ fn responses_items_pass_through_verbatim() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); @@ -138,6 +140,7 @@ fn typed_content_parts_pass_through_as_array() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); @@ -178,6 +181,7 @@ fn structured_output_via_text_field_reaches_wire() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); @@ -219,6 +223,7 @@ fn store_false_reaches_responses_wire_body() { tool_choice: None, store: Some(false), previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); @@ -252,6 +257,7 @@ fn store_absent_omitted_from_wire_body() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); @@ -285,6 +291,7 @@ fn previous_response_id_reaches_wire_body() { tool_choice: None, store: Some(false), previous_response_id: Some("resp_prior_turn".into()), + conversation: None, token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); @@ -317,9 +324,45 @@ fn responses_omitted_token_limit_not_emitted() { tool_choice: None, store: None, previous_response_id: None, + conversation: None, token_limit_field: None, }; let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); assert!(v.get("max_output_tokens").is_none(), "未传时不出现"); } + +#[test] +fn conversation_field_reaches_wire_body() { + // hidb4ai P2:Responses 的 conversation 参数(与会话 ID 不同) + // 也必须透传到上游载荷,让 Core 决定接受或拒绝。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: Some("conv_prior".into()), + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["conversation"], "conv_prior", + "conversation 参数必须原样到达 Responses wire body" + ); +}