spin_componentize/
lib.rs

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
#![deny(warnings)]

use {
    anyhow::{anyhow, Context, Result},
    convert::{IntoEntityType, IntoExportKind},
    module_info::ModuleInfo,
    std::{borrow::Cow, collections::HashSet},
    wasm_encoder::{CustomSection, ExportSection, ImportSection, Module, RawSection},
    wasmparser::{Encoding, Parser, Payload},
    wit_component::{metadata, ComponentEncoder},
};

pub mod bugs;

#[cfg(test)]
mod abi_conformance;
mod convert;
mod module_info;

const SPIN_ADAPTER: &[u8] = include_bytes!(concat!(
    env!("OUT_DIR"),
    "/wasm32-unknown-unknown/release/wasi_snapshot_preview1_spin.wasm"
));
const PREVIEW1_ADAPTER: &[u8] = include_bytes!(concat!(
    env!("OUT_DIR"),
    "/wasm32-unknown-unknown/release/wasi_snapshot_preview1_upstream.wasm"
));

const COMMAND_ADAPTER: &[u8] = include_bytes!(concat!(
    env!("OUT_DIR"),
    "/wasm32-unknown-unknown/release/wasi_snapshot_preview1_command.wasm"
));

static ADAPTER_NAME: &str = "wasi_snapshot_preview1";
static CUSTOM_SECTION_NAME: &str = "component-type:reactor";
static WORLD_NAME: &str = "reactor";

static EXPORT_INTERFACES: &[(&str, &str)] = &[
    ("handle-redis-message", "inbound-redis"),
    ("handle-http-request", "inbound-http"),
];

pub fn componentize_if_necessary(module_or_component: &[u8]) -> Result<Cow<[u8]>> {
    for payload in Parser::new(0).parse_all(module_or_component) {
        if let Payload::Version { encoding, .. } = payload.context("unable to parse binary")? {
            return match encoding {
                Encoding::Component => Ok(Cow::Borrowed(module_or_component)),
                Encoding::Module => componentize(module_or_component).map(Cow::Owned),
            };
        }
    }
    Err(anyhow!("unable to determine wasm binary encoding"))
}

pub fn componentize(module: &[u8]) -> Result<Vec<u8>> {
    let module_info = ModuleInfo::from_module(module)?;
    match WitBindgenVersion::detect(&module_info)? {
        WitBindgenVersion::V0_2OrNone => componentize_old_module(module, &module_info),
        WitBindgenVersion::GreaterThanV0_4 => componentize_new_bindgen(module),
        WitBindgenVersion::Other(other) => Err(anyhow::anyhow!(
            "cannot adapt modules created with wit-bindgen version {other}"
        )),
    }
}

/// In order to properly componentize modules, we need to know which
/// version of wit-bindgen was used
#[derive(Debug)]
enum WitBindgenVersion {
    GreaterThanV0_4,
    V0_2OrNone,
    Other(String),
}

impl WitBindgenVersion {
    fn detect(module_info: &ModuleInfo) -> Result<Self> {
        if let Some(processors) = module_info.bindgen_processors() {
            let bindgen_version = processors
                .iter()
                .find_map(|(key, value)| key.starts_with("wit-bindgen").then_some(value.as_str()));
            if let Some(v) = bindgen_version {
                let mut parts = v.split('.');
                let Some(major) = parts.next().and_then(|p| p.parse::<u8>().ok()) else {
                    return Ok(Self::Other(v.to_owned()));
                };
                let Some(minor) = parts.next().and_then(|p| p.parse::<u8>().ok()) else {
                    return Ok(Self::Other(v.to_owned()));
                };
                if (major == 0 && minor < 5) || major >= 1 {
                    return Ok(Self::Other(v.to_owned()));
                }
                // Either there should be no patch version or nothing after patch
                if parts.next().is_none() || parts.next().is_none() {
                    return Ok(Self::GreaterThanV0_4);
                } else {
                    return Ok(Self::Other(v.to_owned()));
                }
            }
        }
        Ok(Self::V0_2OrNone)
    }
}

/// Modules produced with wit-bindgen 0.5 and newer only need wasi preview 1 to preview 2 adapter
pub fn componentize_new_bindgen(module: &[u8]) -> Result<Vec<u8>> {
    ComponentEncoder::default()
        .validate(true)
        .module(module)?
        .adapter("wasi_snapshot_preview1", PREVIEW1_ADAPTER)?
        .encode()
}

/// Modules *not* produced with wit-bindgen >= 0.5 could be old wit-bindgen or no wit-bindgen
pub fn componentize_old_module(module: &[u8], module_info: &ModuleInfo) -> Result<Vec<u8>> {
    // If the module has a _start export and doesn't obviously use wit-bindgen
    // it is likely an old p1 command module.
    if module_info.has_start_export && !module_info.probably_uses_wit_bindgen() {
        bugs::WasiLibc377Bug::check(module_info)?;
        componentize_command(module)
    } else {
        componentize_old_bindgen(module)
    }
}

