devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! The client side: connect to the daemon, starting it when nothing answers
//! (the lazy start), and handle a version handoff. Commands that need live
//! features call [`connect`] ([`ensure_bridge`] for the ssh-agent relay).

use std::collections::VecDeque;
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use serde_json::Value;

use super::endpoint::{self, Stream};
use super::proto::{self, HelloParams, HelloResult, Notification, Request, Response, Version};

/// How long [`connect`] waits for a daemon it started (or one handing off).
pub const START_TIMEOUT: Duration = Duration::from_secs(5);
const POLL: Duration = Duration::from_millis(50);

/// A connection past the hello. `daemon` is what the daemon reported. Held
/// open, it makes its client a holder (the TUI holds one for its life).
///
/// Sync and single-threaded: [`call`](Self::call) sets aside any
/// notification that arrives before its response, and
/// [`next_notification`](Self::next_notification) hands them out, oldest
/// first, then waits for the next.
pub struct Conn {
    reader: BufReader<Stream>,
    writer: Stream,
    next_id: u64,
    #[allow(dead_code)] // read by tests; clients that check `protocol` will
    pub daemon: HelloResult,
    /// Notifications read while waiting for a response.
    notes: VecDeque<Notification>,
    /// A line cut short by a read timeout, completed by the next read.
    partial: Vec<u8>,
}

enum Incoming {
    Response(Response),
    Notification(Notification),
    /// The daemon closed the connection (a line cut short included).
    Closed,
}

/// How [`Conn::call_streaming`] ended.
#[derive(Debug)]
pub enum Streamed {
    Answer(Response),
    /// The callback asked to hang up; the caller drops the connection.
    HungUp,
    /// The connection ended before the response: the daemon exited (a
    /// handoff, a crash) or reset it.
    Lost,
}

impl Conn {
    /// Over `stream`, past its hello (`daemon` is the reply): the local
    /// daemon's socket, or a machine's `ssh::Duplex`.
    pub(crate) fn new(stream: Stream, daemon: HelloResult) -> Result<Self> {
        let reader = BufReader::new(stream.try_clone().context("cannot clone the daemon connection")?);
        Ok(Self { reader, writer: stream, next_id: 1, daemon, notes: VecDeque::new(), partial: Vec::new() })
    }

    /// One request, one response; notifications read meanwhile are kept for
    /// [`next_notification`](Self::next_notification).
    pub fn call(&mut self, method: &str, params: Value) -> Result<Response> {
        let id = self.next_id;
        self.next_id += 1;
        let mut line = serde_json::to_vec(&Request { id: Some(id), method: method.into(), params })?;
        line.push(b'\n');
        self.writer.write_all(&line).context("cannot write to devsandbox serve")?;
        self.reader.get_ref().set_read_timeout(None).context("cannot clear the read timeout")?;
        loop {
            match self.read()? {
                Some(Incoming::Notification(n)) => self.notes.push_back(n),
                Some(Incoming::Response(r)) if r.id == Some(id) => return Ok(r),
                Some(Incoming::Response(r)) => bail!("devsandbox serve answered request {:?}, expected {id}", r.id),
                Some(Incoming::Closed) => bail!("devsandbox serve closed the connection"),
                None => bail!("timed out reading from devsandbox serve"),
            }
        }
    }

