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
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"),
        ]
    })
}

/// Reject explicit exclusions that would hide the package's Cargo or Rust inputs.
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)?;
            // A crate-root build.rs can share a directory with generated outputs.
            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() {
            // Never omit the manifest, entry files, or effective Cargo configuration.
            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'])
}

/// Move private staged outputs into their public names. The caller owns the
/// output lock and stages on the same filesystem as the output.
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)
}