Files
leleka/desktop-core/src/node_connection.rs
T

338 lines
11 KiB
Rust

//! Independently owned node observer. Reconnects state, never inference.
use crate::node::{
self,
proto::{self, node_client::NodeClient},
};
use serde::Serialize;
use std::{
net::SocketAddr,
sync::Arc,
time::{Duration, Instant},
};
use tokio::{sync::watch, task::JoinHandle};
use tonic::{Code, Status, transport::Channel};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
Connecting,
Ready,
Disconnected,
AuthError,
ProtocolError,
}
#[derive(Clone)]
struct State {
phase: Phase,
snapshot: Option<proto::Snapshot>,
heard: Option<Instant>,
client: Option<NodeClient<Channel>>,
}
#[derive(Clone, Debug, Serialize)]
pub struct StatusView {
pub phase: Phase,
pub fresh: bool,
pub agent_epoch: Option<String>,
pub sequence: Option<u64>,
pub active_responses: Option<u32>,
pub capabilities: Vec<String>,
}
struct Owner {
state: watch::Receiver<State>,
task: JoinHandle<()>,
freshness: Duration,
}
impl Drop for Owner {
fn drop(&mut self) {
self.task.abort()
}
}
#[derive(Clone)]
pub struct Connection(Arc<Owner>);
#[derive(Clone, Copy)]
pub struct Timing {
pub heartbeat: Duration,
pub deadline: Duration,
pub freshness: Duration,
pub retry_min: Duration,
pub retry_max: Duration,
}
impl Default for Timing {
fn default() -> Self {
Self {
heartbeat: Duration::from_secs(5),
deadline: Duration::from_secs(5),
freshness: Duration::from_secs(15),
retry_min: Duration::from_millis(200),
retry_max: Duration::from_secs(10),
}
}
}
impl Connection {
pub fn start(address: SocketAddr, token: String) -> Result<Self, String> {
Self::with_timing(address, token, Timing::default())
}
pub fn with_timing(address: SocketAddr, token: String, timing: Timing) -> Result<Self, String> {
if !address.ip().is_loopback()
|| token.len() < 32
|| token.len() > 4096
|| !token.bytes().all(|b| b.is_ascii_graphic())
{
return Err("invalid node address or credential".into());
}
if timing.heartbeat.is_zero()
|| timing.deadline.is_zero()
|| timing.retry_min.is_zero()
|| timing.retry_max < timing.retry_min
|| timing.freshness < timing.heartbeat + timing.deadline
{
return Err("invalid observer timing".into());
}
let (tx, state) = watch::channel(State {
phase: Phase::Connecting,
snapshot: None,
heard: None,
client: None,
});
let task = tokio::spawn(observe(address, token, timing, tx));
Ok(Self(Arc::new(Owner {
state,
task,
freshness: timing.freshness,
})))
}
pub fn status(&self) -> StatusView {
let s = self.0.state.borrow();
let snapshot = s.snapshot.as_ref();
let fresh =
s.phase == Phase::Ready && s.heard.is_some_and(|h| h.elapsed() < self.0.freshness);
StatusView {
phase: if s.phase == Phase::Ready && !fresh {
Phase::Disconnected
} else {
s.phase
},
fresh,
agent_epoch: snapshot.map(|s| s.agent_epoch.clone()),
sequence: snapshot.map(|s| s.sequence),
active_responses: snapshot.map(|s| s.active_responses),
capabilities: snapshot.map(|s| s.capabilities.clone()).unwrap_or_default(),
}
}
pub fn client(&self, capability: &str) -> Result<NodeClient<Channel>, Status> {
let s = self.0.state.borrow();
if s.phase != Phase::Ready || !s.heard.is_some_and(|h| h.elapsed() < self.0.freshness) {
return Err(Status::unavailable("node state is not fresh"));
}
if !s
.snapshot
.as_ref()
.is_some_and(|s| s.capabilities.iter().any(|c| c == capability))
{
return Err(Status::failed_precondition("node capability unavailable"));
}
s.client
.clone()
.ok_or_else(|| Status::unavailable("node disconnected"))
}
pub async fn wait_ready(&self, timeout: Duration) -> Result<(), Status> {
let mut state = self.0.state.clone();
tokio::time::timeout(timeout, async {
loop {
match state.borrow().phase {
Phase::Ready => return Ok(()),
Phase::AuthError => {
return Err(Status::unauthenticated("node authentication failed"));
}
Phase::ProtocolError => {
return Err(Status::failed_precondition("node protocol incompatible"));
}
_ => {}
}
state
.changed()
.await
.map_err(|_| Status::unavailable("node observer stopped"))?;
}
})
.await
.map_err(|_| Status::deadline_exceeded("node connect timeout"))?
}
}
fn terminal(code: Code) -> Option<Phase> {
match code {
Code::Unauthenticated | Code::PermissionDenied => Some(Phase::AuthError),
Code::FailedPrecondition | Code::Unimplemented | Code::InvalidArgument => {
Some(Phase::ProtocolError)
}
_ => None,
}
}
fn validate(s: &proto::Snapshot, old: Option<&proto::Snapshot>) -> Result<(), Status> {
if s.protocol_version != 1
|| s.agent_epoch.is_empty()
|| s.agent_epoch.len() > 128
|| s.sequence == 0
|| !s.full_snapshot
|| s.capabilities.len() > 64
|| s.capabilities.iter().any(|s| s.len() > 128)
{
return Err(Status::failed_precondition("invalid node snapshot"));
}
if old.is_some_and(|o| o.agent_epoch == s.agent_epoch && o.sequence > s.sequence) {
return Err(Status::failed_precondition("node sequence regressed"));
}
Ok(())
}
async fn hello(
client: &mut NodeClient<Channel>,
token: &str,
timing: Timing,
) -> Result<proto::Snapshot, Status> {
let mut r = node::authorized(
proto::Hello {
protocol_version: 1,
},
token,
)?;
r.set_timeout(timing.deadline);
tokio::time::timeout(timing.deadline, client.handshake(r))
.await
.map_err(|_| Status::deadline_exceeded("node heartbeat deadline"))?
.map(|s| s.into_inner())
}
async fn session(
address: SocketAddr,
token: &str,
timing: Timing,
tx: &watch::Sender<State>,
) -> Result<(), Status> {
let mut client = connect_client(address, timing).await?;
let first = hello(&mut client, token, timing).await?;
let previous = tx.borrow().snapshot.clone();
validate(&first, previous.as_ref())?;
let feed = open_watch_stream(&mut client, token, timing, &first).await?;
publish_ready(tx, &feed.current, &client);
follow_updates(&mut client, feed, token, timing, tx).await
}
async fn connect_client(
address: SocketAddr,
timing: Timing,
) -> Result<NodeClient<Channel>, Status> {
tokio::time::timeout(timing.deadline, node::connect(address))
.await
.map_err(|_| Status::unavailable("node connect timeout"))?
.map_err(|_| Status::unavailable("node unavailable"))
}
/// An open watch subscription and the snapshot it supplied first.
struct WatchFeed {
stream: tonic::Streaming<proto::Snapshot>,
current: proto::Snapshot,
}
/// Opens the watch from the handshake cursor and reads its first snapshot.
/// Admission stays closed until the subscription itself supplies a full snapshot.
async fn open_watch_stream(
client: &mut NodeClient<Channel>,
token: &str,
timing: Timing,
first: &proto::Snapshot,
) -> Result<WatchFeed, Status> {
let cursor = proto::Cursor {
agent_epoch: first.agent_epoch.clone(),
sequence: first.sequence,
};
let r = node::authorized(cursor, token)?;
let mut stream = tokio::time::timeout(timing.deadline, client.watch(r))
.await
.map_err(|_| Status::deadline_exceeded("node subscription timeout"))??
.into_inner();
let current = tokio::time::timeout(timing.deadline, stream.message())
.await
.map_err(|_| Status::deadline_exceeded("node snapshot timeout"))??
.ok_or_else(|| Status::unavailable("node subscription closed"))?;
validate(&current, Some(first))?;
Ok(WatchFeed { stream, current })
}
fn publish_ready(
tx: &watch::Sender<State>,
snapshot: &proto::Snapshot,
client: &NodeClient<Channel>,
) {
tx.send_replace(State {
phase: Phase::Ready,
snapshot: Some(snapshot.clone()),
heard: Some(Instant::now()),
client: Some(client.clone()),
});
}
/// Applies watch events and heartbeat handshakes until the node misbehaves or the stream ends.
async fn follow_updates(
client: &mut NodeClient<Channel>,
feed: WatchFeed,
token: &str,
timing: Timing,
tx: &watch::Sender<State>,
) -> Result<(), Status> {
let WatchFeed {
mut stream,
mut current,
} = feed;
let mut heartbeat = tokio::time::interval(timing.heartbeat);
heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
heartbeat.tick().await;
loop {
let (next, from_watch) = tokio::select! {
event=stream.message()=> (event?.ok_or_else(||Status::unavailable("node subscription closed"))?,true),
_=heartbeat.tick()=> (hello(client,token,timing).await?,false),
};
if is_overtaken_watch_event(&next, from_watch, &current) {
continue;
}
validate(&next, Some(&current))?;
if next.agent_epoch != current.agent_epoch {
return Err(Status::unavailable("node epoch changed; resubscribe"));
}
current = next;
publish_ready(tx, &current, client);
}
}
/// A handshake can overtake a buffered watch event. Ignore old buffered state;
/// the independent handshake must itself never go backwards in an epoch.
fn is_overtaken_watch_event(
next: &proto::Snapshot,
from_watch: bool,
current: &proto::Snapshot,
) -> bool {
from_watch && next.agent_epoch == current.agent_epoch && next.sequence < current.sequence
}
async fn observe(address: SocketAddr, token: String, timing: Timing, tx: watch::Sender<State>) {
let mut retry = timing.retry_min;
loop {
let started = Instant::now();
let error = session(address, &token, timing, &tx)
.await
.expect_err("subscriptions end with status");
let phase = terminal(error.code()).unwrap_or(Phase::Disconnected);
tx.send_modify(|s| {
s.phase = phase;
s.client = None;
s.heard = None;
});
if matches!(phase, Phase::AuthError | Phase::ProtocolError) {
return;
}
if started.elapsed() >= timing.heartbeat {
retry = timing.retry_min;
}
let jitter = Duration::from_millis((uuid::Uuid::new_v4().as_u128() % 101) as u64);
tokio::time::sleep((retry + jitter).min(timing.retry_max)).await;
retry = (retry * 2).min(timing.retry_max);
}
}