Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,7 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "common",
crate_name = "app_test_support",
crate_srcs = glob(["*.rs"]),
)

View File

@@ -0,0 +1,49 @@
[package]
name = "app_test_support"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
path = "lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
akode-app-server-protocol = { workspace = true }
akode-config = { workspace = true }
akode-core = { workspace = true }
akode-exec-server = { workspace = true }
akode-features = { workspace = true }
akode-login = { workspace = true }
akode-model-provider = { workspace = true }
akode-protocol = { workspace = true }
akode-utils-cargo-bin = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = [
"io-util",
"io-std",
"macros",
"net",
"process",
"rt-multi-thread",
"sync",
"test-util",
"time",
] }
tokio-util = { workspace = true }
url = { workspace = true }
uuid = { workspace = true }
wiremock = { workspace = true }
core_test_support = { path = "../../../core/tests/common" }
shlex = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }

View File

@@ -0,0 +1,243 @@
use akode_features::FEATURES;
use akode_features::Feature;
use std::collections::BTreeMap;
use std::path::Path;
/// Composes the standard mock Responses provider with test-specific configuration.
pub struct MockResponsesConfig {
provider_id: String,
provider_name: String,
provider_base_url: String,
model: String,
approval_policy: String,
sandbox_mode: String,
features: BTreeMap<Feature, bool>,
root_config: Vec<String>,
provider_config: Vec<String>,
extra_config: Vec<String>,
}
impl MockResponsesConfig {
pub fn new(server_uri: &str) -> Self {
Self {
provider_id: "mock_provider".to_string(),
provider_name: "Mock provider for test".to_string(),
provider_base_url: format!("{server_uri}/v1"),
model: "mock-model".to_string(),
approval_policy: "never".to_string(),
sandbox_mode: "read-only".to_string(),
features: BTreeMap::new(),
root_config: Vec::new(),
provider_config: Vec::new(),
extra_config: Vec::new(),
}
}
pub fn with_model_provider(mut self, provider_id: &str) -> Self {
self.provider_id = provider_id.to_string();
self
}
pub fn with_provider_name(mut self, provider_name: &str) -> Self {
self.provider_name = provider_name.to_string();
self
}
pub fn with_provider_base_url(mut self, provider_base_url: &str) -> Self {
self.provider_base_url = provider_base_url.to_string();
self
}
pub fn with_model(mut self, model: &str) -> Self {
self.model = model.to_string();
self
}
pub fn with_approval_policy(mut self, approval_policy: &str) -> Self {
self.approval_policy = approval_policy.to_string();
self
}
pub fn with_sandbox_mode(mut self, sandbox_mode: &str) -> Self {
self.sandbox_mode = sandbox_mode.to_string();
self
}
pub fn enable_feature(mut self, feature: Feature) -> Self {
self.features.insert(feature, true);
self
}
pub fn disable_feature(mut self, feature: Feature) -> Self {
self.features.insert(feature, false);
self
}
pub fn with_features(mut self, features: &BTreeMap<Feature, bool>) -> Self {
self.features.extend(
features
.iter()
.map(|(&feature, &enabled)| (feature, enabled)),
);
self
}
pub fn with_root_config(mut self, config: &str) -> Self {
self.root_config.push(config.to_string());
self
}
pub fn with_provider_config(mut self, config: &str) -> Self {
self.provider_config.push(config.to_string());
self
}
pub fn with_extra_config(mut self, config: &str) -> Self {
self.extra_config.push(config.to_string());
self
}
pub fn write(self, codex_home: &Path) -> std::io::Result<()> {
let Self {
provider_id,
provider_name,
provider_base_url,
model,
approval_policy,
sandbox_mode,
features,
root_config,
provider_config,
extra_config,
} = self;
let mut root_config = root_config.join("\n");
let mut provider_config = provider_config.join("\n");
let extra_config = extra_config.join("\n");
// aKode providers without a catalog URL synthesize local metadata; tests keep the
// bundled catalog the removed built-in defaults provided (unless they configure one).
if !root_config.contains("model_catalog_json")
&& !extra_config.contains("model_catalog_json")
&& !provider_config.contains("model_catalog_url")
{
root_config.push('\n');
root_config.push_str(&bundled_model_catalog_config(codex_home)?);
}
// Upstream custom providers offered hosted web search by default; aKode makes it an
// explicit provider capability, so the mock provider opts in to keep request shapes.
// Upstream also gave providers named "OpenAI" remote compaction V2 by name; aKode
// requires the explicit capability.
if !provider_config.contains("capabilities") && !extra_config.contains("capabilities") {
if provider_name == "OpenAI" {
provider_config.push_str(
"\ncapabilities = { hosted_web_search = true, remote_compaction = \"v2\" }",
);
} else {
provider_config.push_str("\ncapabilities = { hosted_web_search = true }");
}
}
// Request-shape tests keep the upstream instruction layout; merging has its own tests.
if !provider_config.contains("merge_system_messages") {
provider_config.push_str("\nmerge_system_messages = false");
}
let feature_entries = features
.into_iter()
.map(|(feature, enabled)| {
let key = FEATURES
.iter()
.find(|spec| spec.id == feature)
.map(|spec| spec.key)
.expect("feature should have a config key");
format!("{key} = {enabled}")
})
.collect::<Vec<_>>()
.join("\n");
let feature_config = if feature_entries.is_empty() {
String::new()
} else {
format!("[features]\n{feature_entries}\n\n")
};
std::fs::write(
codex_home.join("config.toml"),
format!(
r#"
model = "{model}"
approval_policy = "{approval_policy}"
sandbox_mode = "{sandbox_mode}"
{root_config}
model_provider = "{provider_id}"
{feature_config}[model_providers.{provider_id}]
name = "{provider_name}"
base_url = "{provider_base_url}"
wire_api = "responses"
request_max_retries = 0
stream_max_retries = 0
{provider_config}
{extra_config}
"#
),
)
}
}
/// Copy the bundled model catalog into `codex_home` and return the root-level
/// `model_catalog_json = ...` line that selects it.
///
/// aKode has no default provider and no bundled catalog seed, so tests that start threads
/// from a hand-written config (and relied on the removed defaults) opt in explicitly.
pub fn bundled_model_catalog_config(codex_home: &Path) -> std::io::Result<String> {
let catalog = codex_home.join(crate::models_cache::HARNESS_CATALOG_FILE);
std::fs::write(
&catalog,
include_str!("../../../models-manager/models.json"),
)?;
Ok(format!(
"model_catalog_json = {}\n",
serde_json::to_string(&catalog.display().to_string())?
))
}
pub fn write_mock_responses_config_toml(
codex_home: &Path,
server_uri: &str,
feature_flags: &BTreeMap<Feature, bool>,
auto_compact_limit: i64,
requires_openai_auth: Option<bool>,
model_provider_id: &str,
compact_prompt: &str,
) -> std::io::Result<()> {
let mut config = MockResponsesConfig::new(server_uri)
.with_model_provider(model_provider_id)
.with_features(feature_flags)
.with_root_config(&format!(
"compact_prompt = \"{compact_prompt}\"\nmodel_auto_compact_token_limit = {auto_compact_limit}"
))
.with_provider_config("supports_websockets = false");
if model_provider_id == "openai" {
config = config.with_root_config(&format!("openai_base_url = \"{server_uri}/v1\""));
}
if matches!(requires_openai_auth, Some(true)) {
config = config
.with_provider_name("OpenAI")
.with_provider_config("requires_openai_auth = true");
}
config.write(codex_home)
}
pub fn write_mock_responses_config_toml_with_chatgpt_base_url(
codex_home: &Path,
server_uri: &str,
chatgpt_base_url: &str,
) -> std::io::Result<()> {
MockResponsesConfig::new(server_uri)
.with_root_config(&format!("chatgpt_base_url = \"{chatgpt_base_url}\""))
.write(codex_home)
}
#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,69 @@
use super::*;
use tempfile::TempDir;
#[test]
fn mock_responses_config_composes_model_provider_features_and_extra_tables() {
let home = TempDir::new().expect("temporary AKODE_HOME");
MockResponsesConfig::new("http://127.0.0.1:1234")
.with_model("custom-model")
.with_model_provider("openai-custom")
.with_provider_name("OpenAI")
.with_provider_base_url("http://127.0.0.1:1234/api/codex")
.with_approval_policy("on-request")
.with_sandbox_mode("workspace-write")
.enable_feature(Feature::FastMode)
.disable_feature(Feature::ShellSnapshot)
.with_root_config("chatgpt_base_url = \"http://127.0.0.1:1234\"")
.with_provider_config("requires_openai_auth = true")
.with_extra_config("[extra]\nenabled = true")
.write(home.path())
.expect("write composable mock Responses config");
let config =
std::fs::read_to_string(home.path().join("config.toml")).expect("read config.toml");
for expected in [
"model = \"custom-model\"",
"approval_policy = \"on-request\"",
"sandbox_mode = \"workspace-write\"",
"chatgpt_base_url = \"http://127.0.0.1:1234\"",
"model_provider = \"openai-custom\"",
"shell_snapshot = false",
"fast_mode = true",
"[model_providers.openai-custom]\nname = \"OpenAI\"",
"base_url = \"http://127.0.0.1:1234/api/codex\"",
"requires_openai_auth = true",
"[extra]\nenabled = true",
] {
assert!(config.contains(expected), "config is missing {expected}");
}
}
#[test]
fn legacy_mock_responses_writer_preserves_provider_auth_and_feature_overrides() {
let home = TempDir::new().expect("temporary AKODE_HOME");
write_mock_responses_config_toml(
home.path(),
"http://127.0.0.1:1234",
&BTreeMap::from([(Feature::FastMode, true), (Feature::ShellSnapshot, false)]),
/*auto_compact_limit*/ 321,
Some(true),
"openai",
"compact this",
)
.expect("write legacy-compatible mock Responses config");
let config =
std::fs::read_to_string(home.path().join("config.toml")).expect("read config.toml");
for expected in [
"compact_prompt = \"compact this\"",
"model_auto_compact_token_limit = 321",
"openai_base_url = \"http://127.0.0.1:1234/v1\"",
"shell_snapshot = false",
"fast_mode = true",
"[model_providers.openai]\nname = \"OpenAI\"",
"supports_websockets = false",
"requires_openai_auth = true",
] {
assert!(config.contains(expected), "config is missing {expected}");
}
}

