Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
426 changes: 182 additions & 244 deletions Cargo.lock

Large diffs are not rendered by default.

57 changes: 42 additions & 15 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,54 @@ description = "Tool for targeting the WebAssembly Component Model using Python"
name = "componentize_py"
crate-type = ["cdylib", "rlib"]

[[bin]]
name = "componentize-py"
required-features = ["embedded-runtime"]

[features]
default = ["embedded-runtime"]
# Builds CPython and the runtime into the crate. Preparing assets and
# `componentize` need it; reading and assembling prepared assets do not.
embedded-runtime = [
"dep:bincode",
"dep:cap-std",
"dep:clap",
"dep:heck",
"dep:im-rc",
"dep:once_cell",
"dep:pretty_env_logger",
"dep:semver",
"dep:tokio",
"dep:wasm-pkg-client",
"dep:wasmtime-wasi",
"dep:wit-bindgen-core",
"dep:wit-dylib",
"dep:wit-parser",
]
pyo3 = ["dep:pyo3", "embedded-runtime"]

[dependencies]
anyhow = { version = "1.0.91", features = ["backtrace"] }
clap = { version = "4.5.20", features = ["derive"] }
clap = { version = "4.5.20", features = ["derive"], optional = true }
tar = "0.4.42"
tempfile = "3.13.0"
zstd = "0.13.2"
wasm-encoder = { version = "0.258.0", features = ["wasmparser"] }
wit-dylib = "0.258.0"
wit-parser = "0.258.0"
wit-dylib = { version = "0.258.0", optional = true }
wit-parser = { version = "0.258.0", optional = true }
wit-component = "0.258.0"
wasmparser = "0.258.0"
indexmap = "2.6.0"
bincode = "1.3.3"
heck = "0.5.0"
bincode = { version = "1.3.3", optional = true }
heck = { version = "0.5.0", optional = true }
pyo3 = { version = "0.28.3", features = [
"abi3-py39",
"extension-module",
], optional = true }
wasmtime = "48.0.0"
wasmtime-wasi = { version = "48.0.0", features = [ "p3" ] }
wasm-pkg-client = "0.16.1"
once_cell = "1.20.2"
wasmtime = "50.0.1"
wasmtime-wasi = { version = "50.0.1", features = [ "p3" ], optional = true }
wasm-pkg-client = { version = "0.16.1", optional = true }
once_cell = { version = "1.20.2", optional = true }
component-init-transform = "0.3.1"
async-trait = "0.1.83"
futures = "0.3.31"
Expand All @@ -40,15 +66,16 @@ tokio = { version = "1.41.0", features = [
"rt",
"rt-multi-thread",
"fs",
] }
], optional = true }
bytes = "1.8.0"
pretty_env_logger = "0.5.0"
cap-std = "3.3.0"
im-rc = "15.1.0"
pretty_env_logger = { version = "0.5.0", optional = true }
cap-std = { version = "3.3.0", optional = true }
im-rc = { version = "15.1.0", optional = true }
serde = { version = "1.0.213", features = ["derive"] }
serde_json = "1.0"
toml = "0.8.19"
semver = "1.0.23"
wit-bindgen-core = "0.61.0"
semver = { version = "1.0.23", optional = true }
wit-bindgen-core = { version = "0.61.0", optional = true }
sha2 = "0.10.9"
filetime = "0.2.29"

