-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathserver.rs
155 lines (128 loc) · 3.78 KB
/
server.rs
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
use crate::{
error::Error,
handler::{local::LocalHandler, remote::RemoteHandler},
options::Dirs,
protocol::ProtocolError,
state::State,
transport::local::LocalServer,
};
use ouisync_bridge::{
config::{ConfigError, ConfigKey},
logger::{LogColor, LogFormat, Logger},
transport::RemoteServer,
};
use scoped_task::ScopedAbortHandle;
use state_monitor::StateMonitor;
use std::{
io,
net::SocketAddr,
path::PathBuf,
sync::{Arc, Mutex},
time::Duration,
};
use tokio::task;
const REPOSITORY_EXPIRATION_POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
pub(crate) async fn run(
dirs: Dirs,
socket: PathBuf,
log_format: LogFormat,
log_color: LogColor,
) -> Result<(), ProtocolError> {
let monitor = StateMonitor::make_root();
let _logger = Logger::new(
None,
String::new(), // log tag, not used here
Some(monitor.clone()),
log_format,
log_color,
)?;
let state = State::init(&dirs, monitor)
.await?
.start_delete_expired_repositories(REPOSITORY_EXPIRATION_POLL_INTERVAL);
let server = LocalServer::bind(socket.as_path())?;
let handle = task::spawn(server.run(LocalHandler::new(state.clone())));
terminated().await?;
handle.abort();
state.close().await;
Ok(())
}
// Wait until the program is terminated.
#[cfg(unix)]
async fn terminated() -> io::Result<()> {
use tokio::{
select,
signal::unix::{signal, SignalKind},
};
// Wait for SIGINT or SIGTERM
let mut interrupt = signal(SignalKind::interrupt())?;
let mut terminate = signal(SignalKind::terminate())?;
select! {
_ = interrupt.recv() => (),
_ = terminate.recv() => (),
}
Ok(())
}
#[cfg(not(unix))]
async fn terminated() -> io::Result<()> {
tokio::signal::ctrl_c().await
}
const BIND_RPC_KEY: ConfigKey<Vec<SocketAddr>> =
ConfigKey::new("bind_rpc", "Addresses to bind the remote API to");
#[derive(Default)]
pub(crate) struct ServerContainer {
handles: Mutex<Vec<ScopedAbortHandle>>,
}
impl ServerContainer {
pub fn new() -> Self {
Self::default()
}
pub async fn init(&self, state: Arc<State>) -> Result<(), Error> {
let entry = state.config.entry(BIND_RPC_KEY);
let addrs = match entry.get().await {
Ok(addrs) => addrs,
Err(ConfigError::NotFound) => Vec::new(),
Err(error) => return Err(error.into()),
};
let (handles, _) = start(state, &addrs).await?;
*self.handles.lock().unwrap() = handles;
Ok(())
}
pub async fn set(
&self,
state: Arc<State>,
addrs: &[SocketAddr],
) -> Result<Vec<SocketAddr>, Error> {
let entry = state.config.entry(BIND_RPC_KEY);
let (handles, addrs) = start(state, addrs).await?;
*self.handles.lock().unwrap() = handles;
entry.set(&addrs).await?;
Ok(addrs)
}
pub fn close(&self) {
self.handles.lock().unwrap().clear();
}
}
async fn start(
state: Arc<State>,
addrs: &[SocketAddr],
) -> Result<(Vec<ScopedAbortHandle>, Vec<SocketAddr>), Error> {
let mut handles = Vec::with_capacity(addrs.len());
let mut local_addrs = Vec::with_capacity(addrs.len());
// Avoid loading the TLS config if not needed
if addrs.is_empty() {
return Ok((handles, local_addrs));
}
let config = state.get_server_config().await?;
for addr in addrs {
let Ok(server) = RemoteServer::bind(*addr, config.clone()).await else {
continue;
};
local_addrs.push(server.local_addr());
handles.push(
task::spawn(server.run(RemoteHandler::new(state.clone())))
.abort_handle()
.into(),
);
}
Ok((handles, local_addrs))
}