View File

@@ -0,0 +1,128 @@
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use serde_json::Value;
use serde_json::json;
use tokio::sync::Notify;
#[derive(Clone, Default)]
pub(crate) struct JsonLogCapture {
lines: Arc<Mutex<Vec<String>>>,
updated: Arc<Notify>,
}
impl JsonLogCapture {
pub(crate) fn record(&self, line: String) {
self.lines
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(line);
self.updated.notify_one();
}
pub(crate) async fn wait_for_event(
&self,
description: &str,
predicate: impl Fn(&Value) -> bool,
timeout: Duration,
) -> Result<Value> {
let result = tokio::time::timeout(timeout, async {
loop {
let updated = self.updated.notified();
if let Some(event) = self.events()?.into_iter().find(&predicate) {
return Ok(event);
}
updated.await;
}
})
.await;
match result {
Ok(result) => result,
Err(_) => {
let lines = self
.lines
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.join("\n");
anyhow::bail!(
"timed out waiting for a JSON log event {description}; captured stderr:\n{lines}"
)
}
}
}
pub(crate) fn events(&self) -> Result<Vec<Value>> {
let lines = self
.lines
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
json_log_events(lines.iter().map(String::as_str))
}
}
pub fn app_server_json_shutdown_event(
binary: &str,
args: &[&str],
codex_home: &Path,
) -> Result<Value> {
std::fs::write(
codex_home.join("config.toml"),
"[features]\nplugins = false\n",
)?;
let output = Command::new(akode_utils_cargo_bin::cargo_bin(binary)?)
.stdin(Stdio::null())
.env("AKODE_HOME", codex_home)
.env(
"AKODE_APP_SERVER_MANAGED_CONFIG_PATH",
codex_home.join("managed_config.toml"),
)
.env("LOG_FORMAT", "json")
.env("RUST_LOG", "akode_app_server=info")
.args(args)
.output()?;
let stderr = String::from_utf8(output.stderr)?;
anyhow::ensure!(output.status.success(), "app-server failed: {stderr}");
let events = json_log_events(stderr.lines())
.with_context(|| format!("app-server stderr was not valid JSONL: {stderr}"))?;
let event = events
.iter()
.find(|event| event["fields"]["message"] == "processor task exited")
.context("missing INFO shutdown event in app-server JSON logs")?;
Ok(json!({
"level": event["level"],
"fields": event["fields"],
"target": event["target"],
}))
}
fn json_log_events<'a>(lines: impl IntoIterator<Item = &'a str>) -> Result<Vec<Value>> {
lines
.into_iter()
.filter(|line| !line.is_empty())
.map(|line| {
let event = serde_json::from_str::<Value>(line)
.with_context(|| format!("log line was not JSON: {line}"))?;
anyhow::ensure!(
event["level"].is_string()
&& event["fields"].is_object()
&& event["target"].is_string(),
"JSON log event did not include level, fields, and target: {line}"
);
let timestamp = event["timestamp"]
.as_str()
.with_context(|| format!("JSON log event did not include a timestamp: {line}"))?;
chrono::DateTime::parse_from_rfc3339(timestamp).with_context(|| {
format!("JSON log event timestamp was not RFC 3339: {timestamp}")
})?;
Ok(event)
})
.collect()
}

