use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use buffa::{EnumValue, MessageField}; use proto::control::{TerminalInfo, TerminalInfos, TerminalRuntimeInfo}; use proto::rpc::health::{HealthReporter, ServingStatus}; use tokio::sync::{Mutex, Notify, watch}; use uuid::Uuid; use crate::{RegistryError, storage}; const ID_NAMESPACE: Uuid = Uuid::from_u128(0x9a55cb17401457128c2a64d47c9b613a); struct Directory { snapshot: TerminalInfos, revisions: HashMap, next_revision: u64, } struct Inner { directory: Mutex, data_path: PathBuf, snapshots: watch::Sender, shutdown: watch::Sender, health: HealthReporter, probe_requested: Notify, } #[derive(Clone)] pub struct RegistryService { inner: Arc, } #[derive(Clone)] pub(crate) struct ProbeTarget { pub id: String, pub info: TerminalInfo, revision: u64, } impl RegistryService { pub async fn open(data_path: impl Into) -> Result { let data_path = data_path.into(); let load_path = data_path.clone(); let snapshot = tokio::task::spawn_blocking(move || storage::load(&load_path)).await??; let revisions = snapshot.infos.keys().map(|id| (id.clone(), 0)).collect(); let (snapshots, _) = watch::channel(snapshot.clone()); let (shutdown, _) = watch::channel(false); let health = HealthReporter::new(); health .set_statuses(&[ ("", ServingStatus::NOT_SERVING), ("control.Center", ServingStatus::NOT_SERVING), ]) .expect("valid initial health statuses"); Ok(Self { inner: Arc::new(Inner { directory: Mutex::new(Directory { snapshot, revisions, next_revision: 1, }), data_path, snapshots, shutdown, health, probe_requested: Notify::new(), }), }) } pub fn subscribe(&self) -> watch::Receiver { self.inner.snapshots.subscribe() } pub fn shutdown_receiver(&self) -> watch::Receiver { self.inner.shutdown.subscribe() } pub async fn shutdown(&self) { let _directory = self.inner.directory.lock().await; self.publish_readiness(ServingStatus::NOT_SERVING); self.inner.shutdown.send_replace(true); } pub(crate) fn health_reporter(&self) -> &HealthReporter { &self.inner.health } pub(crate) async fn set_ready(&self) -> Result<(), RegistryError> { let _directory = self.inner.directory.lock().await; self.ensure_running()?; self.publish_readiness(ServingStatus::SERVING); Ok(()) } fn publish_readiness(&self, status: ServingStatus) { self.inner .health .set_statuses(&[("", status), ("control.Center", status)]) .expect("readiness maps to valid health statuses"); } pub async fn register(&self, info: TerminalInfo) -> Result { let info = normalize_info(info)?; let service = self.clone(); tokio::spawn(async move { service.register_transaction(info).await }).await? } async fn register_transaction(&self, info: TerminalInfo) -> Result { let mut directory = self.inner.directory.lock().await; self.ensure_running()?; let id = terminal_id(&info.terminal_mac); if directory .snapshot .infos .get(&id) .and_then(|runtime| runtime.info.as_option()) == Some(&info) { return Ok(id); } let mut candidate = directory.snapshot.clone(); candidate.infos.insert( id.clone(), TerminalRuntimeInfo { info: MessageField::some(info), status: ServingStatus::UNKNOWN.into(), ..Default::default() }, ); self.persist(candidate.clone()).await?; let revision = directory.next_revision; directory.next_revision += 1; directory.revisions.insert(id.clone(), revision); directory.snapshot = candidate.clone(); self.inner.snapshots.send_replace(candidate); self.inner.probe_requested.notify_one(); Ok(id) } pub async fn deregister(&self, id: String) -> Result<(), RegistryError> { let service = self.clone(); tokio::spawn(async move { let mut directory = service.inner.directory.lock().await; service.ensure_running()?; let mut candidate = directory.snapshot.clone(); if candidate.infos.remove(&id).is_none() { return Ok(()); } service.persist(candidate.clone()).await?; directory.revisions.remove(&id); directory.snapshot = candidate.clone(); service.inner.snapshots.send_replace(candidate); service.inner.probe_requested.notify_one(); Ok(()) }) .await? } async fn persist(&self, snapshot: TerminalInfos) -> Result<(), RegistryError> { let path = self.inner.data_path.clone(); tokio::task::spawn_blocking(move || storage::save(&path, snapshot)).await? } fn ensure_running(&self) -> Result<(), RegistryError> { if *self.inner.shutdown.borrow() { Err(RegistryError::new( "UNAVAILABLE", "registry is shutting down", )) } else { Ok(()) } } pub(crate) async fn probe_requested(&self) { self.inner.probe_requested.notified().await; } pub(crate) async fn probe_targets(&self) -> Vec { let directory = self.inner.directory.lock().await; directory .snapshot .infos .iter() .map(|(id, runtime)| ProbeTarget { id: id.clone(), info: runtime.info.as_option().unwrap().clone(), revision: directory.revisions[id], }) .collect() } pub(crate) async fn update_health( &self, target: &ProbeTarget, status: EnumValue, ) { let mut directory = self.inner.directory.lock().await; if *self.inner.shutdown.borrow() || directory.revisions.get(&target.id) != Some(&target.revision) { return; } if let Some(runtime) = directory.snapshot.infos.get_mut(&target.id) { if runtime.status != status { runtime.status = status; self.inner .snapshots .send_replace(directory.snapshot.clone()); } } } } pub(crate) fn terminal_id(mac: &str) -> String { Uuid::new_v5(&ID_NAMESPACE, mac.as_bytes()).to_string() } pub(crate) fn normalize_info(mut info: TerminalInfo) -> Result { info.terminal_mac = info.terminal_mac.trim().to_ascii_lowercase(); if info.terminal_mac.is_empty() || info.terminal_host.trim().is_empty() || !(1..=65535).contains(&info.terminal_port) { return Err(RegistryError::new( "INVALID_ARGUMENT", "host and MAC must be nonempty and port must be 1..=65535", )); } Ok(info) }