    /// [`call`](Self::call), waiting at most `timeout` for the response:
    /// `None` when it didn't come. The request is then still answered some
    /// time, out of turn for the next call, so the caller drops the
    /// connection (a machine link reconnects).
    pub fn call_within(&mut self, method: &str, params: Value, timeout: Duration) -> Result<Option<Response>> {
        let id = self.next_id;
        self.next_id += 1;
        let mut line = serde_json::to_vec(&Request { id: Some(id), method: method.into(), params })?;
        line.push(b'\n');
        self.writer.write_all(&line).context("cannot write to devsandbox serve")?;
        let deadline = Instant::now() + timeout;
        loop {
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                return Ok(None);
            }
            self.reader.get_ref().set_read_timeout(Some(left)).context("cannot set a read timeout")?;
            match self.read()? {
                Some(Incoming::Notification(n)) => self.notes.push_back(n),
                Some(Incoming::Response(r)) if r.id == Some(id) => return Ok(Some(r)),
                Some(Incoming::Response(r)) => bail!("devsandbox serve answered request {:?}, expected {id}", r.id),
                Some(Incoming::Closed) => bail!("devsandbox serve closed the connection"),
                None => {}
            }
        }
    }

    /// One request whose response may take long (a verb), with its
    /// notifications handed to `on` as they come. `on` also runs with `None`
    /// every `tick` without a line, so it can poll a flag (Ctrl-C); it
    /// returns `false` to hang up, which is how a client cancels.
    pub fn call_streaming(
        &mut self,
        method: &str,
        params: Value,
        tick: Duration,
        on: &mut dyn FnMut(Option<&Notification>) -> bool,
    ) -> Result<Streamed> {
        let id = self.next_id;
        self.next_id += 1;
        let mut line = serde_json::to_vec(&Request { id: Some(id), method: method.into(), params })?;
        line.push(b'\n');
        self.writer.write_all(&line).context("cannot write to devsandbox serve")?;
        self.reader.get_ref().set_read_timeout(Some(tick)).context("cannot set a read timeout")?;
        while let Some(n) = self.notes.pop_front() {
            if !on(Some(&n)) {
                return Ok(Streamed::HungUp);
            }
        }
        loop {
            let incoming = match self.read() {
                Ok(incoming) => incoming,
                // A reset, or a line that won't parse: the answer isn't coming.
                Err(_) => return Ok(Streamed::Lost),
            };
            let go_on = match incoming {
                Some(Incoming::Response(r)) if r.id == Some(id) => return Ok(Streamed::Answer(r)),
                Some(Incoming::Response(r)) => bail!("devsandbox serve answered request {:?}, expected {id}", r.id),
                Some(Incoming::Closed) => return Ok(Streamed::Lost),
                Some(Incoming::Notification(n)) => on(Some(&n)),
                None => on(None),
            };
            if !go_on {
                return Ok(Streamed::HungUp);
            }
        }
    }

    /// The oldest notification set aside, else wait up to `timeout` for one;
    /// `None` when none came.
    pub fn next_notification(&mut self, timeout: Duration) -> Result<Option<Notification>> {
        if let Some(n) = self.notes.pop_front() {
            return Ok(Some(n));
        }
        let deadline = Instant::now() + timeout;
        loop {
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                return Ok(None);
            }
            self.reader.get_ref().set_read_timeout(Some(left)).context("cannot set a read timeout")?;
            match self.read()? {
                Some(Incoming::Notification(n)) => return Ok(Some(n)),
                Some(Incoming::Response(r)) => bail!("devsandbox serve sent a response {:?} nobody asked for", r.id),
                Some(Incoming::Closed) => bail!("devsandbox serve closed the connection"),
                None => {}
            }
        }
    }

    /// One line, `None` on a read timeout (a partial line is kept for the
    /// next call), [`Incoming::Closed`] at the end. A line with a `method` is
    /// a notification.
    fn read(&mut self) -> Result<Option<Incoming>> {
        let limit = proto::MAX_LINE.saturating_sub(self.partial.len() as u64);
        match (&mut self.reader).take(limit).read_until(b'\n', &mut self.partial) {
            Ok(_) => {}
            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => return Ok(None),
            Err(e) => return Err(e).context("cannot read from devsandbox serve"),
        }
        if !self.partial.ends_with(b"\n") {
            if self.partial.len() as u64 >= proto::MAX_LINE {
                bail!("devsandbox serve sent a line over {} bytes", proto::MAX_LINE);
            }
            return Ok(Some(Incoming::Closed));
        }
        let line = std::mem::take(&mut self.partial);
        let value: Value = serde_json::from_slice(&line).context("bad message from devsandbox serve")?;
        Ok(Some(if value.get("method").is_some() {
            Incoming::Notification(serde_json::from_value(value).context("bad notification from devsandbox serve")?)
        } else {
            Incoming::Response(serde_json::from_value(value).context("bad response from devsandbox serve")?)
        }))
    }
}

