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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
//! `devsandbox fleet-link --peer <dialer>` (hidden)
//! (docs/architecture/daemon/fleet.md, *Peer links*): the dialed end of a
//! link `machine add <this host>` made on `<dialer>` ([`fleet_link_peer`],
//! [`run_peer`]). The opener (it writes the sentinel), saying
//! `update::hello_of` (its build, whether this host is the control plane, and its
//! fleet's control plane, as `member.toml` says when it starts); a dialer naming
//! another control plane is refused (`update::same_fleet`). IN:
//! each stream the dialer opens on `API`, `PTY`, `TUNNEL`, `TRANSFER`,
//! `AGENT` (answered by this host's agent grant for the key the dialer
//! proved, `fleet::agent`) or `ROUTE` (a routed stream to relay or answer,
//! `fleet::route`) is handed to this host's daemon as a connection whose
//! first line is `link.attach {peer: <dialer>, channel, key, introduced_by}`
//! ([`attach_stream`]: the key and introducer the dialer proved), so this
//! host's trust table for the dialer applies to every one. Right after the `Hello`s both
//! ends prove their member keys (`fleet::proof`; this host's identity read
//! once, at the start: no key or log, no link): the dialer must prove the
//! key `<dialer>` has in the membership log (or a held introduction), and
//! when this host's log is behind, the dialer's newer entries are stored
//! through this host's daemon (`membership.adopt`) before anything is
//! announced, the link ending if they moved the control plane. OUT: `fleet-<dialer>.sock` and
//! its `.pty`, `.tunnel`, `.transfer` siblings, each accept a stream to the
//! dialer; `agent-link-<dialer>.sock` (`endpoint::link_agent_socket`,
//! `fleet::agent::serve`) while the dialer serves `AGENT`. Once the
//! `Hello`s are through it announces the dialer as an inbound neighbor
//! (`links.inbound`, a refusal ends the link with why) and holds that
//! connection for the link's life, re-announcing on a new one when it drops
//! (a version handoff of this host's daemon) ([`Announce`]); a
//! `links.cycle` notification on it (this host's control plane changed) ends the
//! link, so the dialer redials and both ends say the new control plane. Versions
//! follow the fleet's pinned build (`update::decide` over the newest log's
//! `Membership::build` and [`Authority`]): this end, not the authority and
//! not on the pin, downloads it or receives it from a dialer that has it,
//! then ends the link (the dialer redials the new binary); this end, having
//! the pin, pushes it to a dialer that would take it ([`push_build`]); this
//! end behind (it can't or won't take the pin) links anyway, saying why on
//! stderr; the announce says who is behind on the link, this end and the
//! dialer (`update::Behind`), for `machine ls` and the dashboard there.

use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

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

use crate::devsbd::mux;
use crate::devsbd::proto::{caps, channel};
use crate::serve::client::{self, Conn};
use crate::serve::endpoint;
use crate::serve::fleet::follow::{Incoming, PUSH_WAIT};
use crate::serve::fleet::lent::Channel;
use crate::serve::fleet::transfer::Receivers;
use crate::serve::fleet::update::Decision;
use crate::serve::fleet::follow::Follow;
use crate::serve::fleet::identity::PublicKey;
use crate::serve::fleet::membership::{Pin, Stored};
use crate::serve::fleet::{self, agent, link, update};
use crate::serve::machines::check_name;

/// This process's own binary: on Linux `/proc/self/exe`, the inode it runs
/// even when the path was replaced since; elsewhere `current_exe()`. The
/// member checks what it got reports this link's `Hello` anyway.
pub(crate) fn own_binary() -> io::Result<std::path::PathBuf> {
    #[cfg(target_os = "linux")]
    return Ok("/proc/self/exe".into());
    #[cfg(not(target_os = "linux"))]
    std::env::current_exe()
}

/// When this end, saying `ours`, pushes the fleet's dev `pin` to the peer
/// saying `theirs` (`update::pushes`, over both `Hello`s and `authority`):
/// the binary it names (its own, or the authority's kept copy under
/// `builds`, `update::builds_dir`) sent on a thread of its own through
/// the link's socket `socket` (`update::push`; its connection waits in the
/// backlog until the far end's accept loop runs). Either end of a link
/// pushes, whichever dialed. A failure is on stderr; the peer's wait ends
/// on its own.
pub fn push_build(
    pin: Option<&Pin>,
    ours: &str,
    theirs: &str,
    authority: Authority,
    socket: PathBuf,
    builds: &Path,
) -> Option<std::thread::JoinHandle<Result<()>>> {
    let source = update::pushes(pin, ours, theirs, authority)?;
    let builds = builds.to_path_buf();
    let pushed = std::thread::Builder::new().name("fleet-push".into()).spawn(move || {
        let pushed = source.path(&builds).context("cannot locate the fleet's build").and_then(|b| update::push(&socket, &b));
        if let Err(e) = &pushed {
            eprintln!("fleet-link: cannot send the fleet's build to the peer: {e:#}");
        }
        pushed
    });
    pushed.ok()
}

/// The first wait before re-announcing a dropped `links.inbound`, doubled
/// up to [`REANNOUNCE_MAX`].
pub const REANNOUNCE: Duration = Duration::from_millis(100);
const REANNOUNCE_MAX: Duration = Duration::from_secs(5);

/// How long [`attach_stream`] waits for `link.attach`'s answer.
const ATTACH_TIMEOUT: Duration = Duration::from_secs(10);

/// What a peer link's dialed end needs besides its stdio ([`run_peer`]).
pub struct PeerOptions {
    /// The socket dir: this host's daemon socket, and where the link's
    /// sockets are bound.
    pub dir: PathBuf,
    /// What this end says (`update::hello_of`): its role and its fleet's
    /// control plane, as `member.toml` said when this process started.
    pub hello: &'static str,
    /// A fresh connection to this host's daemon (lazy start), for
    /// `links.inbound`.
    pub daemon: Arc<dyn Fn() -> Result<Conn> + Send + Sync>,
    /// How this end follows the fleet's pinned build.
    pub follow: Follow,
    /// The re-announce backoff's first wait ([`REANNOUNCE`]).
    pub reannounce: Duration,
    /// How long a wait for the pinned binary waits ([`PUSH_WAIT`]).
    pub push_wait: Duration,
    /// This host's `member.toml`: its name, and the `member.key` and
    /// `membership.json` next to it the link proves with
    /// (`fleet::proof::Identity`).
    pub member: PathBuf,
}

/// The `--peer` CLI entry: the socket dir (created 0700 if missing), this
/// end's hello from `member.toml`'s `control_plane` and name (each dial is a process
/// of its own: read once), then [`run_peer`] on stdin/stdout. Following the
/// pin uses the release steps (`update::Release`), `member.toml`'s
/// `dev-builds` / trust `full`, read at the `Hello`s, and the kept builds
/// next to it (`update::builds_dir`).
pub fn fleet_link_peer(peer: &str) -> Result<()> {
    check_name(peer)?;
    let dir = endpoint::socket_dir()?;
    endpoint::ensure_private_dir(&dir)?;
    let member = fleet::member::path()?;
    let this = fleet::member::load(&member)?.unwrap_or_default();
    let own = this.name_or(&crate::serve::machines::link::hostname()).ok();
    let daemon_dir = dir.clone();
    let opts = PeerOptions {
        dir: dir.clone(),
        hello: update::hello_for(&this.control_plane(), own.as_deref(), this.takes_dev_builds()),
        daemon: Arc::new(move || client::connect(&daemon_dir, "fleet-link").context("cannot reach this host's devsandbox serve")),
        follow: Follow {
            steps: Arc::new(update::Release { socket_dir: dir }),
            dev_builds: {
                let member = member.clone();
                Arc::new(move || fleet::member::load(&member).ok().flatten().is_some_and(|m| m.takes_dev_builds()))
            },
            builds: update::builds_dir(member.parent().unwrap_or(Path::new("."))),
        },
        reannounce: REANNOUNCE,
        push_wait: PUSH_WAIT,
        member: member.clone(),
    };
    run_peer(io::stdin(), io::stdout(), peer, opts)
}

