cdk-rsx-cli 0.1.1

Build and test Internet Computer canisters with CDK RSX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use crate::TOOLCHAIN;
use anyhow::{Context, Result, bail, ensure};
use serde_json::Value;
use std::{
    collections::BTreeSet,
    env,
    fs::{self, File, OpenOptions},
    os::{fd::AsRawFd, unix::process::CommandExt},
    path::{Path, PathBuf},
    process::{Command, Output, Stdio},
};

pub const BUILD_STD: &str = "-Zbuild-std=std,panic_abort";

pub fn feature_flags(
    features: impl IntoIterator<Item = String>,
    all_features: bool,
    no_default_features: bool,
) -> Vec<String> {
    let mut flags = Vec::new();
    for features in features {
        flags.extend(["--features".into(), features]);
    }
    if all_features {
        flags.push("--all-features".into());
    }
    if no_default_features {
        flags.push("--no-default-features".into());
    }
    flags
}

pub fn refresh_lock(manifest: &Path, offline: bool) -> Result<()> {
    let manifest = manifest
        .canonicalize()
        .with_context(|| format!("open {}", manifest.display()))?;
    let compiler = Compiler::select(offline)?;
    let mut cargo = compiler.for_manifest(&manifest, "update");
    cargo.arg("--workspace");
    if offline {
        cargo.arg("--offline");
    }
    checked(&mut cargo, &[]).context("refresh the application workspace lockfile")?;
    Ok(())
}

pub struct Compiler {
    pub rustc: PathBuf,
    pub cargo: PathBuf,
    pub host: String,
    pub version: String,
    pub home: PathBuf,
    pub sources: PathBuf,
    target_directory: Option<PathBuf>,
}

impl Compiler {
    pub fn select(offline: bool) -> Result<Self> {
        let locate = || {
            Command::new("rustup")
                .args(["which", "--toolchain", TOOLCHAIN, "rustc"])
                .output()
                .context("Rustup is required to select the pinned canister compiler")
        };
        let result = locate()?;
        let rustc = if result.status.success() {
            PathBuf::from(String::from_utf8(result.stdout)?.trim()).canonicalize()?
        } else {
            ensure!(
                !offline,
                "install {TOOLCHAIN} and rust-src before building offline"
            );
            checked(
                Command::new("rustup").args([
                    "toolchain",
                    "install",
                    TOOLCHAIN,
                    "--profile",
                    "minimal",
                    "--component",
                    "rust-src",
                    "--no-self-update",
                ]),
                &[],
            )?;
            PathBuf::from(
                String::from_utf8(checked(
                    Command::new("rustup").args(["which", "--toolchain", TOOLCHAIN, "rustc"]),
                    &[],
                )?)?
                .trim(),
            )
            .canonicalize()?
        };
        let version = String::from_utf8(checked(Command::new(&rustc).arg("-Vv"), &[])?)?;
        let host = version
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("pinned rustc did not report its native host")?
            .to_owned();
        let sources = rustc
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("lib/rustlib/src/rust");
        if !sources.join("library/Cargo.toml").is_file() {
            ensure!(
                !offline,
                "install rust-src for {TOOLCHAIN} before building offline"
            );
            checked(
                Command::new("rustup").args([
                    "component",
                    "add",
                    "--toolchain",
                    TOOLCHAIN,
                    "rust-src",
                ]),
                &[],
            )?;
        }
        let home = env::var_os("CARGO_HOME")
            .map(PathBuf::from)
            .or_else(|| env::var_os("HOME").map(|path| PathBuf::from(path).join(".cargo")))
            .context("set CARGO_HOME to a writable Cargo cache")?;
        fs::create_dir_all(&home)?;
        let target_directory = env::var_os("CARGO_TARGET_DIR")
            .map(std::path::absolute)
            .transpose()
            .context("resolve CARGO_TARGET_DIR from the invocation directory")?;
        Ok(Self {
            cargo: rustc.with_file_name("cargo"),
            rustc,
            host,
            version,
            home: home.canonicalize()?,
            sources: sources.canonicalize()?,
            target_directory,
        })
    }

