Debian Codegraph @

crates/wasm-compose/example/server/src/main.rs

raw
1 use async_trait::async_trait;
2 use clap::Parser;
3 use std::path::{Path, PathBuf};
4 use tide::{
5 Request, Response, StatusCode,
6 http::{
7 headers::{HeaderName, HeaderValue},
8 mime,
9 },
10 utils::After,
11 };
12
13 use wasmtime::{Config, Engine, Store, component::*};
14 use wasmtime_wasi::preview2::{Table, WasiCtx, WasiCtxBuilder, WasiView, command};
15
16 use example::service::{
17 logging::{self, HostLogger},
18 types::{self, HostRequest, HostResponse},
19 };
20 use exports::example::service::handler;
21
22 wasmtime::component::bindgen!({
23 path: "../service.wit",
24 world: "service",
25 async: true
26 });
27
28 /// Represents state stored in the tide application context.
29 ///
30 /// This is so that a component is only parsed and compiled once.
31 /// Each request will create a new instance of the component.
32 #[derive(Clone)]
33 struct State {
34 engine: Engine,
35 component: Component,
36 }
37
38 impl State {
39 fn new(path: impl AsRef<Path>) -> tide::Result<Self> {
40 // Enable component model support in Wasmtime
41 let mut config = Config::default();
42 config.wasm_component_model(true);
43 config.async_support(true);
44
45 // Load the component from the given path
46 let engine = Engine::new(&config)?;
47 let component = Component::from_file(&engine, path)?;
48 Ok(Self { engine, component })
49 }
50 }
51
52 impl handler::Error {
53 fn into_tide(self) -> tide::Error {
54 match self {
55 Self::BadRequest => {
56 tide::Error::from_str(StatusCode::BadRequest, "bad service request")
57 }
58 }
59 }
60 }
61
62 /// WebAssembly component server.
63 ///
64 /// A demonstration server that executes WebAssembly components.
65 #[derive(Parser)]
66 #[clap(name = "server", version = env!("CARGO_PKG_VERSION"))]
67 struct ServerApp {
68 /// The path to the service component.
69 #[clap(value_name = "SERVICE_PATH")]
70 service: PathBuf,
71
72 /// The port to listen on.
73 #[clap(long, short = 'p', value_name = "PORT", default_value = "8080")]
74 port: u16,
75 }
76
77 impl ServerApp {
78 async fn run(self) -> tide::Result<()> {
79 // Create a new server with state holding the service component.
80 let mut app = tide::with_state(State::new(&self.service)?);
81 app.with(driftwood::DevLogger);
82
83 // Add a middleware that responds with error text for 500s
84 app.with(After(|response: Response| async move {
85 Ok(match response.status() {
86 // For demonstration purposes, respond with the error text for debugging
87 // Please, don't do this in production
88 StatusCode::InternalServerError => Response::builder(500)
89 .content_type(mime::PLAIN)
90 .body(response.error().unwrap().to_string())
91 .build(),
92 _ => response,
93 })
94 }));
95
96 // App handles only POSTs to `/`
97 app.at("/").post(Self::process_request);
98
99 // Finally listen at the desired port
100 let address = format!("localhost:{port}", port = self.port);
101 println!("listening at http://{address}/");
102 app.listen(address).await.map_err(Into::into)
103 }
104
105 async fn process_request(mut req: Request<State>) -> tide::Result {
106 let body = req.body_bytes().await?;
107 let headers = req
108 .iter()
109 .map(|(n, v)| {
110 (
111 n.as_str().as_bytes().to_vec(),
112 v.as_str().as_bytes().to_vec(),
113 )
114 })
115 .collect::<Vec<_>>();
116
117 // Create a new store for the request
118 let state = req.state();
119 let mut linker = Linker::new(&state.engine);
120 command::add_to_linker(&mut linker)?;
121 Service::add_to_linker(&mut linker, |view| view)?;
122
123 let wasi_view = ServerWasiView::new()?;
124 let mut store = Store::new(&state.engine, wasi_view);
125 let (service, _) =
126 Service::instantiate_async(&mut store, &state.component, &linker).await?;
127
128 let host_request = store
129 .data_mut()
130 .table_mut()
131 .push(MyRequest { headers, body })?;
132 let request = Resource::new_own(host_request.rep());
133
134 let response = service
135 .example_service_handler()
136 .call_execute(&mut store, request)
137 .await?
138 .map_err(handler::Error::into_tide)?;
139
140 let host_response: Resource<MyResponse> = Resource::new_own(response.rep());
141 let response = store.data_mut().table_mut().delete(host_response)?;
142
143 let mut builder = tide::Response::builder(StatusCode::Ok);
144 for (name, value) in response.headers {
145 builder = builder.header(
146 HeaderName::from_bytes(name)?,
147 HeaderValue::from_bytes(value)?,
148 );
149 }
150 builder = builder.body(response.body);
151 Ok(builder.build())
152 }
153 }
154
155 struct ServerWasiView {
156 logger_handle: Resource<logging::Logger>,
157 table: Table,
158 ctx: WasiCtx,
159 }
160
161 impl ServerWasiView {
162 fn new() -> anyhow::Result<Self> {
163 let mut table = Table::new();
164 let ctx = WasiCtxBuilder::new().inherit_stdio().build();
165
166 let host_logger = table.push(MyLogger)?;
167 let logger_handle = Resource::new_own(host_logger.rep());
168
169 Ok(Self {
170 table,
171 ctx,
172 logger_handle,
173 })
174 }
175 }
176
177 impl WasiView for ServerWasiView {
178 fn table(&self) -> &Table {
179 &self.table
180 }
181
182 fn table_mut(&mut self) -> &mut Table {
183 &mut self.table
184 }
185
186 fn ctx(&self) -> &WasiCtx {
187 &self.ctx
188 }
189
190 fn ctx_mut(&mut self) -> &mut WasiCtx {
191 &mut self.ctx
192 }
193 }
194
195 struct MyRequest {
196 headers: Vec<(Vec<u8>, Vec<u8>)>,
197 body: Vec<u8>,
198 }
199
200 #[async_trait]
201 impl HostRequest for ServerWasiView {
202 async fn new(
203 &mut self,
204 headers: Vec<(Vec<u8>, Vec<u8>)>,
205 body: Vec<u8>,
206 ) -> anyhow::Result<Resource<types::Request>> {
207 let host_handle = self.table_mut().push(MyRequest { headers, body })?;
208 let guest_handle = Resource::new_own(host_handle.rep());
209
210 Ok(guest_handle)
211 }
212
213 async fn headers(
214 &mut self,
215 this: Resource<types::Request>,
216 ) -> anyhow::Result<Vec<(Vec<u8>, Vec<u8>)>> {
217 let host_handle: Resource<MyRequest> = Resource::new_own(this.rep());
218
219 Ok(self.table().get(&host_handle)?.headers.clone())
220 }
221
222 async fn body(&mut self, this: Resource<types::Request>) -> anyhow::Result<Vec<u8>> {
223 let host_handle: Resource<MyRequest> = Resource::new_own(this.rep());
224
225 Ok(self.table().get(&host_handle)?.body.clone())
226 }
227
228 fn drop(&mut self, this: Resource<types::Request>) -> anyhow::Result<()> {
229 let host_handle: Resource<MyRequest> = Resource::new_own(this.rep());
230
231 Ok(self.table_mut().delete(host_handle).map(|_| ())?)
232 }
233 }
234
235 struct MyResponse {
236 headers: Vec<(Vec<u8>, Vec<u8>)>,
237 body: Vec<u8>,
238 }
239
240 #[async_trait]
241 impl HostResponse for ServerWasiView {
242 async fn new(
243 &mut self,
244 headers: Vec<(Vec<u8>, Vec<u8>)>,
245 body: Vec<u8>,
246 ) -> anyhow::Result<Resource<types::Response>> {
247 let host_handle = self.table_mut().push(MyResponse { headers, body })?;
248 let guest_handle = Resource::new_own(host_handle.rep());
249
250 Ok(guest_handle)
251 }
252
253 async fn headers(
254 &mut self,
255 this: Resource<types::Response>,
256 ) -> anyhow::Result<Vec<(Vec<u8>, Vec<u8>)>> {
257 let host_handle: Resource<MyResponse> = Resource::new_own(this.rep());
258 Ok(self.table().get(&host_handle)?.headers.clone())
259 }
260
261 async fn body(&mut self, this: Resource<types::Response>) -> anyhow::Result<Vec<u8>> {
262 let host_handle: Resource<MyResponse> = Resource::new_own(this.rep());
263 Ok(self.table().get(&host_handle)?.body.clone())
264 }
265
266 fn drop(&mut self, this: Resource<types::Response>) -> anyhow::Result<()> {
267 let host_handle: Resource<MyResponse> = Resource::new_own(this.rep());
268 Ok(self.table_mut().delete(host_handle).map(|_| ())?)
269 }
270 }
271
272 impl types::Host for ServerWasiView {}
273
274 struct MyLogger;
275
276 #[async_trait]
277 impl HostLogger for ServerWasiView {
278 async fn log(
279 &mut self,
280 this: Resource<logging::Logger>,
281 message: String,
282 ) -> anyhow::Result<()> {
283 let host_handle: Resource<MyLogger> = Resource::new_own(this.rep());
284
285 self.table().get(&host_handle)?;
286
287 println!("host logger: {message}");
288
289 Ok(())
290 }
291
292 fn drop(&mut self, _this: Resource<logging::Logger>) -> anyhow::Result<()> {
293 Ok(())
294 }
295 }
296
297 #[async_trait]
298 impl logging::Host for ServerWasiView {
299 async fn get_logger(&mut self) -> anyhow::Result<Resource<logging::Logger>> {
300 Ok(Resource::new_own(self.logger_handle.rep()))
301 }
302 }
303
304 #[async_std::main]
305 async fn main() -> tide::Result<()> {
306 // Parse the command line arguments and run the application
307 ServerApp::parse().run().await
308 }