/// The daemon's answer to a hello.
#[derive(Debug)]
pub enum Hello {
    Ready(HelloResult),
    /// This client is newer; the daemon is draining and will exit.
    Handoff,
    /// The connection closed or timed out first (the daemon is exiting).
    Closed,
}

/// Why [`connect_with`] starts a daemon.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartReason {
    /// Nothing answered on the socket (the plain lazy start).
    NothingAnswering,
    /// The daemon answered `handoff`: this client is newer.
    Handoff,
}

/// Connect to the daemon in `dir`, starting it if nothing answers, and say
/// hello as `client` (`tui`, `cli`, …). The start goes through the service
/// manager when `serve install` installed a unit ([`super::install::lazy_start`]).
pub fn connect(dir: &Path, client: &str) -> Result<Conn> {
    connect_with(dir, client, &Version::current(), START_TIMEOUT, &super::install::lazy_start)
}

/// Make sure a daemon runs (lazy start), for a command that just started a
/// container: its dispatcher must get a live host even with no dashboard
/// open. Best effort: a failure is one warning line on stderr (stdout stays
/// clean for `run --json`), never an error. The connection is dropped at
/// once; from then on the running instance holds the daemon, if it's one
/// that expects a host.
pub fn ensure_running(client: &str) {
    if let Err(e) = endpoint::socket_dir().and_then(|dir| connect(&dir, client)) {
        eprintln!("warning: devsandbox serve: {e:#}");
    }
}

/// Ask the daemon (lazy start, as `cli`) for instance `instance`'s bridge
/// (`bridges.ensure`, docs/reference/api.md), reporting `agent`, the caller's
/// own `SSH_AUTH_SOCK`. Without `wait` it returns once the daemon took the
/// request; with it, once the bridge's handshake is decided or `wait` ran out,
/// with the [`Readiness`](crate::devsbd::bridge::Readiness) (`None` from a
/// daemon too old to wait). Hold the returned connection while the command
/// that needs the relay runs: it makes the command a holder.
///
/// Under [`set_in_process`] it never starts one: no daemon answering is an
/// error (the caller's `note:`), as in [`ensure_bridge_running`].
pub fn ensure_bridge(
    instance: &str,
    agent: Option<&Path>,
    wait: Option<Duration>,
) -> Result<(Conn, Option<crate::devsbd::bridge::Readiness>)> {
    let dir = endpoint::socket_dir()?;
    let mut conn = if IN_PROCESS.load(std::sync::atomic::Ordering::Relaxed) {
        connect_running(&dir, "cli", &Version::current(), START_TIMEOUT)?
            .context("devsandbox serve isn't running (not starting it from an --in-process verb)")?
    } else {
        connect(&dir, "cli")?
    };
    let ready = request_bridge(&mut conn, instance, agent, wait)?;
    Ok((conn, ready))
}

/// Set once by `main` for `--in-process`: this process is a verb run by the
/// daemon (or the dispatcher, or a client's fallback), so it must never lazy
/// start a daemon. A subprocess of a draining daemon would race the
/// successor for `serve.lock` (why [`ensure_bridge_running`] exists), and in
/// the fallback nothing answers anyway, at 5 s per start. A process-wide flag
/// rather than a parameter: the bridge waits sit deep in `run`/`start`, and
/// the mode is fixed for the process's life.
static IN_PROCESS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

pub fn set_in_process() {
    IN_PROCESS.store(true, std::sync::atomic::Ordering::Relaxed);
}

pub fn in_process() -> bool {
    IN_PROCESS.load(std::sync::atomic::Ordering::Relaxed)
}

/// How long [`attach_hold`] waits for the hello, then for the answer.
const ATTACH_WAIT: Duration = Duration::from_millis(500);