View File

@@ -0,0 +1,70 @@
#![allow(clippy::expect_used)]
mod config;
mod json_logging;
mod local_websocket_exec_server;
mod mock_model_server;
mod models_cache;
mod responses;
mod rollout;
mod rpc_delay;
mod test_app_server;
use akode_app_server_protocol::JSONRPCResponse;
pub use config::MockResponsesConfig;
pub use config::bundled_model_catalog_config;
pub use config::write_mock_responses_config_toml;
pub use config::write_mock_responses_config_toml_with_chatgpt_base_url;
pub use core_test_support::PathBufExt;
pub use core_test_support::format_with_current_shell;
pub use core_test_support::format_with_current_shell_display;
pub use core_test_support::format_with_current_shell_display_non_login;
pub use core_test_support::format_with_current_shell_non_login;
pub use core_test_support::test_absolute_path;
pub use core_test_support::test_path_buf_with_windows;
pub use core_test_support::test_tmp_path;
pub use core_test_support::test_tmp_path_buf;
pub use json_logging::app_server_json_shutdown_event;
pub use mock_model_server::create_mock_responses_server_repeating_assistant;
pub use mock_model_server::create_mock_responses_server_sequence;
pub use mock_model_server::create_mock_responses_server_sequence_unchecked;
pub use models_cache::write_model_catalog_json;
pub use models_cache::write_models_cache;
pub use models_cache::write_models_cache_with_models;
pub use responses::create_apply_patch_sse_response;
pub use responses::create_command_execution_sse_response;
pub use responses::create_escalated_command_execution_sse_response;
pub use responses::create_exec_command_sse_response;
pub use responses::create_final_assistant_message_sse_response;
pub use responses::create_request_permissions_sse_response;
pub use responses::create_request_user_input_sse_response;
pub use rollout::create_fake_paginated_rollout;
pub use rollout::create_fake_parented_rollout_with_source;
pub use rollout::create_fake_rollout;
pub use rollout::create_fake_rollout_with_session_and_thread_source;
pub use rollout::create_fake_rollout_with_source;
pub use rollout::create_fake_rollout_with_text_elements;
pub use rollout::create_fake_rollout_with_token_usage;
pub use rollout::rollout_path;
use serde::de::DeserializeOwned;
pub use test_app_server::DEFAULT_CLIENT_NAME;
pub use test_app_server::DISABLE_PLUGIN_STARTUP_TASKS_ARG;
pub use test_app_server::TestAppServer;
pub use test_app_server::TestAppServerBuilder;
pub fn to_response<T: DeserializeOwned>(response: JSONRPCResponse) -> anyhow::Result<T> {
let value = serde_json::to_value(response.result)?;
let codex_response = serde_json::from_value(value)?;
Ok(codex_response)
}
/// Store an API key in `codex_home` the way `akode login --with-api-key` does.
pub fn write_api_key_auth(codex_home: &std::path::Path) -> anyhow::Result<()> {
akode_login::login_with_api_key(
codex_home,
"sk-test-api-key",
akode_config::types::AuthCredentialsStoreMode::File,
akode_login::AuthKeyringBackendKind::default(),
)?;
Ok(())
}

View File

@@ -0,0 +1,90 @@
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Child;
use tokio::process::Command;
const START_TIMEOUT: Duration = Duration::from_secs(10);
#[cfg(target_os = "linux")]
const AKODE_LINUX_SANDBOX_EXE_ENV_VAR: &str = "AKODE_TEST_LINUX_SANDBOX_EXE";
/// Host-local exec-server fixture that exposes a WebSocket URL.
///
/// This is distinct from the ordinary local stdio executor: callers use it
/// when they need a socket transport they can interpose.
pub(crate) struct LocalWebsocketExecServer {
child: Child,
websocket_url: String,
}
impl LocalWebsocketExecServer {
pub(crate) async fn start(codex_home: &Path, exec_server_program: &Path) -> Result<Self> {
let mut command = Command::new(exec_server_program);
command.stdin(Stdio::null());
command.stdout(Stdio::piped());
command.stderr(Stdio::inherit());
command.current_dir(codex_home);
command.env("AKODE_HOME", codex_home);
#[cfg(target_os = "linux")]
command.env(
AKODE_LINUX_SANDBOX_EXE_ENV_VAR,
core_test_support::find_codex_linux_sandbox_exe()
.context("should find binary for delayed exec-server Linux sandbox helper")?,
);
command.kill_on_drop(true);
let child = command.spawn().context("start local exec-server fixture")?;
let mut exec_server = Self {
child,
websocket_url: String::new(),
};
let stdout = exec_server
.child
.stdout
.take()
.ok_or_else(|| anyhow!("local exec-server fixture stdout was not captured"))?;
let mut lines = BufReader::new(stdout).lines();
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
exec_server.websocket_url = loop {
let remaining = deadline
.checked_duration_since(tokio::time::Instant::now())
.ok_or_else(|| anyhow!("timed out waiting for local exec-server listen URL"))?;
let line = tokio::time::timeout(remaining, lines.next_line())
.await
.map_err(|_| anyhow!("timed out waiting for local exec-server listen URL"))??
.ok_or_else(|| {
anyhow!("local exec-server exited before emitting its listen URL")
})?;
let listen_url = line.trim();
if listen_url.starts_with("ws://") {
break listen_url.to_string();
}
};
Ok(exec_server)
}
pub(crate) fn websocket_url(&self) -> &str {
&self.websocket_url
}
}
impl Drop for LocalWebsocketExecServer {
fn drop(&mut self) {
let _ = self.child.start_kill();
let start = std::time::Instant::now();
let timeout = Duration::from_secs(5);
while start.elapsed() < timeout {
match self.child.try_wait() {
Ok(Some(_)) => return,
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
Err(_) => return,
}
}
}
}

