iroh_n0des/simulation/
events.rs

1use std::{borrow::Cow, fmt};
2
3use iroh::NodeId;
4
5pub struct EventId<'a, T>(Option<&'a T>);
6
7impl<'a, T> fmt::Display for EventId<'a, T>
8where
9    T: fmt::Display,
10{
11    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12        match self.0.as_ref() {
13            None => Ok(()),
14            Some(inner) => inner.fmt(f),
15        }
16    }
17}
18
19#[derive(Debug, derive_more::From, derive_more::Display)]
20pub enum VisNode<'a> {
21    #[display("{}", _0.fmt_short())]
22    Node(NodeId),
23    Other(Cow<'a, str>),
24}
25
26impl<'a> VisNode<'a> {
27    pub fn to_static(self) -> VisNode<'static> {
28        match self {
29            VisNode::Node(n) => VisNode::Node(n),
30            VisNode::Other(cow) => VisNode::Other(Cow::Owned(cow.into_owned())),
31        }
32    }
33}
34
35impl<'a> From<&'a str> for VisNode<'a> {
36    fn from(value: &'a str) -> Self {
37        Self::Other(Cow::Borrowed(value))
38    }
39}
40
41impl<'a> From<String> for VisNode<'a> {
42    fn from(value: String) -> Self {
43        Self::Other(Cow::Owned(value))
44    }
45}
46
47pub const TARGET: &str = "_n0des_event";
48pub const TARGET_END: &str = "_n0des_event_end";
49
50pub fn event<'a>(
51    from: impl Into<VisNode<'a>>,
52    to: impl Into<VisNode<'a>>,
53    label: impl fmt::Display,
54) {
55    event_start(from, to, label, Option::<&str>::None);
56}
57
58pub fn event_start<'a>(
59    from: impl Into<VisNode<'a>>,
60    to: impl Into<VisNode<'a>>,
61    label: impl fmt::Display,
62    id: Option<impl fmt::Display>,
63) {
64    let from = from.into();
65    let to = to.into();
66    if let Some(ref id) = id {
67        tracing::event! {
68            target: TARGET,
69            tracing::Level::INFO,
70            %from, %to, %label, %id
71        }
72    } else {
73        tracing::event! {
74            target: TARGET,
75            tracing::Level::INFO,
76            %from, %to, %label
77        }
78    }
79}
80
81pub fn event_end<'a>(
82    from: impl Into<VisNode<'a>>,
83    to: impl Into<VisNode<'a>>,
84    label: impl fmt::Display,
85    id: impl fmt::Display,
86) {
87    let from = from.into();
88    let to = to.into();
89    tracing::event! {
90        target: TARGET_END,
91        tracing::Level::INFO,
92        %from, %to, %label, %id
93    }
94}