Expand Down
11 changes: 7 additions & 4 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ fn main() -> Result<()> {
|| env::var("CLIPPY_ARGS").is_ok()
|| env::var("CARGO_EXPAND_NO_RUN_NIGHTLY").is_ok()
{
println!(
"cargo:warning=using stubbed runtime, core library, and adapter for static analysis purposes..."
);
stubs_for_clippy(&out_dir)
} else if env::var_os("CARGO_FEATURE_EMBEDDED_RUNTIME").is_none() {
// Without the embedded runtime, the crate only reads and assembles
// prepared assets, which carry their own runtime.
stubs_for_clippy(&out_dir)
} else {
package_all_the_things(&out_dir)
Expand All @@ -75,10 +82,6 @@ fn main() -> Result<()> {
}

fn stubs_for_clippy(out_dir: &Path) -> Result<()> {
println!(
"cargo:warning=using stubbed runtime, core library, and adapter for static analysis purposes..."
);

let files = [
"libcomponentize_py_runtime_sync.so.zst",
"libcomponentize_py_runtime_async.so.zst",
Expand Down
160 changes: 158 additions & 2 deletions src/command.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use {
crate::{BindingsGenerator, ComponentGenerator},
anyhow::{Context, Result},
crate::{
BindingsGenerator, ComponentGenerator,
prepared::{Assembler, BindingsPreparer, Prepared},
},
anyhow::{Context, Result, bail},
clap::Parser as _,
std::{
env,
Expand Down Expand Up @@ -130,6 +133,63 @@ pub enum Command {
/// bindings generated by this command need not and should not be used by an
/// actual component produced using the `componentize` command.
Bindings(Bindings),

/// Prepare the bindings, runtime and metadata for a WIT world, for
/// assembly with any number of applications.
///
/// Prints the identity of the prepared assets.
Prepare(Prepare),

/// Link prepared assets with a Python app and its native extensions, then
/// pre-initialize the result.
///
/// The WIT world comes from the prepared assets; `--wit-path`, `--world`
/// and the other WIT options do not apply.
Assemble(Assemble),
}

#[derive(clap::Args, Debug)]
pub struct Prepare {
/// Directory to which the prepared assets should be written. It must not
/// exist or must be empty.
pub output_dir: PathBuf,

/// Specify a world to intersect with the target world. See
/// `componentize --intersect-world`.
#[arg(short = 'i', long)]
pub intersect_world: Option<String>,
}

#[derive(clap::Args, Debug)]
pub struct Assemble {
/// The name of a Python module containing the app to wrap.
pub app_name: String,

/// Directory containing prepared assets.
#[arg(long)]
pub prepared: PathBuf,

/// Fail unless the prepared assets have this identity.
#[arg(long)]
pub expect_identity: Option<String>,

/// Specify a directory containing the app and/or its dependencies, as
/// `[NAME=]DIRECTORY`. May be specified more than once.
///
/// The directory is visible at `/NAME` during pre-initialization, and the
/// library names of native extensions under it start with `/NAME`. NAME
/// defaults to the position of the option, starting at 0.
#[arg(short = 'p', long, default_value = ".")]
pub python_path: Vec<String>,

/// Output file to which to write the resulting component
#[arg(short = 'o', long, default_value = "index.wasm")]
pub output: PathBuf,

/// Size in bytes of the linear-memory stack used by C code. See
/// `componentize --stack-size`.
#[arg(long)]
pub stack_size: Option<u32>,
}

#[derive(clap::Args, Debug)]
Expand Down Expand Up @@ -256,7 +316,103 @@ pub fn run<T: Into<OsString> + Clone, I: IntoIterator<Item = T>>(args: I) -> Res
match command {
Command::Componentize(opts) => componentize(common, opts),
Command::Bindings(opts) => generate_bindings(common, opts),
Command::Prepare(opts) => prepare(common, opts),
Command::Assemble(opts) => assemble(common, opts),
}
}

fn prepare(common: Common, prepare: Prepare) -> Result<()> {
let prepared = Runtime::new()?.block_on(
BindingsPreparer {
wit_paths: &common
.wit_path
.iter()
.map(|v| v.as_path())
.collect::<Vec<_>>(),
worlds: &common.world.iter().map(|v| v.as_str()).collect::<Vec<_>>(),
features: &common
.features
.iter()
.map(|v| v.as_str())
.collect::<Vec<_>>(),
all_features: common.all_features,
bindings_module: common.bindings_module.as_deref(),
import_interface_names: &common
.import_interface_name
.iter()
.map(|(a, b)| (a.as_str(), b.as_str()))
.collect(),
export_interface_names: &common
.export_interface_name
.iter()
.map(|(a, b)| (a.as_str(), b.as_str()))
.collect(),
intersect_world: prepare.intersect_world.as_deref(),
registry_config: common.registry_config.as_deref(),
default_registries: !common.no_default_registries,
}
.prepare(),
)?;
prepared.write(&prepare.output_dir)?;
println!("{}", prepared.identity());
Ok(())
}

fn assemble(common: Common, assemble: Assemble) -> Result<()> {
if !common.wit_path.is_empty()
|| !common.world.is_empty()
|| !common.features.is_empty()
|| common.all_features
|| !common.import_interface_name.is_empty()
|| !common.export_interface_name.is_empty()
|| common.bindings_module.is_some()
{
bail!("`assemble` takes the WIT world from the prepared assets; remove the WIT options");
}

let prepared = Prepared::read(&assemble.prepared)?;
if let Some(expected) = &assemble.expect_identity
&& prepared.identity() != *expected
{
bail!(
"prepared assets at {} have identity {}, not {expected}",
assemble.prepared.display(),
prepared.identity()
);
}

let python_path = assemble
.python_path
.iter()
.enumerate()
.map(|(index, entry)| match entry.split_once('=') {
Some((name, path)) => (name.to_owned(), PathBuf::from(path)),
None => (index.to_string(), PathBuf::from(entry)),
})
.collect::<Vec<_>>();

let assembly = Assembler {
prepared: &prepared,
app_name: &assemble.app_name,
python_path: &python_path
.iter()
.map(|(name, path)| (name.as_str(), path.as_path()))
.collect::<Vec<_>>(),
stack_size: assemble.stack_size,
}
.assemble()?;
let component = Runtime::new()?.block_on(assembly.initialize_default())?;

if let Some(parent) = assemble.output.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&assemble.output, component)?;

if !common.quiet {
println!("Component built successfully");
}

Ok(())
}

fn generate_bindings(common: Common, bindings: Bindings) -> Result<()> {
Expand Down
Loading