-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmain.rs
87 lines (77 loc) · 2.72 KB
/
main.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
use std::path::PathBuf;
use anyhow::Result;
use wasmtime::{
component::{Component, Linker},
Config, Engine, Store, WasmBacktraceDetails,
};
use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiView};
use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};
mod bindings {
// This macro produces generated code that is used to link
// the functionality exposed by the component, and eventually
// call it.
wasmtime::component::bindgen!({
world: "component",
path: "../guest/hello.wit",
async: true
});
}
// Default path to the WebAsssembly component as generated in the 'guest' folder,
// facilitating `cargo run` from the 'host' directory.
//
// If this binary is compiled and used from another folder, this path will likely be invalid,
// and in that case, using the `COMPONENT_PATH` environment variable is preferred.
const DEFAULT_COMPONENT_PATH: &str = "../guest/hello.component.wasm";
#[async_std::main]
async fn main() -> Result<()> {
let mut builder = WasiCtxBuilder::new();
builder.inherit_stdio();
let table = ResourceTable::new();
let wasi = builder.build();
let mut config = Config::new();
config.cache_config_load_default().unwrap();
config.wasm_backtrace_details(WasmBacktraceDetails::Enable);
config.wasm_component_model(true);
config.async_support(true);
let engine = Engine::new(&config)?;
let mut linker = Linker::new(&engine);
let component_path = std::env::var("COMPONENT_WASM_PATH")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(DEFAULT_COMPONENT_PATH));
let component = Component::from_file(&engine, component_path).unwrap();
struct CommandExtendedCtx {
table: ResourceTable,
wasi: WasiCtx,
http: WasiHttpCtx,
}
impl WasiView for CommandExtendedCtx {
fn table(&mut self) -> &mut ResourceTable {
&mut self.table
}
fn ctx(&mut self) -> &mut WasiCtx {
&mut self.wasi
}
}
impl WasiHttpView for CommandExtendedCtx {
fn table(&mut self) -> &mut ResourceTable {
&mut self.table
}
fn ctx(&mut self) -> &mut WasiHttpCtx {
&mut self.http
}
}
wasmtime_wasi::add_to_linker_sync(&mut linker)?;
wasmtime_wasi_http::add_only_http_to_linker_sync(&mut linker)?;
let mut store = Store::new(
&engine,
CommandExtendedCtx {
table,
wasi,
http: WasiHttpCtx::new(),
},
);
let hello = bindings::Component::instantiate_async(&mut store, &component, &linker).await?;
let res = hello.call_hello(&mut store, "ComponentizeJS").await?;
println!("{}", res);
Ok(())
}