/// Tell a running daemon this process attaches to `instance` (an exact name
/// or id; on `machine` when given), for as long as the returned connection
/// is held (`instances.attach`, docs/reference/api.md): where that
/// instance's opens go. Best effort and silent: `None` when no daemon
/// answers within [`ATTACH_WAIT`], it refuses, or under [`set_in_process`].
/// Never starts a daemon, and says hello as version 0.0.0 (older than any)
/// so it never triggers a handoff either: an attach record isn't worth a
/// daemon's restart. Nothing else rides on the connection, so it is
/// attach-only: it doesn't hold the daemon up, and a drain ending it ends
/// only the record. For a terminal the user is at (a TTY `exec`, a
/// dashboard tab), never a script's exec.
pub fn attach_hold(instance: &str, machine: Option<&str>) -> Option<Conn> {
    if IN_PROCESS.load(std::sync::atomic::Ordering::Relaxed) {
        return None;
    }
    let dir = endpoint::socket_dir().ok()?;
    let version = Version { semver: "0.0.0".into(), build: 0 };
    let mut conn = connect_running(&dir, "cli", &version, ATTACH_WAIT).ok()??;
    let mut params = serde_json::json!({ "instance": instance });
    if let Some(machine) = machine {
        params["machine"] = machine.into();
    }
    attach_on(&mut conn, params).then_some(conn)
}

/// `instances.attach` with `params` on `conn`, within [`ATTACH_WAIT`]:
/// whether it was taken.
fn attach_on(conn: &mut Conn, params: Value) -> bool {
    matches!(conn.call_within("instances.attach", params, ATTACH_WAIT), Ok(Some(r)) if r.error.is_none())
}

/// [`ensure_bridge`] without the lazy start (`None` when no daemon answers),
/// for code running in the daemon itself (a dispatcher's child op), which
/// reaches it over its own socket. While it drains nothing answers, and a
/// lazy start would spawn this binary (maybe outdated) to race the
/// successor for `serve.lock`, or undo a `shutdown`.
pub(crate) fn ensure_bridge_running(
    dir: &Path,
    instance: &str,
    agent: Option<&Path>,
    wait: Option<Duration>,
) -> Result<Option<(Conn, Option<crate::devsbd::bridge::Readiness>)>> {
    let Some(mut conn) = connect_running(dir, "cli", &Version::current(), START_TIMEOUT)? else { return Ok(None) };
    let ready = request_bridge(&mut conn, instance, agent, wait)?;
    Ok(Some((conn, ready)))
}

/// Send `bridges.ensure` on `conn`; the readiness as [`ensure_bridge`]'s.
fn request_bridge(
    conn: &mut Conn,
    instance: &str,
    agent: Option<&Path>,
    wait: Option<Duration>,
) -> Result<Option<crate::devsbd::bridge::Readiness>> {
    // A non-UTF-8 path can't go on the wire: the daemon falls back to its own.
    let agent = agent.and_then(Path::to_str);
    let mut params = serde_json::json!({ "instance": instance, "agent": agent });
    if let Some(wait) = wait {
        params["wait"] = wait.as_secs_f64().into();
    }
    let r = conn.call("bridges.ensure", params)?;
    if let Some(e) = r.error {
        bail!("devsandbox serve: {} ({})", e.message, e.code);
    }
    Ok(readiness(&r.result.unwrap_or(Value::Null)))
}

/// A waited `bridges.ensure` result's readiness; `None` without `ready` (a
/// daemon that predates `wait` answers a plain `{"ok":true}`).
fn readiness(result: &Value) -> Option<crate::devsbd::bridge::Readiness> {
    let ready = result.get("ready")?.as_bool()?;
    let error = result.get("error").and_then(Value::as_str).map(str::to_string);
    Some(crate::devsbd::bridge::Readiness { ready, error })
}

/// Connect to a daemon already running in `dir`, without the lazy start:
/// `None` when nothing answers, or the one answering is exiting (a handoff,
/// which this `version` may have just triggered). `timeout` bounds the hello.
pub(crate) fn connect_running(dir: &Path, client: &str, version: &Version, timeout: Duration) -> Result<Option<Conn>> {
    let Ok(mut stream) = endpoint::connect(dir) else { return Ok(None) };
    stream.set_read_timeout(Some(timeout)).context("cannot set a read timeout")?;
    match hello(&mut stream, version, client)? {
        Hello::Ready(daemon) => {
            stream.set_read_timeout(None).context("cannot clear the read timeout")?;
            Ok(Some(Conn::new(stream, daemon)?))
        }
        Hello::Handoff | Hello::Closed => Ok(None),
    }
}