View File

@@ -0,0 +1,82 @@
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use core_test_support::responses;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Respond;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path_regex;
/// Create a mock server that will provide the responses, in order, for
/// requests to the `/v1/responses` endpoint.
pub async fn create_mock_responses_server_sequence(responses: Vec<String>) -> MockServer {
let server = responses::start_mock_server().await;
let num_calls = responses.len();
let seq_responder = SeqResponder {
num_calls: AtomicUsize::new(0),
responses,
};
Mock::given(method("POST"))
.and(path_regex(".*/responses$"))
.respond_with(seq_responder)
.expect(num_calls as u64)
.mount(&server)
.await;
server
}
/// Same as `create_mock_responses_server_sequence` but does not enforce an
/// expectation on the number of calls.
pub async fn create_mock_responses_server_sequence_unchecked(responses: Vec<String>) -> MockServer {
let server = responses::start_mock_server().await;
let seq_responder = SeqResponder {
num_calls: AtomicUsize::new(0),
responses,
};
Mock::given(method("POST"))
.and(path_regex(".*/responses$"))
.respond_with(seq_responder)
.mount(&server)
.await;
server
}
struct SeqResponder {
num_calls: AtomicUsize,
responses: Vec<String>,
}
impl Respond for SeqResponder {
fn respond(&self, _: &wiremock::Request) -> ResponseTemplate {
let call_num = self.num_calls.fetch_add(1, Ordering::SeqCst);
let response = self
.responses
.get(call_num)
.expect("mock model response should exist");
responses::sse_response(response.clone())
}
}
/// Create a mock responses API server that returns the same assistant message for every request.
pub async fn create_mock_responses_server_repeating_assistant(message: &str) -> MockServer {
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_assistant_message("msg-1", message),
responses::ev_completed("resp-1"),
]);
Mock::given(method("POST"))
.and(path_regex(".*/responses$"))
.respond_with(responses::sse_response(body))
.mount(&server)
.await;
server
}

View File

@@ -0,0 +1,196 @@
use akode_core::test_support::all_model_presets;
use akode_protocol::config_types::ReasoningSummary;
use akode_protocol::openai_models::ConfigShellToolType;
use akode_protocol::openai_models::ModelInfo;
use akode_protocol::openai_models::ModelMessages;
use akode_protocol::openai_models::ModelPreset;
use akode_protocol::openai_models::ModelVisibility;
use akode_protocol::openai_models::TruncationPolicyConfig;
use akode_protocol::openai_models::default_input_modalities;
use std::path::Path;
/// Convert a ModelPreset to ModelInfo for cache storage.
fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo {
ModelInfo {
slug: preset.id.clone(),
display_name: preset.display_name.clone(),
description: Some(preset.description.clone()),
default_reasoning_level: Some(preset.default_reasoning_effort.clone()),
supported_reasoning_levels: preset.supported_reasoning_efforts.clone(),
shell_type: ConfigShellToolType::UnifiedExec,
visibility: if preset.show_in_picker {
ModelVisibility::List
} else {
ModelVisibility::Hide
},
supported_in_api: preset.supported_in_api,
priority,
additional_speed_tiers: preset.additional_speed_tiers.clone(),
service_tiers: preset.service_tiers.clone(),
default_service_tier: preset.default_service_tier.clone(),
upgrade: preset.upgrade.as_ref().map(Into::into),
model_messages: Some(ModelMessages {
apps: None,
plugins: None,
content_filter_guidance: None,
persistent_instructions: None,
tools: None,
instructions_template: Some("base instructions".to_string()),
approvals: None,
collaboration_modes: None,
auto_review: None,
permissions: None,
multi_agent: None,
token_budget: None,
confirmation_policies: None,
guardian_v2: None,
}),
include_skills_usage_instructions: false,
include_plugin_usage_instructions: false,
include_apps_usage_instructions: false,
supports_reasoning_summary_parameter: true,
default_reasoning_summary: ReasoningSummary::Auto,
support_verbosity: false,
default_verbosity: None,
availability_nux: preset.availability_nux.clone(),
apply_patch_tool_type: None,
web_search_tool_type: Default::default(),
web_search_provider: None,
truncation_policy: TruncationPolicyConfig::bytes(/*limit*/ 10_000),
supports_image_detail_original: false,
context_window: Some(272_000),
max_context_window: None,
auto_compact_token_limit: None,
comp_hash: None,
effective_context_window_percent: 95,
experimental_supported_tools: Vec::new(),
input_modalities: default_input_modalities(),
supports_search_tool: false,
supports_experimental_context: false,
use_responses_lite: false,
supports_reasoning_effort_updates: false,
guardian: None,
node_repl_auto_review_required: false,
node_repl_disabled: false,
auto_review_model_override: None,
model_specialty: None,
tool_mode: None,
multi_agent_version: preset.multi_agent_version,
multi_agent_reasoning_effort: None,
}
}
/// Write a models_cache.json file to the codex home directory.
/// This prevents ModelsManager from making network requests to refresh models.
/// The cache will be treated as fresh (within TTL) and used instead of fetching from the network.
/// Uses bundled-catalog-derived presets, converted to ModelInfo format.
pub async fn write_models_cache(codex_home: &Path) -> std::io::Result<()> {
// Get a stable bundled-catalog-derived preset list and filter for picker-visible entries.
let presets: Vec<&ModelPreset> = all_model_presets()
.iter()
.filter(|preset| preset.show_in_picker)
.collect();
// Convert presets to ModelInfo, assigning priorities (lower = earlier in list).
// Priority is used for sorting, so the first model gets the lowest priority.
let models: Vec<ModelInfo> = presets
.iter()
.enumerate()
.map(|(idx, preset)| {
// Lower priority = earlier in list.
let priority = idx as i32;
preset_to_info(preset, priority)
})
.collect();
write_models_cache_with_models(codex_home, models).await
}
/// Write a models_cache.json file with specific models.
/// Useful when tests need specific models to be available.
pub async fn write_models_cache_with_models(
codex_home: &Path,
models: Vec<ModelInfo>,
) -> std::io::Result<()> {
let config = akode_core::config::ConfigBuilder::default()
.loader_overrides(akode_config::LoaderOverrides::without_managed_config_for_tests())
.codex_home(codex_home.to_path_buf())
.build()
.await?;
let auth = akode_login::CodexAuth::from_auth_storage(
codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
)
.await?;
let cache = akode_model_provider::test_support::models_cache_entry(
&config.model_provider,
auth.as_ref(),
models.clone(),
);
let cache_path = codex_home.join("models_cache.json");
std::fs::write(cache_path, serde_json::to_string_pretty(&cache)?)?;
// aKode: providers without `model_catalog_url` never read `models_cache.json` (they
// use an explicit catalog or the provider's `/models` listing). Keep the cached
// models authoritative, as they were upstream, by serving them as the explicit
// catalog — replacing the bundled one `MockResponsesConfig` installs by default.
if config.model_provider.model_catalog_url.is_none() {
let config_path = codex_home.join("config.toml");
let config_text = std::fs::read_to_string(&config_path).unwrap_or_default();
let harness_catalog = codex_home.join(HARNESS_CATALOG_FILE);
// Upstream merged cached models over the bundled catalog by slug.
let mut catalog = serde_json::from_str::<akode_protocol::openai_models::ModelsResponse>(
include_str!("../../../models-manager/models.json"),
)?
.models;
for model in models {
match catalog
.iter()
.position(|existing| existing.slug == model.slug)
{
Some(index) => catalog[index] = model,
None => catalog.push(model),
}
}
if config_text.contains(HARNESS_CATALOG_FILE) && harness_catalog.exists() {
std::fs::write(
harness_catalog,
serde_json::to_string_pretty(&serde_json::json!({ "models": catalog }))?,
)?;
} else if !config_text.contains("model_catalog_json") {
if !config_path.exists() {
std::fs::write(&config_path, "")?;
}
write_model_catalog_json(codex_home, catalog)?;
}
}
Ok(())
}
/// Catalog file `MockResponsesConfig::write` installs unless a test configures one.
pub(crate) const HARNESS_CATALOG_FILE: &str = "test-models.json";
/// Write `models` as a `model_catalog_json` catalog and point `config.toml` at it.
///
/// API-key sessions without a provider model catalog URL never read `models_cache.json`, so
/// tests that pair specific model metadata with API-key auth configure the catalog directly.
pub fn write_model_catalog_json(codex_home: &Path, models: Vec<ModelInfo>) -> std::io::Result<()> {
let catalog_path = codex_home.join("models.json");
std::fs::write(
&catalog_path,
serde_json::to_string_pretty(&serde_json::json!({ "models": models }))?,
)?;
let config_path = codex_home.join("config.toml");
// Replace the default catalog `MockResponsesConfig::write` may have installed.
let config = std::fs::read_to_string(&config_path)?
.lines()
.filter(|line| !line.trim_start().starts_with("model_catalog_json"))
.collect::<Vec<_>>()
.join("\n");
std::fs::write(
&config_path,
format!(
"model_catalog_json = {}\n{config}",
serde_json::to_string(&catalog_path)?
),
)
}

