use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use sha2::{Digest, Sha256};
pub fn main(args: &[String]) -> Result<(), String> {
if args.len() < 2 {
return Err("usage: flow-toolkit extract|serve tools.rs --module tools.rs [--prepare | --contract FILE]".into());
}
let action = &args[0];
let mut module = None;
let mut contract = None;
let mut declaration_hash = None;
let mut prepare = false;
let mut depfile = None;
let mut origins = None;
let mut project_root = None;
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
"--prepare" => prepare = true,
"--project-root" => {
i += 1;
project_root = Some(
fs::canonicalize(args.get(i).ok_or("--project-root needs a path")?)
.map_err(|error| error.to_string())?,
);
}
"--origins" => {
i += 1;
origins = Some(args.get(i).ok_or("--origins needs a path")?.clone());
}
"--module" => {
i += 1;
module = args.get(i).cloned();
}
"--declaration-hash" => {
i += 1;
declaration_hash = args.get(i).cloned();
}
"--depfile" => {
i += 1;
depfile = Some(args.get(i).ok_or("--depfile needs a path")?.clone());
}
"--contract" => {
i += 1;
contract = args.get(i).cloned();
}
_ => return Err(format!("unknown argument {}", args[i])),
}
i += 1;
}
let module = module.ok_or("--module FILE is required")?;
if !matches!(action.as_str(), "extract" | "serve")
|| (action == "serve"
&& (prepare || contract.is_none() || depfile.is_some() || origins.is_some()))
|| (action == "extract" && (contract.is_some() || declaration_hash.is_some()))
{
return Err("invalid function toolkit command".into());
}
let attempted = std::env::current_dir()
.map_err(|error| error.to_string())?
.join(&args[1]);
let selected = fs::canonicalize(&attempted)
.map_err(|error| format!("{}: {error}", attempted.display()))?;
let package = Package::for_source_in(&selected, project_root)?;
let cache = ensure_prepared(&package, &selected, prepare)?;
if action == "extract" {
if let Some(destination) = origins {
write_origins(&package, &selected, Path::new(&destination))?;
}
if let Some(depfile) = depfile {
write_depfile(&package, &cache, Path::new(&depfile))?;
}
print!(
"{}",
fs::read_to_string(cache.join("declarations.flow")).map_err(|e| e.to_string())?
);
return Ok(());
}
serve(&cache, contract.unwrap(), &module, declaration_hash)
}
#[derive(Debug)]
pub struct Exported {
pub declarations: PathBuf,
pub executable: PathBuf,
pub origins: PathBuf,
pub inputs: BTreeMap<PathBuf, String>,
pub build_inputs: BTreeMap<String, String>,
pub build_fingerprint: String,
}
pub fn export(source: &Path, destination: &Path) -> Result<Exported, String> {
if destination.exists() {
return Err(format!(
"export destination already exists: {}",
destination.display()
));
}
let selected = fs::canonicalize(source).map_err(|error| error.to_string())?;
let mut package = Package::for_source_in(&selected, None)?;
package.release = true;
package.inputs = Some(package.cache(&selected).join("inputs"));
let cache = ensure_prepared(&package, &selected, true)?;
#[cfg(unix)]
let _snapshot_lock = lock_preparation(&cache)?;
let mut inputs = PreparationInputs::default();
let build_fingerprint = fingerprint_inputs(&package, &mut inputs)?;
let cached_fingerprint =
fs::read_to_string(cache.join("fingerprint")).map_err(|error| error.to_string())?;
if cached_fingerprint.split('\n').next() != Some(build_fingerprint.as_str()) {
return Err("Rust tool inputs changed before export; run preparation again".into());
}
let build_inputs = inputs
.cargo_configurations
.into_iter()
.map(|(location, input)| {
let digest = hex_hash(&fs::read(input).map_err(|error| error.to_string())?);
Ok((location, digest))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
let inputs = inputs
.source_files
.into_iter()
.map(|input| {
let digest = hex_hash(&fs::read(&input).map_err(|error| error.to_string())?);
Ok((input, digest))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
let executable = prepared_executable(&cache)?;
fs::create_dir(destination).map_err(|error| error.to_string())?;
let declarations = destination.join("declarations.flow");
let copied_executable = destination.join("tools");
let origins = destination.join("origins.json");
let copied = (|| {
fs::copy(cache.join("declarations.flow"), &declarations)
.map_err(|error| error.to_string())?;
fs::copy(executable, &copied_executable).map_err(|error| error.to_string())?;
write_origins(&package, &selected, &origins)?;
if fingerprint(&package)? != build_fingerprint {
return Err("Rust tool inputs changed during export; run preparation again".into());
}
Ok(Exported {
declarations,
executable: copied_executable,
origins,
inputs,
build_inputs,
build_fingerprint,
})
})();
if copied.is_err() {
let _ = fs::remove_dir_all(destination);
}
copied
}
fn ensure_prepared(package: &Package, selected: &Path, prepare: bool) -> Result<PathBuf, String> {
let cache = package.cache(selected);
let cached = fs::read_to_string(cache.join("fingerprint")).ok();
let fresh = match (cached, prepared_executable(&cache).ok()) {
(Some(cached), Some(path)) => {
cached == format!("{}\n{}", fingerprint(package)?, path.display())
&& path.is_file()
&& cache.join("declarations.flow").is_file()
}
_ => false,
};
if !fresh {
if !prepare {
return Err(format!(
"Rust tools need preparation: run `flow prepare <source.rs>` ({} changed or has no prepared metadata)",
selected.display()
));
}
build(package, &cache, selected)?;
}
Ok(cache)
}
fn serve(
cache: &Path,
contract: String,
module: &str,
declaration_hash: Option<String>,
) -> Result<(), String> {
if let Some(expected) = declaration_hash {
let source =
fs::read(cache.join("declarations.flow")).map_err(|error| error.to_string())?;
let actual =
Sha256::digest(source)
.iter()
.fold(String::from("sha256:"), |mut text, byte| {
let _ = write!(text, "{byte:02x}");
text
});
if actual != expected {
return Err("Rust Tool declaration changed since program formation; prepare and check the program again".into());
}
}
let mut command = Command::new(prepared_executable(cache)?);
command
.arg("serve")
.arg(fs::canonicalize(contract).map_err(|error| error.to_string())?)
.arg(module)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
replace_process(&mut command)
}
#[cfg(unix)]
fn replace_process(command: &mut Command) -> Result<(), String> {
use std::os::unix::process::CommandExt as _;
Err(format!(
"Rust Tool launcher could not start: {}",
command.exec()
))
}
#[cfg(not(unix))]
fn replace_process(_command: &mut Command) -> Result<(), String> {
Err("Rust function-first serving requires process replacement, which is currently supported only on Unix".into())
}
struct Package {
root: PathBuf,
name: String,
library: PathBuf,
inputs: Option<PathBuf>,
project_root: Option<PathBuf>,
release: bool,
}
impl Package {
#[cfg(test)]
fn for_source(source: &Path) -> Result<Self, String> {
Self::for_source_in(source, None)
}
fn for_source_in(source: &Path, project_root: Option<PathBuf>) -> Result<Self, String> {
if source.extension().is_none_or(|extension| extension != "rs") {
return Err("Rust native imports select a .rs file, not Cargo.toml; import a public library module".into());
}
if project_root
.as_ref()
.is_some_and(|root| !source.starts_with(root))
{
return Err("Rust native source lies outside its project root".into());
}
let manifest = source
.ancestors()
.skip(1)
.take_while(|root| {
project_root
.as_ref()
.is_none_or(|cap| root.starts_with(cap))
})
.map(|root| root.join("Cargo.toml"))
.find(|path| path.is_file())
.ok_or("Rust source has no enclosing Cargo.toml; create a Cargo library package")?;
let mut package = Self::read(&manifest)?;
package.inputs = Some(package.cache(source).join("inputs"));
package.project_root = project_root;
Ok(package)
}
fn cache(&self, selected: &Path) -> PathBuf {
let key = Sha256::digest(selected.as_os_str().as_encoded_bytes())
.iter()
.fold(String::new(), |mut text, byte| {
let _ = write!(text, "{byte:02x}");
text
});
self.root.join("target/flow-toolkit").join(if self.release {
format!("{key}-release")
} else {
key
})
}
fn read(manifest: &Path) -> Result<Self, String> {
let root = fs::canonicalize(manifest.parent().ok_or("Cargo manifest needs a parent")?)
.map_err(|error| error.to_string())?;
let document = fs::read_to_string(manifest)
.map_err(|e| e.to_string())?
.parse::<toml::Table>()
.map_err(|e| e.to_string())?;
let name = document
.get("package")
.and_then(|p| p.get("name"))
.and_then(toml::Value::as_str)
.ok_or("Rust tools need a Cargo package with a library target")?
.to_owned();
let library = root.join(
document
.get("lib")
.and_then(|p| p.get("path"))
.and_then(toml::Value::as_str)
.unwrap_or("src/lib.rs"),
);
if !library.is_file() {
return Err(
"Rust tools need src/lib.rs or [lib].path, without a handwritten main".into(),
);
}
Ok(Self {
root,
name,
library,
inputs: None,
project_root: None,
release: false,
})
}
}
fn hash_bytes(hash: &mut Sha256, bytes: &[u8]) {
hash.update((bytes.len() as u64).to_le_bytes());
hash.update(bytes);
}
fn digest_tree(
path: &Path,
hash: &mut Sha256,
files: &mut BTreeSet<PathBuf>,
) -> Result<(), String> {
hash.update(b"directory");
let mut entries = fs::read_dir(path)
.map_err(|e| e.to_string())?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
entries.sort_by_key(std::fs::DirEntry::file_name);
for entry in entries {
let name = entry.file_name();
if matches!(
name.to_str(),
Some("target" | ".git" | ".flow" | "node_modules")
) {
continue;
}
let kind = entry.file_type().map_err(|e| e.to_string())?;
if kind.is_dir() {
hash_bytes(hash, name.as_encoded_bytes());
digest_tree(&entry.path(), hash, files)?;
} else if kind.is_file() {
files.insert(fs::canonicalize(entry.path()).map_err(|error| error.to_string())?);
hash.update(b"file");
hash_bytes(hash, name.as_encoded_bytes());
hash_bytes(hash, &fs::read(entry.path()).map_err(|e| e.to_string())?);
} else {
return Err(format!(
"Rust preparation cannot fingerprint symbolic or special input {}",
entry.path().display()
));
}
}
hash.update(b"end-directory");
Ok(())
}
#[derive(Default)]
struct PreparationInputs {
source_files: BTreeSet<PathBuf>,
cargo_configurations: BTreeMap<String, PathBuf>,
}
fn cargo_configurations(package: &Package) -> Result<BTreeMap<String, PathBuf>, String> {
let mut configurations = BTreeMap::new();
for (level, directory) in package.root.ancestors().enumerate() {
for name in ["config", "config.toml"] {
let file = directory.join(".cargo").join(name);
if file.is_file() {
configurations.insert(
format!("ancestor/{level}/{name}"),
fs::canonicalize(file).map_err(|error| error.to_string())?,
);
}
}
}
let cargo_home = std::env::var_os("CARGO_HOME")
.map(PathBuf::from)
.or_else(|| {
std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(|home| PathBuf::from(home).join(".cargo"))
});
if let Some(home) = cargo_home {
for name in ["config", "config.toml"] {
let file = home.join(name);
if file.is_file() {
configurations.insert(
format!("cargo_home/{name}"),
fs::canonicalize(file).map_err(|error| error.to_string())?,
);
}
}
}
Ok(configurations)
}
fn fingerprint(package: &Package) -> Result<String, String> {
fingerprint_inputs(package, &mut PreparationInputs::default())
}
fn fingerprint_inputs(package: &Package, inputs: &mut PreparationInputs) -> Result<String, String> {
let files = &mut inputs.source_files;
let mut hash = Sha256::new();
hash_bytes(&mut hash, if package.release { b"release" } else { b"dev" });
if let Some(cap) = &package.project_root {
hash_bytes(&mut hash, cap.as_os_str().as_encoded_bytes());
}
if let Some(inputs) = package
.inputs
.as_ref()
.and_then(|path| fs::read_to_string(path).ok())
{
for directory in inputs.lines() {
digest_tree(Path::new(directory), &mut hash, files)?;
}
}
digest_tree(&package.root, &mut hash, files)?;
for ancestor in package.root.ancestors().skip(1).take_while(|root| {
package
.project_root
.as_ref()
.is_none_or(|cap| root.starts_with(cap))
}) {
for name in ["Cargo.lock", "Cargo.toml", "rust-toolchain.toml"] {
let path = ancestor.join(name);
if path.is_file() {
files.insert(fs::canonicalize(&path).map_err(|error| error.to_string())?);
hash_bytes(&mut hash, path.as_os_str().as_encoded_bytes());
hash_bytes(&mut hash, &fs::read(path).map_err(|e| e.to_string())?);
}
}
}
digest_tree(
sdk_dir(package)?.as_path().join("src").as_path(),
&mut hash,
files,
)?;
inputs.cargo_configurations = cargo_configurations(package)?;
for (location, path) in &inputs.cargo_configurations {
files.remove(path);
hash_bytes(&mut hash, location.as_bytes());
hash_bytes(&mut hash, path.as_os_str().as_encoded_bytes());
hash_bytes(
&mut hash,
&fs::read(path).map_err(|error| error.to_string())?,
);
}
let mut env = std::env::vars_os()
.filter(|(k, _)| {
k.to_str().is_some_and(|s| {
s.starts_with("CARGO_")
|| s.starts_with("RUST")
|| s.starts_with("CC")
|| s.starts_with("CXX")
})
})
.collect::<Vec<_>>();
env.sort();
for (key, value) in env {
hash_bytes(&mut hash, key.as_encoded_bytes());
hash_bytes(&mut hash, value.as_encoded_bytes());
}
Ok(hash
.finalize()
.iter()
.fold(String::new(), |mut text, byte| {
let _ = write!(text, "{byte:02x}");
text
}))
}
fn write_depfile(package: &Package, cache: &Path, destination: &Path) -> Result<(), String> {
let mut inputs = PreparationInputs::default();
fingerprint_inputs(package, &mut inputs)?;
let mut files = inputs.source_files;
files.extend(inputs.cargo_configurations.into_values());
for name in [
"inputs",
"sdk",
"sdk-dependency",
"declarations.flow",
"fingerprint",
"executable",
] {
let path = cache.join(name);
if path.is_file() {
files.insert(fs::canonicalize(path).map_err(|error| error.to_string())?);
}
}
let files = files
.into_iter()
.map(|path| {
path.to_str()
.map(|path| crate::Json::String(path.into()))
.ok_or("Rust input dependency paths must be UTF-8")
})
.collect::<Result<Vec<_>, _>>()?;
fs::write(destination, crate::Json::Array(files).canonical())
.map_err(|error| format!("{}: {error}", destination.display()))
}
fn sdk_dir(package: &Package) -> Result<PathBuf, String> {
if let Some(path) = std::env::var_os("FLOW_RUST_SDK") {
let path = PathBuf::from(path);
if path.join("Cargo.toml").is_file() {
let source =
fs::metadata(path.join("src/lib.rs")).map_err(|error| error.to_string())?;
if !source.is_file() {
return Err("FLOW_RUST_SDK must contain the Rust toolkit's src/lib.rs".into());
}
return fs::canonicalize(path).map_err(|error| error.to_string());
}
return Err("FLOW_RUST_SDK must name the installed Rust toolkit directory".into());
}
if let Some(inputs) = &package.inputs {
let selected = inputs.with_file_name("sdk");
if selected.is_file() {
let root = fs::read_to_string(&selected).map_err(|error| error.to_string())?;
return fs::canonicalize(root).map_err(|error| error.to_string());
}
}
let executable = std::env::current_exe().map_err(|error| error.to_string())?;
for parent in executable.ancestors().skip(1) {
let path = parent.join("toolkits/rust");
if path.join("Cargo.toml").is_file() {
return Ok(path);
}
}
Err("Rust toolkit sources are unavailable; reinstall the complete Flow toolkit or set FLOW_RUST_SDK".into())
}
fn sdk_dependency(package: &Package) -> Result<String, String> {
if std::env::var_os("FLOW_RUST_SDK").is_none()
&& let Some(inputs) = &package.inputs
{
let path = inputs.with_file_name("sdk-dependency");
if path.is_file() {
return fs::read_to_string(path).map_err(|error| error.to_string());
}
}
Ok(format!(
"{{ path = {} }}",
literal(&sdk_dir(package)?.to_string_lossy())
))
}
fn toolkit_dependency(package: &crate::Json, root: &Path) -> Result<String, String> {
let version = metadata_text(package, "version")?;
match package.get("source") {
Some(crate::Json::Null) => Ok(format!("{{ path = {} }}", literal(&root.to_string_lossy()))),
Some(crate::Json::String(source)) => {
if let Some(index) = source.strip_prefix("registry+") {
return Ok(format!(
"{{ version = {}, registry-index = {} }}",
literal(&format!("={version}")),
literal(index)
));
}
if let Some(source) = source.strip_prefix("git+") {
let (source, _) = source
.rsplit_once('#')
.ok_or("Cargo Git source has no commit identity")?;
let (url, reference) = source
.split_once('?')
.map_or((source, None), |(url, query)| (url, Some(query)));
let mut dependency = format!("{{ git = {}", literal(url));
if let Some(reference) = reference {
let (kind, value) = reference
.split_once('=')
.ok_or("Cargo Git source has no reference value")?;
if !matches!(kind, "branch" | "tag" | "rev") {
return Err("Cargo Git reference kind is unsupported".into());
}
let _ = write!(dependency, ", {kind} = {}", literal(value));
}
dependency.push_str(" }");
return Ok(dependency);
}
Err(format!("Cargo toolkit source is unsupported: {source}"))
}
_ => Err("Cargo toolkit source is missing".into()),
}
}
fn literal(value: &str) -> String {
format!("{value:?}")
}
#[derive(Default)]
struct Exports {
selected: Option<PathBuf>,
found: bool,
origins: Vec<crate::Json>,
functions: Vec<String>,
lifecycle: Option<String>,
}
fn collect(file: &Path, module: &str, exports: &mut Exports) -> Result<(), String> {
let source = fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
if exports
.selected
.as_deref()
.is_some_and(|selected| selected == file)
{
exports.found = true;
}
let syntax = syn::parse_file(&source).map_err(|e| format!("{}: {e}", file.display()))?;
collect_items(&syntax.items, file, module, exports, file)
}
fn collect_items(
items: &[syn::Item],
file: &Path,
module: &str,
exports: &mut Exports,
source_file: &Path,
) -> Result<(), String> {
for item in items {
match item {
syn::Item::Fn(function)
if function
.attrs
.iter()
.any(|a| a.path().segments.last().is_some_and(|s| s.ident == "tool")) =>
{
if function
.attrs
.iter()
.any(|a| a.path().is_ident("cfg") || a.path().is_ident("cfg_attr"))
{
return Err("conditional #[tool] exports are unsupported; use an unconditional public tool function".into());
}
if exports
.selected
.as_deref()
.is_none_or(|selected| selected == source_file)
{
exports
.origins
.push(function_origin(source_file, &function.sig.ident)?);
exports.functions.push(format!(
"tool_impl::{module}__flow_tool_{}()",
function.sig.ident.to_string().trim_start_matches("r#")
));
}
}
syn::Item::Fn(function)
if function.attrs.iter().any(|a| {
a.path()
.segments
.last()
.is_some_and(|s| s.ident == "lifecycle")
}) =>
{
if function
.attrs
.iter()
.any(|a| a.path().is_ident("cfg") || a.path().is_ident("cfg_attr"))
{
return Err("conditional #[lifecycle] exports are unsupported".into());
}
let factory = format!("tool_impl::{module}__flow_lifecycle_{}", function.sig.ident);
if exports.lifecycle.replace(factory).is_some() {
return Err(
"a Rust tool package may export at most one #[lifecycle] initializer"
.into(),
);
}
}
syn::Item::Mod(item) => {
if !matches!(item.vis, syn::Visibility::Public(_)) {
continue;
}
if item.attrs.iter().any(|a| {
a.path().is_ident("cfg")
|| a.path().is_ident("cfg_attr")
|| a.path().is_ident("path")
}) {
return Err(
"conditional or #[path] exported tool modules are unsupported".into(),
);
}
let nested = format!("{module}{}::", item.ident);
let directory = if module.is_empty()
|| file
.file_name()
.is_some_and(|n| n == "lib.rs" || n == "mod.rs")
{
file.parent().unwrap().to_owned()
} else {
file.with_extension("")
};
if let Some((_, items)) = &item.content {
collect_items(
items,
&directory.join(item.ident.to_string()).join("mod.rs"),
&nested,
exports,
source_file,
)?;
} else {
let first = directory.join(format!("{}.rs", item.ident));
let second = directory.join(item.ident.to_string()).join("mod.rs");
collect(
if first.is_file() { &first } else { &second },
&nested,
exports,
)?;
}
}
_ => {}
}
}
Ok(())
}
fn function_origin(source_file: &Path, identifier: &syn::Ident) -> Result<crate::Json, String> {
let source = fs::read(source_file).map_err(|error| error.to_string())?;
let mut range = identifier.span().byte_range();
if identifier.to_string().starts_with("r#") {
range.start += 2;
}
Ok(crate::Json::Object(vec![
(
"name".into(),
crate::Json::String(identifier.to_string().trim_start_matches("r#").to_owned()),
),
(
"source".into(),
crate::Json::String(source_file.to_string_lossy().into_owned()),
),
("sha256".into(), crate::Json::String(hex_hash(&source))),
(
"start".into(),
crate::Json::Number(flow_value::Decimal::parse(&range.start.to_string()).unwrap()),
),
(
"end".into(),
crate::Json::Number(flow_value::Decimal::parse(&range.end.to_string()).unwrap()),
),
]))
}
fn selected_exports(package: &Package, selected: &Path) -> Result<Exports, String> {
let mut exports = Exports {
selected: Some(fs::canonicalize(selected).map_err(|error| error.to_string())?),
..Exports::default()
};
collect(
&fs::canonicalize(&package.library).map_err(|error| error.to_string())?,
"",
&mut exports,
)?;
if !exports.found {
return Err("Rust native source is not a member of the public Cargo library module tree; declare it with pub mod in the library".into());
}
Ok(exports)
}
fn hex_hash(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.fold(String::new(), |mut text, byte| {
let _ = write!(text, "{byte:02x}");
text
})
}
fn write_origins(package: &Package, selected: &Path, destination: &Path) -> Result<(), String> {
let exports = selected_exports(package, selected)?;
let report = crate::Json::Object(vec![
(
"source".into(),
crate::Json::String(selected.to_string_lossy().into_owned()),
),
(
"sha256".into(),
crate::Json::String(hex_hash(
&fs::read(selected).map_err(|error| error.to_string())?,
)),
),
("functions".into(), crate::Json::Array(exports.origins)),
]);
fs::write(destination, report.canonical()).map_err(|error| error.to_string())
}
#[cfg(unix)]
fn lock_preparation(cache: &Path) -> Result<fs::File, String> {
let lock = fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(cache.join("prepare.lock"))
.map_err(|error| error.to_string())?;
rustix::fs::flock(&lock, rustix::fs::FlockOperation::NonBlockingLockExclusive)
.map_err(|error| format!("Rust tools are already being prepared; retry after that preparation finishes: {error}"))?;
Ok(lock)
}
fn build(package: &Package, cache: &Path, selected: &Path) -> Result<(), String> {
let exports = selected_exports(package, selected)?;
if exports.functions.is_empty() {
return Err("no public #[tool] functions found in the Rust library".into());
}
fs::create_dir_all(cache.join("src")).map_err(|e| e.to_string())?;
#[cfg(unix)]
let _preparation_lock = lock_preparation(cache)?;
let profiles = prepare_native_resolution(package, cache)?;
let manifest = format!(
"[package]\nname = \"flow-function-launcher\"\nversion = \"0.0.0\"\nedition = \"2024\"\n[workspace]\n[dependencies]\ntool_impl = {{ package = {}, path = {} }}\nflow-toolkit = {}\n",
literal(&package.name),
literal(&package.root.to_string_lossy()),
sdk_dependency(package)?
);
fs::write(cache.join("Cargo.toml"), manifest + &profiles).map_err(|e| e.to_string())?;
let source = format!(
"fn main() {{ if let Err(error) = flow_toolkit::__bridge::run(&[{}],{}) {{ eprintln!(\"{{error}}\"); std::process::exit(2); }} }}",
exports.functions.join(","),
exports
.lifecycle
.map_or_else(|| "None".into(), |factory| format!("Some({factory})"))
);
fs::write(cache.join("src/main.rs"), source).map_err(|e| e.to_string())?;
let before = fingerprint(package)?;
let _ = fs::remove_file(cache.join("fingerprint"));
let executable = compile_executable(package, cache)?;
let descriptor = Command::new(&executable)
.arg("extract")
.output()
.map_err(|error| format!("Rust metadata launcher {} cannot execute on this host; select a native Cargo build target: {error}",executable.display()))?;
if !descriptor.status.success() {
return Err(format!(
"Rust metadata extraction failed: {}",
String::from_utf8_lossy(&descriptor.stderr)
));
}
let after = fingerprint(package)?;
if before != after {
return Err("Rust tool inputs changed during preparation; run preparation again".into());
}
fs::write(cache.join("declarations.flow"), descriptor.stdout).map_err(|e| e.to_string())?;
fs::write(
cache.join("executable"),
executable
.to_str()
.ok_or("Rust launcher path must be UTF-8")?,
)
.map_err(|error| error.to_string())?;
fs::write(
cache.join("fingerprint"),
format!("{after}\n{}", executable.display()),
)
.map_err(|e| e.to_string())?;
Ok(())
}
fn compilation_target(
package: &Package,
cache: &Path,
cargo_target: Option<&std::ffi::OsStr>,
) -> PathBuf {
if !package.release {
return cache.join("target");
}
#[cfg(unix)]
{
let shared = || -> Option<PathBuf> {
let target = Path::new(cargo_target.filter(|target| !target.is_empty())?);
let target = package.root.join(target).canonicalize().ok()?;
if !target.is_dir() {
return None;
}
let target = target.join("flow-package-launchers");
let target = match fs::symlink_metadata(&target) {
Ok(metadata) if metadata.is_dir() || metadata.file_type().is_symlink() => {
let target = target.canonicalize().ok()?;
if !target.is_dir() {
return None;
}
target
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => target,
_ => return None,
};
let inventory = fs::read_to_string(package.inputs.as_ref()?).ok()?;
let mut roots = inventory
.lines()
.map(|root| {
let root = Path::new(root);
root.is_absolute()
.then(|| root.canonicalize().ok())
.flatten()
})
.collect::<Option<Vec<_>>>()?;
if roots.is_empty() || roots.iter().any(|root| !root.is_dir()) {
return None;
}
roots.push(package.root.clone());
roots.push(sdk_dir(package).ok()?.canonicalize().ok()?);
roots
.iter()
.all(|root| !target.starts_with(root) && !root.starts_with(&target))
.then_some(target)
};
if let Some(target) = shared() {
return target;
}
}
#[cfg(not(unix))]
let _ = cargo_target;
cache.parent().unwrap_or(cache).join("package-launchers")
}
fn compile_executable(package: &Package, cache: &Path) -> Result<PathBuf, String> {
let target = compilation_target(
package,
cache,
std::env::var_os("CARGO_TARGET_DIR").as_deref(),
);
fs::create_dir_all(&target).map_err(|error| error.to_string())?;
#[cfg(unix)]
let _release_lock = if package.release {
let lock = fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(target.join("export.lock"))
.map_err(|error| error.to_string())?;
rustix::fs::flock(&lock, rustix::fs::FlockOperation::LockExclusive)
.map_err(|error| error.to_string())?;
Some(lock)
} else {
None
};
let mut command = Command::new("cargo");
command
.args(["build", "--message-format=json-render-diagnostics"])
.current_dir(&package.root)
.arg("--manifest-path")
.arg(cache.join("Cargo.toml"))
.arg("--target-dir")
.arg(target)
.stderr(Stdio::inherit());
if package.release {
command.arg("--release");
}
let output = command.output().map_err(|error| error.to_string())?;
let artifact = compiler_executable(&output.stdout);
if !output.status.success() {
return Err(format!(
"Rust tool compilation failed with {}",
output.status
));
}
if package.release {
let executable = cache.join("exported-tools");
fs::copy(artifact?, &executable).map_err(|error| error.to_string())?;
Ok(executable)
} else {
artifact
}
}
fn prepared_executable(cache: &Path) -> Result<PathBuf, String> {
let path = fs::read_to_string(cache.join("executable")).map_err(|error| {
format!("Rust tools need preparation: missing executable artifact: {error}")
})?;
let path = PathBuf::from(path);
if !path.is_absolute() {
return Err("Rust launcher artifact path must be absolute".into());
}
Ok(path)
}
fn compiler_executable(messages: &[u8]) -> Result<PathBuf, String> {
let messages = std::str::from_utf8(messages).map_err(|error| error.to_string())?;
let mut executable = None;
for line in messages.lines() {
let message = flow_abi::parse(line, &crate::data::LIMITS)
.map_err(|error| format!("invalid Cargo build message: {error}"))?;
if matches!(message.get("reason"),Some(crate::Json::String(reason)) if reason=="compiler-message")
&& let Some(crate::Json::String(rendered)) = message
.get("message")
.and_then(|message| message.get("rendered"))
{
eprint!("{rendered}");
}
if matches!(message.get("reason"),Some(crate::Json::String(reason)) if reason=="compiler-artifact")
&& matches!(message.get("target").and_then(|target|target.get("name")),Some(crate::Json::String(name)) if name=="flow-function-launcher")
&& let Some(crate::Json::String(path)) = message.get("executable")
{
if executable.is_some() {
return Err("Cargo reported multiple launcher artifacts".into());
}
executable = Some(PathBuf::from(path));
}
}
executable.ok_or_else(|| {
"Cargo did not report a native launcher executable; check its build target and profile"
.into()
})
}
fn metadata_text<'a>(value: &'a crate::Json, key: &str) -> Result<&'a str, String> {
match value.get(key) {
Some(crate::Json::String(text)) => Ok(text),
_ => Err(format!("Cargo metadata needs {key}")),
}
}
fn metadata_index(rows: &[crate::Json]) -> Result<BTreeMap<&str, &crate::Json>, String> {
let mut index = BTreeMap::new();
for row in rows {
let id = metadata_text(row, "id")?;
if index.insert(id, row).is_some() {
return Err(format!("duplicate Cargo metadata package ID: {id}"));
}
}
Ok(index)
}
fn local_dependency_roots(
metadata: &crate::Json,
manifest: &Path,
) -> Result<BTreeSet<PathBuf>, String> {
let Some(crate::Json::Array(packages)) = metadata.get("packages") else {
return Err("Cargo metadata has no packages".into());
};
let Some(crate::Json::Array(nodes)) = metadata
.get("resolve")
.and_then(|resolve| resolve.get("nodes"))
else {
return Err("Cargo metadata has no resolved dependency graph".into());
};
let packages = metadata_index(packages)?;
let nodes = metadata_index(nodes)?;
let selected = fs::canonicalize(manifest).map_err(|error| error.to_string())?;
let selected = packages
.iter()
.find_map(|(id, package)| {
let path = metadata_text(package, "manifest_path").ok()?;
(fs::canonicalize(path).ok().as_ref() == Some(&selected)).then_some(*id)
})
.ok_or("Cargo metadata does not contain the selected native package")?;
let mut pending = vec![selected];
let mut visited = BTreeSet::new();
let mut roots = BTreeSet::new();
while let Some(id) = pending.pop() {
if !visited.insert(id) {
continue;
}
let package = packages
.get(id)
.ok_or_else(|| format!("Cargo dependency package is missing: {id}"))?;
if matches!(package.get("source"), Some(crate::Json::Null)) {
let manifest = Path::new(metadata_text(package, "manifest_path")?);
let root = manifest
.parent()
.ok_or("Cargo package manifest has no parent")?;
roots.insert(fs::canonicalize(root).map_err(|error| error.to_string())?);
}
let node = nodes
.get(id)
.ok_or_else(|| format!("Cargo dependency node is missing: {id}"))?;
let Some(crate::Json::Array(dependencies)) = node.get("deps") else {
return Err(format!("Cargo dependency node has no deps: {id}"));
};
for dependency in dependencies {
let Some(crate::Json::Array(kinds)) = dependency.get("dep_kinds") else {
return Err("Cargo dependency has no kind information".into());
};
let mut used = false;
for kind in kinds {
match kind.get("kind") {
Some(crate::Json::Null) => used = true,
Some(crate::Json::String(kind)) if kind == "build" => used = true,
Some(crate::Json::String(kind)) if kind == "dev" => {}
_ => return Err("Cargo dependency kind is unsupported".into()),
}
}
if used {
pending.push(metadata_text(dependency, "pkg")?);
}
}
}
Ok(roots)
}
fn resolved_toolkit(
metadata: &crate::Json,
manifest: &Path,
) -> Result<Option<(PathBuf, String)>, String> {
let Some(crate::Json::Array(packages)) = metadata.get("packages") else {
return Err("Cargo metadata has no packages".into());
};
let Some(crate::Json::Array(nodes)) =
metadata.get("resolve").and_then(|value| value.get("nodes"))
else {
return Err("Cargo metadata has no resolved dependency graph".into());
};
let packages = metadata_index(packages)?;
let selected = fs::canonicalize(manifest).map_err(|error| error.to_string())?;
let selected = packages
.iter()
.find_map(|(id, package)| {
let path = metadata_text(package, "manifest_path").ok()?;
(fs::canonicalize(path).ok().as_ref() == Some(&selected)).then_some(*id)
})
.ok_or("Cargo metadata does not contain the selected native package")?;
let nodes = metadata_index(nodes)?;
let node = nodes
.get(selected)
.ok_or("selected Cargo dependency node is missing")?;
let Some(crate::Json::Array(dependencies)) = node.get("deps") else {
return Err("selected Cargo dependency node has no deps".into());
};
let mut roots = BTreeSet::new();
for dependency in dependencies {
let id = metadata_text(dependency, "pkg")?;
let resolved = packages
.get(id)
.ok_or("Cargo dependency package is missing")?;
if metadata_text(resolved, "name")? == "flow-toolkit" {
let manifest = Path::new(metadata_text(resolved, "manifest_path")?);
let root = manifest.parent().ok_or("toolkit manifest has no parent")?;
let root = fs::canonicalize(root).map_err(|error| error.to_string())?;
let dependency = toolkit_dependency(resolved, &root)?;
roots.insert((root, dependency));
}
}
if roots.len() > 1 {
return Err("native package resolves multiple Flow toolkit identities".into());
}
Ok(roots.into_iter().next())
}
fn prepare_native_resolution(package: &Package, cache: &Path) -> Result<String, String> {
let metadata = Command::new("cargo")
.args(["metadata", "--format-version", "1", "--manifest-path"])
.arg(package.root.join("Cargo.toml"))
.current_dir(&package.root)
.output()
.map_err(|error| error.to_string())?;
if !metadata.status.success() {
return Err(format!(
"Cargo metadata failed: {}",
String::from_utf8_lossy(&metadata.stderr)
));
}
let metadata = flow_abi::parse(
std::str::from_utf8(&metadata.stdout).map_err(|error| error.to_string())?,
&crate::data::LIMITS,
)
.map_err(|error| error.to_string())?;
if let Some((root, dependency)) = resolved_toolkit(&metadata, &package.root.join("Cargo.toml"))?
{
fs::write(cache.join("sdk"), root.to_string_lossy().as_bytes())
.map_err(|error| error.to_string())?;
fs::write(cache.join("sdk-dependency"), dependency).map_err(|error| error.to_string())?;
} else {
let _ = fs::remove_file(cache.join("sdk"));
let _ = fs::remove_file(cache.join("sdk-dependency"));
}
let mut roots = Vec::new();
for root in local_dependency_roots(&metadata, &package.root.join("Cargo.toml"))? {
let root = root.to_str().ok_or("Cargo package path must be UTF-8")?;
if root.contains('\n') {
return Err("Cargo package path contains a newline".into());
}
roots.push(root.to_owned());
}
fs::write(cache.join("inputs"), roots.join("\n")).map_err(|error| error.to_string())?;
let mut profiles = String::new();
if let Some(crate::Json::String(workspace)) = metadata.get("workspace_root") {
let workspace = fs::canonicalize(workspace).map_err(|error| error.to_string())?;
if package
.project_root
.as_ref()
.is_some_and(|cap| !workspace.starts_with(cap))
{
return Err("Cargo workspace lies outside the native project root; declare an independent [workspace] in the imported Cargo package".into());
}
let workspace_manifest = fs::read_to_string(workspace.join("Cargo.toml"))
.map_err(|error| error.to_string())?
.parse::<toml::Table>()
.map_err(|error| error.to_string())?;
if let Some(profile) = workspace_manifest.get("profile") {
let mut config = toml::Table::new();
config.insert("profile".into(), profile.clone());
profiles = toml::to_string(&config).map_err(|error| error.to_string())?;
}
}
if let Some(lock) = package
.root
.ancestors()
.take_while(|root| {
package
.project_root
.as_ref()
.is_none_or(|cap| root.starts_with(cap))
})
.map(|root| root.join("Cargo.lock"))
.find(|path| path.is_file())
{
fs::copy(lock, cache.join("Cargo.lock")).map_err(|error| error.to_string())?;
}
Ok(profiles)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
#[test]
fn cargo_workspace_profiles_and_lockfile_are_preserved_in_native_resolution() {
let (files, package) = fixture();
fs::write(
files.join("Cargo.toml"),
concat!(
"[package]\nname=\"fixture\"\nversion=\"0.0.0\"\n",
"[workspace]\n[profile.dev]\nopt-level=1\ndebug=false\n",
"[profile.release]\noverflow-checks=true\n"
),
)
.unwrap();
let cache = files.join("resolution");
fs::create_dir(&cache).unwrap();
fs::write(
cache.join("Cargo.toml"),
"[package]\nname=\"launcher\"\nversion=\"0.0.0\"\n",
)
.unwrap();
let profiles = prepare_native_resolution(&package, &cache).unwrap();
let manifest = profiles.parse::<toml::Table>().unwrap();
let profiles = manifest["profile"].as_table().unwrap();
assert_eq!(profiles["dev"]["opt-level"].as_integer(), Some(1));
assert_eq!(profiles["dev"]["debug"].as_bool(), Some(false));
assert_eq!(profiles["release"]["overflow-checks"].as_bool(), Some(true));
assert_eq!(
fs::read(cache.join("Cargo.lock")).unwrap(),
fs::read(files.join("Cargo.lock")).unwrap()
);
assert_eq!(
fs::read_to_string(cache.join("inputs")).unwrap(),
fs::canonicalize(files.path()).unwrap().to_str().unwrap()
);
}
#[test]
fn direct_selection_separates_siblings_lifecycle_and_utf8_origins() {
let (files, package) = fixture();
fs::write(
&package.library,
"pub mod left; pub mod right; #[lifecycle] pub fn resources() {} ",
)
.unwrap();
let left = files.path().join("src/left.rs");
let right = files.path().join("src/right.rs");
let source = "// café 🌊\n#[tool] pub fn r#answer() {}\npub mod nested { #[tool] pub fn inside() {} }\n";
fs::write(&left, source).unwrap();
fs::write(&right, "#[tool] pub fn other() {}").unwrap();
let left = fs::canonicalize(left).unwrap();
let right = fs::canonicalize(right).unwrap();
let exports = selected_exports(&package, &left).unwrap();
assert_eq!(
exports.functions,
[
"tool_impl::left::__flow_tool_answer()",
"tool_impl::left::nested::__flow_tool_inside()"
]
);
assert_eq!(
exports.lifecycle.as_deref(),
Some("tool_impl::__flow_lifecycle_resources")
);
assert_eq!(
selected_exports(&package, &right).unwrap().functions,
["tool_impl::right::__flow_tool_other()"]
);
assert_ne!(package.cache(&left), package.cache(&right));
let report = files.path().join("origins.json");
write_origins(&package, &left, &report).unwrap();
let report = crate::parse_json(&fs::read_to_string(report).unwrap()).unwrap();
let crate::Json::Array(functions) = report.get("functions").unwrap() else {
panic!("origins array")
};
assert_eq!(
functions[0].get("name"),
Some(&crate::Json::String("answer".into()))
);
let offset = source.find("answer").unwrap();
assert_eq!(
functions[0].get("start"),
Some(&crate::Json::Number(
flow_value::Decimal::parse(&offset.to_string()).unwrap()
))
);
assert_eq!(
functions[0].get("end"),
Some(&crate::Json::Number(
flow_value::Decimal::parse(&(offset + 6).to_string()).unwrap()
))
);
let outsider = files.path().join("src/outsider.rs");
fs::write(&outsider, "#[tool] pub fn outsider() {}").unwrap();
assert!(
selected_exports(&package, &outsider)
.err()
.unwrap()
.contains("public Cargo library")
);
fs::write(&right, "pub fn plain() {}").unwrap();
assert_eq!(
selected_exports(&package, &right).unwrap().functions,
[] as [std::string::String; 0]
);
}
#[test]
fn native_source_context_refuses_manifest_authoring_and_explains_missing_cargo_library() {
let files = flow_testing::TempDir::new("rust-native-context").unwrap();
let source = files.path().join("tools.rs");
fs::write(&source, "#[tool] pub fn echo() {}").unwrap();
assert!(
Package::for_source(&source)
.err()
.unwrap()
.contains("enclosing Cargo.toml")
);
let nested = files.path().join("nested");
fs::create_dir(&nested).unwrap();
let nested_source = nested.join("tools.rs");
fs::write(&nested_source, "").unwrap();
let manifest = files.path().join("Cargo.toml");
fs::write(&manifest, "[workspace]\n").unwrap();
assert!(
Package::for_source(&manifest)
.err()
.unwrap()
.contains(".rs file")
);
assert!(
Package::for_source(&source)
.err()
.unwrap()
.contains("Cargo package with a library")
);
fs::write(
&manifest,
"[package]\nname=\"native-context\"\nversion=\"0.0.0\"\n",
)
.unwrap();
assert!(
Package::for_source(&source)
.err()
.unwrap()
.contains("src/lib.rs or [lib].path")
);
assert!(
Package::for_source_in(&nested_source, Some(nested))
.err()
.unwrap()
.contains("enclosing Cargo.toml")
);
assert!(
Package::for_source_in(&source, Some(files.path().join("outside")))
.err()
.unwrap()
.contains("outside its project root")
);
}
#[test]
fn cargo_artifact_selection_refuses_absent_ambiguous_and_malformed_messages() {
assert!(
compiler_executable(b"not JSON")
.unwrap_err()
.contains("invalid Cargo")
);
assert!(
compiler_executable(br#"{"reason":"build-finished","success":true}"#)
.unwrap_err()
.contains("did not report")
);
let artifact=br#"{"reason":"compiler-artifact","target":{"name":"flow-function-launcher"},"executable":"/target/host-triple/debug/flow-function-launcher"}"#;
assert_eq!(
compiler_executable(artifact).unwrap(),
Path::new("/target/host-triple/debug/flow-function-launcher")
);
let diagnostic =
br#"{"reason":"compiler-message","message":{"rendered":"fixture Cargo diagnostic\n"}}"#;
let streamed = [diagnostic.as_slice(), b"\n", artifact.as_slice()].concat();
assert_eq!(
compiler_executable(&streamed).unwrap(),
Path::new("/target/host-triple/debug/flow-function-launcher")
);
let duplicate = [artifact.as_slice(), b"\n", artifact.as_slice()].concat();
assert!(
compiler_executable(&duplicate)
.unwrap_err()
.contains("multiple")
);
}
#[test]
fn source_discovery_follows_inline_and_external_rust_module_directories() {
let root = std::env::temp_dir().join(format!(
"flow-rust-modules-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(root.join("group")).unwrap();
fs::write(root.join("lib.rs"), "pub mod group { pub mod tools; }").unwrap();
fs::write(
root.join("group/tools.rs"),
"#[flow_toolkit::tool] pub fn echo(value:String)->Result<String,String>{Ok(value)}",
)
.unwrap();
let mut exports = Exports::default();
collect(&root.join("lib.rs"), "", &mut exports).unwrap();
assert_eq!(
exports.functions,
["tool_impl::group::tools::__flow_tool_echo()"]
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn fingerprint_frames_file_names_and_contents() {
let root = std::env::temp_dir().join(format!(
"flow-rust-framing-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(root.join("left")).unwrap();
fs::create_dir_all(root.join("right")).unwrap();
fs::write(root.join("left/a"), b"bc").unwrap();
fs::write(root.join("right/ab"), b"c").unwrap();
let mut left = Sha256::new();
let mut right = Sha256::new();
digest_tree(&root.join("left"), &mut left, &mut BTreeSet::new()).unwrap();
digest_tree(&root.join("right"), &mut right, &mut BTreeSet::new()).unwrap();
assert_ne!(left.finalize(), right.finalize());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn metadata_only_refuses_unprepared_sources_without_running_build_code() {
let root = std::env::temp_dir().join(format!(
"flow-rust-metadata-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(root.join("src")).unwrap();
fs::write(
root.join("Cargo.toml"),
"[package]\nname=\"metadata-refusal\"\nversion=\"0.0.0\"\n",
)
.unwrap();
fs::write(
root.join("src/lib.rs"),
"compile_error!(\"must not compile during check\");",
)
.unwrap();
fs::write(
root.join("build.rs"),
"compile_error!(\"must not execute during check\");",
)
.unwrap();
let error = main(&[
"extract".into(),
root.join("src/lib.rs").to_string_lossy().into_owned(),
"--module".into(),
"tools.flow".into(),
])
.unwrap_err();
assert!(error.contains("need preparation"));
assert!(!root.join("target").exists());
fs::remove_dir_all(root).unwrap();
}
fn fixture() -> (flow_testing::TempDir, Package) {
let files = flow_testing::TempDir::new("rust-prepare-failures").unwrap();
fs::create_dir(files.path().join("src")).unwrap();
fs::write(
files.path().join("Cargo.toml"),
"[package]\nname=\"fixture\"\nversion=\"0.0.0\"\n",
)
.unwrap();
fs::write(files.path().join("src/lib.rs"), "pub fn plain() {}\n").unwrap();
let package = Package::read(&files.path().join("Cargo.toml")).unwrap();
(files, package)
}
fn assert_compilation_targets(
package: &mut Package,
cache: &Path,
output: &flow_testing::TempDir,
) {
let isolated = cache.parent().unwrap().join("package-launchers");
assert_eq!(compilation_target(package, cache, None), isolated);
assert_eq!(
compilation_target(package, cache, Some(std::ffi::OsStr::new(""))),
isolated
);
let explicit = output.join("shared-target");
fs::create_dir(&explicit).unwrap();
let explicit = explicit.canonicalize().unwrap();
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
isolated,
"a missing dependency inventory cannot authorize sharing"
);
fs::create_dir_all(cache).unwrap();
package.inputs = Some(cache.join("inputs"));
fs::write(
package.inputs.as_ref().unwrap(),
format!("{}\n", package.root.display()),
)
.unwrap();
#[cfg(unix)]
{
let expected = explicit.join("flow-package-launchers");
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
expected
);
let relative = Path::new("..")
.join(output.path().file_name().unwrap())
.join("shared-target");
assert_eq!(
compilation_target(package, cache, Some(relative.as_os_str())),
expected
);
let inside = package.root.join("custom-cargo-output");
fs::create_dir(&inside).unwrap();
assert_eq!(
compilation_target(package, cache, Some(inside.as_os_str())),
isolated
);
assert!(!inside.join("flow-package-launchers").exists());
let sdk = sdk_dir(package).unwrap();
assert_eq!(
compilation_target(package, cache, Some(sdk.as_os_str())),
isolated
);
std::os::unix::fs::symlink(&package.root, &expected).unwrap();
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
isolated
);
fs::remove_file(expected).unwrap();
assert_unusable_compilation_targets(package, cache, &explicit);
}
#[cfg(not(unix))]
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
isolated
);
package.release = false;
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
cache.join("target")
);
package.release = true;
}
#[cfg(unix)]
fn assert_unusable_compilation_targets(package: &Package, cache: &Path, explicit: &Path) {
let isolated = cache.parent().unwrap().join("package-launchers");
let ordinary = explicit.parent().unwrap().join("authored-target-file");
let bytes = b"preserve existing authored file\n";
fs::write(&ordinary, bytes).unwrap();
assert_eq!(
compilation_target(package, cache, Some(ordinary.as_os_str())),
isolated
);
assert_eq!(fs::read(&ordinary).unwrap(), bytes);
let child = explicit.join("flow-package-launchers");
fs::write(&child, bytes).unwrap();
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
isolated
);
assert_eq!(fs::read(&child).unwrap(), bytes);
fs::remove_file(&child).unwrap();
std::os::unix::fs::symlink(&ordinary, &child).unwrap();
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
isolated
);
assert_eq!(fs::read_link(&child).unwrap(), ordinary);
assert_eq!(fs::read(&ordinary).unwrap(), bytes);
fs::remove_file(&child).unwrap();
let inventory = package.inputs.as_ref().unwrap();
let original = fs::read(inventory).unwrap();
for damaged in [
String::new(),
"relative-input\n".into(),
format!("{}\n", ordinary.display()),
] {
fs::write(inventory, damaged).unwrap();
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
isolated
);
assert!(!child.exists());
assert_eq!(fs::read(&ordinary).unwrap(), bytes);
}
fs::write(inventory, original).unwrap();
assert_eq!(
compilation_target(package, cache, Some(explicit.as_os_str())),
child
);
}
#[test]
fn exported_artifacts_are_independent_copies_and_existing_destinations_are_preserved() {
let (_files, mut package) = fixture();
package.release = true;
let output = flow_testing::TempDir::new("rust-exported-artifacts").unwrap();
let selected = fs::canonicalize(&package.library).unwrap();
let cache = package.cache(&selected);
assert_compilation_targets(&mut package, &cache, &output);
fs::create_dir_all(&cache).unwrap();
let executable = cache.join("fixture-launcher");
fs::write(&executable, "independent executable bytes").unwrap();
fs::write(cache.join("executable"), executable.to_str().unwrap()).unwrap();
fs::write(
cache.join("declarations.flow"),
"pub type Exported { Value }\n",
)
.unwrap();
fs::write(
cache.join("fingerprint"),
format!(
"{}\n{}",
fingerprint(&package).unwrap(),
executable.display()
),
)
.unwrap();
let destination = output.join("artifact");
let exported = export(&selected, &destination).unwrap();
assert_eq!(
fs::read_to_string(&exported.declarations).unwrap(),
"pub type Exported { Value }\n"
);
assert_eq!(
fs::read_to_string(&exported.executable).unwrap(),
"independent executable bytes"
);
assert_eq!(
exported.inputs.get(&selected),
Some(&hex_hash(&fs::read(&selected).unwrap()))
);
assert_eq!(exported.build_fingerprint, fingerprint(&package).unwrap());
fs::remove_dir_all(&cache).unwrap();
assert_eq!(
fs::read_to_string(&exported.executable).unwrap(),
"independent executable bytes"
);
assert!(
export(&selected, &destination)
.unwrap_err()
.contains("already exists")
);
assert_eq!(
fs::read_to_string(exported.executable).unwrap(),
"independent executable bytes"
);
}
#[test]
fn missing_cargo_files_and_an_unhashed_missing_contract_preserve_io_failures() {
let (files, package) = fixture();
assert!(Package::read(&files.join("absent/Cargo.toml")).is_err());
assert!(Package::read(&files.join("missing.toml")).is_err());
let cache = cached_export_fixture(&package);
let missing = files.join("missing-contract.json");
let error = serve(&cache, missing.to_str().unwrap().into(), "tools", None).unwrap_err();
assert!(error.contains("No such file"), "{error}");
assert!(cache.join("declarations.flow").is_file());
}
#[cfg(unix)]
#[test]
fn a_failed_declaration_copy_removes_only_its_new_export_directory() {
use std::os::unix::fs::PermissionsExt as _;
let (files, mut package) = fixture();
package.release = true;
let cache = cached_export_fixture(&package);
let declaration = cache.join("declarations.flow");
fs::set_permissions(&declaration, fs::Permissions::from_mode(0o0)).unwrap();
let inaccessible = fs::read(&declaration).is_err();
let destination = files.join("refused-export");
let observed = export(&package.library, &destination);
fs::set_permissions(&declaration, fs::Permissions::from_mode(0o600)).unwrap();
if inaccessible {
assert!(observed.is_err());
assert!(!destination.exists());
} else {
assert!(observed.is_ok());
}
assert!(cache.join("fingerprint").is_file());
assert_eq!(
fs::read_to_string(declaration).unwrap(),
"pub type Exported { Value }\n"
);
}
#[cfg(unix)]
#[test]
fn a_removed_working_directory_refuses_native_source_discovery() {
const MARKER: &str = "FLOW_TEST_REMOVED_PREPARATION_DIRECTORY";
if std::env::var_os(MARKER).is_some() {
let directory = std::env::current_dir().unwrap();
fs::remove_dir(directory).unwrap();
let error = main(&[
"extract".into(),
"source.rs".into(),
"--module".into(),
"source.rs".into(),
])
.unwrap_err();
assert!(error.contains("No such file"), "{error}");
return;
}
let files = flow_testing::TempDir::new("rust-removed-working-directory").unwrap();
let directory = files.join("working");
fs::create_dir(&directory).unwrap();
let output = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"prepare::tests::a_removed_working_directory_refuses_native_source_discovery",
"--nocapture",
])
.env(MARKER, "1")
.current_dir(directory)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn optimized_exports_have_distinct_preparation_identity_from_native_development() {
let (_files, mut package) = fixture();
let selected = fs::canonicalize(&package.library).unwrap();
let development_cache = package.cache(&selected);
let development_fingerprint = fingerprint(&package).unwrap();
package.release = true;
assert_ne!(package.cache(&selected), development_cache);
assert_ne!(fingerprint(&package).unwrap(), development_fingerprint);
assert!(package.cache(&selected).ends_with(format!(
"{}-release",
development_cache.file_name().unwrap().to_str().unwrap()
)));
}
fn args(package: &Package, action: &str, extra: &[&str]) -> Vec<String> {
[
vec![
action.to_owned(),
package
.root
.join("src/lib.rs")
.to_string_lossy()
.into_owned(),
"--module".into(),
"tools.flow".into(),
],
extra.iter().map(|s| (*s).to_owned()).collect(),
]
.concat()
}
#[test]
fn build_environment_changes_invalidate_the_prepared_native_graph() {
const ROOT: &str = "FLOW_TEST_FINGERPRINT_ROOT";
if let Some(root) = std::env::var_os(ROOT) {
let package = Package::read(&PathBuf::from(root).join("Cargo.toml")).unwrap();
println!("fingerprint-probe:{}", fingerprint(&package).unwrap());
return;
}
let (files, _) = fixture();
let probe = |key: &str, value: &str| {
let output = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "prepare::tests::build_environment_changes_invalidate_the_prepared_native_graph", "--nocapture", "--test-threads=1"])
.env(ROOT, files.path()).env(key, value).output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8(output.stdout).unwrap();
stdout
.lines()
.find_map(|line| {
line.split_once("fingerprint-probe:")
.map(|(_, digest)| digest.to_owned())
})
.expect("child fingerprint")
};
for key in [
"CARGO_FLOW_FINGERPRINT_PROBE",
"RUST_FLOW_FINGERPRINT_PROBE",
"CC_FLOW_FINGERPRINT_PROBE",
"CXX_FLOW_FINGERPRINT_PROBE",
] {
assert_eq!(probe(key, "first"), probe(key, "first"), "{key}");
assert_ne!(probe(key, "first"), probe(key, "second"), "{key}");
}
}
#[test]
fn ancestor_cargo_configuration_changes_invalidate_the_prepared_native_graph() {
let files = flow_testing::TempDir::new("rust-workspace-inputs").unwrap();
let member = files.path().join("member");
fs::create_dir_all(member.join("src")).unwrap();
fs::create_dir(files.path().join(".cargo")).unwrap();
fs::write(
member.join("Cargo.toml"),
"[package]\nname=\"member\"\nversion=\"0.0.0\"\n",
)
.unwrap();
fs::write(member.join("src/lib.rs"), "").unwrap();
fs::write(
files.path().join("Cargo.toml"),
"[workspace]\nmembers=[\"member\"]\n",
)
.unwrap();
fs::write(files.path().join("Cargo.lock"), "version=4\n").unwrap();
let config = files.path().join(".cargo/config.toml");
fs::write(&config, "[build]\njobs=1\n").unwrap();
let package = Package::read(&member.join("Cargo.toml")).unwrap();
let mut inputs = PreparationInputs::default();
let before = fingerprint_inputs(&package, &mut inputs).unwrap();
assert!(
inputs
.cargo_configurations
.values()
.any(|path| path == &fs::canonicalize(&config).unwrap())
);
assert!(
!inputs
.source_files
.contains(&fs::canonicalize(&config).unwrap())
);
fs::write(config, "[build]\njobs=2\n").unwrap();
assert_ne!(before, fingerprint(&package).unwrap());
}
#[test]
fn native_inputs_follow_only_normal_and_build_dependency_edges() {
let files = flow_testing::TempDir::new("rust-selected-dependencies").unwrap();
fs::write(files.join("Cargo.toml"), "[workspace]\nmembers=[\"selected\",\"dependency\",\"unrelated\",\"buildonly\"]\nresolver=\"2\"\n").unwrap();
for name in ["selected", "dependency", "unrelated", "buildonly"] {
let root = files.join(name);
fs::create_dir_all(root.join("src")).unwrap();
fs::write(
root.join("Cargo.toml"),
format!("[package]\nname={name:?}\nversion=\"0.0.0\"\nedition=\"2024\"\n"),
)
.unwrap();
fs::write(root.join("src/lib.rs"), "pub fn value() -> bool { true }\n").unwrap();
}
let selected = files.join("selected");
let manifest = selected.join("Cargo.toml");
fs::write(&manifest, "[package]\nname=\"selected\"\nversion=\"0.0.0\"\nedition=\"2024\"\n[dependencies]\ndependency={path=\"../dependency\"}\n[build-dependencies]\nbuildonly={path=\"../buildonly\"}\n[dev-dependencies]\nunrelated={path=\"../unrelated\"}\n").unwrap();
let cache = selected.join("target/test-cache");
fs::create_dir_all(&cache).unwrap();
let mut package = Package::read(&manifest).unwrap();
package.inputs = Some(cache.join("inputs"));
prepare_native_resolution(&package, &cache).unwrap();
let roots = fs::read_to_string(cache.join("inputs"))
.unwrap()
.lines()
.map(PathBuf::from)
.collect::<BTreeSet<_>>();
assert_eq!(
roots,
["selected", "dependency", "buildonly"]
.into_iter()
.map(|name| fs::canonicalize(files.join(name)).unwrap())
.collect()
);
let mut inputs = PreparationInputs::default();
let first = fingerprint_inputs(&package, &mut inputs).unwrap();
let source_digests = |inputs: &PreparationInputs| {
inputs
.source_files
.iter()
.map(|path| (path.clone(), hex_hash(&fs::read(path).unwrap())))
.collect::<BTreeMap<_, _>>()
};
let first_sources = source_digests(&inputs);
fs::write(
files.join("unrelated/src/lib.rs"),
"pub fn unrelated_edit() {}\n",
)
.unwrap();
let mut after_unrelated = PreparationInputs::default();
assert_eq!(
first,
fingerprint_inputs(&package, &mut after_unrelated).unwrap()
);
assert_eq!(first_sources, source_digests(&after_unrelated));
assert!(
!after_unrelated
.source_files
.contains(&fs::canonicalize(files.join("unrelated/src/lib.rs")).unwrap())
);
fs::write(
files.join("dependency/src/lib.rs"),
"pub fn dependency_edit() {}\n",
)
.unwrap();
let after_dependency = fingerprint(&package).unwrap();
assert_ne!(first, after_dependency);
fs::write(
files.join("buildonly/src/lib.rs"),
"pub fn build_dependency_edit() {}\n",
)
.unwrap();
assert_ne!(after_dependency, fingerprint(&package).unwrap());
}
#[test]
fn malformed_dependency_graphs_cannot_drop_required_native_inputs() {
let (_files, package) = fixture();
let manifest =
crate::Json::String(package.root.join("Cargo.toml").to_str().unwrap().into())
.canonical();
let selected = format!(r#"{{"id":"selected","source":null,"manifest_path":{manifest}}}"#);
for (metadata, cause) in [
(
format!(r#"{{"packages":[{selected}]}}"#),
"no resolved dependency graph",
),
(
r#"{"packages":[],"resolve":{"nodes":[]}}"#.into(),
"does not contain the selected native package",
),
(
format!(r#"{{"packages":[{selected}],"resolve":{{"nodes":[]}}}}"#),
"dependency node is missing",
),
(
format!(
r#"{{"packages":[{selected}],"resolve":{{"nodes":[{{"id":"selected"}}]}}}}"#
),
"has no deps",
),
(
format!(
r#"{{"packages":[{selected}],"resolve":{{"nodes":[{{"id":"selected","deps":[{{"pkg":"missing","dep_kinds":[{{"kind":null}}]}}]}}]}}}}"#
),
"dependency package is missing",
),
(
format!(
r#"{{"packages":[{selected}],"resolve":{{"nodes":[{{"id":"selected","deps":[{{"pkg":"selected"}}]}}]}}}}"#
),
"no kind information",
),
(
format!(
r#"{{"packages":[{selected}],"resolve":{{"nodes":[{{"id":"selected","deps":[{{"pkg":"selected","dep_kinds":[{{"kind":"future"}}]}}]}}]}}}}"#
),
"kind is unsupported",
),
] {
let metadata = crate::parse_json(&metadata).unwrap();
assert!(
local_dependency_roots(&metadata, &package.root.join("Cargo.toml"))
.unwrap_err()
.contains(cause),
"{cause}"
);
}
let duplicate = crate::parse_json(r#"[{"id":"same"},{"id":"same"}]"#).unwrap();
let crate::Json::Array(rows) = duplicate else {
unreachable!()
};
assert!(
metadata_index(&rows)
.unwrap_err()
.contains("duplicate Cargo metadata package ID")
);
assert!(
metadata_index(&[crate::Json::Null])
.unwrap_err()
.contains("Cargo metadata needs id")
);
}
fn cached_export_fixture(package: &Package) -> PathBuf {
let selected = fs::canonicalize(&package.library).unwrap();
let cache = package.cache(&selected);
fs::create_dir_all(&cache).unwrap();
let executable = cache.join("fixture-launcher");
fs::write(&executable, "independent executable bytes").unwrap();
fs::write(cache.join("executable"), executable.to_str().unwrap()).unwrap();
fs::write(
cache.join("declarations.flow"),
"pub type Exported { Value }\n",
)
.unwrap();
fs::write(
cache.join("fingerprint"),
format!(
"{}\n{}",
fingerprint(package).unwrap(),
executable.display()
),
)
.unwrap();
cache
}
#[test]
fn host_cargo_configuration_is_build_provenance_not_source_identity() {
let files = flow_testing::TempDir::new("rust-host-config-inputs").unwrap();
let repository = files.join("checkout");
fs::create_dir_all(repository.join("src")).unwrap();
fs::create_dir(files.join(".cargo")).unwrap();
fs::write(
repository.join("Cargo.toml"),
"[package]\nname=\"host-config-inputs\"\nversion=\"0.0.0\"\n",
)
.unwrap();
fs::write(repository.join("src/lib.rs"), "pub fn plain() {}\n").unwrap();
let config = files.join(".cargo/config.toml");
fs::write(&config, "[build]\njobs=1\n").unwrap();
let mut package = Package::read(&repository.join("Cargo.toml")).unwrap();
package.release = true;
cached_export_fixture(&package);
let first = export(&package.library, &files.join("first")).unwrap();
assert!(
!first
.inputs
.contains_key(&fs::canonicalize(&config).unwrap())
);
assert_eq!(
first.build_inputs.get("ancestor/1/config.toml"),
Some(&hex_hash(b"[build]\njobs=1\n"))
);
fs::write(&config, "[build]\njobs=2\n").unwrap();
assert_ne!(first.build_fingerprint, fingerprint(&package).unwrap());
cached_export_fixture(&package);
let second = export(&package.library, &files.join("second")).unwrap();
assert_eq!(first.inputs, second.inputs);
assert_ne!(first.build_inputs, second.build_inputs);
assert_ne!(first.build_fingerprint, second.build_fingerprint);
assert!(
second
.build_inputs
.keys()
.all(|key| !key.contains(files.path().to_str().unwrap()))
);
}
#[test]
fn cargo_configuration_discovery_respects_explicit_and_default_home_locations() {
const ROOT: &str = "FLOW_TEST_CARGO_CONFIGURATION_ROOT";
const CASE: &str = "FLOW_TEST_CARGO_CONFIGURATION_CASE";
if let Some(root) = std::env::var_os(ROOT) {
let root = PathBuf::from(root);
let package = Package::read(&root.join("package/Cargo.toml")).unwrap();
let configurations = cargo_configurations(&package).unwrap();
let case = std::env::var(CASE).unwrap();
let expected = match case.as_str() {
"explicit" => Some(root.join("cargo/config.toml")),
"home" => Some(root.join("home/.cargo/config.toml")),
"profile" => Some(root.join("profile/.cargo/config.toml")),
"none" => None,
_ => panic!("unknown fixture case"),
};
assert_eq!(
configurations.get("cargo_home/config.toml"),
expected
.as_ref()
.map(|path| fs::canonicalize(path).unwrap())
.as_ref()
);
return;
}
let files = flow_testing::TempDir::new("rust-cargo-configuration-homes").unwrap();
fs::create_dir_all(files.join("package/src")).unwrap();
fs::write(
files.join("package/Cargo.toml"),
"[package]\nname=\"configuration-homes\"\nversion=\"0.0.0\"\n",
)
.unwrap();
fs::write(files.join("package/src/lib.rs"), "").unwrap();
for path in ["cargo", "home/.cargo", "profile/.cargo"] {
fs::create_dir_all(files.join(path)).unwrap();
fs::write(files.join(path).join("config.toml"), "[build]\njobs=1\n").unwrap();
}
for case in ["explicit", "home", "profile", "none"] {
let mut child = Command::new(std::env::current_exe().unwrap());
child.args(["--exact", "prepare::tests::cargo_configuration_discovery_respects_explicit_and_default_home_locations", "--nocapture"])
.env(ROOT, files.path()).env(CASE, case)
.env_remove("CARGO_HOME").env_remove("HOME").env_remove("USERPROFILE");
if case != "none" {
child.env("USERPROFILE", files.join("profile"));
}
if case == "explicit" || case == "home" {
child.env("HOME", files.join("home"));
}
if case == "explicit" {
child.env("CARGO_HOME", files.join("cargo"));
}
let output = child.output().unwrap();
assert!(
output.status.success(),
"{case}: {}",
String::from_utf8_lossy(&output.stderr)
);
}
}
#[cfg(unix)]
#[test]
fn export_refuses_a_cooperating_rebuild_during_its_artifact_snapshot() {
let (files, mut package) = fixture();
package.release = true;
let cache = cached_export_fixture(&package);
let _rebuild_lock = lock_preparation(&cache).unwrap();
let destination = files.join("export-during-rebuild");
assert!(
export(&package.library, &destination)
.unwrap_err()
.contains("already being prepared")
);
assert!(!destination.exists());
}
#[test]
fn preparation_refuses_invalid_commands_package_layouts_and_unsupported_export_discovery() {
let (_files, package) = fixture();
for (action, extra, expected) in [
("extract", vec!["--unknown"], "unknown argument"),
("extract", vec!["--depfile"], "needs a path"),
("extract", vec!["--origins"], "needs a path"),
(
"serve",
vec!["--origins", "origins.json", "--contract", "contract.json"],
"invalid",
),
(
"serve",
vec!["--prepare", "--contract", "contract.json"],
"invalid",
),
(
"serve",
vec!["--depfile", "deps.json", "--contract", "contract.json"],
"invalid",
),
(
"extract",
vec!["--contract", "contract.json", "--declaration-hash", "wrong"],
"invalid",
),
("unknown", vec![], "invalid"),
] {
assert!(
main(&args(&package, action, &extra))
.unwrap_err()
.contains(expected)
);
}
assert!(
build(
&package,
&package.root.join("target/cache"),
&package.library
)
.unwrap_err()
.contains("no public")
);
for (source, expected) in [
(
"#[cfg(test)] #[tool] pub fn conditional() {}",
"conditional #[tool]",
),
(
"#[cfg(test)] #[lifecycle] pub fn conditional() {}",
"conditional #[lifecycle]",
),
(
"#[lifecycle] pub fn one() {} #[lifecycle] pub fn two() {}",
"at most one",
),
("#[cfg(test)] pub mod conditional {}", "conditional or"),
("#[path=\"other.rs\"] pub mod renamed;", "conditional or"),
] {
fs::write(&package.library, source).unwrap();
assert!(
collect(&package.library, "", &mut Exports::default())
.unwrap_err()
.contains(expected)
);
}
fs::write(
&package.library,
"mod private { pub mod missing; } const VALUE:bool=true; pub mod outer;",
)
.unwrap();
fs::create_dir(package.root.join("src/outer")).unwrap();
fs::create_dir(package.root.join("src/outer/inner")).unwrap();
fs::write(package.root.join("src/outer.rs"), "pub mod inner;").unwrap();
fs::write(
package.root.join("src/outer/inner/mod.rs"),
"#[tool] pub fn nested() {}",
)
.unwrap();
let mut exports = Exports::default();
collect(&package.library, "", &mut exports).unwrap();
assert_eq!(
exports.functions,
["tool_impl::outer::inner::__flow_tool_nested()"]
);
fs::write(package.root.join("Cargo.toml"), "bad toml !!!").unwrap();
assert!(Package::read(&package.root.join("Cargo.toml")).is_err());
fs::write(
package.root.join("Cargo.toml"),
"[package]\nname=\"fixture\"\n[lib]\npath=\"custom.rs\"\n",
)
.unwrap();
assert!(
Package::read(&package.root.join("Cargo.toml"))
.err()
.unwrap()
.contains("without a handwritten main")
);
fs::write(package.root.join("custom.rs"), "").unwrap();
assert!(Package::read(&package.root.join("Cargo.toml")).is_ok());
}
#[cfg(unix)]
#[test]
fn valid_prepared_metadata_cannot_bypass_declaration_hash_or_start_an_unexecutable_artifact() {
let (_files, package) = fixture();
let cache = package.cache(&fs::canonicalize(&package.library).unwrap());
fs::create_dir_all(&cache).unwrap();
let executable = cache.join("not-executable");
fs::write(&executable, "not an executable").unwrap();
fs::write(cache.join("executable"), executable.to_str().unwrap()).unwrap();
let source = "@tool pub flow answer() -> Result<Text, Never>\n";
fs::write(cache.join("declarations.flow"), source).unwrap();
let contract = cache.join("contract.json");
fs::write(&contract, "{}").unwrap();
fs::write(
cache.join("fingerprint"),
format!(
"{}\n{}",
fingerprint(&package).unwrap(),
executable.display()
),
)
.unwrap();
let contract = contract.to_str().unwrap();
assert!(
main(&args(
&package,
"serve",
&["--contract", contract, "--declaration-hash", "sha256:wrong"]
))
.unwrap_err()
.contains("changed since program formation")
);
let digest = Sha256::digest(source.as_bytes()).iter().fold(
String::from("sha256:"),
|mut text, byte| {
let _ = write!(text, "{byte:02x}");
text
},
);
assert!(
main(&args(
&package,
"serve",
&["--contract", contract, "--declaration-hash", &digest]
))
.unwrap_err()
.contains("could not start")
);
let missing = cache.join("missing/deps.json");
assert!(
main(&args(
&package,
"extract",
&["--depfile", missing.to_str().unwrap()]
))
.is_err()
);
fs::write(cache.join("executable"), "relative/path").unwrap();
assert!(
prepared_executable(&cache)
.unwrap_err()
.contains("absolute")
);
let link = package.root.join("linked");
std::os::unix::fs::symlink(&package.library, &link).unwrap();
assert!(
fingerprint(&package)
.unwrap_err()
.contains("symbolic or special")
);
}
#[test]
fn toolkit_dependency_requires_source_metadata_and_keeps_explicit_git_selection() {
let (_files, package) = fixture();
for (source, expected) in [
(
"git+https://example.invalid/toolkit#0123456789abcdef0123456789abcdef01234567",
"{ git = \"https://example.invalid/toolkit\" }",
),
(
"git+https://example.invalid/toolkit?tag=v0.1.0#0123456789abcdef0123456789abcdef01234567",
"{ git = \"https://example.invalid/toolkit\", tag = \"v0.1.0\" }",
),
(
"git+https://example.invalid/toolkit?rev=0123456789abcdef#0123456789abcdef0123456789abcdef01234567",
"{ git = \"https://example.invalid/toolkit\", rev = \"0123456789abcdef\" }",
),
] {
let metadata = crate::Json::Object(vec![
("version".into(), crate::Json::String("0.1.0".into())),
("source".into(), crate::Json::String(source.into())),
]);
assert_eq!(
toolkit_dependency(&metadata, &package.root).unwrap(),
expected
);
}
for source in [None, Some(crate::Json::Bool(false))] {
let mut fields = vec![("version".into(), crate::Json::String("0.1.0".into()))];
fields.extend(source.map(|source| ("source".into(), source)));
assert_eq!(
toolkit_dependency(&crate::Json::Object(fields), &package.root).unwrap_err(),
"Cargo toolkit source is missing"
);
}
let missing_reference = crate::parse_json(r#"{"version":"0.1.0","source":"git+https://example.invalid/toolkit?branch#0123456789abcdef0123456789abcdef01234567"}"#).unwrap();
assert_eq!(
toolkit_dependency(&missing_reference, &package.root).unwrap_err(),
"Cargo Git source has no reference value"
);
}
fn resolved_package_entry(id: &str, name: &str, manifest: &Path) -> crate::Json {
crate::Json::Object(vec![
("id".into(), crate::Json::String(id.into())),
("name".into(), crate::Json::String(name.into())),
(
"version".into(),
crate::Json::String(id.rsplit_once('@').unwrap().1.into()),
),
("source".into(), crate::Json::Null),
(
"manifest_path".into(),
crate::Json::String(manifest.to_str().unwrap().into()),
),
])
}
#[test]
fn native_sdk_resolution_requires_a_graph_and_refuses_two_selected_toolkit_identities() {
let (files, package) = fixture();
let manifest = package.root.join("Cargo.toml");
let selected = format!("path+file://{}#fixture@0.0.0", package.root.display());
let selected_entry = resolved_package_entry(&selected, "fixture", &manifest);
let no_graph = crate::Json::Object(vec![(
"packages".into(),
crate::Json::Array(vec![selected_entry.clone()]),
)]);
assert_eq!(
resolved_toolkit(&no_graph, &manifest).unwrap_err(),
"Cargo metadata has no resolved dependency graph"
);
assert_eq!(
local_dependency_roots(&crate::Json::Null, &manifest).unwrap_err(),
"Cargo metadata has no packages"
);
let no_dependencies = crate::Json::Object(vec![
(
"packages".into(),
crate::Json::Array(vec![selected_entry.clone()]),
),
(
"resolve".into(),
crate::Json::Object(vec![(
"nodes".into(),
crate::Json::Array(vec![crate::Json::Object(vec![(
"id".into(),
crate::Json::String(selected.clone()),
)])]),
)]),
),
]);
assert_eq!(
resolved_toolkit(&no_dependencies, &manifest).unwrap_err(),
"selected Cargo dependency node has no deps"
);
let mut packages = vec![selected_entry];
let mut dependencies = Vec::new();
let mut nodes = Vec::new();
let source = fs::read_to_string(&manifest).unwrap();
fs::write(&manifest, source + "[dependencies]\nsdk-a={package='flow-toolkit',path='sdk-a'}\nsdk-b={package='flow-toolkit',path='sdk-b'}\n").unwrap();
for (name, version) in [("sdk-a", "0.1.0"), ("sdk-b", "0.2.0")] {
let root = files.join(name);
fs::create_dir(&root).unwrap();
fs::write(
root.join("Cargo.toml"),
format!(
"[package]\nname='flow-toolkit'\nversion='{version}'\n[lib]\npath='lib.rs'\n"
),
)
.unwrap();
fs::write(root.join("lib.rs"), "").unwrap();
let id = format!("path+file://{}#flow-toolkit@{version}", root.display());
packages.push(resolved_package_entry(
&id,
"flow-toolkit",
&root.join("Cargo.toml"),
));
dependencies.push(crate::Json::Object(vec![(
"pkg".into(),
crate::Json::String(id.clone()),
)]));
nodes.push(crate::Json::Object(vec![
("id".into(), crate::Json::String(id)),
("deps".into(), crate::Json::Array(Vec::new())),
]));
}
nodes.push(crate::Json::Object(vec![
("id".into(), crate::Json::String(selected)),
("deps".into(), crate::Json::Array(dependencies)),
]));
let ambiguous = crate::Json::Object(vec![
("packages".into(), crate::Json::Array(packages)),
(
"resolve".into(),
crate::Json::Object(vec![("nodes".into(), crate::Json::Array(nodes))]),
),
]);
assert_eq!(
resolved_toolkit(&ambiguous, &manifest).unwrap_err(),
"native package resolves multiple Flow toolkit identities"
);
}
#[cfg(target_os = "linux")]
#[test]
fn a_non_utf8_native_input_refuses_the_depfile_without_replacing_its_previous_contents() {
use std::os::unix::ffi::OsStringExt as _;
let (files, package) = fixture();
let input = package
.root
.join("src")
.join(std::ffi::OsString::from_vec(b"native-\xff.rs".to_vec()));
fs::write(&input, "pub fn native_input() {}\n").unwrap();
let destination = files.join("dependencies.json");
fs::write(&destination, "previous complete dependency inventory\n").unwrap();
let error = write_depfile(&package, &files.join("cache"), &destination).unwrap_err();
assert_eq!(error, "Rust input dependency paths must be UTF-8");
assert_eq!(
fs::read_to_string(&destination).unwrap(),
"previous complete dependency inventory\n"
);
assert!(input.is_file());
}
#[test]
fn missing_preparation_input_directories_do_not_produce_a_partial_dependency_inventory() {
let (files, mut package) = fixture();
let missing = files.join("missing-native-input");
let inputs = files.join("inputs");
fs::write(&inputs, missing.to_str().unwrap()).unwrap();
package.inputs = Some(inputs);
let destination = files.join("dependencies.json");
assert!(write_depfile(&package, &files.join("cache"), &destination).is_err());
assert!(!destination.exists());
assert!(!missing.exists());
let mut observed = BTreeSet::new();
assert!(digest_tree(&missing, &mut Sha256::new(), &mut observed).is_err());
assert!(observed.is_empty());
}
}