veilid/veilid-server/src/client_api.rs

210 lines
6.7 KiB
Rust
Raw Normal View History

2022-11-16 17:49:53 +00:00
use crate::settings::*;
2022-06-28 03:46:29 +00:00
use crate::tools::*;
2021-11-22 16:28:30 +00:00
use crate::veilid_client_capnp::*;
2022-07-01 16:13:52 +00:00
use crate::veilid_logs::VeilidLogs;
2022-06-29 14:13:49 +00:00
use cfg_if::*;
2022-06-29 14:34:23 +00:00
use futures_util::{future::try_join_all, FutureExt as FuturesFutureExt, StreamExt};
2022-07-01 16:13:52 +00:00
use serde::*;
2021-11-22 16:28:30 +00:00
use std::cell::RefCell;
use std::collections::HashMap;
2022-07-01 16:13:52 +00:00
use std::fmt;
2021-11-22 16:28:30 +00:00
use std::net::SocketAddr;
2022-06-29 14:13:49 +00:00
use stop_token::future::FutureExt;
use stop_token::*;
2022-06-08 01:31:05 +00:00
use tracing::*;
use veilid_core::*;
2021-11-22 16:28:30 +00:00
2023-06-06 23:09:29 +00:00
// struct VeilidServerImpl {
// veilid_api: veilid_core::VeilidAPI,
// veilid_logs: VeilidLogs,
// settings: Settings,
// next_id: u64,
// }
// impl VeilidServerImpl {
// #[instrument(level = "trace", skip_all)]
// pub fn new(
// veilid_api: veilid_core::VeilidAPI,
// veilid_logs: VeilidLogs,
// settings: Settings,
// ) -> Self {
// Self {
// next_id: 0,
// veilid_api,
// veilid_logs,
// settings,
// }
// }
// #[instrument(level = "trace", skip_all)]
// fn shutdown(
// &mut self,
// _params: veilid_server::ShutdownParams,
// mut _results: veilid_server::ShutdownResults,
// ) -> Promise<(), ::capnp::Error> {
// trace!("VeilidServerImpl::shutdown");
// cfg_if::cfg_if! {
// if #[cfg(windows)] {
// assert!(false, "write me!");
// }
// else {
// crate::server::shutdown();
// }
// }
// Promise::ok(())
// }
// #[instrument(level = "trace", skip_all)]
// fn change_log_level(
// &mut self,
// params: veilid_server::ChangeLogLevelParams,
// mut results: veilid_server::ChangeLogLevelResults,
// ) -> Promise<(), ::capnp::Error> {
// trace!("VeilidServerImpl::change_log_level");
// let layer = pry!(pry!(params.get()).get_layer()).to_owned();
// let log_level_json = pry!(pry!(params.get()).get_log_level()).to_owned();
// let log_level: veilid_core::VeilidConfigLogLevel =
// pry!(veilid_core::deserialize_json(&log_level_json)
// .map_err(|e| ::capnp::Error::failed(format!("{:?}", e))));
// let result = self.veilid_logs.change_log_level(layer, log_level);
// encode_api_result(&result, &mut results.get().init_result());
// Promise::ok(())
// }
// }
2021-11-22 16:28:30 +00:00
// --- Client API Server-Side ---------------------------------
2021-11-29 01:08:50 +00:00
type ClientApiAllFuturesJoinHandle =
2022-06-28 03:46:29 +00:00
JoinHandle<Result<Vec<()>, Box<(dyn std::error::Error + 'static)>>>;
2021-11-29 01:08:50 +00:00
2021-11-22 16:28:30 +00:00
struct ClientApiInner {
veilid_api: veilid_core::VeilidAPI,
2022-07-01 16:13:52 +00:00
veilid_logs: VeilidLogs,
2022-11-16 17:49:53 +00:00
settings: Settings,
2022-06-29 14:13:49 +00:00
stop: Option<StopSource>,
2021-11-29 01:08:50 +00:00
join_handle: Option<ClientApiAllFuturesJoinHandle>,
2021-11-22 16:28:30 +00:00
}
pub struct ClientApi {
2023-06-06 23:09:29 +00:00
inner: Arc<Mutex<ClientApiInner>>,
2021-11-22 16:28:30 +00:00
}
impl ClientApi {
2022-06-10 21:07:10 +00:00
#[instrument(level = "trace", skip_all)]
2022-11-16 17:49:53 +00:00
pub fn new(
veilid_api: veilid_core::VeilidAPI,
veilid_logs: VeilidLogs,
settings: Settings,
) -> Rc<Self> {
2021-11-22 16:28:30 +00:00
Rc::new(Self {
inner: RefCell::new(ClientApiInner {
2021-11-28 02:31:01 +00:00
veilid_api,
2022-07-01 16:13:52 +00:00
veilid_logs,
2022-11-16 17:49:53 +00:00
settings,
2022-06-29 14:13:49 +00:00
stop: Some(StopSource::new()),
2021-11-22 16:28:30 +00:00
join_handle: None,
}),
})
}
2022-06-10 21:07:10 +00:00
#[instrument(level = "trace", skip(self))]
2021-11-22 16:28:30 +00:00
pub async fn stop(self: Rc<Self>) {
trace!("ClientApi::stop requested");
let jh = {
let mut inner = self.inner.borrow_mut();
if inner.join_handle.is_none() {
trace!("ClientApi stop ignored");
return;
}
2022-06-29 14:13:49 +00:00
drop(inner.stop.take());
2021-11-22 16:28:30 +00:00
inner.join_handle.take().unwrap()
};
trace!("ClientApi::stop: waiting for stop");
2021-12-14 14:48:33 +00:00
if let Err(err) = jh.await {
error!("{}", err);
}
2021-11-22 16:28:30 +00:00
trace!("ClientApi::stop: stopped");
}
2023-06-06 23:09:29 +00:00
#[instrument(level = "trace", skip(self), err)]
2021-11-22 16:28:30 +00:00
async fn handle_incoming(
2023-06-06 23:09:29 +00:00
self,
2021-11-22 16:28:30 +00:00
bind_addr: SocketAddr,
) -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind(bind_addr).await?;
debug!("Client API listening on: {:?}", bind_addr);
2022-06-28 03:46:29 +00:00
// Process the incoming accept stream
2022-06-29 14:13:49 +00:00
cfg_if! {
if #[cfg(feature="rt-async-std")] {
let mut incoming_stream = listener.incoming();
} else if #[cfg(feature="rt-tokio")] {
let mut incoming_stream = tokio_stream::wrappers::TcpListenerStream::new(listener);
}
}
2023-06-06 23:09:29 +00:00
let stop_token = self.inner.lock().stop.as_ref().unwrap().token();
2021-11-22 16:28:30 +00:00
let incoming_loop = async move {
2022-06-29 14:13:49 +00:00
while let Ok(Some(stream_result)) =
incoming_stream.next().timeout_at(stop_token.clone()).await
{
2021-11-22 16:28:30 +00:00
let stream = stream_result?;
stream.set_nodelay(true)?;
2022-06-29 14:13:49 +00:00
cfg_if! {
if #[cfg(feature="rt-async-std")] {
2022-06-29 14:34:23 +00:00
use futures_util::AsyncReadExt;
2022-06-29 14:13:49 +00:00
let (reader, writer) = stream.split();
} else if #[cfg(feature="rt-tokio")] {
use tokio_util::compat::*;
let (reader, writer) = stream.into_split();
let reader = reader.compat();
let writer = writer.compat_write();
}
}
2021-11-22 16:28:30 +00:00
2023-06-06 23:09:29 +00:00
xxx spawn json_api handler
2022-06-28 03:46:29 +00:00
spawn_local(rpc_system.map(drop));
2021-11-22 16:28:30 +00:00
}
Ok::<(), Box<dyn std::error::Error>>(())
};
incoming_loop.await
}
2022-06-10 21:07:10 +00:00
#[instrument(level = "trace", skip(self))]
pub fn handle_update(self: Rc<Self>, veilid_update: veilid_core::VeilidUpdate) {
2022-06-08 01:31:05 +00:00
// serialize update
let veilid_update = serialize_json(veilid_update);
2021-12-11 01:14:33 +00:00
2022-06-08 01:31:05 +00:00
// Pass other updates to clients
2021-12-11 01:14:33 +00:00
self.send_request_to_all_clients(|_id, registration| {
2022-06-08 01:31:05 +00:00
match veilid_update
.len()
.try_into()
.map_err(|e| ::capnp::Error::failed(format!("{:?}", e)))
{
Ok(len) => {
let mut request = registration.client.update_request();
let mut rpc_veilid_update = request.get().init_veilid_update(len);
rpc_veilid_update.push_str(&veilid_update);
Some(request.send())
}
Err(_) => None,
}
2021-12-11 01:14:33 +00:00
});
}
2022-06-10 21:07:10 +00:00
#[instrument(level = "trace", skip(self))]
2023-06-06 23:09:29 +00:00
pub fn run(&self, bind_addrs: Vec<SocketAddr>) {
2021-11-22 16:28:30 +00:00
let bind_futures = bind_addrs
.iter()
2023-06-06 23:09:29 +00:00
.map(|addr| self.clone().handle_incoming(*addr));
2022-06-29 14:34:23 +00:00
let bind_futures_join = try_join_all(bind_futures);
2022-06-28 03:46:29 +00:00
self.inner.borrow_mut().join_handle = Some(spawn_local(bind_futures_join));
2021-11-22 16:28:30 +00:00
}
}