View File

@@ -0,0 +1,128 @@
use core_test_support::responses;
use serde_json::json;
use std::path::Path;
pub fn create_command_execution_sse_response(
command: Vec<String>,
workdir: Option<&Path>,
timeout_ms: Option<u64>,
call_id: &str,
) -> anyhow::Result<String> {
let command_str = shlex::try_join(command.iter().map(String::as_str))?;
let mut arguments = json!({
"cmd": command_str,
"workdir": workdir.map(|w| w.to_string_lossy()),
});
if let Some(timeout_ms) = timeout_ms {
arguments["yield_time_ms"] = json!(timeout_ms);
}
let tool_call_arguments = serde_json::to_string(&arguments)?;
Ok(responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call(call_id, "exec_command", &tool_call_arguments),
responses::ev_completed("resp-1"),
]))
}
pub fn create_escalated_command_execution_sse_response(
command: Vec<String>,
workdir: Option<&Path>,
timeout_ms: Option<u64>,
call_id: &str,
) -> anyhow::Result<String> {
let command_str = shlex::try_join(command.iter().map(String::as_str))?;
let tool_call_arguments = serde_json::to_string(&json!({
"cmd": command_str,
"workdir": workdir.map(|w| w.to_string_lossy()),
"yield_time_ms": timeout_ms,
"sandbox_permissions": "require_escalated",
"justification": "Test approval request."
}))?;
Ok(responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call(call_id, "exec_command", &tool_call_arguments),
responses::ev_completed("resp-1"),
]))
}
pub fn create_final_assistant_message_sse_response(message: &str) -> anyhow::Result<String> {
Ok(responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_assistant_message("msg-1", message),
responses::ev_completed("resp-1"),
]))
}
pub fn create_apply_patch_sse_response(
patch_content: &str,
call_id: &str,
) -> anyhow::Result<String> {
Ok(responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_apply_patch_exec_command_call_via_heredoc(call_id, patch_content),
responses::ev_completed("resp-1"),
]))
}
pub fn create_exec_command_sse_response(call_id: &str) -> anyhow::Result<String> {
let (cmd, args) = if cfg!(windows) {
("cmd.exe", vec!["/d", "/c", "echo hi"])
} else {
("/bin/sh", vec!["-c", "echo hi"])
};
let command = std::iter::once(cmd.to_string())
.chain(args.into_iter().map(str::to_string))
.collect::<Vec<_>>();
let tool_call_arguments = serde_json::to_string(&json!({
"cmd": command.join(" "),
"yield_time_ms": 500
}))?;
Ok(responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call(call_id, "exec_command", &tool_call_arguments),
responses::ev_completed("resp-1"),
]))
}
pub fn create_request_user_input_sse_response(call_id: &str) -> anyhow::Result<String> {
let tool_call_arguments = serde_json::to_string(&json!({
"questions": [{
"id": "confirm_path",
"header": "Confirm",
"question": "Proceed with the plan?",
"options": [{
"label": "Yes (Recommended)",
"description": "Continue the current plan."
}, {
"label": "No",
"description": "Stop and revisit the approach."
}]
}]
}))?;
Ok(responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call(call_id, "request_user_input", &tool_call_arguments),
responses::ev_completed("resp-1"),
]))
}
pub fn create_request_permissions_sse_response(call_id: &str) -> anyhow::Result<String> {
let tool_call_arguments = serde_json::to_string(&json!({
"reason": "Select a workspace root",
"permissions": {
"file_system": {
"write": [
".",
"../shared"
]
}
}
}))?;
Ok(responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call(call_id, "request_permissions", &tool_call_arguments),
responses::ev_completed("resp-1"),
]))
}

