Skip to main content

spin_trigger_http/
server.rs

1use std::{
2    collections::HashMap,
3    io::{ErrorKind, IsTerminal},
4    marker::PhantomData,
5    net::SocketAddr,
6    pin::Pin,
7    sync::{Arc, OnceLock, Weak},
8    task::{Context, Poll},
9    time::{Duration, Instant},
10};
11
12use anyhow::{Context as _, bail};
13use http::{
14    Request, Response, StatusCode, Uri,
15    uri::{Authority, Scheme},
16};
17use http_body_util::BodyExt;
18use hyper::{
19    body::{Bytes, Incoming},
20    service::service_fn,
21};
22use hyper_util::{
23    rt::{TokioExecutor, TokioIo},
24    server::conn::auto::Builder,
25};
26use pin_project_lite::pin_project;
27use rand::RngExt;
28use spin_app::{APP_DESCRIPTION_KEY, APP_NAME_KEY};
29use spin_factor_outbound_http::{OutboundHttpFactor, SelfRequestOrigin};
30use spin_factors::RuntimeFactors;
31use spin_factors_executor::InstanceState;
32use spin_http::{
33    app_info::AppInfo,
34    body,
35    config::{HttpExecutorType, HttpTriggerConfig},
36    routes::{RouteInfo, RouteMatch, Router},
37    trigger::HandlerType,
38};
39use tokio::{
40    io::{AsyncRead, AsyncWrite},
41    net::TcpListener,
42    task,
43};
44use tracing::Instrument;
45use wasmtime::{Store, StoreContextMut, ToWasmtimeResult, component::TaskGroupId};
46use wasmtime_wasi::p2::bindings::CommandIndices;
47use wasmtime_wasi_http::Error as WasiHttpError;
48use wasmtime_wasi_http::handler::{
49    HandlerState, Instance, Proxy, ShouldAccept, WorkerExpiration, WorkerState, WorkerStatus,
50};
51use wasmtime_wasi_http::p2::body::HyperOutgoingBody;
52use wasmtime_wasi_http::p3::bindings::Service;
53
54use crate::{
55    Body, InstanceReuseConfig, NotFoundRouteKind, OutputFormat, TlsConfig, TriggerApp,
56    TriggerInstanceBuilder,
57    headers::strip_forbidden_headers,
58    instrument::{MatchedRoute, finalize_http_span, http_span, instrument_error},
59    outbound_http::OutboundHttpInterceptor,
60    spin::SpinHttpExecutor,
61    wagi::WagiHttpExecutor,
62    wasi::WasiHttpExecutor,
63    wasip3::Wasip3HttpExecutor,
64};
65
66pub const MAX_RETRIES: u16 = 10;
67const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
68
69pub(crate) fn set_request_deadline<T>(
70    store: &mut spin_core::Store<T>,
71    request_deadline: Option<Duration>,
72) {
73    if let Some(timeout) = request_deadline {
74        store.set_deadline(Instant::now() + timeout);
75    }
76}
77
78/// An HTTP server which runs Spin apps.
79pub struct HttpServer<F: RuntimeFactors> {
80    /// The address the server was configured to listen on (the `--listen` value).
81    listen_addr: SocketAddr,
82    /// The address the server is actually bound to, captured once after binding.
83    ///
84    /// This can differ from `listen_addr` when the OS assigns the port — e.g.
85    /// `--listen 127.0.0.1:0` or `--find-free-port`. Self-request origins must use
86    /// this real address rather than the configured one.
87    local_addr: OnceLock<SocketAddr>,
88    /// The TLS configuration for the server.
89    tls_config: Option<TlsConfig>,
90    /// The maximum buffer size for an HTTP1 connection.
91    http1_max_buf_size: Option<usize>,
92    /// Whether to find a free port if the specified port is already in use.
93    find_free_port: bool,
94    /// The output format for the server's startup information.
95    output_format: OutputFormat,
96    /// Hard Wasmtime request deadline for direct HTTP executor paths.
97    request_deadline: Option<Duration>,
98    /// Request router.
99    router: Router,
100    /// The app being triggered.
101    trigger_app: Arc<TriggerApp<F>>,
102    /// The application name, resolved once for use as the `app_id` telemetry attribute.
103    app_id: Arc<str>,
104    // Component ID -> component trigger config
105    component_trigger_configs: HashMap<spin_http::routes::TriggerLookupKey, HttpTriggerConfig>,
106    // Component ID -> handler type
107    component_handler_types: HashMap<String, HandlerType<HttpHandlerState<F>>>,
108}
109
110impl<F: RuntimeFactors> HttpServer<F> {
111    /// Create a new [`HttpServer`].
112    pub fn new(
113        listen_addr: SocketAddr,
114        tls_config: Option<TlsConfig>,
115        find_free_port: bool,
116        trigger_app: TriggerApp<F>,
117        http1_max_buf_size: Option<usize>,
118        reuse_config: InstanceReuseConfig,
119        output_format: OutputFormat,
120    ) -> anyhow::Result<Self> {
121        // This needs to be a vec before building the router to handle duplicate routes
122        let component_trigger_configs = trigger_app
123            .app()
124            .trigger_configs::<HttpTriggerConfig>("http")?
125            .into_iter()
126            .map(|(trigger_id, config)| config.lookup_key(trigger_id).map(|k| (k, config)))
127            .collect::<Result<Vec<_>, _>>()?;
128
129        // Build router
130        let component_routes = component_trigger_configs
131            .iter()
132            .map(|(key, config)| (key, &config.route));
133        let mut duplicate_routes = Vec::new();
134        let router = Router::build("/", component_routes, Some(&mut duplicate_routes))?;
135        if !duplicate_routes.is_empty() {
136            tracing::error!(
137                "The following component routes are duplicates and will never be used:"
138            );
139            for dup in &duplicate_routes {
140                tracing::error!(
141                    "  {}: {} (duplicate of {})",
142                    dup.replaced_id,
143                    dup.route(),
144                    dup.effective_id,
145                );
146            }
147        }
148        if router.contains_reserved_route() {
149            tracing::error!(
150                "Routes under {} are handled by the Spin runtime and will never be reached",
151                spin_http::WELL_KNOWN_PREFIX
152            );
153        }
154        tracing::trace!(
155            "Constructed router: {:?}",
156            router.routes().collect::<Vec<_>>()
157        );
158
159        // Now that router is built we can merge duplicate routes by component
160        let component_trigger_configs = HashMap::from_iter(component_trigger_configs);
161
162        let trigger_app = Arc::new(trigger_app);
163
164        let app_id: Arc<str> = trigger_app
165            .app()
166            .get_metadata(APP_NAME_KEY)?
167            .unwrap_or_else(|| "<unnamed>".into())
168            .into();
169
170        let component_handler_types = component_trigger_configs
171            .iter()
172            .filter_map(|(key, trigger_config)| match key {
173                spin_http::routes::TriggerLookupKey::Component(component) => Some(
174                    Self::handler_type_for_component(
175                        &trigger_app,
176                        component,
177                        &trigger_config.executor,
178                        reuse_config,
179                    )
180                    .map(|ht| (component.clone(), ht)),
181                ),
182                spin_http::routes::TriggerLookupKey::Trigger(_) => None,
183            })
184            .collect::<anyhow::Result<_>>()?;
185        Ok(Self {
186            listen_addr,
187            local_addr: OnceLock::new(),
188            tls_config,
189            find_free_port,
190            router,
191            trigger_app,
192            app_id,
193            http1_max_buf_size,
194            component_trigger_configs,
195            component_handler_types,
196            output_format,
197            request_deadline: reuse_config.request_deadline,
198        })
199    }
200
201    fn handler_type_for_component(
202        trigger_app: &Arc<TriggerApp<F>>,
203        component_id: &str,
204        executor: &Option<HttpExecutorType>,
205        reuse_config: InstanceReuseConfig,
206    ) -> anyhow::Result<HandlerType<HttpHandlerState<F>>> {
207        let pre = trigger_app.get_instance_pre(component_id)?;
208        let handler_type = match executor {
209            None | Some(HttpExecutorType::Http) => HandlerType::from_instance_pre(
210                pre,
211                HttpHandlerState {
212                    component_id: component_id.into(),
213                    reuse_config,
214                    server: Default::default(),
215                    self_scheme: Default::default(),
216                },
217            )?,
218            Some(HttpExecutorType::Wagi(wagi_config)) => {
219                anyhow::ensure!(
220                    wagi_config.entrypoint == "_start",
221                    "Wagi component '{component_id}' cannot use deprecated 'entrypoint' field"
222                );
223                HandlerType::Wagi(
224                    CommandIndices::new(pre)
225                        .map_err(anyhow::Error::from)
226                        .context("failed to find wasi command interface for wagi executor")?,
227                )
228            }
229        };
230        Ok(handler_type)
231    }
232
233    /// Serve incoming requests over the provided [`TcpListener`].
234    pub async fn serve(self: Arc<Self>) -> anyhow::Result<()> {
235        let listener: TcpListener = if self.find_free_port {
236            self.search_for_free_port().await?
237        } else {
238            TcpListener::bind(self.listen_addr).await.map_err(|err| {
239                if err.kind() == ErrorKind::AddrInUse {
240                    anyhow::anyhow!("{} is already in use. To have Spin search for a free port, use the --find-free-port option.", self.listen_addr)
241                } else {
242                    anyhow::anyhow!("Unable to listen on {}: {err:?}", self.listen_addr)
243                }
244            })?
245        };
246
247        let _ = self.local_addr.set(listener.local_addr()?);
248
249        if let Some(tls_config) = self.tls_config.clone() {
250            self.serve_https(listener, tls_config).await?;
251        } else {
252            self.serve_http(listener).await?;
253        }
254        Ok(())
255    }
256
257    async fn search_for_free_port(&self) -> anyhow::Result<TcpListener> {
258        let mut found_listener = None;
259        let mut addr = self.listen_addr;
260
261        for _ in 1..=MAX_RETRIES {
262            if addr.port() == u16::MAX {
263                anyhow::bail!(
264                    "Couldn't find a free port as we've reached the maximum port number. Consider retrying with a lower base port."
265                );
266            }
267
268            match TcpListener::bind(addr).await {
269                Ok(listener) => {
270                    found_listener = Some(listener);
271                    break;
272                }
273                Err(err) if err.kind() == ErrorKind::AddrInUse => {
274                    addr.set_port(addr.port() + 1);
275                    continue;
276                }
277                Err(err) => anyhow::bail!("Unable to listen on {addr}: {err:?}",),
278            }
279        }
280
281        found_listener.ok_or_else(|| anyhow::anyhow!(
282            "Couldn't find a free port in the range {}-{}. Consider retrying with a different base port.",
283            self.listen_addr.port(),
284            self.listen_addr.port() + MAX_RETRIES
285        ))
286    }
287
288    async fn serve_http(self: Arc<Self>, listener: TcpListener) -> anyhow::Result<()> {
289        self.print_startup_msgs("http", &listener)?;
290        loop {
291            let (stream, client_addr) = listener.accept().await?;
292            self.clone()
293                .serve_connection(stream, Scheme::HTTP, client_addr);
294        }
295    }
296
297    async fn serve_https(
298        self: Arc<Self>,
299        listener: TcpListener,
300        tls_config: TlsConfig,
301    ) -> anyhow::Result<()> {
302        self.print_startup_msgs("https", &listener)?;
303        let acceptor = tls_config.server_config()?;
304        loop {
305            let (stream, client_addr) = match listener.accept().await {
306                Ok(stm_addr) => stm_addr,
307                Err(e) if can_continue_after(&e) => continue,
308                Err(e) => return Err(e.into()),
309            };
310
311            let server = self.clone();
312            let acceptor = acceptor.clone();
313
314            task::spawn(async move {
315                match tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, acceptor.accept(stream)).await {
316                    Ok(Ok(stream)) => server.serve_connection(stream, Scheme::HTTPS, client_addr),
317                    Ok(Err(err)) => {
318                        tracing::error!(%client_addr, ?err, "Failed to start TLS session")
319                    }
320                    Err(_) => {
321                        tracing::warn!(%client_addr, "Handshake timeout starting TLS session")
322                    }
323                }
324            });
325        }
326    }
327
328    /// Handles incoming requests using an HTTP executor.
329    ///
330    /// This method handles well known paths and routes requests to the handler when the router
331    /// matches the requests path.
332    pub async fn handle(
333        self: &Arc<Self>,
334        mut req: Request<Body>,
335        server_scheme: Scheme,
336        client_addr: SocketAddr,
337    ) -> anyhow::Result<Response<Body>> {
338        strip_forbidden_headers(&mut req);
339
340        spin_telemetry::extract_trace_context(&req);
341
342        let path = req.uri().path().to_string();
343
344        tracing::info!("Processing request on path '{path}'");
345
346        // Handle well-known spin paths
347        if let Some(well_known) = path.strip_prefix(spin_http::WELL_KNOWN_PREFIX) {
348            return match well_known {
349                "health" => Ok(MatchedRoute::with_response_extension(
350                    Response::new(body::full(Bytes::from_static(b"OK"))),
351                    path,
352                )),
353                "info" => self.app_info(path),
354                _ => Self::not_found(NotFoundRouteKind::WellKnown),
355            };
356        }
357
358        match self.router.route(&path) {
359            Ok(route_match) => {
360                self.handle_trigger_route(req, route_match, server_scheme, client_addr)
361                    .await
362            }
363            Err(_) => Self::not_found(NotFoundRouteKind::Normal(path.to_string())),
364        }
365    }
366
367    /// Handles a successful route match.
368    pub async fn handle_trigger_route(
369        self: &Arc<Self>,
370        mut req: Request<Body>,
371        route_match: RouteMatch<'_, '_>,
372        server_scheme: Scheme,
373        client_addr: SocketAddr,
374    ) -> anyhow::Result<Response<Body>> {
375        set_req_uri(&mut req, server_scheme)?;
376        let lookup_key = route_match.lookup_key();
377
378        spin_telemetry::metrics::counter!(
379            spin.request_count = 1,
380            trigger_type = "http",
381            app_id = self.app_id.clone(),
382            component_id = lookup_key.to_string()
383        );
384
385        let trigger_config = self
386            .component_trigger_configs
387            .get(lookup_key)
388            .with_context(|| format!("unknown routing destination '{lookup_key}'"))?;
389
390        match (&trigger_config.component, &trigger_config.static_response) {
391            (Some(component), None) => {
392                self.respond_wasm_component(
393                    req,
394                    route_match,
395                    client_addr,
396                    component,
397                    &trigger_config.executor,
398                )
399                .await
400            }
401            (None, Some(static_response)) => Self::respond_static_response(static_response),
402            // These error cases should have been ruled out by this point but belt and braces
403            (None, None) => Err(anyhow::anyhow!(
404                "Triggers must specify either component or static_response - neither is specified for {}",
405                route_match.raw_route()
406            )),
407            (Some(_), Some(_)) => Err(anyhow::anyhow!(
408                "Triggers must specify either component or static_response - both are specified for {}",
409                route_match.raw_route()
410            )),
411        }
412    }
413
414    fn get_local_addr(&self) -> SocketAddr {
415        self.local_addr.get().copied().unwrap_or(self.listen_addr)
416    }
417
418    async fn respond_wasm_component(
419        self: &Arc<Self>,
420        req: Request<Body>,
421        route_match: RouteMatch<'_, '_>,
422        client_addr: SocketAddr,
423        component_id: &str,
424        executor: &Option<HttpExecutorType>,
425    ) -> anyhow::Result<Response<Body>> {
426        // Prepare HTTP executor
427        let handler_type = self
428            .component_handler_types
429            .get(component_id)
430            .with_context(|| format!("unknown component ID {component_id:?}"))?;
431        let executor = executor.as_ref().unwrap_or(&HttpExecutorType::Http);
432
433        let res = match executor {
434            HttpExecutorType::Http => match handler_type {
435                HandlerType::Spin => {
436                    SpinHttpExecutor
437                        .execute(self, &route_match, req, client_addr, component_id)
438                        .await
439                }
440                HandlerType::Wasi0_3(handler) => {
441                    Wasip3HttpExecutor(handler)
442                        .execute(self, &route_match, req, client_addr)
443                        .await
444                }
445                HandlerType::Wasi0_2(_)
446                | HandlerType::Wasi2023_11_10(_)
447                | HandlerType::Wasi2023_10_18(_)
448                | HandlerType::Wasi2026_03_15(_) => {
449                    WasiHttpExecutor { handler_type }
450                        .execute(self, &route_match, req, client_addr, component_id)
451                        .await
452                }
453                HandlerType::Wagi(_) => unreachable!(),
454            },
455            HttpExecutorType::Wagi(wagi_config) => {
456                let indices = match handler_type {
457                    HandlerType::Wagi(indices) => indices,
458                    _ => unreachable!(),
459                };
460                let executor = WagiHttpExecutor {
461                    wagi_config,
462                    indices,
463                };
464                executor
465                    .execute(self, &route_match, req, client_addr, component_id)
466                    .await
467            }
468        };
469        match res {
470            Ok(res) => Ok(MatchedRoute::with_response_extension(
471                res,
472                route_match.raw_route(),
473            )),
474            Err(err) => {
475                tracing::error!("Error processing request: {err:?}");
476                instrument_error(&err);
477                Self::internal_error(None, route_match.raw_route())
478            }
479        }
480    }
481
482    pub(crate) fn trigger_instance_builder(
483        self: &'_ Arc<Self>,
484        component_id: &str,
485        self_scheme: Option<&Scheme>,
486    ) -> anyhow::Result<TriggerInstanceBuilder<'_, F>> {
487        let mut instance_builder = self.trigger_app.prepare(component_id)?;
488
489        // Set up outbound HTTP request origin and service chaining
490        // The outbound HTTP factor is required since both inbound and outbound wasi HTTP
491        // implementations assume they use the same underlying wasmtime resource storage.
492        // Eventually, we may be able to factor this out to a separate factor.
493        let outbound_http = instance_builder
494            .factor_builder::<OutboundHttpFactor>()
495            .context(
496            "The wasi HTTP trigger was configured without the required wasi outbound http support",
497        )?;
498
499        let self_scheme = self_scheme.cloned().unwrap_or(Scheme::HTTPS);
500        let self_addr = self.get_local_addr();
501        let origin = SelfRequestOrigin::create(self_scheme, &self_addr.to_string())?;
502        outbound_http.set_self_request_origin(origin);
503        outbound_http.set_request_interceptor(OutboundHttpInterceptor::new(self.clone()))?;
504        Ok(instance_builder)
505    }
506
507    fn respond_static_response(
508        sr: &spin_http::config::StaticResponse,
509    ) -> anyhow::Result<Response<Body>> {
510        let mut response = Response::builder();
511
512        response = response.status(sr.status());
513        for (header_name, header_value) in sr.headers() {
514            response = response.header(header_name, header_value);
515        }
516
517        let body = match sr.body() {
518            Some(b) => body::full(b.clone().into()),
519            None => body::empty(),
520        };
521
522        Ok(response.body(body)?)
523    }
524
525    /// Returns spin status information.
526    fn app_info(&self, route: String) -> anyhow::Result<Response<Body>> {
527        let info = AppInfo::new(self.trigger_app.app());
528        let body = serde_json::to_vec_pretty(&info)?;
529        Ok(MatchedRoute::with_response_extension(
530            Response::builder()
531                .header("content-type", "application/json")
532                .body(body::full(body.into()))?,
533            route,
534        ))
535    }
536
537    /// Creates an HTTP 500 response.
538    fn internal_error(
539        body: Option<&str>,
540        route: impl Into<String>,
541    ) -> anyhow::Result<Response<Body>> {
542        let body = match body {
543            Some(body) => body::full(Bytes::copy_from_slice(body.as_bytes())),
544            None => body::empty(),
545        };
546
547        Ok(MatchedRoute::with_response_extension(
548            Response::builder()
549                .status(StatusCode::INTERNAL_SERVER_ERROR)
550                .body(body)?,
551            route,
552        ))
553    }
554
555    /// Creates an HTTP 404 response.
556    fn not_found(kind: NotFoundRouteKind) -> anyhow::Result<Response<Body>> {
557        use std::sync::atomic::{AtomicBool, Ordering};
558        static SHOWN_GENERIC_404_WARNING: AtomicBool = AtomicBool::new(false);
559        if let NotFoundRouteKind::Normal(route) = kind
560            && !SHOWN_GENERIC_404_WARNING.fetch_or(true, Ordering::Relaxed)
561            && std::io::stderr().is_terminal()
562        {
563            terminal::warn!(
564                "Request to {route} matched no pattern, and received a generic 404 response. To serve a more informative 404 page, add a catch-all (/...) route."
565            );
566        }
567        Ok(Response::builder()
568            .status(StatusCode::NOT_FOUND)
569            .body(body::empty())?)
570    }
571
572    fn serve_connection<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
573        self: Arc<Self>,
574        stream: S,
575        server_scheme: Scheme,
576        client_addr: SocketAddr,
577    ) {
578        task::spawn(async move {
579            let mut server_builder = Builder::new(TokioExecutor::new());
580
581            if let Some(http1_max_buf_size) = self.http1_max_buf_size {
582                server_builder.http1().max_buf_size(http1_max_buf_size);
583            }
584
585            if let Err(err) = server_builder
586                .serve_connection(
587                    TokioIo::new(stream),
588                    service_fn(move |request| {
589                        self.clone().instrumented_service_fn(
590                            server_scheme.clone(),
591                            client_addr,
592                            request,
593                        )
594                    }),
595                )
596                .await
597            {
598                tracing::warn!("Error serving HTTP connection: {err:?}");
599            }
600        });
601    }
602
603    async fn instrumented_service_fn(
604        self: Arc<Self>,
605        server_scheme: Scheme,
606        client_addr: SocketAddr,
607        request: Request<Incoming>,
608    ) -> anyhow::Result<Response<HyperOutgoingBody>> {
609        let span = http_span!(request, client_addr);
610        let method = request.method().to_string();
611        async {
612            let result = self
613                .handle(
614                    request.map(|body: Incoming| body.map_err(WasiHttpError::from).boxed_unsync()),
615                    server_scheme,
616                    client_addr,
617                )
618                .await;
619            finalize_http_span(result, method)
620        }
621        .instrument(span)
622        .await
623    }
624
625    fn get_description_for_route(
626        &self,
627        key: &spin_http::routes::TriggerLookupKey,
628    ) -> anyhow::Result<Option<String>> {
629        if let spin_http::routes::TriggerLookupKey::Component(component_id) = key {
630            self.trigger_app
631                .app()
632                .get_component(component_id)
633                .and_then(|c| c.get_metadata(APP_DESCRIPTION_KEY).transpose())
634                .transpose()
635                .map_err(Into::into)
636        } else {
637            Ok(None)
638        }
639    }
640
641    fn print_startup_msgs(&self, scheme: &str, listener: &TcpListener) -> anyhow::Result<()> {
642        let local_addr = listener.local_addr()?;
643        let base_url = format!("{scheme}://{local_addr:?}");
644        tracing::info!("Serving {base_url}");
645
646        match self.output_format {
647            OutputFormat::Plain => {
648                terminal::step!("\nServing", "{base_url}");
649                println!("Available Routes:");
650                for (route, key) in self.router.routes() {
651                    println!("  {key}: {base_url}{route}");
652                    if let Some(description) = self.get_description_for_route(key)? {
653                        println!("    {description}");
654                    }
655                }
656            }
657            OutputFormat::Json => {
658                #[derive(serde::Serialize)]
659                struct RoutesOutput {
660                    base_url: String,
661                    routes: Vec<RouteEntry>,
662                }
663
664                #[derive(serde::Serialize)]
665                struct RouteEntry {
666                    id: String,
667                    route: String,
668                    wildcard: bool,
669                    #[serde(skip_serializing_if = "Option::is_none")]
670                    description: Option<String>,
671                }
672                let mut routes = Vec::new();
673                for (route, key) in self.router.routes() {
674                    routes.push(RouteEntry {
675                        id: key.to_string(),
676                        route: route.path().to_string(),
677                        wildcard: route.is_wildcard(),
678                        description: self.get_description_for_route(key)?,
679                    });
680                }
681
682                let output = RoutesOutput { base_url, routes };
683                println!("{}", serde_json::to_string_pretty(&output)?);
684            }
685        }
686        Ok(())
687    }
688
689    pub(crate) fn request_deadline(&self) -> Option<Duration> {
690        self.request_deadline
691    }
692}
693
694/// The incoming request's scheme and authority
695///
696/// The incoming request's URI is relative to the server, so we need to set the scheme and authority.
697/// Either the `Host` header or the request's URI's authority is used as the source of truth for the authority.
698/// This function will error if the authority cannot be unambiguously determined.
699fn set_req_uri(req: &mut Request<Body>, scheme: Scheme) -> anyhow::Result<()> {
700    let uri = req.uri().clone();
701    let mut parts = uri.into_parts();
702    let headers = req.headers();
703    let header_authority = headers
704        .get(http::header::HOST)
705        .map(|h| -> anyhow::Result<Authority> {
706            let host_header = h.to_str().context("'Host' header is not valid UTF-8")?;
707            host_header
708                .parse()
709                .context("'Host' header contains an invalid authority")
710        })
711        .transpose()?;
712    let uri_authority = parts.authority;
713
714    // Get authority either from request URI or from 'Host' header
715    let authority = match (header_authority, uri_authority) {
716        (None, None) => bail!("no 'Host' header present in request"),
717        (None, Some(a)) => a,
718        (Some(a), None) => a,
719        (Some(a1), Some(a2)) => {
720            // Ensure that if `req.authority` is set, it matches what was in the `Host` header
721            // https://github.com/hyperium/hyper/issues/1612
722            if a1 != a2 {
723                return Err(anyhow::anyhow!(
724                    "authority in 'Host' header does not match authority in URI"
725                ));
726            }
727            a1
728        }
729    };
730    parts.scheme = Some(scheme);
731    parts.authority = Some(authority);
732    *req.uri_mut() = Uri::from_parts(parts)?;
733    Ok(())
734}
735
736pin_project! {
737    pub(crate) struct HttpWorkerExpiration {
738        idle_timeout: Duration,
739        request_timeout: Duration,
740        #[pin]
741        sleep: tokio::time::Sleep,
742    }
743}
744
745impl WorkerExpiration for HttpWorkerExpiration {
746    fn poll(
747        self: Pin<&mut Self>,
748        cx: &mut Context<'_>,
749        status: WorkerStatus,
750        start: Instant,
751    ) -> Poll<()> {
752        let mut me = self.project();
753
754        let timeout = match status {
755            WorkerStatus::Idle => *me.idle_timeout,
756            // TODO: add a dedicated `post_return_timeout` config setting
757            // instead of reusing `request_timeout` for
758            // `WorkerStatus::PostReturn` here
759            WorkerStatus::Requests | WorkerStatus::PostReturn => *me.request_timeout,
760        };
761
762        if let Some(deadline) = start.checked_add(timeout) {
763            let deadline = deadline.into();
764            if deadline != me.sleep.deadline() {
765                me.sleep.as_mut().reset(deadline);
766            }
767            me.sleep.poll(cx)
768        } else {
769            Poll::Pending
770        }
771    }
772}
773
774pub(crate) struct HttpWorkerState<F: RuntimeFactors> {
775    request_timeout: Duration,
776    max_instance_reuse_count: usize,
777    max_instance_concurrent_reuse_count: usize,
778    _phantom: PhantomData<F>,
779}
780
781impl<F: RuntimeFactors> WorkerState for HttpWorkerState<F> {
782    type StoreData = InstanceState<F::InstanceState, ()>;
783    type RequestData = ();
784
785    fn should_accept_request(&self, concurrent_count: usize, total_count: usize) -> ShouldAccept {
786        if total_count >= self.max_instance_reuse_count {
787            ShouldAccept::Never
788        } else if concurrent_count >= self.max_instance_concurrent_reuse_count {
789            ShouldAccept::No
790        } else {
791            ShouldAccept::Yes
792        }
793    }
794
795    fn on_request_start(
796        &self,
797        _: StoreContextMut<'_, Self::StoreData>,
798        _: Self::RequestData,
799        _: TaskGroupId,
800    ) -> Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>> {
801        Box::pin(tokio::time::sleep(self.request_timeout))
802    }
803
804    fn drop(&self, store: Store<Self::StoreData>, result: Result<(), wasmtime::Error>) {
805        if let Err(error) = result {
806            eprintln!("worker failed: {error:?}");
807        }
808
809        drop(store);
810    }
811}
812
813pub(crate) struct HttpHandlerState<F: RuntimeFactors> {
814    component_id: String,
815    reuse_config: InstanceReuseConfig,
816    server: OnceLock<Weak<HttpServer<F>>>,
817    self_scheme: OnceLock<Scheme>,
818}
819
820impl<F: RuntimeFactors> HttpHandlerState<F> {
821    pub(crate) fn init_once(&self, server: &Arc<HttpServer<F>>, first_uri: &Uri) {
822        self.server.get_or_init(|| Arc::downgrade(server));
823        if let Some(scheme) = first_uri.scheme() {
824            self.self_scheme.get_or_init(|| scheme.clone());
825        }
826    }
827}
828
829impl<F: RuntimeFactors> HandlerState for HttpHandlerState<F> {
830    type StoreData = InstanceState<F::InstanceState, ()>;
831    type WorkerExpiration = HttpWorkerExpiration;
832    type WorkerState = HttpWorkerState<F>;
833
834    async fn instantiate(
835        &self,
836    ) -> wasmtime::Result<Instance<Self::StoreData, Self::WorkerExpiration, Self::WorkerState>>
837    {
838        let server = self
839            .server
840            .get()
841            .expect("server should have been set")
842            .upgrade()
843            .ok_or_else(|| wasmtime::format_err!("HTTP server is no longer available"))?;
844        let (instance, mut store) = server
845            .trigger_instance_builder(&self.component_id, self.self_scheme.get())
846            .to_wasmtime_result()?
847            .instantiate(())
848            .await
849            .to_wasmtime_result()?;
850        set_request_deadline(&mut store, self.reuse_config.request_deadline);
851
852        let mut store = store.into_inner();
853
854        let proxy = Proxy::P3(Service::new(&mut store, &instance).unwrap());
855
856        let request_timeout = self
857            .reuse_config
858            .request_timeout
859            .map(|range| rand::rng().random_range(range))
860            .unwrap_or(Duration::MAX);
861
862        Ok(Instance {
863            store,
864            proxy,
865            view: |data| {
866                spin_factor_outbound_http::OutboundHttpFactor::get_wasi_http_impl(
867                    data.factors_instance_state_mut(),
868                )
869                .unwrap()
870            },
871            expiration: HttpWorkerExpiration {
872                idle_timeout: rand::rng().random_range(self.reuse_config.idle_instance_timeout),
873                request_timeout,
874                sleep: tokio::time::sleep(Duration::MAX),
875            },
876            state: HttpWorkerState {
877                request_timeout,
878                max_instance_reuse_count: rand::rng()
879                    .random_range(self.reuse_config.max_instance_reuse_count),
880                max_instance_concurrent_reuse_count: rand::rng()
881                    .random_range(self.reuse_config.max_instance_concurrent_reuse_count),
882                _phantom: PhantomData,
883            },
884        })
885    }
886}
887
888/// Whether the server can continue serving after the given `accept` error
889/// (e.g. if the connection is reset that is *not* fatal to the server)
890fn can_continue_after(error: &std::io::Error) -> bool {
891    error.kind() == ErrorKind::ConnectionReset || error.kind() == ErrorKind::ConnectionAborted
892}