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
use super::server_streaming;
use crate::generic::server::UnaryService;
use crate::generic::{Encode, Encoder};
use crate::{Request, Response};
use futures::{try_ready, Future, Poll, Stream};
use std::fmt;
use tower_service::Service;
pub struct ResponseFuture<T, E, S>
where
T: UnaryService<S::Item>,
S: Stream,
{
inner: server_streaming::ResponseFuture<Inner<T>, E, S>,
}
#[derive(Debug)]
pub struct Once<T> {
inner: Option<T>,
}
#[derive(Debug, Clone)]
struct Inner<T>(pub T);
#[derive(Debug)]
struct InnerFuture<T>(T);
impl<T, E, S> ResponseFuture<T, E, S>
where
T: UnaryService<S::Item, Response = E::Item>,
E: Encoder,
S: Stream<Error = crate::Status>,
{
pub fn new(inner: T, request: Request<S>, encoder: E) -> Self {
let inner = server_streaming::ResponseFuture::new(Inner(inner), request, encoder);
ResponseFuture { inner }
}
}
impl<T, E, S> Future for ResponseFuture<T, E, S>
where
T: UnaryService<S::Item, Response = E::Item>,
E: Encoder,
S: Stream<Error = crate::Status>,
{
type Item = http::Response<Encode<E, Once<T::Response>>>;
type Error = crate::error::Never;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.inner.poll()
}
}
impl<T, R> Service<Request<R>> for Inner<T>
where
T: UnaryService<R>,
{
type Response = Response<Once<T::Response>>;
type Error = crate::Status;
type Future = InnerFuture<T::Future>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(().into())
}
fn call(&mut self, request: Request<R>) -> Self::Future {
let inner = self.0.call(request);
InnerFuture(inner)
}
}
impl<T, U> Future for InnerFuture<T>
where
T: Future<Item = Response<U>, Error = crate::Status>,
{
type Item = Response<Once<U>>;
type Error = crate::Status;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let response = try_ready!(self.0.poll());
Ok(Once::map(response).into())
}
}
impl<T> Once<T> {
pub(super) fn map(response: Response<T>) -> Response<Self> {
response.map(|body| Once { inner: Some(body) })
}
}
impl<T> Stream for Once<T> {
type Item = T;
type Error = crate::Status;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
Ok(self.inner.take().into())
}
}
impl<T, E, S> fmt::Debug for ResponseFuture<T, E, S>
where
T: UnaryService<S::Item> + fmt::Debug,
T::Response: fmt::Debug,
T::Future: fmt::Debug,
E: fmt::Debug,
S: Stream + fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("unary::ResponseFuture")
.field("inner", &self.inner)
.finish()
}
}