Base: codex-main originale (prima del fork aKode)
This commit is contained in:
5
bazel/rules/testing/BUILD.bazel
Normal file
5
bazel/rules/testing/BUILD.bazel
Normal file
@@ -0,0 +1,5 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files([
|
||||
"foreign_platform_binary.bzl",
|
||||
])
|
||||
31
bazel/rules/testing/compat/BUILD.bazel
Normal file
31
bazel/rules/testing/compat/BUILD.bazel
Normal file
@@ -0,0 +1,31 @@
|
||||
load("@rules_rust//rust:defs.bzl", "rust_test")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files(["exec_server_compat_test.bzl"])
|
||||
|
||||
# exec_server_compat_test wraps this shared binary with current or released builds.
|
||||
# Keep it manual so only wrapped compatibility tests enter the normal test graph.
|
||||
rust_test(
|
||||
name = "exec-server-compat-test-bin",
|
||||
srcs = ["exec_server_compat_test.rs"],
|
||||
crate_name = "exec_server_compat_test",
|
||||
crate_root = "exec_server_compat_test.rs",
|
||||
edition = "2024",
|
||||
tags = ["manual"],
|
||||
target_compatible_with = [
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
],
|
||||
visibility = ["//codex-rs/exec-server:__pkg__"],
|
||||
deps = [
|
||||
"//codex-rs/exec-server",
|
||||
"//codex-rs/exec-server/tests/support",
|
||||
"@crates//:anyhow",
|
||||
"@crates//:pretty_assertions",
|
||||
"@crates//:serde_json",
|
||||
"@crates//:tempfile",
|
||||
"@crates//:tokio",
|
||||
"@crates//:wiremock",
|
||||
],
|
||||
)
|
||||
47
bazel/rules/testing/compat/exec_server_compat_test.bzl
Normal file
47
bazel/rules/testing/compat/exec_server_compat_test.bzl
Normal file
@@ -0,0 +1,47 @@
|
||||
"""Bazel coverage for app-server and exec-server release compatibility."""
|
||||
|
||||
load("//:defs.bzl", "workspace_root_test")
|
||||
|
||||
def exec_server_compat_test(
|
||||
name,
|
||||
comparison_binary = None,
|
||||
current_binary = "//codex-rs/cli:codex",
|
||||
release = None):
|
||||
"""Tests both executor directions against another Codex build or release.
|
||||
|
||||
Args:
|
||||
name: Name of the generated compatibility test target.
|
||||
comparison_binary: Built Codex executable to compare with the current build.
|
||||
current_binary: Built Codex executable representing the current version.
|
||||
release: External release repository exposing `:codex` and `:package`.
|
||||
"""
|
||||
if (comparison_binary == None) == (release == None):
|
||||
fail("exactly one of comparison_binary and release must be set")
|
||||
|
||||
comparison = comparison_binary if release == None else release + "//:codex"
|
||||
data = [] if release == None else [release + "//:package"]
|
||||
comparison_alias = name + "-comparison-binary"
|
||||
native.alias(
|
||||
name = comparison_alias,
|
||||
actual = comparison,
|
||||
tags = ["manual"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
workspace_root_test(
|
||||
name = name,
|
||||
args = ["--test-threads=1"],
|
||||
data = data,
|
||||
runfile_env = {
|
||||
"//codex-rs/bwrap:bwrap": "CARGO_BIN_EXE_bwrap",
|
||||
current_binary: "CODEX_TEST_CURRENT_CODEX",
|
||||
":" + comparison_alias: "CODEX_TEST_RELEASED_CODEX",
|
||||
},
|
||||
tags = ["no-sandbox"],
|
||||
target_compatible_with = [
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
],
|
||||
test_bin = "//bazel/rules/testing/compat:exec-server-compat-test-bin",
|
||||
workspace_root_marker = "//codex-rs/utils/cargo-bin:repo_root.marker",
|
||||
)
|
||||
439
bazel/rules/testing/compat/exec_server_compat_test.rs
Normal file
439
bazel/rules/testing/compat/exec_server_compat_test.rs
Normal file
@@ -0,0 +1,439 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID_ENV_VAR;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_NOISE_REGISTRY_URL_ENV_VAR;
|
||||
use codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR;
|
||||
use codex_exec_server::REMOTE_ENVIRONMENT_ID;
|
||||
use codex_exec_server_test_support::relay::TEST_TIMEOUT as VERSION_SKEW_TIMEOUT;
|
||||
use codex_exec_server_test_support::relay::accept_websocket;
|
||||
use codex_exec_server_test_support::relay::assert_relay_data_is_encrypted;
|
||||
use codex_exec_server_test_support::relay::proxy_relay_frames;
|
||||
use codex_exec_server_test_support::relay::registered_executor_public_key;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::io::Lines;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::process::ChildStdin;
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const ENVIRONMENT_ID: &str = "env-noise-relay-test";
|
||||
const EXECUTOR_REGISTRATION_ID: &str = "registration-1";
|
||||
const HARNESS_KEY_AUTHORIZATION: &str = "harness-key-authorization";
|
||||
const REGISTRY_TOKEN: &str = "registry-token";
|
||||
const RELEASED_CODEX_ENV_VAR: &str = "CODEX_TEST_RELEASED_CODEX";
|
||||
const CURRENT_CODEX_ENV_VAR: &str = "CODEX_TEST_CURRENT_CODEX";
|
||||
const EXECUTOR_MARKER_ENV_VAR: &str = "CODEX_EXECUTOR_VERSION_SKEW_MARKER";
|
||||
const EXPECTED_OUTPUT: &str = "executor-version-skew-ok";
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn current_app_server_runs_commands_on_released_exec_server_over_noise() -> Result<()> {
|
||||
let Some((current, released)) = version_skew_binaries()? else {
|
||||
return Ok(());
|
||||
};
|
||||
assert_noise_version_skew(¤t, &released).await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn released_app_server_runs_commands_on_current_exec_server_over_noise() -> Result<()> {
|
||||
let Some((current, released)) = version_skew_binaries()? else {
|
||||
return Ok(());
|
||||
};
|
||||
assert_noise_version_skew(&released, ¤t).await
|
||||
}
|
||||
|
||||
fn version_skew_binaries() -> Result<Option<(PathBuf, PathBuf)>> {
|
||||
let Some(released) = std::env::var_os(RELEASED_CODEX_ENV_VAR) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let current = std::env::var_os(CURRENT_CODEX_ENV_VAR)
|
||||
.with_context(|| format!("{CURRENT_CODEX_ENV_VAR} must name the current Codex binary"))?;
|
||||
let current = PathBuf::from(current);
|
||||
let released = PathBuf::from(released);
|
||||
anyhow::ensure!(
|
||||
current.is_file(),
|
||||
"current Codex does not exist: {}",
|
||||
current.display()
|
||||
);
|
||||
anyhow::ensure!(
|
||||
released.is_file(),
|
||||
"released Codex does not exist: {}",
|
||||
released.display()
|
||||
);
|
||||
Ok(Some((current, released)))
|
||||
}
|
||||
|
||||
async fn assert_noise_version_skew(app_binary: &Path, executor_binary: &Path) -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let workspace = TempDir::new()?;
|
||||
let skill_dir = workspace.path().join(".agents/skills/version-skew");
|
||||
std::fs::create_dir_all(&skill_dir)?;
|
||||
let skill_path = skill_dir.join("SKILL.md");
|
||||
let skill_body = "Repository instructions loaded across executor versions.";
|
||||
std::fs::write(
|
||||
&skill_path,
|
||||
format!(
|
||||
"---\nname: version-skew\ndescription: Check executor compatibility.\n---\n{skill_body}\n"
|
||||
),
|
||||
)?;
|
||||
let selected_root = workspace.path().join("selected-skills");
|
||||
let selected_skill_dir = selected_root.join("selected-version-skew");
|
||||
std::fs::create_dir_all(&selected_skill_dir)?;
|
||||
let selected_skill_body = "Selected instructions loaded across executor versions.";
|
||||
std::fs::write(
|
||||
selected_skill_dir.join("SKILL.md"),
|
||||
format!(
|
||||
"---\nname: selected-version-skew\ndescription: Check selected skill compatibility.\n---\n{selected_skill_body}\n"
|
||||
),
|
||||
)?;
|
||||
let model = mock_model(workspace.path()).await?;
|
||||
let model_url = model.uri();
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
model = "mock-model"
|
||||
approval_policy = "never"
|
||||
sandbox_mode = "workspace-write"
|
||||
model_provider = "mock_provider"
|
||||
|
||||
[features]
|
||||
executor_capability_discovery = false
|
||||
executor_capability_discovery_v2 = false
|
||||
|
||||
[model_providers.mock_provider]
|
||||
name = "Mock provider"
|
||||
base_url = "{model_url}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let rendezvous_url = format!("ws://{}", listener.local_addr()?);
|
||||
let registry = MockServer::start().await;
|
||||
let registry_url = registry.uri();
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/cloud/environment/{ENVIRONMENT_ID}/register"
|
||||
)))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"environment_id": ENVIRONMENT_ID,
|
||||
"url": format!("{rendezvous_url}/relay?role=environment"),
|
||||
"security_profile": "noise_hybrid_ik_v1",
|
||||
"executor_registration_id": EXECUTOR_REGISTRATION_ID,
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/cloud/environment/{ENVIRONMENT_ID}/validate"
|
||||
)))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"valid": true})))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.await;
|
||||
|
||||
let mut executor = Command::new(executor_binary)
|
||||
.args([
|
||||
"exec-server",
|
||||
"--remote",
|
||||
registry_url.as_str(),
|
||||
"--environment-id",
|
||||
ENVIRONMENT_ID,
|
||||
])
|
||||
.current_dir(codex_home.path())
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env("CODEX_API_KEY", REGISTRY_TOKEN)
|
||||
.env(EXECUTOR_MARKER_ENV_VAR, EXPECTED_OUTPUT)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.with_context(|| format!("start remote executor from {}", executor_binary.display()))?;
|
||||
|
||||
let environment_websocket = accept_websocket(&listener, "environment").await?;
|
||||
let executor_public_key = registered_executor_public_key(®istry).await?;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!("/cloud/environment/{ENVIRONMENT_ID}/connect")))
|
||||
.and(header("authorization", format!("Bearer {REGISTRY_TOKEN}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"environment_id": ENVIRONMENT_ID,
|
||||
"url": format!("{rendezvous_url}/relay?role=harness"),
|
||||
"security_profile": "noise_hybrid_ik_v1",
|
||||
"executor_registration_id": EXECUTOR_REGISTRATION_ID,
|
||||
"executor_public_key": executor_public_key,
|
||||
"harness_key_authorization": HARNESS_KEY_AUTHORIZATION,
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.await;
|
||||
|
||||
let captured_frames = Arc::new(Mutex::new(Vec::new()));
|
||||
let captured_relay_frames = Arc::clone(&captured_frames);
|
||||
let relay = tokio::spawn(async move {
|
||||
let harness_websocket = accept_websocket(&listener, "harness").await?;
|
||||
proxy_relay_frames(
|
||||
environment_websocket,
|
||||
harness_websocket,
|
||||
captured_relay_frames,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
let mut app_server = Command::new(app_binary)
|
||||
.arg("app-server")
|
||||
.current_dir(codex_home.path())
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.env("CODEX_API_KEY", REGISTRY_TOKEN)
|
||||
.env(
|
||||
"CODEX_APP_SERVER_MANAGED_CONFIG_PATH",
|
||||
codex_home.path().join("managed_config.toml"),
|
||||
)
|
||||
.env(CODEX_EXEC_SERVER_NOISE_REGISTRY_URL_ENV_VAR, ®istry_url)
|
||||
.env(
|
||||
CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID_ENV_VAR,
|
||||
ENVIRONMENT_ID,
|
||||
)
|
||||
.env(CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR, REGISTRY_TOKEN)
|
||||
.env_remove(CODEX_EXEC_SERVER_URL_ENV_VAR)
|
||||
.env_remove(EXECUTOR_MARKER_ENV_VAR)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.with_context(|| format!("start app-server from {}", app_binary.display()))?;
|
||||
let mut stdin = app_server.stdin.take().context("app-server stdin")?;
|
||||
let stdout = app_server.stdout.take().context("app-server stdout")?;
|
||||
let mut stdout = BufReader::new(stdout).lines();
|
||||
let mut notifications = Vec::new();
|
||||
|
||||
app_server_request(
|
||||
&mut stdin,
|
||||
&mut stdout,
|
||||
&mut notifications,
|
||||
/*id*/ 1,
|
||||
"initialize",
|
||||
json!({
|
||||
"clientInfo": {"name": "noise-version-skew", "version": "0.1.0"},
|
||||
"capabilities": {"experimentalApi": true},
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
stdin.write_all(b"{\"method\":\"initialized\"}\n").await?;
|
||||
|
||||
let thread = app_server_request(
|
||||
&mut stdin,
|
||||
&mut stdout,
|
||||
&mut notifications,
|
||||
/*id*/ 2,
|
||||
"thread/start",
|
||||
json!({
|
||||
"cwd": workspace.path(),
|
||||
"selectedCapabilityRoots": [{
|
||||
"id": "version-skew-selected",
|
||||
"location": {
|
||||
"type": "environment",
|
||||
"environmentId": REMOTE_ENVIRONMENT_ID,
|
||||
"path": selected_root,
|
||||
},
|
||||
}],
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let thread_id = thread["thread"]["id"]
|
||||
.as_str()
|
||||
.context("thread/start should return a thread id")?;
|
||||
app_server_request(
|
||||
&mut stdin,
|
||||
&mut stdout,
|
||||
&mut notifications,
|
||||
/*id*/ 3,
|
||||
"turn/start",
|
||||
json!({
|
||||
"threadId": thread_id,
|
||||
"input": [{
|
||||
"type": "text",
|
||||
"text": "Use $selected-version-skew and run the Noise compatibility command.",
|
||||
"textElements": [],
|
||||
}, {
|
||||
"type": "skill",
|
||||
"name": "version-skew",
|
||||
"path": skill_path,
|
||||
}],
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
while !notifications
|
||||
.iter()
|
||||
.any(|notification: &Value| notification["method"] == "turn/completed")
|
||||
{
|
||||
let line = timeout(VERSION_SKEW_TIMEOUT, stdout.next_line())
|
||||
.await
|
||||
.context("waiting for turn/completed")??
|
||||
.context("app-server exited before turn/completed")?;
|
||||
notifications.push(serde_json::from_str(&line)?);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(workspace.path().join("version-skew-output.txt"))?,
|
||||
EXPECTED_OUTPUT
|
||||
);
|
||||
let requests = model.received_requests().await.context("model requests")?;
|
||||
let first_request = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path() == "/v1/responses")
|
||||
.context("model response request")?;
|
||||
let first_request: Value = serde_json::from_slice(&first_request.body)?;
|
||||
let input = first_request["input"].as_array().context("model input")?;
|
||||
assert!(input.iter().any(|item| {
|
||||
item["role"] == "developer"
|
||||
&& item["content"]
|
||||
.to_string()
|
||||
.contains("selected-version-skew")
|
||||
}));
|
||||
for body in [skill_body, selected_skill_body] {
|
||||
assert!(
|
||||
input
|
||||
.iter()
|
||||
.any(|item| item["role"] == "user" && item["content"].to_string().contains(body))
|
||||
);
|
||||
}
|
||||
assert_relay_data_is_encrypted(&captured_frames)?;
|
||||
registry.verify().await;
|
||||
model.verify().await;
|
||||
|
||||
let _ = app_server.start_kill();
|
||||
let _ = executor.start_kill();
|
||||
relay.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn app_server_request(
|
||||
stdin: &mut ChildStdin,
|
||||
stdout: &mut Lines<BufReader<ChildStdout>>,
|
||||
notifications: &mut Vec<Value>,
|
||||
id: u64,
|
||||
method: &str,
|
||||
params: Value,
|
||||
) -> Result<Value> {
|
||||
let request = json!({"id": id, "method": method, "params": params});
|
||||
stdin.write_all(request.to_string().as_bytes()).await?;
|
||||
stdin.write_all(b"\n").await?;
|
||||
|
||||
loop {
|
||||
let line = timeout(VERSION_SKEW_TIMEOUT, stdout.next_line())
|
||||
.await
|
||||
.with_context(|| format!("waiting for {method} response"))??
|
||||
.with_context(|| format!("app-server exited before {method} response"))?;
|
||||
let response: Value = serde_json::from_str(&line)?;
|
||||
if response["id"] == id {
|
||||
anyhow::ensure!(
|
||||
response.get("error").is_none(),
|
||||
"{method} failed: {}",
|
||||
response["error"]
|
||||
);
|
||||
return response.get("result").cloned().context("missing result");
|
||||
}
|
||||
notifications.push(response);
|
||||
}
|
||||
}
|
||||
|
||||
async fn mock_model(codex_home: &Path) -> Result<MockServer> {
|
||||
let server = MockServer::start().await;
|
||||
let arguments = serde_json::to_string(&json!({
|
||||
"cmd": format!("printf '%s' \"${EXECUTOR_MARKER_ENV_VAR}\" > version-skew-output.txt"),
|
||||
"workdir": codex_home,
|
||||
"yield_time_ms": 5_000,
|
||||
}))?;
|
||||
let completed = |id| {
|
||||
json!({
|
||||
"type": "response.completed",
|
||||
"response": {
|
||||
"id": id,
|
||||
"usage": {
|
||||
"input_tokens": 0,
|
||||
"input_tokens_details": null,
|
||||
"output_tokens": 0,
|
||||
"output_tokens_details": null,
|
||||
"total_tokens": 0,
|
||||
},
|
||||
},
|
||||
})
|
||||
};
|
||||
let responses = vec![
|
||||
event_stream(vec![
|
||||
json!({"type": "response.created", "response": {"id": "response-1"}}),
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"item": {
|
||||
"type": "function_call",
|
||||
"call_id": "noise-version-skew-command",
|
||||
"name": "exec_command",
|
||||
"arguments": arguments,
|
||||
},
|
||||
}),
|
||||
completed("response-1"),
|
||||
])?,
|
||||
event_stream(vec![
|
||||
json!({"type": "response.created", "response": {"id": "response-2"}}),
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"item": {
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"id": "message-1",
|
||||
"content": [{"type": "output_text", "text": "done"}],
|
||||
},
|
||||
}),
|
||||
completed("response-2"),
|
||||
])?,
|
||||
];
|
||||
for response in responses {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/responses"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(response, "text/event-stream"))
|
||||
.up_to_n_times(1)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
fn event_stream(events: Vec<Value>) -> Result<String> {
|
||||
events
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
let event_type = event["type"].as_str().context("SSE event type")?;
|
||||
Ok(format!("event: {event_type}\ndata: {event}\n\n"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
53
bazel/rules/testing/foreign_platform_binary.bzl
Normal file
53
bazel/rules/testing/foreign_platform_binary.bzl
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Makes a binary built for a foreign platform available as test data."""
|
||||
|
||||
_EXTRA_RUSTC_FLAGS = "@rules_rust//rust/settings:extra_rustc_flags"
|
||||
|
||||
def _foreign_platform_transition_impl(settings, attr):
|
||||
# A transition cannot rewrite a dependency's rule attributes. Use the
|
||||
# rules_rust build setting when every Rust target in the foreign
|
||||
# configuration needs additional compiler or linker flags.
|
||||
return {
|
||||
"//command_line_option:platforms": [attr.platform],
|
||||
_EXTRA_RUSTC_FLAGS: settings[_EXTRA_RUSTC_FLAGS] + attr.extra_rustc_flags,
|
||||
}
|
||||
|
||||
_foreign_platform_transition = transition(
|
||||
implementation = _foreign_platform_transition_impl,
|
||||
inputs = [_EXTRA_RUSTC_FLAGS],
|
||||
outputs = [
|
||||
"//command_line_option:platforms",
|
||||
_EXTRA_RUSTC_FLAGS,
|
||||
],
|
||||
)
|
||||
|
||||
def _foreign_platform_binary_impl(ctx):
|
||||
if len(ctx.attr.binary) != 1:
|
||||
fail("expected exactly one transitioned binary")
|
||||
binary = ctx.attr.binary[0][DefaultInfo]
|
||||
runfiles = ctx.runfiles(transitive_files = binary.files)
|
||||
runfiles = runfiles.merge(binary.default_runfiles)
|
||||
return [
|
||||
DefaultInfo(
|
||||
files = binary.files,
|
||||
runfiles = runfiles,
|
||||
),
|
||||
]
|
||||
|
||||
foreign_platform_binary = rule(
|
||||
implementation = _foreign_platform_binary_impl,
|
||||
attrs = {
|
||||
"binary": attr.label(
|
||||
cfg = _foreign_platform_transition,
|
||||
executable = True,
|
||||
mandatory = True,
|
||||
),
|
||||
"extra_rustc_flags": attr.string_list(
|
||||
doc = "Additional flags applied to every Rust target in the foreign configuration.",
|
||||
),
|
||||
"platform": attr.string(mandatory = True),
|
||||
"_allowlist_function_transition": attr.label(
|
||||
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
|
||||
),
|
||||
},
|
||||
doc = "Builds `binary` for `platform` and exposes its files and runfiles.",
|
||||
)
|
||||
54
bazel/rules/testing/wine/BUILD.bazel
Normal file
54
bazel/rules/testing/wine/BUILD.bazel
Normal file
@@ -0,0 +1,54 @@
|
||||
load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library")
|
||||
load(":wine.bzl", "wine_rust_test")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
exports_files([
|
||||
"wine.bzl",
|
||||
"wine_runtime.bzl",
|
||||
])
|
||||
|
||||
rust_library(
|
||||
name = "wine_test_support",
|
||||
testonly = True,
|
||||
srcs = [
|
||||
"src/lib.rs",
|
||||
"src/lib_tests.rs",
|
||||
],
|
||||
crate_name = "wine_test_support",
|
||||
crate_root = "src/lib.rs",
|
||||
edition = "2024",
|
||||
target_compatible_with = ["@platforms//os:linux"],
|
||||
deps = [
|
||||
"//codex-rs/utils/cargo-bin",
|
||||
"//codex-rs/utils/pty",
|
||||
"@crates//:anyhow",
|
||||
"@crates//:tempfile",
|
||||
"@crates//:tokio",
|
||||
],
|
||||
)
|
||||
|
||||
rust_binary(
|
||||
name = "windows-smoke",
|
||||
testonly = True,
|
||||
srcs = ["fixtures/windows_smoke.rs"],
|
||||
crate_name = "wine_smoke",
|
||||
crate_root = "fixtures/windows_smoke.rs",
|
||||
edition = "2024",
|
||||
tags = ["manual"],
|
||||
target_compatible_with = ["@platforms//os:windows"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
wine_rust_test(
|
||||
name = "wine-test-support-unit-tests",
|
||||
timeout = "moderate",
|
||||
crate = ":wine_test_support",
|
||||
windows_binaries = {
|
||||
"wine-smoke": ":windows-smoke",
|
||||
},
|
||||
deps = [
|
||||
"@crates//:futures",
|
||||
"@crates//:pretty_assertions",
|
||||
],
|
||||
)
|
||||
15
bazel/rules/testing/wine/fixtures/windows_smoke.rs
Normal file
15
bazel/rules/testing/wine/fixtures/windows_smoke.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use std::io::Write;
|
||||
|
||||
fn main() {
|
||||
println!("WINE_TEST_READY");
|
||||
std::io::stdout().flush().expect("flush readiness marker");
|
||||
|
||||
if std::env::args().any(|arg| arg == "--fail") {
|
||||
std::process::exit(9);
|
||||
}
|
||||
if std::env::args().any(|arg| arg == "--wait") {
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
}
|
||||
402
bazel/rules/testing/wine/src/lib.rs
Normal file
402
bazel/rules/testing/wine/src/lib.rs
Normal file
@@ -0,0 +1,402 @@
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
compile_error!("wine_test_support can only run on Linux");
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::future::Future;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command as StdCommand;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use tempfile::TempDir;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
|
||||
/// Builds a command that runs a Windows executable in an isolated Wine prefix.
|
||||
pub struct WineTestCommand {
|
||||
executable: PathBuf,
|
||||
args: Vec<OsString>,
|
||||
env: Vec<(OsString, OsString)>,
|
||||
}
|
||||
|
||||
/// Owns a Wine process and its isolated wineserver.
|
||||
///
|
||||
/// Call [`Self::scope`] or [`Self::shutdown`] on every successful path. A
|
||||
/// normal unguarded drop panics, while a drop during unwinding performs
|
||||
/// blocking cleanup without introducing a second panic.
|
||||
pub struct WineTestProcess {
|
||||
processes: Option<WineProcesses>,
|
||||
}
|
||||
|
||||
struct WineProcesses {
|
||||
child: Child,
|
||||
cleanup_complete: bool,
|
||||
prefix: TempDir,
|
||||
runtime: WineRuntimePaths,
|
||||
}
|
||||
|
||||
struct WineRuntimePaths {
|
||||
dll_path: PathBuf,
|
||||
powershell_runtime: PathBuf,
|
||||
wine: PathBuf,
|
||||
wineserver: PathBuf,
|
||||
}
|
||||
|
||||
impl WineTestCommand {
|
||||
/// Creates a Wine command for `executable`.
|
||||
pub fn new(executable: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
args: Vec::new(),
|
||||
env: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an argument passed to the Windows executable.
|
||||
#[must_use]
|
||||
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
|
||||
self.args.push(arg.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds or overrides an environment variable for the Wine process.
|
||||
#[must_use]
|
||||
pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
|
||||
self.env.push((key.into(), value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Starts the Windows executable with a fresh `WINEPREFIX`.
|
||||
pub fn spawn(self) -> Result<WineTestProcess> {
|
||||
let runtime = WineRuntimePaths::from_runfiles()?;
|
||||
let prefix = TempDir::new().context("create isolated Wine prefix")?;
|
||||
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
|
||||
let mut command = StdCommand::new(&runtime.wine);
|
||||
configure_wine_environment(&mut command, &runtime, prefix.path());
|
||||
command
|
||||
.arg(self.executable)
|
||||
.args(self.args)
|
||||
.envs(self.env)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
|
||||
let mut command = TokioCommand::from(command);
|
||||
command.kill_on_drop(true);
|
||||
let child = command
|
||||
.spawn()
|
||||
.context("start Windows process under Wine")?;
|
||||
|
||||
Ok(WineTestProcess {
|
||||
processes: Some(WineProcesses {
|
||||
child,
|
||||
cleanup_complete: false,
|
||||
prefix,
|
||||
runtime,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl WineTestProcess {
|
||||
/// Returns the host path to this process's isolated Wine prefix.
|
||||
pub fn prefix_path(&self) -> &Path {
|
||||
let Some(processes) = self.processes.as_ref() else {
|
||||
panic!("Wine process guard is missing");
|
||||
};
|
||||
processes.prefix.path()
|
||||
}
|
||||
|
||||
/// Takes the piped standard output of the Wine process.
|
||||
///
|
||||
/// This may only be called once for a process created by
|
||||
/// [`WineTestCommand::spawn`].
|
||||
pub fn take_stdout(&mut self) -> ChildStdout {
|
||||
let Some(processes) = self.processes.as_mut() else {
|
||||
panic!("Wine process guard is missing");
|
||||
};
|
||||
let Some(stdout) = processes.child.stdout.take() else {
|
||||
panic!("Wine process stdout has already been taken");
|
||||
};
|
||||
stdout
|
||||
}
|
||||
|
||||
/// Runs `future`, then asynchronously tears down Wine before returning.
|
||||
///
|
||||
/// If both the scoped operation and teardown fail, the operation error is
|
||||
/// returned with the teardown error attached as context. A panic in the
|
||||
/// scoped operation triggers the blocking unwind-time fallback instead.
|
||||
pub async fn scope<T>(self, future: impl Future<Output = Result<T>>) -> Result<T> {
|
||||
let scope_result = future.await;
|
||||
let shutdown_result = self.shutdown().await;
|
||||
match (scope_result, shutdown_result) {
|
||||
(Ok(value), Ok(())) => Ok(value),
|
||||
(Err(error), Ok(())) => Err(error),
|
||||
(Ok(_), Err(error)) => Err(error),
|
||||
(Err(error), Err(shutdown_error)) => {
|
||||
Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kills the Windows process, waits for it, and stops its wineserver.
|
||||
pub async fn shutdown(mut self) -> Result<()> {
|
||||
let Some(processes) = self.processes.as_mut() else {
|
||||
anyhow::bail!("Wine process guard is missing");
|
||||
};
|
||||
let result = processes.shutdown().await;
|
||||
self.processes.take();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WineTestProcess {
|
||||
fn drop(&mut self) {
|
||||
// Panicking here starts unwinding, after which WineProcesses performs
|
||||
// the blocking fallback while its field is dropped.
|
||||
if self.processes.is_some() && !std::thread::panicking() {
|
||||
panic!("WineTestProcess dropped without async teardown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WineRuntimePaths {
|
||||
fn from_runfiles() -> Result<Self> {
|
||||
let wine = codex_utils_cargo_bin::cargo_bin("wine")?;
|
||||
let runtime_marker = codex_utils_cargo_bin::cargo_bin("wine-runtime-marker")?;
|
||||
let dll_path = runtime_marker
|
||||
.parent()
|
||||
.context("locate Wine runtime directory")?
|
||||
.to_path_buf();
|
||||
let wineserver = codex_utils_cargo_bin::cargo_bin("wineserver")?;
|
||||
let powershell_runtime = codex_utils_cargo_bin::cargo_bin("pwsh-runtime-marker")?
|
||||
.parent()
|
||||
.context("locate PowerShell runtime directory")?
|
||||
.to_path_buf();
|
||||
Ok(Self {
|
||||
dll_path,
|
||||
powershell_runtime,
|
||||
wine,
|
||||
wineserver,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl WineProcesses {
|
||||
async fn shutdown(&mut self) -> Result<()> {
|
||||
let (kill_result, check_exit_status) = match self.child.try_wait() {
|
||||
Ok(Some(_)) => (Ok(()), true),
|
||||
Ok(None) => (
|
||||
self.child
|
||||
.start_kill()
|
||||
.context("kill Windows process running under Wine"),
|
||||
false,
|
||||
),
|
||||
Err(error) => (Err(error).context("check Windows process status"), false),
|
||||
};
|
||||
let wait_result = self
|
||||
.child
|
||||
.wait()
|
||||
.await
|
||||
.context("wait for Windows process running under Wine")
|
||||
.and_then(|status| {
|
||||
anyhow::ensure!(
|
||||
!check_exit_status || status.success(),
|
||||
"Windows process exited with {status}"
|
||||
);
|
||||
Ok(())
|
||||
});
|
||||
let wineserver_result = async {
|
||||
let mut command = TokioCommand::from(self.stop_wineserver_command());
|
||||
let status = command.status().await.context("stop isolated wineserver")?;
|
||||
anyhow::ensure!(status.success(), "wineserver exited with {status}");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
|
||||
// Every cleanup action has been attempted, so an individual error
|
||||
// should not cause the blocking fallback to repeat them.
|
||||
self.cleanup_complete = true;
|
||||
kill_result?;
|
||||
wait_result?;
|
||||
wineserver_result
|
||||
}
|
||||
|
||||
fn stop_wineserver_command(&self) -> StdCommand {
|
||||
let mut command = StdCommand::new(&self.runtime.wineserver);
|
||||
configure_wine_environment(&mut command, &self.runtime, self.prefix.path());
|
||||
command
|
||||
.args(["-k", "-w"])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
command
|
||||
}
|
||||
|
||||
fn shutdown_blocking(&mut self) {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup starting for prefix {}",
|
||||
self.prefix.path().display()
|
||||
));
|
||||
if let Err(error) = self.child.start_kill() {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not kill its child: {error}"
|
||||
));
|
||||
}
|
||||
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup waiting for its child"));
|
||||
loop {
|
||||
match self.child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup child exited with {status}"
|
||||
));
|
||||
break;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
|
||||
Err(error) => {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not wait for its child: {error}"
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup stopping its wineserver"));
|
||||
match self.stop_wineserver_command().status() {
|
||||
Ok(status) => log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup wineserver exited with {status}"
|
||||
)),
|
||||
Err(error) => log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not stop its wineserver: {error}"
|
||||
)),
|
||||
}
|
||||
self.cleanup_complete = true;
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup complete"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WineProcesses {
|
||||
fn drop(&mut self) {
|
||||
// Never introduce a second panic while unwinding. Blocking here is
|
||||
// intentional because test failures must not leak Wine children.
|
||||
if !self.cleanup_complete && std::thread::panicking() {
|
||||
self.shutdown_blocking();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_panic_cleanup(args: std::fmt::Arguments<'_>) {
|
||||
let _ = writeln!(std::io::stderr().lock(), "{args}");
|
||||
}
|
||||
|
||||
fn configure_wine_environment(command: &mut StdCommand, runtime: &WineRuntimePaths, prefix: &Path) {
|
||||
command
|
||||
.env_remove("DISPLAY")
|
||||
.env("HOME", prefix)
|
||||
.env("XDG_RUNTIME_DIR", prefix)
|
||||
.env("WINEARCH", "win64")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDLLPATH", &runtime.dll_path)
|
||||
.env("WINESERVER", &runtime.wineserver)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.env("WINEDLLOVERRIDES", "mscoree,mshtml,winegstreamer=")
|
||||
.env("LANG", "C.UTF-8")
|
||||
.env("LC_ALL", "C.UTF-8")
|
||||
.env("LC_CTYPE", "C.UTF-8")
|
||||
.env("TEMP", r"C:\windows\temp")
|
||||
.env("TMP", r"C:\windows\temp");
|
||||
}
|
||||
|
||||
/// Installs the complete pinned PowerShell distribution where Windows tooling
|
||||
/// expects to discover PowerShell 7.
|
||||
///
|
||||
/// `pwsh.exe` is not a standalone executable: it loads its adjacent .NET host,
|
||||
/// managed assemblies, native libraries, modules, and configuration files at
|
||||
/// startup. The Bazel archive is exposed through runfiles rather than a normal
|
||||
/// Windows installation, while shell detection deliberately probes the
|
||||
/// conventional `C:\Program Files\PowerShell\7` fallback. We therefore have to
|
||||
/// reproduce the archive's directory tree inside each isolated Wine prefix;
|
||||
/// copying only the executable would fail before a command could run.
|
||||
fn install_powershell_runtime(prefix: &Path, runtime: &Path) -> Result<()> {
|
||||
let powershell_parent = prefix
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell");
|
||||
fs::create_dir_all(&powershell_parent).context("create PowerShell installation parent")?;
|
||||
let destination = powershell_parent.join("7");
|
||||
materialize_runtime_directory(runtime, &destination)
|
||||
}
|
||||
|
||||
/// Recursively reproduces a runfiles directory in a writable Wine prefix.
|
||||
///
|
||||
/// Bazel runfiles may be immutable, represented by a symlink forest, and may
|
||||
/// contain the PowerShell distribution on a different filesystem from the
|
||||
/// temporary prefix. Hard links avoid repeatedly copying the roughly
|
||||
/// hundred-megabyte runtime when both locations share a filesystem; the copy
|
||||
/// fallback preserves correctness for sandbox or remote-execution layouts
|
||||
/// where cross-device hard links are unavailable.
|
||||
fn materialize_runtime_directory(source: &Path, destination: &Path) -> Result<()> {
|
||||
fs::create_dir_all(destination).with_context(|| {
|
||||
format!(
|
||||
"create PowerShell runtime directory {}",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
for entry in fs::read_dir(source)
|
||||
.with_context(|| format!("read PowerShell runtime directory {}", source.display()))?
|
||||
{
|
||||
let entry = entry.context("read PowerShell runtime entry")?;
|
||||
let source_path = entry.path();
|
||||
let destination_path = destination.join(entry.file_name());
|
||||
// Local Bazel runfiles trees expose external-repository files as
|
||||
// symlinks. Resolve those trusted runfiles entries before inspecting
|
||||
// or linking them so the writable prefix contains ordinary files.
|
||||
let resolved_source_path = fs::canonicalize(&source_path).with_context(|| {
|
||||
format!("resolve PowerShell runtime entry {}", source_path.display())
|
||||
})?;
|
||||
let file_type = fs::metadata(&resolved_source_path)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"inspect PowerShell runtime entry {}",
|
||||
resolved_source_path.display()
|
||||
)
|
||||
})?
|
||||
.file_type();
|
||||
if file_type.is_dir() {
|
||||
// PowerShell resolves assemblies and modules by their relative
|
||||
// locations, so flattening the archive is not an option.
|
||||
materialize_runtime_directory(&resolved_source_path, &destination_path)?;
|
||||
} else if file_type.is_file() {
|
||||
// A hard link gives each prefix the expected installation layout
|
||||
// without duplicating the large runtime in the common local case.
|
||||
if fs::hard_link(&resolved_source_path, &destination_path).is_err() {
|
||||
// Cross-device links are common under Bazel sandboxing and
|
||||
// remote execution, where an ordinary copy is still valid.
|
||||
fs::copy(&resolved_source_path, &destination_path).with_context(|| {
|
||||
format!(
|
||||
"copy PowerShell runtime file {} to {}",
|
||||
resolved_source_path.display(),
|
||||
destination_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
} else {
|
||||
anyhow::bail!(
|
||||
"unsupported PowerShell runtime entry type at {}",
|
||||
source_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
451
bazel/rules/testing/wine/src/lib_tests.rs
Normal file
451
bazel/rules/testing/wine/src/lib_tests.rs
Normal file
@@ -0,0 +1,451 @@
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::future::Future;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_utils_pty::SpawnedProcess;
|
||||
use codex_utils_pty::TerminalSize;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::WineRuntimePaths;
|
||||
use super::WineTestCommand;
|
||||
use super::WineTestProcess;
|
||||
use super::install_powershell_runtime;
|
||||
|
||||
async fn waiting_smoke_process() -> Result<WineTestProcess> {
|
||||
let executable = codex_utils_cargo_bin::cargo_bin("wine-smoke")?;
|
||||
let mut process = WineTestCommand::new(executable).arg("--wait").spawn()?;
|
||||
let mut lines = BufReader::new(process.take_stdout()).lines();
|
||||
let ready_line = lines
|
||||
.next_line()
|
||||
.await?
|
||||
.context("Windows smoke process exited before becoming ready")?;
|
||||
assert_eq!(ready_line, "WINE_TEST_READY");
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
fn prefix_path(process: &WineTestProcess) -> PathBuf {
|
||||
process
|
||||
.processes
|
||||
.as_ref()
|
||||
.expect("Wine process guard")
|
||||
.prefix
|
||||
.path()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn assert_prefix_removed(prefix: &Path) {
|
||||
assert!(
|
||||
!prefix.exists(),
|
||||
"Wine prefix remains: {}",
|
||||
prefix.display()
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_panic_message(panic: Box<dyn Any + Send>, expected: &str) {
|
||||
assert_eq!(panic.downcast_ref::<&str>(), Some(&expected));
|
||||
}
|
||||
|
||||
async fn assert_future_panics<T>(future: impl Future<Output = T>, expected: &str) {
|
||||
let panic = match AssertUnwindSafe(future).catch_unwind().await {
|
||||
Ok(_) => panic!("future should panic"),
|
||||
Err(panic) => panic,
|
||||
};
|
||||
assert_panic_message(panic, expected);
|
||||
}
|
||||
|
||||
async fn process_with_failing_wineserver_stop() -> Result<WineTestProcess> {
|
||||
let mut process = waiting_smoke_process().await?;
|
||||
let processes = process.processes.as_mut().expect("Wine process guard");
|
||||
|
||||
let mut command = TokioCommand::from(processes.stop_wineserver_command());
|
||||
let status = command
|
||||
.status()
|
||||
.await
|
||||
.context("pre-stop isolated wineserver")?;
|
||||
assert!(status.success(), "wineserver exited with {status}");
|
||||
|
||||
processes.runtime.wineserver = processes.prefix.path().join("missing-wineserver");
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_without_teardown_panics() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async move { drop(process) },
|
||||
"WineTestProcess dropped without async teardown",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_while_panicking_does_not_panic_again() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async move {
|
||||
let _process = process;
|
||||
panic!("sentinel panic");
|
||||
},
|
||||
"sentinel panic",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_teardown_disarms_drop_bomb() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
process.shutdown().await?;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn take_stdout_panics_when_called_twice() -> Result<()> {
|
||||
let mut process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async {
|
||||
process.take_stdout();
|
||||
},
|
||||
"Wine process stdout has already been taken",
|
||||
)
|
||||
.await;
|
||||
process.shutdown().await?;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_returns_value_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
let value = process
|
||||
.scope(async { Ok::<_, anyhow::Error>("scope value") })
|
||||
.await?;
|
||||
assert_eq!(value, "scope value");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_returns_body_error_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.scope(async { Err::<(), _>(anyhow!("scope body failed")) })
|
||||
.await
|
||||
.expect_err("scope body should fail");
|
||||
|
||||
assert_eq!(error.to_string(), "scope body failed");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_panic_preserves_panic_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
assert_future_panics(
|
||||
process.scope::<()>(async { panic!("scope panic") }),
|
||||
"scope panic",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_reports_nonzero_process_exit() -> Result<()> {
|
||||
let executable = codex_utils_cargo_bin::cargo_bin("wine-smoke")?;
|
||||
let mut process = WineTestCommand::new(executable).arg("--fail").spawn()?;
|
||||
let prefix = prefix_path(&process);
|
||||
let status = process
|
||||
.processes
|
||||
.as_mut()
|
||||
.expect("Wine process guard")
|
||||
.child
|
||||
.wait()
|
||||
.await?;
|
||||
assert!(
|
||||
!status.success(),
|
||||
"Windows smoke process unexpectedly passed"
|
||||
);
|
||||
|
||||
let error = process.shutdown().await.expect_err("shutdown should fail");
|
||||
|
||||
assert!(error.to_string().starts_with("Windows process exited with"));
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_preserves_body_error_when_teardown_also_fails() -> Result<()> {
|
||||
let process = process_with_failing_wineserver_stop().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.scope(async { Err::<(), _>(anyhow!("scope body failed")) })
|
||||
.await
|
||||
.expect_err("scope body and teardown should fail");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.starts_with("Wine teardown also failed: stop isolated wineserver"),
|
||||
"unexpected error: {error:#}"
|
||||
);
|
||||
assert_eq!(
|
||||
error.chain().last().map(ToString::to_string),
|
||||
Some("scope body failed".to_string())
|
||||
);
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_returns_teardown_error() -> Result<()> {
|
||||
let process = process_with_failing_wineserver_stop().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.shutdown()
|
||||
.await
|
||||
.expect_err("shutdown should report a wineserver failure");
|
||||
|
||||
assert_eq!(error.to_string(), "stop isolated wineserver");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_runtime_is_materialized_at_the_windows_fallback_path() -> Result<()> {
|
||||
let prefix = TempDir::new()?;
|
||||
let runtime = TempDir::new()?;
|
||||
fs::create_dir(runtime.path().join("Modules"))?;
|
||||
fs::write(runtime.path().join("pwsh.exe"), b"pwsh")?;
|
||||
fs::write(runtime.path().join("Modules").join("marker.txt"), b"module")?;
|
||||
|
||||
install_powershell_runtime(prefix.path(), runtime.path())?;
|
||||
|
||||
let installed = prefix
|
||||
.path()
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell")
|
||||
.join("7");
|
||||
assert_eq!(fs::read(installed.join("pwsh.exe"))?, b"pwsh");
|
||||
assert_eq!(
|
||||
fs::read(installed.join("Modules").join("marker.txt"))?,
|
||||
b"module"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_runtime_follows_runfiles_symlinks() -> Result<()> {
|
||||
let prefix = TempDir::new()?;
|
||||
let runtime = TempDir::new()?;
|
||||
let backing = TempDir::new()?;
|
||||
let backing_file = backing.path().join("pwsh.exe");
|
||||
fs::write(&backing_file, b"pwsh")?;
|
||||
std::os::unix::fs::symlink(&backing_file, runtime.path().join("pwsh.exe"))?;
|
||||
|
||||
install_powershell_runtime(prefix.path(), runtime.path())?;
|
||||
|
||||
let installed = prefix
|
||||
.path()
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell")
|
||||
.join("7")
|
||||
.join("pwsh.exe");
|
||||
assert_eq!(fs::read(installed)?, b"pwsh");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pinned_powershell_runs_under_wine_with_a_pty() -> Result<()> {
|
||||
// Keep this integration smoke test local to the Wine support crate. The
|
||||
// production-shaped PowerShell launch path belongs to exec-server tests.
|
||||
// The marker makes the assertion resilient to Wine or PTY startup chatter.
|
||||
const POWERSHELL_SMOKE_MARKER: &str = "WINE_PWSH_SMOKE";
|
||||
// Besides proving that the pinned runtime starts, report the properties
|
||||
// that shell detection and command construction rely on: PowerShell 7 Core
|
||||
// running with Windows semantics and a backslash path separator.
|
||||
const POWERSHELL_SMOKE_SCRIPT: &str = concat!(
|
||||
"$ErrorActionPreference = 'Stop'; ",
|
||||
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ",
|
||||
"$separatorCode = [int]([System.IO.Path]::DirectorySeparatorChar); ",
|
||||
"if ($PSVersionTable.PSVersion.Major -ne 7) { throw 'expected PowerShell 7' }; ",
|
||||
"if ($PSVersionTable.PSEdition -ne 'Core') { throw 'expected PowerShell Core' }; ",
|
||||
"if (-not $IsWindows) { throw 'expected Windows semantics' }; ",
|
||||
"if ($separatorCode -ne 92) { throw 'expected backslash path separator' }; ",
|
||||
"Write-Output ('WINE_PWSH_SMOKE|' + ",
|
||||
"$PSVersionTable.PSVersion.ToString() + '|' + ",
|
||||
"$PSVersionTable.PSEdition + '|' + ",
|
||||
"$IsWindows.ToString().ToLowerInvariant() + '|' + $separatorCode)",
|
||||
);
|
||||
let runtime = WineRuntimePaths::from_runfiles()?;
|
||||
let prefix = TempDir::new()?;
|
||||
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
|
||||
let mut env = std::env::vars().collect::<HashMap<_, _>>();
|
||||
env.remove("DISPLAY");
|
||||
env.extend([
|
||||
(
|
||||
"HOME".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"XDG_RUNTIME_DIR".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
("WINEARCH".to_string(), "win64".to_string()),
|
||||
(
|
||||
"WINEPREFIX".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"WINEDLLPATH".to_string(),
|
||||
runtime.dll_path.to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"WINESERVER".to_string(),
|
||||
runtime.wineserver.to_string_lossy().into_owned(),
|
||||
),
|
||||
("WINEDEBUG".to_string(), "-all".to_string()),
|
||||
(
|
||||
"WINEDLLOVERRIDES".to_string(),
|
||||
"mscoree,mshtml,winegstreamer=".to_string(),
|
||||
),
|
||||
("LANG".to_string(), "C.UTF-8".to_string()),
|
||||
("LC_ALL".to_string(), "C.UTF-8".to_string()),
|
||||
("LC_CTYPE".to_string(), "C.UTF-8".to_string()),
|
||||
("TEMP".to_string(), r"C:\windows\temp".to_string()),
|
||||
("TMP".to_string(), r"C:\windows\temp".to_string()),
|
||||
]);
|
||||
let args = [
|
||||
r"C:\Program Files\PowerShell\7\pwsh.exe".to_string(),
|
||||
"-NoLogo".to_string(),
|
||||
"-NoProfile".to_string(),
|
||||
"-NonInteractive".to_string(),
|
||||
"-Command".to_string(),
|
||||
POWERSHELL_SMOKE_SCRIPT.to_string(),
|
||||
];
|
||||
let wine = runtime.wine.to_string_lossy().into_owned();
|
||||
let SpawnedProcess {
|
||||
session,
|
||||
mut stdout_rx,
|
||||
mut stderr_rx,
|
||||
exit_rx,
|
||||
} = codex_utils_pty::spawn_pty_process(
|
||||
&wine,
|
||||
&args,
|
||||
prefix.path(),
|
||||
&env,
|
||||
/*arg0*/ &None,
|
||||
TerminalSize::default(),
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let command_result = timeout(Duration::from_secs(90), async {
|
||||
let stdout = async {
|
||||
let mut output = Vec::new();
|
||||
while let Some(chunk) = stdout_rx.recv().await {
|
||||
output.extend(chunk);
|
||||
}
|
||||
output
|
||||
};
|
||||
let stderr = async {
|
||||
let mut output = Vec::new();
|
||||
while let Some(chunk) = stderr_rx.recv().await {
|
||||
output.extend(chunk);
|
||||
}
|
||||
output
|
||||
};
|
||||
let (stdout, stderr, exit_code) = tokio::join!(stdout, stderr, exit_rx);
|
||||
Ok::<_, anyhow::Error>((stdout, stderr, exit_code.context("wait for PowerShell")?))
|
||||
})
|
||||
.await
|
||||
.context("PowerShell smoke test timed out")
|
||||
.and_then(std::convert::identity);
|
||||
drop(session);
|
||||
let shutdown_result = timeout(Duration::from_secs(10), async {
|
||||
let mut command = TokioCommand::new(&runtime.wineserver);
|
||||
command
|
||||
.args(["-k", "-w"])
|
||||
.env("HOME", prefix.path())
|
||||
.env("WINEPREFIX", prefix.path())
|
||||
.env("XDG_RUNTIME_DIR", prefix.path())
|
||||
.kill_on_drop(true);
|
||||
let status = command.status().await.context("stop isolated wineserver")?;
|
||||
anyhow::ensure!(
|
||||
status.success() || status.code() == Some(1),
|
||||
"wineserver exited with {status}"
|
||||
);
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await
|
||||
.context("stop isolated wineserver timed out")
|
||||
.and_then(std::convert::identity);
|
||||
let (stdout, stderr, exit_code) = match (command_result, shutdown_result) {
|
||||
(Ok(output), Ok(())) => output,
|
||||
(Err(error), Ok(())) => return Err(error),
|
||||
(Ok(_), Err(error)) => return Err(error),
|
||||
(Err(error), Err(shutdown_error)) => {
|
||||
return Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")));
|
||||
}
|
||||
};
|
||||
anyhow::ensure!(
|
||||
exit_code == 0,
|
||||
"PowerShell exited with {}; stderr: {}",
|
||||
exit_code,
|
||||
String::from_utf8_lossy(&stderr),
|
||||
);
|
||||
let output = String::from_utf8(stdout)?;
|
||||
let marker_start = output
|
||||
.find(POWERSHELL_SMOKE_MARKER)
|
||||
.with_context(|| format!("PowerShell smoke marker was missing from {output:?}"))?;
|
||||
let smoke = output[marker_start..]
|
||||
.lines()
|
||||
.next()
|
||||
.context("PowerShell smoke marker line was incomplete")?
|
||||
.trim_end_matches('\r');
|
||||
let fields = smoke.split('|').collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
fields.len(),
|
||||
5,
|
||||
"unexpected PowerShell smoke output: {smoke}"
|
||||
);
|
||||
assert_eq!(fields[0], POWERSHELL_SMOKE_MARKER);
|
||||
assert_eq!(
|
||||
fields[1].split('.').next(),
|
||||
Some("7"),
|
||||
"expected PowerShell 7.x, got {}",
|
||||
fields[1],
|
||||
);
|
||||
assert_eq!(&fields[2..], &["Core", "true", "92"]);
|
||||
Ok(())
|
||||
}
|
||||
69
bazel/rules/testing/wine/wine.bzl
Normal file
69
bazel/rules/testing/wine/wine.bzl
Normal file
@@ -0,0 +1,69 @@
|
||||
"""Macros for cross-building Windows Rust binaries and testing them with Wine."""
|
||||
|
||||
load("@rules_rust//rust:defs.bzl", "rust_test")
|
||||
load("//:defs.bzl", "WINDOWS_GNULLVM_RUSTC_LINK_FLAGS")
|
||||
load("//bazel/rules/testing:foreign_platform_binary.bzl", "foreign_platform_binary")
|
||||
load(":wine_runtime.bzl", "WINE_TEST_TARGET_COMPATIBLE_WITH", "wine_test_runtime")
|
||||
|
||||
def wine_rust_test(
|
||||
name,
|
||||
windows_binaries,
|
||||
host_binaries = {},
|
||||
data = [],
|
||||
target_compatible_with = [],
|
||||
**kwargs):
|
||||
"""Defines an x86-64 Linux Rust test with a pinned Wine runtime.
|
||||
|
||||
Each `windows_binaries` executable is transitioned to GNU/LLVM Windows;
|
||||
every Rust dependency receives the repository's Windows linker flags while
|
||||
the test stays on x86-64 Linux. Its environment-variable contract is:
|
||||
|
||||
* Each `host_binaries` and `windows_binaries` entry contributes
|
||||
`CARGO_BIN_EXE_<binary_name>` for its executable.
|
||||
* `CARGO_BIN_EXE_wine` and `CARGO_BIN_EXE_wineserver` identify Wine tools.
|
||||
* `CARGO_BIN_EXE_wine-runtime-marker` identifies a file whose parent is the
|
||||
Wine DLL directory to use as `WINEDLLPATH`.
|
||||
* `CARGO_BIN_EXE_pwsh` identifies the pinned PowerShell executable and
|
||||
`CARGO_BIN_EXE_pwsh-runtime-marker` identifies a file whose parent is the
|
||||
complete PowerShell runtime.
|
||||
|
||||
These are Bazel runfile locations. Resolve binaries with
|
||||
`codex_utils_cargo_bin::cargo_bin`; `:wine_test_support` resolves the fixed
|
||||
runtime names and starts each process in an isolated prefix.
|
||||
|
||||
Args:
|
||||
name: Name of the generated Linux `rust_test`.
|
||||
windows_binaries: Map from `CARGO_BIN_EXE_*` suffixes to Windows targets.
|
||||
host_binaries: Map from `CARGO_BIN_EXE_*` suffixes to Linux host targets.
|
||||
data: Additional runtime data for the Linux test.
|
||||
target_compatible_with: Additional compatibility constraints.
|
||||
**kwargs: Remaining attributes forwarded to `rust_test`.
|
||||
"""
|
||||
binaries = dict(host_binaries)
|
||||
for index, binary_name in enumerate(sorted(windows_binaries.keys())):
|
||||
if binary_name in binaries:
|
||||
fail("Windows test binary name collides with host binary: {}".format(binary_name))
|
||||
transitioned_binary = name + "-windows-binary-" + str(index)
|
||||
foreign_platform_binary(
|
||||
name = transitioned_binary,
|
||||
binary = windows_binaries[binary_name],
|
||||
extra_rustc_flags = WINDOWS_GNULLVM_RUSTC_LINK_FLAGS,
|
||||
platform = "//:windows_x86_64_gnullvm",
|
||||
tags = ["manual"],
|
||||
target_compatible_with = [
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
],
|
||||
testonly = True,
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
binaries[binary_name] = ":" + transitioned_binary
|
||||
|
||||
runtime = wine_test_runtime(binaries)
|
||||
rust_test(
|
||||
name = name,
|
||||
data = data + runtime.data,
|
||||
env = runtime.env,
|
||||
target_compatible_with = target_compatible_with + WINE_TEST_TARGET_COMPATIBLE_WITH,
|
||||
**kwargs
|
||||
)
|
||||
40
bazel/rules/testing/wine/wine_runtime.bzl
Normal file
40
bazel/rules/testing/wine/wine_runtime.bzl
Normal file
@@ -0,0 +1,40 @@
|
||||
"""Runfiles shared by tests that execute Windows binaries through Wine."""
|
||||
|
||||
_WINE_RUNTIME_BINARIES = {
|
||||
"pwsh": "@powershell_windows_x86_64//:pwsh",
|
||||
"pwsh-runtime-marker": "@powershell_windows_x86_64//:runtime_marker",
|
||||
"wine": "@wine_linux_x86_64//:wine",
|
||||
"wine-runtime-marker": "@wine_linux_x86_64//:runtime_marker",
|
||||
"wineserver": "@wine_linux_x86_64//:wineserver",
|
||||
}
|
||||
|
||||
_WINE_RUNTIME_DATA = [
|
||||
"@powershell_windows_x86_64//:runtime",
|
||||
"@wine_linux_x86_64//:runtime",
|
||||
]
|
||||
|
||||
WINE_TEST_TARGET_COMPATIBLE_WITH = [
|
||||
"@llvm//constraints/libc:gnu.2.28",
|
||||
"@platforms//cpu:x86_64",
|
||||
"@platforms//os:linux",
|
||||
]
|
||||
|
||||
def wine_test_runtime(test_binaries = {}):
|
||||
"""Returns data and environment mappings for a Wine-backed test."""
|
||||
binaries = dict(_WINE_RUNTIME_BINARIES)
|
||||
for binary_name in sorted(test_binaries.keys()):
|
||||
if binary_name in binaries:
|
||||
fail("test binary name collides with Wine runtime: {}".format(binary_name))
|
||||
binaries[binary_name] = test_binaries[binary_name]
|
||||
|
||||
return struct(
|
||||
data = _WINE_RUNTIME_DATA + [binary for binary in binaries.values()],
|
||||
env = {
|
||||
"CARGO_BIN_EXE_{}".format(binary_name): "$(rlocationpath {})".format(binary)
|
||||
for binary_name, binary in binaries.items()
|
||||
},
|
||||
runfile_env = {
|
||||
binary_label: "CARGO_BIN_EXE_" + binary_name
|
||||
for binary_name, binary_label in binaries.items()
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user