1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
mod meta;
mod router;
mod service;
use std::{fmt, time::Duration};
use motore::{
    layer::{Identity, Layer, Stack},
    service::{Service, TowerAdapter},
    BoxError,
};
pub use service::ServiceBuilder;
use volo::{net::incoming::Incoming, spawn};
pub use self::router::Router;
use crate::{
    body::Body, context::ServerContext, server::meta::MetaService, Request, Response, Status,
};
pub trait NamedService {
    const NAME: &'static str;
}
#[derive(Clone)]
pub struct Server<L> {
    layer: L,
    http2_config: Http2Config,
    router: Router,
}
impl Default for Server<Identity> {
    fn default() -> Self {
        Self::new()
    }
}
impl Server<Identity> {
    pub fn new() -> Self {
        Self {
            layer: Identity::new(),
            http2_config: Http2Config::default(),
            router: Router::new(),
        }
    }
}
impl<L> Server<L> {
    pub fn http2_init_stream_window_size(mut self, sz: impl Into<u32>) -> Self {
        self.http2_config.init_stream_window_size = sz.into();
        self
    }
    pub fn http2_init_connection_window_size(mut self, sz: impl Into<u32>) -> Self {
        self.http2_config.init_connection_window_size = sz.into();
        self
    }
    pub fn http2_adaptive_window(mut self, enabled: bool) -> Self {
        self.http2_config.adaptive_window = enabled;
        self
    }
    pub fn http2_max_concurrent_streams(mut self, max: impl Into<Option<u32>>) -> Self {
        self.http2_config.max_concurrent_streams = max.into();
        self
    }
    pub fn http2_keepalive_interval(mut self, interval: impl Into<Option<Duration>>) -> Self {
        self.http2_config.http2_keepalive_interval = interval.into();
        self
    }
    pub fn http2_keepalive_timeout(mut self, timeout: Duration) -> Self {
        self.http2_config.http2_keepalive_timeout = timeout;
        self
    }
    pub fn http2_max_frame_size(mut self, sz: impl Into<Option<u32>>) -> Self {
        self.http2_config.max_frame_size = sz.into();
        self
    }
    pub fn http2_max_send_buf_size(mut self, max: impl Into<usize>) -> Self {
        self.http2_config.max_send_buf_size = max.into();
        self
    }
    pub fn http2_max_header_list_size(mut self, max: impl Into<u32>) -> Self {
        self.http2_config.max_header_list_size = max.into();
        self
    }
    pub fn accept_http1(mut self, accept_http1: bool) -> Self {
        self.http2_config.accept_http1 = accept_http1;
        self
    }
    pub fn layer<O>(self, layer: O) -> Server<Stack<O, L>> {
        Server {
            layer: Stack::new(layer, self.layer),
            http2_config: self.http2_config,
            router: self.router,
        }
    }
    pub fn layer_front<Front>(self, layer: Front) -> Server<Stack<L, Front>> {
        Server {
            layer: Stack::new(self.layer, layer),
            http2_config: self.http2_config,
            router: self.router,
        }
    }
    pub fn add_service<S>(self, s: S) -> Self
    where
        S: Service<ServerContext, Request<hyper::Body>, Response = Response<Body>, Error = Status>
            + NamedService
            + Clone
            + Send
            + Sync
            + 'static,
    {
        Self {
            layer: self.layer,
            http2_config: self.http2_config,
            router: self.router.add_service(s),
        }
    }
    pub async fn run<A: volo::net::MakeIncoming>(self, incoming: A) -> Result<(), BoxError>
    where
        L: Layer<Router>,
        L::Service: Service<ServerContext, Request<hyper::Body>, Response = Response<Body>>
            + Clone
            + Send
            + Sync
            + 'static,
        <L::Service as Service<ServerContext, Request<hyper::Body>>>::Error: Into<Status> + Send,
    {
        let mut incoming = incoming.make_incoming().await?;
        tracing::info!("[VOLO] server start at: {:?}", incoming);
        let service = motore::builder::ServiceBuilder::new()
            .layer(self.layer)
            .service(self.router);
        while let Some(conn) = incoming.accept().await? {
            tracing::trace!("[VOLO] recv a connection from: {:?}", conn.info.peer_addr);
            let peer_addr = conn.info.peer_addr.clone();
            let service = MetaService::new(service.clone(), peer_addr)
                .tower(|req| (ServerContext::default(), req));
            let mut server = hyper::server::conn::Http::new();
            server
                .http2_only(!self.http2_config.accept_http1)
                .http2_initial_stream_window_size(self.http2_config.init_stream_window_size)
                .http2_initial_connection_window_size(self.http2_config.init_connection_window_size)
                .http2_adaptive_window(self.http2_config.adaptive_window)
                .http2_max_concurrent_streams(self.http2_config.max_concurrent_streams)
                .http2_keep_alive_interval(self.http2_config.http2_keepalive_interval)
                .http2_keep_alive_timeout(self.http2_config.http2_keepalive_timeout)
                .http2_max_frame_size(self.http2_config.max_frame_size)
                .http2_max_send_buf_size(self.http2_config.max_send_buf_size)
                .http2_max_header_list_size(self.http2_config.max_header_list_size);
            spawn(async move {
                let result = server.serve_connection(conn, service).await;
                if let Err(err) = result {
                    tracing::debug!("[VOLO] connection error: {:?}", err);
                }
            });
        }
        Ok(())
    }
}
impl<L> fmt::Debug for Server<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Server")
            .field("http2_config", &self.http2_config)
            .field("router", &self.router)
            .finish()
    }
}
const DEFAULT_KEEPALIVE_TIMEOUT_SECS: Duration = Duration::from_secs(20);
const DEFAULT_CONN_WINDOW_SIZE: u32 = 1024 * 1024; const DEFAULT_STREAM_WINDOW_SIZE: u32 = 1024 * 1024; const DEFAULT_MAX_SEND_BUF_SIZE: usize = 1024 * 400; const DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE: u32 = 16 << 20; #[derive(Debug, Clone, Copy)]
pub struct Http2Config {
    pub(crate) init_stream_window_size: u32,
    pub(crate) init_connection_window_size: u32,
    pub(crate) max_concurrent_streams: Option<u32>,
    pub(crate) adaptive_window: bool,
    pub(crate) http2_keepalive_interval: Option<Duration>,
    pub(crate) http2_keepalive_timeout: Duration,
    pub(crate) max_frame_size: Option<u32>,
    pub(crate) max_send_buf_size: usize,
    pub(crate) max_header_list_size: u32,
    pub(crate) accept_http1: bool,
}
impl Default for Http2Config {
    fn default() -> Self {
        Self {
            init_stream_window_size: DEFAULT_STREAM_WINDOW_SIZE,
            init_connection_window_size: DEFAULT_CONN_WINDOW_SIZE,
            adaptive_window: false,
            max_concurrent_streams: None,
            http2_keepalive_interval: None,
            http2_keepalive_timeout: DEFAULT_KEEPALIVE_TIMEOUT_SECS,
            max_frame_size: None,
            max_send_buf_size: DEFAULT_MAX_SEND_BUF_SIZE,
            max_header_list_size: DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE,
            accept_http1: false,
        }
    }
}