-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.rs
More file actions
88 lines (76 loc) · 2.52 KB
/
Copy pathservice.rs
File metadata and controls
88 lines (76 loc) · 2.52 KB
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
//! Service trait — the user-supplied request handler.
//!
//! This mirrors `hyper::service::Service` but is tailored to our
//! [`Request`] / [`Response`] types (which carry fds inline). Notably
//! `call` takes `&self` rather than `&mut self` so a single service
//! value can be shared across requests on a connection without
//! interior mutability boilerplate; clones are cheap when the service
//! is wrapped in an `Arc`.
use std::error::Error as StdError;
use std::future::Future;
use crate::message::{Request, Response};
/// An async handler from [`Request`] to [`Response`].
pub trait Service {
/// Errors produced by the handler. Non-`Service`-fatal errors should
/// generally be turned into 4xx/5xx responses instead of returned
/// here; returning an `Err` aborts the connection.
type Error: Into<Box<dyn StdError + Send + Sync>>;
/// The future returned by `call`.
type Future: Future<Output = Result<Response, Self::Error>>;
fn call(&self, req: Request) -> Self::Future;
}
// Blanket impls for common smart-pointer wrappers, mirroring hyper.
impl<S: Service + ?Sized> Service for &S {
type Error = S::Error;
type Future = S::Future;
fn call(&self, req: Request) -> Self::Future {
(**self).call(req)
}
}
impl<S: Service + ?Sized> Service for Box<S> {
type Error = S::Error;
type Future = S::Future;
fn call(&self, req: Request) -> Self::Future {
(**self).call(req)
}
}
impl<S: Service + ?Sized> Service for std::sync::Arc<S> {
type Error = S::Error;
type Future = S::Future;
fn call(&self, req: Request) -> Self::Future {
(**self).call(req)
}
}
impl<S: Service + ?Sized> Service for std::rc::Rc<S> {
type Error = S::Error;
type Future = S::Future;
fn call(&self, req: Request) -> Self::Future {
(**self).call(req)
}
}
/// Adapter turning a closure `Fn(Request) -> Future<Output = Result<Response, E>>`
/// into a [`Service`]. Useful for tests and one-off handlers.
pub fn service_fn<F, Fut, E>(f: F) -> ServiceFn<F>
where
F: Fn(Request) -> Fut,
Fut: Future<Output = Result<Response, E>>,
E: Into<Box<dyn StdError + Send + Sync>>,
{
ServiceFn { f }
}
#[derive(Clone, Copy, Debug)]
pub struct ServiceFn<F> {
f: F,
}
impl<F, Fut, E> Service for ServiceFn<F>
where
F: Fn(Request) -> Fut,
Fut: Future<Output = Result<Response, E>>,
E: Into<Box<dyn StdError + Send + Sync>>,
{
type Error = E;
type Future = Fut;
fn call(&self, req: Request) -> Self::Future {
(self.f)(req)
}
}