/// Which ends of a peer link are the fleet's authority, the member whose key
/// signs the membership log (`Membership::is_authority`; pure). `log` is the
/// newest log this end holds once the key proof is through (the peer's
/// `Proven::newer` when it carried newer entries, else this end's stored
/// one), `ours` this end's keys (`proof::Identity::public_keys`: a pending
/// rotation's next key too, which the log names once the rotation is in),
/// `theirs` the key the peer proved. Neither, in no fleet's log.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Authority {
    pub ours: bool,
    pub theirs: bool,
}

impl Authority {
    pub fn of(log: &Stored, ours: &[PublicKey], theirs: &PublicKey) -> Authority {
        let Some(m) = log.log.membership() else {
            return Authority::default();
        };
        Authority { ours: ours.iter().any(|k| m.is_authority(k)), theirs: m.is_authority(theirs) }
    }
}

/// The fleet's pinned build in `log` (`Membership::build`, the latest
/// `Op::Build`); `None` in no fleet's log or before the first pin.
pub fn pinned(log: &Stored) -> Option<Pin> {
    log.log.membership()?.build.as_ref().map(|(_, pin)| pin.clone())
}

/// The dialed end of a peer link with `peer` (its dialer) over
/// `reader`/`writer` (see the module doc). `Ok` when the dialer went away;
/// an error when `links.inbound` was refused, the link failed, or this end
/// followed the pin (the update's outcome: handed off, or why not). Either
/// way the link has ended, so the dialer redials.
pub fn run_peer(reader: impl Read + Send + 'static, writer: impl Write + Send + 'static, peer: &str, opts: PeerOptions) -> Result<()> {
    check_name(peer)?;
    let identity = fleet::proof::Identity::load(&opts.member, &crate::serve::machines::link::hostname())?;
    let (stored, own_keys) = (identity.stored.clone(), identity.public_keys());
    let dir = opts.dir.clone();
    let socket = endpoint::fleet_socket(&dir, peer);
    // While the pinned binary is on its way nothing but it is served.
    let receiving = Arc::new(AtomicBool::new(false));
    let incoming = Arc::new(Incoming::default());
    let binary = Arc::new(incoming.receiver(Receivers::new(|m| eprintln!("{m}"))));
    // Who the dialer proved it is, set once the `Hello`s and the proof are
    // through (before any stream is served).
    let proven: Arc<OnceLock<fleet::proof::Proven>> = Arc::default();
    let attached = |ch: Channel| {
        let (dir, proven, receiving) = (dir.clone(), Arc::clone(&proven), Arc::clone(&receiving));
        move || if receiving.load(Ordering::Relaxed) { None } else { attach_stream(&dir, ch, proven.get()?) }
    };
    let transfers = {
        let (attach, receiving) = (attached(Channel::Transfer), Arc::clone(&receiving));
        move || if receiving.load(Ordering::Relaxed) { binary.accept() } else { attach() }
    };
    let serves = link::Serves::default()
        .with(channel::API, attached(Channel::Api))
        .with(channel::PTY, attached(Channel::Pty))
        .with(channel::TUNNEL, attached(Channel::Tunnel))
        .with(channel::AGENT, attached(Channel::Agent))
        .with(channel::ROUTE, attached(Channel::Route))
        .with(channel::TRANSFER, transfers);
    let outlet = Arc::new(link::Outlet::default());
    let over = Arc::new(AtomicBool::new(false));
    let spec = link::Spec { hello: opts.hello, ..fleet::LINK };
    let refused: Arc<Mutex<Option<String>>> = Arc::default();
    let mut wanted: Option<(String, [u8; 32])> = None;
    // This host's update lock, from the decision to the handoff.
    let mut update_lock = None;
    let mut held = None;
    let mut agent_thread = None;
    let auth = fleet::proof::Auth { identity, expect: peer.to_string(), log: |m| eprintln!("fleet-link: {m}") };
    let endpoint = link::Endpoint { socket: Some(&socket), serves, outlet: Some(&outlet), auth: Some(auth) };
    let end = link::opener_with(&spec, reader, writer, endpoint, |theirs| {
        let Some(p) = &theirs.proven else {
            bail!("{peer} proved no member key");
        };
        let _ = proven.set(fleet::proof::Proven { newer: None, ..p.clone() });
        if let Some(newer) = theirs.proven.as_ref().and_then(|p| p.newer.as_ref()) {
            adopt(&mut (opts.daemon)()?, newer).with_context(|| format!("cannot take {peer}'s newer membership entries"))?;
            eprintln!("fleet-link: took {peer}'s newer membership log ({})", newer.log.head());
            if let Some(why) = fleet::proof::control_plane_moved(spec.hello, newer) {
                bail!("{why}");
            }
        }
        update::same_fleet(peer, spec.hello, &theirs.hash).map_err(|why| anyhow!("{why}"))?;
        let log = p.newer.as_ref().unwrap_or(&stored);
        let authority = Authority::of(log, &own_keys, &p.key);
        let pin = pinned(log);
        let decision = update::decide(spec.hello, (opts.follow.dev_builds)(), authority, pin.as_ref(), &theirs.hash);
        let behind = update::Behind {
            here: decision.behind().map(str::to_string),
            peer: update::peer_behind(pin.as_ref(), spec.hello, &theirs.hash, authority),
        };
        let (decision, lock, busy) = update::under_lock(decision, &dir);
        if let Some(why) = busy {
            eprintln!("fleet-link: {why}");
        }
        update_lock = lock;
        match (decision, &pin) {
            (Decision::Same, _) => {}
            (Decision::Behind(why), _) => eprintln!("fleet-link: behind: {why}"),
            (Decision::Download { semver, sums_sha256 }, _) => {
                wanted = Some((semver.clone(), sums_sha256));
                bail!("the fleet's build is devsandbox {semver}: updating this one first");
            }
            (Decision::Receive, Some(pin)) => {
                let scratch = update::scratch_dir(&std::env::temp_dir()).context("cannot take the fleet's build")?;
                receiving.store(true, Ordering::Relaxed);
                let hang_up = Arc::clone(&outlet);
                let seq = incoming.expect(pin.clone(), scratch, Some(Box::new(move || hang_up.hang_up())));
                incoming.watch(seq, opts.push_wait);
                eprintln!("fleet-link: the fleet's build is {pin}: receiving it from {peer}");
                return Ok(());
            }
            (Decision::Receive, None) => unreachable!("`decide` receives only a pin"),
        }
        let params = inbound_params(peer, &theirs.hash, &behind);
        let mut conn = (opts.daemon)()?;
        if let Err(why) = announce(&mut conn, &params)? {
            bail!("refused: {why}");
        }
        let on_end = {
            let (refused, outlet, peer) = (Arc::clone(&refused), Arc::clone(&outlet), peer.to_string());
            move |end: AnnounceEnd| {
                let why = match end {
                    AnnounceEnd::Refused(why) => format!("refused: {why}"),
                    AnnounceEnd::Cycled(Some(why)) => why,
                    AnnounceEnd::Cycled(None) => format!("this host's control plane changed: the link ends so {peer} redials it"),
                };
                eprintln!("fleet-link: {why}");
                *refused.lock().unwrap() = Some(why);
                outlet.hang_up();
            }
        };
        held = Some(Announce::hold(conn, params, Arc::clone(&opts.daemon), opts.reannounce, on_end));
        if theirs.caps & caps::AGENT != 0 {
            let (path, outlet, over) = (endpoint::link_agent_socket(&dir, peer), Arc::clone(&outlet), Arc::clone(&over));
            agent_thread = std::thread::Builder::new()
                .name("fleet-link-agent".into())
                .spawn(move || {
                    if let Err(e) = agent::serve(&path, &*outlet, &over, agent::PROBE) {
                        eprintln!("fleet-link: {e:#}");
                    }
                })
                .ok();
        }
        push_build(pin.as_ref(), spec.hello, &theirs.hash, authority, socket.clone(), &opts.follow.builds);
        Ok(())
    });
    over.store(true, Ordering::Relaxed);
    drop(held);
    if let Some(t) = agent_thread {
        let _ = t.join();
    }
    let steps = opts.follow.steps.as_ref();
    if let Some(want) = incoming.take() {
        let label = want.pin.to_string();
        let installed = match &want.received {
            Some(binary) => update::install_received(steps, binary, &want.pin),
            None => Err(anyhow!("{}", want.why.as_deref().unwrap_or("the link ended before the fleet's build arrived"))),
        };
        let _ = std::fs::remove_dir_all(&want.dir);
        installed.with_context(|| format!("update to {label} failed"))?;
        bail!("updated to devsandbox {label}, handing off: the link ends so {peer} redials it");
    }
    if let Some((version, sums_sha256)) = wanted {
        let (os, arch) = (std::env::consts::OS, std::env::consts::ARCH);
        update::update(steps, &version, &sums_sha256, os, arch, &std::env::temp_dir()).with_context(|| format!("update to {version} failed"))?;
        bail!("updated to devsandbox {version}, handing off: the link ends so {peer} redials it");
    }
    drop(update_lock);
    if let Some(why) = refused.lock().unwrap().take() {
        bail!("{why}");
    }
    end
}

