1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use crate::{CloneCounter, Server};
use std::marker::PhantomData;
use trillium::Handler;
use trillium_http::Stopper;
use trillium_tls_common::Acceptor;

/**
# Primary entrypoint for configuring and running a trillium server

The associated methods on this struct are intended to be chained.

## Example
```rust,no_run
trillium_smol::config() // or trillium_async_std, trillium_tokio
    .with_port(8080) // the default
    .with_host("localhost") // the default
    .with_nodelay()
    .with_max_connections(Some(10000))
    .without_signals()
    .run(|conn: trillium::Conn| async move { conn.ok("hello") });
```

# Socket binding

The socket binding logic is as follows:

* If a LISTEN_FD environment variable is available on `cfg(unix)`
  systems, that will be used, overriding host and port settings
* Otherwise:
  * Host will be selected from explicit configuration using
    [`Config::with_host`] or else the `HOST` environment variable,
    or else a default of "localhost".
    * On `cfg(unix)` systems only: If the host string (as set by env var
      or direct config) begins with `.`, `/`, or `~`, it is
      interpreted to be a path, and trillium will bind to it as a unix
      domain socket. Port will be ignored. The socket will be deleted
      on clean shutdown.
  * Port will be selected from explicit configuration using
    [`Config::with_port`] or else the `PORT` environment variable,
    or else a default of 8080.

## Signals

On `cfg(unix)` systems, `SIGTERM`, `SIGINT`, and `SIGQUIT` are all
registered to perform a graceful shutdown on the first signal and an
immediate shutdown on a subsequent signal. This behavior may change as
trillium matures. To disable this behavior, use
[`Config::without_signals`].

## For runtime adapter authors

In order to use this to _implement_ a trillium server, see
[`trillium_server_common::ConfigExt`](crate::ConfigExt)
*/

#[derive(Debug)]
pub struct Config<ServerType: ?Sized, AcceptorType> {
    pub(crate) acceptor: AcceptorType,
    pub(crate) port: Option<u16>,
    pub(crate) host: Option<String>,
    pub(crate) nodelay: bool,
    pub(crate) stopper: Stopper,
    pub(crate) counter: CloneCounter,
    pub(crate) register_signals: bool,
    pub(crate) max_connections: Option<usize>,
    server: PhantomData<ServerType>,
}

impl<ServerType, AcceptorType> Config<ServerType, AcceptorType>
where
    ServerType: Server + ?Sized,
    AcceptorType: Acceptor<ServerType::Transport>,
{
    /// Starts an async runtime and runs the provided handler with
    /// this config in that runtime. This is the appropriate
    /// entrypoint for applications that do not need to spawn tasks
    /// outside of trillium's web server. For applications that embed a
    /// trillium server inside of an already-running async runtime, use
    /// [`Config::run_async`]
    pub fn run<H: Handler>(self, h: H) {
        ServerType::run(self, h)
    }

    /// Runs the provided handler with this config, in an
    /// already-running runtime. This is the appropriate entrypoint
    /// for an application that needs to spawn async tasks that are
    /// unrelated to the trillium application. If you do not need to spawn
    /// other tasks, [`Config::run`] is the preferred entrypoint
    pub async fn run_async(self, handler: impl Handler) {
        ServerType::run_async(self, handler).await
    }

    /// Configures the server to listen on this port. The default is
    /// the PORT environment variable or 8080
    pub fn with_port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Configures the server to listen on this host or ip
    /// address. The default is the HOST environment variable or
    /// "localhost"
    pub fn with_host(mut self, host: &str) -> Self {
        self.host = Some(host.into());
        self
    }

    /// Configures the server to NOT register for graceful-shutdown
    /// signals with the operating system. Default behavior is for the
    /// server to listen for SIGINT and SIGTERM and perform a graceful
    /// shutdown.
    pub fn without_signals(mut self) -> Self {
        self.register_signals = false;
        self
    }

    /// Configures the tcp listener to use TCP_NODELAY. See
    /// <https://en.wikipedia.org/wiki/Nagle%27s_algorithm> for more
    /// information on this setting.
    pub fn with_nodelay(mut self) -> Self {
        self.nodelay = true;
        self
    }

    /// Configures the tls acceptor for this server
    pub fn with_acceptor<A: Acceptor<ServerType::Transport>>(
        self,
        acceptor: A,
    ) -> Config<ServerType, A> {
        Config {
            acceptor,
            host: self.host,
            port: self.port,
            nodelay: self.nodelay,
            server: PhantomData,
            stopper: self.stopper,
            counter: self.counter,
            register_signals: self.register_signals,
            max_connections: self.max_connections,
        }
    }

    /// use the specific [`Stopper`] provided
    pub fn with_stopper(mut self, stopper: Stopper) -> Self {
        self.stopper = stopper;
        self
    }

    /**
    Configures the maximum number of connections to accept. The
    default is 75% of the soft rlimit_nofile (`ulimit -n`) on unix
    systems, and None on other sytems.
    */
    pub fn with_max_connections(mut self, max_connections: Option<usize>) -> Self {
        self.max_connections = max_connections;
        self
    }
}

impl<ServerType> Config<ServerType, ()> {
    /// build a new config with default acceptor
    pub fn new() -> Self {
        Self::default()
    }
}

impl<ServerType: ?Sized, AcceptorType: Clone> Clone for Config<ServerType, AcceptorType> {
    fn clone(&self) -> Self {
        Self {
            acceptor: self.acceptor.clone(),
            port: self.port,
            host: self.host.clone(),
            server: PhantomData,
            nodelay: self.nodelay,
            stopper: self.stopper.clone(),
            counter: self.counter.clone(),
            register_signals: self.register_signals,
            max_connections: self.max_connections,
        }
    }
}

impl<ServerType> Default for Config<ServerType, ()> {
    fn default() -> Self {
        #[cfg(unix)]
        let max_connections = {
            rlimit::getrlimit(rlimit::Resource::NOFILE)
                .ok()
                .and_then(|(soft, _hard)| soft.try_into().ok())
                .map(|limit: usize| 3 * limit / 4)
        };

        #[cfg(not(unix))]
        let max_connections = None;

        log::debug!("using max connections of {:?}", max_connections);

        Self {
            acceptor: (),
            port: None,
            host: None,
            server: PhantomData,
            nodelay: false,
            stopper: Stopper::new(),
            counter: CloneCounter::new(),
            register_signals: cfg!(unix),
            max_connections,
        }
    }
}