OXYGENHUB
# 1a50d4dae89c oxygenflow / crates / flow / src / wasm.rs
25.0 KiB · Rust · last changed Runner builds fetched through the swarm (refs #84); the WASM tier as a cargo feature, off for Haiku (refs #91) 7 days ago source blame history raw
1
//! The WASM tier (spec §4.1, oxygenflow#75): a job's `exec` names a WASI
2
//! preview 1 module, or a glob of modules run one after another, which
3
//! wasmtime runs with the job's workspace at `/src` and nothing else: no
4
//! network, no other file of the runner. Every runner can offer it, and it
5
//! is the tier phones and browsers run (docs/handover.md).
6
//!
7
//! As in the syscall tier the module runs in a child of the runner
8
//! (`flow __wasm SPEC`), so the runner streams its output as it comes,
9
//! stops it at the time limit or when the run is cancelled, and measures
10
//! its memory the same way; wasmtime itself also holds it to the sandbox's
11
//! memory limit.
12
13
use crate::microvm::{Outcome, Sink};
14
use crate::syscall::{lines, self_hash, FAILED};
15
use anyhow::{bail, Context, Result};
16
use flow_core::api::Record;
17
use flow_core::{Environment, Job, MountSource, Sandbox};
18
use serde::{Deserialize, Serialize};
19
use std::path::{Path, PathBuf};
20
use std::sync::mpsc;
21
use std::time::{Duration, Instant};
22
23
/// The runtime, named in every receipt this tier writes.
24
pub const WASMTIME: &str = "49.0.4";
25
26
/// Whether this build has the tier: a build for a system wasmtime does not
27
/// run on (Haiku, oxygenflow#91) leaves it out with the `wasm` feature, and
28
/// its runner does not offer it.
29
pub const AVAILABLE: bool = cfg!(feature = "wasm");
30
31
/// What a build without the tier says when asked to run a job in it.
32
const WITHOUT: &str = "this flow was built without the WASM tier (the `wasm` feature): it runs on systems wasmtime supports";
33
34
/// A line the helper writes to say something about the job itself (which
35
/// module starts), shown as the runner's own note rather than the job's.
36
const NOTE: &str = "\u{1e}N ";
37
38
/// The exit code for a module that trapped (crashed) rather than exiting.
39
#[cfg(feature = "wasm")]
40
const TRAPPED: i32 = 134;
41
42
/// What the helper runs, written by the runner for `flow __wasm`.
43
#[derive(Serialize, Deserialize)]
44
struct Spec {
45
    /// The job's files, preopened as `/src` (and as the current directory).
46
    workspace: PathBuf,
47
    /// The modules to run in turn, relative to the workspace.
48
    modules: Vec<String>,
49
    /// The arguments after the module.
50
    args: Vec<String>,
51
    env: Vec<(String, String)>,
52
    memory_mib: u32,
53
    /// The job's mounts: a directory of the runner and where the module sees it.
54
    preopens: Vec<(PathBuf, String)>,
55
}
56
57
/// The receipt environment of a job in this tier: the runtime and its
58
/// version, this runner's binary, the memory allowed, and every module run
59
/// with its hash, so the receipt says exactly what code ran.
60
pub fn environment(sandbox: &Sandbox, job: &Job, modules: &[(String, String)]) -> Environment {
61
    Environment {
62
        runtime: "wasm".into(),
63
        parts: vec![
64
            ("wasmtime".into(), WASMTIME.into()),
65
            ("flow".into(), self_hash().to_string()),
66
            ("memory_mib".into(), sandbox.memory_mib.to_string()),
67
        ]
68
        .into_iter()
69
        .chain(modules.iter().map(|(path, hash)| (format!("module {path}"), hash.clone())))
70
        .collect(),
71
        rootfs: String::new(),
72
        argv: job.exec.clone(),
73
        env: job.env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
74
    }
75
}
76
77
/// The modules `program` names in `workspace`: one file, or the files a
78
/// glob matches (`*` in its last part only), sorted. A path may start with
79
/// `/src/`, where the module sees the workspace.
80
pub fn modules(workspace: &Path, program: &str) -> Result<Vec<String>> {
81
    let rel = program.strip_prefix("/src/").unwrap_or(program).trim_start_matches("./");
82
    if rel.is_empty() || rel.starts_with('/') || rel.split('/').any(|p| p == "..") {
83
        bail!("module {program:?}: give a path inside the job's files, such as target/wasm32-wasip1/debug/app.wasm");
84
    }
85
    let (dir, last) = rel.rsplit_once('/').unwrap_or(("", rel));
86
    if dir.contains('*') {
87
        bail!("module {program:?}: only the file name may hold `*`");
88
    }
89
    if !last.contains('*') {
90
        if !workspace.join(rel).is_file() {
91
            bail!("module {rel} is not among the job's files (its scope or an earlier job's artifact)");
92
        }
93
        return Ok(vec![rel.to_string()]);
94
    }
95
    let mut found: Vec<String> = std::fs::read_dir(workspace.join(dir))
96
        .with_context(|| format!("module {program:?}: the directory {dir} is not among the job's files"))?
97
        .filter_map(|e| e.ok())
98
        .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
99
        .filter_map(|e| e.file_name().into_string().ok())
100
        .filter(|name| wildcard(last, name))
101
        .map(|name| if dir.is_empty() { name } else { format!("{dir}/{name}") })
102
        .collect();
103
    found.sort();
104
    if found.is_empty() {
105
        bail!("no module matches {program:?}");
106
    }
107
    Ok(found)
108
}
109
110
/// Whether `name` matches `pattern`, where `*` stands for any run of characters.
111
fn wildcard(pattern: &str, name: &str) -> bool {
112
    let parts: Vec<&str> = pattern.split('*').collect();
113
    let (first, last) = (parts[0], parts[parts.len() - 1]);
114
    if parts.len() == 1 {
115
        return pattern == name;
116
    }
117
    if !name.starts_with(first) || !name[first.len()..].ends_with(last) || name.len() < first.len() + last.len() {
118
        return false;
119
    }
120
    let mut rest = &name[first.len()..name.len() - last.len()];
121
    for middle in &parts[1..parts.len() - 1] {
122
        match rest.find(middle) {
123
            Some(i) => rest = &rest[i + middle.len()..],
124
            None => return false,
125
        }
126
    }
127
    true
128
}
129
130
/// Run `job` in this tier with its files in `workspace` (as the syscall
131
/// tier lays them out); `scratch` holds the helper's spec and the job's
132
/// mounts.
133
pub fn run(sandbox: &Sandbox, job: &Job, workspace: &Path, scratch: &Path, timeout: Duration, sink: &mut dyn Sink) -> Result<Outcome> {
134
    if !AVAILABLE {
135
        bail!("job {}: {WITHOUT}", job.name);
136
    }
137
    if !job.secrets.is_empty() || !job.identities.is_empty() {
138
        bail!("job {}: the WASM tier takes no secrets or identities yet; run it in a microvm or syscall sandbox", job.name);
139
    }
140
    let Some(program) = job.exec.first() else { bail!("job {}: exec names no module", job.name) };
141
    let modules = modules(workspace, program)?;
142
    let hashed: Vec<(String, String)> =
143
        modules.iter().map(|m| Ok((m.clone(), crate::home::hash_file(&workspace.join(m))?))).collect::<Result<_>>()?;
144
    let environment = environment(sandbox, job, &hashed);
145
    let mut preopens = Vec::new();
146
    let mut disks = 0;
147
    for (i, m) in job.mounts.iter().enumerate() {
148
        let dir = match m.source {
149
            MountSource::Disk => {
150
                disks += 1;
151
                crate::syscall::disk_dir(scratch, disks - 1)
152
            }
153
            MountSource::Tmpfs => scratch.join(format!("tmpfs-{i}")),
154
        };
155
        std::fs::create_dir_all(&dir)?;
156
        preopens.push((dir, m.target.clone()));
157
    }
158
    let spec = Spec {
159
        workspace: workspace.to_path_buf(),
160
        modules,
161
        args: job.exec[1..].to_vec(),
162
        env: job.env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
163
        memory_mib: sandbox.memory_mib,
164
        preopens,
165
    };
166
    if in_process() {
167
        return run_in_thread(&spec, environment, timeout, sink);
168
    }
169
    let spec_path = scratch.join("wasm.json");
170
    std::fs::write(&spec_path, serde_json::to_vec(&spec)?)?;
171
172
    let started = Instant::now();
173
    let mut child = std::process::Command::new(crate::tier::self_exe())
174
        .arg("__wasm")
175
        .arg(&spec_path)
176
        .env_clear()
177
        .current_dir(scratch)
178
        .stdin(std::process::Stdio::null())
179
        .stdout(std::process::Stdio::piped())
180
        .stderr(std::process::Stdio::piped())
181
        .spawn()
182
        .context("start the WASM helper")?;
183
    let (tx, rx) = mpsc::channel::<(bool, Vec<u8>)>();
184
    let out = child.stdout.take().unwrap();
185
    let err = child.stderr.take().unwrap();
186
    let tx2 = tx.clone();
187
    let readers = [std::thread::spawn(move || lines(out, true, tx)), std::thread::spawn(move || lines(err, false, tx2))];
188
    let t = |s: &Instant| s.elapsed().as_millis() as u64;
189
    let (mut timed_out, mut cancelled, mut failed_to_start) = (false, false, false);
190
    let mut peak_memory_mib = None;
191
    let deadline = started + timeout;
192
    loop {
193
        if let Some(m) = crate::facts::peak_rss_mib(child.id()) {
194
            peak_memory_mib = Some(m);
195
        }
196
        match rx.recv_timeout(Duration::from_millis(200)) {
197
            Ok((stdout, line)) => {
198
                let text = String::from_utf8_lossy(&line).into_owned();
199
                let rec = |stream: &str, text: &str| Record { t: t(&started), stream: stream.into(), text: text.into() };
200
                if let Some(note) = text.strip_prefix(NOTE).filter(|_| !stdout) {
201
                    sink.record(rec("flow", note));
202
                } else if let Some(why) = text.strip_prefix(FAILED).filter(|_| !stdout) {
203
                    failed_to_start = true;
204
                    sink.record(rec("flow", &format!("the WASM tier could not run the job: {why}")));
205
                } else {
206
                    sink.record(rec(if stdout { "out" } else { "err" }, &text));
207
                }
208
            }
209
            Err(mpsc::RecvTimeoutError::Timeout) => {}
210
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
211
        }
212
        if !timed_out && !cancelled && sink.cancelled() {
213
            cancelled = true;
214
            let _ = child.kill();
215
            sink.record(Record { t: t(&started), stream: "flow".into(), text: "stopped: the run was cancelled".into() });
216
        }
217
        if Instant::now() >= deadline && !timed_out && !cancelled {
218
            timed_out = true;
219
            let _ = child.kill();
220
            sink.record(Record {
221
                t: t(&started),
222
                stream: "flow".into(),
223
                text: format!("stopped at the time limit of {} s", timeout.as_secs()),
224
            });
225
        }
226
    }
227
    let status = child.wait()?;
228
    for r in readers {
229
        let _ = r.join();
230
    }
231
    let _ = std::fs::remove_file(&spec_path);
232
    let exit_code = status.code();
233
    if exit_code.is_none() && !timed_out && !cancelled && !failed_to_start {
234
        sink.record(Record {
235
            t: t(&started),
236
            stream: "flow".into(),
237
            text: format!("the WASM helper ended without an exit code ({status})"),
238
        });
239
    }
240
    Ok(Outcome {
241
        exit_code: if timed_out || cancelled { None } else { exit_code },
242
        duration_ms: t(&started),
243
        environment,
244
        timed_out,
245
        cancelled,
246
        peak_memory_mib,
247
        pruned: Vec::new(),
248
    })
249
}
250
251
/// Whether modules run in a thread of this process rather than in a child
252
/// `flow __wasm`: on Android, where the runner is a library inside an app
253
/// that cannot start itself as a command (oxygenhub-android#8), and
254
/// anywhere `FLOW_WASM_IN_PROCESS` is set (how the tests check this way).
255
pub fn in_process() -> bool {
256
    cfg!(target_os = "android") || std::env::var_os("FLOW_WASM_IN_PROCESS").is_some()
257
}
258
259
#[cfg(feature = "wasm")]
260
/// The most of a module's output kept before it is read, per stream.
261
const PIPE_BYTES: usize = 64 << 20;
262
263
#[cfg(feature = "wasm")]
264
/// Run the spec's modules in a thread of this process, streaming their
265
/// output as it comes: the pipes are read every 100 ms, and a time limit
266
/// or a cancelled run interrupts the module through wasmtime's epoch.
267
fn run_in_thread(spec: &Spec, environment: Environment, timeout: Duration, sink: &mut dyn Sink) -> Result<Outcome> {
268
    use wasmtime_wasi::p2::pipe::MemoryOutputPipe;
269
    let mut config = wasmtime::Config::new();
270
    config.epoch_interruption(true);
271
    let engine = ww(wasmtime::Engine::new(&config), || "start wasmtime".into())?;
272
    let (stdout, stderr) = (MemoryOutputPipe::new(PIPE_BYTES), MemoryOutputPipe::new(PIPE_BYTES));
273
    let (notes_tx, notes) = mpsc::channel::<String>();
274
    let io = Io::Pipes { stdout: stdout.clone(), stderr: stderr.clone(), notes: notes_tx };
275
    let started = Instant::now();
276
    let t = |s: &Instant| s.elapsed().as_millis() as u64;
277
    let deadline = started + timeout;
278
    let (mut timed_out, mut cancelled) = (false, false);
279
    // Bytes of each stream already passed on, and the part line not ended yet.
280
    let mut said = [(0usize, Vec::<u8>::new()), (0usize, Vec::<u8>::new())];
281
    let mut pass_on = |sink: &mut dyn Sink, last: bool| {
282
        for (i, pipe) in [&stdout, &stderr].into_iter().enumerate() {
283
            let all = pipe.contents();
284
            let (offset, partial) = &mut said[i];
285
            partial.extend_from_slice(&all[*offset..]);
286
            *offset = all.len();
287
            while let Some(n) = partial.iter().position(|b| *b == b'\n') {
288
                let line: Vec<u8> = partial.drain(..=n).collect();
289
                let text = String::from_utf8_lossy(&line[..line.len() - 1]).into_owned();
290
                sink.record(Record { t: t(&started), stream: if i == 0 { "out" } else { "err" }.into(), text });
291
            }
292
            if last && !partial.is_empty() {
293
                let text = String::from_utf8_lossy(partial).into_owned();
294
                partial.clear();
295
                sink.record(Record { t: t(&started), stream: if i == 0 { "out" } else { "err" }.into(), text });
296
            }
297
        }
298
        while let Ok(note) = notes.try_recv() {
299
            sink.record(Record { t: t(&started), stream: "flow".into(), text: note });
300
        }
301
    };
302
    let ran = std::thread::scope(|scope| {
303
        let worker = scope.spawn(|| run_modules(&engine, spec, &io));
304
        while !worker.is_finished() {
305
            std::thread::sleep(Duration::from_millis(100));
306
            pass_on(sink, false);
307
            // Once stopped, keep moving the epoch: a store made after the
308
            // first increment (its module still compiling when the time
309
            // limit or the cancel came) sets its deadline one epoch past
310
            // that, and a single increment would never reach it (#93).
311
            if timed_out || cancelled {
312
                engine.increment_epoch();
313
            }
314
            if !timed_out && !cancelled && sink.cancelled() {
315
                cancelled = true;
316
                engine.increment_epoch();
317
                sink.record(Record { t: t(&started), stream: "flow".into(), text: "stopped: the run was cancelled".into() });
318
            }
319
            if Instant::now() >= deadline && !timed_out && !cancelled {
320
                timed_out = true;
321
                engine.increment_epoch();
322
                sink.record(Record {
323
                    t: t(&started),
324
                    stream: "flow".into(),
325
                    text: format!("stopped at the time limit of {} s", timeout.as_secs()),
326
                });
327
            }
328
        }
329
        worker.join().unwrap_or_else(|_| Err(anyhow::anyhow!("the WASM worker panicked")))
330
    });
331
    pass_on(sink, true);
332
    let (exit_code, peak) = match ran {
333
        Ok((code, peak)) => (Some(code), Some(peak)),
334
        Err(e) => {
335
            sink.record(Record { t: t(&started), stream: "flow".into(), text: format!("the WASM tier could not run the job: {e:#}") });
336
            (Some(125), None)
337
        }
338
    };
339
    Ok(Outcome {
340
        exit_code: if timed_out || cancelled { None } else { exit_code },
341
        duration_ms: t(&started),
342
        environment,
343
        timed_out,
344
        cancelled,
345
        peak_memory_mib: peak.map(|b| (b as u64).div_ceil(1 << 20)),
346
        pruned: Vec::new(),
347
    })
348
}
349
350
#[cfg(feature = "wasm")]
351
/// `flow __wasm SPEC`: run the spec's modules in turn, each in a fresh
352
/// instance; the exit code is the first non-zero one, after all have run,
353
/// so one failing module does not hide another's results.
354
pub fn wasm_main(spec_path: &Path) -> i32 {
355
    let ran = (|| {
356
        let spec: Spec = serde_json::from_slice(&std::fs::read(spec_path)?).context("read the spec")?;
357
        let engine = ww(wasmtime::Engine::new(&wasmtime::Config::new()), || "start wasmtime".into())?;
358
        run_modules(&engine, &spec, &Io::Inherit)
359
    })();
360
    match ran {
361
        Ok((code, _)) => code,
362
        Err(e) => {
363
            eprintln!("{FAILED}{e:#}");
364
            125
365
        }
366
    }
367
}
368
369
/// `flow __wasm SPEC` in a build without the tier: says so.
370
#[cfg(not(feature = "wasm"))]
371
pub fn wasm_main(_spec_path: &Path) -> i32 {
372
    eprintln!("{FAILED}{WITHOUT}");
373
    125
374
}
375
376
#[cfg(not(feature = "wasm"))]
377
fn run_in_thread(_spec: &Spec, _environment: Environment, _timeout: Duration, _sink: &mut dyn Sink) -> Result<Outcome> {
378
    bail!(WITHOUT)
379
}
380
381
#[cfg(feature = "wasm")]
382
/// wasmtime's own error, as this crate's: with its whole chain of causes.
383
fn ww<T>(r: wasmtime::Result<T>, what: impl FnOnce() -> String) -> Result<T> {
384
    r.map_err(|e| anyhow::anyhow!("{}: {e:#}", what()))
385
}
386
387
#[cfg(feature = "wasm")]
388
/// Where a module's output and the tier's notes go: inherited by the
389
/// helper process (notes on stderr, marked), or pipes the runner reads.
390
enum Io {
391
    Inherit,
392
    Pipes {
393
        stdout: wasmtime_wasi::p2::pipe::MemoryOutputPipe,
394
        stderr: wasmtime_wasi::p2::pipe::MemoryOutputPipe,
395
        notes: mpsc::Sender<String>,
396
    },
397
}
398
399
#[cfg(feature = "wasm")]
400
impl Io {
401
    fn note(&self, text: String) {
402
        match self {
403
            Io::Inherit => eprintln!("{NOTE}{text}"),
404
            Io::Pipes { notes, .. } => {
405
                let _ = notes.send(text);
406
            }
407
        }
408
    }
409
}
410
411
#[cfg(feature = "wasm")]
412
/// The sandbox's memory limit, and the most a module asked for within it.
413
struct Limits {
414
    memory: usize,
415
    peak: usize,
416
}
417
418
#[cfg(feature = "wasm")]
419
impl wasmtime::ResourceLimiter for Limits {
420
    fn memory_growing(&mut self, _current: usize, desired: usize, maximum: Option<usize>) -> wasmtime::Result<bool> {
421
        let ok = desired <= self.memory && maximum.is_none_or(|m| desired <= m);
422
        if ok {
423
            self.peak = self.peak.max(desired);
424
        }
425
        Ok(ok)
426
    }
427
428
    fn table_growing(&mut self, _current: usize, desired: usize, maximum: Option<usize>) -> wasmtime::Result<bool> {
429
        Ok(maximum.is_none_or(|m| desired <= m))
430
    }
431
}
432
433
#[cfg(feature = "wasm")]
434
struct State {
435
    wasi: wasmtime_wasi::p1::WasiP1Ctx,
436
    limits: Limits,
437
}
438
439
#[cfg(feature = "wasm")]
440
/// Run each module in turn: the first non-zero exit code after all ran,
441
/// and the most memory any of them held, in bytes.
442
fn run_modules(engine: &wasmtime::Engine, spec: &Spec, io: &Io) -> Result<(i32, usize)> {
443
    let mut linker: wasmtime::Linker<State> = wasmtime::Linker::new(engine);
444
    ww(wasmtime_wasi::p1::add_to_linker_sync(&mut linker, |s: &mut State| &mut s.wasi), || "link WASI".into())?;
445
    let (mut first_failure, mut peak) = (0, 0);
446
    for path in &spec.modules {
447
        if spec.modules.len() > 1 {
448
            io.note(format!("running {path}"));
449
        }
450
        let (code, held) = run_module(engine, &linker, spec, path, io)?;
451
        peak = peak.max(held);
452
        if spec.modules.len() > 1 {
453
            io.note(format!("{path}: exit {code}"));
454
        }
455
        if first_failure == 0 && code != 0 {
456
            first_failure = code;
457
        }
458
    }
459
    Ok((first_failure, peak))
460
}
461
462
#[cfg(feature = "wasm")]
463
fn run_module(engine: &wasmtime::Engine, linker: &wasmtime::Linker<State>, spec: &Spec, path: &str, io: &Io) -> Result<(i32, usize)> {
464
    use wasmtime_wasi::{FsPerms, WasiCtxBuilder};
465
    let module = ww(wasmtime::Module::from_file(engine, spec.workspace.join(path)), || format!("module {path} does not load"))?;
466
    let name = path.rsplit('/').next().unwrap_or(path);
467
    let mut argv = vec![name.to_string()];
468
    argv.extend(spec.args.iter().cloned());
469
    let mut wasi = WasiCtxBuilder::new();
470
    match io {
471
        Io::Inherit => {
472
            wasi.inherit_stdout().inherit_stderr();
473
        }
474
        Io::Pipes { stdout, stderr, .. } => {
475
            wasi.stdout(stdout.clone()).stderr(stderr.clone());
476
        }
477
    }
478
    wasi.args(&argv).envs(&spec.env).env("PWD", "/src").allow_blocking_current_thread(true);
479
    let open = |wasi: &mut WasiCtxBuilder, dir: &Path, at: &str| {
480
        ww(wasi.preopened_dir(dir, at, FsPerms::ReadWrite).map(|_| ()), || format!("open {} as {at}", dir.display()))
481
    };
482
    open(&mut wasi, &spec.workspace, "/src")?;
483
    // Relative paths resolve against the workspace too.
484
    open(&mut wasi, &spec.workspace, ".")?;
485
    for (dir, target) in &spec.preopens {
486
        open(&mut wasi, dir, target)?;
487
    }
488
    let limits = Limits { memory: spec.memory_mib as usize * 1024 * 1024, peak: 0 };
489
    let mut store = wasmtime::Store::new(engine, State { wasi: wasi.build_p1(), limits });
490
    store.limiter(|s| &mut s.limits);
491
    // With epoch interruption on (in process), one tick from now traps:
492
    // the runner ticks only to stop the module.
493
    store.set_epoch_deadline(1);
494
    let instance = ww(linker.instantiate(&mut store, &module), || format!("module {path} cannot start here"))?;
495
    let start =
496
        ww(instance.get_typed_func::<(), ()>(&mut store, "_start"), || format!("module {path} has no _start: is it a WASI command?"))?;
497
    let code = match start.call(&mut store, ()) {
498
        Ok(()) => 0,
499
        Err(e) => match e.downcast_ref::<wasmtime_wasi::I32Exit>() {
500
            Some(exit) => exit.0,
501
            None => {
502
                io.note(format!("{path} trapped: {e:#}"));
503
                TRAPPED
504
            }
505
        },
506
    };
507
    Ok((code, store.data().limits.peak))
508
}
509
510
#[cfg(all(test, feature = "wasm"))]
511
mod tests {
512
    use super::*;
513
514
    /// A spec running `text` (WAT) as the only module, with 64 MiB.
515
    fn spec_of(dir: &Path, text: &str) -> Spec {
516
        std::fs::write(dir.join("m.wasm"), wat::parse_str(text).unwrap()).unwrap();
517
        Spec { workspace: dir.to_path_buf(), modules: vec!["m.wasm".into()], args: vec![], env: vec![], memory_mib: 64, preopens: vec![] }
518
    }
519
520
    fn env() -> Environment {
521
        Environment { runtime: "wasm".into(), parts: vec![], rootfs: String::new(), argv: vec![], env: vec![] }
522
    }
523
524
    /// Records, and whether to say the run was cancelled.
525
    struct Collect(Vec<Record>, bool);
526
    impl Sink for Collect {
527
        fn record(&mut self, r: Record) {
528
            self.0.push(r);
529
        }
530
        fn cancelled(&mut self) -> bool {
531
            self.1
532
        }
533
    }
534
535
    const PRINT: &str = r#"(module
536
      (import "wasi_snapshot_preview1" "fd_write" (func $w (param i32 i32 i32 i32) (result i32)))
537
      (memory (export "memory") 2)
538
      (data (i32.const 16) "line one\nline two")
539
      (func (export "_start")
540
        (i32.store (i32.const 0) (i32.const 16)) (i32.store (i32.const 4) (i32.const 17))
541
        (drop (call $w (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 8)))))"#;
542
543
    const SPIN: &str = r#"(module (func (export "_start") (loop $l (br $l))))"#;
544
545
    #[test]
546
    fn in_process_output_streams_as_lines() {
547
        let dir = tempfile::tempdir().unwrap();
548
        let mut sink = Collect(vec![], false);
549
        let o = run_in_thread(&spec_of(dir.path(), PRINT), env(), Duration::from_secs(30), &mut sink).unwrap();
550
        assert_eq!(o.exit_code, Some(0));
551
        let out: Vec<&str> = sink.0.iter().filter(|r| r.stream == "out").map(|r| r.text.as_str()).collect();
552
        assert_eq!(out, ["line one", "line two"], "a last line without its newline still comes");
553
        assert_eq!(o.peak_memory_mib, Some(1), "two 64 KiB pages, in whole MiB");
554
    }
555
556
    #[test]
557
    fn in_process_stops_at_the_time_limit_and_when_cancelled() {
558
        let dir = tempfile::tempdir().unwrap();
559
        let mut sink = Collect(vec![], false);
560
        let started = Instant::now();
561
        let o = run_in_thread(&spec_of(dir.path(), SPIN), env(), Duration::from_millis(300), &mut sink).unwrap();
562
        assert!(o.timed_out && o.exit_code.is_none(), "{:?}", sink.0);
563
        assert!(started.elapsed() < Duration::from_secs(5), "the endless loop was interrupted");
564
        let mut sink = Collect(vec![], true);
565
        let o = run_in_thread(&spec_of(dir.path(), SPIN), env(), Duration::from_secs(30), &mut sink).unwrap();
566
        assert!(o.cancelled && o.exit_code.is_none());
567
        assert!(sink.0.iter().any(|r| r.text == "stopped: the run was cancelled"));
568
    }
569
570
    #[test]
571
    fn globs_match_names_with_stars() {
572
        assert!(wildcard("*.wasm", "oxy_core-1a2b.wasm"));
573
        assert!(wildcard("oxy_core-*.wasm", "oxy_core-1a2b.wasm"));
574
        assert!(!wildcard("oxy_core-*.wasm", "oxy_core-1a2b.d"));
575
        assert!(wildcard("a*b*c", "aXbYc") && !wildcard("a*b*c", "aXcYb"));
576
        assert!(wildcard("plain.wasm", "plain.wasm") && !wildcard("plain.wasm", "other.wasm"));
577
    }
578
579
    #[test]
580
    fn modules_are_files_of_the_job() {
581
        let dir = tempfile::tempdir().unwrap();
582
        let deps = dir.path().join("target/wasm32-wasip1/debug/deps");
583
        std::fs::create_dir_all(&deps).unwrap();
584
        for f in ["b-2.wasm", "a-1.wasm", "a-1.d"] {
585
            std::fs::write(deps.join(f), b"").unwrap();
586
        }
587
        let ws = dir.path();
588
        assert_eq!(
589
            modules(ws, "/src/target/wasm32-wasip1/debug/deps/*.wasm").unwrap(),
590
            ["target/wasm32-wasip1/debug/deps/a-1.wasm", "target/wasm32-wasip1/debug/deps/b-2.wasm"]
591
        );
592
        assert_eq!(modules(ws, "./target/wasm32-wasip1/debug/deps/b-2.wasm").unwrap(), ["target/wasm32-wasip1/debug/deps/b-2.wasm"]);
593
        assert!(modules(ws, "target/wasm32-wasip1/debug/deps/*.so").unwrap_err().to_string().contains("no module matches"));
594
        assert!(modules(ws, "../etc/passwd").is_err());
595
        assert!(modules(ws, "/etc/x.wasm").is_err());
596
        assert!(modules(ws, "target/*/debug/a.wasm").unwrap_err().to_string().contains("only the file name"));
597
    }
598
}