Skip to main content

wasmtime_cli/commands/
serve.rs

1use crate::common::{HttpHooks, Profile, RunCommon, RunTarget};
2use bytes::Bytes;
3use clap::Parser;
4use futures::future::FutureExt;
5use http::{Response, StatusCode};
6use http_body_util::BodyExt as _;
7use http_body_util::combinators::UnsyncBoxBody;
8use hyper::body::{Body, Frame, SizeHint};
9use std::convert::Infallible;
10use std::ffi::OsString;
11use std::net::SocketAddr;
12use std::pin::Pin;
13use std::task::{Context, Poll};
14use std::{
15    path::PathBuf,
16    sync::{
17        Arc, Mutex,
18        atomic::{AtomicBool, Ordering},
19    },
20    time::Duration,
21};
22use tokio::io::{self, AsyncWrite};
23use tokio::sync::Notify;
24use wasmtime::component::{Component, Linker};
25use wasmtime::{
26    Engine, Result, Store, StoreContextMut, StoreLimits, UpdateDeadline, bail, error::Context as _,
27};
28use wasmtime_cli_flags::opt::WasmtimeOptionValue;
29use wasmtime_wasi::p2::{StreamError, StreamResult};
30use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
31#[cfg(feature = "component-model-async")]
32use wasmtime_wasi_http::handler::p2::bindings as p2;
33use wasmtime_wasi_http::handler::{HandlerState, Proxy, ProxyHandler, ProxyPre, StoreBundle};
34use wasmtime_wasi_http::io::TokioIo;
35use wasmtime_wasi_http::{WasiHttpCtx, p2::WasiHttpView};
36
37#[cfg(feature = "debug")]
38use crate::commands::run::RunCommand;
39
40#[cfg(feature = "wasi-config")]
41use wasmtime_wasi_config::{WasiConfig, WasiConfigVariables};
42#[cfg(feature = "wasi-keyvalue")]
43use wasmtime_wasi_keyvalue::{WasiKeyValue, WasiKeyValueCtx, WasiKeyValueCtxBuilder};
44#[cfg(feature = "wasi-nn")]
45use wasmtime_wasi_nn::wit::WasiNnCtx;
46
47const DEFAULT_WASIP3_MAX_INSTANCE_REUSE_COUNT: usize = 128;
48const DEFAULT_WASIP2_MAX_INSTANCE_REUSE_COUNT: usize = 1;
49const DEFAULT_WASIP3_MAX_INSTANCE_CONCURRENT_REUSE_COUNT: usize = 16;
50
51struct Host {
52    table: wasmtime::component::ResourceTable,
53    ctx: WasiCtx,
54    http: WasiHttpCtx,
55    hooks: HttpHooks,
56
57    limits: StoreLimits,
58
59    #[cfg(feature = "wasi-nn")]
60    nn: Option<WasiNnCtx>,
61
62    #[cfg(feature = "wasi-config")]
63    wasi_config: Option<WasiConfigVariables>,
64
65    #[cfg(feature = "wasi-keyvalue")]
66    wasi_keyvalue: Option<WasiKeyValueCtx>,
67
68    #[cfg(feature = "profiling")]
69    guest_profiler: Option<Arc<wasmtime::GuestProfiler>>,
70}
71
72impl WasiView for Host {
73    fn ctx(&mut self) -> WasiCtxView<'_> {
74        WasiCtxView {
75            ctx: &mut self.ctx,
76            table: &mut self.table,
77        }
78    }
79}
80
81impl wasmtime_wasi_http::p2::WasiHttpView for Host {
82    fn http(&mut self) -> wasmtime_wasi_http::p2::WasiHttpCtxView<'_> {
83        wasmtime_wasi_http::p2::WasiHttpCtxView {
84            ctx: &mut self.http,
85            table: &mut self.table,
86            hooks: &mut self.hooks,
87        }
88    }
89}
90
91#[cfg(feature = "component-model-async")]
92impl wasmtime_wasi_http::p3::WasiHttpView for Host {
93    fn http(&mut self) -> wasmtime_wasi_http::p3::WasiHttpCtxView<'_> {
94        wasmtime_wasi_http::p3::WasiHttpCtxView {
95            table: &mut self.table,
96            ctx: &mut self.http,
97            hooks: &mut self.hooks,
98        }
99    }
100}
101
102const DEFAULT_ADDR: std::net::SocketAddr = std::net::SocketAddr::new(
103    std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
104    8080,
105);
106
107fn parse_duration(s: &str) -> Result<Duration, String> {
108    Duration::parse(Some(s)).map_err(|e| e.to_string())
109}
110
111/// Runs a WebAssembly module
112#[derive(Parser)]
113pub struct ServeCommand {
114    #[command(flatten)]
115    run: RunCommon,
116
117    /// Socket address for the web server to bind to.
118    #[arg(long , value_name = "SOCKADDR", default_value_t = DEFAULT_ADDR)]
119    addr: SocketAddr,
120
121    /// Socket address where, when connected to, will initiate a graceful
122    /// shutdown.
123    ///
124    /// Note that graceful shutdown is also supported on ctrl-c.
125    #[arg(long, value_name = "SOCKADDR")]
126    shutdown_addr: Option<SocketAddr>,
127
128    /// Disable log prefixes of wasi-http handlers.
129    /// if unspecified, logs will be prefixed with 'stdout|stderr [{req_id}] :: '
130    #[arg(long)]
131    no_logging_prefix: bool,
132
133    /// The WebAssembly component to run.
134    #[arg(value_name = "WASM", required = true)]
135    component: PathBuf,
136
137    /// Maximum number of requests to send to a single component instance before
138    /// dropping it.
139    ///
140    /// This defaults to 1 for WASIp2 components and 128 for WASIp3 components.
141    #[arg(long)]
142    max_instance_reuse_count: Option<usize>,
143
144    /// Maximum number of concurrent requests to send to a single component
145    /// instance.
146    ///
147    /// This defaults to 1 for WASIp2 components and 16 for WASIp3 components.
148    /// Note that setting it to more than 1 will have no effect for WASIp2
149    /// components since they cannot be called concurrently.
150    #[arg(long)]
151    max_instance_concurrent_reuse_count: Option<usize>,
152
153    /// Time to hold an idle component instance for possible reuse before
154    /// dropping it.
155    ///
156    /// A number with no suffix or with an `s` suffix is interpreted as seconds;
157    /// other accepted suffixes include `ms` (milliseconds), `us` or `μs`
158    /// (microseconds), and `ns` (nanoseconds).
159    #[arg(long, default_value = "1s", value_parser = parse_duration)]
160    idle_instance_timeout: Duration,
161}
162
163impl ServeCommand {
164    /// Start a server to run the given wasi-http proxy component
165    pub fn execute(mut self) -> Result<()> {
166        self.run.common.init_logging()?;
167
168        // We force cli errors before starting to listen for connections so then
169        // we don't accidentally delay them to the first request.
170
171        if self.run.common.wasi.nn == Some(true) {
172            #[cfg(not(feature = "wasi-nn"))]
173            {
174                bail!("Cannot enable wasi-nn when the binary is not compiled with this feature.");
175            }
176        }
177
178        if self.run.common.wasi.threads == Some(true) {
179            bail!("wasi-threads does not support components yet")
180        }
181
182        // The serve command requires both wasi-http and the component model, so
183        // we enable those by default here.
184        if self.run.common.wasi.http.replace(true) == Some(false) {
185            bail!("wasi-http is required for the serve command, and must not be disabled");
186        }
187        if self.run.common.wasm.component_model.replace(true) == Some(false) {
188            bail!("components are required for the serve command, and must not be disabled");
189        }
190
191        let runtime = tokio::runtime::Builder::new_multi_thread()
192            .enable_time()
193            .enable_io()
194            .build()?;
195
196        runtime.block_on(self.serve())?;
197
198        Ok(())
199    }
200
201    /// Set up the debugger component side-car, mirroring
202    /// [`RunCommand::debugger_run`].
203    #[cfg(feature = "debug")]
204    fn debugger_setup(&mut self) -> Result<Option<RunCommand>> {
205        fn set_implicit_option(
206            place: &str,
207            name: &str,
208            setting: &mut Option<bool>,
209            value: bool,
210        ) -> Result<()> {
211            if *setting == Some(!value) {
212                bail!(
213                    "Explicitly-set option on {place} {name}={} is not compatible \
214                     with debugging-implied setting {value}",
215                    setting.unwrap()
216                );
217            }
218            *setting = Some(value);
219            Ok(())
220        }
221
222        #[cfg(feature = "gdbstub")]
223        let override_bytes = if let Some(addr) = self.run.gdbstub.as_deref() {
224            if self.run.common.debug.debugger.is_some() {
225                bail!("-g/--gdb cannot be combined with -Ddebugger=");
226            }
227            let addr = if addr.parse::<u16>().is_ok() {
228                format!("127.0.0.1:{addr}")
229            } else {
230                use std::net::SocketAddr as SA;
231                addr.parse::<SA>()
232                    .with_context(|| format!("invalid gdbstub address: `{addr}`"))?;
233                addr.to_string()
234            };
235            self.run.common.debug.debugger = Some("<built-in gdbstub>".into());
236            self.run.common.debug.arg.push(addr);
237            Some(gdbstub_component_artifact::GDBSTUB_COMPONENT)
238        } else {
239            None
240        };
241        #[cfg(not(feature = "gdbstub"))]
242        let override_bytes = None;
243
244        if let Some(debugger_component_path) = self.run.common.debug.debugger.as_ref() {
245            set_implicit_option(
246                "debuggee",
247                "guest_debug",
248                &mut self.run.common.debug.guest_debug,
249                true,
250            )?;
251            set_implicit_option(
252                "debuggee",
253                "epoch_interruption",
254                &mut self.run.common.wasm.epoch_interruption,
255                true,
256            )?;
257
258            let mut debugger_run = RunCommand::try_parse_from(
259                ["run".into(), debugger_component_path.into()]
260                    .into_iter()
261                    .chain(self.run.common.debug.arg.iter().map(OsString::from)),
262            )?;
263            debugger_run.module_bytes = override_bytes;
264
265            debugger_run.run.common.wasi.tcp.get_or_insert(true);
266            debugger_run
267                .run
268                .common
269                .wasi
270                .inherit_network
271                .get_or_insert(true);
272
273            set_implicit_option(
274                "debugger",
275                "inherit_stdin",
276                &mut debugger_run.run.common.wasi.inherit_stdin,
277                self.run.common.debug.inherit_stdin.unwrap_or(false),
278            )?;
279            set_implicit_option(
280                "debugger",
281                "inherit_stdout",
282                &mut debugger_run.run.common.wasi.inherit_stdout,
283                self.run.common.debug.inherit_stdout.unwrap_or(false),
284            )?;
285            set_implicit_option(
286                "debugger",
287                "inherit_stderr",
288                &mut debugger_run.run.common.wasi.inherit_stderr,
289                self.run.common.debug.inherit_stderr.unwrap_or(false),
290            )?;
291            Ok(Some(debugger_run))
292        } else {
293            Ok(None)
294        }
295    }
296
297    /// Run the HTTP server under a debugger component.
298    ///
299    /// Uses a single store and instance to handle all requests
300    /// sequentially, so the debugger can pause and inspect state.
301    #[cfg(feature = "debug")]
302    async fn serve_under_debugger(
303        &self,
304        mut debug_run: RunCommand,
305        engine: &Engine,
306        linker: &Linker<Host>,
307        component: &Component,
308    ) -> Result<()> {
309        let instance_pre = linker.instantiate_pre(component)?;
310        let proxy_pre = wasmtime_wasi_http::p2::bindings::ProxyPre::new(instance_pre)?;
311
312        let mut debuggee_store = self.new_store(engine, None)?;
313
314        // Pre-register component modules so the debugger can see
315        // them and set breakpoints at the initial stop.
316        debuggee_store.debug_register_component(component)?;
317
318        let debug_engine = debug_run.new_engine()?;
319        let debug_main = debug_run.run.load_module(
320            &debug_engine,
321            debug_run.module_and_args[0].as_ref(),
322            debug_run.module_bytes.as_ref().map(|v| &v[..]),
323        )?;
324        let (mut debug_store, debug_linker) =
325            debug_run.new_store_and_linker(&debug_engine, &debug_main)?;
326        let debug_component = match debug_main {
327            RunTarget::Core(_) => {
328                bail!("Debugger component is a core module; only components are supported")
329            }
330            RunTarget::Component(c) => c,
331        };
332        let mut debug_linker = match debug_linker {
333            crate::commands::run::CliLinker::Core(_) => unreachable!(),
334            crate::commands::run::CliLinker::Component(l) => l,
335        };
336        debug_run.add_debugger_api(&mut debug_linker)?;
337
338        let addr = self.addr;
339        debug_run
340            .invoke_debugger(
341                &mut debug_store,
342                &debug_component,
343                &mut debug_linker,
344                debuggee_store,
345                move |store| Box::pin(debug_serve_body(store, proxy_pre, addr)),
346            )
347            .await
348    }
349
350    fn new_store(&self, engine: &Engine, req_id: Option<u64>) -> Result<Store<Host>> {
351        let mut builder = WasiCtxBuilder::new();
352        self.run.configure_wasip2(&mut builder)?;
353
354        if let Some(req_id) = req_id {
355            builder.env("REQUEST_ID", req_id.to_string());
356        }
357
358        let stdout_prefix: String;
359        let stderr_prefix: String;
360        match req_id {
361            Some(req_id) if !self.no_logging_prefix => {
362                stdout_prefix = format!("stdout [{req_id}] :: ");
363                stderr_prefix = format!("stderr [{req_id}] :: ");
364            }
365            _ => {
366                stdout_prefix = "".to_string();
367                stderr_prefix = "".to_string();
368            }
369        }
370        builder.stdout(LogStream::new(stdout_prefix, Output::Stdout));
371        builder.stderr(LogStream::new(stderr_prefix, Output::Stderr));
372
373        let mut table = wasmtime::component::ResourceTable::new();
374        if let Some(max) = self.run.common.wasi.max_resources {
375            table.set_max_capacity(max);
376        }
377        let mut host = Host {
378            table,
379            ctx: builder.build(),
380            http: self.run.wasi_http_ctx()?,
381            hooks: self.run.wasi_http_hooks(),
382
383            limits: StoreLimits::default(),
384
385            #[cfg(feature = "wasi-nn")]
386            nn: None,
387            #[cfg(feature = "wasi-config")]
388            wasi_config: None,
389            #[cfg(feature = "wasi-keyvalue")]
390            wasi_keyvalue: None,
391            #[cfg(feature = "profiling")]
392            guest_profiler: None,
393        };
394
395        if self.run.common.wasi.nn == Some(true) {
396            #[cfg(feature = "wasi-nn")]
397            {
398                let graphs = self
399                    .run
400                    .common
401                    .wasi
402                    .nn_graph
403                    .iter()
404                    .map(|g| (g.format.clone(), g.dir.clone()))
405                    .collect::<Vec<_>>();
406                let (backends, registry) = wasmtime_wasi_nn::preload(&graphs)?;
407                host.nn.replace(WasiNnCtx::new(backends, registry));
408            }
409        }
410
411        if self.run.common.wasi.config == Some(true) {
412            #[cfg(feature = "wasi-config")]
413            {
414                let vars = WasiConfigVariables::from_iter(
415                    self.run
416                        .common
417                        .wasi
418                        .config_var
419                        .iter()
420                        .map(|v| (v.key.clone(), v.value.clone())),
421                );
422                host.wasi_config.replace(vars);
423            }
424        }
425
426        if self.run.common.wasi.keyvalue == Some(true) {
427            #[cfg(feature = "wasi-keyvalue")]
428            {
429                let ctx = WasiKeyValueCtxBuilder::new()
430                    .in_memory_data(
431                        self.run
432                            .common
433                            .wasi
434                            .keyvalue_in_memory_data
435                            .iter()
436                            .map(|v| (v.key.clone(), v.value.clone())),
437                    )
438                    .build();
439                host.wasi_keyvalue.replace(ctx);
440            }
441        }
442
443        let mut store = Store::new(engine, host);
444
445        if let Some(fuel) = self.run.common.wasi.hostcall_fuel {
446            store.set_hostcall_fuel(fuel);
447        }
448
449        store.data_mut().limits = self.run.store_limits();
450        store.limiter(|t| &mut t.limits);
451
452        // If fuel has been configured, we want to add the configured
453        // fuel amount to this store.
454        if let Some(fuel) = self.run.common.wasm.fuel {
455            store.set_fuel(fuel)?;
456        }
457
458        Ok(store)
459    }
460
461    fn add_to_linker(&self, linker: &mut Linker<Host>) -> Result<()> {
462        self.run.validate_p3_option()?;
463        let cli = self.run.validate_cli_enabled()?;
464
465        // Repurpose the `-Scli` flag of `wasmtime run` for `wasmtime serve`
466        // to serve as a signal to enable all WASI interfaces instead of just
467        // those in the `proxy` world. If `-Scli` is present then add all
468        // `command` APIs and then additionally add in the required HTTP APIs.
469        //
470        // If `-Scli` isn't passed then use the `add_to_linker_async`
471        // bindings which adds just those interfaces that the proxy interface
472        // uses.
473        if cli == Some(true) {
474            self.run.add_wasmtime_wasi_to_linker(linker)?;
475            wasmtime_wasi_http::p2::add_only_http_to_linker_async(linker)?;
476            #[cfg(feature = "component-model-async")]
477            if self.run.common.wasi.p3.unwrap_or(crate::common::P3_DEFAULT) {
478                wasmtime_wasi_http::p3::add_to_linker(linker)?;
479            }
480        } else {
481            wasmtime_wasi_http::p2::add_to_linker_async(linker)?;
482            #[cfg(feature = "component-model-async")]
483            if self.run.common.wasi.p3.unwrap_or(crate::common::P3_DEFAULT) {
484                wasmtime_wasi_http::p3::add_to_linker(linker)?;
485                wasmtime_wasi::p3::clocks::add_to_linker(linker)?;
486                wasmtime_wasi::p3::random::add_to_linker(linker)?;
487                wasmtime_wasi::p3::cli::add_to_linker(linker)?;
488            }
489        }
490
491        if self.run.common.wasi.nn == Some(true) {
492            #[cfg(not(feature = "wasi-nn"))]
493            {
494                bail!("support for wasi-nn was disabled at compile time");
495            }
496            #[cfg(feature = "wasi-nn")]
497            {
498                wasmtime_wasi_nn::wit::add_to_linker(linker, |h: &mut Host| {
499                    let ctx = h.nn.as_mut().unwrap();
500                    wasmtime_wasi_nn::wit::WasiNnView::new(&mut h.table, ctx)
501                })?;
502            }
503        }
504
505        if self.run.common.wasi.config == Some(true) {
506            #[cfg(not(feature = "wasi-config"))]
507            {
508                bail!("support for wasi-config was disabled at compile time");
509            }
510            #[cfg(feature = "wasi-config")]
511            {
512                wasmtime_wasi_config::add_to_linker(linker, |h| {
513                    WasiConfig::from(h.wasi_config.as_ref().unwrap())
514                })?;
515            }
516        }
517
518        if self.run.common.wasi.keyvalue == Some(true) {
519            #[cfg(not(feature = "wasi-keyvalue"))]
520            {
521                bail!("support for wasi-keyvalue was disabled at compile time");
522            }
523            #[cfg(feature = "wasi-keyvalue")]
524            {
525                wasmtime_wasi_keyvalue::add_to_linker(linker, |h: &mut Host| {
526                    WasiKeyValue::new(h.wasi_keyvalue.as_ref().unwrap(), &mut h.table)
527                })?;
528            }
529        }
530
531        if self.run.common.wasi.threads == Some(true) {
532            bail!("support for wasi-threads is not available with components");
533        }
534
535        if self.run.common.wasi.http == Some(false) {
536            bail!("support for wasi-http must be enabled for `serve` subcommand");
537        }
538
539        Ok(())
540    }
541
542    async fn serve(mut self) -> Result<()> {
543        use hyper::server::conn::http1;
544
545        #[cfg(feature = "debug")]
546        let debug_run = self.debugger_setup()?;
547
548        let mut config = self
549            .run
550            .common
551            .config(use_pooling_allocator_by_default().unwrap_or(None))?;
552        config.wasm_component_model(true);
553
554        if self.run.common.wasm.timeout.is_some() {
555            config.epoch_interruption(true);
556        }
557
558        match self.run.profile {
559            Some(Profile::Native(s)) => {
560                config.profiler(s);
561            }
562            Some(Profile::Guest { .. }) => {
563                config.epoch_interruption(true);
564            }
565            None => {}
566        }
567
568        let engine = Engine::new(&config)?;
569        let mut linker = Linker::new(&engine);
570
571        self.add_to_linker(&mut linker)?;
572
573        let component = match self.run.load_module(&engine, &self.component, None)? {
574            RunTarget::Core(_) => bail!("The serve command currently requires a component"),
575            RunTarget::Component(c) => c,
576        };
577
578        #[cfg(feature = "debug")]
579        if let Some(debug_run) = debug_run {
580            return self
581                .serve_under_debugger(debug_run, &engine, &linker, &component)
582                .await;
583        }
584
585        let instance = linker.instantiate_pre(&component)?;
586        #[cfg(feature = "component-model-async")]
587        let instance = match wasmtime_wasi_http::p3::bindings::ServicePre::new(instance.clone()) {
588            Ok(pre) => ProxyPre::P3(pre),
589            Err(_) => ProxyPre::P2(p2::ProxyPre::new(instance)?),
590        };
591        #[cfg(not(feature = "component-model-async"))]
592        let instance = ProxyPre::P2(p2::ProxyPre::new(instance)?);
593
594        // Spawn background task(s) waiting for graceful shutdown signals. This
595        // always listens for ctrl-c but additionally can listen for a TCP
596        // connection to the specified address.
597        let shutdown = Arc::new(GracefulShutdown::default());
598        tokio::task::spawn({
599            let shutdown = shutdown.clone();
600            async move {
601                tokio::signal::ctrl_c().await.unwrap();
602                shutdown.requested.notify_one();
603            }
604        });
605        if let Some(addr) = self.shutdown_addr {
606            let listener = tokio::net::TcpListener::bind(addr).await?;
607            eprintln!(
608                "Listening for shutdown on tcp://{}/",
609                listener.local_addr()?
610            );
611            let shutdown = shutdown.clone();
612            tokio::task::spawn(async move {
613                let _ = listener.accept().await;
614                shutdown.requested.notify_one();
615            });
616        }
617
618        let socket = match &self.addr {
619            SocketAddr::V4(_) => tokio::net::TcpSocket::new_v4()?,
620            SocketAddr::V6(_) => tokio::net::TcpSocket::new_v6()?,
621        };
622        // Conditionally enable `SO_REUSEADDR` depending on the current
623        // platform. On Unix we want this to be able to rebind an address in
624        // the `TIME_WAIT` state which can happen then a server is killed with
625        // active TCP connections and then restarted. On Windows though if
626        // `SO_REUSEADDR` is specified then it enables multiple applications to
627        // bind the port at the same time which is not something we want. Hence
628        // this is conditionally set based on the platform (and deviates from
629        // Tokio's default from always-on).
630        socket.set_reuseaddr(!cfg!(windows))?;
631        socket.bind(self.addr)?;
632        let listener = socket.listen(100)?;
633
634        eprintln!("Serving HTTP on http://{}/", listener.local_addr()?);
635
636        log::info!("Listening on {}", self.addr);
637
638        let epoch_interval = if let Some(Profile::Guest { interval, .. }) = self.run.profile {
639            Some(interval)
640        } else if let Some(t) = self.run.common.wasm.timeout {
641            Some(EPOCH_INTERRUPT_PERIOD.min(t))
642        } else {
643            None
644        };
645        let _epoch_thread = epoch_interval.map(|t| EpochThread::spawn(t, engine.clone()));
646
647        let max_instance_reuse_count = self.max_instance_reuse_count.unwrap_or_else(|| {
648            if let ProxyPre::P3(_) = &instance {
649                DEFAULT_WASIP3_MAX_INSTANCE_REUSE_COUNT
650            } else {
651                DEFAULT_WASIP2_MAX_INSTANCE_REUSE_COUNT
652            }
653        });
654
655        let max_instance_concurrent_reuse_count = if let ProxyPre::P3(_) = &instance {
656            self.max_instance_concurrent_reuse_count
657                .unwrap_or(DEFAULT_WASIP3_MAX_INSTANCE_CONCURRENT_REUSE_COUNT)
658        } else {
659            1
660        };
661
662        let handler = ProxyHandler::new(
663            HostHandlerState {
664                cmd: self,
665                engine,
666                component,
667                max_instance_reuse_count,
668                max_instance_concurrent_reuse_count,
669            },
670            instance,
671        );
672
673        loop {
674            // Wait for a socket, but also "race" against shutdown to break out
675            // of this loop. Once the graceful shutdown signal is received then
676            // this loop exits immediately.
677            let (stream, _) = tokio::select! {
678                _ = shutdown.requested.notified() => break,
679                v = listener.accept() => v?,
680            };
681
682            // The Nagle algorithm can impose a significant latency penalty
683            // (e.g. 40ms on Linux) on guests which write small, intermittent
684            // response body chunks (e.g. SSE streams).  Here we disable that
685            // algorithm and rely on the guest to buffer if appropriate to avoid
686            // TCP fragmentation.
687            stream.set_nodelay(true)?;
688
689            let stream = TokioIo::new(stream);
690            let h = handler.clone();
691            let shutdown_guard = shutdown.clone().increment();
692            tokio::task::spawn(async move {
693                if let Err(e) = http1::Builder::new()
694                    .keep_alive(true)
695                    .serve_connection(
696                        stream,
697                        hyper::service::service_fn(move |req| {
698                            let h = h.clone();
699                            async move {
700                                use http_body_util::{BodyExt, Full};
701                                match handle_request(h, req).await {
702                                    Ok(r) => Ok::<_, Infallible>(r),
703                                    Err(e) => {
704                                        eprintln!("error: {e:?}");
705                                        let error_html = "\
706<!doctype html>
707<html>
708<head>
709    <title>500 Internal Server Error</title>
710</head>
711<body>
712    <center>
713        <h1>500 Internal Server Error</h1>
714        <hr>
715        wasmtime
716    </center>
717</body>
718</html>";
719                                        Ok(Response::builder()
720                                            .status(StatusCode::INTERNAL_SERVER_ERROR)
721                                            .header("Content-Type", "text/html; charset=UTF-8")
722                                            .body(
723                                                Full::new(bytes::Bytes::from(error_html))
724                                                    .map_err(|_| unreachable!())
725                                                    .boxed_unsync(),
726                                            )
727                                            .unwrap())
728                                    }
729                                }
730                            }
731                        }),
732                    )
733                    .await
734                {
735                    eprintln!("error: {e:?}");
736                }
737                drop(shutdown_guard);
738            });
739        }
740
741        // Upon exiting the loop we'll no longer process any more incoming
742        // connections but there may still be outstanding connections
743        // processing in child tasks. If there are wait for those to complete
744        // before shutting down completely. Also enable short-circuiting this
745        // wait with a second ctrl-c signal.
746        if shutdown.close() {
747            return Ok(());
748        }
749        eprintln!("Waiting for child tasks to exit, ctrl-c again to quit sooner...");
750        tokio::select! {
751            _ = tokio::signal::ctrl_c() => {}
752            _ = shutdown.complete.notified() => {}
753        }
754
755        Ok(())
756    }
757}
758
759struct HostHandlerState {
760    cmd: ServeCommand,
761    engine: Engine,
762    component: Component,
763    max_instance_reuse_count: usize,
764    max_instance_concurrent_reuse_count: usize,
765}
766
767impl HandlerState for HostHandlerState {
768    type StoreData = Host;
769
770    fn new_store(&self, req_id: Option<u64>) -> Result<StoreBundle<Host>> {
771        let mut store = self.cmd.new_store(&self.engine, req_id)?;
772        let write_profile = setup_epoch_handler(&self.cmd, &mut store, self.component.clone())?;
773
774        Ok(StoreBundle {
775            store,
776            write_profile,
777        })
778    }
779
780    fn request_timeout(&self) -> Duration {
781        self.cmd.run.common.wasm.timeout.unwrap_or(Duration::MAX)
782    }
783
784    fn idle_instance_timeout(&self) -> Duration {
785        self.cmd.idle_instance_timeout
786    }
787
788    fn max_instance_reuse_count(&self) -> usize {
789        self.max_instance_reuse_count
790    }
791
792    fn max_instance_concurrent_reuse_count(&self) -> usize {
793        self.max_instance_concurrent_reuse_count
794    }
795
796    fn handle_worker_error(&self, error: wasmtime::Error) {
797        eprintln!("worker error: {error}");
798    }
799}
800
801/// Helper structure to manage graceful shutdown int he accept loop above.
802#[derive(Default)]
803struct GracefulShutdown {
804    /// Async notification that shutdown has been requested.
805    requested: Notify,
806    /// Async notification that shutdown has completed, signaled when
807    /// `notify_when_done` is `true` and `active_tasks` reaches 0.
808    complete: Notify,
809    /// Internal state related to what's in progress when shutdown is requested.
810    state: Mutex<GracefulShutdownState>,
811}
812
813#[derive(Default)]
814struct GracefulShutdownState {
815    active_tasks: u32,
816    notify_when_done: bool,
817}
818
819impl GracefulShutdown {
820    /// Increments the number of active tasks and returns a guard indicating
821    fn increment(self: Arc<Self>) -> impl Drop {
822        struct Guard(Arc<GracefulShutdown>);
823
824        let mut state = self.state.lock().unwrap();
825        assert!(!state.notify_when_done);
826        state.active_tasks += 1;
827        drop(state);
828
829        return Guard(self);
830
831        impl Drop for Guard {
832            fn drop(&mut self) {
833                let mut state = self.0.state.lock().unwrap();
834                state.active_tasks -= 1;
835                if state.notify_when_done && state.active_tasks == 0 {
836                    self.0.complete.notify_one();
837                }
838            }
839        }
840    }
841
842    /// Flags this state as done spawning tasks and returns whether there are no
843    /// more child tasks remaining.
844    fn close(&self) -> bool {
845        let mut state = self.state.lock().unwrap();
846        state.notify_when_done = true;
847        state.active_tasks == 0
848    }
849}
850
851/// When executing with a timeout enabled, this is how frequently epoch
852/// interrupts will be executed to check for timeouts. If guest profiling
853/// is enabled, the guest epoch period will be used.
854const EPOCH_INTERRUPT_PERIOD: Duration = Duration::from_millis(50);
855
856struct EpochThread {
857    shutdown: Arc<AtomicBool>,
858    handle: Option<std::thread::JoinHandle<()>>,
859}
860
861impl EpochThread {
862    fn spawn(interval: std::time::Duration, engine: Engine) -> Self {
863        let shutdown = Arc::new(AtomicBool::new(false));
864        let handle = {
865            let shutdown = Arc::clone(&shutdown);
866            let handle = std::thread::spawn(move || {
867                while !shutdown.load(Ordering::Relaxed) {
868                    std::thread::sleep(interval);
869                    engine.increment_epoch();
870                }
871            });
872            Some(handle)
873        };
874
875        EpochThread { shutdown, handle }
876    }
877}
878
879impl Drop for EpochThread {
880    fn drop(&mut self) {
881        if let Some(handle) = self.handle.take() {
882            self.shutdown.store(true, Ordering::Relaxed);
883            handle.join().unwrap();
884        }
885    }
886}
887
888type WriteProfile = Box<dyn FnOnce(StoreContextMut<Host>) + Send>;
889
890fn setup_epoch_handler(
891    cmd: &ServeCommand,
892    store: &mut Store<Host>,
893    component: Component,
894) -> Result<WriteProfile> {
895    // Profiling Enabled
896    if let Some(Profile::Guest { interval, path }) = &cmd.run.profile {
897        #[cfg(feature = "profiling")]
898        return setup_guest_profiler(store, path.clone(), *interval, component.clone());
899        #[cfg(not(feature = "profiling"))]
900        {
901            let _ = (path, interval);
902            bail!("support for profiling disabled at compile time!");
903        }
904    }
905
906    // Profiling disabled but there's a global request timeout
907    if cmd.run.common.wasm.timeout.is_some() {
908        store.epoch_deadline_async_yield_and_update(1);
909    }
910
911    Ok(Box::new(|_store| {}))
912}
913
914#[cfg(feature = "profiling")]
915fn setup_guest_profiler(
916    store: &mut Store<Host>,
917    path: String,
918    interval: Duration,
919    component: Component,
920) -> Result<WriteProfile> {
921    use wasmtime::{AsContext, GuestProfiler, StoreContext, StoreContextMut};
922
923    let module_name = "<main>";
924
925    store.data_mut().guest_profiler = Some(Arc::new(GuestProfiler::new_component(
926        store.engine(),
927        module_name,
928        interval,
929        component,
930        std::iter::empty(),
931    )?));
932
933    fn sample(
934        mut store: StoreContextMut<Host>,
935        f: impl FnOnce(&mut GuestProfiler, StoreContext<Host>),
936    ) {
937        let mut profiler = store.data_mut().guest_profiler.take().unwrap();
938        f(
939            Arc::get_mut(&mut profiler).expect("profiling doesn't support threads yet"),
940            store.as_context(),
941        );
942        store.data_mut().guest_profiler = Some(profiler);
943    }
944
945    // Hostcall entry/exit, etc.
946    store.call_hook(|store, kind| {
947        sample(store, |profiler, store| profiler.call_hook(store, kind));
948        Ok(())
949    });
950
951    store.epoch_deadline_callback(move |store| {
952        sample(store, |profiler, store| {
953            profiler.sample(store, std::time::Duration::ZERO)
954        });
955
956        Ok(UpdateDeadline::Continue(1))
957    });
958
959    store.set_epoch_deadline(1);
960
961    let write_profile = Box::new(move |mut store: StoreContextMut<Host>| {
962        let profiler = Arc::try_unwrap(store.data_mut().guest_profiler.take().unwrap())
963            .expect("profiling doesn't support threads yet");
964        if let Err(e) = std::fs::File::create(&path)
965            .map_err(wasmtime::Error::new)
966            .and_then(|output| profiler.finish(std::io::BufWriter::new(output)))
967        {
968            eprintln!("failed writing profile at {path}: {e:#}");
969        } else {
970            eprintln!();
971            eprintln!("Profile written to: {path}");
972            eprintln!("View this profile at https://profiler.firefox.com/.");
973        }
974    });
975
976    Ok(write_profile)
977}
978
979/// Build a minimal error response with an empty body.
980fn error_response(status: StatusCode) -> hyper::Response<UnsyncBoxBody<Bytes, wasmtime::Error>> {
981    Response::builder()
982        .status(status)
983        .body(
984            http_body_util::Empty::new()
985                .map_err(|_| unreachable!())
986                .boxed_unsync(),
987        )
988        .unwrap()
989}
990
991/// Debuggee body for `wasmtime serve -g`: instantiate the HTTP component
992/// once, then handle requests sequentially on a single store.
993#[cfg(feature = "debug")]
994async fn debug_serve_body(
995    store: &mut Store<Host>,
996    proxy_pre: wasmtime_wasi_http::p2::bindings::ProxyPre<Host>,
997    addr: SocketAddr,
998) -> Result<()> {
999    use hyper::server::conn::http1;
1000    use wasmtime_wasi_http::p2::bindings::http::types::Scheme;
1001    use wasmtime_wasi_http::p2::body::HyperOutgoingBody;
1002
1003    type P2Response = std::result::Result<
1004        hyper::Response<HyperOutgoingBody>,
1005        wasmtime_wasi_http::p2::bindings::http::types::ErrorCode,
1006    >;
1007
1008    let engine_clone = store.engine().clone();
1009    let _epoch_thread = std::thread::spawn(move || {
1010        loop {
1011            std::thread::sleep(Duration::from_millis(1));
1012            engine_clone.increment_epoch();
1013        }
1014    });
1015
1016    store.epoch_deadline_async_yield_and_update(1);
1017
1018    // Instantiate the HTTP component once.
1019    let proxy = proxy_pre.instantiate_async(&mut *store).await?;
1020
1021    // Bind the TCP listener.
1022    let socket = match addr {
1023        SocketAddr::V4(_) => tokio::net::TcpSocket::new_v4()?,
1024        SocketAddr::V6(_) => tokio::net::TcpSocket::new_v6()?,
1025    };
1026    socket.set_reuseaddr(!cfg!(windows))?;
1027    socket.bind(addr)?;
1028    let listener = socket.listen(100)?;
1029    eprintln!("Serving HTTP on http://{}/", listener.local_addr()?);
1030
1031    // Accept loop: handle one connection at a time, requests sequentially.
1032    loop {
1033        let (stream, _) = listener.accept().await?;
1034        stream.set_nodelay(true)?;
1035        let stream = TokioIo::new(stream);
1036
1037        // Channel to bridge hyper's service_fn with our sequential
1038        // request processing on the single store.
1039        type RespBody = hyper::Response<UnsyncBoxBody<Bytes, wasmtime::Error>>;
1040        let (req_tx, mut req_rx) = tokio::sync::mpsc::channel::<(
1041            hyper::Request<hyper::body::Incoming>,
1042            tokio::sync::oneshot::Sender<std::result::Result<RespBody, Infallible>>,
1043        )>(1);
1044
1045        let serve_conn = http1::Builder::new().keep_alive(true).serve_connection(
1046            stream,
1047            hyper::service::service_fn(move |req| {
1048                let req_tx = req_tx.clone();
1049                async move {
1050                    let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
1051                    if req_tx.send((req, resp_tx)).await.is_err() {
1052                        return Ok::<_, Infallible>(error_response(
1053                            StatusCode::SERVICE_UNAVAILABLE,
1054                        ));
1055                    }
1056                    resp_rx
1057                        .await
1058                        .unwrap_or(Ok(error_response(StatusCode::SERVICE_UNAVAILABLE)))
1059                }
1060            }),
1061        );
1062
1063        tokio::pin!(serve_conn);
1064
1065        loop {
1066            tokio::select! {
1067                result = &mut serve_conn => {
1068                    if let Err(e) = result {
1069                        eprintln!("connection error: {e:?}");
1070                    }
1071                    break;
1072                }
1073                msg = req_rx.recv() => {
1074                    let Some((req, resp_tx)) = msg else { break };
1075
1076                    let (p2_tx, p2_rx) = tokio::sync::oneshot::channel::<P2Response>();
1077                    let wasi_req = store
1078                        .data_mut()
1079                        .http()
1080                        .new_incoming_request(Scheme::Http, req);
1081                    let wasi_out = wasi_req.and_then(|_req| {
1082                        let out = store.data_mut().http().new_response_outparam(p2_tx);
1083                        out.map(|out| (_req, out))
1084                    });
1085                    let (wasi_req, wasi_out) = match wasi_out {
1086                        Ok(pair) => pair,
1087                        Err(e) => {
1088                            eprintln!("error creating WASI request: {e:?}");
1089                            let _ = resp_tx.send(Ok(error_response(
1090                                StatusCode::INTERNAL_SERVER_ERROR,
1091                            )));
1092                            continue;
1093                        }
1094                    };
1095
1096                    if let Err(e) = proxy
1097                        .wasi_http_incoming_handler()
1098                        .call_handle(&mut *store, wasi_req, wasi_out)
1099                        .await
1100                    {
1101                        eprintln!("handler error: {e:?}");
1102                    }
1103
1104                    let resp = match p2_rx.await {
1105                        Ok(Ok(resp)) => resp.map(|body| {
1106                            body.map_err(|e| e.into()).boxed_unsync()
1107                        }),
1108                        Ok(Err(e)) => {
1109                            eprintln!("component error: {e:?}");
1110                            error_response(StatusCode::INTERNAL_SERVER_ERROR)
1111                        }
1112                        Err(_) => error_response(StatusCode::INTERNAL_SERVER_ERROR),
1113                    };
1114                    let _ = resp_tx.send(Ok(resp));
1115                }
1116            }
1117        }
1118    }
1119}
1120
1121type Request = hyper::Request<hyper::body::Incoming>;
1122
1123async fn handle_request(
1124    handler: ProxyHandler<HostHandlerState>,
1125    req: Request,
1126) -> Result<hyper::Response<UnsyncBoxBody<Bytes, wasmtime::Error>>> {
1127    use tokio::sync::oneshot;
1128
1129    let req_id = handler.next_req_id();
1130
1131    log::info!(
1132        "Request {req_id} handling {} to {}",
1133        req.method(),
1134        req.uri()
1135    );
1136
1137    // Here we must declare different channel types for p2 and p3 since p2's
1138    // `WasiHttpView::new_response_outparam` expects a specific kind of sender
1139    // that uses `p2::http::types::ErrorCode`, and we don't want to have to
1140    // convert from the p3 `ErrorCode` to the p2 one, only to convert again to
1141    // `wasmtime::Error`.
1142
1143    type P2Response = Result<
1144        hyper::Response<wasmtime_wasi_http::p2::body::HyperOutgoingBody>,
1145        p2::http::types::ErrorCode,
1146    >;
1147    type P3Response = hyper::Response<UnsyncBoxBody<Bytes, wasmtime::Error>>;
1148
1149    enum Sender {
1150        P2(oneshot::Sender<P2Response>),
1151        P3(oneshot::Sender<P3Response>),
1152    }
1153
1154    enum Receiver {
1155        P2(oneshot::Receiver<P2Response>),
1156        P3(oneshot::Receiver<P3Response>),
1157    }
1158
1159    let (tx, rx) = match handler.instance_pre() {
1160        ProxyPre::P2(_) => {
1161            let (tx, rx) = oneshot::channel();
1162            (Sender::P2(tx), Receiver::P2(rx))
1163        }
1164        ProxyPre::P3(_) => {
1165            let (tx, rx) = oneshot::channel();
1166            (Sender::P3(tx), Receiver::P3(rx))
1167        }
1168    };
1169
1170    handler.spawn(
1171        if handler.state().max_instance_reuse_count() == 1 {
1172            Some(req_id)
1173        } else {
1174            None
1175        },
1176        Box::new(move |store, proxy| {
1177            Box::pin(
1178                async move {
1179                    match proxy {
1180                        Proxy::P2(proxy) => {
1181                            let Sender::P2(tx) = tx else { unreachable!() };
1182                            let (req, out) = store.with(move |mut store| {
1183                                let req = store
1184                                    .data_mut()
1185                                    .http()
1186                                    .new_incoming_request(p2::http::types::Scheme::Http, req)?;
1187                                let out = store.data_mut().http().new_response_outparam(tx)?;
1188                                wasmtime::error::Ok((req, out))
1189                            })?;
1190
1191                            proxy
1192                                .wasi_http_incoming_handler()
1193                                .call_handle(store, req, out)
1194                                .await
1195                        }
1196                        Proxy::P3(proxy) => {
1197                            use wasmtime_wasi_http::p3::bindings::http::types::{
1198                                ErrorCode, Request,
1199                            };
1200
1201                            let Sender::P3(tx) = tx else { unreachable!() };
1202                            let (req, body) = req.into_parts();
1203                            let body = body.map_err(ErrorCode::from_hyper_request_error);
1204                            let req = http::Request::from_parts(req, body);
1205                            let (request, request_io_result) = Request::from_http(req);
1206                            let res = proxy.handle(store, request).await??;
1207                            let res = store
1208                                .with(|mut store| res.into_http(&mut store, request_io_result))?;
1209
1210                            // With the guest response now transformed into a
1211                            // host-compatible response layer one more wrapper
1212                            // around the body. This layer is solely responsible
1213                            // for dropping a channel half on destruction, and
1214                            // this enables waiting here until the body is
1215                            // consumed by waiting for this destruction to
1216                            // happen.
1217                            let (resp_body_tx, resp_body_rx) = oneshot::channel();
1218                            let res = res.map(|body| {
1219                                let body = body.map_err(|e| e.into());
1220                                P3BodyWrapper {
1221                                    _tx: resp_body_tx,
1222                                    body,
1223                                }
1224                                .boxed_unsync()
1225                            });
1226
1227                            // If `wasmtime serve` is waiting on this response
1228                            // and actually got it then wait for the body to
1229                            // finish, otherwise it's thrown away so skip that
1230                            // step.
1231                            if tx.send(res).is_ok() {
1232                                _ = resp_body_rx.await;
1233                            }
1234
1235                            Ok(())
1236                        }
1237                    }
1238                }
1239                .map(move |result| {
1240                    if let Err(error) = result {
1241                        eprintln!("[{req_id}] :: {error:?}");
1242                    }
1243                }),
1244            )
1245        }),
1246    );
1247
1248    return Ok(match rx {
1249        Receiver::P2(rx) => rx
1250            .await
1251            .context("guest never invoked `response-outparam::set` method")?
1252            .map_err(|e| wasmtime::Error::from(e))?
1253            .map(|body| body.map_err(|e| e.into()).boxed_unsync()),
1254        Receiver::P3(rx) => rx.await?,
1255    });
1256
1257    // Forwarding implementation of `Body` to an inner `B` with the sole purpose
1258    // of carrying `_tx` to its destruction.
1259    struct P3BodyWrapper<B> {
1260        body: B,
1261        _tx: oneshot::Sender<()>,
1262    }
1263
1264    impl<B: Body + Unpin> Body for P3BodyWrapper<B> {
1265        type Data = B::Data;
1266        type Error = B::Error;
1267
1268        fn poll_frame(
1269            mut self: Pin<&mut Self>,
1270            cx: &mut Context<'_>,
1271        ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
1272            Pin::new(&mut self.body).poll_frame(cx)
1273        }
1274
1275        fn is_end_stream(&self) -> bool {
1276            self.body.is_end_stream()
1277        }
1278
1279        fn size_hint(&self) -> SizeHint {
1280            self.body.size_hint()
1281        }
1282    }
1283}
1284
1285#[derive(Clone)]
1286enum Output {
1287    Stdout,
1288    Stderr,
1289}
1290
1291impl Output {
1292    fn write_all(&self, buf: &[u8]) -> io::Result<()> {
1293        use std::io::Write;
1294
1295        match self {
1296            Output::Stdout => std::io::stdout().write_all(buf),
1297            Output::Stderr => std::io::stderr().write_all(buf),
1298        }
1299    }
1300}
1301
1302#[derive(Clone)]
1303struct LogStream {
1304    output: Output,
1305    state: Arc<LogStreamState>,
1306}
1307
1308struct LogStreamState {
1309    prefix: String,
1310    needs_prefix_on_next_write: AtomicBool,
1311}
1312
1313impl LogStream {
1314    fn new(prefix: String, output: Output) -> LogStream {
1315        LogStream {
1316            output,
1317            state: Arc::new(LogStreamState {
1318                prefix,
1319                needs_prefix_on_next_write: AtomicBool::new(true),
1320            }),
1321        }
1322    }
1323
1324    fn write_all(&mut self, mut bytes: &[u8]) -> io::Result<()> {
1325        while !bytes.is_empty() {
1326            if self
1327                .state
1328                .needs_prefix_on_next_write
1329                .load(Ordering::Relaxed)
1330            {
1331                self.output.write_all(self.state.prefix.as_bytes())?;
1332                self.state
1333                    .needs_prefix_on_next_write
1334                    .store(false, Ordering::Relaxed);
1335            }
1336            match bytes.iter().position(|b| *b == b'\n') {
1337                Some(i) => {
1338                    let (a, b) = bytes.split_at(i + 1);
1339                    bytes = b;
1340                    self.output.write_all(a)?;
1341                    self.state
1342                        .needs_prefix_on_next_write
1343                        .store(true, Ordering::Relaxed);
1344                }
1345                None => {
1346                    self.output.write_all(bytes)?;
1347                    break;
1348                }
1349            }
1350        }
1351
1352        Ok(())
1353    }
1354}
1355
1356impl wasmtime_wasi::cli::StdoutStream for LogStream {
1357    fn p2_stream(&self) -> Box<dyn wasmtime_wasi::p2::OutputStream> {
1358        Box::new(self.clone())
1359    }
1360    fn async_stream(&self) -> Box<dyn AsyncWrite + Send + Sync> {
1361        Box::new(self.clone())
1362    }
1363}
1364
1365impl wasmtime_wasi::cli::IsTerminal for LogStream {
1366    fn is_terminal(&self) -> bool {
1367        match &self.output {
1368            Output::Stdout => std::io::stdout().is_terminal(),
1369            Output::Stderr => std::io::stderr().is_terminal(),
1370        }
1371    }
1372}
1373
1374impl wasmtime_wasi::p2::OutputStream for LogStream {
1375    fn write(&mut self, bytes: bytes::Bytes) -> StreamResult<()> {
1376        self.write_all(&bytes)
1377            .map_err(|e| StreamError::LastOperationFailed(e.into()))?;
1378        Ok(())
1379    }
1380
1381    fn flush(&mut self) -> StreamResult<()> {
1382        Ok(())
1383    }
1384
1385    fn check_write(&mut self) -> StreamResult<usize> {
1386        Ok(1024 * 1024)
1387    }
1388}
1389
1390#[async_trait::async_trait]
1391impl wasmtime_wasi::p2::Pollable for LogStream {
1392    async fn ready(&mut self) {}
1393}
1394
1395impl AsyncWrite for LogStream {
1396    fn poll_write(
1397        mut self: Pin<&mut Self>,
1398        _cx: &mut Context<'_>,
1399        buf: &[u8],
1400    ) -> Poll<io::Result<usize>> {
1401        Poll::Ready(self.write_all(buf).map(|_| buf.len()))
1402    }
1403    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1404        Poll::Ready(Ok(()))
1405    }
1406    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1407        Poll::Ready(Ok(()))
1408    }
1409}
1410
1411/// The pooling allocator is tailor made for the `wasmtime serve` use case, so
1412/// try to use it when we can. The main cost of the pooling allocator, however,
1413/// is the virtual memory required to run it. Not all systems support the same
1414/// amount of virtual memory, for example some aarch64 and riscv64 configuration
1415/// only support 39 bits of virtual address space.
1416///
1417/// The pooling allocator, by default, will request 1000 linear memories each
1418/// sized at 6G per linear memory. This is 6T of virtual memory which ends up
1419/// being about 42 bits of the address space. This exceeds the 39 bit limit of
1420/// some systems, so there the pooling allocator will fail by default.
1421///
1422/// This function attempts to dynamically determine the hint for the pooling
1423/// allocator. This returns `Some(true)` if the pooling allocator should be used
1424/// by default, or `None` or an error otherwise.
1425///
1426/// The method for testing this is to allocate a 0-sized 64-bit linear memory
1427/// with a maximum size that's N bits large where we force all memories to be
1428/// static. This should attempt to acquire N bits of the virtual address space.
1429/// If successful that should mean that the pooling allocator is OK to use, but
1430/// if it fails then the pooling allocator is not used and the normal mmap-based
1431/// implementation is used instead.
1432fn use_pooling_allocator_by_default() -> Result<Option<bool>> {
1433    use wasmtime::{Config, Memory, MemoryType};
1434    const BITS_TO_TEST: u32 = 42;
1435    let mut config = Config::new();
1436    config.wasm_memory64(true);
1437    config.memory_reservation(1 << BITS_TO_TEST);
1438    let engine = Engine::new(&config)?;
1439    let mut store = Store::new(&engine, ());
1440    // NB: the maximum size is in wasm pages to take out the 16-bits of wasm
1441    // page size here from the maximum size.
1442    let ty = MemoryType::new64(0, Some(1 << (BITS_TO_TEST - 16)));
1443    if Memory::new(&mut store, ty).is_ok() {
1444        Ok(Some(true))
1445    } else {
1446        Ok(None)
1447    }
1448}