    pub fn command(&self, executable: &Path, workspace: &Path) -> Command {
        let mut command = Command::new(executable);
        let path = env::join_paths(
            std::iter::once(self.rustc.parent().unwrap().to_path_buf())
                .chain(env::var_os("PATH").iter().flat_map(env::split_paths)),
        );
        if let Ok(path) = path {
            command.env("PATH", path);
        }
        if let Some(target) = &self.target_directory {
            command.env("CARGO_TARGET_DIR", target);
        }
        command
            .current_dir(workspace)
            .env("CARGO_HOME", &self.home)
            .env("RUSTUP_TOOLCHAIN", TOOLCHAIN)
            .env("RUSTC", &self.rustc)
            .env("RUSTDOC", self.rustc.with_file_name("rustdoc"))
            .env("CARGO_BUILD_TARGET", &self.host)
            .env("CARGO_ENCODED_RUSTFLAGS", "")
            .env_remove("RUSTFLAGS")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .env_remove("CDK_RSX_COMPAT_CONTEXT")
            .env_remove("CDK_RSX_COMPAT_ALIASES")
            .env_remove("CDK_RSX_COMPAT_TOOLING")
            .env_remove("CDK_RSX_COMPAT_PACKAGE_ROOTS")
            .env("CARGO_UNSTABLE_CHECKSUM_FRESHNESS", "true")
            .env("CARGO_BUILD_FINGERPRINT", "content")
            .env("CARGO_INCREMENTAL", "0");
        command
    }

    pub fn for_manifest(&self, manifest: &Path, subcommand: &str) -> Command {
        let mut command = self.command(&self.cargo, manifest.parent().unwrap());
        command.arg(subcommand).arg("--manifest-path").arg(manifest);
        command
    }

    pub fn prepare_lock(&self, manifest: &Path, locked: bool, offline: bool) -> Result<()> {
        let workspace = checked(
            self.for_manifest(manifest, "locate-project").args([
                "--workspace",
                "--message-format",
                "plain",
            ]),
            &[],
        )?;
        let lock = Path::new(std::str::from_utf8(&workspace)?.trim()).with_file_name("Cargo.lock");
        if !lock.is_file() {
            ensure!(
                !locked && !offline,
                "{} is missing; run cdk-rsx lock to create it",
                lock.display()
            );
            checked(&mut self.for_manifest(manifest, "generate-lockfile"), &[])?;
        }
        Ok(())
    }

    pub fn fetch(&self, manifest: &Path, target: Option<&str>) -> Result<()> {
        let mut fetch = self.for_manifest(manifest, "fetch");
        fetch.arg("--locked").stdout(Stdio::inherit());
        if let Some(target) = target {
            fetch.args(["--target", target, BUILD_STD]);
        }
        checked(&mut fetch, &[])
            .context("fetch locked dependencies (run cdk-rsx lock after dependency edits)")?;
        Ok(())
    }

    pub fn workspace_metadata(&self, manifest: &Path) -> Result<Value> {
        let output = checked(
            self.for_manifest(manifest, "metadata").args([
                "--format-version",
                "1",
                "--no-deps",
                "--locked",
                "--offline",
            ]),
            &[],
        )
        .context("list app workspace packages")?;
        serde_json::from_slice(&output).context("parse Cargo metadata")
    }

    pub fn metadata(
        &self,
        manifest: &Path,
        features: &[String],
        platform: Option<&str>,
        offline: bool,
    ) -> Result<Value> {
        let mut command = self.for_manifest(manifest, "metadata");
        command.args(["--format-version", "1", "--locked"]).args(features);
        if offline {
            command.arg("--offline");
        }
        if let Some(platform) = platform {
            command.args(["--filter-platform", platform]);
        }
        let output = checked(&mut command, &[]).context(
            "resolve locked app dependencies (run cdk-rsx lock after dependency edits)",
        )?;
        serde_json::from_slice(&output).context("parse Cargo metadata")
    }
}

