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
use std::{net::SocketAddr, sync::Arc, time::Duration};

use anyhow::{Context, Error};
use futures::{stream::FuturesUnordered, StreamExt};
use http::Request;
use tower::ServiceBuilder;
use tower_http::{catch_panic::CatchPanicLayer, cors::CorsLayer, trace::TraceLayer};
use webc::metadata::Command;

use crate::{
    bin_factory::BinaryPackage,
    runners::wasi::WasiRunner,
    runtime::{task_manager::VirtualTaskManagerExt, DynRuntime},
};

use super::factory::DProxyInstanceFactory;

#[derive(Debug)]
pub struct DProxyRunner {
    config: Config,
    factory: DProxyInstanceFactory,
}

impl DProxyRunner {
    pub fn new(inner: WasiRunner, pkg: &BinaryPackage) -> Self {
        Self {
            config: Config::new(inner, pkg),
            factory: DProxyInstanceFactory::new(),
        }
    }

    pub fn config(&mut self) -> &mut Config {
        &mut self.config
    }
}

/// The base URI used by a [`DProxy`] runner.
pub const DPROXY_RUNNER_URI: &str = "https://webc.org/runner/dproxy";

impl crate::runners::Runner for DProxyRunner {
    fn can_run_command(command: &Command) -> Result<bool, Error> {
        Ok(command.runner.starts_with(DPROXY_RUNNER_URI))
    }

    fn run_command(
        &mut self,
        command_name: &str,
        _pkg: &BinaryPackage,
        runtime: Arc<DynRuntime>,
    ) -> Result<(), Error> {
        // Create the handler that will process the HTTP requests
        let handler = super::handler::Handler::new(
            self.config.clone(),
            command_name.to_string(),
            self.factory.clone(),
            runtime.clone(),
        );

        // We create a HTTP server which will reverse proxy all the requests
        // to the proxy workload
        let service = ServiceBuilder::new()
            .layer(
                TraceLayer::new_for_http()
                    .make_span_with(|request: &Request<hyper::body::Incoming>| {
                        tracing::info_span!(
                            "request",
                            method = %request.method(),
                            uri = %request.uri(),
                            status_code = tracing::field::Empty,
                        )
                    })
                    .on_response(super::super::response_tracing::OnResponseTracer),
            )
            .layer(CatchPanicLayer::new())
            .layer(CorsLayer::permissive())
            .service(handler);

        let address = self.config.addr;
        tracing::info!(%address, "Starting the DProxy server");

        runtime
            .task_manager()
            .spawn_and_block_on(async move {
                let (mut shutdown, _abort_handle) =
                    futures::future::abortable(futures::future::pending::<()>());

                let listener = tokio::net::TcpListener::bind(&address).await?;
                let graceful = hyper_util::server::graceful::GracefulShutdown::new();

                let http = hyper::server::conn::http1::Builder::new();

                let mut futs = FuturesUnordered::new();

                loop {
                    tokio::select! {
                        Ok((stream, _addr)) = listener.accept() => {
                            let io = hyper_util::rt::tokio::TokioIo::new(stream);
                            let service = hyper_util::service::TowerToHyperService::new(service.clone());
                            let conn = http.serve_connection(io, service);
                            // watch this connection
                            let fut = graceful.watch(conn);
                            futs.push(async move {
                                if let Err(e) = fut.await {
                                    eprintln!("Error serving connection: {:?}", e);
                                }
                            });
                        },

                        _ = futs.next() => {}

                        _ = &mut shutdown => {
                            tracing::info!("Shutting down gracefully");
                            // stop the accept loop
                            break;
                        }
                    }
                }

                Ok::<_, anyhow::Error>(())
            })
            .context("Unable to start the server")??;

        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct Config {
    pub(crate) inner: WasiRunner,
    pub(crate) addr: SocketAddr,
    pub(crate) pkg: BinaryPackage,
    pub(crate) proxy_connect_init_timeout: Duration,
    pub(crate) proxy_connect_nominal_timeout: Duration,
}

impl Config {
    pub fn new(inner: WasiRunner, pkg: &BinaryPackage) -> Self {
        Self {
            inner,
            pkg: pkg.clone(),
            addr: ([127, 0, 0, 1], 8000).into(),
            proxy_connect_init_timeout: Duration::from_secs(30),
            proxy_connect_nominal_timeout: Duration::from_secs(30),
        }
    }

    pub fn addr(&mut self, addr: SocketAddr) -> &mut Self {
        self.addr = addr;
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn send_and_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}

        assert_send::<DProxyRunner>();
        assert_sync::<DProxyRunner>();
    }
}