/// Modules produced with wit-bindgen 0.2 need more extensive adaption
pub fn componentize_old_bindgen(module: &[u8]) -> Result<Vec<u8>> {
    let (module, exports) = retarget_imports_and_get_exports(ADAPTER_NAME, module)?;
    let allowed = exports
        .into_iter()
        .filter_map(|export| {
            EXPORT_INTERFACES
                .iter()
                .find_map(|(k, v)| (*k == export).then_some(*v))
        })
        .collect::<HashSet<&str>>();

    let (adapter, mut bindgen) = metadata::decode(SPIN_ADAPTER)?;
    let adapter = adapter.expect(
        "adapter module was malformed, and did not contain a 'component-type' custom section",
    );

    let world = bindgen
        .resolve
        .worlds
        .iter()
        .find_map(|(k, v)| (v.name == WORLD_NAME).then_some(k))
        .ok_or_else(|| anyhow!("world not found: {WORLD_NAME}"))?;

    bindgen.resolve.worlds[world].exports.retain(|k, _| {
        let k = match &k {
            wit_parser::WorldKey::Name(n) => n,
            wit_parser::WorldKey::Interface(i) => match &bindgen.resolve.interfaces[*i].name {
                Some(n) => n,
                None => return true,
            },
        };
        allowed.contains(k.as_str())
    });

    let body = metadata::encode(
        &bindgen.resolve,
        world,
        wit_component::StringEncoding::UTF8,
        None,
    )?;

    let adapter = add_custom_section(CUSTOM_SECTION_NAME, &body, &adapter)?;

    ComponentEncoder::default()
        .validate(true)
        .module(&module)?
        .adapter(ADAPTER_NAME, &adapter)?
        .encode()
}

pub fn componentize_command(module: &[u8]) -> Result<Vec<u8>> {
    ComponentEncoder::default()
        .validate(true)
        .module(module)?
        .adapter(ADAPTER_NAME, COMMAND_ADAPTER)?
        .encode()
}

fn retarget_imports_and_get_exports(target: &str, module: &[u8]) -> Result<(Vec<u8>, Vec<String>)> {
    let mut result = Module::new();
    let mut exports_result = Vec::new();

    for payload in Parser::new(0).parse_all(module) {
        match payload? {
            Payload::ImportSection(reader) => {
                let mut imports = ImportSection::new();
                for import in reader {
                    let import = import?;
                    let (module, field) = if import.module == target {
                        (Cow::Borrowed(import.module), Cow::Borrowed(import.name))
                    } else {
                        (
                            Cow::Borrowed(target),
                            Cow::Owned(format!("{}:{}", import.module, import.name)),
                        )
                    };
                    imports.import(&module, &field, IntoEntityType(import.ty));
                }
                result.section(&imports);
            }

            Payload::ExportSection(reader) => {
                let mut exports = ExportSection::new();
                for export in reader {
                    let export = export?;
                    exports_result.push(export.name.to_owned());
                    exports.export(
                        export.name,
                        IntoExportKind(export.kind).into(),
                        export.index,
                    );
                }
                result.section(&exports);
            }

            payload => {
                if let Some((id, range)) = payload.as_section() {
                    result.section(&RawSection {
                        id,
                        data: &module[range],
                    });
                }
            }
        }
    }

    Ok((result.finish(), exports_result))
}

fn add_custom_section(name: &str, data: &[u8], module: &[u8]) -> Result<Vec<u8>> {
    let mut result = Module::new();

    for payload in Parser::new(0).parse_all(module) {
        if let Some((id, range)) = payload?.as_section() {
            result.section(&RawSection {
                id,
                data: &module[range],
            });
        }
    }

    result.section(&CustomSection {
        name: Cow::Borrowed(name),
        data: Cow::Borrowed(data),
    });

    Ok(result.finish())
}

#[cfg(test)]
mod tests {
    use std::{path::PathBuf, process};

    use anyhow::Context;
    use wasmtime_wasi::pipe::MemoryOutputPipe;

    use {
        super::abi_conformance::{
            InvocationStyle, KeyValueReport, LlmReport, MysqlReport, PostgresReport, RedisReport,
            Report, TestConfig, WasiReport,
        },
        anyhow::{anyhow, Result},
        tokio::fs,
        wasmtime::{
            component::{Component, Linker},
            Config, Engine, Store,
        },
        wasmtime_wasi::{bindings::Command, pipe::MemoryInputPipe, ResourceTable, WasiView},
        wasmtime_wasi::{WasiCtx, WasiCtxBuilder},
    };

