aboutsummaryrefslogtreecommitdiffstats
path: root/crates/turtle/src/client/mod.rs
blob: 07f01e6c6fc4e5e36cd29ef8666e912a155cd9c9 (plain) (blame)
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use eyre::{Context as EyreContext, Result};
use time::OffsetDateTime;
use tonic::Code;
use tonic::transport::{Channel, Endpoint, Uri};
use tower::service_fn;

use hyper_util::rt::TokioIo;

#[cfg(unix)]
use tokio::net::UnixStream;

use crate::generated::{
    self, DAEMON_PROTOCOL_VERSION,
    control::{
        ForceSyncReply, ForceSyncRequest, PathsReply, PathsRequest, StatusReply, StatusRequest,
        control_client::ControlClient as ControlServiceClient,
    },
    history::{
        EndHistoryReply, EndHistoryRequest, HistoryEntry, HistoryRequest, StartHistoryReply,
        StartHistoryRequest, TailHistoryRequest,
        history_client::HistoryClient as HistoryServiceClient,
    },
};

pub use crate::generated::history::{HistoryEventKind, TailHistoryReply};
use crate::history::History;

fn normalize_optional_field(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_owned())
    }
}

pub fn history_entry_to_history(entry: HistoryEntry) -> History {
    let timestamp = OffsetDateTime::from_unix_timestamp_nanos(i128::from(entry.timestamp))
        .expect("Daemon history timestamp should always be valid");

    History {
        id: entry.id.into(),
        timestamp,
        duration: entry.duration,
        exit: entry.exit,
        command: entry.command,
        cwd: entry.cwd,
        session: entry.session,
        hostname: entry.hostname,
        author: entry.author,
        intent: normalize_optional_field(&entry.intent),
        deleted_at: None,
    }
}

#[must_use]
pub fn daemon_matches_expected(version: &str, protocol: u32) -> bool {
    protocol == DAEMON_PROTOCOL_VERSION
}

#[must_use]
pub fn daemon_mismatch_message(version: &str, protocol: u32) -> String {
    if protocol == DAEMON_PROTOCOL_VERSION {
        unreachable!()
    } else {
        format!("daemon protocol mismatch: expected {DAEMON_PROTOCOL_VERSION}, got {protocol}")
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DaemonClientErrorKind {
    Connect,
    Unavailable,
    Unimplemented,
    Other,
}

#[must_use]
pub fn classify_error(error: &eyre::Report) -> DaemonClientErrorKind {
    for cause in error.chain() {
        if cause.downcast_ref::<tonic::transport::Error>().is_some() {
            return DaemonClientErrorKind::Connect;
        }

        if let Some(status) = cause.downcast_ref::<tonic::Status>() {
            return match status.code() {
                Code::Unavailable => DaemonClientErrorKind::Unavailable,
                Code::Unimplemented => DaemonClientErrorKind::Unimplemented,
                _ => DaemonClientErrorKind::Other,
            };
        }
    }

    DaemonClientErrorKind::Other
}

#[derive(Debug)]
pub enum Probe {
    Ready(ControlClient),
    NeedsRestart(String),
    Unreachable(eyre::Report),
}

/// Check if a client can reach the daemon.
pub async fn probe(path: String) -> Probe {
    let mut client = match ControlClient::new(path).await {
        Ok(client) => client,
        Err(err) => return Probe::Unreachable(err),
    };

    match client.status().await {
        Ok(status) => {
            if daemon_matches_expected(&status.version, status.protocol) {
                Probe::Ready(client)
            } else {
                Probe::NeedsRestart(daemon_mismatch_message(&status.version, status.protocol))
            }
        }
        Err(err) => Probe::Unreachable(err),
    }
}

// ============================================================================
// History Client
// ============================================================================

#[derive(Debug)]
pub struct HistoryClient {
    client: HistoryServiceClient<Channel>,
}

pub struct Range {
    pub start: OffsetDateTime,
    pub end: OffsetDateTime,
}

// Wrap the grpc client
impl HistoryClient {
    #[cfg(unix)]
    pub async fn new(path: String) -> Result<Self> {
        use eyre::Context;

        let log_path = path.clone();
        let channel = Endpoint::try_from("http://atuin_local_daemon:0")?
            .connect_with_connector(service_fn(move |_: Uri| {
                let path = path.clone();

                async move {
                    Ok::<_, std::io::Error>(TokioIo::new(UnixStream::connect(path.clone()).await?))
                }
            }))
            .await
            .wrap_err_with(|| {
                format!(
                    "failed to connect to local atuin daemon at {}. Is it running?",
                    &log_path
                )
            })?;

        let client = HistoryServiceClient::new(channel);

        Ok(Self { client })
    }

    pub async fn start_history(&mut self, h: History) -> Result<StartHistoryReply> {
        let req = StartHistoryRequest {
            command: h.command,
            cwd: h.cwd,
            hostname: h.hostname,
            session: h.session,
            timestamp: h.timestamp.unix_timestamp_nanos() as u64,
            author: h.author,
            intent: h.intent.unwrap_or_default(),
        };

        Ok(self.client.start_history(req).await?.into_inner())
    }

    pub async fn history(&mut self, session: String, range: Option<Range>) -> Result<Vec<History>> {
        let req = HistoryRequest {
            session,
            range: range.map(|r| generated::history::Range {
                start: r.start.unix_timestamp() as u64,
                end: r.end.unix_timestamp() as u64,
            }),
        };

        let reply = self.client.history(req).await?.into_inner();

        Ok(reply
            .entries
            .into_iter()
            .map(history_entry_to_history)
            .collect())
    }

    pub async fn end_history(
        &mut self,
        id: String,
        duration: u64,
        exit: i64,
    ) -> Result<EndHistoryReply> {
        let req = EndHistoryRequest { id, exit, duration };

        Ok(self.client.end_history(req).await?.into_inner())
    }

    pub async fn tail_history(&mut self) -> Result<tonic::Streaming<TailHistoryReply>> {
        Ok(self
            .client
            .tail_history(TailHistoryRequest {})
            .await?
            .into_inner())
    }
}

// ============================================================================
// Control Client
// ============================================================================

/// Client for the Control gRPC service.
#[derive(Debug)]
pub struct ControlClient {
    client: ControlServiceClient<Channel>,
}

impl ControlClient {
    /// Connect to the daemon's control service.
    pub async fn new(path: String) -> Result<Self> {
        let log_path = path.clone();
        let channel = Endpoint::try_from("http://atuin_local_daemon:0")?
            .connect_with_connector(service_fn(move |_: Uri| {
                let path = path.clone();

                async move {
                    Ok::<_, std::io::Error>(TokioIo::new(UnixStream::connect(path.clone()).await?))
                }
            }))
            .await
            .wrap_err_with(|| {
                format!(
                    "failed to connect to local atuin daemon at {}. Is it running?",
                    &log_path
                )
            })?;

        let client = ControlServiceClient::new(channel);

        Ok(Self { client })
    }

    pub async fn paths(&mut self) -> Result<PathsReply> {
        Ok(self.client.paths(PathsRequest {}).await?.into_inner())
    }

    pub async fn force_sync(&mut self) -> Result<ForceSyncReply> {
        Ok(self
            .client
            .force_sync(ForceSyncRequest {})
            .await?
            .into_inner())
    }

    pub async fn status(&mut self) -> Result<StatusReply> {
        Ok(self.client.status(StatusRequest {}).await?.into_inner())
    }
}