/// `links.inbound`'s params for the link to `peer`, whose `Hello` is
/// `theirs`: who it is, and who is behind the fleet's pin on it
/// (`behind_here` this host, `behind` the peer; `null` when not).
fn inbound_params(peer: &str, theirs: &str, behind: &update::Behind) -> Value {
    json!({
        "peer": peer,
        "version": theirs,
        "control_plane": update::is_control_plane(theirs),
        "behind_here": behind.here,
        "behind": behind.peer,
    })
}

/// `membership.adopt` of `newer` on `conn` (this host's daemon writes the
/// log, and `control_plane` from it).
fn adopt(conn: &mut Conn, newer: &fleet::membership::Stored) -> Result<()> {
    let r = conn.call("membership.adopt", serde_json::to_value(newer.to_wire())?)?;
    match r.error {
        Some(e) => bail!("{}", e.message),
        None => Ok(()),
    }
}

/// The notification on the held `links.inbound` connection that ends the
/// link: `daemon::Shared::set_control_plane` (this host's control plane changed, so both ends
/// redial saying the new one), or `daemon::Shared::end_inbound` (the peer
/// is out of this host's fleet; params `{why}`).
pub const LINKS_CYCLE: &str = "links.cycle";

/// Why [`Announce`]'s hold ends the link.
#[derive(Debug, PartialEq, Eq)]
pub enum AnnounceEnd {
    /// A re-announce was refused, with why.
    Refused(String),
    /// The daemon sent [`LINKS_CYCLE`], with its `why` when it gave one.
    Cycled(Option<String>),
}

/// `links.inbound` with `params` on `conn`: `Ok(Err(why))` when the daemon
/// refused it (a name clash), `Err` when the call failed.
fn announce(conn: &mut Conn, params: &Value) -> Result<Result<(), String>> {
    let r = conn.call("links.inbound", params.clone())?;
    Ok(match r.error {
        Some(e) => Err(e.message),
        None => Ok(()),
    })
}

/// The held `links.inbound` connection: while the link is up, a thread waits
/// for it to drop (the daemon handed off or restarted) and then announces
/// again on a new one, backing off from the first wait to
/// [`REANNOUNCE_MAX`] while the daemon can't be reached. A refusal then, or
/// a [`LINKS_CYCLE`] notification on it, goes to `on_end` (which ends the
/// link) and the thread ends. Dropping it stops the thread and closes the
/// connection.
pub struct Announce {
    stop: Arc<AtomicBool>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl Announce {
    fn hold(
        conn: Conn,
        params: Value,
        daemon: Arc<dyn Fn() -> Result<Conn> + Send + Sync>,
        first_wait: Duration,
        on_end: impl FnOnce(AnnounceEnd) + Send + 'static,
    ) -> Announce {
        let stop = Arc::new(AtomicBool::new(false));
        let stopping = Arc::clone(&stop);
        let thread = std::thread::Builder::new()
            .name("fleet-link-announce".into())
            .spawn(move || {
                let mut conn = conn;
                loop {
                    // Only `links.cycle` means something on it; an error is the drop.
                    while !stopping.load(Ordering::Relaxed) {
                        match conn.next_notification(Duration::from_millis(100)) {
                            Ok(Some(n)) if n.method == LINKS_CYCLE => {
                                let why = n.params.get("why").and_then(Value::as_str).map(str::to_string);
                                return on_end(AnnounceEnd::Cycled(why));
                            }
                            Ok(_) => {}
                            Err(_) => break,
                        }
                    }
                    let mut wait = first_wait;
                    conn = loop {
                        if !sleep_unless(&stopping, wait) {
                            return;
                        }
                        wait = (wait * 2).min(REANNOUNCE_MAX);
                        match daemon().and_then(|mut c| Ok((announce(&mut c, &params)?, c))) {
                            Ok((Ok(()), c)) => break c,
                            Ok((Err(why), _)) => return on_end(AnnounceEnd::Refused(why)),
                            Err(e) => eprintln!("fleet-link: cannot announce the link again yet: {e:#}"),
                        }
                    };
                }
            })
            .ok();
        Announce { stop, thread }
    }
}

impl Drop for Announce {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }
}

/// Sleep `d` in short steps; `false` once `stop` is set.
fn sleep_unless(stop: &AtomicBool, d: Duration) -> bool {
    let until = Instant::now() + d;
    while Instant::now() < until {
        if stop.load(Ordering::Relaxed) {
            return false;
        }
        std::thread::sleep(until.saturating_duration_since(Instant::now()).min(Duration::from_millis(20)));
    }
    !stop.load(Ordering::Relaxed)
}

/// One stream peer `peer` (who its link proved: name, key, introducer)
/// opens on `channel`, handed to this host's daemon in `dir`: a socket pair
/// whose far end a thread of its own takes (this runs on the link's read
/// thread). The thread connects the daemon, sends `link.attach {peer,
/// channel, key, introduced_by}` as the connection's first line, reads the
/// answer (nothing past it), and splices the stream to the connection (an
/// `API` stream's first byte is the daemon's, fleet plan decision 27). A
/// refused attach closes the stream, with why on stderr. `None` when no
/// pair or thread could be made.
pub fn attach_stream(dir: &Path, channel: Channel, peer: &fleet::proof::Proven) -> Option<mux::Conn> {
    let (ours, theirs) = std::os::unix::net::UnixStream::pair().ok()?;
    let params = attach_params(peer, channel);
    let dir = dir.to_path_buf();
    let spawned = std::thread::Builder::new().name("fleet-link-attach".into()).spawn(move || {
        let daemon = match attach(&dir, params) {
            Ok(daemon) => daemon,
            Err(e) => return eprintln!("fleet-link: cannot hand a {} stream to this host's devsandbox: {e:#}", channel.as_str()),
        };
        link::splice(ours, daemon.into());
    });
    spawned.ok()?;
    Some(theirs.into())
}