View File

@@ -0,0 +1,422 @@
use anyhow::Result;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::GitInfo;
use akode_protocol::protocol::SessionMeta;
use akode_protocol::protocol::SessionMetaLine;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::ThreadHistoryMode;
use akode_protocol::protocol::ThreadSource;
use akode_protocol::protocol::TokenCountEvent;
use akode_protocol::protocol::TokenUsage;
use akode_protocol::protocol::TokenUsageInfo;
use core_test_support::test_path_buf;
use serde_json::json;
use std::fs;
use std::fs::FileTimes;
use std::path::Path;
use std::path::PathBuf;
use uuid::Uuid;
pub fn rollout_path(codex_home: &Path, filename_ts: &str, thread_id: &str) -> PathBuf {
let year = &filename_ts[0..4];
let month = &filename_ts[5..7];
let day = &filename_ts[8..10];
codex_home
.join("sessions")
.join(year)
.join(month)
.join(day)
.join(format!("rollout-{filename_ts}-{thread_id}.jsonl"))
}
/// Create a minimal rollout file under `AKODE_HOME/sessions/YYYY/MM/DD/`.
///
/// - `filename_ts` is the filename timestamp component in `YYYY-MM-DDThh-mm-ss` format.
/// - `meta_rfc3339` is the envelope timestamp used in JSON lines.
/// - `preview` is the user message preview text.
/// - `model_provider` optionally sets the provider in the session meta payload.
///
/// Returns the generated conversation/session UUID as a string.
pub fn create_fake_rollout(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
) -> Result<String> {
create_fake_rollout_with_source(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
git_info,
SessionSource::Cli,
)
}
/// Creates a minimal paginated rollout with ordinalized JSONL records.
pub fn create_fake_paginated_rollout(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
) -> Result<String> {
let thread_id = create_fake_rollout(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
git_info,
)?;
let path = rollout_path(codex_home, filename_ts, &thread_id);
let mut lines = fs::read_to_string(path.as_path())?
.lines()
.map(serde_json::from_str::<serde_json::Value>)
.collect::<Result<Vec<_>, _>>()?;
lines[0]["payload"]["history_mode"] = serde_json::to_value(ThreadHistoryMode::Paginated)?;
for (ordinal, line) in lines.iter_mut().enumerate() {
line["ordinal"] = serde_json::to_value(ordinal)?;
}
let contents = lines
.into_iter()
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n");
fs::write(path, format!("{contents}\n"))?;
Ok(thread_id)
}
/// Creates a minimal rollout whose history includes a persisted token usage event.
///
/// Resume and fork tests use this fixture to verify lifecycle replay of restored
/// usage without starting a model turn. The exact token values are intentionally
/// non-zero and asymmetric so assertions catch swapped total/last fields and
/// dropped cached or reasoning counters.
pub fn create_fake_rollout_with_token_usage(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
) -> Result<String> {
let thread_id = create_fake_rollout(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
/*git_info*/ None,
)?;
let payload = serde_json::to_value(EventMsg::TokenCount(TokenCountEvent {
info: Some(TokenUsageInfo {
total_token_usage: TokenUsage {
input_tokens: 120,
cached_input_tokens: 20,
cache_write_input_tokens: 0,
output_tokens: 30,
reasoning_output_tokens: 10,
total_tokens: 150,
codex_rollout_budget_units: None,
},
last_usage_includes_reasoning: None,
last_token_usage: TokenUsage {
input_tokens: 70,
cached_input_tokens: 10,
cache_write_input_tokens: 0,
output_tokens: 20,
reasoning_output_tokens: 5,
total_tokens: 90,
codex_rollout_budget_units: None,
},
model_context_window: Some(200_000),
}),
rate_limits: None,
}))?;
let file_path = rollout_path(codex_home, filename_ts, &thread_id);
let line = json!({
"timestamp": meta_rfc3339,
"type": "event_msg",
"payload": payload
})
.to_string();
fs::write(
&file_path,
format!("{}{}\n", fs::read_to_string(&file_path)?, line),
)?;
Ok(thread_id)
}
/// Create a minimal rollout file with an explicit session source.
pub fn create_fake_rollout_with_source(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
source: SessionSource,
) -> Result<String> {
create_fake_rollout_with_session_and_thread_source(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
git_info,
source,
/*thread_source*/ None,
)
}
/// Create a minimal rollout file with explicit session and thread sources.
#[allow(clippy::too_many_arguments)]
pub fn create_fake_rollout_with_session_and_thread_source(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
source: SessionSource,
thread_source: Option<ThreadSource>,
) -> Result<String> {
create_fake_rollout_with_source_and_parent_thread_id(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
git_info,
source,
thread_source,
/*session_id*/ None,
/*parent_thread_id*/ None,
)
}
/// Create a minimal rollout file with an explicit root session and control parent.
#[allow(clippy::too_many_arguments)]
pub fn create_fake_parented_rollout_with_source(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
source: SessionSource,
session_id: SessionId,
parent_thread_id: ThreadId,
) -> Result<String> {
create_fake_rollout_with_source_and_parent_thread_id(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
git_info,
source,
/*thread_source*/ None,
Some(session_id),
Some(parent_thread_id),
)
}
#[allow(clippy::too_many_arguments)]
fn create_fake_rollout_with_source_and_parent_thread_id(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
source: SessionSource,
thread_source: Option<ThreadSource>,
session_id: Option<SessionId>,
parent_thread_id: Option<ThreadId>,
) -> Result<String> {
let uuid = Uuid::new_v4();
let uuid_str = uuid.to_string();
let conversation_id = ThreadId::from_string(&uuid_str)?;
let session_id = session_id.unwrap_or_else(|| conversation_id.into());
let file_path = rollout_path(codex_home, filename_ts, &uuid_str);
let dir = file_path
.parent()
.ok_or_else(|| anyhow::anyhow!("missing rollout parent directory"))?;
fs::create_dir_all(dir)?;
// Build JSONL lines
let meta = SessionMeta {
account_scoped: false,
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id,
id: conversation_id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id,
timestamp: meta_rfc3339.to_string(),
cwd: test_path_buf("/"),
runtime_workspace_roots: None,
originator: "codex".to_string(),
cli_version: "0.0.0".to_string(),
source,
thread_source,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: model_provider.map(str::to_string),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode: Default::default(),
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
};
let payload = serde_json::to_value(SessionMetaLine {
meta,
git: git_info,
})?;
let lines = [
json!({
"timestamp": meta_rfc3339,
"type": "session_meta",
"payload": payload
})
.to_string(),
json!({
"timestamp": meta_rfc3339,
"type":"response_item",
"payload": {
"type":"message",
"role":"user",
"content":[{"type":"input_text","text": preview}]
}
})
.to_string(),
json!({
"timestamp": meta_rfc3339,
"type":"event_msg",
"payload": {
"type":"user_message",
"message": preview,
"kind": "plain"
}
})
.to_string(),
];
fs::write(&file_path, lines.join("\n") + "\n")?;
let parsed = chrono::DateTime::parse_from_rfc3339(meta_rfc3339)?.with_timezone(&chrono::Utc);
let times = FileTimes::new().set_modified(parsed.into());
std::fs::OpenOptions::new()
.append(true)
.open(&file_path)?
.set_times(times)?;
Ok(uuid_str)
}
pub fn create_fake_rollout_with_text_elements(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
text_elements: Vec<serde_json::Value>,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
) -> Result<String> {
let uuid = Uuid::new_v4();
let uuid_str = uuid.to_string();
let conversation_id = ThreadId::from_string(&uuid_str)?;
// sessions/YYYY/MM/DD derived from filename_ts (YYYY-MM-DDThh-mm-ss)
let year = &filename_ts[0..4];
let month = &filename_ts[5..7];
let day = &filename_ts[8..10];
let dir = codex_home.join("sessions").join(year).join(month).join(day);
fs::create_dir_all(&dir)?;
let file_path = dir.join(format!("rollout-{filename_ts}-{uuid}.jsonl"));
// Build JSONL lines
let meta = SessionMeta {
account_scoped: false,
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id: conversation_id.into(),
id: conversation_id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp: meta_rfc3339.to_string(),
cwd: test_path_buf("/"),
runtime_workspace_roots: None,
originator: "codex".to_string(),
cli_version: "0.0.0".to_string(),
source: SessionSource::Cli,
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: model_provider.map(str::to_string),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode: Default::default(),
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
};
let payload = serde_json::to_value(SessionMetaLine {
meta,
git: git_info,
})?;
let lines = [
json!( {
"timestamp": meta_rfc3339,
"type": "session_meta",
"payload": payload
})
.to_string(),
json!( {
"timestamp": meta_rfc3339,
"type":"response_item",
"payload": {
"type":"message",
"role":"user",
"content":[{"type":"input_text","text": preview}]
}
})
.to_string(),
json!( {
"timestamp": meta_rfc3339,
"type":"event_msg",
"payload": {
"type":"user_message",
"message": preview,
"text_elements": text_elements,
"local_images": []
}
})
.to_string(),
];
fs::write(file_path, lines.join("\n") + "\n")?;
Ok(uuid_str)
}

