use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use rustls::ClientConfig;
use rustls::pki_types::ServerName;
use serde_json::Value;
mod dial;
pub mod edition;
pub mod entries;
pub mod frame;
pub mod hello;
pub mod leaf;
pub mod material;
pub mod reach;
pub mod tls;
pub(crate) use dial::connect;
use material::Material;
pub use reach::Reach;
#[derive(Debug)]
pub struct Channel {
config: Arc<ClientConfig>,
endpoints: Vec<Endpoint>,
key: String,
anchors: PathBuf,
chain: PathBuf,
spelled: AtomicU32,
}
#[derive(Debug)]
struct Endpoint {
address: String,
name: ServerName<'static>,
}
impl Channel {
pub fn open(m: &Material) -> Result<Self, String> {
Ok(Self {
config: tls::client_config(m)?,
endpoints: m
.addresses
.iter()
.map(|address| {
Ok(Endpoint {
address: address.clone(),
name: server_name(address)?,
})
})
.collect::<Result<_, String>>()?,
key: m
.anchors
.parent()
.map(|dir| dir.display().to_string())
.unwrap_or_default(),
anchors: m.anchors.clone(),
chain: m.chain.clone(),
spelled: AtomicU32::new(edition::FLOOR),
})
}
pub fn spells(&self, shape: &str, key: &str) -> bool {
edition::spells(self.spelled.load(Ordering::Relaxed), shape, key)
}
pub fn address(&self) -> String {
let listed: Vec<&str> = self
.endpoints
.iter()
.map(|at| at.address.as_str())
.collect();
listed.join(", ")
}
pub fn ask(&self, request: &Value) -> Result<Vec<Value>, Reach> {
let whole_at_first = crate::verbs::queue::replaces(request);
let mut stream = Vec::new();
self.follow(request, &mut |frame| {
stream.push(frame);
!whole_at_first
})?;
Ok(stream)
}
pub fn follow(
&self,
request: &Value,
on_frame: &mut dyn FnMut(Value) -> bool,
) -> Result<(), Reach> {
let mut tls = self.dial(request)?;
while let Some(chunk) =
frame::read_value(&mut tls).map_err(|e| Reach::Unanswered(format!("receive: {e}")))?
{
if !on_frame(chunk) {
return Ok(());
}
}
Ok(())
}
}
fn server_name(address: &str) -> Result<ServerName<'static>, String> {
let host = address.rsplit_once(':').map_or(address, |(head, _)| head);
let host = host.trim_start_matches('[').trim_end_matches(']');
if let Ok(ip) = host.parse::<IpAddr>() {
return Ok(ServerName::IpAddress(ip.into()));
}
ServerName::try_from(host.to_owned()).map_err(|e| format!("{address}: not a server name: {e}"))
}
#[cfg(test)]
mod tests;