/// `link.attach`'s params for a `channel` stream of `peer` (pure).
pub fn attach_params(peer: &fleet::proof::Proven, channel: Channel) -> Value {
    json!({ "peer": peer.name, "channel": channel.as_str(), "key": peer.key, "introduced_by": peer.introduced_by })
}

/// A connection to the daemon in `dir` past `link.attach`'s `ok` (with
/// `params`, [`attach_params`]), its answer read byte by byte so nothing
/// past it is taken.
fn attach(dir: &Path, params: Value) -> Result<endpoint::Stream> {
    let mut stream = endpoint::connect(dir).context("cannot connect")?;
    stream.set_read_timeout(Some(ATTACH_TIMEOUT)).context("cannot set a read timeout")?;
    let line = json!({ "id": 0, "method": "link.attach", "params": params });
    stream.write_all(format!("{line}\n").as_bytes()).context("cannot send link.attach")?;
    let mut answer = Vec::new();
    let mut byte = [0u8; 1];
    loop {
        let n = match stream.read(&mut byte) {
            // A timed read fails with it even under `SA_RESTART`.
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            n => n.context("no link.attach answer")?,
        };
        match n {
            0 => bail!("the daemon closed the connection before answering link.attach"),
            _ if byte[0] == b'\n' => break,
            _ if answer.len() as u64 >= crate::serve::proto::MAX_LINE => bail!("link.attach's answer is too long"),
            _ => answer.push(byte[0]),
        }
    }
    let answer: Value = serde_json::from_slice(&answer).context("bad link.attach answer")?;
    if let Some(e) = answer.get("error").filter(|e| !e.is_null()) {
        bail!("link.attach refused: {}", e.get("message").and_then(Value::as_str).unwrap_or("?"));
    }
    stream.set_read_timeout(None).context("cannot clear the read timeout")?;
    Ok(stream)
}

#[cfg(test)]
mod tests {
    use std::net::Shutdown;
    use std::os::unix::net::UnixStream;
    use std::path::PathBuf;
    use std::time::{Duration, Instant};

    use serde_json::Value;

    use super::*;
    use crate::serve::daemon::tests::{opts, scratch, spawn_daemon};
    use crate::serve::daemon::Exit;
    use crate::serve::fleet::membership_api::test_support;
    use crate::serve::fleet::proof::{Auth, Identity};
    use crate::serve::machines::{self, Entry, ssh};
    use crate::serve::proto::{HelloResult, Version};