    async fn run_spin(module: &[u8]) -> Result<()> {
        let mut config = Config::new();
        config.wasm_component_model(true);
        config.async_support(true);

        let engine = Engine::new(&config)?;

        let component = Component::new(
            &engine,
            crate::componentize(module).context("could not componentize")?,
        )
        .context("failed to instantiate componentized bytes")?;

        let report = super::abi_conformance::test(
            &component,
            &engine,
            TestConfig {
                invocation_style: InvocationStyle::InboundHttp,
            },
        )
        .await
        .context("abi conformance test failed")?;

        let expected = Report {
            inbound_http: Ok(()),
            inbound_redis: Ok(()),
            config: Ok(()),
            http: Ok(()),
            redis: RedisReport {
                publish: Ok(()),
                set: Ok(()),
                get: Ok(()),
                incr: Ok(()),
                del: Ok(()),
                sadd: Ok(()),
                srem: Ok(()),
                smembers: Ok(()),
                execute: Ok(()),
            },
            postgres: PostgresReport {
                execute: Ok(()),
                query: Ok(()),
            },
            mysql: MysqlReport {
                execute: Ok(()),
                query: Ok(()),
            },
            key_value: KeyValueReport {
                open: Ok(()),
                get: Ok(()),
                set: Ok(()),
                delete: Ok(()),
                exists: Ok(()),
                get_keys: Ok(()),
                close: Ok(()),
            },
            llm: LlmReport { infer: Ok(()) },
            wasi: WasiReport {
                env: Ok(()),
                epoch: Ok(()),
                random: Ok(()),
                stdio: Ok(()),
                read: Ok(()),
                readdir: Ok(()),
                stat: Ok(()),
            },
        };

        if report == expected {
            Ok(())
        } else {
            Err(anyhow!("{report:#?}"))
        }
    }

    async fn run_command(module: &[u8]) -> Result<()> {
        let mut config = Config::new();
        config.wasm_component_model(true);
        config.async_support(true);

        let engine = Engine::new(&config)?;

        struct Wasi {
            ctx: WasiCtx,
            table: ResourceTable,
        }
        impl WasiView for Wasi {
            fn table(&mut self) -> &mut ResourceTable {
                &mut self.table
            }

            fn ctx(&mut self) -> &mut WasiCtx {
                &mut self.ctx
            }
        }

        let mut linker = Linker::<Wasi>::new(&engine);
        wasmtime_wasi::add_to_linker_async(&mut linker)?;
        let mut ctx = WasiCtxBuilder::new();
        let stdout = MemoryOutputPipe::new(1024);
        ctx.stdin(MemoryInputPipe::new("So rested he by the Tumtum tree"))
            .stdout(stdout.clone())
            .args(&["Jabberwocky"]);

        let table = ResourceTable::new();
        let wasi = Wasi {
            ctx: ctx.build(),
            table,
        };

        let mut store = Store::new(&engine, wasi);

        let component = Component::new(&engine, crate::componentize_command(module)?)?;

        let wasi = Command::instantiate_async(&mut store, &component, &linker).await?;

        wasi.wasi_cli_run()
            .call_run(&mut store)
            .await?
            .map_err(|()| anyhow!("command returned with failing exit status"))?;

        drop(store);

        let stdout = stdout.try_into_inner().unwrap().to_vec();

        assert_eq!(
            b"Jabberwocky\nSo rested he by the Tumtum tree" as &[_],
            &stdout
        );

        Ok(())
    }

    #[tokio::test]
    async fn rust_wit_bindgen_02() -> Result<()> {
        build_rust_test_case("rust-case-0.2");
        run_spin(
            &fs::read(concat!(
                env!("OUT_DIR"),
                "/wasm32-wasi/release/rust_case_02.wasm"
            ))
            .await?,
        )
        .await
    }

    #[tokio::test]
    async fn rust_wit_bindgen_08() -> Result<()> {
        build_rust_test_case("rust-case-0.8");
        run_spin(
            &fs::read(concat!(
                env!("OUT_DIR"),
                "/wasm32-wasi/release/rust_case_08.wasm"
            ))
            .await?,
        )
        .await
    }

    #[ignore]
    #[tokio::test]
    async fn go() -> Result<()> {
        let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap());
        let mut cmd = process::Command::new("tinygo");
        cmd.arg("build")
            .current_dir("tests/go-case")
            .arg("-target=wasi")
            .arg("-gc=leaking")
            .arg("-no-debug")
            .arg("-o")
            .arg(out_dir.join("go_case.wasm"))
            .arg("main.go");

        // If just skip this if TinyGo is not installed
        _ = cmd.status();
        run_spin(&fs::read(concat!(env!("OUT_DIR"), "/go_case.wasm")).await?).await
    }

    #[tokio::test]
    async fn rust_command() -> Result<()> {
        build_rust_test_case("rust-command");
        run_command(
            &fs::read(concat!(
                env!("OUT_DIR"),
                "/wasm32-wasi/release/rust-command.wasm"
            ))
            .await?,
        )
        .await
    }

    fn build_rust_test_case(name: &str) {
        let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap());
        let mut cmd = process::Command::new("cargo");
        cmd.arg("build")
            .current_dir(format!("tests/{name}"))
            .arg("--release")
            .arg("--target=wasm32-wasi")
            .env("CARGO_TARGET_DIR", out_dir);

        let status = cmd.status().unwrap();
        assert!(status.success());
    }
}