carte 0.6.0

Runs your apps' processes on demand behind *.localhost hostnames, one stack per git worktree
Documentation
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Talks to the daemon over its Unix socket.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use anyhow::{Context, bail};
use bytes::{Bytes, BytesMut};
use carte_api::ErrorBody;
use http::{HeaderMap, Method, Request, StatusCode, header};
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::upgrade::Upgraded;
use hyper_util::rt::TokioIo;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tokio::net::UnixStream;

use crate::exit::{Exit, Failure};

pub struct Client {
    socket: PathBuf,
}

static WARN_ABOUT_VERSION: AtomicBool = AtomicBool::new(false);

/// Has the first answer from a daemon that runs another carte print a warning to
/// stderr. Off unless called, for the TUI and the MCP server.
pub fn warn_about_version() {
    WARN_ABOUT_VERSION.store(true, Ordering::Relaxed);
}

/// What to tell the user when the daemon runs another carte than this one: the
/// version from the daemon's `carte-version` header, which daemons before it lack.
fn version_hint(headers: &HeaderMap) -> Option<String> {
    let this = env!("CARGO_PKG_VERSION");
    let daemon = headers
        .get(carte_api::VERSION_HEADER)
        .and_then(|value| value.to_str().ok());
    match daemon {
        Some(daemon) if daemon == this => None,
        Some(daemon) => Some(format!(
            "the daemon runs carte {daemon}, this is {this}; run `carte daemon restart`"
        )),
        None => Some(format!(
            "the daemon runs an older carte than this one ({this}); run `carte daemon restart`"
        )),
    }
}

/// Warns once, when asked to, that the daemon runs another carte.
fn check_version(headers: &HeaderMap) {
    warn_once(&WARN_ABOUT_VERSION, headers, &mut std::io::stderr());
}

/// Warns on `out` about the first answer after `armed` was set, if it comes from
/// another carte.
fn warn_once(armed: &AtomicBool, headers: &HeaderMap, out: &mut impl std::io::Write) {
    if armed.swap(false, Ordering::Relaxed)
        && let Some(hint) = version_hint(headers)
    {
        let _ = writeln!(out, "warning: {hint}");
    }
}

impl Client {
    pub fn new(socket: &Path) -> Self {
        Client {
            socket: socket.to_path_buf(),
        }
    }

    pub async fn get<T: DeserializeOwned>(&self, path: &str) -> anyhow::Result<T> {
        let response = self.send(Method::GET, path, Bytes::new()).await?;
        decode(response).await
    }

    pub async fn post<B: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> anyhow::Result<T> {
        let response = self
            .send(Method::POST, path, Bytes::from(serde_json::to_vec(body)?))
            .await?;
        decode(response).await
    }

    /// Posts `body` and calls `each` for every line of a newline-delimited JSON
    /// response, until the daemon ends it.
    pub async fn stream<B: Serialize, T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
        mut each: impl FnMut(T),
    ) -> anyhow::Result<()> {
        let bytes = match body {
            Some(body) => Bytes::from(serde_json::to_vec(body)?),
            None => Bytes::new(),
        };
        let response = self.send(method, path, bytes).await?;
        if !response.status().is_success() {
            return decode::<serde_json::Value>(response).await.map(|_| ());
        }
        check_version(response.headers());
        let mut body = response.into_body();
        let mut buf = BytesMut::new();
        while let Some(frame) = body.frame().await {
            if let Ok(data) = frame?.into_data() {
                buf.extend_from_slice(&data);
            }
            while let Some(pos) = buf.iter().position(|&b| b == b'\n') {
                let line = buf.split_to(pos + 1);
                each(serde_json::from_slice(&line[..pos])?);
            }
        }
        Ok(())
    }

    /// Posts `body` asking to switch the connection to `protocol`, and returns the
    /// connection once the daemon agrees.
    pub async fn upgrade<B: Serialize>(
        &self,
        path: &str,
        protocol: &str,
        body: &B,
    ) -> anyhow::Result<TokioIo<Upgraded>> {
        let stream = self.connect().await?;
        let (mut sender, connection) =
            hyper::client::conn::http1::handshake(TokioIo::new(stream)).await?;
        tokio::spawn(connection.with_upgrades());
        let request = Request::builder()
            .method(Method::POST)
            .uri(path)
            .header("host", "carte")
            .header("content-type", "application/json")
            .header(header::CONNECTION, "upgrade")
            .header(header::UPGRADE, protocol)
            .body(Full::new(Bytes::from(serde_json::to_vec(body)?)))?;
        let response = sender.send_request(request).await?;
        if response.status() != StatusCode::SWITCHING_PROTOCOLS {
            return decode::<serde_json::Value>(response).await.and_then(|_| {
                bail!("the daemon didn't switch to {protocol}");
            });
        }
        check_version(response.headers());
        Ok(TokioIo::new(hyper::upgrade::on(response).await?))
    }

    async fn connect(&self) -> anyhow::Result<UnixStream> {
        UnixStream::connect(&self.socket)
            .await
            .map_err(|err| unreachable(&self.socket, &err).into())
    }

    async fn send(
        &self,
        method: Method,
        path: &str,
        body: Bytes,
    ) -> anyhow::Result<http::Response<Incoming>> {
        let stream = self.connect().await?;
        let (mut sender, connection) =
            hyper::client::conn::http1::handshake(TokioIo::new(stream)).await?;
        tokio::spawn(connection);
        let request = Request::builder()
            .method(method)
            .uri(path)
            .header("host", "carte")
            .header("content-type", "application/json")
            .body(Full::new(body))?;
        Ok(sender.send_request(request).await?)
    }
}

