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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! # Wasmtime's WASI HTTPp2 Implementation
//!
//! This module is Wasmtime's host implementation of the `wasi:http` package as
//! part of WASIp2. This crate's implementation is primarily built on top of
//! [`hyper`] and [`tokio`].
//!
//! # WASI HTTP Interfaces
//!
//! This crate contains implementations of the following interfaces:
//!
//! * [`wasi:http/incoming-handler`]
//! * [`wasi:http/outgoing-handler`]
//! * [`wasi:http/types`]
//!
//! The crate also contains an implementation of the [`wasi:http/proxy`] world.
//!
//! [`wasi:http/proxy`]: crate::p2::bindings::Proxy
//! [`wasi:http/outgoing-handler`]: crate::p2::bindings::http::outgoing_handler::Host
//! [`wasi:http/types`]: crate::p2::bindings::http::types::Host
//! [`wasi:http/incoming-handler`]: crate::p2::bindings::exports::wasi::http::incoming_handler::Guest
//!
//! This crate is very similar to [`wasmtime_wasi`] in the it uses the
//! `bindgen!` macro in Wasmtime to generate bindings to interfaces. Bindings
//! are located in the [`bindings`] module.
//!
//! # The `WasiHttp{View,Hooks}` traits
//!
//! All `bindgen!`-generated `Host` traits are implemented for the
//! [`WasiHttpCtxView`] type. This type is created from a store's data `T`
//! through the [`WasiHttpView`] trait. The [`add_to_linker_async`] function,
//! for example, uses [`WasiHttpView`] to acquire the context view.
//!
//! The [`WasiHttpCtxView`] structure requires that a [`ResourceTable`] and
//! [`WasiHttpCtx`] live within the store. This is store-specific state that is
//! used to implement various APIs and store host state.
//!
//! The final `hooks` field within [`WasiHttpCtxView`] is a trait object of
//! [`WasiHttpHooks`]. This provides a few more hooks, dynamically, to configure
//! how `wasi:http` behaves. For example [`WasiHttpHooks::send_request`] can
//! customize how outgoing HTTP requests are handled. The `hooks` field can be
//! initialized with the [`default_hooks`] function for the default behavior.
//!
//! # Async and Sync
//!
//! There are both asynchronous and synchronous bindings in this crate. For
//! example [`add_to_linker_async`] is for asynchronous embedders and
//! [`add_to_linker_sync`] is for synchronous embedders. Note that under the
//! hood both versions are implemented with `async` on top of [`tokio`].
//!
//! # Examples
//!
//! Usage of this crate is done through a few steps to get everything hooked up:
//!
//! 1. First implement [`WasiHttpView`] for your type which is the `T` in
//! [`wasmtime::Store<T>`].
//! 2. Add WASI HTTP interfaces to a [`wasmtime::component::Linker<T>`]. There
//! are a few options of how to do this:
//! * Use [`add_to_linker_async`] to bundle all interfaces in
//! `wasi:http/proxy` together
//! * Use [`add_only_http_to_linker_async`] to add only HTTP interfaces but
//! no others. This is useful when working with
//! [`wasmtime_wasi::p2::add_to_linker_async`] for example.
//! * Add individual interfaces such as with the
//! [`bindings::http::outgoing_handler::add_to_linker`] function.
//! 3. Use [`ProxyPre`](bindings::ProxyPre) to pre-instantiate a component
//! before serving requests.
//! 4. When serving requests use
//! [`ProxyPre::instantiate_async`](bindings::ProxyPre::instantiate_async)
//! to create instances and handle HTTP requests.
//!
//! A standalone example of doing all this looks like:
//!
//! ```no_run
//! use wasmtime::bail;
//! use hyper::server::conn::http1;
//! use std::sync::Arc;
//! use tokio::net::TcpListener;
//! use wasmtime::component::{Component, Linker, ResourceTable};
//! use wasmtime::{Engine, Result, Store};
//! use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
//! use wasmtime_wasi_http::p2::bindings::ProxyPre;
//! use wasmtime_wasi_http::p2::bindings::http::types::Scheme;
//! use wasmtime_wasi_http::p2::body::HyperOutgoingBody;
//! use wasmtime_wasi_http::io::TokioIo;
//! use wasmtime_wasi_http::{WasiHttpCtx, p2::{WasiHttpView, WasiHttpCtxView}};
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//! let component = std::env::args().nth(1).unwrap();
//!
//! // Prepare the `Engine` for Wasmtime
//! let engine = Engine::default();
//!
//! // Compile the component on the command line to machine code
//! let component = Component::from_file(&engine, &component)?;
//!
//! // Prepare the `ProxyPre` which is a pre-instantiated version of the
//! // component that we have. This will make per-request instantiation
//! // much quicker.
//! let mut linker = Linker::new(&engine);
//! wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
//! wasmtime_wasi_http::p2::add_only_http_to_linker_async(&mut linker)?;
//! let pre = ProxyPre::new(linker.instantiate_pre(&component)?)?;
//!
//! // Prepare our server state and start listening for connections.
//! let server = Arc::new(MyServer { pre });
//! let listener = TcpListener::bind("127.0.0.1:8000").await?;
//! println!("Listening on {}", listener.local_addr()?);
//!
//! loop {
//! // Accept a TCP connection and serve all of its requests in a separate
//! // tokio task. Note that for now this only works with HTTP/1.1.
//! let (client, addr) = listener.accept().await?;
//! println!("serving new client from {addr}");
//!
//! let server = server.clone();
//! tokio::task::spawn(async move {
//! if let Err(e) = http1::Builder::new()
//! .keep_alive(true)
//! .serve_connection(
//! TokioIo::new(client),
//! hyper::service::service_fn(move |req| {
//! let server = server.clone();
//! async move { server.handle_request(req).await }
//! }),
//! )
//! .await
//! {
//! eprintln!("error serving client[{addr}]: {e:?}");
//! }
//! });
//! }
//! }
//!
//! struct MyServer {
//! pre: ProxyPre<MyClientState>,
//! }
//!
//! impl MyServer {
//! async fn handle_request(
//! &self,
//! req: hyper::Request<hyper::body::Incoming>,
//! ) -> Result<hyper::Response<HyperOutgoingBody>> {
//! // Create per-http-request state within a `Store` and prepare the
//! // initial resources passed to the `handle` function.
//! let mut store = Store::new(
//! self.pre.engine(),
//! MyClientState {
//! table: ResourceTable::new(),
//! wasi: WasiCtx::builder().inherit_stdio().build(),
//! http: WasiHttpCtx::new(),
//! },
//! );
//! let (sender, receiver) = tokio::sync::oneshot::channel();
//! let req = store.data_mut().http().new_incoming_request(Scheme::Http, req)?;
//! let out = store.data_mut().http().new_response_outparam(sender)?;
//! let pre = self.pre.clone();
//!
//! // Run the http request itself in a separate task so the task can
//! // optionally continue to execute beyond after the initial
//! // headers/response code are sent.
//! let task = tokio::task::spawn(async move {
//! let proxy = pre.instantiate_async(&mut store).await?;
//!
//! if let Err(e) = proxy
//! .wasi_http_incoming_handler()
//! .call_handle(store, req, out)
//! .await
//! {
//! return Err(e);
//! }
//!
//! Ok(())
//! });
//!
//! match receiver.await {
//! // If the client calls `response-outparam::set` then one of these
//! // methods will be called.
//! Ok(Ok(resp)) => Ok(resp),
//! Ok(Err(e)) => Err(e.into()),
//!
//! // Otherwise the `sender` will get dropped along with the `Store`
//! // meaning that the oneshot will get disconnected and here we can
//! // inspect the `task` result to see what happened
//! Err(_) => {
//! let e = match task.await {
//! Ok(Ok(())) => {
//! bail!("guest never invoked `response-outparam::set` method")
//! }
//! Ok(Err(e)) => e,
//! Err(e) => e.into(),
//! };
//! return Err(e.context("guest never invoked `response-outparam::set` method"));
//! }
//! }
//! }
//! }
//!
//! struct MyClientState {
//! wasi: WasiCtx,
//! http: WasiHttpCtx,
//! table: ResourceTable,
//! }
//!
//! impl WasiView for MyClientState {
//! fn ctx(&mut self) -> WasiCtxView<'_> {
//! WasiCtxView { ctx: &mut self.wasi, table: &mut self.table }
//! }
//! }
//!
//! impl WasiHttpView for MyClientState {
//! fn http(&mut self) -> WasiHttpCtxView<'_> {
//! WasiHttpCtxView {
//! ctx: &mut self.http,
//! table: &mut self.table,
//! hooks: Default::default(),
//! }
//! }
//! }
//! ```
use ErrorCode;
use crate::;
use HeaderName;
use ;
pub use *;
/// A trait which provides hooks into internal WASI HTTP operations.
///
/// # Example
///
/// ```
/// use wasmtime::component::ResourceTable;
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
/// use wasmtime_wasi_http::WasiHttpCtx;
/// use wasmtime_wasi_http::p2::{WasiHttpView, WasiHttpCtxView};
///
/// struct MyState {
/// ctx: WasiCtx,
/// http_ctx: WasiHttpCtx,
/// table: ResourceTable,
/// }
///
/// impl WasiHttpView for MyState {
/// fn http(&mut self) -> WasiHttpCtxView<'_> {
/// WasiHttpCtxView {
/// ctx: &mut self.http_ctx,
/// table: &mut self.table,
/// hooks: Default::default(),
/// }
/// }
/// }
///
/// impl WasiView for MyState {
/// fn ctx(&mut self) -> WasiCtxView<'_> {
/// WasiCtxView { ctx: &mut self.ctx, table: &mut self.table }
/// }
/// }
///
/// impl MyState {
/// fn new() -> MyState {
/// let mut wasi = WasiCtx::builder();
/// wasi.arg("./foo.wasm");
/// wasi.arg("--help");
/// wasi.env("FOO", "bar");
///
/// MyState {
/// ctx: wasi.build(),
/// table: ResourceTable::new(),
/// http_ctx: WasiHttpCtx::new(),
/// }
/// }
/// }
/// ```
/// Returns a value suitable for the `WasiHttpCtxView::hooks` field which has
/// the default behavior for `wasi:http`.
/// The default value configured for [`WasiHttpHooks::outgoing_body_buffer_chunks`] in [`WasiHttpView`].
pub const DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS: usize = 1;
/// The default value configured for [`WasiHttpHooks::outgoing_body_chunk_size`] in [`WasiHttpView`].
pub const DEFAULT_OUTGOING_BODY_CHUNK_SIZE: usize = 1024 * 1024;
/// Structure which `wasi:http` `Host`-style traits are implemented for.
///
/// This structure is used by embedders with the [`WasiHttpView`] trait's return
/// value and is used to provide access to this crate all internals necessary to
/// implement `wasi:http`. This is similar to [`wasmtime_wasi::WasiCtxView`]
/// for example.
/// The type for which this crate implements the `wasi:http` interfaces.
;
/// A trait used to project state that this crate needs to implement `wasi:http`
/// from the `self` type.
///
/// This trait is used in [`add_to_linker_sync`] and [`add_to_linker_async`] for
/// example as a bound on `T` in `Store<T>`. This is used to access data from
/// `T`, the data within a `Store`, an instance of [`WasiHttpCtxView`]. The
/// [`WasiHttpCtxView`] contains contextual information such as the
/// [`ResourceTable`] for the store, HTTP context info in [`WasiHttpCtx`], and
/// any hooks via [`WasiHttpHooks`] if the embedder desires.
///
/// # Example
///
/// ```
/// use wasmtime::component::ResourceTable;
/// use wasmtime_wasi_http::WasiHttpCtx;
/// use wasmtime_wasi_http::p2::{WasiHttpView, WasiHttpCtxView};
///
/// struct MyState {
/// http_ctx: WasiHttpCtx,
/// table: ResourceTable,
/// }
///
/// impl WasiHttpView for MyState {
/// fn http(&mut self) -> WasiHttpCtxView<'_> {
/// WasiHttpCtxView {
/// ctx: &mut self.http_ctx,
/// table: &mut self.table,
/// hooks: Default::default(),
/// }
/// }
/// }
/// ```
/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].
///
/// This function will add the `async` variant of all interfaces into the
/// `Linker` provided. For embeddings with async support disabled see
/// [`add_to_linker_sync`] instead.
///
/// # Example
///
/// ```
/// use wasmtime::{Engine, Result};
/// use wasmtime::component::{ResourceTable, Linker};
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
/// use wasmtime_wasi_http::{WasiHttpCtx, p2::{WasiHttpView, WasiHttpCtxView}};
///
/// fn main() -> Result<()> {
/// let engine = Engine::default();
///
/// let mut linker = Linker::<MyState>::new(&engine);
/// wasmtime_wasi_http::p2::add_to_linker_async(&mut linker)?;
/// // ... add any further functionality to `linker` if desired ...
///
/// Ok(())
/// }
///
/// struct MyState {
/// ctx: WasiCtx,
/// http_ctx: WasiHttpCtx,
/// table: ResourceTable,
/// }
///
/// impl WasiHttpView for MyState {
/// fn http(&mut self) -> WasiHttpCtxView<'_> {
/// WasiHttpCtxView {
/// ctx: &mut self.http_ctx,
/// table: &mut self.table,
/// hooks: Default::default(),
/// }
/// }
/// }
///
/// impl WasiView for MyState {
/// fn ctx(&mut self) -> WasiCtxView<'_> {
/// WasiCtxView { ctx: &mut self.ctx, table: &mut self.table }
/// }
/// }
/// ```
/// A slimmed down version of [`add_to_linker_async`] which only adds
/// `wasi:http` interfaces to the linker.
///
/// This is useful when using [`wasmtime_wasi::p2::add_to_linker_async`] for
/// example to avoid re-adding the same interfaces twice.
/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].
///
/// This function will add the `sync` variant of all interfaces into the
/// `Linker` provided. For embeddings with async support see
/// [`add_to_linker_async`] instead.
///
/// # Example
///
/// ```
/// use wasmtime::{Engine, Result, Config};
/// use wasmtime::component::{ResourceTable, Linker};
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
/// use wasmtime_wasi_http::WasiHttpCtx;
/// use wasmtime_wasi_http::p2::{WasiHttpView, WasiHttpCtxView};
///
/// fn main() -> Result<()> {
/// let config = Config::default();
/// let engine = Engine::new(&config)?;
///
/// let mut linker = Linker::<MyState>::new(&engine);
/// wasmtime_wasi_http::p2::add_to_linker_sync(&mut linker)?;
/// // ... add any further functionality to `linker` if desired ...
///
/// Ok(())
/// }
///
/// struct MyState {
/// ctx: WasiCtx,
/// http_ctx: WasiHttpCtx,
/// table: ResourceTable,
/// }
/// impl WasiHttpView for MyState {
/// fn http(&mut self) -> WasiHttpCtxView<'_> {
/// WasiHttpCtxView {
/// ctx: &mut self.http_ctx,
/// table: &mut self.table,
/// hooks: Default::default(),
/// }
/// }
/// }
/// impl WasiView for MyState {
/// fn ctx(&mut self) -> WasiCtxView<'_> {
/// WasiCtxView { ctx: &mut self.ctx, table: &mut self.table }
/// }
/// }
/// ```
/// A slimmed down version of [`add_to_linker_sync`] which only adds
/// `wasi:http` interfaces to the linker.
///
/// This is useful when using [`wasmtime_wasi::p2::add_to_linker_sync`] for
/// example to avoid re-adding the same interfaces twice.
/// The default implementation of how an outgoing request is sent.
///
/// This implementation is used by the `wasi:http/outgoing-handler` interface
/// default implementation.
/// The underlying implementation of how an outgoing request is sent. This should likely be spawned
/// in a task.
///
/// This is called from [default_send_request] to actually send the request.
pub async