pub fn project_metadata(path: &Path) -> Result<Value> {
    let manifest = path
        .canonicalize()
        .with_context(|| format!("open {}", path.display()))?;
    let compiler = Compiler::select(false)?;
    compiler.prepare_lock(&manifest, false, false)?;
    compiler.metadata(&manifest, &[], None, false)
}

fn execute(command: &mut Command, locks: &[&File]) -> Result<Output> {
    if !locks.is_empty() {
        // A child writing shared Cargo outputs must keep the advisory locks if
        // the CLI is killed. Clear CLOEXEC only in the child after fork.
        let handles: Vec<_> = locks.iter().map(|file| file.as_raw_fd()).collect();
        // SAFETY: this callback only touches its forked file descriptor table.
        unsafe {
            command.pre_exec(move || {
                for &fd in &handles {
                    if libc::fcntl(fd, libc::F_SETFD, 0) < 0 {
                        return Err(std::io::Error::last_os_error());
                    }
                }
                Ok(())
            });
        }
    }
    command
        .stderr(Stdio::inherit())
        .output()
        .with_context(|| format!("run {}", command.get_program().to_string_lossy()))
}

pub fn checked(command: &mut Command, locks: &[&File]) -> Result<Vec<u8>> {
    let output = execute(command, locks)?;
    ensure!(
        output.status.success(),
        "{} exited with {}",
        command.get_program().to_string_lossy(),
        output.status
    );
    Ok(output.stdout)
}

pub fn lock(directory: &Path, name: &str) -> Result<File> {
    let root = directory.join(".cdk-rsx-build-locks");
    fs::create_dir_all(&root)?;
    let file = OpenOptions::new()
        .create(true)
        .truncate(false)
        .append(true)
        .open(root.join(name))?;
    file.lock()
        .with_context(|| format!("lock {}", root.join(name).display()))?;
    Ok(file)
}

pub fn app_library<'a>(
    metadata: &'a Value,
    manifest: &Path,
    requested: Option<&str>,
) -> Result<(&'a Value, &'a Value)> {
    let packages = metadata["packages"]
        .as_array()
        .context("missing Cargo packages")?;
    let members = metadata["workspace_members"]
        .as_array()
        .context("missing Cargo workspace members")?;
    let available: Vec<_> = packages
        .iter()
        .filter(|package| members.contains(&package["id"]))
        .collect();
    let mut selected: Vec<_> = available
        .iter()
        .copied()
        .filter(|package| match requested {
            Some(name) => package["name"] == name,
            None => package["manifest_path"]
                .as_str()
                .is_some_and(|path| Path::new(path) == manifest),
        })
        .collect();
    if selected.is_empty() && requested.is_none() {
        let defaults = metadata["workspace_default_members"]
            .as_array()
            .context("missing default workspace members")?;
        selected = available
            .iter()
            .copied()
            .filter(|package| defaults.contains(&package["id"]))
            .collect();
    }
    let [package] = selected.as_slice() else {
        let names = available
            .iter()
            .filter_map(|row| row["name"].as_str())
            .collect::<Vec<_>>()
            .join(", ");
        bail!("select one canister with --package (workspace packages: {names})");
    };
    let library = package["targets"]
        .as_array()
        .and_then(|targets| {
            targets.iter().find(|target| {
                target["crate_types"].as_array().is_some_and(|types| {
                    types.iter().any(|kind| kind == "cdylib")
                        && types.iter().any(|kind| kind == "rlib")
                })
            })
        })
        .context("the app needs [lib] crate-type = [\"cdylib\", \"rlib\"]")?;
    Ok((package, library))
}

pub fn compile(command: Command, locks: &[&File]) -> Result<Vec<Value>> {
    compile_with(command, locks, |_| false)
}

