use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use eryx::{CpuFeatureLevel, Session}; use sha2::{Digest, Sha256};
const MAX_RUNTIME_WASM_BYTES: u64 = 256 * 1024 * 1024;
const MAX_CHECKSUM_BYTES: u64 = 1024;
#[derive(Parser, Debug)]
#[command(name = "eryx-precompile")]
#[command(version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Debug)]
enum Command {
Setup(SetupArgs),
Compile(Box<CompileArgs>),
Upgrade(UpgradeArgs),
}
#[derive(Parser, Debug)]
struct UpgradeArgs {
#[arg(required = true)]
input: PathBuf,
#[arg(short, long, required = true)]
output: PathBuf,
#[arg(long)]
no_verify: bool,
#[arg(short, long)]
verbose: bool,
}
#[derive(Parser, Debug)]
struct SetupArgs {
#[arg(long)]
version: Option<String>,
#[arg(long, value_name = "HEX")]
sha256: Option<String>,
#[arg(short, long)]
verbose: bool,
}
#[derive(Parser, Debug)]
struct CompileArgs {
#[arg(required = true)]
input: PathBuf,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(short, long)]
target: Option<String>,
#[arg(short = 'c', long, value_name = "LEVEL")]
cpu_features: Option<CpuFeatureLevel>,
#[arg(long)]
preinit: bool,
#[arg(long)]
stdlib: Option<PathBuf>,
#[arg(long, requires = "preinit")]
site_packages: Option<PathBuf>,
#[arg(long = "package", value_name = "PATH", requires = "preinit")]
packages: Vec<PathBuf>,
#[arg(long = "import", value_name = "MODULE", requires = "preinit")]
imports: Vec<String>,
#[arg(long, conflicts_with_all = ["target", "cpu_features"])]
wasm_only: bool,
#[arg(long)]
no_verify: bool,
#[arg(
long,
value_name = "CODE",
conflicts_with = "setup_file",
requires = "preinit"
)]
setup_code: Option<String>,
#[arg(
long,
value_name = "PATH",
conflicts_with = "setup_code",
requires = "preinit"
)]
setup_file: Option<PathBuf>,
#[arg(long, value_name = "PATH", requires = "preinit")]
callbacks: Option<PathBuf>,
#[arg(long, requires = "preinit")]
no_build_inputs: bool,
#[arg(long, value_name = "CODE")]
verify_code: Option<String>,
#[arg(short, long)]
verbose: bool,
}
#[tokio::main]
async fn main() -> Result<()> {
if let Err(_already_set) = rustls::crypto::aws_lc_rs::default_provider().install_default() {
}
let cli = Cli::parse();
match cli.command {
Command::Setup(args) => run_setup(args).await,
Command::Compile(args) => run_compile(*args).await,
Command::Upgrade(args) => run_upgrade(args).await,
}
}
fn cache_dir() -> Result<PathBuf> {
let dir = if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
PathBuf::from(xdg).join("eryx")
} else {
let home = std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.context("Could not determine home directory (set HOME or XDG_CACHE_HOME)")?;
PathBuf::from(home).join(".cache").join("eryx")
};
Ok(dir)
}
fn platform_target() -> String {
let arch = std::env::consts::ARCH; let os = std::env::consts::OS; format!("{arch}-{os}")
}
async fn download_runtime_wasm(
client: &reqwest::Client,
version: &str,
expected_sha256: Option<&str>,
) -> Result<Vec<u8>> {
let tag_patterns = [
format!("eryx-v{version}"),
format!("eryx-precompile-v{version}"),
format!("v{version}"),
];
let mut last_error = None;
for tag in &tag_patterns {
let url = format!("https://github.com/eryx-org/eryx/releases/download/{tag}/runtime.wasm");
println!(" Trying {url}");
match client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => {
println!(" Found runtime.wasm in release {tag}");
let expected = match expected_sha256 {
Some(hex) => parse_sha256(hex)?,
None => fetch_sha256(client, &format!("{url}.sha256")).await?,
};
let bytes = read_capped(resp, MAX_RUNTIME_WASM_BYTES)
.await
.context("Failed to download runtime.wasm body")?;
verify_sha256(&bytes, &expected)?;
println!(" Verified SHA-256 {}", hex::encode(expected));
return Ok(bytes);
}
Ok(resp) => {
last_error = Some(anyhow::anyhow!("GET {url} returned HTTP {}", resp.status()));
}
Err(e) => {
last_error = Some(e.into());
}
}
}
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("No tag patterns to try"))).context(format!(
"Could not find runtime.wasm in any GitHub Release for version {version}.\n\
Tried tags: {}.\n\
Check https://github.com/eryx-org/eryx/releases for available versions.",
tag_patterns.join(", ")
))
}
async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> {
let resp = client
.get(url)
.send()
.await
.with_context(|| format!("Failed to fetch {url}"))?;
if !resp.status().is_success() {
anyhow::bail!(
"GET {url} returned HTTP {}. Releases before 0.12.0 don't publish a checksum; \
pass the expected hash with --sha256",
resp.status()
);
}
let body = read_capped(resp, MAX_CHECKSUM_BYTES)
.await
.with_context(|| format!("Failed to download {url}"))?;
parse_sha256(&String::from_utf8_lossy(&body))
.with_context(|| format!("Invalid checksum in {url}"))
}
async fn read_capped(mut resp: reqwest::Response, max: u64) -> Result<Vec<u8>> {
if let Some(len) = resp.content_length()
&& len > max
{
anyhow::bail!("response is {len} bytes, more than the {max} byte limit");
}
let mut body = Vec::new();
while let Some(chunk) = resp.chunk().await? {
if (body.len() + chunk.len()) as u64 > max {
anyhow::bail!("response is more than the {max} byte limit");
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
fn parse_sha256(text: &str) -> Result<[u8; 32]> {
let hex = text.split_whitespace().next().unwrap_or_default();
let mut hash = [0u8; 32];
hex::decode_to_slice(hex, &mut hash)
.with_context(|| format!("expected a 64-character hex SHA-256, got {hex:?}"))?;
Ok(hash)
}
fn verify_sha256(bytes: &[u8], expected: &[u8; 32]) -> Result<()> {
let actual: [u8; 32] = Sha256::digest(bytes).into();
if actual != *expected {
anyhow::bail!(
"SHA-256 mismatch: expected {}, got {}",
hex::encode(expected),
hex::encode(actual)
);
}
Ok(())
}
fn checksum_path(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(".sha256");
PathBuf::from(name)
}
fn cached_runtime_is_valid(path: &Path) -> bool {
let (Ok(bytes), Ok(checksum)) = (
std::fs::read(path),
std::fs::read_to_string(checksum_path(path)),
) else {
return false;
};
parse_sha256(&checksum).is_ok_and(|expected| verify_sha256(&bytes, &expected).is_ok())
}
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
let dir = path.parent().context("path has no parent directory")?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)
.with_context(|| format!("Failed to create a temp file in {}", dir.display()))?;
tmp.write_all(bytes)?;
tmp.as_file().sync_all()?;
tmp.persist(path)
.with_context(|| format!("Failed to write {}", path.display()))?;
Ok(())
}
fn write_cached_runtime(path: &Path, cwasm: &[u8]) -> Result<()> {
let checksum = checksum_path(path);
if let Err(e) = std::fs::remove_file(&checksum)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Err(e).with_context(|| format!("Failed to remove {}", checksum.display()));
}
write_atomic(path, cwasm)?;
let hash = hex::encode(Sha256::digest(cwasm));
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
write_atomic(&checksum, format!("{hash} {file_name}\n").as_bytes())
}
async fn run_setup(args: SetupArgs) -> Result<()> {
init_tracing(args.verbose);
let own_version = env!("CARGO_PKG_VERSION");
let version = args.version.unwrap_or_else(|| own_version.to_string());
if version != own_version {
anyhow::bail!(
"eryx-precompile {own_version} can only set up the runtime for eryx {own_version}, \
because a precompiled runtime only loads in the eryx version that built it. \
To set up {version}, install the matching binary: \
cargo binstall eryx-precompile@{version}"
);
}
let target = platform_target();
let cache = cache_dir()?;
let cwasm_name = format!("runtime-v{version}-{target}.cwasm");
let cwasm_path = cache.join(&cwasm_name);
println!("eryx-precompile setup");
println!("=====================");
println!();
println!("Version: {version}");
println!("Platform: {target}");
println!("Cache: {}", cache.display());
println!();
if std::fs::symlink_metadata(&cwasm_path)
.is_ok_and(|meta| meta.is_file() && eryx::cache::is_private(&meta))
&& cached_runtime_is_valid(&cwasm_path)
{
println!("Already cached: {}", cwasm_path.display());
println!();
println!(
"To force re-download, delete the file and run again:\n rm {}",
cwasm_path.display()
);
return Ok(());
}
println!("Step 1: Downloading runtime.wasm from GitHub Release...");
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::limited(10))
.user_agent(format!("eryx-precompile/{version}"))
.connect_timeout(Duration::from_secs(30))
.read_timeout(Duration::from_secs(60))
.build()
.context("Failed to create HTTP client")?;
let wasm_bytes = download_runtime_wasm(&client, &version, args.sha256.as_deref()).await?;
println!(
" Downloaded {} bytes ({:.1} MB)",
wasm_bytes.len(),
wasm_bytes.len() as f64 / 1_000_000.0
);
println!();
println!("Step 2: Pre-compiling to native code (this may take a minute)...");
let start = Instant::now();
let precompiled =
eryx::PythonExecutor::precompile_with_options(&wasm_bytes, None, CpuFeatureLevel::Native)
.context("Failed to pre-compile runtime.wasm to native code")?;
let elapsed = start.elapsed();
println!(
" Done in {elapsed:?} ({} bytes, {:.1} MB)",
precompiled.len(),
precompiled.len() as f64 / 1_000_000.0
);
println!();
println!("Step 3: Writing to cache...");
eryx::cache::ensure_private_dir(&cache)
.with_context(|| format!("Failed to create cache directory: {}", cache.display()))?;
write_cached_runtime(&cwasm_path, &precompiled)?;
println!(" Saved to: {}", cwasm_path.display());
println!();
println!(
"Setup complete! `cargo build` with `features = [\"embedded\"]` will now find the cached runtime."
);
println!();
println!(
"Tip: for cross-compilation or custom CPU targets, use `eryx-precompile compile` instead."
);
Ok(())
}
#[derive(serde::Deserialize)]
struct CallbackDeclarationFile {
name: String,
#[serde(default)]
description: String,
#[serde(default = "empty_object")]
parameters: serde_json::Value,
}
fn empty_object() -> serde_json::Value {
serde_json::Value::Object(serde_json::Map::new())
}
fn read_callback_declarations(path: &Path) -> Result<Vec<eryx::preinit::CallbackDeclaration>> {
let text = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read callbacks file: {}", path.display()))?;
let entries: Vec<CallbackDeclarationFile> = serde_json::from_str(&text)
.with_context(|| format!("Invalid callbacks file: {}", path.display()))?;
entries
.into_iter()
.map(|entry| {
Ok(eryx::preinit::CallbackDeclaration {
name: entry.name,
description: entry.description,
parameters_schema_json: serde_json::to_string(&entry.parameters)
.context("Failed to serialize callback parameters schema")?,
})
})
.collect()
}
async fn run_compile(args: CompileArgs) -> Result<()> {
init_tracing(args.verbose);
let output = args.output.unwrap_or_else(|| {
let mut out = args.input.clone();
if args.wasm_only {
out.set_extension("preinit.wasm");
} else {
out.set_extension("cwasm");
}
out
});
let (target_triple, cpu_features) =
resolve_target_and_features(args.target.as_deref(), args.cpu_features)?;
if !args.wasm_only
&& target_triple.is_none()
&& args.cpu_features.is_none()
&& cpu_features == CpuFeatureLevel::Native
{
eprintln!(
"warning: no --cpu-features given, compiling for this machine's CPU (native). \
The artifact may not load on other machines; pass --cpu-features \
(e.g. baseline or x86-64-v3) for a portable build."
);
}
println!("eryx-precompile");
println!("===============");
println!();
println!("Input: {}", args.input.display());
println!("Output: {}", output.display());
if !args.wasm_only {
if let Some(ref triple) = target_triple {
println!("Target: {triple}");
}
println!("CPU: {cpu_features}");
}
let stdlib = resolve_stdlib(args.stdlib.as_deref())?;
if args.preinit {
println!("Stdlib: {}", stdlib.display());
}
if let Some(ref site_pkg) = args.site_packages {
println!("Site-packages: {}", site_pkg.display());
}
if !args.packages.is_empty() {
println!(
"Packages: {}",
args.packages
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
);
}
if !args.imports.is_empty() {
println!("Imports: {}", args.imports.join(", "));
}
let setup_code = if let Some(code) = args.setup_code {
Some(code)
} else if let Some(ref path) = args.setup_file {
let code = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read setup file: {}", path.display()))?;
Some(code)
} else {
None
};
if setup_code.is_some() {
println!(
"Setup: {} (baked into snapshot)",
args.setup_file
.as_ref()
.map_or("inline code".to_string(), |p| p.display().to_string())
);
}
let callbacks = match &args.callbacks {
Some(path) => read_callback_declarations(path)?,
None => Vec::new(),
};
if !callbacks.is_empty() {
println!(
"Callbacks: {} (baked into snapshot)",
callbacks
.iter()
.map(|cb| cb.name.as_str())
.collect::<Vec<_>>()
.join(", ")
);
}
println!();
let wasm_bytes = std::fs::read(&args.input)
.with_context(|| format!("Failed to read input file: {}", args.input.display()))?;
println!(
"Input size: {} bytes ({:.1} MB)",
wasm_bytes.len(),
wasm_bytes.len() as f64 / 1_000_000.0
);
let build_inputs = eryx::bundle::BuildInputs::new()
.with_imports(args.imports.iter().cloned())
.with_setup_code(setup_code)
.with_callbacks(callbacks)
.with_target(target_triple.clone())
.with_cpu_features(Some(cpu_features));
let packages = if args.preinit {
Some(process_packages(
args.site_packages.as_ref(),
&args.packages,
)?)
} else {
None
};
let component_bytes = if let Some(packages) = &packages {
preinitialize(&stdlib, packages, &build_inputs).await?
} else {
println!();
println!("Step 1: Skipping pre-initialization (use --preinit to enable)");
wasm_bytes
};
if args.wasm_only {
println!();
println!("Step 2: Writing pre-initialized WASM...");
std::fs::write(&output, &component_bytes)
.with_context(|| format!("Failed to write output: {}", output.display()))?;
println!(
" Saved to: {} ({} bytes)",
output.display(),
component_bytes.len()
);
} else {
println!();
println!("Step 2: AOT compiling to native code...");
let start = Instant::now();
let precompiled = eryx::PythonExecutor::precompile_with_options(
&component_bytes,
target_triple.as_deref(),
cpu_features,
)
.context("Failed to AOT compile")?;
let elapsed = start.elapsed();
println!(
" Done in {elapsed:?} ({} bytes, {:.1} MB)",
precompiled.len(),
precompiled.len() as f64 / 1_000_000.0
);
println!();
println!("Step 3: Writing output...");
let bundle = match &packages {
Some(packages) if !args.no_build_inputs => Some(BundleContents {
site_packages: packages.site_packages.as_deref(),
build_inputs: build_inputs.to_json()?,
}),
_ => None,
};
write_precompiled(&output, precompiled, bundle.as_ref())?;
println!(" Saved to: {}", output.display());
if !args.no_verify {
println!();
if let Some(reason) = unrunnable_reason(target_triple.as_deref(), cpu_features) {
println!("Step 4: Skipping verification: {reason}");
} else {
println!("Step 4: Verifying...");
verify_cwasm(&output, &stdlib, &args.imports, args.verify_code.as_deref()).await?;
println!(" Verification passed!");
}
}
}
println!();
println!("Success!");
Ok(())
}
fn resolve_stdlib(stdlib: Option<&Path>) -> Result<PathBuf> {
let stdlib = match stdlib {
Some(path) => path.to_path_buf(),
None => eryx::embedded_stdlib::EmbeddedStdlib::get()
.context("Failed to extract the embedded Python stdlib")?
.path()
.to_path_buf(),
};
if !stdlib.join("encodings").exists() {
anyhow::bail!(
"Invalid Python stdlib at {}: expected 'encodings' subdirectory",
stdlib.display()
);
}
Ok(stdlib)
}
async fn preinitialize(
stdlib: &Path,
packages: &ProcessedPackages,
inputs: &eryx::bundle::BuildInputs,
) -> Result<Vec<u8>> {
if let Some(ref sp) = packages.site_packages {
println!("Site-packages dir: {}", sp.display());
}
if !packages.extensions.is_empty() {
println!("Native extensions: {}", packages.extensions.len());
}
println!();
println!("Step 1: Pre-initializing Python...");
let start = Instant::now();
let mut options = eryx::preinit::PreInitOptions::new(stdlib)
.imports(inputs.imports.iter().cloned())
.extensions(packages.extensions.clone())
.callbacks(inputs.callbacks.clone());
if let Some(path) = &packages.site_packages {
options = options.site_packages(path);
}
if let Some(code) = &inputs.setup_code {
options = options.setup_code(code.clone());
}
let preinit_bytes = eryx::preinit::pre_initialize_with_options(options)
.await
.context("Failed to pre-initialize Python")?;
let elapsed = start.elapsed();
println!(
" Done in {elapsed:?} ({} bytes, {:.1} MB)",
preinit_bytes.len(),
preinit_bytes.len() as f64 / 1_000_000.0
);
Ok(preinit_bytes)
}
struct BundleContents<'a> {
site_packages: Option<&'a Path>,
build_inputs: Vec<u8>,
}
fn write_precompiled(
path: &Path,
precompiled: Vec<u8>,
bundle: Option<&BundleContents<'_>>,
) -> Result<()> {
let write = || -> std::io::Result<()> {
let Some(bundle) = bundle else {
return std::fs::write(path, &precompiled);
};
let data_files = bundle
.site_packages
.map(eryx::bundle::collect_data_files)
.transpose()?
.unwrap_or_default();
let mut writer = std::io::BufWriter::new(std::fs::File::create(path)?);
eryx::bundle::write(
&eryx::PrecompiledArtifact::new(precompiled.clone()),
&data_files,
&bundle.build_inputs,
&mut writer,
)?;
writer.flush()
};
write().with_context(|| format!("Failed to write output: {}", path.display()))
}
async fn run_upgrade(args: UpgradeArgs) -> Result<()> {
init_tracing(args.verbose);
if args.output.exists()
&& std::fs::canonicalize(&args.output)? == std::fs::canonicalize(&args.input)?
{
anyhow::bail!(
"--output must differ from the input: processes running the old version \
may still have {} mapped, and keeping it lets you roll back",
args.input.display()
);
}
let read_err = || format!("Failed to read {}", args.input.display());
let mut file = std::fs::File::open(&args.input).with_context(read_err)?;
let layout = eryx::bundle::read_layout(&mut file).with_context(read_err)?;
let Some((data_files, build_inputs)) = layout
.sections()
.filter(|(_, build_inputs)| !build_inputs.is_empty())
else {
anyhow::bail!(
"{} doesn't store its build inputs, so it can't be rebuilt. Only output of \
`eryx-precompile compile --preinit` (without --no-build-inputs) and pyeryx \
factories from eryx 0.13.0 on store them: build it again with \
`eryx-precompile compile` instead",
args.input.display()
);
};
let data_files = read_range(&mut file, &data_files).with_context(read_err)?;
let build_inputs = read_range(&mut file, &build_inputs).with_context(read_err)?;
let inputs = eryx::bundle::BuildInputs::from_json(&build_inputs).with_context(read_err)?;
let target_triple = inputs.target.clone();
let cpu_features = inputs.cpu_features.unwrap_or(CpuFeatureLevel::Native);
println!("eryx-precompile upgrade");
println!("=======================");
println!();
println!("Input: {}", args.input.display());
println!("Output: {}", args.output.display());
println!("Version: {}", env!("CARGO_PKG_VERSION"));
println!("Target: {}", target_triple.as_deref().unwrap_or("host"));
println!("CPU: {}", cpu_features.as_str());
if !inputs.imports.is_empty() {
println!("Imports: {}", inputs.imports.join(", "));
}
let site_packages_dir =
tempfile::tempdir().context("Failed to create site-packages directory")?;
eryx::bundle::extract_data_files(&data_files, site_packages_dir.path())
.with_context(read_err)?;
let site_packages = (!data_files.is_empty()).then(|| site_packages_dir.path().to_path_buf());
let packages = process_packages(site_packages.as_ref(), &[])?;
let stdlib = resolve_stdlib(None)?;
let preinit_bytes = preinitialize(&stdlib, &packages, &inputs).await?;
println!();
println!("Step 2: AOT compiling to native code...");
let start = Instant::now();
let precompiled = eryx::PythonExecutor::precompile_with_options(
&preinit_bytes,
target_triple.as_deref(),
cpu_features,
)
.context("Failed to AOT compile")?;
println!(" Done in {:?}", start.elapsed());
println!();
println!("Step 3: Writing output...");
let bundle = BundleContents {
site_packages: packages.site_packages.as_deref(),
build_inputs,
};
write_precompiled(&args.output, precompiled, Some(&bundle))?;
println!(" Saved to: {}", args.output.display());
if !args.no_verify {
println!();
if let Some(reason) = unrunnable_reason(target_triple.as_deref(), cpu_features) {
println!("Step 4: Skipping verification: {reason}");
} else {
println!("Step 4: Verifying...");
verify_cwasm(&args.output, &stdlib, &inputs.imports, None).await?;
println!(" Verification passed!");
}
}
println!();
println!("Success!");
Ok(())
}
fn read_range(file: &mut std::fs::File, range: &std::ops::Range<u64>) -> std::io::Result<Vec<u8>> {
use std::io::{Read as _, Seek as _};
file.seek(std::io::SeekFrom::Start(range.start))?;
let mut bytes = Vec::new();
file.take(range.end - range.start).read_to_end(&mut bytes)?;
Ok(bytes)
}
fn init_tracing(verbose: bool) {
let filter = if verbose {
"eryx=debug,eryx_precompile=debug"
} else {
"eryx=warn,eryx_precompile=info"
};
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(false)
.init();
}
struct ProcessedPackages {
site_packages: Option<PathBuf>,
extensions: Vec<eryx::preinit::NativeExtension>,
_extracted_packages: Vec<eryx::ExtractedPackage>,
_merged_dir: Option<tempfile::TempDir>,
}
fn process_packages(
site_packages: Option<&PathBuf>,
packages: &[PathBuf],
) -> Result<ProcessedPackages> {
let mut extensions = Vec::new();
let mut extracted_packages = Vec::new();
let merged_dir = if usize::from(site_packages.is_some()) + packages.len() > 1 {
let dir = tempfile::tempdir().context("Failed to create merged site-packages directory")?;
if let Some(site_packages) = site_packages {
copy_directory_contents(site_packages, dir.path()).with_context(|| {
format!("Failed to copy site-packages: {}", site_packages.display())
})?;
}
Some(dir)
} else {
None
};
let mut final_site_packages = merged_dir
.as_ref()
.map(|dir| dir.path().to_path_buf())
.or_else(|| site_packages.cloned());
for path in packages {
println!("Extracting package: {}", path.display());
let package = eryx::ExtractedPackage::from_path(path)
.with_context(|| format!("Failed to extract package: {}", path.display()))?;
println!(
" {} (native extensions: {})",
package.name,
package.native_extensions.len()
);
match &merged_dir {
Some(dir) => copy_directory_contents(&package.python_path, dir.path())
.with_context(|| format!("Failed to merge package: {}", package.name))?,
None => final_site_packages = Some(package.python_path.clone()),
}
for ext in &package.native_extensions {
let dlopen_path = format!("/site-packages/{}", ext.relative_path);
extensions.push(eryx::preinit::NativeExtension::new(
dlopen_path,
ext.bytes.clone(),
));
}
extracted_packages.push(package);
}
if let Some(ref site_pkg_path) = final_site_packages
&& site_pkg_path.exists()
{
for entry in walkdir::WalkDir::new(site_pkg_path) {
let entry = entry.context("Failed to walk site-packages directory")?;
let path = entry.path();
if path.extension().is_some_and(|ext| ext == "so") {
let relative = path
.strip_prefix(site_pkg_path)
.context("Failed to compute relative path")?;
let relative_str = relative
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
let dlopen_path = format!("/site-packages/{relative_str}");
if extensions.iter().any(|e| e.name == dlopen_path) {
continue;
}
let bytes = std::fs::read(path).context("Failed to read native extension .so")?;
extensions.push(eryx::preinit::NativeExtension::new(dlopen_path, bytes));
}
}
}
Ok(ProcessedPackages {
site_packages: final_site_packages,
extensions,
_extracted_packages: extracted_packages,
_merged_dir: merged_dir,
})
}
fn copy_directory_contents(src: &std::path::Path, dst: &std::path::Path) -> Result<()> {
for entry in walkdir::WalkDir::new(src) {
let entry = entry.context("Failed to walk directory")?;
let src_path = entry.path();
let relative = src_path
.strip_prefix(src)
.context("Failed to compute relative path")?;
let dst_path = dst.join(relative);
if src_path.is_dir() {
std::fs::create_dir_all(&dst_path).context("Failed to create directory")?;
} else if src_path.is_file() {
if let Some(parent) = dst_path.parent() {
std::fs::create_dir_all(parent).context("Failed to create parent directory")?;
}
std::fs::copy(src_path, &dst_path).context("Failed to copy file")?;
}
}
Ok(())
}
fn resolve_target_and_features(
target: Option<&str>,
cpu_features: Option<CpuFeatureLevel>,
) -> Result<(Option<String>, CpuFeatureLevel)> {
match (target, cpu_features) {
(None, None) => Ok((None, CpuFeatureLevel::Native)),
(None, Some(level)) => Ok((None, level)),
(Some(t), None) => {
if let Some(level) = CpuFeatureLevel::parse(t) {
eprintln!(
"note: use --cpu-features {t} instead of --target {t} \
(--target is now for cross-compilation triples)"
);
Ok((None, level))
} else {
Ok((Some(t.to_string()), CpuFeatureLevel::Native))
}
}
(Some(t), Some(_)) if CpuFeatureLevel::parse(t).is_some() => {
anyhow::bail!(
"--target {t} looks like a CPU feature level, not a target triple. \
Use --cpu-features {t} instead, or pass a real triple to --target."
);
}
(Some(t), Some(level)) => Ok((Some(t.to_string()), level)),
}
}
fn unrunnable_reason(target: Option<&str>, cpu_features: CpuFeatureLevel) -> Option<String> {
if let Some(target) = target {
let host = env!("ERYX_PRECOMPILE_HOST_TARGET");
if target != host {
return Some(format!(
"artifact targets {target}, which cannot run on this host ({host})"
));
}
}
let missing = missing_host_features(cpu_features);
if missing.is_empty() {
None
} else {
Some(format!(
"this host lacks {} required by --cpu-features {cpu_features}",
missing.join(", ")
))
}
}
#[cfg(target_arch = "x86_64")]
fn missing_host_features(level: CpuFeatureLevel) -> Vec<&'static str> {
macro_rules! missing {
($($feature:tt),*) => {
[$((std::arch::is_x86_feature_detected!($feature), $feature)),*]
.into_iter()
.filter_map(|(present, name)| (!present).then_some(name))
.collect()
};
}
let mut missing: Vec<&'static str> = Vec::new();
if matches!(
level,
CpuFeatureLevel::X86_64v2 | CpuFeatureLevel::X86_64v3 | CpuFeatureLevel::X86_64v4
) {
missing.extend::<Vec<_>>(missing!(
"cmpxchg16b",
"popcnt",
"sse3",
"sse4.1",
"sse4.2",
"ssse3"
));
}
if matches!(level, CpuFeatureLevel::X86_64v3 | CpuFeatureLevel::X86_64v4) {
missing.extend::<Vec<_>>(missing!(
"avx", "avx2", "bmi1", "bmi2", "f16c", "fma", "lzcnt", "movbe"
));
}
if level == CpuFeatureLevel::X86_64v4 {
missing.extend::<Vec<_>>(missing!(
"avx512f", "avx512bw", "avx512cd", "avx512dq", "avx512vl"
));
}
missing
}
#[cfg(not(target_arch = "x86_64"))]
fn missing_host_features(_level: CpuFeatureLevel) -> Vec<&'static str> {
Vec::new()
}
async fn verify_cwasm(
cwasm_path: &Path,
stdlib_path: &Path,
imports: &[String],
verify_code: Option<&str>,
) -> Result<()> {
#[allow(unsafe_code)]
let sandbox = unsafe {
eryx::Sandbox::builder()
.with_precompiled_file(cwasm_path)
.with_python_stdlib(stdlib_path)
.build()
.context("Failed to create sandbox from compiled cwasm")?
};
let mut session = eryx::InProcessSession::new(&sandbox)
.await
.context("Failed to create session")?;
let result = session
.execute("print('eryx-precompile verification OK')")
.await
.context("Failed to execute test code")?;
let stdout = result.stdout_text();
if !stdout.contains("OK") {
anyhow::bail!("Verification failed: unexpected output: {}", stdout);
}
if !imports.is_empty() {
let import_code = imports
.iter()
.map(|m| format!("import {m}"))
.collect::<Vec<_>>()
.join("\n");
let verify_code = format!("{import_code}\nprint('imports OK')");
let result = session
.execute(&verify_code)
.await
.context("Failed to verify imports")?;
let stdout = result.stdout_text();
if !stdout.contains("imports OK") {
let error_detail = if result.stderr.is_empty() {
stdout
} else {
result.stderr_text()
};
anyhow::bail!(
"Import verification failed for [{}]: {}",
imports.join(", "),
error_detail
);
}
println!(" Imports verified: {}", imports.join(", "));
}
if let Some(code) = verify_code {
println!(" Running verify code...");
let result = session
.execute(code)
.await
.context("Failed to execute verify code")?;
if !result.stderr.is_empty() {
anyhow::bail!("Verify code produced stderr:\n{}", result.stderr_text());
}
if !result.stdout.is_empty() {
print!(" Output: {}", result.stdout_text());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
async fn serve_chunked_body(len: usize) -> Result<String> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let addr = listener.local_addr()?;
tokio::spawn(async move {
let (mut stream, _) = listener.accept().await?;
let mut request = [0u8; 1024];
let _ = stream.read(&mut request).await?;
let mut response = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec();
response.extend_from_slice(format!("{len:x}\r\n").as_bytes());
response.resize(response.len() + len, b'x');
response.extend_from_slice(b"\r\n0\r\n\r\n");
stream.write_all(&response).await?;
stream.shutdown().await
});
Ok(format!("http://{addr}/"))
}
#[tokio::test]
async fn download_size_limit_is_enforced() -> Result<()> {
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
let client = reqwest::Client::new();
let resp = client.get(serve_chunked_body(100).await?).send().await?;
assert_eq!(read_capped(resp, 100).await?.len(), 100);
let resp = client.get(serve_chunked_body(101).await?).send().await?;
assert!(read_capped(resp, 100).await.is_err());
Ok(())
}
#[test]
fn checksum_parsing_accepts_sha256sum_output() -> Result<()> {
let hex = "ab".repeat(32);
assert_eq!(parse_sha256(&hex)?, [0xab; 32]);
assert_eq!(parse_sha256(&format!("{hex} runtime.wasm\n"))?, [0xab; 32]);
assert!(parse_sha256(&hex[..62]).is_err());
assert!(parse_sha256("").is_err());
Ok(())
}
#[test]
fn checksum_mismatch_is_rejected() {
let expected: [u8; 32] = Sha256::digest(b"runtime").into();
assert!(verify_sha256(b"runtime", &expected).is_ok());
assert!(verify_sha256(b"runtim", &expected).is_err());
}
#[test]
fn cached_runtime_must_match_its_checksum() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("runtime.cwasm");
assert!(!cached_runtime_is_valid(&path));
write_cached_runtime(&path, b"compiled runtime")?;
assert!(cached_runtime_is_valid(&path));
std::fs::write(&path, b"compiled")?;
assert!(!cached_runtime_is_valid(&path));
write_cached_runtime(&path, b"compiled runtime")?;
std::fs::remove_file(checksum_path(&path))?;
assert!(!cached_runtime_is_valid(&path));
Ok(())
}
#[test]
fn package_flags_require_preinit() {
for flag in [
["--site-packages", "sp"],
["--package", "pkg.whl"],
["--import", "numpy"],
] {
let base = ["eryx-precompile", "compile", "runtime.wasm"];
assert!(Cli::try_parse_from(base.iter().chain(&flag)).is_err());
assert!(
Cli::try_parse_from(
base.iter()
.chain(&["--preinit", "--stdlib", "stdlib"])
.chain(&flag)
)
.is_ok()
);
}
}
#[test]
fn merging_packages_leaves_sources_untouched() -> Result<()> {
let site_packages = tempfile::tempdir()?;
std::fs::write(site_packages.path().join("a.py"), "")?;
let package = tempfile::tempdir()?;
std::fs::create_dir(package.path().join("b"))?;
std::fs::write(package.path().join("b").join("__init__.py"), "")?;
let packages = process_packages(
Some(&site_packages.path().to_path_buf()),
&[package.path().to_path_buf()],
)?;
let merged = packages
.site_packages
.as_ref()
.context("expected a site-packages dir")?;
assert_ne!(merged, site_packages.path());
assert!(merged.join("a.py").is_file());
assert!(merged.join("b").join("__init__.py").is_file());
assert!(!site_packages.path().join("b").exists());
Ok(())
}
#[test]
fn verification_skipped_for_foreign_target() {
assert!(
unrunnable_reason(
Some("riscv64gc-unknown-none-elf"),
CpuFeatureLevel::Baseline
)
.is_some()
);
assert!(unrunnable_reason(None, CpuFeatureLevel::Native).is_none());
assert!(
unrunnable_reason(
Some(env!("ERYX_PRECOMPILE_HOST_TARGET")),
CpuFeatureLevel::Baseline
)
.is_none()
);
}
}