const BASELINE_PYTHON_VERSION: &str = "3.13.1";
pub async fn output_store(dir: impl Into<std::path::PathBuf>) -> aither_sandbox::OutputStore {
aither_sandbox::OutputStore::new(dir, aither_core::AnyIdAllocator::default())
.await
.expect("the output directory can be created")
}
pub async fn finish_run(
run: crate::Run<impl std::future::Future<Output = Result<(), crate::AgentError>>>,
) -> Result<(), crate::AgentError> {
run.drive((), std::future::pending(), |(), _| async {
std::ops::ControlFlow::<std::convert::Infallible, _>::Continue(())
})
.await
.map(|_| ())
}
pub async fn finish_compaction(
run: crate::Run<impl std::future::Future<Output = Result<(), crate::AgentError>>>,
) -> Result<Option<crate::CompactResult>, crate::AgentError> {
let std::ops::ControlFlow::Continue(applied) = run
.drive(None, std::future::pending(), |applied, timed| async move {
std::ops::ControlFlow::<std::convert::Infallible, _>::Continue(match timed.event {
crate::AgentEvent::CompactionFinished {
outcome: crate::CompactionOutcome::Applied(result),
} => Some(result),
_ => applied,
})
})
.await?;
Ok(applied)
}
pub struct TempDir(tempfile::TempDir);
impl TempDir {
pub fn new() -> Self {
Self(tempfile::tempdir().unwrap())
}
}
impl std::ops::Deref for TempDir {
type Target = tempfile::TempDir;
fn deref(&self) -> &tempfile::TempDir {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut pending = vec![self.0.path().to_path_buf()];
while let Some(path) = pending.pop() {
let Ok(metadata) = std::fs::symlink_metadata(&path) else {
continue;
};
if metadata.is_symlink() {
continue;
}
let mode = metadata.permissions().mode() | 0o200;
let _ =
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode | 0o100));
if metadata.is_dir()
&& let Ok(entries) = std::fs::read_dir(&path)
{
pending.extend(entries.flatten().map(|entry| entry.path()));
}
}
}
}
}
pub struct ToolCache {
path: std::path::PathBuf,
_temporary: Option<TempDir>,
}
impl ToolCache {
pub const SHARED_ENVIRONMENT: &str = "AITHER_TOOL_CACHE";
pub fn temporary() -> Self {
let directory = TempDir::new();
Self {
path: directory.path().to_path_buf(),
_temporary: Some(directory),
}
}
pub fn shared() -> Self {
std::env::var_os(Self::SHARED_ENVIRONMENT).map_or_else(Self::temporary, |path| Self {
path: path.into(),
_temporary: None,
})
}
pub fn path(&self) -> &std::path::Path {
&self.path
}
}
pub async fn compile_baseline_fixture(source: &std::path::Path) -> std::path::PathBuf {
let fixture = std::path::Path::new("baseline_tool.rs");
async_fs::write(
source.join(fixture),
include_bytes!("../templates/test_baseline_tool.rs"),
)
.await
.unwrap();
let output =
std::path::Path::new("baseline-tool").with_extension(std::env::consts::EXE_EXTENSION);
let path = source.join(&output);
let compiled = async_process::Command::new("rustc")
.current_dir(source)
.env(
"BASELINE_ALIASES",
aither_sandbox::ManagedTool::Coreutils.aliases().join("\n"),
)
.env("BASELINE_PYTHON_VERSION", BASELINE_PYTHON_VERSION)
.env(
"BASELINE_COMMANDS",
aither_sandbox::ManagedTool::ALL
.map(aither_sandbox::ManagedTool::command)
.join("\n"),
)
.arg("--crate-name")
.arg("baseline_tool")
.arg(fixture)
.arg("-o")
.arg(&output)
.kill_on_drop(true)
.output()
.await
.unwrap();
assert!(compiled.status.success(), "{compiled:?}");
path
}
async fn fixture_artifacts(
binary: &std::path::Path,
version: &str,
tools: &[aither_sandbox::ManagedTool],
) -> Vec<aither_sandbox::ToolArtifact> {
use aither_sandbox::{ToolArtifact, ToolArtifactFormat, ToolTarget};
use sha2::Digest as _;
let bytes = async_fs::read(binary).await.unwrap();
tools
.iter()
.map(|&tool| ToolArtifact {
tool,
version: version.into(),
target: ToolTarget::native().unwrap(),
url: aither_sandbox::ToolArtifactLocation::Download(
url::Url::from_file_path(binary).unwrap(),
),
sha256: hex::encode(sha2::Sha256::digest(&bytes)),
size: bytes.len() as u64,
encoding: ToolArtifactFormat::Executable,
})
.collect()
}
fn distribution_of(
artifacts: &[serde_json::Value],
python: &[serde_json::Value],
) -> aither_sandbox::ToolDistribution {
aither_sandbox::ToolDistribution::from_json(
&serde_json::to_vec(&serde_json::json!({
"artifacts": artifacts,
"host_programs": aither_sandbox::test_heel::host_programs(),
"python": python,
}))
.unwrap(),
)
.unwrap()
}
async fn fixture_python(binary: &std::path::Path) -> Vec<serde_json::Value> {
use sha2::Digest as _;
let target = aither_sandbox::ToolTarget::native().unwrap();
if !target.provides_python() {
return Vec::new();
}
let bytes = async_fs::read(binary).await.unwrap();
vec![
serde_json::to_value(aither_sandbox::PythonPin {
version: BASELINE_PYTHON_VERSION.into(),
target,
interpreter_sha256: hex::encode(sha2::Sha256::digest(&bytes)),
})
.unwrap(),
]
}
pub async fn fixture_distribution(
binary: &std::path::Path,
version: &str,
) -> aither_sandbox::ToolDistribution {
let native = aither_sandbox::ToolTarget::native().unwrap();
let artifacts = fixture_artifacts(binary, version, native.required_tools()).await;
distribution_of(
&artifacts
.iter()
.map(|artifact| serde_json::to_value(artifact).unwrap())
.collect::<Vec<_>>(),
&fixture_python(binary).await,
)
}
pub async fn real_distribution(binary: &std::path::Path) -> aither_sandbox::ToolDistribution {
let pinned =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../patch/third-party-tools.json");
let pinned: serde_json::Value =
serde_json::from_slice(&async_fs::read(pinned).await.unwrap()).unwrap();
let mut artifacts = pinned["artifacts"].as_array().unwrap().clone();
artifacts.extend(
fixture_artifacts(
binary,
"1.0.0",
&[
aither_sandbox::ManagedTool::ApplyPatch,
aither_sandbox::ManagedTool::Sed,
aither_sandbox::ManagedTool::Bash,
],
)
.await
.iter()
.map(|artifact| serde_json::to_value(artifact).unwrap()),
);
let distribution = distribution_of(&artifacts, pinned["python"].as_array().unwrap());
match std::env::var("GITHUB_TOKEN") {
Ok(token) => distribution.with_github_token(token),
Err(_) => distribution,
}
}
pub struct PreparedFixture {
pub tools: aither_sandbox::PreparedTools<std::path::PathBuf>,
_source: tempfile::TempDir,
_cache: TempDir,
}
pub async fn prepared_fixture() -> PreparedFixture {
let source = tempfile::tempdir().unwrap();
let cache = TempDir::new();
let binary = compile_baseline_fixture(source.path()).await;
let bundle = fixture_distribution(&binary, "1.0.0")
.await
.load(
&aither_sandbox::ToolTarget::native().unwrap(),
&cache.path().join("artifacts"),
)
.await
.unwrap();
let tools = bundle
.prepare_local(&cache.path().join("runtimes"))
.await
.unwrap();
PreparedFixture {
tools,
_source: source,
_cache: cache,
}
}