    fn wait_for(mut cond: impl FnMut() -> bool, what: &str) {
        let start = Instant::now();
        while !cond() {
            assert!(start.elapsed() < Duration::from_secs(10), "timed out waiting: {what}");
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    /// A raw connection past a 0.0.0 hello (never a handoff), retrying
    /// while the daemon binds.
    fn stream_at(dir: &Path) -> endpoint::Stream {
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            if let Ok(mut stream) = endpoint::connect(dir) {
                match client::hello(&mut stream, &Version { semver: "0.0.0".into(), build: 0 }, "test").unwrap() {
                    client::Hello::Ready(_) => return stream,
                    other => panic!("{other:?}"),
                }
            }
            assert!(Instant::now() < deadline, "daemon never listened");
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    fn conn_at(dir: &Path) -> Conn {
        let reply = HelloResult { version: "0.0.0".into(), build: 0, protocol: 1, handoff: false };
        Conn::new(stream_at(dir), reply).unwrap()
    }

    /// A daemon for a peer link's end in `base/<name>`: its data dir (where
    /// fleet roots go) `base/<name>-data`, its registry there, a state whose
    /// one instance is in its own root `base/<name>-own` (canonical, returned
    /// with the socket dir and the data dir).
    fn peer_daemon(base: &Path, name: &str) -> (PathBuf, PathBuf, PathBuf, crate::serve::daemon::Options) {
        let (dir, data, own) = (base.join(name), base.join(format!("{name}-data")), base.join(format!("{name}-own")));
        std::fs::create_dir_all(&data).unwrap();
        std::fs::create_dir_all(&own).unwrap();
        let own = std::fs::canonicalize(own).unwrap();
        let state = data.join("state.toml");
        std::fs::write(
            &state,
            format!(
                "[instance.w]\ninstance_id = \"id-w\"\nsandbox = \"web\"\ncontainer = \"devsandbox-w\"\nfolder = \"/w\"\n\
                 workspace = \"/w\"\ncreated_unix = 1\nconfig_dir = {:?}\n",
                own.to_str().unwrap()
            ),
        )
        .unwrap();
        let mut o = opts(1, 60_000);
        o.state = Some(state);
        o.member = Some(data.join("member.toml"));
        o.machines = Some(data.join("machines.toml"));
        o.home = Some(base.join(format!("{name}-home")));
        (dir, std::fs::canonicalize(&data).unwrap(), own, o)
    }

    /// A handler whose every stream gets `tag` written, then closed.
    fn tagged(tag: &'static [u8]) -> impl Fn() -> Option<crate::devsbd::mux::Conn> + Send + Sync + 'static {
        move || {
            let (mut ours, theirs) = UnixStream::pair().ok()?;
            std::thread::spawn(move || {
                let _ = ours.write_all(tag);
            });
            Some(theirs.into())
        }
    }

    /// K (`k_member`, its `member.toml`) and L (`l_member`) in one fleet,
    /// K its authority and control plane; the fleet's log and L's identity (the fake
    /// dialer's).
    fn fleet(k_member: &Path, l_member: &Path) -> (crate::serve::fleet::membership::Stored, Identity) {
        for m in [k_member, l_member] {
            std::fs::create_dir_all(m.parent().unwrap()).unwrap();
        }
        let stored = test_support::fleet_of("K", &[("K", k_member), ("L", l_member)]);
        (stored, Identity::load(l_member, "L").unwrap())
    }

    /// [`fleet`] in `base/k-id` and `base/l-id`: K's `member.toml` and L's
    /// identity.
    fn ids(base: &Path) -> (PathBuf, Identity) {
        let k = base.join("k-id/member.toml");
        let (_, l) = fleet(&k, &base.join("l-id/member.toml"));
        (k, l)
    }

    /// The dialer's end, faked as 7d's daemon answers it: the answerer of a
    /// peer link saying `hello`, proving `identity` (L's) and expecting `K`,
    /// each `API` stream K opens handed to the daemon in `daemon` as peer
    /// `K`'s (`attach_stream`, the in-process path's stand-in), `PTY`
    /// streams answered `dialer pty`; its outlet `outlet`.
    fn fake_dialer(io: UnixStream, hello: &'static str, identity: Identity, daemon: PathBuf, outlet: Arc<link::Outlet>) -> std::thread::JoinHandle<link::End> {
        let (r, w) = (io.try_clone().unwrap(), io);
        std::thread::spawn(move || {
            let proven: Arc<OnceLock<fleet::proof::Proven>> = Arc::default();
            let k = Arc::clone(&proven);
            let serves = link::Serves::default()
                .with(channel::API, move || attach_stream(&daemon, Channel::Api, k.get()?))
                .with(channel::PTY, tagged(b"dialer pty"));
            let spec = link::Spec { hello, ..fleet::LINK };
            let auth = Auth { identity, expect: "K".into(), log: |_| {} };
            let endpoint = link::Endpoint { serves, outlet: Some(&outlet), auth: Some(auth), ..link::Endpoint::default() };
            let ready = |peer: &link::Ready| {
                let _ = proven.set(peer.proven.clone().ok_or_else(|| "K proved no key".to_string())?);
                Ok(())
            };
            link::answerer_with(&spec, r, w, endpoint, ready, || {})
        })
    }

    /// K's `fleet-link --peer L` over `io`, its daemon and sockets in `dir`,
    /// its `member.toml` `member`, a member; following through `steps` (dev
    /// builds taken).
    fn peer_link(io: UnixStream, dir: PathBuf, member: PathBuf, steps: Arc<dyn update::Steps>) -> std::thread::JoinHandle<Result<()>> {
        peer_link_saying(io, dir, member, steps, update::hello_of(false, None, true))
    }

    /// [`peer_link`], K saying `hello`.
    fn peer_link_saying(
        io: UnixStream,
        dir: PathBuf,
        member: PathBuf,
        steps: Arc<dyn update::Steps>,
        hello: &'static str,
    ) -> std::thread::JoinHandle<Result<()>> {
        let (r, w) = (io.try_clone().unwrap(), io);
        let daemon_dir = dir.clone();
        let opts = PeerOptions {
            dir,
            hello,
            daemon: Arc::new(move || Ok(conn_at(&daemon_dir))),
            follow: Follow { steps, dev_builds: Arc::new(|| true), builds: update::builds_dir(member.parent().unwrap()) },
            reannounce: Duration::from_millis(20),
            push_wait: Duration::from_secs(5),
            member,
        };
        std::thread::spawn(move || run_peer(r, w, "L", opts))
    }

    /// What the dialer proved goes into `link.attach` as the daemon parses
    /// it: name, channel, key, introducer.
    #[test]
    fn an_attach_carries_the_proven_key_and_introducer() {
        use crate::serve::fleet::identity::{Signer, SigningKey};
        use crate::serve::fleet::lent;
        let key = SigningKey::from_seed([3; 32]).public_key();
        let proven = fleet::proof::Proven { name: "pi".into(), key, introduced_by: Some("lap".into()), newer: None };
        let got = lent::attach_params(&attach_params(&proven, Channel::Pty)).unwrap();
        assert_eq!(got, lent::Attach { name: "pi".into(), channel: Channel::Pty, key, introduced_by: Some("lap".into()) });
        let member = fleet::proof::Proven { introduced_by: None, ..proven };
        assert_eq!(lent::attach_params(&attach_params(&member, Channel::Api)).unwrap().introduced_by, None);
    }

    fn machine_rows(dir: &Path) -> Vec<Value> {
        let rows = conn_at(dir).call("machines.list", Value::Null).unwrap().result.unwrap();
        rows.as_array().unwrap().clone()
    }

    fn inbound_row(dir: &Path) -> Option<Value> {
        machine_rows(dir).into_iter().find(|r| r["kind"] == "inbound")
    }

    /// A peer link end to end: K's `fleet-link --peer L` announces L, which
    /// `machines.list` shows with the roots L's daemon answers over the link
    /// (its own root and its fleet root for K); L's `API` streams reach K's
    /// daemon under K's trust table for L; K's local clients reach L's
    /// table through `fleet-L.sock`; the neighbor goes with the link.
    #[test]
    fn a_peer_link_announces_its_dialer_and_hands_its_streams_to_the_daemon() {
        let base = scratch("peer-e2e");
        let (k_dir, k_data, k_own, k_opts) = peer_daemon(&base, "k");
        let (l_dir, l_data, l_own, l_opts) = peer_daemon(&base, "l");
        let k_member = k_opts.member.clone().unwrap();
        let (_, l_id) = fleet(&k_member, l_opts.member.as_ref().unwrap());
        let daemons = [spawn_daemon(&k_dir, k_opts), spawn_daemon(&l_dir, l_opts)];
        drop((conn_at(&k_dir), conn_at(&l_dir)));

        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let outlet = Arc::new(link::Outlet::default());
        let dialer = fake_dialer(dialer_io, update::hello_of(false, None, false), l_id, l_dir.clone(), Arc::clone(&outlet));
        let k_end = peer_link(k_io.try_clone().unwrap(), k_dir.clone(), k_member, Arc::new(update::tests::Fake::default()));
        let l_fleet = l_data.join("fleet/K");
        let want = json!([l_own, l_fleet]);
        // A machine on K: its held link's state and its daemon's semver.
        wait_for(|| inbound_row(&k_dir).is_some_and(|r| r["roots"] == want && r["state"] == "connected"), "L listed with its roots");
        let row = inbound_row(&k_dir).unwrap();
        assert_eq!((&row["name"], &row["target"], &row["state"]), (&json!("L"), &Value::Null, &json!("connected")));
        assert_eq!(row["version"], "0.6.0");
        let socket = endpoint::fleet_socket(&k_dir, "L");
        assert!(socket.exists(), "{}", socket.display());
        assert!(!endpoint::link_agent_socket(&k_dir, "L").exists(), "the dialer serves no AGENT");

        // A registry entry can't take a live neighbor's name.
        let mut k = conn_at(&k_dir);
        let key = crate::serve::fleet::identity::Signer::public_key(&crate::serve::fleet::identity::SigningKey::from_seed([9; 32]));
        let add = json!({"control_plane": false, "target": "me@l", "name": "L", "key": key});
        let e = k.call("machines.add", add).unwrap().error.unwrap();
        assert!(e.code == "denied" && e.message.contains("inbound neighbor"), "{e:?}");

        // L → K: an `API` stream, K's trust table for L (`worker`): its
        // fleet root `fleet/L/` and K's own root, nothing else.
        wait_for(|| outlet.is_up(), "the dialer's outlet is up");
        let crate::devsbd::mux::Conn::Unix(stream) = outlet.open(channel::API).unwrap() else { panic!("a socket pair") };
        let duplex = ssh::Duplex::socket(stream.into());
        let mut api = crate::serve::machines::link::handshake("K", duplex, Duration::from_secs(5), crate::serve::machines::link::Over::Link).unwrap();
        let cfg = k_data.join("fleet/L/cfg");
        std::fs::create_dir_all(&cfg).unwrap();
        let code = |c: &mut Conn, m: &str, p: Value| c.call(m, p).unwrap().error.map(|e| e.code);
        assert_eq!(code(&mut api.conn, "instances.list", json!({"dir": cfg})), None, "under L's fleet root");
        assert_eq!(code(&mut api.conn, "instances.list", json!({"dir": k_own})), None, "K's own root");
        assert_eq!(code(&mut api.conn, "instances.list", json!({"dir": base})), Some("denied".into()));
        assert_eq!(code(&mut api.conn, "member.get", json!({})), Some("denied".into()));
        assert_eq!(code(&mut api.conn, "links.inbound", json!({"peer": "x", "version": "v"})), Some("denied".into()));
        drop(api);

        // K → L: a local client on K reaches the dialer's table.
        let mut got = Vec::new();
        link::connect(&socket, channel::PTY).unwrap().read_to_end(&mut got).unwrap();
        assert_eq!(got, b"dialer pty");

        // The link ends: K's end returns, its socket and the neighbor go.
        k_io.shutdown(Shutdown::Both).unwrap();
        k_end.join().unwrap().unwrap();
        assert!(!endpoint::fleet_socket(&k_dir, "L").exists());
        wait_for(|| inbound_row(&k_dir).is_none(), "L no longer listed");
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        drop(k);
        for (dir, daemon) in [&k_dir, &l_dir].into_iter().zip(daemons) {
            assert!(conn_at(dir).call("shutdown", json!({})).unwrap().error.is_none());
            assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
        }
        let _ = std::fs::remove_dir_all(&base);
    }

    /// A dialer named like a registry entry here is refused: the link ends
    /// with why, nothing listed but the entry.
    #[test]
    fn a_dialer_named_like_a_registry_entry_is_refused() {
        let base = scratch("peer-clash");
        let (k_dir, k_data, _, k_opts) = peer_daemon(&base, "k");
        machines::update(&k_data.join("machines.toml"), |e| e.push(Entry::ssh("L", "me@l"))).unwrap();
        let k_member = k_opts.member.clone().unwrap();
        let (_, l_id) = fleet(&k_member, &base.join("l-id/member.toml"));
        let daemon = spawn_daemon(&k_dir, k_opts);
        drop(conn_at(&k_dir));
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, update::hello_of(false, None, false), l_id, base.join("nowhere"), Arc::default());
        let err = peer_link(k_io, k_dir.clone(), k_member, Arc::new(update::tests::Fake::default())).join().unwrap().unwrap_err();
        assert!(format!("{err:#}").contains("refused: `L` is already a machine here (me@l)"), "{err:#}");
        assert!(!endpoint::fleet_socket(&k_dir, "L").exists());
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        let rows = machine_rows(&k_dir);
        assert_eq!((rows.len(), &rows[0]["kind"]), (1, &json!("ssh")));
        assert!(conn_at(&k_dir).call("shutdown", json!({})).unwrap().error.is_none());
        assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
        let _ = std::fs::remove_dir_all(&base);
    }

    /// K's daemon goes away under a live link (a handoff): the link stays,
    /// and the next daemon learns the neighbor from a new announce.
    #[test]
    fn the_neighbor_is_announced_again_to_the_next_daemon() {
        let base = scratch("peer-again");
        let (k_dir, _, _, k_opts) = peer_daemon(&base, "k");
        let (l_dir, _, _, l_opts) = peer_daemon(&base, "l");
        let again = crate::serve::daemon::Options { machines: k_opts.machines.clone(), state: k_opts.state.clone(), member: k_opts.member.clone(), ..opts(2, 60_000) };
        let k_member = k_opts.member.clone().unwrap();
        let (_, l_id) = fleet(&k_member, l_opts.member.as_ref().unwrap());
        let first = spawn_daemon(&k_dir, k_opts);
        let l_daemon = spawn_daemon(&l_dir, l_opts);
        drop((conn_at(&k_dir), conn_at(&l_dir)));
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, update::hello_of(false, None, false), l_id, l_dir.clone(), Arc::default());
        let k_end = peer_link(k_io.try_clone().unwrap(), k_dir.clone(), k_member, Arc::new(update::tests::Fake::default()));
        wait_for(|| inbound_row(&k_dir).is_some(), "L listed");
        assert!(conn_at(&k_dir).call("shutdown", json!({})).unwrap().error.is_none());
        assert_eq!(first.join().unwrap().unwrap(), Exit::Shutdown);
        let second = spawn_daemon(&k_dir, again);
        wait_for(|| endpoint::connect(&k_dir).is_ok() && inbound_row(&k_dir).is_some(), "L announced again");
        assert!(endpoint::fleet_socket(&k_dir, "L").exists(), "the link stayed up");
        k_io.shutdown(Shutdown::Both).unwrap();
        k_end.join().unwrap().unwrap();
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        for (dir, daemon) in [(&k_dir, second), (&l_dir, l_daemon)] {
            assert!(conn_at(dir).call("shutdown", json!({})).unwrap().error.is_none());
            assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
        }
        let _ = std::fs::remove_dir_all(&base);
    }

    /// K's control plane changes (a newer membership log adopted on K's daemon): K's
    /// end gets `links.cycle` on its held announce and ends the link,
    /// saying why.
    #[test]
    fn a_control_plane_change_on_the_dialed_host_ends_the_link() {
        use crate::serve::fleet::membership::Op;
        let base = scratch("peer-cycle");
        let (k_dir, _, _, k_opts) = peer_daemon(&base, "k");
        let k_member = k_opts.member.clone().unwrap();
        let (l_dir, _, _, l_opts) = peer_daemon(&base, "l");
        let (mut k_fleet, l_id) = fleet(&k_member, l_opts.member.as_ref().unwrap());
        k_fleet.log.append(Op::ControlPlane { name: "L".into() }, "K", &test_support::key_of(&k_member)).unwrap();
        let daemons = [spawn_daemon(&k_dir, k_opts), spawn_daemon(&l_dir, l_opts)];
        drop((conn_at(&k_dir), conn_at(&l_dir)));
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, update::hello_of(false, None, false), l_id, l_dir.clone(), Arc::default());
        let k_end = peer_link(k_io.try_clone().unwrap(), k_dir.clone(), k_member, Arc::new(update::tests::Fake::default()));
        wait_for(|| inbound_row(&k_dir).is_some(), "L listed");
        let adopt = serde_json::to_value(k_fleet.to_wire()).unwrap();
        assert!(conn_at(&k_dir).call("membership.adopt", adopt).unwrap().error.is_none());
        let err = k_end.join().unwrap().unwrap_err();
        assert_eq!(format!("{err:#}"), "this host's control plane changed: the link ends so L redials it");
        // `fleet-link` exits there: its stdio closes.
        k_io.shutdown(Shutdown::Both).unwrap();
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        wait_for(|| inbound_row(&k_dir).is_none(), "L no longer listed");
        for (dir, daemon) in [&k_dir, &l_dir].into_iter().zip(daemons) {
            assert!(conn_at(dir).call("shutdown", json!({})).unwrap().error.is_none());
            assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
        }
        let _ = std::fs::remove_dir_all(&base);
    }

    /// K's membership log is behind the dialer's, whose newer entry makes
    /// `L` the control plane: K's end stores it through its daemon (`membership.adopt`:
    /// K's `member.toml` control plane follows) before announcing anything, then ends
    /// the link so both ends redial saying the new control plane.
    #[test]
    fn the_dialed_end_behind_takes_the_dialers_entries() {
        use crate::serve::fleet::member::{self, ControlPlane};
        use crate::serve::fleet::membership::Op;
        let base = scratch("peer-behind");
        let (k_dir, _, _, k_opts) = peer_daemon(&base, "k");
        let k_member = k_opts.member.clone().unwrap();
        let (mut ahead, mut l_id) = fleet(&k_member, &base.join("l-id/member.toml"));
        ahead.log.append(Op::ControlPlane { name: "L".into() }, "K", &test_support::key_of(&k_member)).unwrap();
        l_id.stored = ahead.clone();
        let daemon = spawn_daemon(&k_dir, k_opts);
        drop(conn_at(&k_dir));
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, update::hello_of(false, None, false), l_id, base.join("nowhere"), Arc::default());
        let err = peer_link(k_io, k_dir.clone(), k_member.clone(), Arc::new(update::tests::Fake::default())).join().unwrap().unwrap_err();
        assert!(format!("{err:#}").contains("the fleet's control plane is now `L`"), "{err:#}");
        assert_eq!(test_support::read(&k_member).unwrap(), ahead, "K took L's entries");
        assert_eq!(member::load(&k_member).unwrap().unwrap().control_plane(), ControlPlane::Other("L".into()));
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        assert!(inbound_row(&k_dir).is_none(), "nothing announced");
        assert!(conn_at(&k_dir).call("shutdown", json!({})).unwrap().error.is_none());
        assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
        let _ = std::fs::remove_dir_all(&base);
    }