/// [`connect`] with the version, timeout and spawner injectable for tests.
///
/// Starts at most one daemon: when the connect fails, or when the daemon
/// answers `handoff` (ours then waits for the old one's lock while it
/// drains). Then polls until `timeout`. Known gap: if an older client's
/// daemon wins that lock race, this gives up after `timeout`; the next call
/// hands off again.
pub(crate) fn connect_with(
    dir: &Path,
    client: &str,
    version: &Version,
    timeout: Duration,
    spawn: &dyn Fn(&Path, StartReason) -> Result<()>,
) -> Result<Conn> {
    let deadline = Instant::now() + timeout;
    let mut spawned = false;
    loop {
        let start = match endpoint::connect(dir) {
            Ok(mut stream) => {
                let left = deadline.saturating_duration_since(Instant::now()).max(POLL);
                stream.set_read_timeout(Some(left)).context("cannot set a read timeout")?;
                match hello(&mut stream, version, client)? {
                    Hello::Ready(daemon) => {
                        stream.set_read_timeout(None).context("cannot clear the read timeout")?;
                        return Conn::new(stream, daemon);
                    }
                    Hello::Handoff => Some(StartReason::Handoff),
                    // Exiting daemon: its lock holds off a successor, retry.
                    Hello::Closed => None,
                }
            }
            Err(_) => Some(StartReason::NothingAnswering),
        };
        if let Some(reason) = start
            && !spawned
        {
            spawn(dir, reason)?;
            spawned = true;
        }
        if Instant::now() >= deadline {
            let log = endpoint::log_path().map(|p| format!("; see {}", p.display())).unwrap_or_default();
            bail!("devsandbox serve did not answer on {} within {timeout:?}{log}", endpoint::socket_path(dir).display());
        }
        std::thread::sleep(POLL);
    }
}

/// Send the hello and read its reply. I/O trouble (EOF, timeout) is
/// [`Hello::Closed`]; an error response is an error. Reads byte by byte so
/// nothing past the reply's newline is consumed before [`Conn`] buffers.
pub(crate) fn hello(stream: &mut Stream, version: &Version, client: &str) -> Result<Hello> {
    hello_with(stream, version, client, false)
}

/// [`hello`], with `force` (`HelloParams::force`): ask the daemon to hand
/// off to this binary whatever its version.
pub(crate) fn hello_with(stream: &mut Stream, version: &Version, client: &str, force: bool) -> Result<Hello> {
    let params = HelloParams { version: version.semver.clone(), build: version.build, client: client.into(), force };
    let request = Request { id: Some(0), method: "hello".into(), params: serde_json::to_value(params)? };
    let mut line = serde_json::to_vec(&request)?;
    line.push(b'\n');
    if stream.write_all(&line).is_err() {
        return Ok(Hello::Closed);
    }
    let Some(reply) = reply_line(stream) else { return Ok(Hello::Closed) };
    let response: Response = serde_json::from_slice(&reply).context("bad hello reply from devsandbox serve")?;
    if let Some(e) = response.error {
        bail!("devsandbox serve refused hello: {} ({})", e.message, e.code);
    }
    let result: HelloResult = serde_json::from_value(response.result.unwrap_or(Value::Null))
        .context("bad hello result from devsandbox serve")?;
    Ok(if result.handoff { Hello::Handoff } else { Hello::Ready(result) })
}

/// The hello's reply line from `r`, byte by byte, without its newline;
/// `None` at EOF, a timeout, any other read error or past `MAX_LINE`. An
/// `EINTR` is read again, not the connection's end: a socket read with a
/// timeout fails with it even under `SA_RESTART` (signal(7)) when a
/// handler runs (the CLI's SIGINT/SIGTERM catch, the TUI's SIGWINCH) or
/// the process is stopped and continued.
fn reply_line(r: &mut impl Read) -> Option<Vec<u8>> {
    let mut reply = Vec::new();
    let mut byte = [0u8; 1];
    loop {
        match r.read(&mut byte) {
            Ok(1) if byte[0] == b'\n' => return Some(reply),
            Ok(1) if (reply.len() as u64) < proto::MAX_LINE => reply.push(byte[0]),
            Err(e) if e.kind() == ErrorKind::Interrupted => {}
            _ => return None,
        }
    }
}

