use std::fmt;
use std::time::{Duration, SystemTime};
use crate::error::{ErrorKind, ErrorStage, NetError};
use crate::module::net_status::inner::names::NameConsumer;
use crate::net_status::NetworkNameSource;
use std::sync::Arc;
#[derive(Clone, Copy, Debug)]
pub struct NetworkNameOptions {
interval: Duration,
timeout: Duration,
}
impl Default for NetworkNameOptions {
fn default() -> Self {
Self {
interval: Duration::from_secs(30),
timeout: Duration::from_secs(10),
}
}
}
impl NetworkNameOptions {
pub fn with_interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn interval(&self) -> Duration {
self.interval
}
pub fn timeout(&self) -> Duration {
self.timeout
}
pub(crate) fn validate(&self) -> Result<(), NetError> {
if !(Duration::from_secs(1)..=Duration::from_secs(3600)).contains(&self.interval)
|| !(Duration::from_millis(100)..=Duration::from_secs(30)).contains(&self.timeout)
{
return Err(
NetError::from(ErrorKind::InvalidInput).with_stage(ErrorStage::NetworkMonitor)
);
}
Ok(())
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NetworkNameState {
Pending,
Ready,
Failed,
Closed,
}
#[derive(Clone)]
pub struct NetworkNameSnapshot {
state: NetworkNameState,
name: Option<String>,
source: NetworkNameSource,
sampled_at: Option<SystemTime>,
error: Option<NetError>,
diagnostics: Vec<NetError>,
#[cfg(test)]
retention_probe: Option<Arc<()>>,
}
impl fmt::Debug for NetworkNameSnapshot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NetworkNameSnapshot")
.field("state", &self.state)
.field("name_present", &self.name.is_some())
.field("source", &self.source)
.field("sampled_at", &self.sampled_at)
.field("error_kind", &self.error.as_ref().map(NetError::kind))
.field("diagnostic_count", &self.diagnostics.len())
.finish()
}
}
impl NetworkNameSnapshot {
pub fn state(&self) -> NetworkNameState {
self.state
}
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn source(&self) -> NetworkNameSource {
self.source
}
pub fn sampled_at(&self) -> Option<SystemTime> {
self.sampled_at
}
pub fn error(&self) -> Option<&NetError> {
self.error.as_ref()
}
pub fn diagnostics(&self) -> &[NetError] {
&self.diagnostics
}
pub(crate) fn empty(state: NetworkNameState) -> Self {
Self {
state,
name: None,
source: NetworkNameSource::NotCollected,
sampled_at: None,
error: None,
diagnostics: Vec::new(),
#[cfg(test)]
retention_probe: None,
}
}
#[cfg(any(windows, test))]
pub(crate) fn ready(
name: Option<String>,
source: NetworkNameSource,
sampled_at: SystemTime,
diagnostics: Vec<NetError>,
) -> Self {
Self {
state: NetworkNameState::Ready,
name,
source,
sampled_at: Some(sampled_at),
error: None,
diagnostics: diagnostics.iter().map(classified).collect(),
#[cfg(test)]
retention_probe: None,
}
}
pub(crate) fn failed(error: &NetError) -> Self {
Self {
error: Some(classified(error)),
..Self::empty(NetworkNameState::Failed)
}
}
#[cfg(test)]
pub(crate) fn retain_probe_for_test(&mut self, probe: Arc<()>) {
self.retention_probe = Some(probe);
}
}
fn classified(error: &NetError) -> NetError {
NetError::from(error.kind()).with_stage(ErrorStage::NetworkMonitor)
}
pub struct NetworkNameObserver {
pub(crate) inner: Arc<NameConsumer>,
pub(crate) changes: tokio::sync::watch::Receiver<()>,
pub(crate) initial: bool,
pub(crate) seen: u64,
pub(crate) terminal: bool,
}
impl fmt::Debug for NetworkNameObserver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NetworkNameObserver")
.finish_non_exhaustive()
}
}
impl NetworkNameObserver {
pub fn snapshot(&self) -> Result<NetworkNameSnapshot, NetError> {
self.inner.snapshot().map(|(_, snapshot)| snapshot)
}
pub async fn recv(&mut self) -> Result<Option<NetworkNameSnapshot>, NetError> {
if self.terminal {
return Ok(None);
}
loop {
self.changes.borrow_and_update();
if let Some((revision, snapshot)) = self.inner.next_snapshot(self.seen, self.initial) {
self.initial = false;
self.terminal = snapshot.state() == NetworkNameState::Closed;
self.seen = revision;
return Ok(Some(snapshot));
}
self.changes
.changed()
.await
.map_err(|_| NetError::from(ErrorKind::Closed))?;
}
}
pub async fn close(&mut self) -> Result<(), NetError> {
self.inner.request_close();
self.inner.wait_cleanup().await
}
}
impl Drop for NetworkNameObserver {
fn drop(&mut self) {
self.inner.request_close();
}
}