View File

@@ -0,0 +1,157 @@
use std::io;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::task::JoinSet;
use tokio::time::Instant;
use tokio::time::sleep_until;
use tokio_util::task::AbortOnDropHandle;
use url::Host;
use url::Url;
const FORWARD_BUFFER_BYTES: usize = 64 * 1024;
const FORWARD_QUEUE_CHUNKS: usize = 16;
pub(crate) struct WebsocketDelayInterposer {
websocket_url: String,
accept_task: JoinHandle<()>,
}
impl WebsocketDelayInterposer {
pub(crate) async fn start(upstream_url: &str, added_delay: Duration) -> Result<Self> {
let upstream = websocket_authority(upstream_url)?;
let listener = TcpListener::bind("127.0.0.1:0")
.await
.context("bind RPC delay interposer")?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let accept_task = tokio::spawn(async move {
let mut connections = JoinSet::new();
loop {
tokio::select! {
accepted = listener.accept() => {
let Ok((downstream, _peer)) = accepted else {
break;
};
let upstream = upstream.clone();
connections.spawn(async move {
let Ok(upstream) = TcpStream::connect(upstream).await else {
return;
};
let _ = proxy_connection(downstream, upstream, added_delay).await;
});
}
_ = connections.join_next(), if !connections.is_empty() => {}
}
}
});
Ok(Self {
websocket_url,
accept_task,
})
}
pub(crate) fn websocket_url(&self) -> &str {
&self.websocket_url
}
}
impl Drop for WebsocketDelayInterposer {
fn drop(&mut self) {
self.accept_task.abort();
}
}
fn websocket_authority(websocket_url: &str) -> Result<String> {
let websocket_url = Url::parse(websocket_url).context("parse RPC delay upstream URL")?;
if websocket_url.scheme() != "ws" {
return Err(anyhow!("RPC delay requires a ws:// exec-server URL"));
}
let host = websocket_url
.host()
.ok_or_else(|| anyhow!("RPC delay exec-server URL has no host"))?;
let port = websocket_url
.port_or_known_default()
.ok_or_else(|| anyhow!("RPC delay exec-server URL has no port"))?;
let host = match host {
Host::Domain(host) => host.to_string(),
Host::Ipv4(host) => host.to_string(),
Host::Ipv6(host) => format!("[{host}]"),
};
Ok(format!("{host}:{port}"))
}
async fn proxy_connection(
downstream: TcpStream,
upstream: TcpStream,
added_delay: Duration,
) -> io::Result<()> {
let (downstream_read, downstream_write) = downstream.into_split();
let (upstream_read, upstream_write) = upstream.into_split();
let client_to_server = forward_direction(downstream_read, upstream_write, added_delay);
let server_to_client = forward_direction(upstream_read, downstream_write, added_delay);
tokio::try_join!(client_to_server, server_to_client)?;
Ok(())
}
async fn forward_direction<R, W>(
mut reader: R,
mut writer: W,
added_delay: Duration,
) -> io::Result<()>
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
// tokio::io::copy would wait before reading the next chunk, turning a
// fixed propagation delay into a bandwidth limit. Timestamping reads into
// a bounded queue lets close-together chunks emerge close together after
// the same delay while still applying backpressure.
let (tx, mut rx) = mpsc::channel::<DelayedChunk>(FORWARD_QUEUE_CHUNKS);
let reader_task = AbortOnDropHandle::new(tokio::spawn(async move {
loop {
let mut bytes = vec![0; FORWARD_BUFFER_BYTES];
let read = reader.read(&mut bytes).await?;
if read == 0 {
break;
}
bytes.truncate(read);
let chunk = DelayedChunk {
deliver_at: Instant::now() + added_delay,
bytes,
};
if tx.send(chunk).await.is_err() {
break;
}
}
Ok::<(), io::Error>(())
}));
while let Some(chunk) = rx.recv().await {
sleep_until(chunk.deliver_at).await;
writer.write_all(&chunk.bytes).await?;
}
writer.shutdown().await?;
reader_task
.await
.map_err(|err| io::Error::other(format!("RPC delay reader task failed: {err}")))??;
Ok(())
}
struct DelayedChunk {
deliver_at: Instant,
bytes: Vec<u8>,
}
#[cfg(test)]
#[path = "rpc_delay_tests.rs"]
mod tests;