/// Why the daemon couldn't be reached. A socket that refuses connections belongs
/// to a daemon that is starting or stopping, or to one that crashed.
fn unreachable(socket: &Path, err: &std::io::Error) -> Failure {
    let message = if err.kind() == std::io::ErrorKind::ConnectionRefused && socket.exists() {
        format!(
            "the carte daemon is starting or stopping ({}: {err}); try again in a moment, and if this persists it may have crashed: start it with `carte daemon`",
            socket.display()
        )
    } else {
        format!(
            "the carte daemon isn't running ({}: {err}); start it with `carte daemon`",
            socket.display()
        )
    };
    Failure::new(Exit::DaemonDown, message)
}

async fn decode<T: DeserializeOwned>(response: http::Response<Incoming>) -> anyhow::Result<T> {
    let status = response.status();
    let headers = response.headers().clone();
    let bytes = response.into_body().collect().await?.to_bytes();
    if status == StatusCode::OK {
        check_version(&headers);
        return serde_json::from_slice(&bytes).context("reading the daemon's answer");
    }
    let error = serde_json::from_slice::<ErrorBody>(&bytes).ok();
    let outdated = matches!(
        status,
        StatusCode::METHOD_NOT_ALLOWED
            | StatusCode::UNSUPPORTED_MEDIA_TYPE
            | StatusCode::UNPROCESSABLE_ENTITY
    ) || (status == StatusCode::NOT_FOUND && error.is_none());
    let found = error.is_some();
    let mut message = match error {
        Some(error) => error.error,
        None => match String::from_utf8_lossy(&bytes).trim() {
            "" => format!("the daemon answered {status}"),
            text => format!("the daemon answered {status}: {text}"),
        },
    };
    if outdated && let Some(hint) = version_hint(&headers) {
        message = format!("{message}; {hint}");
    }
    if status == StatusCode::NOT_FOUND && found {
        return Err(Failure::new(Exit::NotFound, message).into());
    }
    bail!("{message}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn a_socket_nobody_listens_on_means_starting_or_stopping() {
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("carte.sock");
        leave_a_socket_nobody_listens_on(&socket);

        let err = Client::new(&socket)
            .get::<serde_json::Value>("/")
            .await
            .unwrap_err();
        let failure = err.downcast_ref::<Failure>().unwrap();
        assert_eq!(failure.exit, Exit::DaemonDown);
        assert!(failure.message.contains("is starting or stopping"), "{err}");

        std::fs::remove_file(&socket).unwrap();
        let err = Client::new(&socket)
            .get::<serde_json::Value>("/")
            .await
            .unwrap_err();
        assert!(err.to_string().contains("isn't running"), "{err}");
    }

    /// Leaves a socket file at `path` that nothing listens on, bound by a forked
    /// child that exits, so no process another test spawns can inherit it.
    fn leave_a_socket_nobody_listens_on(path: &Path) {
        use nix::sys::socket::{AddressFamily, SockFlag, SockType, UnixAddr, bind, socket};
        use nix::sys::wait::{WaitStatus, waitpid};
        use nix::unistd::{ForkResult, fork};

        let addr = UnixAddr::new(path).unwrap();
        // SAFETY: the child makes only async-signal-safe calls, on `addr` built before the fork.
        match unsafe { fork() }.unwrap() {
            ForkResult::Child => {
                let bound = socket(
                    AddressFamily::Unix,
                    SockType::Stream,
                    SockFlag::empty(),
                    None,
                )
                .and_then(|fd| bind(std::os::fd::AsRawFd::as_raw_fd(&fd), &addr));
                // SAFETY: _exit takes no pointers.
                unsafe { libc::_exit(i32::from(bound.is_err())) }
            }
            ForkResult::Parent { child } => {
                assert_eq!(waitpid(child, None).unwrap(), WaitStatus::Exited(child, 0));
            }
        }
    }

    /// Serves `app` on a socket in `dir`, answering as carte `version` when given.
    fn stub(dir: &Path, version: Option<&'static str>, app: axum::Router) -> Client {
        let socket = dir.join("test.sock");
        let listener = tokio::net::UnixListener::bind(&socket).unwrap();
        let app = app.layer(axum::middleware::map_response(
            move |mut response: axum::response::Response| async move {
                if let Some(version) = version {
                    response.headers_mut().insert(
                        carte_api::VERSION_HEADER,
                        http::HeaderValue::from_static(version),
                    );
                }
                response
            },
        ));
        tokio::spawn(async move { axum::serve(listener, app).await });
        Client::new(&socket)
    }

    #[test]
    fn warns_once_and_only_about_another_version() {
        let headers = |version: &'static str| {
            let mut headers = HeaderMap::new();
            headers.insert(
                carte_api::VERSION_HEADER,
                http::HeaderValue::from_static(version),
            );
            headers
        };
        let this = env!("CARGO_PKG_VERSION");
        let mut out = Vec::new();

        let armed = AtomicBool::new(true);
        warn_once(&armed, &headers("0.0.1"), &mut out);
        warn_once(&armed, &headers("0.0.1"), &mut out);
        assert_eq!(
            String::from_utf8(std::mem::take(&mut out)).unwrap(),
            format!(
                "warning: the daemon runs carte 0.0.1, this is {this}; run `carte daemon restart`\n"
            )
        );

        let armed = AtomicBool::new(true);
        warn_once(&armed, &headers(this), &mut out);
        warn_once(&armed, &headers("0.0.1"), &mut out);
        assert!(out.is_empty(), "{}", String::from_utf8_lossy(&out));

        let armed = AtomicBool::new(false);
        warn_once(&armed, &headers("0.0.1"), &mut out);
        assert!(out.is_empty(), "{}", String::from_utf8_lossy(&out));
    }

    #[tokio::test]
    async fn a_daemon_without_a_route_is_named_as_another_version() {
        let dir = tempfile::tempdir().unwrap();
        let app = axum::Router::new()
            .route("/v1/snapshot", axum::routing::get(|| async { "{}" }))
            .fallback(|| async { StatusCode::NOT_FOUND });
        let client = stub(dir.path(), Some("0.0.1"), app);
        let err = client
            .upgrade(
                carte_api::paths::ATTACH,
                carte_api::attach::PROTOCOL,
                &serde_json::json!({}),
            )
            .await
            .unwrap_err()
            .to_string();
        let this = env!("CARGO_PKG_VERSION");
        assert!(
            err.contains(&format!(
                "the daemon runs carte 0.0.1, this is {this}; run `carte daemon restart`"
            )),
            "{err}"
        );
        assert!(
            err.starts_with("the daemon answered 404 Not Found"),
            "{err}"
        );
    }

    #[tokio::test]
    async fn a_daemon_without_the_version_header_is_older() {
        let dir = tempfile::tempdir().unwrap();
        let app = axum::Router::new().route(
            "/v1/control",
            axum::routing::post(|| async {
                (
                    StatusCode::UNPROCESSABLE_ENTITY,
                    "Failed to deserialize the JSON body: unknown variant `nap`",
                )
            }),
        );
        let client = stub(dir.path(), None, app);
        let err = client
            .post::<_, serde_json::Value>("/v1/control", &serde_json::json!({}))
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("unknown variant `nap`"), "{err}");
        assert!(
            err.contains("the daemon runs an older carte than this one"),
            "{err}"
        );
    }

    #[tokio::test]
    async fn errors_from_the_same_version_have_no_hint() {
        let dir = tempfile::tempdir().unwrap();
        let app = axum::Router::new()
            .route(
                "/v1/control",
                axum::routing::post(|| async {
                    (
                        StatusCode::NOT_FOUND,
                        axum::Json(ErrorBody {
                            error: "no app nova".into(),
                        }),
                    )
                }),
            )
            .fallback(|| async { StatusCode::NOT_FOUND });
        let client = stub(dir.path(), Some(env!("CARGO_PKG_VERSION")), app);
        let err = client
            .post::<_, serde_json::Value>("/v1/control", &serde_json::json!({}))
            .await
            .unwrap_err();
        assert_eq!(err.downcast_ref::<Failure>().unwrap().exit, Exit::NotFound);
        assert_eq!(err.to_string(), "no app nova");
        let err = client
            .post::<_, serde_json::Value>("/v1/attach", &serde_json::json!({}))
            .await
            .unwrap_err();
        assert_eq!(err.to_string(), "the daemon answered 404 Not Found");
    }

    #[tokio::test]
    async fn reads_bodies_larger_than_one_chunk() {
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("test.sock");
        let listener = tokio::net::UnixListener::bind(&socket).unwrap();
        let big: Vec<String> = (0..20_000).map(|i| format!("item {i}")).collect();
        let body = big.clone();
        let app = axum::Router::new().route(
            "/big",
            axum::routing::get(move || async move { axum::Json(body) }),
        );
        tokio::spawn(async move { axum::serve(listener, app).await });

        let got: Vec<String> = Client::new(&socket).get("/big").await.unwrap();
        assert_eq!(got, big);
    }
}