moqros 0.8.0

Stream ROS 2 topics (images as video, any message as data) over Media over QUIC
Documentation
//! Relay connection settings shared by publishers and subscribers.

use std::path::PathBuf;
use std::time::Duration;

use url::Url;

use crate::error::Wrap;
use crate::{Error, Publisher, Result, Subscriber};

/// Where and how to connect to a MoQ relay.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ClientConfig {
	/// Relay URL. The path scopes broadcast names, e.g. `http://localhost:4443/anon`.
	///
	/// `http://` fetches the relay's self-signed certificate fingerprint from
	/// `/certificate.sha256` (development only); `https://` verifies TLS normally.
	pub url: Url,
	/// Skip TLS verification entirely. Development only.
	pub insecure: bool,
	/// PEM client certificate chain for mTLS. Set it together with `tls_key`.
	pub tls_cert: Option<PathBuf>,
	/// PEM private key of `tls_cert`.
	pub tls_key: Option<PathBuf>,
}

impl ClientConfig {
	/// Connect to `url` with TLS verification and no client certificate.
	pub fn new(url: Url) -> Self {
		Self {
			url,
			insecure: false,
			tls_cert: None,
			tls_key: None,
		}
	}

	/// Set [`ClientConfig::insecure`].
	pub fn with_insecure(mut self, insecure: bool) -> Self {
		self.insecure = insecure;
		self
	}

	/// Present a client certificate to the relay (mTLS).
	pub fn with_client_cert(mut self, cert: impl Into<PathBuf>, key: impl Into<PathBuf>) -> Self {
		self.tls_cert = Some(cert.into());
		self.tls_key = Some(key.into());
		self
	}

	pub(crate) fn client(&self) -> Result<moq_tokio::Client> {
		let mut connect = moq_tokio::connect::Config::default();
		if self.insecure {
			connect.tls.insecure = Some(true);
		}
		connect.tls.cert = self.tls_cert.clone();
		connect.tls.key = self.tls_key.clone();
		connect.init(Default::default()).connection()
	}
}

/// Start one connection to the relay that both publishes and subscribes, e.g. for a robot
/// that streams its camera and takes commands. Must be called inside a tokio runtime.
///
/// The two handles share the session: [`Publisher::closed`] and [`Subscriber::closed`] resolve
/// together, and closing either closes both. Each direction keeps its own origin, so the
/// broadcasts subscribed to aren't published back to the relay.
pub fn connect_both(config: &ClientConfig) -> Result<(Publisher, Subscriber)> {
	let publish = moq_tokio::origin::spawn();
	let subscribe = moq_tokio::origin::spawn();
	let session = Session::new(
		config
			.client()?
			.with_publisher(&publish)
			.with_subscriber(subscribe.clone())
			.connect(config.url.clone()),
	);
	Ok((
		Publisher::from_parts(publish, session.clone()),
		Subscriber::from_parts(subscribe, session),
	))
}

/// How long [`Session::established`] waits for the relay to refuse a session it just accepted.
const REFUSAL_WINDOW: Duration = Duration::from_millis(500);

/// The connection to a relay behind a [`Publisher`] or [`Subscriber`].
///
/// The connection redials in the background if it drops. Clones share it, and so do a
/// publisher and subscriber made by [`connect_both`].
#[derive(Clone)]
pub struct Session {
	connection: moq_tokio::Connection,
}

impl Session {
	pub(crate) fn new(connection: moq_tokio::Connection) -> Self {
		Self { connection }
	}

	/// Wait until the first session with the relay is established.
	///
	/// Fails if the relay refuses the session, e.g. for missing credentials.
	pub async fn established(&self) -> Result<()> {
		// A relay accepts the transport before it asks its auth server about the session, so
		// a refusal (e.g. `Unauthorized`) closes a session that already looked established.
		// Watch the connection for a moment longer so that refusal is returned here.
		// The returned handle is a clone; our handle keeps the dial alive.
		let _ = self.connection.clone().established().await.connection()?;
		tokio::select! {
			res = self.connection.closed() => {
				res.connection()?;
				Err(Error::Connection("the connection closed right after it was established".into()))
			}
			_ = tokio::time::sleep(REFUSAL_WINDOW) => Ok(()),
		}
	}

	/// Resolves when the connection gives up for good.
	pub async fn closed(&self) -> Result<()> {
		self.connection.closed().await.connection()
	}

	/// Close the connection for every clone, without redialing.
	///
	/// Data already queued is delivered first, for at most about a second. Call this before
	/// exiting so the relay ends this session's broadcasts and subscriptions right away;
	/// otherwise it holds them until the session times out.
	pub async fn close(&self) -> Result<()> {
		self.connection.clone().close().await.connection()
	}
}

/// Turn a ROS topic into a broadcast name: `/camera/image_raw` -> `camera/image_raw`.
pub fn broadcast_name_for_topic(topic: &str) -> String {
	normalize_broadcast_name(topic).to_string()
}

/// A broadcast name without slashes at either end, the form to compare names in:
/// `/robots/a/` -> `robots/a`.
pub fn normalize_broadcast_name(name: &str) -> &str {
	name.trim_matches('/')
}

/// Whether the broadcast `name` is under `prefix`, by whole path segments: `robots` covers
/// `robots/a/camera` and `robots`, but not `robots2/camera`. Slashes at either end of both are
/// ignored, and an empty prefix covers every name.
pub fn broadcast_is_under(name: &str, prefix: &str) -> bool {
	let (name, prefix) = (normalize_broadcast_name(name), normalize_broadcast_name(prefix));
	prefix.is_empty() || name == prefix || name.strip_prefix(prefix).is_some_and(|rest| rest.starts_with('/'))
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn topic_to_broadcast_name() {
		assert_eq!(broadcast_name_for_topic("/camera/image_raw"), "camera/image_raw");
		assert_eq!(broadcast_name_for_topic("image"), "image");
	}

	#[test]
	fn broadcast_name_trims_all_outer_slashes() {
		assert_eq!(broadcast_name_for_topic("/front/image_raw/"), "front/image_raw");
		assert_eq!(broadcast_name_for_topic("//image"), "image");
		assert_eq!(broadcast_name_for_topic("/"), "");
	}

	#[test]
	fn matches_prefixes_by_segment() {
		assert!(broadcast_is_under("robots/a/camera", "robots"));
		assert!(broadcast_is_under("robots/a/camera", "robots/a"));
		assert!(broadcast_is_under("robots", "robots"));
		assert!(broadcast_is_under("anything", ""));
		assert!(broadcast_is_under("/robots/a/", "/robots/"));
		assert!(broadcast_is_under("anything", "/"));
		assert!(!broadcast_is_under("robots2/camera", "robots"));
		assert!(!broadcast_is_under("robot", "robots"));
	}

	#[test]
	fn new_config_verifies_tls() {
		let config = ClientConfig::new("https://relay.example/anon".parse().unwrap());
		assert!(!config.insecure);
		assert_eq!(config.url.path(), "/anon");
	}

	#[test]
	fn client_cert_needs_a_key() {
		let mut config = ClientConfig::new("https://relay.example/anon".parse().unwrap());
		config.tls_cert = Some("client.pem".into());
		assert!(config.client().is_err());
	}
}