use anyhow::{Context, Result, bail, ensure};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use flate2::{Compression, GzBuilder};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
pub(crate) use crate::compat::digest as hash_bytes;
pub const FORMAT: &str = "cdk-rsx-typed-root-artifacts-v1";
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FileRecord {
pub path: PathBuf,
pub bytes: u64,
pub sha256: String,
}
pub fn record(path: &Path) -> Result<FileRecord> {
let path = path
.canonicalize()
.with_context(|| format!("resolve build input {}", path.display()))?;
ensure!(path.is_file(), "not a regular file: {}", path.display());
let mut hash = Sha256::new();
let mut file = File::open(&path).with_context(|| format!("read {}", path.display()))?;
let bytes =
io::copy(&mut file, &mut hash).with_context(|| format!("hash {}", path.display()))?;
Ok(FileRecord {
path,
bytes,
sha256: format!("{:x}", hash.finalize()),
})
}
pub fn verify_bytes(file: &FileRecord, contents: &[u8]) -> Result<()> {
ensure!(
file.bytes == contents.len() as u64 && file.sha256 == hash_bytes(contents),
"pinned input changed: {}",
file.path.display()
);
Ok(())
}
pub fn write_json(path: &Path, contents: &impl Serialize) -> Result<()> {
let mut output = File::create(path).with_context(|| format!("write {}", path.display()))?;
serde_json::to_writer_pretty(&mut output, contents)?;
output.write_all(b"\n")?;
Ok(())
}
pub fn write_gzip_json(path: &Path, contents: &impl Serialize) -> Result<()> {
gzip_json(
File::create(path).with_context(|| format!("write {}", path.display()))?,
contents,
)
}
fn gzip_json(output: File, contents: &impl Serialize) -> Result<()> {
let mut gzip = GzBuilder::new()
.mtime(0)
.write(output, Compression::default());
serde_json::to_writer(&mut gzip, contents)?;
gzip.finish()?;
Ok(())
}
fn metadata_packages(metadata: &Value) -> Result<&[Value]> {
metadata["packages"]
.as_array()
.map(Vec::as_slice)
.context("Cargo metadata is missing packages")
}
fn metadata_path<'a>(value: &'a Value, field: &str) -> Result<&'a Path> {
value[field]
.as_str()
.map(Path::new)
.with_context(|| format!("Cargo metadata is missing {field}"))
}
fn package_directory(manifest: &Path) -> Result<&Path> {
manifest
.parent()
.context("Cargo manifest requires a parent directory")
}
fn cargo_inputs(directory: &Path) -> impl Iterator<Item = PathBuf> + '_ {
directory.ancestors().flat_map(|parent| {
[
parent.join(".cargo/config"),
parent.join(".cargo/config.toml"),
]
})
}
pub fn validate_generated_dirs(metadata: &Value, directories: &[PathBuf]) -> Result<()> {
if directories.is_empty() {
return Ok(());
}
let workspace = metadata_path(metadata, "workspace_root")?.canonicalize()?;
let mut protected_files = BTreeSet::from([
workspace.join("Cargo.toml"),
workspace.join("Cargo.lock"),
workspace.join("rust-toolchain.toml"),
]);
let mut protected_directories = BTreeSet::new();
protected_files.extend(cargo_inputs(&workspace));
for package in metadata_packages(metadata)? {
let manifest = metadata_path(package, "manifest_path")?.canonicalize()?;
let root = package_directory(&manifest)?;
protected_directories.insert(root.join("src"));
protected_files.extend(cargo_inputs(root));
for target in package["targets"]
.as_array()
.context("missing Cargo targets")?
{
let source = metadata_path(target, "src_path")?.canonicalize()?;
let directory = package_directory(&source)?;
if directory != root {
protected_directories.insert(directory.to_owned());
}
protected_files.insert(source);
}
protected_files.insert(manifest);
}
for directory in directories {
ensure!(
!directory.exists() || directory.is_dir(),
"--generated-dir must name a directory: {}",
directory.display()
);
let hidden = protected_files
.iter()
.find(|path| path.starts_with(directory))
.or_else(|| {
protected_directories
.iter()
.find(|path| path.starts_with(directory) || directory.starts_with(path))
});
if let Some(hidden) = hidden {
bail!(
"--generated-dir {} overlaps a build input: {}",
directory.display(),
hidden.display()
);
}
}
Ok(())
}
fn collect_files(
directory: &Path,
excluded: &[PathBuf],
rust_only: bool,
files: &mut BTreeSet<PathBuf>,
) -> Result<()> {
if excluded.iter().any(|root| directory.starts_with(root)) {
return Ok(());
}
for entry in fs::read_dir(directory).with_context(|| format!("list {}", directory.display()))? {
let entry = entry?;
if matches!(
entry.file_name().to_str(),
Some(".git" | ".rustup" | ".cargo-home" | "node_modules" | "__pycache__")
) {
continue;
}
let path = entry.path();
let kind = entry.file_type()?;
if kind.is_dir() {
collect_files(&path, excluded, rust_only, files)?;
} else if (kind.is_file() || kind.is_symlink() && path.is_file())
&& (!rust_only || path.extension().is_some_and(|ext| ext == "rs"))
&& !matches!(
path.extension().and_then(|ext| ext.to_str()),
Some("pyc" | "pyo")
)
{
files.insert(path);
}
}
Ok(())
}
fn snapshot_inner(
metadata: &Value,
excluded: &[PathBuf],
extra: &[PathBuf],
rust_sources: Option<&Path>,
) -> Result<Vec<FileRecord>> {
let workspace = metadata_path(metadata, "workspace_root")?.canonicalize()?;
let mut files: BTreeSet<_> = extra.iter().cloned().collect();
let workspace_inputs =
["Cargo.toml", "Cargo.lock", "rust-toolchain.toml"].map(|name| workspace.join(name));
files.extend(
workspace_inputs
.into_iter()
.chain(cargo_inputs(&workspace))
.filter(|p| p.is_file()),
);
for package in metadata_packages(metadata)? {
if !package["source"].is_null() && rust_sources.is_none() {
continue;
}
let manifest = metadata_path(package, "manifest_path")?.canonicalize()?;
let root = package_directory(&manifest)?;
collect_files(root, excluded, false, &mut files)?;
if package["source"].is_null() {
files.extend(cargo_inputs(root).filter(|path| path.is_file()));
for target in package["targets"]
.as_array()
.context("missing Cargo targets")?
{
files.insert(metadata_path(target, "src_path")?.to_owned());
}
files.insert(manifest);
}
}
if let Some(rust_sources) = rust_sources {
collect_files(&rust_sources.join("library"), excluded, true, &mut files)?;
}
let canonical: BTreeSet<_> = files
.iter()
.map(|path| {
path.canonicalize()
.with_context(|| format!("resolve snapshot input {}", path.display()))
})
.collect::<Result<_, _>>()?;
canonical.iter().map(|path| record(path)).collect()
}
pub fn snapshot(
metadata: &Value,
excluded: &[PathBuf],
extra: &[PathBuf],
) -> Result<Vec<FileRecord>> {
snapshot_inner(metadata, excluded, extra, None)
}
pub fn snapshot_debug(
metadata: &Value,
excluded: &[PathBuf],
extra: &[PathBuf],
rust_sources: &Path,
) -> Result<Vec<FileRecord>> {
snapshot_inner(metadata, excluded, extra, Some(rust_sources))
}
pub fn verify_snapshot(before: &[FileRecord], after: &[FileRecord]) -> Result<()> {
if before == after {
return Ok(());
}
let original: BTreeMap<_, _> = before.iter().map(|row| (&row.path, row)).collect();
let current: BTreeMap<_, _> = after.iter().map(|row| (&row.path, row)).collect();
for path in original
.keys()
.chain(current.keys())
.copied()
.collect::<BTreeSet<_>>()
{
let action = match (original.get(path), current.get(path)) {
(None, Some(_)) => "added",
(Some(_), None) => "removed",
(Some(old), Some(new)) if old != new => "changed",
_ => continue,
};
bail!(
"source inputs changed during build ({action} {}). Freeze inputs and rebuild. Keep logs and generated files beside the app or declare their directory with --generated-dir.",
path.display()
);
}
bail!("snapshot input order changed during build")
}
fn private_gzip_json(path: &Path, contents: &impl Serialize) -> Result<()> {
use std::os::unix::fs::OpenOptionsExt as _;
let output = OpenOptions::new()
.create_new(true)
.write(true)
.mode(0o600)
.open(path)
.with_context(|| format!("write private source archive {}", path.display()))?;
gzip_json(output, contents)
}
fn archived_file(file: &FileRecord, path: &Path) -> Result<Value> {
let contents = fs::read(&file.path).with_context(|| format!("read {}", file.path.display()))?;
verify_bytes(file, &contents)?;
Ok(json!({
"path": path,
"bytes": file.bytes,
"sha256": file.sha256,
"contents_base64": STANDARD.encode(&contents),
}))
}
pub fn archive_sources(
sources: &[FileRecord],
commit: Option<&str>,
destination: &Path,
) -> Result<()> {
let first = &sources.first().context("empty source snapshot")?.path;
let root = package_directory(first)?
.ancestors()
.find(|root| sources.iter().all(|row| row.path.starts_with(root)))
.context("source files have no common parent")?;
let files = sources
.iter()
.map(|file| archived_file(file, file.path.strip_prefix(root)?))
.collect::<Result<Vec<_>>>()?;
private_gzip_json(
destination,
&json!({
"format": "cdk-rsx-exact-source-v1",
"recorded_build_root": format!("{}/", root.display()),
"files": files,
"commit": commit,
}),
)
}
pub fn archive_debug_sources(
sources: &[FileRecord],
generated: &[PathBuf],
remappings: &[(PathBuf, String)],
installed_sha256: &str,
destination: &Path,
) -> Result<()> {
let mut generated_files = BTreeSet::new();
for directory in generated {
if directory.is_dir() {
collect_files(directory, &[], false, &mut generated_files)?;
}
}
let mut rows: BTreeMap<_, _> = sources
.iter()
.cloned()
.map(|row| (row.path.clone(), row))
.collect();
for path in generated_files {
if path.extension().is_some_and(|ext| ext == "rs")
|| path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.ends_with(".rs.map.json"))
{
let row = record(&path)?;
rows.insert(row.path.clone(), row);
}
}
let mut precedence: Vec<_> = remappings.iter().collect();
precedence.sort_by_key(|(physical, _)| std::cmp::Reverse(physical.as_os_str().len()));
let files = rows
.values()
.map(|row| {
let logical = precedence
.iter()
.find_map(|(physical, logical)| {
row.path
.strip_prefix(physical)
.ok()
.map(|suffix| Path::new(logical).join(suffix))
})
.unwrap_or_else(|| row.path.clone());
let mut file = archived_file(row, &logical)?;
file["physical_path"] = serde_json::to_value(&row.path)?;
Ok(file)
})
.collect::<Result<Vec<_>>>()?;
let mappings: Vec<_> = remappings
.iter()
.map(|(physical, logical)| json!({"physical": physical, "logical": logical}))
.collect();
private_gzip_json(
destination,
&json!({
"format": "cdk-rsx-debug-sources-v1",
"installed_sha256": installed_sha256,
"path_remappings": mappings,
"files": files,
}),
)
}
pub fn remove_completion(output: &Path, stem: &str) -> Result<()> {
ensure!(safe_name(stem), "invalid artifact filename stem: {stem:?}");
remove_file(&output.join(format!("{stem}.SHA256SUMS")))
}
fn remove_file(path: &Path) -> Result<()> {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error).with_context(|| format!("remove {}", path.display())),
}
}
pub fn safe_name(name: &str) -> bool {
!name.is_empty() && !matches!(name, "." | "..") && !name.contains(['/', '\\', '\n', '\r', '\0'])
}
pub fn publish(
stage: &Path,
output: &Path,
stem: &str,
build: &Value,
sources: &[FileRecord],
artifacts: &[&str],
commit: Option<&str>,
) -> Result<PathBuf> {
ensure!(safe_name(stem), "invalid artifact filename stem: {stem:?}");
let output = output.canonicalize()?;
let stage = stage.canonicalize()?;
ensure!(output != stage, "artifact staging must be private");
let mut suffixes = BTreeSet::new();
let mut records = Vec::with_capacity(artifacts.len());
let mut marker = String::new();
for suffix in artifacts {
ensure!(
safe_name(suffix)
&& !matches!(*suffix, "manifest.json" | "SHA256SUMS")
&& suffixes.insert(*suffix),
"invalid or duplicate artifact output suffix: {suffix}"
);
let name = format!("{stem}.{suffix}");
let staged = stage.join(&name);
let mut file = record(&staged)?;
ensure!(file.path == staged, "staged artifact is a symlink: {name}");
file.path = output.join(&name);
marker.push_str(&format!("{} {name}\n", file.sha256));
records.push(file);
}
let wasm_path = output.join(format!("{stem}.wasm"));
let wasm = records
.iter()
.find(|row| row.path == wasm_path)
.context("missing staged Wasm")?;
let manifest_name = format!("{stem}.manifest.json");
let manifest = stage.join(&manifest_name);
write_json(
&manifest,
&json!({
"format": FORMAT,
"implementation": "cdk-rsx",
"package": build["package"],
"commit": commit,
"compiler": fs::read_to_string(stage.join(format!("{stem}.toolchain.txt")))?,
"wasmSha256": wasm.sha256,
"features": build["features"],
"sourceUnchangedDuringBuild": true,
"buildSeconds": build["build_seconds"],
"canonicalBuild": build,
"sources": sources,
"outputs": records,
}),
)?;
marker.push_str(&format!("{} {manifest_name}\n", record(&manifest)?.sha256));
let marker_name = format!("{stem}.SHA256SUMS");
fs::write(stage.join(&marker_name), marker)?;
remove_completion(&output, stem)?;
for suffix in artifacts {
let name = format!("{stem}.{suffix}");
fs::rename(stage.join(&name), output.join(&name))
.with_context(|| format!("publish {}", output.join(&name).display()))?;
}
for suffix in [
"source-archive.json.gz",
"debug-sources.json.gz",
"stripped.raw.wasm",
] {
if !suffixes.contains(suffix) {
remove_file(&output.join(format!("{stem}.{suffix}")))?;
}
}
let published = output.join(manifest_name);
fs::rename(manifest, &published)?;
fs::rename(stage.join(&marker_name), output.join(&marker_name))?;
Ok(published)
}