2021-11-22 16:28:30 +00:00
|
|
|
use crate::veilid_client_capnp::*;
|
|
|
|
use async_std::net::TcpListener;
|
|
|
|
use async_std::prelude::FutureExt;
|
|
|
|
use capnp::capability::Promise;
|
|
|
|
use capnp_rpc::{pry, rpc_twoparty_capnp, twoparty, RpcSystem};
|
|
|
|
use failure::*;
|
|
|
|
use futures::FutureExt as FuturesFutureExt;
|
|
|
|
use futures::{AsyncReadExt, StreamExt};
|
|
|
|
use log::*;
|
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::net::SocketAddr;
|
|
|
|
use std::rc::Rc;
|
|
|
|
use veilid_core::xx::Eventual;
|
|
|
|
|
|
|
|
#[derive(Fail, Debug)]
|
|
|
|
#[fail(display = "Client API error: {}", _0)]
|
|
|
|
pub struct ClientAPIError(String);
|
|
|
|
|
2022-01-18 17:33:14 +00:00
|
|
|
fn convert_attachment_state(state: &veilid_core::AttachmentState) -> AttachmentState {
|
|
|
|
match state {
|
|
|
|
veilid_core::AttachmentState::Detached => AttachmentState::Detached,
|
|
|
|
veilid_core::AttachmentState::Attaching => AttachmentState::Attaching,
|
|
|
|
veilid_core::AttachmentState::AttachedWeak => AttachmentState::AttachedWeak,
|
|
|
|
veilid_core::AttachmentState::AttachedGood => AttachmentState::AttachedGood,
|
|
|
|
veilid_core::AttachmentState::AttachedStrong => AttachmentState::AttachedStrong,
|
|
|
|
veilid_core::AttachmentState::FullyAttached => AttachmentState::FullyAttached,
|
|
|
|
veilid_core::AttachmentState::OverAttached => AttachmentState::OverAttached,
|
|
|
|
veilid_core::AttachmentState::Detaching => AttachmentState::Detaching,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn convert_update(
|
|
|
|
update: &veilid_core::VeilidUpdate,
|
|
|
|
rpc_update: crate::veilid_client_capnp::veilid_update::Builder,
|
|
|
|
) {
|
|
|
|
match update {
|
|
|
|
veilid_core::VeilidUpdate::Attachment(state) => {
|
|
|
|
let mut att = rpc_update.init_attachment();
|
|
|
|
att.set_state(convert_attachment_state(state));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn convert_state(
|
|
|
|
state: &veilid_core::VeilidState,
|
|
|
|
rpc_state: crate::veilid_client_capnp::veilid_state::Builder,
|
|
|
|
) {
|
|
|
|
rpc_state
|
|
|
|
.init_attachment()
|
|
|
|
.set_state(convert_attachment_state(&state.attachment));
|
|
|
|
}
|
|
|
|
|
2021-11-22 16:28:30 +00:00
|
|
|
// --- interface Registration ---------------------------------
|
|
|
|
|
|
|
|
struct RegistrationHandle {
|
|
|
|
client: veilid_client::Client,
|
|
|
|
requests_in_flight: i32,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct RegistrationMap {
|
|
|
|
registrations: HashMap<u64, RegistrationHandle>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RegistrationMap {
|
|
|
|
fn new() -> Self {
|
|
|
|
Self {
|
|
|
|
registrations: HashMap::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct RegistrationImpl {
|
|
|
|
id: u64,
|
|
|
|
registration_map: Rc<RefCell<RegistrationMap>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RegistrationImpl {
|
|
|
|
fn new(id: u64, registrations: Rc<RefCell<RegistrationMap>>) -> Self {
|
|
|
|
Self {
|
2021-11-28 02:31:01 +00:00
|
|
|
id,
|
2021-11-22 16:28:30 +00:00
|
|
|
registration_map: registrations,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for RegistrationImpl {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
debug!("Registration dropped");
|
|
|
|
self.registration_map
|
|
|
|
.borrow_mut()
|
|
|
|
.registrations
|
|
|
|
.remove(&self.id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl registration::Server for RegistrationImpl {}
|
|
|
|
|
|
|
|
// --- interface VeilidServer ---------------------------------
|
|
|
|
|
|
|
|
struct VeilidServerImpl {
|
|
|
|
veilid_api: veilid_core::VeilidAPI,
|
|
|
|
next_id: u64,
|
|
|
|
pub registration_map: Rc<RefCell<RegistrationMap>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl VeilidServerImpl {
|
|
|
|
pub fn new(veilid_api: veilid_core::VeilidAPI) -> Self {
|
|
|
|
Self {
|
|
|
|
next_id: 0,
|
|
|
|
registration_map: Rc::new(RefCell::new(RegistrationMap::new())),
|
2021-11-28 02:31:01 +00:00
|
|
|
veilid_api,
|
2021-11-22 16:28:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl veilid_server::Server for VeilidServerImpl {
|
|
|
|
fn register(
|
|
|
|
&mut self,
|
|
|
|
params: veilid_server::RegisterParams,
|
|
|
|
mut results: veilid_server::RegisterResults,
|
|
|
|
) -> Promise<(), ::capnp::Error> {
|
|
|
|
trace!("VeilidServerImpl::register");
|
|
|
|
self.registration_map.borrow_mut().registrations.insert(
|
|
|
|
self.next_id,
|
|
|
|
RegistrationHandle {
|
|
|
|
client: pry!(pry!(params.get()).get_veilid_client()),
|
|
|
|
requests_in_flight: 0,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
results
|
|
|
|
.get()
|
|
|
|
.set_registration(capnp_rpc::new_client(RegistrationImpl::new(
|
|
|
|
self.next_id,
|
|
|
|
self.registration_map.clone(),
|
|
|
|
)));
|
|
|
|
|
|
|
|
self.next_id += 1;
|
|
|
|
|
2022-01-18 17:33:14 +00:00
|
|
|
Promise::ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn debug(
|
|
|
|
&mut self,
|
|
|
|
params: veilid_server::DebugParams,
|
|
|
|
mut results: veilid_server::DebugResults,
|
|
|
|
) -> Promise<(), ::capnp::Error> {
|
|
|
|
trace!("VeilidServerImpl::debug");
|
2021-11-22 16:28:30 +00:00
|
|
|
let veilid_api = self.veilid_api.clone();
|
2022-01-18 17:33:14 +00:00
|
|
|
let what = pry!(pry!(params.get()).get_what()).to_owned();
|
|
|
|
|
2021-11-22 16:28:30 +00:00
|
|
|
Promise::from_future(async move {
|
2022-01-18 17:33:14 +00:00
|
|
|
let output = veilid_api
|
|
|
|
.debug(what)
|
2021-12-08 03:09:45 +00:00
|
|
|
.await
|
2022-01-18 17:33:14 +00:00
|
|
|
.map_err(|e| ::capnp::Error::failed(format!("{:?}", e)))?;
|
|
|
|
results.get().set_output(output.as_str());
|
|
|
|
Ok(())
|
2021-11-22 16:28:30 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn attach(
|
|
|
|
&mut self,
|
|
|
|
_params: veilid_server::AttachParams,
|
|
|
|
mut _results: veilid_server::AttachResults,
|
|
|
|
) -> Promise<(), ::capnp::Error> {
|
|
|
|
trace!("VeilidServerImpl::attach");
|
|
|
|
let veilid_api = self.veilid_api.clone();
|
|
|
|
Promise::from_future(async move {
|
2021-12-08 03:09:45 +00:00
|
|
|
veilid_api
|
|
|
|
.attach()
|
|
|
|
.await
|
|
|
|
.map_err(|e| ::capnp::Error::failed(format!("{:?}", e)))
|
2021-11-22 16:28:30 +00:00
|
|
|
})
|
|
|
|
}
|
2022-01-18 17:33:14 +00:00
|
|
|
|
2021-11-22 16:28:30 +00:00
|
|
|
fn detach(
|
|
|
|
&mut self,
|
|
|
|
_params: veilid_server::DetachParams,
|
|
|
|
mut _results: veilid_server::DetachResults,
|
|
|
|
) -> Promise<(), ::capnp::Error> {
|
|
|
|
trace!("VeilidServerImpl::detach");
|
|
|
|
let veilid_api = self.veilid_api.clone();
|
|
|
|
Promise::from_future(async move {
|
2021-12-08 03:09:45 +00:00
|
|
|
veilid_api
|
|
|
|
.detach()
|
|
|
|
.await
|
|
|
|
.map_err(|e| ::capnp::Error::failed(format!("{:?}", e)))
|
2021-11-22 16:28:30 +00:00
|
|
|
})
|
|
|
|
}
|
2022-01-18 17:33:14 +00:00
|
|
|
|
2021-11-22 16:28:30 +00:00
|
|
|
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 {
|
2022-01-15 23:50:56 +00:00
|
|
|
crate::server::shutdown();
|
2021-11-22 16:28:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Promise::ok(())
|
|
|
|
}
|
2021-12-11 01:14:33 +00:00
|
|
|
|
2022-01-18 17:33:14 +00:00
|
|
|
fn get_state(
|
2021-12-11 01:14:33 +00:00
|
|
|
&mut self,
|
2022-01-18 17:33:14 +00:00
|
|
|
_params: veilid_server::GetStateParams,
|
|
|
|
mut results: veilid_server::GetStateResults,
|
2021-12-11 01:14:33 +00:00
|
|
|
) -> Promise<(), ::capnp::Error> {
|
2022-01-18 17:33:14 +00:00
|
|
|
trace!("VeilidServerImpl::get_state");
|
2021-12-11 01:14:33 +00:00
|
|
|
let veilid_api = self.veilid_api.clone();
|
|
|
|
Promise::from_future(async move {
|
2022-01-18 17:33:14 +00:00
|
|
|
let state = veilid_api
|
|
|
|
.get_state()
|
2021-12-11 01:14:33 +00:00
|
|
|
.await
|
|
|
|
.map_err(|e| ::capnp::Error::failed(format!("{:?}", e)))?;
|
2022-01-18 17:33:14 +00:00
|
|
|
|
|
|
|
let rpc_state = results.get().init_state();
|
|
|
|
convert_state(&state, rpc_state);
|
2021-12-11 01:14:33 +00:00
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
}
|
2021-11-22 16:28:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// --- Client API Server-Side ---------------------------------
|
|
|
|
|
2021-11-29 01:08:50 +00:00
|
|
|
type ClientApiAllFuturesJoinHandle =
|
|
|
|
async_std::task::JoinHandle<Result<Vec<()>, Box<(dyn std::error::Error + 'static)>>>;
|
|
|
|
|
2021-11-22 16:28:30 +00:00
|
|
|
struct ClientApiInner {
|
|
|
|
veilid_api: veilid_core::VeilidAPI,
|
|
|
|
registration_map: Rc<RefCell<RegistrationMap>>,
|
|
|
|
stop: Eventual,
|
2021-11-29 01:08:50 +00:00
|
|
|
join_handle: Option<ClientApiAllFuturesJoinHandle>,
|
2021-11-22 16:28:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ClientApi {
|
|
|
|
inner: RefCell<ClientApiInner>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ClientApi {
|
|
|
|
pub fn new(veilid_api: veilid_core::VeilidAPI) -> Rc<Self> {
|
|
|
|
Rc::new(Self {
|
|
|
|
inner: RefCell::new(ClientApiInner {
|
2021-11-28 02:31:01 +00:00
|
|
|
veilid_api,
|
2021-11-22 16:28:30 +00:00
|
|
|
registration_map: Rc::new(RefCell::new(RegistrationMap::new())),
|
|
|
|
stop: Eventual::new(),
|
|
|
|
join_handle: None,
|
|
|
|
}),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
inner.stop.resolve();
|
|
|
|
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");
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_incoming(
|
|
|
|
self: Rc<Self>,
|
|
|
|
bind_addr: SocketAddr,
|
|
|
|
client: veilid_server::Client,
|
|
|
|
) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
let listener = TcpListener::bind(bind_addr).await?;
|
|
|
|
debug!("Client API listening on: {:?}", bind_addr);
|
|
|
|
|
|
|
|
// Get the
|
|
|
|
let mut incoming = listener.incoming();
|
|
|
|
let stop = self.inner.borrow().stop.clone();
|
|
|
|
let incoming_loop = async move {
|
|
|
|
while let Some(stream_result) = stop.instance_none().race(incoming.next()).await {
|
|
|
|
let stream = stream_result?;
|
|
|
|
stream.set_nodelay(true)?;
|
|
|
|
let (reader, writer) = stream.split();
|
|
|
|
let network = twoparty::VatNetwork::new(
|
|
|
|
reader,
|
|
|
|
writer,
|
|
|
|
rpc_twoparty_capnp::Side::Server,
|
|
|
|
Default::default(),
|
|
|
|
);
|
|
|
|
|
|
|
|
let rpc_system = RpcSystem::new(Box::new(network), Some(client.clone().client));
|
|
|
|
|
|
|
|
async_std::task::spawn_local(rpc_system.map(drop));
|
|
|
|
}
|
|
|
|
Ok::<(), Box<dyn std::error::Error>>(())
|
|
|
|
};
|
|
|
|
|
|
|
|
incoming_loop.await
|
|
|
|
}
|
|
|
|
|
2021-12-11 01:14:33 +00:00
|
|
|
fn send_request_to_all_clients<F, T>(self: Rc<Self>, request: F)
|
|
|
|
where
|
|
|
|
F: Fn(u64, &mut RegistrationHandle) -> ::capnp::capability::RemotePromise<T>,
|
|
|
|
T: capnp::traits::Pipelined + for<'a> capnp::traits::Owned<'a> + 'static + Unpin,
|
|
|
|
{
|
2021-11-22 16:28:30 +00:00
|
|
|
// Send status update to each registered client
|
|
|
|
let registration_map = self.inner.borrow().registration_map.clone();
|
|
|
|
let registration_map1 = registration_map.clone();
|
|
|
|
let regs = &mut registration_map.borrow_mut().registrations;
|
|
|
|
for (&id, mut registration) in regs.iter_mut() {
|
|
|
|
if registration.requests_in_flight > 5 {
|
2021-12-11 03:04:38 +00:00
|
|
|
println!(
|
2021-12-11 01:14:33 +00:00
|
|
|
"too many requests in flight: {}",
|
2021-11-22 16:28:30 +00:00
|
|
|
registration.requests_in_flight
|
|
|
|
);
|
|
|
|
}
|
|
|
|
registration.requests_in_flight += 1;
|
2021-12-11 01:14:33 +00:00
|
|
|
|
|
|
|
let request_promise = request(id, registration);
|
|
|
|
|
2021-11-22 16:28:30 +00:00
|
|
|
let registration_map2 = registration_map1.clone();
|
2021-12-11 01:14:33 +00:00
|
|
|
async_std::task::spawn_local(request_promise.promise.map(move |r| match r {
|
2021-11-22 16:28:30 +00:00
|
|
|
Ok(_) => {
|
2021-11-29 01:08:50 +00:00
|
|
|
if let Some(ref mut s) =
|
|
|
|
registration_map2.borrow_mut().registrations.get_mut(&id)
|
|
|
|
{
|
|
|
|
s.requests_in_flight -= 1;
|
|
|
|
}
|
2021-11-22 16:28:30 +00:00
|
|
|
}
|
|
|
|
Err(e) => {
|
2021-12-11 03:04:38 +00:00
|
|
|
println!("Got error: {:?}. Dropping registation.", e);
|
2021-11-22 16:28:30 +00:00
|
|
|
registration_map2.borrow_mut().registrations.remove(&id);
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-18 17:33:14 +00:00
|
|
|
pub fn handle_update(self: Rc<Self>, veilid_update: veilid_core::VeilidUpdate) {
|
2021-12-11 01:14:33 +00:00
|
|
|
self.send_request_to_all_clients(|_id, registration| {
|
2022-01-18 17:33:14 +00:00
|
|
|
let mut request = registration.client.update_request();
|
|
|
|
let rpc_veilid_update = request.get().init_veilid_update();
|
|
|
|
convert_update(&veilid_update, rpc_veilid_update);
|
2021-12-11 01:14:33 +00:00
|
|
|
request.send()
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn handle_client_log(self: Rc<Self>, message: String) {
|
|
|
|
self.send_request_to_all_clients(|_id, registration| {
|
|
|
|
let mut request = registration.client.log_message_request();
|
|
|
|
request.get().set_message(&message);
|
|
|
|
request.send()
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-11-22 16:28:30 +00:00
|
|
|
pub fn run(self: Rc<Self>, bind_addrs: Vec<SocketAddr>) {
|
|
|
|
// Create client api VeilidServer
|
|
|
|
let veilid_server_impl = VeilidServerImpl::new(self.inner.borrow().veilid_api.clone());
|
|
|
|
self.inner.borrow_mut().registration_map = veilid_server_impl.registration_map.clone();
|
|
|
|
|
|
|
|
// Make a client object for the server to send to each rpc client
|
|
|
|
let client: veilid_server::Client = capnp_rpc::new_client(veilid_server_impl);
|
|
|
|
|
|
|
|
let bind_futures = bind_addrs
|
|
|
|
.iter()
|
2021-11-28 02:31:01 +00:00
|
|
|
.map(|addr| self.clone().handle_incoming(*addr, client.clone()));
|
2021-11-22 16:28:30 +00:00
|
|
|
let bind_futures_join = futures::future::try_join_all(bind_futures);
|
|
|
|
self.inner.borrow_mut().join_handle = Some(async_std::task::spawn_local(bind_futures_join));
|
|
|
|
}
|
|
|
|
}
|