wasi_virt_layer_cli/wasm_stream/
pipeline.rs1use eyre::Context as _;
2
3pub trait StreamPass: Send + Sync {
4 fn run(&mut self, input_wasm: &[u8]) -> eyre::Result<Vec<u8>>;
7}
8
9pub trait StreamChecker: Send + Sync {
10 fn check(&mut self, payload: &wasmparser::Payload) -> eyre::Result<()>;
11}
12
13pub struct ParallelCheckStreamPass {
14 checkers: Vec<Box<dyn StreamChecker>>,
15}
16
17impl ParallelCheckStreamPass {
18 pub fn new(checkers: Vec<Box<dyn StreamChecker>>) -> Self {
19 Self { checkers }
20 }
21}
22
23impl StreamPass for ParallelCheckStreamPass {
24 fn run(&mut self, input_wasm: &[u8]) -> eyre::Result<Vec<u8>> {
25 for payload in wasmparser::Parser::new(0).parse_all(input_wasm) {
26 let payload = payload?;
27 for checker in &mut self.checkers {
31 checker.check(&payload)?;
32 }
33 }
34 Ok(input_wasm.to_vec())
35 }
36}
37
38pub struct Pipeline {
40 passes: Vec<Box<dyn StreamPass>>,
41}
42
43pub fn par_process_code_section<F>(
46 code_section: wasmparser::CodeSectionReader<'_>,
47 transform: F,
48) -> eyre::Result<wasm_encoder::CodeSection>
49where
50 F: Fn(usize, wasmparser::FunctionBody<'_>) -> eyre::Result<wasm_encoder::Function>
51 + Sync
52 + Send,
53{
54 use eyre::Context;
55 use rayon::prelude::*;
56
57 let bodies = code_section
59 .into_iter()
60 .collect::<Result<Vec<_>, _>>()
61 .wrap_err("Failed to read function bodies")?;
62
63 let encoded_functions = bodies
65 .into_par_iter()
66 .enumerate()
67 .map(|(i, body)| transform(i, body))
68 .collect::<eyre::Result<Vec<_>>>()?;
69
70 let mut new_code_section = wasm_encoder::CodeSection::new();
72 for encoded_func in encoded_functions {
73 new_code_section.function(&encoded_func);
74 }
75
76 Ok(new_code_section)
77}
78
79impl Pipeline {
80 pub fn new() -> Self {
82 Self { passes: Vec::new() }
83 }
84
85 pub fn add_pass(&mut self, pass: Box<dyn StreamPass>) {
87 self.passes.push(pass);
88 }
89
90 pub fn run(&mut self, input_wasm: &[u8]) -> eyre::Result<Vec<u8>> {
92 let mut current_wasm = input_wasm.to_vec();
93 log::debug!("PIPELINE RUN IS EXECUTING!");
94
95 let mut i = 0;
96 for pass in &mut self.passes {
97 log::debug!("RUNNING STREAM PASS #{}", i);
98 current_wasm = pass
99 .run(¤t_wasm)
100 .wrap_err_with(|| format!("Failed in stream pass #{i}"))?;
101 i += 1;
102 }
103
104 Ok(current_wasm)
105 }
106}