summaryrefslogtreecommitdiffstats
path: root/src/session.rs
blob: 01183837800b67f2119f0b48f0f91c3dd263c9a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use std::{
    collections::{hash_map::Entry, HashMap},
    fmt::Display,
    io::{BufWriter, Write},
    iter::IntoIterator,
    time::Duration,
};

use clap::Args;
use serde::{Deserialize, Serialize};

pub trait SessionWriter {
    type Error: Display;
    type Writer: Write;

    fn writer(&self) -> Result<Self::Writer, std::io::Error>;
    fn format(&self, session: &Session) -> Result<String, Self::Error>;
    fn filter(&self, session: &Session) -> bool;
}

#[derive(Debug, Clone, Args)]
#[group(skip)]
pub struct Config {
    /// Enable sorting
    #[arg(long, default_value_t = true)]
    pub sort: bool,
}

#[derive(Debug, Default)]
pub struct Sessions {
    inner: HashMap<String, State>,
    sort: bool,
}

impl Sessions {
    pub fn new(Config { sort }: Config) -> Self {
        Self {
            sort,
            ..Default::default()
        }
    }

    pub fn write_sessions<W: SessionWriter>(&self, writer: W) -> std::io::Result<()> {
        let mut buf_writer = BufWriter::new(writer.writer()?);

        let mut sessions: Vec<Session> = self.inner.iter().map(Session::from).collect();

        if self.sort {
            sessions.sort();
        }

        for session in sessions {
            match writer.format(&session) {
                Ok(fmt) if writer.filter(&session) => writeln!(buf_writer, "{fmt}")?,
                Err(err) => tracing::warn!(%err, "Failed to format session"),
                _ => tracing::debug!(%session, "Skipping filtered session"),
            }
        }

        Ok(())
    }

    pub fn add(&mut self, item: Session) {
        let span = tracing::trace_span!("Entry", ?item);
        let _guard = span.enter();

        match self.inner.entry(item.name) {
            Entry::Occupied(mut o) if item.state.is_better_than(o.get()) => {
                tracing::trace!(prev=?o, ?item.state, "New entry is more recent or accurate, replacing");
                o.insert(item.state);
            }
            Entry::Occupied(o) => {
                tracing::trace!(existing=?o, ?item.state, "Existing entry is more recent or accurate, skipping");
            }
            Entry::Vacant(v) => {
                tracing::trace!(?item.state, "No previous entry exists, inserting");
                v.insert(item.state);
            }
        }
    }
}

impl Extend<Session> for Sessions {
    fn extend<T: IntoIterator<Item = Session>>(&mut self, iter: T) {
        for item in iter {
            self.add(item)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum State {
    Discovered,
    #[serde(with = "epoch_timestamp")]
    Created(Duration),
    #[serde(with = "epoch_timestamp")]
    Attached(Duration),
    LocalHost,
}

impl State {
    pub fn is_better_than(&self, state: &State) -> bool {
        match (self, state) {
            (&State::LocalHost, _) => false,
            (_, &State::LocalHost) => true,
            _ => self > state,
        }
    }
}

mod epoch_timestamp {
    use std::time::Duration;

    use serde::{self, Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u64(duration.as_secs())
    }

    pub fn deserialize<'de, D>(d: D) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        u64::deserialize(d).map(Duration::from_secs)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Session {
    pub state: State,
    pub name: String,
}

impl Session {
    pub fn discover(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            state: State::Discovered,
        }
    }

    pub fn localhost(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            state: State::LocalHost,
        }
    }
}

impl Display for Session {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl From<(String, State)> for Session {
    fn from((name, state): (String, State)) -> Self {
        Self { state, name }
    }
}

impl From<(&String, &State)> for Session {
    fn from((name, &state): (&String, &State)) -> Self {
        Self {
            state,
            name: name.to_owned(),
        }
    }
}