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
use crate::listener::{Listener, ToListener};
use crate::Server;
use std::fmt::{self, Debug, Display, Formatter};
use async_std::io;
use crate::listener::ListenInfo;
#[derive(Default)]
pub struct FailoverListener<State> {
listeners: Vec<Option<Box<dyn Listener<State>>>>,
index: Option<usize>,
}
impl<State> FailoverListener<State>
where
State: Clone + Send + Sync + 'static,
{
pub fn new() -> Self {
Self {
listeners: vec![],
index: None,
}
}
pub fn add<L>(&mut self, listener: L) -> io::Result<()>
where
L: ToListener<State>,
{
self.listeners.push(Some(Box::new(listener.to_listener()?)));
Ok(())
}
pub fn with_listener<L>(mut self, listener: L) -> Self
where
L: ToListener<State>,
{
self.add(listener).expect("Unable to add listener");
self
}
}
#[async_trait::async_trait]
impl<State> Listener<State> for FailoverListener<State>
where
State: Clone + Send + Sync + 'static,
{
async fn bind(&mut self, app: Server<State>) -> io::Result<()> {
for (index, listener) in self.listeners.iter_mut().enumerate() {
let listener = listener.as_deref_mut().expect("bind called twice");
match listener.bind(app.clone()).await {
Ok(_) => {
self.index = Some(index);
return Ok(());
}
Err(e) => {
crate::log::info!("unable to bind", {
listener: listener.to_string(),
error: e.to_string()
});
}
}
}
Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
"unable to bind to any supplied listener spec",
))
}
async fn accept(&mut self) -> io::Result<()> {
match self.index {
Some(index) => {
let mut listener = self.listeners[index].take().expect("accept called twice");
listener.accept().await?;
Ok(())
}
None => Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
"unable to listen to any supplied listener spec",
)),
}
}
fn info(&self) -> Vec<ListenInfo> {
match self.index {
Some(index) => match self.listeners.get(index) {
Some(Some(listener)) => listener.info(),
_ => vec![],
},
None => vec![],
}
}
}
impl<State> Debug for FailoverListener<State> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.listeners)
}
}
impl<State> Display for FailoverListener<State> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let string = self
.listeners
.iter()
.map(|l| match l {
Some(l) => l.to_string(),
None => String::new(),
})
.collect::<Vec<_>>()
.join(", ");
writeln!(f, "{}", string)
}
}