pub fn compile_with(
    mut command: Command,
    locks: &[&File],
    format_failure: impl FnOnce(&[Value]) -> bool,
) -> Result<Vec<Value>> {
    // Keep compiler-message events on stdout so a formatter can use spans.
    command.arg("--message-format=json");
    let output = execute(&mut command, locks)?;
    let messages: Vec<Value> = std::str::from_utf8(&output.stdout)?
        .lines()
        .filter(|line| line.starts_with('{'))
        .map(serde_json::from_str)
        .collect::<serde_json::Result<_>>()?;
    if output.status.success() || !format_failure(&messages) {
        for message in &messages {
            if message["reason"] == "compiler-message" {
                eprint!(
                    "{}",
                    message["message"]["rendered"].as_str().unwrap_or_default()
                );
            }
        }
    }
    ensure!(
        output.status.success(),
        "Cargo build exited with {}",
        output.status
    );
    Ok(messages)
}

pub fn artifact<'a>(
    messages: &'a [Value],
    package: &Value,
    library: &Value,
    suffix: &str,
) -> Result<(PathBuf, &'a Value)> {
    let mut selected = messages
        .iter()
        .filter(|message| {
            message["reason"] == "compiler-artifact"
                && message["package_id"] == *package
                && message["target"]["name"] == *library
        })
        .flat_map(|message| {
            message["filenames"]
                .as_array()
                .into_iter()
                .flatten()
                .map(move |file| (file, message))
        })
        .filter_map(|(file, message)| {
            file.as_str()
                .filter(|name| name.ends_with(suffix))
                .map(|name| (PathBuf::from(name), message))
        });
    let pair = selected
        .next()
        .with_context(|| format!("Cargo did not report a {suffix} for {library}"))?;
    ensure!(
        selected.next().is_none(),
        "Cargo reported multiple {suffix} outputs for {library}"
    );
    Ok(pair)
}

pub fn native_interface(
    compiler: &Compiler,
    directory: &Path,
    messages: &[Value],
    package: &Value,
    library: &Value,
    output: &Path,
    locks: &[&File],
) -> Result<()> {
    let stage = output
        .parent()
        .context("missing Wire descriptor output directory")?;
    let (rmeta, _) = artifact(messages, package, library, ".rmeta")?;
    let (rlib, _) = artifact(messages, package, library, ".rlib")?;
    let driver = stage.join("wire-descriptor.rs");
    fs::write(
        &driver,
        r#"extern crate rsx_app;
unsafe extern "Rust" { fn __cdk_rsx_wire_interface() -> Result<String, String>; }
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // SAFETY: the linked application root exports this exact Rust signature.
    println!("{}", unsafe { __cdk_rsx_wire_interface()? });
    Ok(())
}
"#,
    )?;
    let binary = stage.join("wire-descriptor");
    let mut link = compiler.command(&compiler.rustc, directory);
    link.args(["--edition=2024", "--target", &compiler.host])
        .arg(&driver)
        .arg("--extern")
        .arg(format!("rsx_app={}", rmeta.display()))
        .arg("--extern")
        .arg(format!("rsx_app={}", rlib.display()));
    let mut search = BTreeSet::new();
    for message in messages {
        if message["reason"] == "build-script-executed" {
            search.extend(
                message["linked_paths"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .filter_map(Value::as_str)
                    .map(str::to_owned),
            );
        } else if message["reason"] == "compiler-artifact" {
            search.extend(
                message["filenames"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .filter_map(Value::as_str)
                    .filter_map(|file| Path::new(file).parent())
                    .map(|path| format!("dependency={}", path.display())),
            );
        }
    }
    for path in search {
        link.arg("-L").arg(path);
    }
    checked(link.arg("-o").arg(&binary), locks).context("link the native IC Wire descriptor")?;
    fs::write(
        output,
        checked(&mut compiler.command(&binary, directory), locks)?,
    )?;
    Ok(())
}