1use std::{
2 fmt,
3 future::Future,
4 net::SocketAddr,
5 pin::Pin,
6 rc::Rc,
7 time::{Duration, Instant},
8};
9
10use bytes::BytesMut;
11
12use crate::{
13 date::{DateService, DATE_VALUE_LENGTH},
14 KeepAlive,
15};
16
17pub(crate) type GracefulShutdownFuture = Pin<Box<dyn Future<Output = ()>>>;
18
19#[derive(Clone)]
20pub(crate) struct GracefulShutdownSignal(Rc<dyn Fn() -> GracefulShutdownFuture>);
21
22impl GracefulShutdownSignal {
23 pub(crate) fn new<F, Fut>(signal: F) -> Self
24 where
25 F: Fn() -> Fut + 'static,
26 Fut: Future<Output = ()> + 'static,
27 {
28 Self(Rc::new(move || Box::pin(signal())))
29 }
30
31 fn notified(&self) -> GracefulShutdownFuture {
32 (self.0)()
33 }
34}
35
36impl fmt::Debug for GracefulShutdownSignal {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.debug_struct("GracefulShutdownSignal")
39 .finish_non_exhaustive()
40 }
41}
42
43pub(crate) const DEFAULT_H2_CONN_WINDOW_SIZE: u32 = 1024 * 1024 * 2; pub(crate) const DEFAULT_H2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024; pub(crate) const DEFAULT_H1_WRITE_BUFFER_SIZE: usize = 32_768;
55
56#[derive(Default, Debug)]
58pub struct ServiceConfigBuilder {
59 inner: Inner,
60}
61
62impl ServiceConfigBuilder {
63 pub fn new() -> Self {
74 Self::default()
75 }
76
77 pub fn secure(mut self, secure: bool) -> Self {
79 self.inner.secure = secure;
80 self
81 }
82
83 pub fn local_addr(mut self, local_addr: Option<SocketAddr>) -> Self {
85 self.inner.local_addr = local_addr;
86 self
87 }
88
89 pub fn keep_alive(mut self, keep_alive: KeepAlive) -> Self {
91 self.inner.keep_alive = keep_alive;
92 self
93 }
94
95 pub fn client_request_timeout(mut self, timeout: Duration) -> Self {
97 self.inner.client_request_timeout = timeout;
98 self
99 }
100
101 pub fn client_disconnect_timeout(mut self, timeout: Duration) -> Self {
104 self.inner.client_disconnect_timeout = timeout;
105 self
106 }
107
108 pub fn tcp_nodelay(mut self, nodelay: Option<bool>) -> Self {
112 self.inner.tcp_nodelay = nodelay;
113 self
114 }
115
116 pub fn h1_allow_half_closed(mut self, allow: bool) -> Self {
122 self.inner.h1_allow_half_closed = allow;
123 self
124 }
125
126 pub fn h1_write_buffer_size(mut self, size: usize) -> Self {
136 assert!(
137 size > 0,
138 "HTTP/1 write buffer size must be greater than zero"
139 );
140
141 self.inner.h1_write_buffer_size = size;
142 self
143 }
144
145 pub(crate) fn graceful_shutdown_signal(
146 mut self,
147 signal: Option<GracefulShutdownSignal>,
148 ) -> Self {
149 self.inner.graceful_shutdown_signal = signal;
150 self
151 }
152
153 pub fn h2_initial_window_size(mut self, size: u32) -> Self {
160 self.inner.h2_stream_window_size = size;
161 self
162 }
163
164 pub fn h2_initial_connection_window_size(mut self, size: u32) -> Self {
171 self.inner.h2_conn_window_size = size;
172 self
173 }
174
175 pub fn build(self) -> ServiceConfig {
177 ServiceConfig(Rc::new(self.inner))
178 }
179}
180
181#[derive(Debug, Clone, Default)]
183pub struct ServiceConfig(Rc<Inner>);
184
185#[derive(Debug)]
186struct Inner {
187 keep_alive: KeepAlive,
188 client_request_timeout: Duration,
189 client_disconnect_timeout: Duration,
190 secure: bool,
191 local_addr: Option<SocketAddr>,
192 tcp_nodelay: Option<bool>,
193 date_service: DateService,
194 h1_allow_half_closed: bool,
195 h1_write_buffer_size: usize,
196 h2_conn_window_size: u32,
197 h2_stream_window_size: u32,
198 graceful_shutdown_signal: Option<GracefulShutdownSignal>,
199}
200
201impl Default for Inner {
202 fn default() -> Self {
203 Self {
204 keep_alive: KeepAlive::default(),
205 client_request_timeout: Duration::from_secs(5),
206 client_disconnect_timeout: Duration::ZERO,
207 secure: false,
208 local_addr: None,
209 tcp_nodelay: Some(true),
210 date_service: DateService::new(),
211 h1_allow_half_closed: true,
212 h1_write_buffer_size: DEFAULT_H1_WRITE_BUFFER_SIZE,
213 h2_conn_window_size: DEFAULT_H2_CONN_WINDOW_SIZE,
214 h2_stream_window_size: DEFAULT_H2_STREAM_WINDOW_SIZE,
215 graceful_shutdown_signal: None,
216 }
217 }
218}
219
220impl ServiceConfig {
221 pub fn new(
223 keep_alive: KeepAlive,
224 client_request_timeout: Duration,
225 client_disconnect_timeout: Duration,
226 secure: bool,
227 local_addr: Option<SocketAddr>,
228 ) -> ServiceConfig {
229 ServiceConfig(Rc::new(Inner {
230 keep_alive: keep_alive.normalize(),
231 client_request_timeout,
232 client_disconnect_timeout,
233 secure,
234 local_addr,
235 tcp_nodelay: Some(true),
236 date_service: DateService::new(),
237 h1_allow_half_closed: true,
238 h1_write_buffer_size: DEFAULT_H1_WRITE_BUFFER_SIZE,
239 h2_conn_window_size: DEFAULT_H2_CONN_WINDOW_SIZE,
240 h2_stream_window_size: DEFAULT_H2_STREAM_WINDOW_SIZE,
241 graceful_shutdown_signal: None,
242 }))
243 }
244
245 #[inline]
247 pub fn secure(&self) -> bool {
248 self.0.secure
249 }
250
251 #[inline]
255 pub fn local_addr(&self) -> Option<SocketAddr> {
256 self.0.local_addr
257 }
258
259 #[inline]
261 pub fn keep_alive(&self) -> KeepAlive {
262 self.0.keep_alive
263 }
264
265 pub fn keep_alive_deadline(&self) -> Option<Instant> {
270 match self.keep_alive() {
271 KeepAlive::Timeout(dur) => Some(self.now() + dur),
272 KeepAlive::Os => None,
273 KeepAlive::Disabled => None,
274 }
275 }
276
277 #[cfg(feature = "http2")]
278 pub(crate) fn request_head_timeout(&self) -> Duration {
279 self.0.client_request_timeout
280 }
281
282 pub fn client_request_deadline(&self) -> Option<Instant> {
287 let timeout = self.0.client_request_timeout;
288 (timeout != Duration::ZERO).then(|| self.now() + timeout)
289 }
290
291 pub fn client_disconnect_deadline(&self) -> Option<Instant> {
293 let timeout = self.0.client_disconnect_timeout;
294 (timeout != Duration::ZERO).then(|| self.now() + timeout)
295 }
296
297 pub fn h1_allow_half_closed(&self) -> bool {
303 self.0.h1_allow_half_closed
304 }
305
306 pub fn h1_write_buffer_size(&self) -> usize {
308 self.0.h1_write_buffer_size
309 }
310
311 pub(crate) fn graceful_shutdown(&self) -> Option<GracefulShutdownFuture> {
312 self.0
313 .graceful_shutdown_signal
314 .as_ref()
315 .map(GracefulShutdownSignal::notified)
316 }
317
318 pub fn tcp_nodelay(&self) -> Option<bool> {
320 self.0.tcp_nodelay
321 }
322
323 pub fn h2_initial_window_size(&self) -> u32 {
325 self.0.h2_stream_window_size
326 }
327
328 pub fn h2_initial_connection_window_size(&self) -> u32 {
330 self.0.h2_conn_window_size
331 }
332
333 pub(crate) fn now(&self) -> Instant {
334 self.0.date_service.now()
335 }
336
337 #[doc(hidden)]
342 pub fn write_date_header(&self, dst: &mut BytesMut, camel_case: bool) {
343 const PREFIX_LEN: usize = 6;
344 const CRLF_LEN: usize = 2;
345 const DATE_HEADER_LEN: usize = PREFIX_LEN + DATE_VALUE_LENGTH + CRLF_LEN;
346
347 let mut buf: [u8; DATE_HEADER_LEN] = [0; DATE_HEADER_LEN];
348
349 buf[..PREFIX_LEN].copy_from_slice(if camel_case { b"Date: " } else { b"date: " });
350
351 self.0.date_service.with_date(|date| {
352 buf[PREFIX_LEN..PREFIX_LEN + DATE_VALUE_LENGTH].copy_from_slice(&date.bytes)
353 });
354
355 buf[PREFIX_LEN + DATE_VALUE_LENGTH..].copy_from_slice(b"\r\n");
356 dst.extend_from_slice(&buf);
357 }
358
359 #[allow(unused)] pub(crate) fn write_date_header_value(&self, dst: &mut BytesMut) {
361 self.0
362 .date_service
363 .with_date(|date| dst.extend_from_slice(&date.bytes));
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use memchr::memmem;
370 use tokio::{
371 task::yield_now,
372 time::{sleep, sleep_until},
373 };
374
375 use super::*;
376 use crate::{date::DATE_VALUE_LENGTH, notify_on_drop};
377
378 #[tokio::test(flavor = "local")]
379 async fn test_date_service_update() {
380 let settings =
381 ServiceConfig::new(KeepAlive::Os, Duration::ZERO, Duration::ZERO, false, None);
382
383 yield_now().await;
384
385 let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
386 settings.write_date_header(&mut buf1, false);
387 let now1 = settings.now();
388
389 sleep_until((Instant::now() + Duration::from_secs(2)).into()).await;
390 yield_now().await;
391
392 let now2 = settings.now();
393 let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
394 settings.write_date_header(&mut buf2, false);
395
396 assert_ne!(now1, now2);
397
398 assert_ne!(buf1, buf2);
399
400 drop(settings);
401
402 let mut times = 0;
404 while !notify_on_drop::is_dropped() {
405 sleep(Duration::from_millis(100)).await;
406 times += 1;
407 assert!(times < 10, "Timeout waiting for task drop");
408 }
409 }
410
411 #[tokio::test(flavor = "local")]
412 async fn test_date_service_drop() {
413 let service = Rc::new(DateService::new());
414
415 yield_now().await;
417
418 let clone1 = service.clone();
419 let clone2 = service.clone();
420 let clone3 = service.clone();
421
422 drop(clone1);
423 assert!(!notify_on_drop::is_dropped());
424 drop(clone2);
425 assert!(!notify_on_drop::is_dropped());
426 drop(clone3);
427 assert!(!notify_on_drop::is_dropped());
428
429 drop(service);
430
431 let mut times = 0;
433 while !notify_on_drop::is_dropped() {
434 sleep(Duration::from_millis(100)).await;
435 times += 1;
436 assert!(times < 10, "Timeout waiting for task drop");
437 }
438 }
439
440 #[test]
441 fn test_date_len() {
442 assert_eq!(DATE_VALUE_LENGTH, "Sun, 06 Nov 1994 08:49:37 GMT".len());
443 }
444
445 #[tokio::test(flavor = "local")]
446 async fn test_date() {
447 let settings = ServiceConfig::default();
448
449 let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
450 settings.write_date_header(&mut buf1, false);
451
452 let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
453 settings.write_date_header(&mut buf2, false);
454
455 assert_eq!(buf1, buf2);
456 }
457
458 #[tokio::test(flavor = "local")]
459 async fn test_date_camel_case() {
460 let settings = ServiceConfig::default();
461
462 let mut buf = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
463 settings.write_date_header(&mut buf, false);
464 assert!(memmem::find(&buf, b"date:").is_some());
465
466 let mut buf = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
467 settings.write_date_header(&mut buf, true);
468 assert!(memmem::find(&buf, b"Date:").is_some());
469 }
470}