#![allow(dead_code)]
use link_cli::protocol::{LinksClient, LinksServer, LinoProtocol, ServerOptions};
use link_cli::{LinkStorage, NamedTypesDecorator};
use std::net::SocketAddr;
use std::path::Path;
use std::thread::{self, JoinHandle};
use tempfile::NamedTempFile;
pub struct RunningServer {
pub address: SocketAddr,
pub shutdown: link_cli::protocol::ShutdownHandle,
pub thread: Option<JoinHandle<()>>,
_database: NamedTempFile,
}
impl RunningServer {
pub fn start(options: ServerOptions, named: bool) -> Self {
Self::start_with(options, named, |server| server)
}
pub fn start_with(
options: ServerOptions,
named: bool,
configure: impl FnOnce(LinksServer) -> LinksServer + Send + 'static,
) -> Self {
Self::start_serving(options, move |server, path| {
let server = configure(server);
if named {
let mut storage = NamedTypesDecorator::new(path, false).unwrap();
server.serve(&mut storage).unwrap();
} else {
let mut storage = LinkStorage::new(path, false).unwrap();
server.serve(&mut storage).unwrap();
}
})
}
pub fn start_serving(
options: ServerOptions,
serve: impl FnOnce(LinksServer, &Path) + Send + 'static,
) -> Self {
let database = NamedTempFile::new().unwrap();
let path = database.path().to_path_buf();
let server = LinksServer::bind("127.0.0.1:0", options).unwrap();
let address = server.local_addr().unwrap();
let shutdown = server.shutdown_handle().unwrap();
let thread = thread::spawn(move || serve(server, &path));
Self {
address,
shutdown,
thread: Some(thread),
_database: database,
}
}
pub fn client(&self, protocol: impl LinoProtocol + 'static) -> LinksClient {
LinksClient::connect(self.address, protocol).unwrap()
}
pub fn stop(&mut self) {
self.shutdown.shutdown();
if let Some(thread) = self.thread.take() {
thread.join().unwrap();
}
}
}
impl Drop for RunningServer {
fn drop(&mut self) {
self.stop();
}
}
mod options;
#[allow(unused_imports)] pub use options::{binary_options, protocols};