    /// A dialer whose key isn't the one K's log has for `L`: refused by the
    /// proof, before anything is announced.
    #[test]
    fn a_dialer_proving_another_key_is_refused() {
        let base = scratch("peer-wrong-key");
        std::fs::create_dir_all(&base).unwrap();
        let (k_member, mut l_id) = ids(&base);
        l_id.key = crate::serve::fleet::identity::SigningKey::from_seed([7; 32]);
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, update::hello_of(false, None, false), l_id, base.join("nowhere"), Arc::default());
        let err = peer_link(k_io, base.clone(), k_member, Arc::new(update::tests::Fake::default())).join().unwrap().unwrap_err();
        assert!(format!("{err:#}").contains("`L` proved key"), "{err:#}");
        assert!(matches!(dialer.join().unwrap(), link::End::Refused(why) if why.contains("`K` refused the link")));
        assert!(!endpoint::fleet_socket(&base, "L").exists());
        let _ = std::fs::remove_dir_all(&base);
    }

    /// A dialer naming another control plane than K's: refused before anything is
    /// announced, naming both.
    #[test]
    fn a_dialer_in_another_fleet_is_refused() {
        let base = scratch("peer-two-fleets");
        std::fs::create_dir_all(&base).unwrap();
        let (k_member, l_id) = ids(&base);
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, update::hello_of(true, Some("lap"), false), l_id, base.join("nowhere"), Arc::default());
        let k_end = peer_link_saying(k_io.try_clone().unwrap(), base.clone(), k_member, Arc::new(update::tests::Fake::default()), update::hello_of(false, Some("box"), false));
        let err = k_end.join().unwrap().unwrap_err();
        assert!(format!("{err:#}").contains("`L` is in `lap`'s fleet, this host in `box`'s"), "{err:#}");
        k_io.shutdown(Shutdown::Both).unwrap();
        let _ = dialer.join().unwrap();
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn the_authority_is_whoever_the_newest_log_names() {
        use crate::serve::fleet::identity::{Signer, SigningKey};
        let (a, c, m) = (SigningKey::from_seed([1; 32]), SigningKey::from_seed([2; 32]), SigningKey::from_seed([3; 32]));
        let (a_pub, c_pub, m_pub) = (a.public_key(), c.public_key(), m.public_key());
        let log = test_support::fleet("A", &a, "C", &[("C", c_pub), ("M", m_pub)]);
        assert_eq!(Authority::of(&log, &[a_pub], &c_pub), Authority { ours: true, theirs: false }, "the authority dials the control plane");
        assert_eq!(Authority::of(&log, &[c_pub], &a_pub), Authority { ours: false, theirs: true }, "the control plane dialed by the authority");
        assert_eq!(Authority::of(&log, &[m_pub], &c_pub), Authority::default(), "an ordinary member");
        assert!(Authority::of(&log, &[m_pub, a_pub], &c_pub).ours, "a pending rotation's next key");
        assert_eq!(Authority::of(&Stored::default(), &[a_pub], &c_pub), Authority::default(), "no fleet's log");
    }

    /// A fleet of `members` (each a name and its `member.toml`, the first
    /// the authority, `L` the control plane) whose log pins `pin`, signed by
    /// the authority, written as every member's `membership.json`.
    fn pinned_fleet(members: &[(&str, &Path)], pin: Pin) -> Stored {
        use crate::serve::fleet::membership::Op;
        for (_, m) in members {
            std::fs::create_dir_all(m.parent().unwrap()).unwrap();
        }
        let mut stored = test_support::fleet_of("L", members);
        let (authority, toml) = members[0];
        stored.log.append(Op::Build { version: 1, pin }, authority, &test_support::key_of(toml)).unwrap();
        for (_, m) in members {
            test_support::write(m, &stored);
        }
        stored
    }

    /// `hello` with the peer link words after the build: control plane `L`,
    /// sha256 prefix `sha`, no dev builds.
    fn saying(build: &str, sha: &str) -> &'static str {
        Box::leak(format!("{build} {} control_plane L {sha} nodev", update::PLATFORM).into_boxed_str())
    }

    /// The pinned release is 9.9.9 and L, the authority, dials: K's end drops
    /// the link, installs that release (its checksums the pin's) and hands
    /// off, and says so.
    #[test]
    fn a_member_follows_a_published_pin() {
        let base = scratch("peer-follow");
        std::fs::create_dir_all(&base).unwrap();
        let (k_member, l_member) = (base.join("k-id/member.toml"), base.join("l-id/member.toml"));
        let pin = Pin::Published { semver: "9.9.9".into(), sums_sha256: update::tests::sums_sha256("9.9.9") };
        pinned_fleet(&[("L", &l_member), ("K", &k_member)], pin);
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, saying("9.9.9 abc published", "-"), Identity::load(&l_member, "L").unwrap(), base.join("nowhere"), Arc::default());
        let fake = Arc::new(update::tests::Fake::building(&format!("9.9.9 abc published {}", update::PLATFORM)));
        let err = peer_link(k_io, base.clone(), k_member, fake.clone()).join().unwrap().unwrap_err();
        assert!(format!("{err:#}").starts_with("updated to devsandbox 9.9.9, handing off"), "{err:#}");
        assert!(fake.calls().first().is_some_and(|c| c.starts_with("fetch https://") && c.contains("v9.9.9")), "{:?}", fake.calls());
        assert_eq!(fake.calls().last().map(String::as_str), Some("handoff "));
        assert!(!endpoint::fleet_socket(&base, "L").exists());
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        // Retried: a child another test forks meanwhile shares the lock's
        // open file until it execs (`O_CLOEXEC`), so a single try can miss.
        let let_go = (0..100).any(|_| update::lock_update(&base).unwrap().is_some() || {
            std::thread::sleep(std::time::Duration::from_millis(20));
            false
        });
        assert!(let_go, "the update lock is let go");
        let _ = std::fs::remove_dir_all(&base);
    }

    /// The pin is a dev build of `b"new build"`; L dials saying sha256
    /// prefix `l_sha`, the authority when `l_authority` (else A is, and L an
    /// ordinary member), and sends `sent` as the binary once K's end waits
    /// for it. K's error and its steps' calls.
    fn take_a_pushed_dev_build(tag: &str, l_authority: bool, l_sha: &str, sent: &'static [u8]) -> (String, Vec<String>) {
        use crate::serve::fleet::transfer::{self, Header};
        let base = scratch(tag);
        std::fs::create_dir_all(&base).unwrap();
        let (k_member, l_member, a_member) = (base.join("k-id/member.toml"), base.join("l-id/member.toml"), base.join("a-id/member.toml"));
        let semver = env!("CARGO_PKG_VERSION");
        let sha256 = <sha2::Sha256 as sha2::Digest>::digest(b"new build").into();
        let pin = Pin::Dev { semver: semver.into(), git: "zzz".into(), platform: update::PLATFORM.into(), sha256 };
        if l_authority {
            pinned_fleet(&[("L", &l_member), ("K", &k_member)], pin);
        } else {
            pinned_fleet(&[("A", &a_member), ("L", &l_member), ("K", &k_member)], pin);
        }
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let outlet = Arc::new(link::Outlet::default());
        let hello = saying(&format!("{semver} zzz dev"), l_sha);
        let dialer = fake_dialer(dialer_io, hello, Identity::load(&l_member, "L").unwrap(), base.join("nowhere"), Arc::clone(&outlet));
        let fake = Arc::new(update::tests::Fake::building(&format!("{semver} zzz dev {}", update::PLATFORM)));
        let k_end = peer_link(k_io.try_clone().unwrap(), base.clone(), k_member, fake.clone());
        wait_for(|| outlet.is_up(), "the link is up");
        // Waiting for the binary: nothing else is served.
        let api = outlet.open(channel::API).unwrap();
        let crate::devsbd::mux::Conn::Unix(mut api) = api else { panic!("a socket pair") };
        api.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
        let mut got = Vec::new();
        api.read_to_end(&mut got).unwrap();
        assert!(got.is_empty(), "refused");
        let (size, sha256) = transfer::digest(sent).unwrap();
        let header = Header { kind: update::BINARY_KIND.into(), name: "devsandbox".into(), size, sha256, to: None, repo: None, refs: None };
        transfer::send(outlet.open(channel::TRANSFER).unwrap(), &header, sent).unwrap();
        let err = format!("{:#}", k_end.join().unwrap().unwrap_err());
        k_io.shutdown(Shutdown::Both).unwrap();
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        let _ = std::fs::remove_dir_all(&base);
        (err, fake.calls())
    }

    /// The authority dials: K's end serves only the binary it pushes (its
    /// kept copy of the pin), then ends the link and installs it.
    #[test]
    fn a_member_takes_the_pinned_dev_build_from_the_authority() {
        let (err, calls) = take_a_pushed_dev_build("peer-dev", true, "-", b"new build");
        assert!(err.starts_with("updated to devsandbox dev "), "{err}");
        assert_eq!(calls, ["build received", "install /dest/devsandbox", "build dest", "handoff "]);
    }

    /// An ordinary member dials, its `Hello` saying it has the pin's bytes:
    /// K's end takes the build from it.
    #[test]
    fn a_member_takes_the_pinned_dev_build_from_a_peer_that_has_it() {
        let has = update::sha_word(&<sha2::Sha256 as sha2::Digest>::digest(b"new build").into());
        let (err, calls) = take_a_pushed_dev_build("peer-dev-has", false, &has, b"new build");
        assert!(err.starts_with("updated to devsandbox dev "), "{err}");
        assert_eq!(calls.len(), 4, "{calls:?}");
    }

    /// Bytes other than the pin's: refused before they ever run.
    #[test]
    fn a_pushed_binary_that_isnt_the_pin_is_never_run() {
        let (err, calls) = take_a_pushed_dev_build("peer-dev-evil", true, "-", b"other build");
        assert!(err.contains("update to dev ") && err.contains("failed: the received binary's sha256 is "), "{err}");
        assert!(calls.is_empty(), "never run: {calls:?}");
    }

    /// An ordinary member without the pin dials: K's end waits for one that
    /// has it, serving the link meanwhile; nothing is downloaded or run.
    #[test]
    fn a_member_doesnt_receive_from_a_peer_without_the_pin() {
        let base = scratch("peer-dev-lacks");
        let (k_dir, _, _, k_opts) = peer_daemon(&base, "k");
        let k_member = k_opts.member.clone().unwrap();
        let (l_member, a_member) = (base.join("l-id/member.toml"), base.join("a-id/member.toml"));
        let pin = Pin::Dev { semver: "9.9.9".into(), git: "zzz".into(), platform: update::PLATFORM.into(), sha256: [7; 32] };
        pinned_fleet(&[("A", &a_member), ("L", &l_member), ("K", &k_member)], pin);
        let daemon = spawn_daemon(&k_dir, k_opts);
        drop(conn_at(&k_dir));
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, saying("9.9.8 yyy dev", "1111111111111111"), Identity::load(&l_member, "L").unwrap(), base.join("nowhere"), Arc::default());
        let fake = Arc::new(update::tests::Fake::default());
        let k_end = peer_link(k_io.try_clone().unwrap(), k_dir.clone(), k_member, fake.clone());
        wait_for(|| inbound_row(&k_dir).is_some(), "L listed: the link is served");
        assert!(fake.calls().is_empty(), "{:?}", fake.calls());
        k_io.shutdown(Shutdown::Both).unwrap();
        k_end.join().unwrap().unwrap();
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        assert!(conn_at(&k_dir).call("shutdown", json!({})).unwrap().error.is_none());
        assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
        let _ = std::fs::remove_dir_all(&base);
    }

    /// A dev pin for another platform: both ends are behind, the link is
    /// served anyway, and K's daemon shows L `connected`, behind, and this
    /// host behind, each with why, as K's end announced it.
    #[test]
    fn a_link_where_both_ends_are_behind_is_up_and_says_so() {
        let base = scratch("peer-behind-pin");
        let (k_dir, _, _, k_opts) = peer_daemon(&base, "k");
        let (l_dir, _, _, l_opts) = peer_daemon(&base, "l");
        let (k_member, l_member) = (k_opts.member.clone().unwrap(), l_opts.member.clone().unwrap());
        let a_member = base.join("a-id/member.toml");
        let pin = Pin::Dev { semver: "9.9.9".into(), git: "zzz".into(), platform: "other/os".into(), sha256: [7; 32] };
        pinned_fleet(&[("A", &a_member), ("L", &l_member), ("K", &k_member)], pin.clone());
        let daemons = [spawn_daemon(&k_dir, k_opts), spawn_daemon(&l_dir, l_opts)];
        drop((conn_at(&k_dir), conn_at(&l_dir)));
        let (dialer_io, k_io) = UnixStream::pair().unwrap();
        let dialer = fake_dialer(dialer_io, saying("9.9.8 yyy dev", "1111111111111111"), Identity::load(&l_member, "L").unwrap(), l_dir.clone(), Arc::default());
        let fake = Arc::new(update::tests::Fake::default());
        let k_end = peer_link(k_io.try_clone().unwrap(), k_dir.clone(), k_member, fake.clone());
        wait_for(|| inbound_row(&k_dir).is_some_and(|r| r["state"] == "connected"), "L connected");
        let row = inbound_row(&k_dir).unwrap();
        let why = format!("dev build: can't run on {} (the fleet's build is {pin})", update::PLATFORM);
        assert_eq!((&row["behind"], &row["behind_here"]), (&json!(why), &json!(why)), "{row}");
        crate::serve::dts::assert_matches("MachineRow", &row);
        assert!(fake.calls().is_empty(), "{:?}", fake.calls());
        k_io.shutdown(Shutdown::Both).unwrap();
        k_end.join().unwrap().unwrap();
        assert!(matches!(dialer.join().unwrap(), link::End::Closed));
        for (dir, daemon) in [&k_dir, &l_dir].into_iter().zip(daemons) {
            assert!(conn_at(dir).call("shutdown", json!({})).unwrap().error.is_none());
            assert_eq!(daemon.join().unwrap().unwrap(), Exit::Shutdown);
        }
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn the_announce_says_who_is_behind() {
        let behind = update::Behind { here: Some("mine".into()), peer: None };
        let p = inbound_params("L", "0.9.0 a dev linux/x86_64 control_plane L - nodev", &behind);
        assert_eq!(p, json!({"peer": "L", "version": "0.9.0 a dev linux/x86_64 control_plane L - nodev", "control_plane": true, "behind_here": "mine", "behind": null}));
    }
}