View File

@@ -0,0 +1,181 @@
use std::collections::VecDeque;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Context;
use std::task::Poll;
use std::time::Duration;
use pretty_assertions::assert_eq;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::ReadBuf;
use tokio::io::duplex;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::time::advance;
use tokio::time::timeout;
use super::WebsocketDelayInterposer;
use super::forward_direction;
use super::websocket_authority;
#[tokio::test(start_paused = true)]
async fn delays_then_flushes_eof() -> anyhow::Result<()> {
let delay = Duration::from_millis(15);
let (mut input_writer, input_reader) = duplex(/*max_buf_size*/ 64);
let (output_writer, mut output_reader) = duplex(/*max_buf_size*/ 64);
let forward_task = tokio::spawn(forward_direction(input_reader, output_writer, delay));
input_writer.write_all(b"payload").await?;
input_writer.shutdown().await?;
tokio::task::yield_now().await;
let mut before_delay = [0; 1];
assert!(
timeout(Duration::ZERO, output_reader.read(&mut before_delay))
.await
.is_err()
);
advance(delay).await;
let mut output = Vec::new();
output_reader.read_to_end(&mut output).await?;
assert_eq!(output, b"payload");
forward_task.await??;
Ok(())
}
#[tokio::test(start_paused = true)]
async fn burst_chunks_share_one_deadline() -> anyhow::Result<()> {
let delay = Duration::from_millis(15);
let (mut input_writer, input_reader) = duplex(/*max_buf_size*/ 1);
let (output_writer, mut output_reader) = duplex(/*max_buf_size*/ 64);
let forward_task = tokio::spawn(forward_direction(input_reader, output_writer, delay));
input_writer.write_all(b"ab").await?;
input_writer.shutdown().await?;
tokio::task::yield_now().await;
advance(delay).await;
tokio::task::yield_now().await;
let mut output = [0; 2];
timeout(Duration::ZERO, output_reader.read_exact(&mut output)).await??;
assert_eq!(output, *b"ab");
forward_task.await??;
Ok(())
}
#[tokio::test]
async fn write_error_cancels_reader() {
let reader_dropped = Arc::new(AtomicBool::new(false));
let reader = PendingAfterChunkReader::new(Arc::clone(&reader_dropped));
let error = forward_direction(reader, FailingWriter, Duration::ZERO)
.await
.expect_err("failing writer should fail forwarding");
assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
for _ in 0..10 {
if reader_dropped.load(Ordering::Acquire) {
break;
}
tokio::task::yield_now().await;
}
assert!(reader_dropped.load(Ordering::Acquire));
}
#[tokio::test]
async fn zero_delay_loopback_forwards_and_closes_active_sockets() -> anyhow::Result<()> {
let upstream_listener = TcpListener::bind("127.0.0.1:0").await?;
let upstream_url = format!("ws://{}", upstream_listener.local_addr()?);
let upstream_task = tokio::spawn(async move {
let (mut upstream, _) = upstream_listener.accept().await?;
let mut request = [0; 5];
upstream.read_exact(&mut request).await?;
assert_eq!(request, *b"hello");
upstream.write_all(b"world").await?;
let mut after_drop = [0; 1];
let read = timeout(Duration::from_secs(1), upstream.read(&mut after_drop)).await??;
Ok::<usize, anyhow::Error>(read)
});
let interposer = WebsocketDelayInterposer::start(&upstream_url, Duration::ZERO).await?;
let mut downstream =
TcpStream::connect(websocket_authority(interposer.websocket_url())?).await?;
downstream.write_all(b"hello").await?;
let mut response = [0; 5];
downstream.read_exact(&mut response).await?;
assert_eq!(response, *b"world");
drop(interposer);
tokio::task::yield_now().await;
let mut after_drop = [0; 1];
let read = timeout(Duration::from_secs(1), downstream.read(&mut after_drop)).await??;
assert_eq!(read, 0);
assert_eq!(upstream_task.await??, 0);
Ok(())
}
struct PendingAfterChunkReader {
chunks: VecDeque<Vec<u8>>,
dropped: Arc<AtomicBool>,
}
impl PendingAfterChunkReader {
fn new(dropped: Arc<AtomicBool>) -> Self {
Self {
chunks: VecDeque::from([b"x".to_vec()]),
dropped,
}
}
}
impl AsyncRead for PendingAfterChunkReader {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let Some(chunk) = self.chunks.pop_front() else {
return Poll::Pending;
};
buf.put_slice(&chunk);
Poll::Ready(Ok(()))
}
}
impl Drop for PendingAfterChunkReader {
fn drop(&mut self) {
self.dropped.store(true, Ordering::Release);
}
}
struct FailingWriter;
impl AsyncWrite for FailingWriter {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
_buf: &[u8],
) -> Poll<io::Result<usize>> {
Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"synthetic write failure",
)))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}

File diff suppressed because it is too large Load Diff