/// Start `devsandbox serve --socket-dir <dir>` detached: its own session
/// (`setsid`, so the terminal's hangup and Ctrl-C don't reach it), cwd `/`
/// (pins no directory), stdin from /dev/null, stdout+stderr appended to
/// `serve.log`, and no other fd ([`cloexec_above_stdio`]).
pub(super) fn spawn_detached(dir: &Path) -> Result<()> {
    let exe = crate::exe::devsandbox().context("cannot locate the devsandbox binary")?;
    let log_path = endpoint::log_path()?;
    if let Some(parent) = log_path.parent() {
        endpoint::ensure_private_dir(parent)?;
    }
    let log = std::fs::File::options()
        .create(true)
        .append(true)
        .open(&log_path)
        .with_context(|| format!("cannot open {}", log_path.display()))?;
    let mut cmd = Command::new(exe);
    cmd.arg("serve")
        .arg("--socket-dir")
        .arg(dir)
        .current_dir("/")
        .stdin(Stdio::null())
        .stdout(log.try_clone().context("cannot clone the log handle")?)
        .stderr(log);
    // sysconf isn't async-signal-safe: read before the fork.
    let max_fd = match unsafe { libc::sysconf(libc::_SC_OPEN_MAX) } {
        n if n > 0 => n.min(1 << 20) as libc::c_int,
        _ => 1024,
    };
    // SAFETY: setsid, close_range and fcntl are async-signal-safe and
    // allocate nothing; nothing else runs between fork and exec.
    unsafe {
        cmd.pre_exec(move || {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            cloexec_above_stdio(max_fd);
            Ok(())
        });
    }
    let mut child = cmd.spawn().context("cannot start devsandbox serve")?;
    // Reap it if it exits while this process lives on (a TUI), so it
    // doesn't linger as a zombie.
    std::thread::spawn(move || {
        let _ = child.wait();
    });
    Ok(())
}

/// Mark every fd above stdio close-on-exec, in the forked child. The daemon
/// outlives the CLI that starts it, and an fd that CLI inherited without
/// CLOEXEC (a shell's `exec 7>&1`, a harness's extra pipe) would otherwise
/// hold its caller's pipe open: the pipeline never ends. CLOEXEC rather than
/// close, as std's exec-error pipe must stay open up to the exec. The loop up
/// to `max_fd` is for kernels or seccomp profiles without `close_range`, and
/// macOS.
fn cloexec_above_stdio(max_fd: libc::c_int) {
    #[cfg(target_os = "linux")]
    // SAFETY: a raw syscall over plain integers.
    if unsafe { libc::syscall(libc::SYS_close_range, 3u32, u32::MAX, libc::CLOSE_RANGE_CLOEXEC) } == 0 {
        return;
    }
    for fd in 3..max_fd {
        // SAFETY: fcntl on a closed fd fails with EBADF, ignored.
        unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
    }
}

