use crate::{BuildStrategy, CompatibilityFloor, ReleasePlan};
use command_group::CommandGroup;
use eggpack_contract::{DistributionContract, ExpandedAssets};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
ffi::OsString,
fs,
io::{Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
sync::{Arc, Mutex},
thread,
time::{Duration, Instant},
};
const MAX_OUTPUT: usize = 256 * 1024;
const MAX_PROCESS_OUTPUT: usize = 8 * 1024 * 1024;
const GIT_TIMEOUT: Duration = Duration::from_secs(30);
const GIT_OUTPUT_LIMIT: usize = 4 * 1024;
const MIN_DRAIN_GRACE: Duration = Duration::from_secs(1);
const MAX_DRAIN_GRACE: Duration = Duration::from_secs(2);
fn ensure_candidate_executable(path: &Path) -> Result<(), BuildError> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let meta =
fs::symlink_metadata(path).map_err(|_| build_err("candidate is not executable"))?;
if meta.file_type().is_symlink() || !meta.is_file() {
return Err(build_err("candidate is not executable"));
}
let mut permissions = meta.permissions();
permissions.set_mode(permissions.mode() | 0o111);
fs::set_permissions(path, permissions)
.map_err(|_| build_err("candidate is not executable"))?;
Ok(())
}
#[cfg(not(unix))]
{
let _ = path;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum LogicalOutputSelector {
Direct,
BundleEntry {
index: usize,
},
ArchiveMember {
source: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildBinding {
pub selector: LogicalOutputSelector,
pub package: String,
pub binary: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildBindingsV1 {
pub schema_version: u32,
pub targets: BTreeMap<String, Vec<BuildBinding>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildError(pub(crate) String);
impl std::fmt::Display for BuildError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for BuildError {}
fn build_err(s: &str) -> BuildError {
BuildError(s.to_owned())
}
#[derive(Clone, Copy)]
enum ExecutableAllowance {
Builder,
Candidate,
Qemu,
Git,
Interpreter,
}
enum Cancellation<'a> {
None,
Build(&'a BuildCancellation),
Flag(&'a std::sync::atomic::AtomicBool),
}
impl Cancellation<'_> {
fn is_cancelled(&self) -> bool {
match self {
Cancellation::None => false,
Cancellation::Build(cancellation) => cancellation.is_cancelled(),
Cancellation::Flag(flag) => flag.load(std::sync::atomic::Ordering::SeqCst),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandSpec {
pub executable: String,
pub args: Vec<String>,
pub cwd: PathBuf,
pub env: BTreeMap<String, String>,
pub timeout: Duration,
pub stdout_limit: usize,
pub stderr_limit: usize,
pub expected_stdout: Option<String>,
pub expected_stdout_exact: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoundCommand {
pub selector: LogicalOutputSelector,
pub package: String,
pub binary: String,
pub command: CommandSpec,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterpreterCommandSpec {
pub executable: String,
pub args: Vec<OsString>,
pub cwd: PathBuf,
pub env: BTreeMap<String, String>,
pub timeout: Duration,
pub stdout_limit: usize,
pub stderr_limit: usize,
pub expected_stdout: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CommandOutcome {
Success,
Failed(i32),
TimedOut,
Cancelled,
OutputLimitExceeded,
}
#[derive(Debug, Clone, Default)]
pub struct BuildCancellation(std::sync::Arc<std::sync::atomic::AtomicBool>);
impl BuildCancellation {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, std::sync::atomic::Ordering::SeqCst);
}
pub(crate) fn is_cancelled(&self) -> bool {
self.0.load(std::sync::atomic::Ordering::SeqCst)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessEvidence {
pub outcome: CommandOutcome,
pub stdout_bytes: usize,
pub stderr_bytes: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CandidateArtifact {
pub target: String,
pub selector: LogicalOutputSelector,
pub package: String,
pub binary: String,
pub path: PathBuf,
pub size: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildAttempt {
pub release_id: String,
pub source_revision: String,
pub target: String,
pub strategy: BuildStrategy,
pub tool_summary: String,
pub process: ProcessEvidence,
pub candidates: Vec<CandidateArtifact>,
}
impl BuildBindingsV1 {
pub fn from_toml(text: &str) -> Result<Self, BuildError> {
let value: Self =
toml::from_str(text).map_err(|_| build_err("invalid BuildBindings TOML"))?;
value.validate_shape()?;
Ok(value)
}
fn validate_shape(&self) -> Result<(), BuildError> {
if self.schema_version != 1 || self.targets.is_empty() || self.targets.len() > 256 {
return Err(build_err("invalid BuildBindings version or target count"));
}
for (target, bindings) in &self.targets {
if target.is_empty() || bindings.is_empty() || bindings.len() > 256 {
return Err(build_err("invalid BuildBindings target or binding count"));
}
let mut slots = BTreeSet::new();
for b in bindings {
if !slots.insert(&b.selector)
|| !valid_identifier(&b.package)
|| !valid_identifier(&b.binary)
{
return Err(build_err("duplicate slot or invalid Cargo identifier"));
}
if let LogicalOutputSelector::ArchiveMember { source } = &b.selector {
if source.is_empty()
|| source.len() > 255
|| source.starts_with('/')
|| source
.split('/')
.any(|p| p.is_empty() || p == "." || p == "..")
{
return Err(build_err("invalid archive member source"));
}
}
}
}
Ok(())
}
pub fn validate_for(
&self,
contract: &DistributionContract,
plan: &ReleasePlan,
) -> Result<(), BuildError> {
self.validate_shape()?;
for target in &plan.targets {
let bindings = self
.targets
.get(&target.target)
.ok_or_else(|| build_err("missing target bindings"))?;
let expanded = contract
.expand(&target.target, &plan.release_id)
.map_err(|_| build_err("contract target expansion failed"))?;
let expected: BTreeSet<LogicalOutputSelector> = match expanded.assets {
ExpandedAssets::Direct(_) => [LogicalOutputSelector::Direct].into_iter().collect(),
ExpandedAssets::Bundle(b) => (0..b.entries.len())
.map(|index| LogicalOutputSelector::BundleEntry { index })
.collect(),
ExpandedAssets::Archive(a) => a
.members
.into_iter()
.map(|m| LogicalOutputSelector::ArchiveMember { source: m.source })
.collect(),
};
let actual: BTreeSet<_> = bindings.iter().map(|b| b.selector.clone()).collect();
if actual != expected {
return Err(build_err(
"bindings do not exactly cover contract Cargo slots",
));
}
}
if self
.targets
.keys()
.any(|k| !plan.targets.iter().any(|t| &t.target == k))
{
return Err(build_err("bindings include target outside ReleasePlan"));
}
Ok(())
}
}
fn valid_identifier(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 128
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))
}
pub fn cargo_command(
target: &crate::PlannedTarget,
binding: &BuildBinding,
cwd: &Path,
target_dir: &Path,
timeout: Duration,
) -> Result<CommandSpec, BuildError> {
if !valid_identifier(&binding.package) || !valid_identifier(&binding.binary) {
return Err(build_err("invalid Cargo identifier"));
}
let rustup = target.policy.toolchain.rust.as_str();
let mut args = vec!["+".to_owned() + rustup];
args.push(
match target.policy.strategy {
BuildStrategy::NativeCargo => "build",
BuildStrategy::CargoZigbuild => "zigbuild",
}
.into(),
);
args.extend(["--release".to_owned(), "--locked".to_owned()]);
if target.policy.strategy == BuildStrategy::CargoZigbuild {
let triple = match target.policy.floor {
CompatibilityFloor::Glibc { major, minor } => {
format!("{}.{major}.{minor}", target.target)
}
CompatibilityFloor::Macos { .. } => {
crate::validate_floor_applicability(
&target.policy.floor,
target.policy.strategy,
&target.target,
)
.map_err(|_| build_err("macOS floor cannot use cargo-zigbuild"))?;
target.target.clone()
}
CompatibilityFloor::None => target.target.clone(),
};
args.extend(["--target".to_owned(), triple]);
} else {
args.extend(["--target".to_owned(), target.target.clone()]);
}
args.extend([
"--package".into(),
binding.package.clone(),
"--bin".into(),
binding.binary.clone(),
]);
let mut env = BTreeMap::new();
env.insert(
"CARGO_TARGET_DIR".into(),
target_dir.to_string_lossy().into_owned(),
);
Ok(CommandSpec {
executable: "cargo".into(),
args,
cwd: cwd.to_path_buf(),
env,
timeout,
stdout_limit: MAX_OUTPUT,
stderr_limit: MAX_OUTPUT,
expected_stdout: None,
expected_stdout_exact: None,
})
}
pub fn run_bounded_cancellable(
spec: &CommandSpec,
cancellation: &BuildCancellation,
) -> Result<ProcessEvidence, BuildError> {
run_bounded_inner(
spec,
Cancellation::Build(cancellation),
ExecutableAllowance::Builder,
)
}
pub fn run_interpreter_bounded(
spec: &InterpreterCommandSpec,
cancelled: Option<&std::sync::atomic::AtomicBool>,
) -> Result<ProcessEvidence, BuildError> {
let cancellation = match cancelled {
Some(flag) => Cancellation::Flag(flag),
None => Cancellation::None,
};
let run = BoundedRun {
executable: spec.executable.as_str(),
args: &spec.args,
cwd: spec.cwd.as_path(),
env: &spec.env,
timeout: spec.timeout,
stdout_limit: spec.stdout_limit,
stderr_limit: spec.stderr_limit,
expected_stdout: spec.expected_stdout.as_deref(),
expected_stdout_exact: None,
};
run_bounded(&run, cancellation, ExecutableAllowance::Interpreter)
}
pub fn run_git_bounded(expected: &str, cwd: Option<&Path>) -> Result<ProcessEvidence, BuildError> {
run_git_resolve_bounded(
vec![
"rev-parse".into(),
"--verify".into(),
"HEAD^{commit}".into(),
],
expected,
cwd,
)
}
pub fn run_git_tag_bounded(
tag: &str,
expected: &str,
cwd: Option<&Path>,
) -> Result<ProcessEvidence, BuildError> {
if crate::validate_exact_tag_safety(tag).is_err() {
return Err(build_err("invalid exact git tag"));
}
run_git_resolve_bounded(
vec![
"rev-parse".into(),
"--verify".into(),
format!("refs/tags/{tag}^{{commit}}"),
],
expected,
cwd,
)
}
fn run_git_resolve_bounded(
args: Vec<String>,
expected: &str,
cwd: Option<&Path>,
) -> Result<ProcessEvidence, BuildError> {
let cwd = match cwd {
Some(cwd) => cwd.to_path_buf(),
None => std::env::current_dir().map_err(|_| build_err("working directory unavailable"))?,
};
let spec = CommandSpec {
executable: "git".into(),
args,
cwd,
env: BTreeMap::new(),
timeout: GIT_TIMEOUT,
stdout_limit: GIT_OUTPUT_LIMIT,
stderr_limit: GIT_OUTPUT_LIMIT,
expected_stdout: None,
expected_stdout_exact: Some(expected.to_owned()),
};
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Git)
}
pub(crate) fn run_qualification_process(
spec: &CommandSpec,
cancellation: &BuildCancellation,
) -> Result<ProcessEvidence, BuildError> {
run_bounded_inner(
spec,
Cancellation::Build(cancellation),
ExecutableAllowance::Candidate,
)
}
pub(crate) fn run_qemu_process(
spec: &CommandSpec,
cancellation: &BuildCancellation,
) -> Result<ProcessEvidence, BuildError> {
run_bounded_inner(
spec,
Cancellation::Build(cancellation),
ExecutableAllowance::Qemu,
)
}
struct BoundedRun<'a> {
executable: &'a str,
args: &'a [OsString],
cwd: &'a Path,
env: &'a BTreeMap<String, String>,
timeout: Duration,
stdout_limit: usize,
stderr_limit: usize,
expected_stdout: Option<&'a str>,
expected_stdout_exact: Option<&'a str>,
}
fn run_bounded_inner(
spec: &CommandSpec,
cancellation: Cancellation<'_>,
allowance: ExecutableAllowance,
) -> Result<ProcessEvidence, BuildError> {
let args: Vec<OsString> = spec.args.iter().map(OsString::from).collect();
let run = BoundedRun {
executable: spec.executable.as_str(),
args: &args,
cwd: spec.cwd.as_path(),
env: &spec.env,
timeout: spec.timeout,
stdout_limit: spec.stdout_limit,
stderr_limit: spec.stderr_limit,
expected_stdout: spec.expected_stdout.as_deref(),
expected_stdout_exact: spec.expected_stdout_exact.as_deref(),
};
run_bounded(&run, cancellation, allowance)
}
#[cfg(unix)]
fn group_signal_failure_is_benign(
error: &std::io::Error,
child_exited: bool,
retry_group_signal: impl FnOnce() -> std::io::Result<()>,
) -> bool {
if error.raw_os_error() == Some(libc::ESRCH) {
return true;
}
if !child_exited {
return false;
}
match retry_group_signal() {
Ok(()) => true,
Err(retry_error) => retry_error.raw_os_error() == Some(libc::ESRCH),
}
}
fn terminate_process_group(
child: &mut command_group::GroupChild,
message: &str,
) -> Result<(), BuildError> {
match child.kill() {
Ok(()) => Ok(()),
Err(error) => {
let child_wait = child.try_wait();
#[cfg(unix)]
let child_exited = child_wait.as_ref().is_ok_and(Option::is_some);
#[cfg(unix)]
if group_signal_failure_is_benign(&error, child_exited, || child.kill()) {
return Ok(());
}
#[cfg(not(unix))]
let _ = child_wait;
Err(build_err(message))
}
}
}
fn run_bounded(
run: &BoundedRun<'_>,
cancellation: Cancellation<'_>,
allowance: ExecutableAllowance,
) -> Result<ProcessEvidence, BuildError> {
let executable_allowed = match allowance {
ExecutableAllowance::Builder => {
matches!(run.executable, "cargo" | "rustc" | "zig")
}
ExecutableAllowance::Candidate => Path::new(run.executable).is_absolute(),
ExecutableAllowance::Qemu => {
matches!(run.executable, "qemu-x86_64" | "qemu-aarch64" | "qemu-arm")
}
ExecutableAllowance::Git => run.executable == "git",
ExecutableAllowance::Interpreter => matches!(run.executable, "python3" | "python"),
};
if !executable_allowed
|| run.timeout.is_zero()
|| run.timeout > Duration::from_secs(86_400)
|| run.stdout_limit == 0
|| run.stderr_limit == 0
|| run.stdout_limit > MAX_PROCESS_OUTPUT
|| run.stderr_limit > MAX_PROCESS_OUTPUT
{
return Err(build_err("invalid process bounds or executable"));
}
if matches!(allowance, ExecutableAllowance::Candidate)
&& ensure_candidate_executable(Path::new(run.executable)).is_err()
{
return Err(build_err("candidate is not executable"));
}
let mut command = Command::new(run.executable);
command
.args(run.args)
.current_dir(run.cwd)
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let environment = if matches!(allowance, ExecutableAllowance::Git) {
[
"PATH",
"HOME",
"USERPROFILE",
"SystemRoot",
"WINDIR",
"TEMP",
"TMP",
]
.as_slice()
} else if !matches!(allowance, ExecutableAllowance::Builder) {
["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP"].as_slice()
} else {
[
"PATH",
"HOME",
"USERPROFILE",
"SystemRoot",
"WINDIR",
"TEMP",
"TMP",
"CARGO_HOME",
"RUSTUP_HOME",
"LIB",
"LIBPATH",
"INCLUDE",
"VCToolsInstallDir",
"VisualStudioVersion",
"VCINSTALLDIR",
"WindowsSdkDir",
"WindowsSDKVersion",
"UniversalCRTSdkDir",
"UCRTVersion",
]
.as_slice()
};
for key in environment {
if let Some(value) = std::env::var_os(key) {
command.env(key, value);
}
}
#[cfg(windows)]
if let Some(vc_tools) = std::env::var_os("VCToolsInstallDir") {
let preferred_linker = PathBuf::from(vc_tools)
.join("bin")
.join("Hostx64")
.join("x64");
if let Some(path) = std::env::var_os("PATH") {
let path = std::iter::once(preferred_linker).chain(std::env::split_paths(&path));
if let Ok(path) = std::env::join_paths(path) {
command.env("PATH", path);
}
}
}
command.envs(run.env);
let mut child = command
.group_spawn()
.map_err(|_| build_err("process spawn failed"))?;
let stdout = child
.inner()
.stdout
.take()
.ok_or_else(|| build_err("stdout pipe unavailable"))?;
let stderr = child
.inner()
.stderr
.take()
.ok_or_else(|| build_err("stderr pipe unavailable"))?;
let out = Arc::new(Mutex::new((Vec::new(), false)));
let err = Arc::new(Mutex::new((Vec::new(), false)));
let out2 = out.clone();
let out_limit = run.stdout_limit;
let t1 = thread::spawn(move || drain(stdout, out2, out_limit));
let err2 = err.clone();
let err_limit = run.stderr_limit;
let t2 = thread::spawn(move || drain(stderr, err2, err_limit));
let until = Instant::now() + run.timeout;
let (timed_out, cancelled, over_limit) = loop {
if cancellation.is_cancelled() {
terminate_process_group(&mut child, "cancelled process-group termination failed")?;
child
.wait()
.map_err(|_| build_err("cancelled process-group wait failed"))?;
break (false, true, false);
}
if Instant::now() >= until {
terminate_process_group(&mut child, "process-group termination failed")?;
child
.wait()
.map_err(|_| build_err("process-group wait failed"))?;
break (true, false, false);
}
if stream_over_limit(&out) || stream_over_limit(&err) {
terminate_process_group(&mut child, "output-limit process-group termination failed")?;
child
.wait()
.map_err(|_| build_err("output-limit process-group wait failed"))?;
break (false, false, true);
}
if child
.try_wait()
.map_err(|_| build_err("process wait failed"))?
.is_some()
{
break (false, false, false);
}
thread::sleep(Duration::from_millis(20));
};
let drain_budget = until
.saturating_duration_since(Instant::now())
.clamp(MIN_DRAIN_GRACE, MAX_DRAIN_GRACE);
let drain_until = Instant::now() + drain_budget;
let drained = join_drained(t1, drain_until, "stdout reader failed")?
& join_drained(t2, drain_until, "stderr reader failed")?;
if !drained {
let _ = child.kill();
}
let status = child
.try_wait()
.map_err(|_| build_err("process wait failed"))?
.ok_or_else(|| build_err("process cleanup incomplete"))?;
let (stdout, out_over) = out
.lock()
.map_err(|_| build_err("stdout state unavailable"))?
.clone();
let (stderr, err_over) = err
.lock()
.map_err(|_| build_err("stderr state unavailable"))?
.clone();
let expected_missing = run
.expected_stdout
.is_some_and(|expected| !String::from_utf8_lossy(&stdout).contains(expected))
|| run
.expected_stdout_exact
.is_some_and(|expected| String::from_utf8_lossy(&stdout).trim() != expected);
let outcome = if timed_out {
CommandOutcome::TimedOut
} else if cancelled {
CommandOutcome::Cancelled
} else if over_limit || !drained || out_over || err_over {
CommandOutcome::OutputLimitExceeded
} else if expected_missing {
CommandOutcome::Failed(-1)
} else if status.success() {
CommandOutcome::Success
} else {
CommandOutcome::Failed(status.code().unwrap_or(-1))
};
Ok(ProcessEvidence {
outcome,
stdout_bytes: stdout.len(),
stderr_bytes: stderr.len(),
})
}
fn join_drained(
handle: thread::JoinHandle<()>,
drain_until: Instant,
reader_error: &'static str,
) -> Result<bool, BuildError> {
while !handle.is_finished() {
if Instant::now() >= drain_until {
return Ok(false);
}
thread::sleep(Duration::from_millis(10));
}
handle.join().map_err(|_| build_err(reader_error))?;
Ok(true)
}
fn stream_over_limit(capture: &Arc<Mutex<(Vec<u8>, bool)>>) -> bool {
capture.lock().map(|state| state.1).unwrap_or(false)
}
fn drain<R: Read>(mut reader: R, capture: Arc<Mutex<(Vec<u8>, bool)>>, limit: usize) {
let mut buffer = [0; 8192];
loop {
match reader.read(&mut buffer) {
Ok(0) | Err(_) => break,
Ok(n) => {
if let Ok(mut state) = capture.lock() {
let keep = n.min(limit.saturating_sub(state.0.len()));
state.0.extend_from_slice(&buffer[..keep]);
if keep < n {
state.1 = true;
}
}
}
}
}
}
fn preflight(
target: &crate::PlannedTarget,
cwd: &Path,
cancellation: &BuildCancellation,
) -> Result<(), BuildError> {
let rust = run_bounded_cancellable(
&CommandSpec {
executable: "rustc".into(),
args: vec![
"+".to_owned() + &target.policy.toolchain.rust,
"--version".into(),
],
cwd: cwd.into(),
env: BTreeMap::new(),
timeout: Duration::from_secs(10),
stdout_limit: 1024,
stderr_limit: 1024,
expected_stdout: None,
expected_stdout_exact: None,
},
cancellation,
)?;
if rust.outcome != CommandOutcome::Success {
return Err(build_err("configured Rust toolchain preflight failed"));
}
let cargo = run_bounded_cancellable(
&CommandSpec {
executable: "cargo".into(),
args: vec![
"+".to_owned() + &target.policy.toolchain.rust,
"--version".into(),
],
cwd: cwd.into(),
env: BTreeMap::new(),
timeout: Duration::from_secs(10),
stdout_limit: 1024,
stderr_limit: 1024,
expected_stdout: None,
expected_stdout_exact: None,
},
cancellation,
)?;
if cargo.outcome != CommandOutcome::Success {
return Err(build_err("configured Cargo toolchain preflight failed"));
}
if target.policy.strategy == BuildStrategy::CargoZigbuild {
let expected = target
.policy
.toolchain
.cargo_zigbuild
.as_deref()
.ok_or_else(|| build_err("cargo-zigbuild version missing"))?;
let expected_zig = target
.policy
.toolchain
.zig
.as_deref()
.ok_or_else(|| build_err("Zig version missing"))?;
let actual = run_bounded_cancellable(
&CommandSpec {
executable: "cargo".into(),
args: vec!["zigbuild".into(), "--version".into()],
cwd: cwd.into(),
env: BTreeMap::new(),
timeout: Duration::from_secs(10),
stdout_limit: 1024,
stderr_limit: 1024,
expected_stdout: None,
expected_stdout_exact: Some(format!("cargo-zigbuild {expected}")),
},
cancellation,
)?;
if actual.outcome != CommandOutcome::Success {
return Err(build_err("cargo-zigbuild version mismatch"));
}
let zig = run_bounded_cancellable(
&CommandSpec {
executable: "zig".into(),
args: vec!["version".into()],
cwd: cwd.into(),
env: BTreeMap::new(),
timeout: Duration::from_secs(10),
stdout_limit: 1024,
stderr_limit: 1024,
expected_stdout: None,
expected_stdout_exact: Some(expected_zig.to_owned()),
},
cancellation,
)?;
if zig.outcome != CommandOutcome::Success {
return Err(build_err("Zig version mismatch"));
}
}
Ok(())
}
pub fn execute_target(
plan: &ReleasePlan,
target: &crate::PlannedTarget,
bindings: &[BuildBinding],
repository_root: &Path,
work_root: &Path,
invocation: &str,
) -> Result<BuildAttempt, BuildError> {
execute_target_cancellable(
plan,
target,
bindings,
repository_root,
work_root,
invocation,
&BuildCancellation::new(),
)
}
pub fn execute_target_cancellable(
plan: &ReleasePlan,
target: &crate::PlannedTarget,
bindings: &[BuildBinding],
repository_root: &Path,
work_root: &Path,
invocation: &str,
cancellation: &BuildCancellation,
) -> Result<BuildAttempt, BuildError> {
if !plan.targets.iter().any(|planned| planned == target)
|| plan.schema_version != 1
|| plan.release_id.is_empty()
|| plan.source_revision.is_empty()
{
return Err(build_err(
"target is not part of the supplied ReleasePlan identity",
));
}
if !repository_root.is_absolute() {
return Err(build_err("repository root must be absolute"));
}
let repository =
fs::canonicalize(repository_root).map_err(|_| build_err("repository root unavailable"))?;
preflight(target, &repository, cancellation)?;
let target_dir = private_target_dir(work_root, invocation, &target.target)?;
fs::create_dir(&target_dir)
.map_err(|_| build_err("private Cargo target directory creation failed"))?;
let mut candidates = Vec::new();
let mut last = ProcessEvidence {
outcome: CommandOutcome::Success,
stdout_bytes: 0,
stderr_bytes: 0,
};
for binding in bindings {
let spec = cargo_command(
target,
binding,
&repository,
&target_dir,
Duration::from_secs(1800),
)?;
let evidence = run_bounded_cancellable(&spec, cancellation)?;
if evidence.outcome != CommandOutcome::Success {
return Ok(BuildAttempt {
release_id: plan.release_id.clone(),
source_revision: plan.source_revision.clone(),
target: target.target.clone(),
strategy: target.policy.strategy,
tool_summary: format!("rust {}", target.policy.toolchain.rust),
process: evidence,
candidates: Vec::new(),
});
}
let (path, size) = discover_candidate(&target_dir, &target.target, &binding.binary)?;
candidates.push(CandidateArtifact {
target: target.target.clone(),
selector: binding.selector.clone(),
package: binding.package.clone(),
binary: binding.binary.clone(),
path,
size,
});
last = evidence;
}
if candidates.is_empty() {
return Err(build_err("build produced no candidates"));
}
Ok(BuildAttempt {
release_id: plan.release_id.clone(),
source_revision: plan.source_revision.clone(),
target: target.target.clone(),
strategy: target.policy.strategy,
tool_summary: format!(
"rust {}{}{}",
target.policy.toolchain.rust,
target
.policy
.toolchain
.cargo_zigbuild
.as_ref()
.map(|v| format!(" cargo-zigbuild {v}"))
.unwrap_or_default(),
target
.policy
.toolchain
.zig
.as_ref()
.map(|v| format!(" zig {v}"))
.unwrap_or_default()
),
process: last,
candidates,
})
}
pub fn private_target_dir(
work_root: &Path,
invocation: &str,
target: &str,
) -> Result<PathBuf, BuildError> {
if !work_root.is_absolute()
|| invocation.is_empty()
|| invocation.len() > 128
|| target.is_empty()
{
return Err(build_err("invalid private work root identity"));
}
if fs::symlink_metadata(work_root)
.map_err(|_| build_err("work root must pre-exist"))?
.file_type()
.is_symlink()
{
return Err(build_err("symlink work root rejected"));
}
let canonical =
fs::canonicalize(work_root).map_err(|_| build_err("work root canonicalization failed"))?;
let name = format!("{}-{}", safe_component(invocation), safe_component(target));
let path = canonical.join(name);
match fs::create_dir(&path) {
Ok(()) => (),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
return Err(build_err("private build directory already exists"))
}
Err(_) => return Err(build_err("private build directory creation failed")),
}
let check = fs::canonicalize(&path)
.map_err(|_| build_err("private build path canonicalization failed"))?;
if !check.starts_with(&canonical) {
return Err(build_err("private build path escapes work root"));
}
let mut metadata = fs::File::create(path.join(".eggpack-owner"))
.map_err(|_| build_err("ownership marker creation failed"))?;
metadata
.write_all(format!("1\n{}\n{}\n", invocation, target).as_bytes())
.map_err(|_| build_err("ownership marker write failed"))?;
Ok(path.join("target"))
}
fn safe_component(s: &str) -> String {
s.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect()
}
pub fn discover_candidate(
target_dir: &Path,
target: &str,
binary: &str,
) -> Result<(PathBuf, u64), BuildError> {
if !valid_identifier(binary) {
return Err(build_err("invalid binary name"));
}
let mut path = target_dir.join(target).join("release").join(binary);
if target.contains("-windows-") {
path.set_file_name(format!("{binary}.exe"));
}
let metadata =
fs::symlink_metadata(&path).map_err(|_| build_err("expected candidate missing"))?;
if metadata.file_type().is_symlink() || !metadata.file_type().is_file() || metadata.len() == 0 {
return Err(build_err("candidate is not a non-empty regular file"));
}
let canonical_root =
fs::canonicalize(target_dir).map_err(|_| build_err("target directory unavailable"))?;
let canonical_file =
fs::canonicalize(&path).map_err(|_| build_err("candidate canonicalization failed"))?;
if !canonical_file.starts_with(&canonical_root) {
return Err(build_err("candidate escapes private target directory"));
}
let release_dir = target_dir.join(target).join("release");
let target_meta = fs::symlink_metadata(target_dir.join(target))
.map_err(|_| build_err("target output directory missing"))?;
let release_meta = fs::symlink_metadata(&release_dir)
.map_err(|_| build_err("release output directory missing"))?;
if target_meta.file_type().is_symlink()
|| !target_meta.is_dir()
|| release_meta.file_type().is_symlink()
|| !release_meta.is_dir()
{
return Err(build_err(
"candidate parent directory is not private regular directory",
));
}
Ok((path, metadata.len()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{HostArch, HostOs, Qualification, SupportTier, TargetPolicy, ToolchainRequirement};
use std::sync::Mutex;
static CARGO_FIXTURE_LOCK: Mutex<()> = Mutex::new(());
fn target() -> crate::PlannedTarget {
crate::PlannedTarget {
target: "x86_64-unknown-linux-gnu".into(),
policy: TargetPolicy {
target: "x86_64-unknown-linux-gnu".into(),
strategy: BuildStrategy::NativeCargo,
host_os: HostOs::Linux,
host_arch: HostArch::X86_64,
qualification_host: None,
toolchain: ToolchainRequirement {
rust: "1.89.0".into(),
cargo_zigbuild: None,
zig: None,
},
floor: CompatibilityFloor::None,
qualification: Qualification::Native,
support: SupportTier::Required,
},
artifact_form: crate::PlannedAssetForm::Direct,
floor_status: crate::FloorVerificationStatus::NotDeclared,
}
}
#[test]
fn command_is_explicit_and_never_shell_based() {
let b = BuildBinding {
selector: LogicalOutputSelector::Direct,
package: "demo".into(),
binary: "demo-bin".into(),
};
let c = cargo_command(
&target(),
&b,
Path::new("/repo"),
Path::new("/private/target"),
Duration::from_secs(10),
)
.unwrap();
assert_eq!(c.executable, "cargo");
assert_eq!(
c.args,
[
"+1.89.0",
"build",
"--release",
"--locked",
"--target",
"x86_64-unknown-linux-gnu",
"--package",
"demo",
"--bin",
"demo-bin"
]
);
assert_eq!(c.env["CARGO_TARGET_DIR"], "/private/target");
let mut arbitrary = c;
arbitrary.executable = "sh".into();
assert!(
run_bounded_inner(&arbitrary, Cancellation::None, ExecutableAllowance::Builder)
.is_err()
);
}
#[test]
fn zigbuild_floor_uses_only_gnu_target_syntax() {
let mut t = target();
t.policy.strategy = BuildStrategy::CargoZigbuild;
t.policy.toolchain.cargo_zigbuild = Some("0.19.8".into());
t.policy.toolchain.zig = Some("0.14.1".into());
t.policy.floor = CompatibilityFloor::Glibc {
major: 2,
minor: 17,
};
let binding = BuildBinding {
selector: LogicalOutputSelector::Direct,
package: "demo".into(),
binary: "demo".into(),
};
let command = cargo_command(
&t,
&binding,
Path::new("/repo"),
Path::new("/target"),
Duration::from_secs(10),
)
.unwrap();
assert_eq!(command.args[1], "zigbuild");
assert_eq!(command.args[5], "x86_64-unknown-linux-gnu.2.17");
t.policy.floor = CompatibilityFloor::Macos {
major: 13,
minor: 0,
};
assert!(cargo_command(
&t,
&binding,
Path::new("/repo"),
Path::new("/target"),
Duration::from_secs(10)
)
.is_err());
}
#[test]
fn the_cargo_zigbuild_floor_rewrite_and_macos_refusal_are_unchanged() {
let mut t = target();
t.policy.strategy = BuildStrategy::CargoZigbuild;
t.policy.toolchain.cargo_zigbuild = Some("0.23.3".into());
t.policy.toolchain.zig = Some("0.14.1".into());
t.policy.floor = CompatibilityFloor::Glibc {
major: 2,
minor: 17,
};
let binding = BuildBinding {
selector: LogicalOutputSelector::Direct,
package: "demo".into(),
binary: "demo".into(),
};
let command = cargo_command(
&t,
&binding,
Path::new("/repo"),
Path::new("/target"),
Duration::from_secs(10),
)
.unwrap();
assert_eq!(
command.args,
vec![
"+1.89.0",
"zigbuild",
"--release",
"--locked",
"--target",
"x86_64-unknown-linux-gnu.2.17",
"--package",
"demo",
"--bin",
"demo",
]
);
t.policy.floor = CompatibilityFloor::Macos {
major: 13,
minor: 0,
};
let refusal = cargo_command(
&t,
&binding,
Path::new("/repo"),
Path::new("/target"),
Duration::from_secs(10),
)
.unwrap_err();
assert_eq!(refusal.to_string(), "macOS floor cannot use cargo-zigbuild");
assert_eq!(
t.policy.floor,
CompatibilityFloor::Macos {
major: 13,
minor: 0
}
);
}
#[test]
fn binding_document_rejects_duplicate_and_unknown_fields() {
let good = r#"schema_version = 1
[targets]
"x86_64-unknown-linux-gnu" = [{ selector = { kind = "direct" }, package = "demo", binary = "demo" }]
"#;
assert!(BuildBindingsV1::from_toml(good).is_ok());
assert!(BuildBindingsV1::from_toml(
&good.replace("schema_version = 1", "schema_version = 2")
)
.is_err());
assert!(
BuildBindingsV1::from_toml(&good.replace("package =", "extra = 1, package =")).is_err()
);
}
#[test]
fn bindings_must_match_direct_contract_slots_exactly() {
let contract = DistributionContract::parse_toml_str(include_str!(
"../../eggpack-contract/tests/fixtures/simple-direct.toml"
))
.unwrap();
let plan = crate::PackConfig {
schema_version: 1,
targets: vec![target().policy],
}
.resolve(&contract, "1.0", "abc", &["linux-x64".into()])
.unwrap();
let bindings = BuildBindingsV1 {
schema_version: 1,
targets: [(
"x86_64-unknown-linux-gnu".into(),
vec![BuildBinding {
selector: LogicalOutputSelector::Direct,
package: "demo".into(),
binary: "demo".into(),
}],
)]
.into_iter()
.collect(),
};
assert!(bindings.validate_for(&contract, &plan).is_ok());
let mut invalid = bindings;
invalid.targets.get_mut("x86_64-unknown-linux-gnu").unwrap()[0].selector =
LogicalOutputSelector::BundleEntry { index: 0 };
assert!(invalid.validate_for(&contract, &plan).is_err());
}
#[test]
fn candidate_lookup_is_exact_regular_and_nonempty() {
let root = crate::test_temp_dir("builder-test");
let out = root.join("x86_64-unknown-linux-gnu/release");
fs::create_dir_all(&out).unwrap();
fs::write(out.join("demo"), b"binary").unwrap();
assert_eq!(
discover_candidate(&root, "x86_64-unknown-linux-gnu", "demo")
.unwrap()
.1,
6
);
fs::write(out.join("empty"), b"").unwrap();
assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "empty").is_err());
assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "other").is_err());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn windows_candidate_appends_exe_and_preserves_dotted_names() {
let root = crate::test_temp_dir("builder-exe-test");
let target = "x86_64-pc-windows-msvc";
let out = root.join(target).join("release");
fs::create_dir_all(&out).unwrap();
fs::write(out.join("demo.exe"), b"binary").unwrap();
assert_eq!(discover_candidate(&root, target, "demo").unwrap().1, 6);
fs::write(out.join("tool.cli.exe"), b"dotted").unwrap();
let (path, size) = discover_candidate(&root, target, "tool.cli").unwrap();
assert!(path.ends_with("tool.cli.exe"), "{path:?}");
assert_eq!(size, 6);
fs::remove_dir_all(root).unwrap();
let root = crate::test_temp_dir("builder-exe-test-2");
let out = root.join(target).join("release");
fs::create_dir_all(&out).unwrap();
fs::write(out.join("tool.exe"), b"truncated").unwrap();
assert!(discover_candidate(&root, target, "tool.cli").is_err());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn windows_candidate_matching_is_not_a_substring_heuristic() {
let root = crate::test_temp_dir("builder-triple-test");
let target = "x86_64-unknown-notwindowsish";
let out = root.join(target).join("release");
fs::create_dir_all(&out).unwrap();
fs::write(out.join("demo"), b"binary").unwrap();
assert!(discover_candidate(&root, target, "demo").is_ok());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn git_verification_is_bounded_and_exact() {
let root = crate::test_temp_dir("builder-git-test");
let git = |args: &[&str]| {
Command::new("git")
.args(args)
.current_dir(&root)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@example.invalid")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@example.invalid")
.output()
};
if !git(&["init", "--quiet"]).is_ok_and(|o| o.status.success()) {
fs::remove_dir_all(root).unwrap();
return; }
fs::write(root.join("f"), b"x").unwrap();
if !git(&["add", "f"]).is_ok_and(|o| o.status.success())
|| !git(&["commit", "--quiet", "-m", "c"]).is_ok_and(|o| o.status.success())
{
fs::remove_dir_all(root).unwrap();
return;
}
let head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
.unwrap()
.trim()
.to_owned();
assert_eq!(head.len(), 40);
assert!(git(&["tag", "v1.2.3"]).is_ok_and(|o| o.status.success()));
assert_eq!(
run_git_tag_bounded("v1.2.3", &head, Some(&root))
.unwrap()
.outcome,
CommandOutcome::Success
);
assert_ne!(
run_git_tag_bounded("v1.2.4", &head, Some(&root))
.unwrap()
.outcome,
CommandOutcome::Success
);
assert!(run_git_tag_bounded("v../evil", &head, Some(&root)).is_err());
assert!(run_git_tag_bounded("v1.2.3^{}", &head, Some(&root)).is_err());
fs::write(root.join("f"), b"second commit").unwrap();
assert!(git(&["add", "f"]).is_ok_and(|o| o.status.success()));
assert!(git(&["commit", "--quiet", "-m", "second"]).is_ok_and(|o| o.status.success()));
assert!(git(&["tag", "v1.2.9"]).is_ok_and(|o| o.status.success()));
let second_head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
.unwrap()
.trim()
.to_owned();
assert_ne!(
run_git_tag_bounded("v1.2.9", &head, Some(&root))
.unwrap()
.outcome,
CommandOutcome::Success,
"another tag pointing at a different commit must fail"
);
assert_eq!(
run_git_bounded(&second_head, Some(&root)).unwrap().outcome,
CommandOutcome::Success
);
let noisy = format!(" {second_head} ");
assert_ne!(
run_git_bounded(&noisy, Some(&root)).unwrap().outcome,
CommandOutcome::Success
);
assert_ne!(
run_git_bounded(&second_head[..39], Some(&root))
.unwrap()
.outcome,
CommandOutcome::Success
);
assert_ne!(
run_git_bounded(&"0".repeat(40), Some(&root))
.unwrap()
.outcome,
CommandOutcome::Success
);
let outside = crate::test_temp_dir("builder-git-outside");
assert_ne!(
run_git_bounded(&second_head, Some(&outside))
.unwrap()
.outcome,
CommandOutcome::Success
);
fs::remove_dir_all(outside).unwrap();
fs::remove_dir_all(root).unwrap();
}
#[test]
fn private_workspace_rejects_relative_and_reused_invocations() {
let root = crate::test_temp_dir("private-test");
assert!(private_target_dir(Path::new("relative"), "run", "target").is_err());
assert!(private_target_dir(&root, "run", "target").is_ok());
assert!(private_target_dir(&root, "run", "target").is_err());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn process_output_is_bounded_and_exit_status_explicit() {
let spec = CommandSpec {
executable: "rustc".into(),
args: vec!["--version".into()],
cwd: std::env::current_dir().unwrap(),
env: BTreeMap::new(),
timeout: Duration::from_secs(5),
stdout_limit: 1024,
stderr_limit: 1024,
expected_stdout: None,
expected_stdout_exact: None,
};
let result =
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder).unwrap();
assert_eq!(result.outcome, CommandOutcome::Success);
assert!(result.stdout_bytes <= 1024);
}
#[cfg(unix)]
#[test]
fn terminating_an_already_exited_process_group_is_not_a_failure() {
let mut command = Command::new("sh");
command.args(["-c", "exit 0"]);
let mut child = command.group_spawn().unwrap();
child.wait().unwrap();
assert!(child.kill().is_err());
assert!(terminate_process_group(&mut child, "test termination").is_ok());
}
#[cfg(unix)]
#[test]
fn a_failed_group_signal_is_benign_only_after_recheck_proves_termination() {
let no_such_group = std::io::Error::from_raw_os_error(libc::ESRCH);
let not_permitted = std::io::Error::from_raw_os_error(libc::EPERM);
assert!(group_signal_failure_is_benign(
&no_such_group,
false,
|| { panic!("ESRCH must not trigger a retry") }
));
assert!(!group_signal_failure_is_benign(
¬_permitted,
false,
|| { panic!("a live or unverified child must not trigger a retry") }
));
assert!(group_signal_failure_is_benign(¬_permitted, true, || Ok(
()
)));
assert!(group_signal_failure_is_benign(¬_permitted, true, || {
Err(std::io::Error::from_raw_os_error(libc::ESRCH))
}));
assert!(!group_signal_failure_is_benign(
¬_permitted,
true,
|| { Err(std::io::Error::from_raw_os_error(libc::EPERM)) }
));
}
#[cfg(unix)]
#[test]
fn terminating_an_exited_leader_still_signals_a_live_group_descendant() {
let root = crate::test_temp_dir("group-descendant-termination");
let started = root.join("descendant-started");
let release = root.join("descendant-release");
let survived = root.join("descendant-survived");
let started_arg = started.to_string_lossy().into_owned();
let release_arg = release.to_string_lossy().into_owned();
let survived_arg = survived.to_string_lossy().into_owned();
let mut command = Command::new("sh");
command.args([
"-c",
"sh -c 'printf started > \"$1\"; while [ ! -e \"$2\" ]; do sleep 0.01; done; printf survived > \"$3\"' sh \"$1\" \"$2\" \"$3\" >/dev/null 2>&1 & while [ ! -e \"$1\" ]; do sleep 0.01; done; exit 0",
"group-fixture",
started_arg.as_str(),
release_arg.as_str(),
survived_arg.as_str(),
]);
let mut child = command.group_spawn().unwrap();
let leader_deadline = Instant::now() + Duration::from_secs(3);
let leader_status = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status),
Ok(None) if Instant::now() < leader_deadline => {
thread::sleep(Duration::from_millis(10));
}
_ => break None,
}
};
let descendant_deadline = Instant::now() + Duration::from_secs(1);
while !started.is_file() && Instant::now() < descendant_deadline {
thread::sleep(Duration::from_millis(10));
}
let terminated = terminate_process_group(&mut child, "test termination").is_ok();
if !terminated {
let _ = child.kill();
}
fs::write(&release, "release").unwrap();
let survivor_deadline = Instant::now() + Duration::from_secs(1);
while !survived.is_file() && Instant::now() < survivor_deadline {
thread::sleep(Duration::from_millis(10));
}
let descendant_started = started.is_file();
let descendant_survived = survived.exists();
let leader_succeeded = leader_status.is_some_and(|status| status.success());
fs::remove_dir_all(root).unwrap();
assert!(leader_succeeded, "the group leader must exit normally");
assert!(descendant_started, "the live descendant fixture must start");
assert!(terminated, "the process group must be terminated");
assert!(
!descendant_survived,
"the descendant must not outlive group termination"
);
}
#[test]
fn nonzero_tool_exit_is_not_success() {
let spec = CommandSpec {
executable: "rustc".into(),
args: vec!["--eggpack-invalid-option".into()],
cwd: std::env::current_dir().unwrap(),
env: BTreeMap::new(),
timeout: Duration::from_secs(5),
stdout_limit: 1024,
stderr_limit: 1024,
expected_stdout: None,
expected_stdout_exact: None,
};
assert!(matches!(
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
.unwrap()
.outcome,
CommandOutcome::Failed(_)
));
}
#[test]
fn stdout_overflow_is_bounded_and_not_success() {
let root = crate::test_temp_dir("output-bound");
let source = root.join("many-errors.rs");
let body = (0..200)
.map(|i| format!("fn f{i}() {{ absent_symbol_{i}(); }}\n"))
.collect::<String>();
fs::write(&source, body).unwrap();
let spec = CommandSpec {
executable: "rustc".into(),
args: vec![
"--crate-type".into(),
"lib".into(),
source.to_string_lossy().into_owned(),
],
cwd: root.clone(),
env: BTreeMap::new(),
timeout: Duration::from_secs(10),
stdout_limit: 128,
stderr_limit: 128,
expected_stdout: None,
expected_stdout_exact: None,
};
assert_eq!(
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
.unwrap()
.outcome,
CommandOutcome::OutputLimitExceeded
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn timeout_kills_and_waits_for_the_process_group() {
let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
let root = crate::test_temp_dir("timeout");
fs::create_dir_all(root.join("src")).unwrap();
fs::write(root.join("Cargo.toml"), "[package]\nname='timeout-fixture'\nversion='0.1.0'\nedition='2021'\nbuild='build.rs'\n").unwrap();
fs::write(
root.join("Cargo.lock"),
"version = 3\n\n[[package]]\nname = \"timeout-fixture\"\nversion = \"0.1.0\"\n",
)
.unwrap();
fs::write(
root.join("build.rs"),
"fn main() { println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_STARTED\"); println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_SLEEP\"); if let Some(path) = std::env::var_os(\"EGGPACK_BUILD_STARTED\") { std::fs::write(path, b\"started\").unwrap(); } if std::env::var_os(\"EGGPACK_BUILD_SLEEP\").is_some() { std::thread::sleep(std::time::Duration::from_secs(30)); } }\n",
)
.unwrap();
fs::write(root.join("src/lib.rs"), "pub fn fixture() {}\n").unwrap();
let mut spec = CommandSpec {
executable: "cargo".into(),
args: vec![
"build".into(),
"--locked".into(),
"--offline".into(),
"--manifest-path".into(),
root.join("Cargo.toml").to_string_lossy().into_owned(),
],
cwd: root.clone(),
env: BTreeMap::new(),
timeout: Duration::from_secs(60),
stdout_limit: 4096,
stderr_limit: 4096,
expected_stdout: None,
expected_stdout_exact: None,
};
for iteration in 0..3 {
spec.timeout = Duration::from_secs(60);
spec.env.remove("EGGPACK_BUILD_SLEEP");
let timeout_target = root.join(format!("cargo-target-timeout-{iteration}"));
spec.env.insert(
"CARGO_TARGET_DIR".into(),
timeout_target.to_string_lossy().into_owned(),
);
let warm_timeout = root.join(format!("warm-timeout-{iteration}"));
spec.env.insert(
"EGGPACK_BUILD_STARTED".into(),
warm_timeout.to_string_lossy().into_owned(),
);
assert_eq!(
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
.unwrap()
.outcome,
CommandOutcome::Success
);
assert!(warm_timeout.is_file(), "timeout fixture warm-up failed");
spec.timeout = Duration::from_secs(5);
spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
let timeout_started = root.join(format!("timeout-started-{iteration}"));
spec.env.insert(
"EGGPACK_BUILD_STARTED".into(),
timeout_started.to_string_lossy().into_owned(),
);
assert_eq!(
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
.unwrap()
.outcome,
CommandOutcome::TimedOut
);
assert!(timeout_started.is_file(), "build script never started");
spec.timeout = Duration::from_secs(60);
spec.env.remove("EGGPACK_BUILD_SLEEP");
let cancel_target = root.join(format!("cargo-target-cancel-{iteration}"));
spec.env.insert(
"CARGO_TARGET_DIR".into(),
cancel_target.to_string_lossy().into_owned(),
);
let warm_cancel = root.join(format!("warm-cancel-{iteration}"));
spec.env.insert(
"EGGPACK_BUILD_STARTED".into(),
warm_cancel.to_string_lossy().into_owned(),
);
assert_eq!(
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
.unwrap()
.outcome,
CommandOutcome::Success
);
assert!(warm_cancel.is_file(), "cancellation fixture warm-up failed");
spec.timeout = Duration::from_secs(180);
spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
let cancellation = BuildCancellation::new();
let request = cancellation.clone();
let cancellation_started = root.join(format!("cancellation-started-{iteration}"));
spec.env.insert(
"EGGPACK_BUILD_STARTED".into(),
cancellation_started.to_string_lossy().into_owned(),
);
let cancellation_started_by_thread = cancellation_started.clone();
let canceller = thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(15);
while !cancellation_started_by_thread.is_file() && Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
assert!(
cancellation_started_by_thread.is_file(),
"build script did not start before cancellation deadline"
);
request.cancel();
});
assert_eq!(
run_bounded_cancellable(&spec, &cancellation)
.unwrap()
.outcome,
CommandOutcome::Cancelled
);
canceller.join().unwrap();
assert!(cancellation_started.is_file());
}
fs::remove_dir_all(root).unwrap();
}
#[test]
#[ignore]
#[allow(clippy::zombie_processes)]
fn builder_child_leaves_parked_descendant() {
std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"builder::tests::builder_child_holds_stdout",
"--ignored",
"--nocapture",
])
.spawn()
.unwrap();
}
#[test]
#[ignore]
fn builder_child_holds_stdout() {
std::thread::sleep(Duration::from_secs(20));
}
#[test]
fn parked_drain_reader_cannot_outlive_the_deadline() {
let spec = CommandSpec {
executable: std::env::current_exe()
.unwrap()
.to_string_lossy()
.into_owned(),
args: vec![
"--exact".into(),
"builder::tests::builder_child_leaves_parked_descendant".into(),
"--ignored".into(),
"--nocapture".into(),
],
cwd: std::env::current_dir().unwrap(),
env: BTreeMap::new(),
timeout: Duration::from_secs(10),
stdout_limit: 4096,
stderr_limit: 4096,
expected_stdout: None,
expected_stdout_exact: None,
};
let started = Instant::now();
let evidence =
run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Candidate).unwrap();
assert_eq!(
evidence.outcome,
CommandOutcome::OutputLimitExceeded,
"a parked drain reader must fail the run closed, not report success"
);
assert!(
started.elapsed() < Duration::from_secs(15),
"bounded run took {:?}; the parked reader defeated the deadline",
started.elapsed()
);
}
#[test]
fn real_local_cargo_fixture_builds_a_direct_candidate() {
let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
let base = crate::test_temp_dir("cargo-smoke");
let repo = base.join("repo");
let work = base.join("work");
fs::create_dir_all(repo.join("src")).unwrap();
fs::create_dir_all(&work).unwrap();
fs::write(
repo.join("Cargo.toml"),
"[package]\nname='smoke-fixture'\nversion='0.1.0'\nedition='2021'\n",
)
.unwrap();
fs::write(
repo.join("Cargo.lock"),
"version = 3\n\n[[package]]\nname = \"smoke-fixture\"\nversion = \"0.1.0\"\n",
)
.unwrap();
fs::write(repo.join("src/main.rs"), "fn main() {}\n").unwrap();
let mut t = target();
t.policy.toolchain.rust = "stable".into();
let (triple, os, arch) = match (std::env::consts::OS, std::env::consts::ARCH) {
("windows", "x86_64") => ("x86_64-pc-windows-msvc", HostOs::Windows, HostArch::X86_64),
("macos", "x86_64") => ("x86_64-apple-darwin", HostOs::Macos, HostArch::X86_64),
("macos", "aarch64") => ("aarch64-apple-darwin", HostOs::Macos, HostArch::Aarch64),
("linux", "x86_64") => ("x86_64-unknown-linux-gnu", HostOs::Linux, HostArch::X86_64),
("linux", "aarch64") => (
"aarch64-unknown-linux-gnu",
HostOs::Linux,
HostArch::Aarch64,
),
other => panic!("unsupported hosted Cargo smoke platform: {other:?}"),
};
t.target = triple.into();
t.policy.target = triple.into();
t.policy.host_os = os;
t.policy.host_arch = arch;
let binding = BuildBinding {
selector: LogicalOutputSelector::Direct,
package: "smoke-fixture".into(),
binary: "smoke-fixture".into(),
};
let plan = ReleasePlan {
schema_version: 1,
release_id: "test".into(),
source_revision: "abc".into(),
targets: vec![t.clone()],
};
let attempt = execute_target(&plan, &t, &[binding], &repo, &work, "smoke").unwrap();
assert_eq!(attempt.process.outcome, CommandOutcome::Success);
assert_eq!(attempt.release_id, plan.release_id);
assert_eq!(attempt.source_revision, plan.source_revision);
assert_eq!(attempt.candidates.len(), 1);
assert!(attempt.candidates[0].size > 0);
fs::remove_dir_all(base).unwrap();
}
}