/// Append one line to `serve.log`, formatted like the daemon's own. For the
/// client side of a start, which must never print (the TUI calls it). Best
/// effort.
pub(super) fn log_line(msg: &str) {
    let Ok(path) = endpoint::log_path() else { return };
    if let Some(parent) = path.parent()
        && endpoint::ensure_private_dir(parent).is_err()
    {
        return;
    }
    let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
    if let Ok(mut f) = std::fs::File::options().create(true).append(true).open(&path) {
        let _ = writeln!(f, "[{secs}] devsandbox serve: {msg}");
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use crate::serve::daemon::Exit;
    use crate::serve::daemon::tests::{opts, scratch, spawn_daemon};

    type Daemons = Mutex<Vec<std::thread::JoinHandle<Result<Exit>>>>;

    fn v(build: u64) -> Version {
        Version { semver: "0.6.0".into(), build }
    }

    /// A spawner that runs an in-process daemon of `build`, counting calls.
    fn fake_spawn<'a>(
        build: u64,
        count: &'a AtomicUsize,
        daemons: &'a Daemons,
    ) -> impl Fn(&Path, StartReason) -> Result<()> + 'a {
        move |dir, _| {
            count.fetch_add(1, Ordering::SeqCst);
            daemons.lock().unwrap().push(spawn_daemon(dir, opts(build, 200)));
            Ok(())
        }
    }

    fn join_all(daemons: Daemons) -> Vec<Exit> {
        daemons.into_inner().unwrap().into_iter().map(|d| d.join().unwrap().unwrap()).collect()
    }

    #[test]
    fn a_detached_child_inherits_no_fd_above_stdio() {
        // `dup` leaves the copy without CLOEXEC, as a shell's `exec 7>&1` does.
        let file = std::fs::File::open("/dev/null").unwrap();
        let fd = unsafe { libc::dup(std::os::fd::AsRawFd::as_raw_fd(&file)) };
        assert!(fd > 2);
        let probe = |cloexec: bool| {
            let mut cmd = Command::new("sh");
            cmd.arg("-c").arg(format!("[ -e /dev/fd/{fd} ]"));
            if cloexec {
                unsafe {
                    cmd.pre_exec(|| {
                        cloexec_above_stdio(1024);
                        Ok(())
                    });
                }
            }
            cmd.status().unwrap().success()
        };
        assert!(probe(false), "the plain child sees fd {fd}");
        assert!(!probe(true), "fd {fd} leaked");
        unsafe { libc::close(fd) };
    }

    /// Its bytes, one `EINTR` before each.
    struct Interrupting(std::collections::VecDeque<u8>, bool);

    impl Read for Interrupting {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            self.1 = !self.1;
            if self.1 {
                return Err(ErrorKind::Interrupted.into());
            }
            Ok(self.0.pop_front().map(|b| buf[0] = b).map_or(0, |()| 1))
        }
    }

    #[test]
    fn a_hello_reply_read_is_retried_after_eintr() {
        let mut r = Interrupting(b"{\"id\":0}\nrest".iter().copied().collect(), false);
        assert_eq!(reply_line(&mut r).as_deref(), Some(&b"{\"id\":0}"[..]));
        assert_eq!(r.0, b"rest", "nothing past the newline read");
        assert_eq!(reply_line(&mut Interrupting(b"{".iter().copied().collect(), false)), None, "EOF first");
    }

    #[test]
    fn lazy_start_spawns_once_and_connects() {
        let dir = scratch("lazy");
        let (count, daemons) = (AtomicUsize::new(0), Daemons::default());
        let mut conn = connect_with(&dir, "test", &v(1), START_TIMEOUT, &fake_spawn(1, &count, &daemons)).unwrap();
        assert_eq!(count.load(Ordering::SeqCst), 1);
        assert_eq!(conn.daemon, HelloResult { version: "0.6.0".into(), build: 1, protocol: proto::PROTOCOL, handoff: false });
        let r = conn.call("nope", Value::Null).unwrap();
        assert_eq!(r.error.unwrap().code, "unknown-method");

        let second = connect_with(&dir, "test", &v(1), START_TIMEOUT, &fake_spawn(1, &count, &daemons)).unwrap();
        assert_eq!(count.load(Ordering::SeqCst), 1);
        drop((conn, second));
        assert_eq!(join_all(daemons), [Exit::Idle]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn lazy_start_gives_up_when_the_daemon_never_answers() {
        let dir = scratch("never");
        let count = AtomicUsize::new(0);
        let spawn = |_: &Path, reason| {
            assert_eq!(reason, StartReason::NothingAnswering);
            count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        };
        let started = Instant::now();
        let err = connect_with(&dir, "test", &v(1), Duration::from_millis(300), &spawn).err().unwrap();
        assert!(format!("{err:#}").contains("did not answer"), "{err:#}");
        assert!(started.elapsed() >= Duration::from_millis(300));
        assert_eq!(count.load(Ordering::SeqCst), 1, "spawned more than once");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn waited_ensure_results_parse() {
        use crate::devsbd::bridge::Readiness;
        assert_eq!(readiness(&serde_json::json!({"ok": true})), None, "older daemon");
        assert_eq!(
            readiness(&serde_json::json!({"ok": true, "ready": true, "error": null})),
            Some(Readiness { ready: true, error: None })
        );
        assert_eq!(
            readiness(&serde_json::json!({"ok": true, "ready": false, "error": "outdated"})),
            Some(Readiness { ready: false, error: Some("outdated".into()) })
        );
    }

    #[test]
    fn in_daemon_bridge_request_never_starts_a_daemon() {
        // Nothing answering is what a draining daemon looks like from inside.
        let dir = scratch("bridge-running");
        let r = ensure_bridge_running(&dir, "web", None, Some(Duration::from_secs(1))).unwrap();
        assert!(r.is_none());
        assert!(endpoint::connect(&dir).is_err(), "a daemon was started");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn call_within_gives_up_and_keeps_notifications() {
        use std::os::unix::net::UnixStream;
        let (ours, theirs) = UnixStream::pair().unwrap();
        let daemon = HelloResult { version: "0.6.0".into(), build: 1, protocol: proto::PROTOCOL, handoff: false };
        let mut conn = Conn::new(ours, daemon).unwrap();
        let peer = std::thread::spawn(move || {
            let mut r = BufReader::new(theirs.try_clone().unwrap());
            let mut line = String::new();
            r.read_line(&mut line).unwrap();
            // A notification, then half a response, never finished.
            (&theirs).write_all(b"{\"method\":\"instances.changed\",\"params\":{}}\n{\"id\":1,").unwrap();
            line.clear();
            r.read_line(&mut line).unwrap();
            (&theirs).write_all(b"\"result\":1}\n{\"id\":2,\"result\":2}\n").unwrap();
            theirs
        });
        let started = Instant::now();
        assert!(conn.call_within("a", Value::Null, Duration::from_millis(200)).unwrap().is_none());
        assert!(started.elapsed() >= Duration::from_millis(200));
        assert_eq!(conn.next_notification(Duration::ZERO).unwrap().unwrap().method, "instances.changed");
        // The late answer is out of turn: the caller drops the connection.
        let err = conn.call_within("b", Value::Null, Duration::from_secs(3)).unwrap_err();
        assert!(format!("{err:#}").contains("answered request Some(1), expected 2"), "{err:#}");
        drop(peer.join().unwrap());
    }

    #[test]
    fn spawn_failure_is_reported() {
        let dir = scratch("spawnfail");
        let err = connect_with(&dir, "test", &v(1), START_TIMEOUT, &|_, _| bail!("no exe")).err().unwrap();
        assert_eq!(format!("{err:#}"), "no exe");
    }

    #[test]
    fn newer_client_hands_off_and_reaches_its_own_daemon() {
        let dir = scratch("cl-handoff");
        let old = spawn_daemon(&dir, opts(1, 60_000));
        while endpoint::connect(&dir).is_err() {
            std::thread::sleep(POLL);
        }
        let (count, daemons) = (AtomicUsize::new(0), Daemons::default());
        // Older/equal clients use the old daemon as is.
        let equal = connect_with(&dir, "old", &v(1), START_TIMEOUT, &fake_spawn(1, &count, &daemons)).unwrap();
        assert_eq!((equal.daemon.build, count.load(Ordering::SeqCst)), (1, 0));
        drop(equal);

        let reasons = Mutex::new(Vec::new());
        let spawn = |d: &Path, reason| {
            reasons.lock().unwrap().push(reason);
            fake_spawn(2, &count, &daemons)(d, reason)
        };
        let conn = connect_with(&dir, "new", &v(2), START_TIMEOUT, &spawn).unwrap();
        assert_eq!(*reasons.lock().unwrap(), [StartReason::Handoff]);
        assert_eq!(conn.daemon.build, 2);
        assert_eq!(count.load(Ordering::SeqCst), 1);
        assert_eq!(old.join().unwrap().unwrap(), Exit::Handoff);
        drop(conn);
        assert_eq!(join_all(daemons), [Exit::Idle]);
        let _ = std::fs::remove_dir_all(&dir);
    }
}