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
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
//! The daemon's port forwards (docs/architecture/daemon/forwards.md,
//! docs/reference/api.md *Forwards*): every live [`Forward`], ad-hoc
//! (`forwards.add`) and configured (the sandboxes' `forwardPorts`), owned by
//! one `serve-forwards` thread so they outlive any dashboard and count as
//! idle holders.
//!
//! Threading: the [`Registry`] thread blocks on its command channel with a
//! [`POLL`] timeout, so it wakes both for requests ([`Handle`]: the API's
//! `forwards.*`, each with a reply channel, and the host poll's running
//! containers) and for the periodic status poll. All config/state work, route
//! resolution and binding happens there, never on a connection thread; a
//! request only waits for its reply (up to [`REPLY_TIMEOUT`]). Dropping the
//! [`Registry`] stops the thread and drops every forward (closing its
//! listener, killing its bridge) before it returns.
//!
//! Open forwards ([`Handle::open_forward`]) are the third kind: made by the
//! opener for a URL's loopback port before the browser opens, reusing any
//! forward of the same instance port, never persisted, stopped after
//! [`OPEN_FORWARD_IDLE`] without a connection or when their instance stops.
//! One into another member's instance (an open delivered from there) is a
//! [`Remote`] like an ad-hoc one; its instance stopping isn't seen here, so
//! it stops on idle or when its machine goes.
//!
//! Forwards are grouped per config root ([`Root`], keyed by the canonical
//! `dir`); ids are unique daemon-wide. Configured forwards are reconciled for
//! every config root recorded in `state.toml` against the host's poll of the
//! running containers (`docs/architecture/daemon/forwards.md`, _Configured
//! forwards (`forwardPorts`)_), reusing the host port saved in state. Status
//! goes out through [`Event`]s (the API's `forwards.changed` /
//! `forwards.status`) and `serve.log`; nothing else is printed.
//!
//! Ad-hoc forwards persist in `forwards.toml` ([`forward_store`]): an add
//! appends, an rm removes, and the thread restores them first thing, on
//! their saved host ports, so they survive a handoff or restart. Stopping
//! the thread leaves the file alone: dropping forwards on exit isn't removal.
//!
//! Forwards into a machine's instance or service ([`Remote`], `forwards.add`
//! with `machine`, or an open forward with one) live apart from the
//! [`Root`]s (which load local config): bound here, each bridge a `TUNNEL`
//! stream through the machine's link socket in the socket dir
//! (`tunnel::remote_opener`, [`via`] per spawn), served under the machine's
//! trust there. Ad-hoc ones persist like local ones; a sync drops those of a
//! machine gone from `machines.toml`, open ones included.
//!
//! Each forward keeps its own self-healing bridge (`Forward::start`); riding
//! the instance's daemon bridge mux instead is a later optimization.

use std::collections::{BTreeMap, BTreeSet};
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

use super::api::ApiError;
use super::forward_store::{self, Entry};
use super::machines;
use super::machines::inbound::Neighbors;
use crate::commands::{port, services, tunnel};
use crate::config::{Config, ForwardPort, ServiceScope};
use crate::devsbd::forward::{local_opener, Forward, ForwardSpec, ForwardState, ForwardStatus, HostPort, PREFER_SPAN};
use crate::state::State;

/// How often the registry re-polls every forward's `status()` while idle, so
/// a state change (Connecting → Active, a note) reaches subscribers within a
/// poll. Also the cadence at which per-connection notes are drained.
pub const POLL: Duration = Duration::from_millis(500);
/// How long an API request waits for the registry's answer (a sync binding
/// several configured forwards may be ahead of it in the queue).
const REPLY_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a restore retries a saved host port that's taken before it
/// falls back to the next free one.
const RESTORE_PORT_WAIT: Duration = Duration::from_secs(1);
/// How long an open forward lives without a connection (counted from its
/// last connection, or its last reuse, whichever is later).
pub const OPEN_FORWARD_IDLE: Duration = Duration::from_secs(10 * 60);

/// One row of `forwards.list`: the dashboard's Ports-tab row plus the forward's
/// config root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForwardRow {
    /// Daemon-wide id, what `forwards.rm` takes.
    pub id: u64,
    /// Canonical config root; with `machine`, the root on that machine.
    pub dir: PathBuf,
    /// Host side, e.g. `"127.0.0.1:3000"`.
    pub local: String,
    /// Route label, e.g. `"api:3000"` or `"postgres:5432 (via instance api)"`;
    /// empty until the first route resolve. A remote forward's is
    /// `<machine>/<label>`, best effort from the request until the far side
    /// first answers.
    pub target: String,
    /// Listening process (`node (pid 412)`), when known.
    pub process: Option<String>,
    /// `"active"`, `"connecting"`, or `"error: …"`.
    pub state: String,
    /// Open connections.
    pub conns: usize,
    /// Started from a sandbox's `forwardPorts`, not by `forwards.add`.
    pub configured: bool,
    /// Made by the opener for a URL's loopback port (an open forward).
    pub open: bool,
    /// The machine whose instance or service it reaches; absent for this
    /// host's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub machine: Option<String>,
}

/// A validated `forwards.add` (the API handler parses and checks the params).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddRequest {
    /// Absolute config root; canonicalized by the registry. With `machine`,
    /// the root on that machine, taken as is.
    pub dir: PathBuf,
    /// Instance name as the user typed it; `None` for a service-only forward.
    /// With `machine`, its name there (resolved by the far `tunnel`).
    pub instance: Option<String>,
    pub service: Option<String>,
    pub bind: IpAddr,
    pub host_port: HostPort,
    pub container_port: u16,
    /// A registered machine: the forward still binds here.
    pub machine: Option<String>,
}

/// The opener's ask for a forward to an instance port a URL names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenRequest {
    /// The machine the instance runs on (an open delivered over the fleet,
    /// `open.deliver`); `None`: this host.
    pub machine: Option<String>,
    /// Absolute config root (on `machine`, as it gave it); canonicalized by
    /// the registry for a local one.
    pub dir: PathBuf,
    /// Instance state key, already resolved; with `machine`, its name there.
    pub instance: String,
    pub container_port: u16,
    /// An OAuth callback port: only a forward bound on the same host port
    /// will do (the provider redirects to exactly that port).
    pub callback: bool,
}

/// [`Handle::open_forward`]'s answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenForward {
    pub host_port: u16,
    /// An existing forward (of any kind) answered.
    pub reused: bool,
}

/// `forwards.add`'s answer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Added {
    pub id: u64,
    /// The bound host address.
    pub local: String,
    /// Route label, best effort this early (see [`route_label_or`]).
    pub target: String,
}

/// What `forwards.rm` stopped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Removed {
    pub local: String,
    pub configured: bool,
}

/// From the registry to the daemon's subscribers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    /// The rows changed: `forwards.changed`.
    Changed,
    /// A one-line status (a configured forward started or failed, a
    /// connection note): `forwards.status`.
    Status(String),
}

pub type OnEvent = Box<dyn Fn(Event) + Send>;

/// How one spawn of a forward into a machine's `request` reaches it: its
/// link's socket in `socket_dir`, else its route socket there
/// (`fleet::route::connect`), for every kind of machine.
fn via(socket_dir: &Path, request: tunnel::Request) -> tunnel::Via {
    tunnel::Via::Fleet { dir: socket_dir.to_path_buf(), request }
}

enum Cmd {
    List { dir: Option<PathBuf>, machines: bool, reply: Sender<Vec<ForwardRow>> },
    Add { req: AddRequest, reply: Sender<Result<Added, ApiError>> },
    Remove { id: u64, reply: Sender<Result<Removed, ApiError>> },
    Open { req: OpenRequest, reply: Sender<Result<OpenForward, ApiError>> },
    /// The runtime's running containers, from the host poll.
    Sync(Vec<String>),
    Stop,
}

/// The registry thread's handle, owned by the daemon. Dropping it stops the
/// thread and drops every forward.
pub struct Registry {
    tx: Sender<Cmd>,
    active: Arc<AtomicUsize>,
    thread: Option<JoinHandle<()>>,
}

/// A cheap clone of the registry's command channel: the API and the host
/// poll talk through it. Requests after the registry stopped fail.
#[derive(Clone)]
pub struct Handle {
    tx: Sender<Cmd>,
}

impl Registry {
    /// Start the registry thread. `log` writes one `serve.log` line; `store`
    /// is the ad-hoc forwards' file ([`forward_store::path`] outside tests),
    /// restored before any request is served; `machines` is `machines.toml`,
    /// read for remote forwards (each add, each bridge spawn, each sync),
    /// with `inbound`'s neighbors machines beside its entries (while up),
    /// and `routed`'s;
    /// `socket_dir` is the daemon's, where each machine's link has its
    /// socket; `on_event` gets every [`Event`] (called on the registry
    /// thread: it must not block).
    pub fn spawn(
        log: fn(&str),
        store: PathBuf,
        machines: PathBuf,
        inbound: Arc<Neighbors>,
        routed: RoutedNames,
        socket_dir: PathBuf,
        on_event: OnEvent,
    ) -> Registry {
        let (tx, rx) = mpsc::channel();
        let active = Arc::new(AtomicUsize::new(0));
        let thread = {
            let active = Arc::clone(&active);
            std::thread::Builder::new().name("serve-forwards".into()).spawn(move || {
                let known = Known { registry: machines, inbound, routed };
                let mut daemon = Daemon::new(log, store, known, socket_dir, on_event, active);
                daemon.restore();
                daemon.poll();
                daemon.run(&rx);
            })
        };
        let thread = thread.map_err(|e| log(&format!("cannot start the forwards thread: {e}"))).ok();
        Registry { tx, active, thread }
    }

    pub fn handle(&self) -> Handle {
        Handle { tx: self.tx.clone() }
    }

    /// Live forwards, ad-hoc, configured, open and remote: the `forwards`
    /// holder count.
    pub fn active(&self) -> usize {
        self.active.load(Ordering::Acquire)
    }
}

impl Drop for Registry {
    fn drop(&mut self) {
        // Not a channel close: `Handle`s outlive us (in the daemon's shared
        // state), so the thread is told to stop explicitly.
        let _ = self.tx.send(Cmd::Stop);
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }
}

impl Handle {
    /// Hand the registry the running containers. Never blocks.
    pub fn sync(&self, running: Vec<String>) {
        let _ = self.tx.send(Cmd::Sync(running));
    }

    /// A forward for the opener: an existing one of the same instance port
    /// when one fits, else a new open forward.
    pub fn open_forward(&self, req: OpenRequest) -> Result<OpenForward, ApiError> {
        self.ask(|reply| Cmd::Open { req, reply })?
    }

    fn ask<T>(&self, cmd: impl FnOnce(Sender<T>) -> Cmd) -> Result<T, ApiError> {
        let (reply, rx) = mpsc::channel();
        self.tx.send(cmd(reply)).map_err(|_| stopped())?;
        rx.recv_timeout(REPLY_TIMEOUT).map_err(|e| match e {
            RecvTimeoutError::Timeout => ApiError::internal(anyhow::anyhow!("the forwards registry didn't answer")),
            RecvTimeoutError::Disconnected => stopped(),
        })
    }
}

fn stopped() -> ApiError {
    ApiError::internal(anyhow::anyhow!("port forwarding is stopping"))
}

impl super::api::Forwarding for Handle {
    fn list(&self, dir: Option<PathBuf>, machines: bool) -> Result<Vec<ForwardRow>, ApiError> {
        self.ask(|reply| Cmd::List { dir, machines, reply })
    }

    fn add(&self, req: AddRequest) -> Result<Added, ApiError> {
        self.ask(|reply| Cmd::Add { req, reply })?
    }

    fn rm(&self, id: u64) -> Result<Removed, ApiError> {
        self.ask(|reply| Cmd::Remove { id, reply })?
    }
}

/// The routed machines' names now (`machines::service::Handle::routed`).
pub type RoutedNames = Arc<dyn Fn() -> Vec<String> + Send + Sync>;

/// The machines a remote forward may go into: `machines.toml`'s entries,
/// the inbound neighbors up now and the routed machines.
#[derive(Clone)]
struct Known {
    registry: PathBuf,
    inbound: Arc<Neighbors>,
    routed: RoutedNames,
}

impl Known {
    fn names(&self) -> anyhow::Result<BTreeSet<String>> {
        let mut names: BTreeSet<String> = machines::load(&self.registry)?.into_iter().map(|m| m.name).collect();
        names.extend(self.inbound.list().into_iter().map(|n| n.name));
        names.extend((self.routed)());
        Ok(names)
    }
}

/// The registry thread's state.
struct Daemon {
    log: fn(&str),
    /// `forwards.toml`.
    store: PathBuf,
    machines: Known,
    /// The daemon's socket dir: the machines' link sockets.
    socket_dir: PathBuf,
    on_event: OnEvent,
    active: Arc<AtomicUsize>,
    roots: BTreeMap<PathBuf, Root>,
    /// Forwards into machines, by id.
    remote: BTreeMap<u64, Remote>,
    next_id: u64,
    /// Last rows seen, so an unchanged poll sends no [`Event::Changed`].
    last_rows: Vec<ForwardRow>,
    /// Last note sent, so a repeated one isn't re-sent.
    last_status: Option<String>,
}

impl Daemon {
    fn new(
        log: fn(&str),
        store: PathBuf,
        machines: Known,
        socket_dir: PathBuf,
        on_event: OnEvent,
        active: Arc<AtomicUsize>,
    ) -> Self {
        Self {
            log,
            store,
            machines,
            socket_dir,
            on_event,
            active,
            roots: BTreeMap::new(),
            remote: BTreeMap::new(),
            next_id: 1,
            last_rows: Vec::new(),
            last_status: None,
        }
    }

    fn run(&mut self, rx: &Receiver<Cmd>) {
        loop {
            match rx.recv_timeout(POLL) {
                Ok(Cmd::List { dir, machines, reply }) => {
                    let _ = reply.send(self.rows(dir.as_deref(), machines));
                }
                Ok(Cmd::Add { req, reply }) => {
                    let _ = reply.send(self.add(req));
                }
                Ok(Cmd::Remove { id, reply }) => {
                    let _ = reply.send(self.remove(id));
                }
                Ok(Cmd::Open { req, reply }) => {
                    let _ = reply.send(self.open(req));
                }
                Ok(Cmd::Sync(running)) => self.sync(&running),
                Err(RecvTimeoutError::Timeout) => {}
                Ok(Cmd::Stop) | Err(RecvTimeoutError::Disconnected) => break,
            }
            self.poll();
        }
        // Every Forward drops here: listeners close, bridges die. The store
        // keeps them, for the successor.
        self.roots.clear();
        self.remote.clear();
        self.active.store(0, Ordering::Release);
    }

    fn status(&mut self, line: String) {
        (self.log)(&format!("forwards: {line}"));
        (self.on_event)(Event::Status(line));
    }

    /// Rows of every local root, or of `dir` (canonicalized; a dir that
    /// doesn't resolve has none), plus with `machines` every remote forward
    /// (whatever `dir`), by id.
    fn rows(&self, dir: Option<&Path>, machines: bool) -> Vec<ForwardRow> {
        let dir = dir.map(|d| d.canonicalize().unwrap_or_else(|_| d.to_path_buf()));
        let mut rows: Vec<ForwardRow> = self
            .roots
            .values()
            .filter(|r| dir.as_ref().is_none_or(|d| *d == r.dir))
            .flat_map(Root::rows)
            .collect();
        if machines {
            rows.extend(self.remote.iter().map(|(&id, r)| r.row(id)));
        }
        rows.sort_by_key(|r| r.id);
        rows
    }

    fn root(&mut self, dir: &Path) -> &mut Root {
        self.roots.entry(dir.to_path_buf()).or_insert_with(|| Root::new(dir.to_path_buf()))
    }

    fn add(&mut self, req: AddRequest) -> Result<Added, ApiError> {
        if let Some(machine) = req.machine.clone() {
            return self.add_remote(machine, &req);
        }
        let dir = req
            .dir
            .canonicalize()
            .map_err(|e| ApiError::not_found(format!("no directory {}: {e}", req.dir.display())))?;
        let mut next_id = self.next_id;
        let started = self.root(&dir).start(&req, &mut next_id);
        self.next_id = next_id;
        let (added, entry) = started?;
        self.persist(|entries| entries.push(entry));
        Ok(added)
    }

    /// The opener's forward: into this host's instance ([`Root::open`]) or,
    /// with `machine`, into that member's ([`Daemon::open_remote`]). A
    /// callback port that can't be bound is also a status line: the OAuth
    /// redirect will miss.
    fn open(&mut self, req: OpenRequest) -> Result<OpenForward, ApiError> {
        let now = Instant::now();
        let opened = match req.machine.clone() {
            Some(machine) => self.open_remote(machine, &req, now),
            None => self.open_local(&req, now),
        };
        opened.map_err(|(e, note)| {
            if let Some(line) = note {
                self.status(line);
            }
            e
        })
    }

    fn open_local(&mut self, req: &OpenRequest, now: Instant) -> Result<OpenForward, OpenError> {
        let dir = req
            .dir
            .canonicalize()
            .map_err(|e| (ApiError::not_found(format!("no directory {}: {e}", req.dir.display())), None))?;
        // Unreadable state: nothing reserved (the configured forwards then
        // can't start either).
        let project = self.root(&dir).project.clone();
        let reserved = project.and_then(|p| State::load().ok().map(|s| root_saved_ports(&s, &p))).unwrap_or_default();
        let mut next_id = self.next_id;
        let opened = self.root(&dir).open(req, &reserved, &mut next_id, now);
        self.next_id = next_id;
        opened
    }

    /// An open forward into `machine`'s instance: `req.dir` is the root
    /// there, as sent (never resolved here), `req.instance` its name there.
    /// The machine must be known like for [`Daemon::add_remote`]. Reuse
    /// follows [`Root::reusable`] over the remote forwards ([`Remote::reaches`],
    /// an ad-hoc one included; an open one's `touched` refreshed), binding
    /// follows [`bind_open`]. Its instance stopping there isn't visible
    /// here: it stops on idle ([`Daemon::expire_open`]) or with its machine
    /// ([`Daemon::drop_unregistered`]).
    fn open_remote(&mut self, machine: String, req: &OpenRequest, now: Instant) -> Result<OpenForward, OpenError> {
        let known = self.registered().map_err(|e| (ApiError::internal(e), None))?;
        if !known.contains(&machine) {
            return Err((ApiError::not_found(machines::no_machine(&machine).to_string()), None));
        }
        let (key, port) = (req.instance.as_str(), req.container_port);
        let reusable = self.remote.iter_mut().find(|(_, r)| {
            r.reaches(&machine, &req.dir, key, port) && (!req.callback || r.forward.status().local_addr.port() == port)
        });
        if let Some((_, r)) = reusable {
            if let Some(touched) = &mut r.opened {
                *touched = now;
            }
            return Ok(OpenForward { host_port: r.forward.status().local_addr.port(), reused: true });
        }
        let entry = Entry {
            dir: req.dir.clone(),
            instance: Some(key.to_string()),
            service: None,
            address: Entry::address_of(IpAddr::V4(Ipv4Addr::LOCALHOST)),
            container_port: port,
            host_port: 0,
            machine: Some(machine),
        };
        // No reserved ports: a member's root has no configured forwards here.
        let (id, entry) =
            bind_open(key, port, req.callback, &BTreeSet::new(), |host_port| self.start_remote(entry.clone(), host_port))?;
        if let Some(r) = self.remote.get_mut(&id) {
            r.opened = Some(now);
        }
        Ok(OpenForward { host_port: entry.host_port, reused: false })
    }

    /// `forwards.add` into `machine`: it must be registered (or an inbound
    /// neighbor up now, or routed); the far side resolves the rest, on the forward's
    /// own thread.
    fn add_remote(&mut self, machine: String, req: &AddRequest) -> Result<Added, ApiError> {
        let known = self.registered().map_err(ApiError::internal)?;
        if !known.contains(&machine) {
            return Err(ApiError::not_found(machines::no_machine(&machine).to_string()));
        }
        let entry = Entry {
            dir: req.dir.clone(),
            instance: req.instance.clone(),
            service: req.service.clone(),
            address: Entry::address_of(req.bind),
            container_port: req.container_port,
            host_port: 0,
            machine: Some(machine),
        };
        let (id, entry) = self.start_remote(entry, req.host_port).map_err(|e| bind_failed(req.host_port, &e))?;
        let forward = &self.remote[&id].forward;
        let added = Added { id, local: forward.status().local_addr.to_string(), target: route_label_or(forward, req) };
        self.persist(|entries| entries.push(entry));
        Ok(added)
    }

    /// Bind `entry`'s remote forward (its `machine` set) on `host_port` and
    /// register it. Returns its id and the entry with the bound host port.
    fn start_remote(&mut self, mut entry: Entry, host_port: HostPort) -> std::io::Result<(u64, Entry)> {
        let machine = entry.machine.clone().unwrap_or_default();
        let (registry, socket_dir) = (self.machines.clone(), self.socket_dir.clone());
        let name = machine.clone();
        let request = tunnel::Request {
            root: entry.dir.clone(),
            instance: entry.instance.clone(),
            service: entry.service.clone(),
            port: entry.container_port,
        };
        // Re-read on every spawn: a removed machine (a gone neighbor) is
        // the bridge's error until the next sync drops the forward.
        let dial: tunnel::TunnelVia = Box::new(move || {
            if !registry.names().map_err(|e| format!("{e:#}"))?.contains(&name) {
                return Err(machines::no_machine(&name).to_string());
            }
            Ok(via(&socket_dir, request.clone()))
        });
        let open = tunnel::remote_opener(machine, dial);
        // No probe fallback: the far helper is the only listening-process lookup.
        let probe = Box::new(|_: &str, _: u16| None);
        let forward = Forward::start(ForwardSpec { bind: entry.bind(), host_port, open, probe })?;
        entry.host_port = forward.status().local_addr.port();
        let id = self.next_id;
        self.next_id += 1;
        self.remote.insert(id, Remote { forward, entry: entry.clone(), opened: None });
        Ok((id, entry))
    }

    /// The machines' names: registered, or inbound neighbors up now.
    fn registered(&self) -> anyhow::Result<BTreeSet<String>> {
        self.machines.names()
    }

    /// Drop the remote forwards, and the ad-hoc ones' store entries, of
    /// machines no longer in `machines.toml` (`machine rm`) or up as an
    /// inbound neighbor (its link went). A registry that doesn't load drops
    /// nothing; with no remote forwards it isn't read.
    fn drop_unregistered(&mut self) {
        if self.remote.is_empty() {
            return;
        }
        let Ok(names) = self.registered() else { return };
        let gone: Vec<u64> =
            self.remote.iter().filter(|(_, r)| !names.contains(r.machine())).map(|(&id, _)| id).collect();
        if gone.is_empty() {
            return;
        }
        let mut entries = Vec::new();
        for id in gone {
            let Some(r) = self.remote.remove(&id) else { continue };
            (self.log)(&format!(
                "forwards: dropping {}: machine `{}` is no longer registered",
                describe(&r.entry),
                r.machine()
            ));
            if r.opened.is_none() {
                entries.push(r.entry);
            }
        }
        if entries.is_empty() {
            return;
        }
        self.persist(|saved| {
            for entry in &entries {
                forward_store::remove(saved, entry);
            }
        });
    }

    fn remove(&mut self, id: u64) -> Result<Removed, ApiError> {
        let found = self.roots.values_mut().find_map(|root| root.remove(id)).or_else(|| {
            let r = self.remote.remove(&id)?;
            let local = r.forward.status().local_addr.to_string();
            // An open one has no store entry.
            Some((Removed { local, configured: false }, r.opened.is_none().then_some(r.entry)))
        });
        let Some((removed, entry)) = found else {
            return Err(ApiError::not_found(format!("no forward {id}")));
        };
        if let Some(entry) = entry {
            self.persist(|entries| {
                forward_store::remove(entries, &entry);
            });
        }
        Ok(removed)
    }

    /// Apply `f` to the store. A failure is logged, never the request's.
    fn persist(&self, f: impl FnOnce(&mut Vec<Entry>)) {
        if let Err(e) = forward_store::update(&self.store, f) {
            (self.log)(&format!("forwards: cannot save {}: {e:#}", self.store.display()));
        }
    }

    /// Recreate the saved ad-hoc forwards: each on its saved host port, else
    /// (taken now) on an automatic one near it, which the store then records.
    /// Entries of instances gone from state, and remote ones of machines no
    /// longer registered, are dropped from the store; a stopped instance's
    /// forward is restored anyway (it heals when the instance runs). Other
    /// failures (a `machines.toml` that doesn't load included) are logged and
    /// the entry kept.
    fn restore(&mut self) {
        let saved = match forward_store::load(&self.store) {
            Ok(saved) if saved.is_empty() => return,
            Ok(saved) => saved,
            Err(e) => return (self.log)(&format!("forwards: cannot restore: {e:#}")),
        };
        let state = match State::load() {
            Ok(state) => state,
            Err(e) => return (self.log)(&format!("forwards: cannot restore: {e:#}")),
        };
        let (keep, dropped) = restorable(saved, &state);
        // (old entry, its replacement; `None` drops it), applied as diffs so a
        // write by an overlapping daemon since the load isn't undone.
        let mut changes: Vec<(Entry, Option<Entry>)> = Vec::new();
        for entry in dropped {
            (self.log)(&format!(
                "forwards: dropping saved {}: instance {} no longer exists",
                describe(&entry),
                entry.instance.as_deref().unwrap_or_default()
            ));
            changes.push((entry, None));
        }
        let registered = match keep.iter().any(|e| e.machine.is_some()).then(|| self.registered()) {
            Some(Err(e)) => {
                (self.log)(&format!("forwards: cannot restore remote forwards: {e:#}"));
                None
            }
            Some(Ok(names)) => Some(names),
            None => None,
        };
        for entry in keep {
            if let Some(machine) = &entry.machine {
                let Some(names) = &registered else { continue };
                if !names.contains(machine) {
                    (self.log)(&format!(
                        "forwards: dropping saved {}: machine `{machine}` is no longer registered",
                        describe(&entry)
                    ));
                    changes.push((entry, None));
                    continue;
                }
            }
            if let Some(now) = self.restore_one(&entry)
                && now != entry
            {
                changes.push((entry, Some(now)));
            }
        }
        if !changes.is_empty() {
            self.persist(|entries| {
                for (old, new) in changes {
                    let Some(i) = entries.iter().position(|e| *e == old) else { continue };
                    match new {
                        Some(new) => entries[i] = new,
                        None => {
                            entries.remove(i);
                        }
                    }
                }
            });
        }
    }

    /// Start one saved forward; the entry as it now runs, `None` when it
    /// couldn't start (logged).
    fn restore_one(&mut self, entry: &Entry) -> Option<Entry> {
        let log = self.log;
        // A machine's root is a path there: nothing to resolve here.
        let dir = match &entry.machine {
            Some(_) => entry.dir.clone(),
            None => match entry.dir.canonicalize() {
                Ok(dir) => dir,
                Err(_) => {
                    log(&format!("forwards: cannot restore {}: no directory {}", describe(entry), entry.dir.display()));
                    return None;
                }
            },
        };
        // Retried briefly before falling back: right after a handoff, or while
        // some process's fork briefly holds the old listener, the saved port
        // frees within moments, and moving the forward would surprise.
        let deadline = std::time::Instant::now() + RESTORE_PORT_WAIT;
        let mut first = self.start_saved(&dir, entry, HostPort::Fixed(entry.host_port));
        while matches!(&first, Err(e) if e.kind() == std::io::ErrorKind::AddrInUse)
            && std::time::Instant::now() < deadline
        {
            std::thread::sleep(Duration::from_millis(50));
            first = self.start_saved(&dir, entry, HostPort::Fixed(entry.host_port));
        }
        let started = match first {
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
                self.start_saved(&dir, entry, HostPort::Prefer(entry.host_port)).map(|now| (now, true))
            }
            started => started.map(|now| (now, false)),
        };
        match started {
            Ok((now, fell_back)) => {
                if fell_back {
                    log(&format!(
                        "forwards: restored {} on port {} (port {} is taken)",
                        describe(entry),
                        now.host_port,
                        entry.host_port
                    ));
                } else {
                    log(&format!("forwards: restored {}", describe(entry)));
                }
                Some(now)
            }
            Err(e) => {
                log(&format!("forwards: cannot restore {}: {}", describe(entry), bind_reason(&e)));
                None
            }
        }
    }

    /// Start one saved forward (local in root `dir`, or remote) on
    /// `host_port`; the entry as it now runs.
    fn start_saved(&mut self, dir: &Path, entry: &Entry, host_port: HostPort) -> std::io::Result<Entry> {
        if entry.machine.is_some() {
            return self.start_remote(entry.clone(), host_port).map(|(_, now)| now);
        }
        let mut next_id = self.next_id;
        let started = self.root(dir).start_adhoc(entry.clone(), host_port, &mut next_id);
        self.next_id = next_id;
        started.map(|(_, now)| now)
    }

    /// Drop the remote forwards of machines gone from `machines.toml`, then
    /// reconcile configured forwards for every config root recorded in state
    /// (plus roots that only have ad-hoc forwards, whose configured ones then
    /// stop if their instances went away).
    fn sync(&mut self, running: &[String]) {
        self.drop_unregistered();
        let Ok(state) = State::load() else { return };
        for dir in super::host::config_roots(&state) {
            self.root(&dir);
        }
        let mut next_id = self.next_id;
        let mut notes = Vec::new();
        let mut stopped = Vec::new();
        for root in self.roots.values_mut() {
            let keys = running_keys(&state, running, &root.dir);
            // Before `Root::sync`, which bails when config or state don't load.
            stopped.extend(root.stop_open(|o, _| !keys.contains(&o.instance)));
            root.sync(&keys, &mut next_id, &mut notes);
        }
        self.next_id = next_id;
        for (target, local) in stopped {
            (self.log)(&format!("forwards: stopped open forward {target} on {local}: its instance stopped"));
        }
        for line in notes {
            self.status(line);
        }
    }

    /// Rebuild the rows and send [`Event::Changed`] only when they changed,
    /// then drain each forward's notes and send the newest as a deduped
    /// [`Event::Status`].
    fn poll(&mut self) {
        self.expire_open(Instant::now());
        let rows = self.rows(None, true);
        self.active.store(rows.len(), Ordering::Release);
        if rows != self.last_rows {
            self.last_rows = rows;
            (self.on_event)(Event::Changed);
        }
        // The newest note per forward, prefixed with the local port, is the one
        // worth showing; dedup so a retry loop doesn't repeat the same line.
        let mut newest: Option<String> = None;
        let local = self.roots.values().flat_map(|r| r.live.values());
        for f in local.chain(self.remote.values().map(|r| &r.forward)) {
            let local_port = f.status().local_addr.port();
            for note in f.drain_notes() {
                newest = Some(format!("{local_port}: {note}"));
            }
        }
        if let Some(line) = newest
            && self.last_status.as_deref() != Some(line.as_str())
        {
            self.last_status = Some(line.clone());
            self.status(line);
        }
    }

    /// Stop the open forwards, local and remote, idle for
    /// [`OPEN_FORWARD_IDLE`] at `now` ([`open_expired`]); each one logged.
    fn expire_open(&mut self, now: Instant) {
        let mut expired: Vec<(String, String)> = self
            .roots
            .values_mut()
            .flat_map(|root| root.stop_open(|o, status| open_expired(status.idle_since, o.touched, now)))
            .collect();
        let remote: Vec<u64> = self
            .remote
            .iter()
            .filter(|(_, r)| r.opened.is_some_and(|touched| open_expired(r.forward.status().idle_since, touched, now)))
            .map(|(&id, _)| id)
            .collect();
        for id in remote {
            let Some(r) = self.remote.remove(&id) else { continue };
            expired.push((r.label(), r.forward.status().local_addr.to_string()));
        }
        for (target, local) in expired {
            (self.log)(&format!(
                "forwards: stopped open forward {target} on {local}: no connection for {} min",
                OPEN_FORWARD_IDLE.as_secs() / 60
            ));
        }
    }
}

/// An open forward's failure: the error, and a status line to send with it.
type OpenError = (ApiError, Option<String>);

/// Bind a new open forward to instance `key`'s `port` with `start`, never
/// on a `reserved` host port (one saved for a configured forward of the
/// root, [`root_saved_ports`]: it would take that forward's port away). A
/// direct one prefers the container port, walking up past taken and
/// reserved ones ([`candidates`]), falling back to an automatic one when
/// none is free or one can't bind for any reason but being taken (a
/// privileged port say); a callback needs exactly that port, and failing
/// that (taken, reserved, or not bindable) comes with a status line: the
/// OAuth redirect will miss.
fn bind_open<T>(
    key: &str,
    port: u16,
    callback: bool,
    reserved: &BTreeSet<u16>,
    mut start: impl FnMut(HostPort) -> std::io::Result<T>,
) -> Result<T, OpenError> {
    if callback && reserved.contains(&port) {
        let note = format!("{key}: port {port} is saved for a configured forward; an OAuth callback to it won't reach {key}");
        return Err((ApiError::bind_failed(format!("port {port}: saved for a configured forward")), Some(note)));
    }
    if callback {
        return start(HostPort::Fixed(port)).map_err(|e| {
            let note = if e.kind() == std::io::ErrorKind::AddrInUse {
                format!("{key}: port {port} is taken; an OAuth callback to it won't reach {key}")
            } else {
                format!("{key}: cannot bind port {port} ({}); an OAuth callback to it won't reach {key}", bind_reason(&e))
            };
            (bind_failed(HostPort::Fixed(port), &e), Some(note))
        });
    }
    for p in candidates(None, port, reserved) {
        match start(HostPort::Fixed(p)) {
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
            Err(_) => break,
            Ok(started) => return Ok(started),
        }
    }
    start(HostPort::Prefer(0)).map_err(|e| (bind_failed(HostPort::Prefer(port), &e), None))
}

/// The running instances (state keys) that may belong to config root `root`:
/// recorded there, or recorded nowhere (from before roots were recorded;
/// [`wanted`] then matches them by sandbox name).
fn running_keys(state: &State, running: &[String], root: &Path) -> BTreeSet<String> {
    state
        .instances
        .iter()
        .filter(|(_, i)| running.contains(&i.container))
        .filter(|(_, i)| i.config_dir.as_deref().is_none_or(|d| d == root))
        .map(|(key, _)| key.clone())
        .collect()
}

/// Who a configured forward belongs to, which is also where its host port is
/// saved in state.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Owner {
    /// Instance state key: its own ports and its isolated services'.
    Instance(String),
    /// A `global` service's port: one forward per config root, however many
    /// running instances declare it.
    Global,
}

/// Identity of a configured forward: its owner plus the entry's
/// [`ForwardPort::key`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Configured {
    owner: Owner,
    entry: String,
}

struct ConfiguredLive {
    /// Its id in `Root::live`.
    id: u64,
    /// The instance port it reaches when it has no service: what an open
    /// request may reuse it for, without reloading config.
    direct: Option<u16>,
}

struct Opened {
    /// Instance state key.
    instance: String,
    container_port: u16,
    /// Its start or last reuse: the idle stop counts from the later of this
    /// and the forward's last connection.
    touched: Instant,
}

/// Whether an open forward has been idle for [`OPEN_FORWARD_IDLE`]: no
/// connection open (`idle_since` is `Some`) and nothing since, counting its
/// last reuse (`touched`).
fn open_expired(idle_since: Option<Instant>, touched: Instant, now: Instant) -> bool {
    idle_since.is_some_and(|idle| now.saturating_duration_since(idle.max(touched)) >= OPEN_FORWARD_IDLE)
}

/// One forward into a machine's instance or service: ad-hoc or open (a
/// machine's `forwardPorts` are never mirrored here), bound here, its bridge
/// a `TUNNEL` stream over the machine's link.
struct Remote {
    forward: Forward,
    /// What it reaches (`machine` set); an ad-hoc one's store entry, what
    /// `forwards.rm` removes.
    entry: Entry,
    /// `Some` for an open forward (never in the store): its start or last
    /// reuse, like [`Opened::touched`].
    opened: Option<Instant>,
}

impl Remote {
    fn machine(&self) -> &str {
        self.entry.machine.as_deref().unwrap_or_default()
    }

    /// Whether it reaches instance `key`'s `port` (no service) in root `dir`
    /// on `machine`: what an open there may reuse.
    fn reaches(&self, machine: &str, dir: &Path, key: &str, port: u16) -> bool {
        let e = &self.entry;
        e.machine.as_deref() == Some(machine)
            && e.dir == dir
            && e.instance.as_deref() == Some(key)
            && e.service.is_none()
            && e.container_port == port
    }

    /// Its best-effort `<machine>/target:port`.
    fn label(&self) -> String {
        let e = &self.entry;
        format!("{}/{}", self.machine(), target_label(e.service.as_deref(), e.instance.as_deref(), e.container_port))
    }

    fn row(&self, id: u64) -> ForwardRow {
        let mut row = status_to_row(id, &self.entry.dir, &self.forward.status(), false);
        if row.target.is_empty() {
            row.target = self.label();
        }
        row.machine = Some(self.machine().to_string());
        row.open = self.opened.is_some();
        row
    }
}

/// One config root's forwards.
struct Root {
    dir: PathBuf,
    /// Config-root id (`services::project_id`), the key for global forwards'
    /// saved ports. `None` when `dir` doesn't resolve: no configured forwards.
    project: Option<String>,
    live: BTreeMap<u64, Forward>,
    /// Live ad-hoc forwards' ids -> their store entry, what `forwards.rm`
    /// removes from the store.
    adhoc: BTreeMap<u64, Entry>,
    /// Live configured forwards -> their id in `live`.
    configured: BTreeMap<Configured, ConfiguredLive>,
    /// Live open forwards' ids -> what they reach. Never in the store.
    opened: BTreeMap<u64, Opened>,
    /// Configured forwards stopped by `forwards.rm`: not restarted until their
    /// owner stops (drops out of the wanted set) and comes back.
    suppressed: BTreeSet<Configured>,
    /// Configured forwards that failed to start (reported once); retried when
    /// their owner stops and comes back.
    failed: BTreeSet<Configured>,
}

impl Root {
    fn new(dir: PathBuf) -> Self {
        let project = services::project_id(&dir).ok();
        Self {
            dir,
            project,
            live: BTreeMap::new(),
            adhoc: BTreeMap::new(),
            configured: BTreeMap::new(),
            opened: BTreeMap::new(),
            suppressed: BTreeSet::new(),
            failed: BTreeSet::new(),
        }
    }

    fn rows(&self) -> Vec<ForwardRow> {
        let configured: BTreeSet<u64> = self.configured.values().map(|c| c.id).collect();
        self.live
            .iter()
            .map(|(&id, f)| ForwardRow {
                open: self.opened.contains_key(&id),
                ..status_to_row(id, &self.dir, &f.status(), configured.contains(&id))
            })
            .collect()
    }

    /// A live forward of instance `key`'s `port` with no service, of any
    /// kind, lowest id first; with `callback`, only one bound on host port
    /// `port` itself.
    fn reusable(&self, key: &str, port: u16, callback: bool) -> Option<u64> {
        let adhoc = self.adhoc.iter().filter(|(_, e)| {
            e.instance.as_deref() == Some(key) && e.service.is_none() && e.container_port == port && e.machine.is_none()
        });
        let configured = self.configured.iter().filter_map(|(c, live)| {
            (c.owner == Owner::Instance(key.to_string()) && live.direct == Some(port)).then_some(live.id)
        });
        let opened = self.opened.iter().filter(|(_, o)| o.instance == key && o.container_port == port);
        let mut ids: Vec<u64> =
            adhoc.map(|(&id, _)| id).chain(configured).chain(opened.map(|(&id, _)| id)).collect();
        ids.sort_unstable();
        ids.into_iter().find(|id| {
            self.live.get(id).is_some_and(|f| !callback || f.status().local_addr.port() == port)
        })
    }

    /// The opener's forward to `req`'s instance port: an existing one that
    /// fits ([`Root::reusable`]; an open one's `touched` refreshed), else a
    /// new open forward on 127.0.0.1 ([`bind_open`], never on a `reserved`
    /// port: [`root_saved_ports`] of this root). The instance key is
    /// taken as given: a bad one is the route's error, on the forward's own
    /// thread.
    fn open(&mut self, req: &OpenRequest, reserved: &BTreeSet<u16>, next_id: &mut u64, now: Instant) -> Result<OpenForward, OpenError> {
        let (key, port) = (req.instance.as_str(), req.container_port);
        if let Some(why) = State::load().ok().and_then(|s| broker_port_refusal(&s, key, port)) {
            return Err((ApiError::denied(why.clone()), Some(why)));
        }
        if let Some(id) = self.reusable(key, port, req.callback) {
            if let Some(o) = self.opened.get_mut(&id) {
                o.touched = now;
            }
            return Ok(OpenForward { host_port: self.live[&id].status().local_addr.port(), reused: true });
        }
        let started = bind_open(key, port, req.callback, reserved, |host_port| {
            Forward::start(ForwardSpec {
                bind: IpAddr::V4(Ipv4Addr::LOCALHOST),
                host_port,
                open: local_opener(port::resolver(self.dir.clone(), Some(key.to_string()), None, port)),
                probe: Box::new(port::listening_procs),
            })
        })?;
        let host_port = started.status().local_addr.port();
        let id = self.insert(started, next_id);
        self.opened.insert(id, Opened { instance: key.to_string(), container_port: port, touched: now });
        Ok(OpenForward { host_port, reused: false })
    }

    /// Drop the open forwards `stop` picks (given the forward's status).
    /// Returns each one's `(target, local)` for the log.
    fn stop_open(&mut self, stop: impl Fn(&Opened, &ForwardStatus) -> bool) -> Vec<(String, String)> {
        let picked: Vec<u64> = self
            .opened
            .iter()
            .filter(|(id, o)| self.live.get(id).is_some_and(|f| stop(o, &f.status())))
            .map(|(&id, _)| id)
            .collect();
        let mut out = Vec::new();
        for id in picked {
            let Some(o) = self.opened.remove(&id) else { continue };
            let Some(f) = self.live.remove(&id) else { continue };
            out.push((target_label(None, Some(&o.instance), o.container_port), f.status().local_addr.to_string()));
        }
        out
    }

    fn insert(&mut self, forward: Forward, next_id: &mut u64) -> u64 {
        let id = *next_id;
        *next_id += 1;
        self.live.insert(id, forward);
        id
    }

    /// Start one ad-hoc forward: resolve the instance name non-interactively,
    /// bind the listener. The route resolves on the forward's own thread.
    /// Returns the answer and the store entry to save.
    fn start(&mut self, req: &AddRequest, next_id: &mut u64) -> Result<(Added, Entry), ApiError> {
        let instance_key = match &req.instance {
            Some(name) => {
                let state = State::load().map_err(ApiError::internal)?;
                let key = crate::commands::resolve_instance_noninteractive(&state, name)
                    .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
                if req.service.is_none()
                    && let Some(why) = broker_port_refusal(&state, &key, req.container_port)
                {
                    return Err(ApiError::denied(why));
                }
                Some(key)
            }
            None => None,
        };
        let entry = Entry {
            dir: self.dir.clone(),
            instance: instance_key,
            service: req.service.clone(),
            address: Entry::address_of(req.bind),
            container_port: req.container_port,
            host_port: 0,
            machine: None,
        };
        let (id, entry) = self.start_adhoc(entry, req.host_port, next_id).map_err(|e| bind_failed(req.host_port, &e))?;
        let forward = &self.live[&id];
        let local = forward.status().local_addr.to_string();
        let target = route_label_or(forward, req);
        Ok((Added { id, local, target }, entry))
    }

    /// Bind `entry`'s forward on `host_port` (its saved `host_port` is
    /// ignored) and register it as ad-hoc. Returns its id and the entry with
    /// the bound host port.
    fn start_adhoc(&mut self, mut entry: Entry, host_port: HostPort, next_id: &mut u64) -> std::io::Result<(u64, Entry)> {
        entry.dir = self.dir.clone();
        let open = local_opener(port::resolver(self.dir.clone(), entry.instance.clone(), entry.service.clone(), entry.container_port));
        let probe = Box::new(port::listening_procs);
        let forward = Forward::start(ForwardSpec { bind: entry.bind(), host_port, open, probe })?;
        entry.host_port = forward.status().local_addr.port();
        let id = self.insert(forward, next_id);
        self.adhoc.insert(id, entry.clone());
        Ok((id, entry))
    }

    /// Drop the forward with `id` (its `Drop` kills the bridge/`exec`), `None`
    /// when this root has no such forward. A configured forward stays stopped
    /// until its owner restarts instead of coming straight back on the next
    /// sync. An ad-hoc one comes with its store entry; an open one has none.
    fn remove(&mut self, id: u64) -> Option<(Removed, Option<Entry>)> {
        let forward = self.live.remove(&id)?;
        let local = forward.status().local_addr.to_string();
        drop(forward);
        let entry = self.adhoc.remove(&id);
        self.opened.remove(&id);
        let configured = self.configured.iter().find(|(_, v)| v.id == id).map(|(c, _)| c.clone());
        if let Some(c) = &configured {
            self.configured.remove(c);
            self.suppressed.insert(c.clone());
        }
        Some((Removed { local, configured: configured.is_some() }, entry))
    }

    /// Reconcile configured forwards with the running instances: stop those
    /// no longer wanted, start the missing ones on their saved (or a newly
    /// allocated) host port, and save newly chosen ports. Config or state that
    /// doesn't load leaves everything as it is. Status lines go to `notes`.
    fn sync(&mut self, running: &BTreeSet<String>, next_id: &mut u64, notes: &mut Vec<String>) {
        let Some(project) = self.project.clone() else { return };
        let (Ok(config), Ok(mut state)) = (Config::load(&self.dir), State::load()) else { return };
        let wanted = wanted(&config, &state, running, &project);

        let gone: Vec<Configured> = self.configured.keys().filter(|c| !wanted.contains_key(c)).cloned().collect();
        for c in gone {
            if let Some(live) = self.configured.remove(&c) {
                self.live.remove(&live.id);
            }
        }
        self.failed.retain(|c| wanted.contains_key(c));
        self.suppressed.retain(|c| wanted.contains_key(c));

        // Stale saved ports would block allocation forever; prune before
        // computing reservations.
        let mut dirty = prune_saved(&mut state, &config, &project);
        let mut chosen = Vec::new();
        for (c, fp) in &wanted {
            if self.configured.contains_key(c) || self.suppressed.contains(c) || self.failed.contains(c) {
                continue;
            }
            // Noted once: `failed` holds it while it's wanted.
            if let (Owner::Instance(key), None) = (&c.owner, &fp.service)
                && let Some(why) = broker_port_refusal(&state, key, fp.port)
            {
                self.failed.insert(c.clone());
                notes.push(format!("forwardPorts `{}`: skipped: {why}", c.entry));
                continue;
            }
            match self.start_configured(&state, &project, c, fp, next_id) {
                Ok((id, port, label)) => {
                    let direct = fp.service.is_none().then_some(fp.port);
                    self.configured.insert(c.clone(), ConfiguredLive { id, direct });
                    notes.push(format!("forwarding 127.0.0.1:{port} -> {label}"));
                    // Later allocations in this pass must see it as taken.
                    dirty |= save_port(&mut state, &project, c, port);
                    chosen.push((c.clone(), port));
                }
                Err(msg) => {
                    self.failed.insert(c.clone());
                    notes.push(msg);
                }
            }
        }
        if !dirty {
            return;
        }
        // Applied to the current file so a `run`/`rm` since the load isn't undone.
        let saved = State::update(|fresh| {
            prune_saved(fresh, &config, &project);
            for (c, port) in &chosen {
                save_port(fresh, &project, c, *port);
            }
            Ok(())
        });
        if let Err(e) = saved {
            notes.push(format!("forwardPorts: {e:#}"));
        }
    }

    /// Bind the first free candidate host port for `c` and start its forward.
    /// Returns `(id, host port, route label)`.
    fn start_configured(
        &mut self,
        state: &State,
        project: &str,
        c: &Configured,
        fp: &ForwardPort,
        next_id: &mut u64,
    ) -> Result<(u64, u16, String), String> {
        let instance = match &c.owner {
            Owner::Instance(key) => Some(key.clone()),
            Owner::Global => None,
        };
        let saved = saved_port(state, project, c);
        let reserved = reserved_ports(state, project, c);
        for port in candidates(saved, fp.base(), &reserved) {
            let spec = ForwardSpec {
                bind: IpAddr::V4(Ipv4Addr::LOCALHOST),
                host_port: HostPort::Fixed(port),
                open: local_opener(port::resolver(self.dir.clone(), instance.clone(), fp.service.clone(), fp.port)),
                probe: Box::new(port::listening_procs),
            };
            match Forward::start(spec) {
                Ok(forward) => {
                    let label = match (&fp.service, &instance) {
                        (Some(svc), _) => format!("{svc}:{}", fp.port),
                        (None, Some(key)) => format!("{key}:{}", fp.port),
                        (None, None) => fp.port.to_string(),
                    };
                    return Ok((self.insert(forward, next_id), port, label));
                }
                Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
                Err(e) => return Err(format!("forwardPorts `{}`: port {port}: {}", c.entry, bind_reason(&e))),
            }
        }
        Err(format!("forwardPorts `{}`: no free host port from {} up", c.entry, fp.base()))
    }
}

/// Project a `ForwardStatus` into a wire row. Pure, so the state-string
/// mapping is unit-tested without a forwarder.
fn status_to_row(id: u64, dir: &Path, status: &ForwardStatus, configured: bool) -> ForwardRow {
    ForwardRow {
        id,
        dir: dir.to_path_buf(),
        local: status.local_addr.to_string(),
        target: status.route_label.clone(),
        process: status.process.clone(),
        state: state_string(&status.state),
        conns: status.open_conns,
        configured,
        open: false,
        machine: None,
    }
}

/// Why instance `key`'s container port `port` can't be forwarded: it's one of
/// its credential broker ports.
fn broker_port_refusal(state: &State, key: &str, port: u16) -> Option<String> {
    let info = state.instances.get(key)?;
    crate::credentials::instance::forward_refusal(&info.claims, info.intercept.as_ref(), key, port)
}

/// Whether `service` is a `global` one (its forward is shared by the config
/// root). An unknown service counts as isolated; its route reports the error.
fn is_global(config: &Config, service: &str) -> bool {
    config.resolve_service(service).is_ok_and(|s| s.spec.scope == ServiceScope::Global)
}

/// Whether `inst` belongs to this config root. Instances from before `project`
/// was recorded match on the sandbox name alone.
fn in_root(config: &Config, inst: &crate::state::Instance, project: &str) -> bool {
    config.sandboxes.contains_key(&inst.sandbox) && (inst.project.is_empty() || inst.project == project)
}

/// The configured forwards the running instances declare. Pure over
/// `(config, state, running)`. A global service's entry is keyed once for the
/// whole root; sandboxes that don't resolve are skipped.
fn wanted(
    config: &Config,
    state: &State,
    running: &BTreeSet<String>,
    project: &str,
) -> BTreeMap<Configured, ForwardPort> {
    let mut out = BTreeMap::new();
    for key in running {
        let Some(inst) = state.instances.get(key).filter(|i| in_root(config, i, project)) else { continue };
        let Ok(sandbox) = config.resolve_sandbox(&inst.sandbox) else { continue };
        for fp in sandbox.properties.forward_ports.unwrap_or_default() {
            let owner = match &fp.service {
                Some(svc) if is_global(config, svc) => Owner::Global,
                _ => Owner::Instance(key.clone()),
            };
            out.entry(Configured { owner, entry: fp.key() }).or_insert(fp);
        }
    }
    out
}

/// The host port saved for `c`, if any.
fn saved_port(state: &State, project: &str, c: &Configured) -> Option<u16> {
    match &c.owner {
        Owner::Instance(key) => state.instances.get(key)?.forwarded_ports.get(&c.entry).copied(),
        Owner::Global => state.global_forwarded_ports.get(project)?.get(&c.entry).copied(),
    }
}

/// Every saved host port except `c`'s own: what other forwards (running or
/// not, any config root) hold, so a stopped instance keeps its ports.
fn reserved_ports(state: &State, project: &str, c: &Configured) -> BTreeSet<u16> {
    let mut out = BTreeSet::new();
    for (key, inst) in &state.instances {
        for (entry, port) in &inst.forwarded_ports {
            if !(c.owner == Owner::Instance(key.clone()) && *entry == c.entry) {
                out.insert(*port);
            }
        }
    }
    for (root, entries) in &state.global_forwarded_ports {
        for (entry, port) in entries {
            if !(c.owner == Owner::Global && root == project && *entry == c.entry) {
                out.insert(*port);
            }
        }
    }
    out
}

/// Every host port `state.toml` saves for a configured forward of config
/// root `project` (its instances' and its global services'): what an open
/// forward there never binds, though the forward may be stopped now
/// ([`bind_open`]).
fn root_saved_ports(state: &State, project: &str) -> BTreeSet<u16> {
    let instances = state.instances.values().filter(|i| i.project == project).flat_map(|i| i.forwarded_ports.values());
    let global = state.global_forwarded_ports.get(project).into_iter().flat_map(|e| e.values());
    instances.chain(global).copied().collect()
}

/// Host ports to try, in order: the saved one, then `base` upward over
/// [`PREFER_SPAN`] ports, skipping ones other forwards hold.
fn candidates(saved: Option<u16>, base: u16, reserved: &BTreeSet<u16>) -> Vec<u16> {
    let scan = (base..=base.saturating_add(PREFER_SPAN - 1)).filter(|p| Some(*p) != saved && !reserved.contains(p));
    saved.into_iter().chain(scan).collect()
}

/// Record `port` as `c`'s host port. Returns whether state changed.
fn save_port(state: &mut State, project: &str, c: &Configured, port: u16) -> bool {
    let map = match &c.owner {
        Owner::Instance(key) => match state.instances.get_mut(key) {
            Some(inst) => &mut inst.forwarded_ports,
            None => return false,
        },
        Owner::Global => state.global_forwarded_ports.entry(project.to_string()).or_default(),
    };
    map.insert(c.entry.clone(), port) != Some(port)
}

/// Drop saved ports of entries this config root no longer declares, so they
/// stop reserving host ports. Only touches instances of this root whose
/// sandbox resolves; global entries only when every sandbox resolves (else an
/// entry might just be unreadable right now). Returns whether state changed.
fn prune_saved(state: &mut State, config: &Config, project: &str) -> bool {
    let mut changed = false;
    let mut global_keys = BTreeSet::new();
    let mut all_resolved = true;
    let mut per_sandbox: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
    for name in config.sandboxes.keys() {
        let Ok(sandbox) = config.resolve_sandbox(name) else {
            all_resolved = false;
            continue;
        };
        let keys = per_sandbox.entry(name).or_default();
        for fp in sandbox.properties.forward_ports.unwrap_or_default() {
            match &fp.service {
                Some(svc) if is_global(config, svc) => global_keys.insert(fp.key()),
                _ => keys.insert(fp.key()),
            };
        }
    }
    for inst in state.instances.values_mut() {
        if inst.project != project {
            continue;
        }
        let Some(keys) = per_sandbox.get(inst.sandbox.as_str()) else { continue };
        let before = inst.forwarded_ports.len();
        inst.forwarded_ports.retain(|entry, _| keys.contains(entry));
        changed |= inst.forwarded_ports.len() != before;
    }
    if all_resolved && let Some(entries) = state.global_forwarded_ports.get_mut(project) {
        let before = entries.len();
        entries.retain(|entry, _| global_keys.contains(entry));
        changed |= entries.len() != before;
        if entries.is_empty() {
            state.global_forwarded_ports.remove(project);
        }
    }
    changed
}

/// The row's state string: `"active"`, `"connecting"`, or `"error: …"`.
fn state_string(state: &ForwardState) -> String {
    match state {
        ForwardState::Active => "active".into(),
        ForwardState::Connecting => "connecting".into(),
        ForwardState::Error(reason) => format!("error: {reason}"),
    }
}

/// `forwards.add`'s error for a failed bind: the immediate, precise one worth
/// naming a port for.
fn bind_failed(host_port: HostPort, e: &std::io::Error) -> ApiError {
    let port = match host_port {
        HostPort::Fixed(p) | HostPort::Prefer(p) => p,
    };
    ApiError::bind_failed(format!("port {port}: {}", bind_reason(e)))
}

/// A short reason for a bind failure. `AddrInUse` is the common one and worth its
/// own phrasing (`address in use`); anything else falls back to the OS message.
fn bind_reason(e: &std::io::Error) -> String {
    if e.kind() == std::io::ErrorKind::AddrInUse {
        "address in use".into()
    } else {
        e.to_string()
    }
}

/// Split saved entries into those to restore and those whose instance is
/// gone from state (a service-only entry always stays, a remote one too: its
/// instance is in the machine's state, not this one's). Pure over `state`.
fn restorable(entries: Vec<Entry>, state: &State) -> (Vec<Entry>, Vec<Entry>) {
    entries.into_iter().partition(|e| {
        e.machine.is_some() || e.instance.as_ref().is_none_or(|key| state.instances.contains_key(key))
    })
}

/// A forward's best-effort `target:port` before its route resolves.
fn target_label(service: Option<&str>, instance: Option<&str>, port: u16) -> String {
    match (service, instance) {
        (Some(svc), _) => format!("{svc}:{port}"),
        (None, Some(instance)) => format!("{instance}:{port}"),
        (None, None) => port.to_string(),
    }
}

/// A saved forward for `serve.log`: `db:5432 on 127.0.0.1:15432`,
/// `box/web:3000 on 127.0.0.1:3000`.
fn describe(entry: &Entry) -> String {
    let target = target_label(entry.service.as_deref(), entry.instance.as_deref(), entry.container_port);
    let target = match &entry.machine {
        Some(machine) => format!("{machine}/{target}"),
        None => target,
    };
    format!("{target} on {}", std::net::SocketAddr::new(entry.bind(), entry.host_port))
}

/// The route label for `forwards.add`'s answer: the resolved label once the
/// supervisor has published one, else a best-effort `target:port` from the
/// request, `<machine>/target:port` for a remote one (the resolve runs on
/// the forward's thread, so it's usually empty this early).
fn route_label_or(forward: &Forward, req: &AddRequest) -> String {
    let label = forward.status().route_label;
    if !label.is_empty() {
        return label;
    }
    let target = target_label(req.service.as_deref(), req.instance.as_deref(), req.container_port);
    match &req.machine {
        Some(machine) => format!("{machine}/{target}"),
        None => target,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::devsbd::forward::{ForwardState, ForwardStatus};
    use crate::serve::api::Forwarding;
    use crate::state::Instance;
    use std::net::{Ipv4Addr, SocketAddr};
    use std::sync::Mutex;

    const CONFIG: &str = r#"
[services.db]
image = "postgres"

[services.redis]
image = "redis"
scope = "global"

[sandbox.api]
services = ["db", "redis"]
forwardPorts = [3000, "8080:3000", "db:5432", "redis:6379"]

[sandbox.web]
services = ["redis"]
forwardPorts = ["redis:6379"]
"#;

    fn inst(sandbox: &str, project: &str, saved: &[(&str, u16)]) -> Instance {
        let mut i: Instance = toml::from_str(&format!(
            "sandbox = \"{sandbox}\"\nproject = \"{project}\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n"
        ))
        .unwrap();
        i.forwarded_ports = saved.iter().map(|(k, p)| (k.to_string(), *p)).collect();
        i
    }

    fn cfg(owner: Owner, entry: &str) -> Configured {
        Configured { owner, entry: entry.into() }
    }

    fn fixture() -> (Config, State) {
        let config = Config::parse(CONFIG).unwrap();
        let mut state = State::default();
        state.instances.insert("api".into(), inst("api", "p1", &[("3000", 3001)]));
        state.instances.insert("api-2".into(), inst("api", "p1", &[]));
        state.instances.insert("web".into(), inst("web", "p1", &[]));
        state.instances.insert("elsewhere".into(), inst("api", "p2", &[("3000", 3000)]));
        (config, state)
    }

    #[test]
    fn wanted_per_instance_and_one_global_forward_per_root() {
        let (config, state) = fixture();
        let running: BTreeSet<String> = ["api", "web", "elsewhere"].map(String::from).into();
        let keys: Vec<Configured> = wanted(&config, &state, &running, "p1").into_keys().collect();
        let api = || Owner::Instance("api".into());
        assert_eq!(
            keys,
            vec![
                cfg(api(), "3000"),
                cfg(api(), "8080:3000"),
                cfg(api(), "db:5432"),
                // Declared by both `api` and `web`, forwarded once.
                cfg(Owner::Global, "redis:6379"),
            ]
        );
        // Another root's instance and stopped instances contribute nothing.
        assert!(wanted(&config, &state, &BTreeSet::new(), "p1").is_empty());
    }

    #[test]
    fn broker_ports_are_refused() {
        let (_, mut state) = fixture();
        let api = state.instances.get_mut("api").unwrap();
        api.claims = vec![crate::credentials::instance::InstanceClaim {
            kind: "sentry".into(),
            feature: "./s".into(),
            version: "v".into(),
            claim: "{}".into(),
            phantom: "p".into(),
            listeners: vec![crate::credentials::instance::Listener { port: 29000, upstream: "sentry.io".into() }],
            files: Vec::new(),
            git_hosts: Vec::new(),
        }];
        let why = broker_port_refusal(&state, "api", 29000).unwrap();
        assert!(why.contains("port 29000 of `api`"), "{why}");
        assert!(broker_port_refusal(&state, "api", 3000).is_none());
        assert!(broker_port_refusal(&state, "web", 29000).is_none());
    }

    #[test]
    fn running_keys_are_this_roots_and_unrecorded_running_instances() {
        let mut state = State::default();
        let mut add = |key: &str, container: &str, root: Option<&str>| {
            let mut i = inst("api", "p1", &[]);
            i.container = container.into();
            i.config_dir = root.map(PathBuf::from);
            state.instances.insert(key.into(), i);
        };
        add("a", "devsandbox-a", Some("/cfg/a"));
        add("b", "devsandbox-b", Some("/cfg/b"));
        add("old", "devsandbox-old", None);
        add("stopped", "devsandbox-stopped", Some("/cfg/a"));
        let running: Vec<String> = ["devsandbox-a", "devsandbox-b", "devsandbox-old"].map(String::from).into();
        let keys = running_keys(&state, &running, Path::new("/cfg/a"));
        assert_eq!(keys, ["a", "old"].map(String::from).into());
        assert!(running_keys(&state, &[], Path::new("/cfg/a")).is_empty());
    }

    #[test]
    fn candidates_try_saved_then_scan_up_skipping_reserved() {
        let reserved: BTreeSet<u16> = [3001, 3003].into();
        let got = candidates(Some(3002), 3000, &reserved);
        assert_eq!(&got[..4], &[3002, 3000, 3004, 3005]);
        assert_eq!(got.len(), PREFER_SPAN as usize - 2 - 1 + 1);
        assert_eq!(candidates(None, u16::MAX, &BTreeSet::new()), vec![u16::MAX]);
    }

    #[test]
    fn root_saved_ports_are_the_roots_instances_and_globals() {
        let (_, mut state) = fixture();
        state.global_forwarded_ports.entry("p1".into()).or_default().insert("redis:6379".into(), 6379);
        state.global_forwarded_ports.entry("p2".into()).or_default().insert("redis:6379".into(), 6380);
        assert_eq!(root_saved_ports(&state, "p1"), [3001, 6379].into());
        assert_eq!(root_saved_ports(&state, "p2"), [3000, 6380].into());
        assert!(root_saved_ports(&state, "p3").is_empty());
    }

    /// A fake `start` for [`bind_open`]: `taken` ports are in use, port 80
    /// is privileged, anything else binds (as the port asked for, 0 as
    /// 40000). Records every attempt.
    fn fake_start<'a>(attempts: &'a mut Vec<HostPort>, taken: &'a [u16]) -> impl FnMut(HostPort) -> std::io::Result<u16> + 'a {
        move |hp| {
            attempts.push(hp);
            match hp {
                HostPort::Fixed(p) | HostPort::Prefer(p) if taken.contains(&p) => Err(std::io::ErrorKind::AddrInUse.into()),
                HostPort::Fixed(80) | HostPort::Prefer(80) => Err(std::io::ErrorKind::PermissionDenied.into()),
                HostPort::Prefer(0) => Ok(40000),
                HostPort::Fixed(p) | HostPort::Prefer(p) => Ok(p),
            }
        }
    }

    #[test]
    fn bind_open_never_takes_a_reserved_port() {
        let reserved: BTreeSet<u16> = [3000, 3001].into();
        let mut attempts = Vec::new();
        assert_eq!(bind_open("web", 3000, false, &reserved, fake_start(&mut attempts, &[3002])).unwrap(), 3003);
        assert_eq!(attempts, vec![HostPort::Fixed(3002), HostPort::Fixed(3003)], "past reserved and taken");

        let mut attempts = Vec::new();
        assert_eq!(bind_open("web", 3000, false, &BTreeSet::new(), fake_start(&mut attempts, &[])).unwrap(), 3000);
        assert_eq!(attempts, vec![HostPort::Fixed(3000)]);

        let mut attempts = Vec::new();
        assert_eq!(bind_open("web", 80, false, &reserved, fake_start(&mut attempts, &[])).unwrap(), 40000, "privileged");
        assert_eq!(attempts, vec![HostPort::Fixed(80), HostPort::Prefer(0)]);

        let all: Vec<u16> = (3000..3000 + PREFER_SPAN).collect();
        let mut attempts = Vec::new();
        assert_eq!(bind_open("web", 3000, false, &reserved, fake_start(&mut attempts, &all)).unwrap(), 40000, "none free");

        let mut attempts = Vec::new();
        let (e, note) = bind_open("web", 3001, true, &reserved, fake_start(&mut attempts, &[])).unwrap_err();
        assert_eq!((e.code, e.message.as_str()), ("bind-failed", "port 3001: saved for a configured forward"));
        assert_eq!(
            note.as_deref(),
            Some("web: port 3001 is saved for a configured forward; an OAuth callback to it won't reach web")
        );
        assert!(attempts.is_empty(), "never tried");

        let mut attempts = Vec::new();
        assert_eq!(bind_open("web", 3005, true, &reserved, fake_start(&mut attempts, &[])).unwrap(), 3005);
        assert_eq!(attempts, vec![HostPort::Fixed(3005)]);
    }

    #[test]
    fn saved_and_reserved_ports_exclude_only_the_forward_itself() {
        let (_, mut state) = fixture();
        let api3000 = cfg(Owner::Instance("api".into()), "3000");
        let api2 = cfg(Owner::Instance("api-2".into()), "3000");
        assert_eq!(saved_port(&state, "p1", &api3000), Some(3001));
        assert_eq!(saved_port(&state, "p1", &api2), None);
        // `api-2` must not take `api`'s port, nor the other root's.
        assert_eq!(reserved_ports(&state, "p1", &api2), [3000, 3001].into());
        assert_eq!(reserved_ports(&state, "p1", &api3000), [3000].into());

        let global = cfg(Owner::Global, "redis:6379");
        assert!(save_port(&mut state, "p1", &global, 6379));
        assert!(!save_port(&mut state, "p1", &global, 6379), "unchanged");
        assert_eq!(saved_port(&state, "p1", &global), Some(6379));
        assert_eq!(saved_port(&state, "p2", &global), None);
        assert!(reserved_ports(&state, "p1", &api2).contains(&6379));
        assert!(!save_port(&mut state, "p1", &cfg(Owner::Instance("ghost".into()), "3000"), 1));
    }

    #[test]
    fn prune_drops_entries_no_longer_declared() {
        let (config, mut state) = fixture();
        state.instances.get_mut("api").unwrap().forwarded_ports.insert("4000".into(), 4000);
        state.global_forwarded_ports.entry("p1".into()).or_default().insert("redis:6379".into(), 6379);
        state.global_forwarded_ports.entry("p1".into()).or_default().insert("redis:1".into(), 1);
        assert!(prune_saved(&mut state, &config, "p1"));
        assert_eq!(state.instances["api"].forwarded_ports, BTreeMap::from([("3000".into(), 3001)]));
        assert_eq!(state.global_forwarded_ports["p1"], BTreeMap::from([("redis:6379".into(), 6379)]));
        // Other roots' instances are left alone.
        assert_eq!(state.instances["elsewhere"].forwarded_ports["3000"], 3000);
        assert!(!prune_saved(&mut state, &config, "p1"), "idempotent");
    }

    fn status(state: ForwardState, process: Option<&str>, conns: usize) -> ForwardStatus {
        ForwardStatus {
            local_addr: SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 3000),
            route_label: "api:3000".into(),
            state,
            open_conns: conns,
            idle_since: None,
            process: process.map(str::to_string),
        }
    }

    #[test]
    fn status_to_row_maps_state_strings() {
        let dir = Path::new("/cfg");
        let row = status_to_row(7, dir, &status(ForwardState::Active, Some("node (pid 412)"), 3), true);
        assert_eq!(row.id, 7);
        assert_eq!(row.dir, dir);
        assert_eq!(row.local, "127.0.0.1:3000");
        assert_eq!(row.target, "api:3000");
        assert_eq!(row.process.as_deref(), Some("node (pid 412)"));
        assert_eq!(row.state, "active");
        assert_eq!(row.conns, 3);
        assert!(row.configured);

        assert_eq!(status_to_row(1, dir, &status(ForwardState::Connecting, None, 0), false).state, "connecting");
        assert_eq!(
            status_to_row(1, dir, &status(ForwardState::Error("no such host db".into()), None, 0), false).state,
            "error: no such host db"
        );
        // Unknown process → None (rendered as `-` by the table).
        assert_eq!(status_to_row(1, dir, &status(ForwardState::Connecting, None, 0), false).process, None);
    }

    #[test]
    fn row_wire_shape() {
        let row = status_to_row(7, Path::new("/cfg"), &status(ForwardState::Active, None, 1), false);
        let v = serde_json::to_value(&row).unwrap();
        assert_eq!(
            v,
            serde_json::json!({
                "id": 7, "dir": "/cfg", "local": "127.0.0.1:3000", "target": "api:3000",
                "process": null, "state": "active", "conns": 1, "configured": false,
                "open": false,
            })
        );
        assert_eq!(serde_json::from_value::<ForwardRow>(v).unwrap(), row);
    }

    #[test]
    fn bind_reason_names_addr_in_use() {
        let in_use = std::io::Error::new(std::io::ErrorKind::AddrInUse, "os says busy");
        assert_eq!(bind_reason(&in_use), "address in use");
        let other = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "nope");
        assert_eq!(bind_reason(&other), "nope");
    }

    /// The `rows != last_rows` gate: identical rows produce no update; a change
    /// (a new state string) does.
    #[test]
    fn rows_changed_gate() {
        let dir = Path::new("/cfg");
        let a = vec![status_to_row(1, dir, &status(ForwardState::Connecting, None, 0), false)];
        let b = a.clone();
        assert_eq!(a, b, "identical rows compare equal (no update sent)");
        let c = vec![status_to_row(1, dir, &status(ForwardState::Active, None, 0), false)];
        assert_ne!(a, c, "a state change makes rows differ (update sent)");
    }

    fn quiet(_: &str) {}

    /// A registry on a store of its own (in a fresh temp dir).
    fn registry() -> (Registry, Arc<Mutex<Vec<Event>>>) {
        static N: AtomicUsize = AtomicUsize::new(0);
        let n = N.fetch_add(1, Ordering::Relaxed);
        registry_at(&tmp(&format!("store-{n}")).join("forwards.toml"))
    }

    /// `machines.toml` and the socket dir are the store's sibling and dir:
    /// a remote bridge fails at once unless the test binds the machine's
    /// link socket there.
    fn registry_at(store: &Path) -> (Registry, Arc<Mutex<Vec<Event>>>) {
        let events = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&events);
        let reg = Registry::spawn(
            quiet,
            store.to_path_buf(),
            store.with_file_name("machines.toml"),
            Arc::default(),
            Arc::new(Vec::new),
            store.parent().unwrap().to_path_buf(),
            Box::new(move |e| sink.lock().unwrap().push(e)),
        );
        (reg, events)
    }

    /// A fresh empty dir under the test tmp dir.
    fn tmp(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("devsandbox-fwd-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn request(dir: &Path, instance: Option<&str>, service: Option<&str>) -> AddRequest {
        AddRequest {
            dir: dir.to_path_buf(),
            instance: instance.map(String::from),
            service: service.map(String::from),
            bind: IpAddr::V4(Ipv4Addr::LOCALHOST),
            host_port: HostPort::Prefer(0),
            container_port: 5432,
            machine: None,
        }
    }

    /// An unknown instance is `not-found` (state is read, nothing else: no
    /// docker), a missing dir too; dropping the registry joins promptly.
    #[test]
    fn add_unknown_instance_or_dir_is_not_found_then_drop_joins() {
        let dir = std::env::temp_dir();
        let (reg, _) = registry();
        let h = reg.handle();
        // The name is chosen to be absurd: a machine that had it would start it.
        let e = h.add(request(&dir, Some("ghost-instance-xyz"), None)).unwrap_err();
        assert_eq!(e.code, "not-found", "{e:?}");
        let e = h.add(request(Path::new("/nonexistent/devsandbox-fwd"), None, Some("db"))).unwrap_err();
        assert_eq!(e.code, "not-found", "{e:?}");
        assert_eq!(h.rm(42).unwrap_err().code, "not-found");
        drop(reg);
        // Stopped: requests fail instead of hanging.
        assert_eq!(h.list(None, false).unwrap_err().code, "internal");
    }

    /// A service-only forward on a root without a config binds (the route
    /// fails on its own thread: config load, before any docker), lists under
    /// its canonical root, counts as a holder, announces `Changed`, and goes
    /// away on `rm`.
    #[test]
    fn add_list_rm_round_trip_counts_holders_and_announces_changes() {
        let dir = std::env::temp_dir().join(format!("devsandbox-fwd-registry-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let canonical = dir.canonicalize().unwrap();
        let (reg, events) = registry();
        let h = reg.handle();

        let added = h.add(request(&dir, None, Some("db"))).unwrap();
        assert_eq!(added.target, "db:5432");
        assert!(added.local.starts_with("127.0.0.1:"), "{added:?}");
        let rows = h.list(Some(dir.clone()), false).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!((rows[0].id, &rows[0].dir, rows[0].configured), (added.id, &canonical, false));
        // Ids only: the row's state moves on its own (the resolver fails here,
        // no config) between the two lists.
        let ids = |rows: &[ForwardRow]| rows.iter().map(|r| r.id).collect::<Vec<_>>();
        assert_eq!(ids(&h.list(None, false).unwrap()), ids(&rows));
        assert!(h.list(Some(PathBuf::from("/nonexistent/other")), false).unwrap().is_empty());
        // A second add gets the next daemon-wide id.
        let second = h.add(request(&dir, None, Some("db"))).unwrap();
        assert_eq!(second.id, added.id + 1);
        // The poll after each command counts them; a request behind it waits.
        h.list(None, false).unwrap();
        assert_eq!(reg.active(), 2);
        assert!(events.lock().unwrap().contains(&Event::Changed));

        events.lock().unwrap().clear();
        assert_eq!(h.rm(added.id).unwrap(), Removed { local: added.local.clone(), configured: false });
        assert_eq!(h.rm(added.id).unwrap_err().code, "not-found");
        assert_eq!(h.list(None, false).unwrap().len(), 1);
        assert_eq!(reg.active(), 1);
        assert!(events.lock().unwrap().contains(&Event::Changed));
        drop(reg);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A fixed host port another listener holds is `bind-failed`.
    #[test]
    fn a_taken_fixed_port_is_bind_failed() {
        let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = taken.local_addr().unwrap().port();
        let (reg, _) = registry();
        let req = AddRequest { host_port: HostPort::Fixed(port), ..request(&std::env::temp_dir(), None, Some("db")) };
        let e = reg.handle().add(req).unwrap_err();
        assert_eq!((e.code, e.message), ("bind-failed", format!("port {port}: address in use")));
        assert!(reg.handle().list(None, false).unwrap().is_empty());
        assert_eq!(reg.active(), 0);
    }

    #[test]
    fn open_forwards_expire_after_the_idle_time_from_the_later_of_close_and_reuse() {
        let t0 = Instant::now();
        let at = |s: u64| t0 + Duration::from_secs(s);
        let idle = OPEN_FORWARD_IDLE.as_secs();
        assert!(!open_expired(None, t0, at(idle * 10)), "a connection is open");
        assert!(!open_expired(Some(t0), t0, at(idle - 1)));
        assert!(open_expired(Some(t0), t0, at(idle)));
        assert!(!open_expired(Some(t0), at(5), at(idle)), "reused since");
        assert!(!open_expired(Some(at(5)), t0, at(idle)), "a connection closed since");
        assert!(open_expired(Some(at(5)), at(3), at(idle + 5)));
        // A clock before `touched` (never in practice) isn't expired.
        assert!(!open_expired(Some(at(9)), at(9), t0));
    }

    fn open_req(dir: &Path, port: u16, callback: bool) -> OpenRequest {
        // An instance no state has: the forward binds anyway, its route errors
        // on its own thread.
        OpenRequest { machine: None, dir: dir.to_path_buf(), instance: "ghost-open-xyz".into(), container_port: port, callback }
    }

    /// A port free right now (bound and released).
    fn free_port() -> u16 {
        std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
    }

    /// A callback open (`Fixed`) of `req(port)` on a port that was free a
    /// moment ago: another test may take it in between, so a `bind-failed`
    /// is retried with a fresh port. The port it bound, and the answer.
    fn first_callback(h: &Handle, req: impl Fn(u16) -> OpenRequest) -> (u16, OpenForward) {
        for _ in 0..5 {
            let port = free_port();
            match h.open_forward(req(port)) {
                Err(e) if e.code == "bind-failed" => continue,
                answer => return (port, answer.unwrap()),
            }
        }
        panic!("no free port bound in 5 tries");
    }

    /// A callback open binds its own port, makes an `open` row and no store
    /// entry; the next callback and a direct open of the same instance port
    /// reuse it. A direct open whose port is taken walks up, and a callback
    /// won't reuse that one (wrong host port), so it tries its own port and
    /// fails. `rm` stops one. The first callback's port is picked free and
    /// may be taken before it binds ([`first_callback`] retries); after that
    /// no port is freed for a later bind, so a parallel test can't take it.
    #[test]
    fn open_forwards_reuse_by_instance_port_never_persist_and_rm() {
        let root = tmp("open-root");
        let store = tmp("open").join("forwards.toml");
        let (reg, _) = registry_at(&store);
        let h = reg.handle();

        let (port, callback) = first_callback(&h, |port| open_req(&root, port, true));
        assert_eq!(callback, OpenForward { host_port: port, reused: false });
        let rows = h.list(None, false).unwrap();
        assert_eq!(rows.len(), 1, "{rows:?}");
        assert!(rows[0].open && !rows[0].configured, "{rows:?}");
        assert_eq!(port_of(&rows[0].local), port);
        assert!(!store.exists() || forward_store::load(&store).unwrap().is_empty(), "never persisted");
        assert_eq!(reg.active(), 1);
        let reused = OpenForward { host_port: port, reused: true };
        assert_eq!(h.open_forward(open_req(&root, port, true)).unwrap(), reused);
        assert_eq!(h.open_forward(open_req(&root, port, false)).unwrap(), reused, "direct reuses it too");

        let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let other = held.local_addr().unwrap().port();
        let direct = h.open_forward(open_req(&root, other, false)).unwrap();
        assert!(!direct.reused);
        assert_ne!(direct.host_port, other, "taken: Prefer walks up");
        let again = h.open_forward(open_req(&root, other, false)).unwrap();
        assert_eq!(again, OpenForward { host_port: direct.host_port, reused: true });
        let e = h.open_forward(open_req(&root, other, true)).unwrap_err();
        assert_eq!(e.code, "bind-failed", "a callback never reuses a forward on another host port");
        let rows = h.list(None, false).unwrap();
        assert_eq!(rows.len(), 2, "{rows:?}");
        assert!(rows.iter().all(|r| r.open));

        let id = rows.iter().find(|r| port_of(&r.local) == port).unwrap().id;
        let local = format!("127.0.0.1:{port}");
        assert_eq!(h.rm(id).unwrap(), Removed { local, configured: false });
        assert_eq!(h.list(None, false).unwrap().len(), 1);
        drop(held);
        assert!(!store.exists() || forward_store::load(&store).unwrap().is_empty());
        drop(reg);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A callback port someone else holds is `bind-failed`, and a status
    /// line says the callback won't arrive.
    #[test]
    fn a_taken_callback_port_is_bind_failed_with_a_status_line() {
        let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = taken.local_addr().unwrap().port();
        let (reg, events) = registry();
        let e = reg.handle().open_forward(open_req(&std::env::temp_dir(), port, true)).unwrap_err();
        assert_eq!((e.code, e.message), ("bind-failed", format!("port {port}: address in use")));
        let want = format!("ghost-open-xyz: port {port} is taken; an OAuth callback to it won't reach ghost-open-xyz");
        assert!(events.lock().unwrap().contains(&Event::Status(want)));
        assert!(reg.handle().list(None, false).unwrap().is_empty());
        assert_eq!(
            reg.handle().open_forward(open_req(Path::new("/nonexistent/devsandbox-fwd"), port, false)).unwrap_err().code,
            "not-found"
        );
    }

    /// A reserved port (saved for a configured forward of the root) is
    /// never an open forward's: a direct open walks past it, a callback on
    /// it is refused with a status line, unless a forward of that instance
    /// port is live on it already (reuse comes first).
    #[test]
    fn open_forwards_never_take_a_reserved_port() {
        let root = tmp("open-reserved");
        let mut r = Root::new(root.clone());
        let (mut next_id, now) = (1, Instant::now());
        let reserved: BTreeSet<u16> = [free_port()].into();
        let p = *reserved.first().unwrap();
        let (e, note) = r.open(&open_req(&root, p, true), &reserved, &mut next_id, now).unwrap_err();
        assert_eq!(e.code, "bind-failed");
        assert!(note.unwrap().contains(&format!("port {p} is saved for a configured forward")));
        let direct = r.open(&open_req(&root, p, false), &reserved, &mut next_id, now).unwrap();
        assert!(!direct.reused && direct.host_port != p, "{direct:?}");

        let (q, first) = (0..5)
            .find_map(|_| {
                let q = free_port();
                r.open(&open_req(&root, q, true), &BTreeSet::new(), &mut next_id, now).ok().map(|f| (q, f))
            })
            .expect("no free port bound in 5 tries");
        assert_eq!(first.host_port, q);
        let now_reserved: BTreeSet<u16> = [q].into();
        let again = r.open(&open_req(&root, q, true), &now_reserved, &mut next_id, now).unwrap();
        assert_eq!(again, OpenForward { host_port: q, reused: true }, "live on it already: reused");
        drop(r);
        let _ = std::fs::remove_dir_all(&root);
    }

    fn saved(dir: &Path, instance: Option<&str>, host_port: u16) -> Entry {
        Entry {
            dir: dir.to_path_buf(),
            instance: instance.map(String::from),
            service: Some("db".into()),
            address: None,
            container_port: 5432,
            host_port,
            machine: None,
        }
    }

    fn port_of(local: &str) -> u16 {
        local.parse::<std::net::SocketAddr>().unwrap().port()
    }

    #[test]
    fn restorable_drops_only_entries_of_removed_instances() {
        let mut state = State::default();
        state.instances.insert("api".into(), inst("api", "p1", &[]));
        let dir = Path::new("/cfg");
        let (keep, dropped) =
            restorable(vec![saved(dir, Some("api"), 1), saved(dir, Some("gone"), 2), saved(dir, None, 3)], &state);
        assert_eq!(keep, vec![saved(dir, Some("api"), 1), saved(dir, None, 3)]);
        assert_eq!(dropped, vec![saved(dir, Some("gone"), 2)]);
        assert_eq!(describe(&saved(dir, None, 3)), "db:5432 on 127.0.0.1:3");
        // A machine's instance isn't in this host's state.
        let far = Entry { machine: Some("box".into()), service: None, ..saved(dir, Some("gone"), 4) };
        assert_eq!(restorable(vec![far.clone()], &state), (vec![far.clone()], vec![]));
        assert_eq!(describe(&far), "box/gone:5432 on 127.0.0.1:4");
    }

    const MACHINES: &str = "[machine.box]\ntarget = \"me@box.invalid\"\nroots = [\"/far/cfg\"]\n";

    /// A forward into `box`'s `web` (a root that doesn't exist here: it's
    /// never resolved locally).
    fn remote_request() -> AddRequest {
        AddRequest { machine: Some("box".into()), ..request(Path::new("/far/cfg"), Some("web"), None) }
    }

    fn remote_saved(host_port: u16) -> Entry {
        Entry { machine: Some("box".into()), service: None, ..saved(Path::new("/far/cfg"), Some("web"), host_port) }
    }

    #[test]
    fn a_remote_add_needs_a_registered_machine() {
        let store = tmp("remote-unknown").join("forwards.toml");
        let (reg, _) = registry_at(&store);
        let e = reg.handle().add(remote_request()).unwrap_err();
        assert_eq!((e.code, e.message.as_str()), ("not-found", "no machine named `box` (devsandbox machine ls)"));
        assert!(reg.handle().list(None, true).unwrap().is_empty());
        assert_eq!(forward_store::load(&store).unwrap(), vec![]);
    }

    /// A remote forward binds here, lists only with `machines` (whatever
    /// `dir`), counts as a holder, persists with its machine, comes back on
    /// its port in a successor, and goes away on `rm`.
    #[test]
    fn remote_forwards_list_persist_restore_and_rm() {
        let store = tmp("remote").join("forwards.toml");
        std::fs::write(store.with_file_name("machines.toml"), MACHINES).unwrap();
        let (reg, _) = registry_at(&store);
        let h = reg.handle();
        let added = h.add(remote_request()).unwrap();
        // The bridge never answers (no header): the best effort stays.
        assert_eq!(added.target, "box/web:5432");
        assert!(h.list(None, false).unwrap().is_empty(), "local only by default");
        let rows = h.list(Some(std::env::temp_dir()), true).unwrap();
        assert_eq!(rows.len(), 1, "{rows:?}");
        let row = &rows[0];
        assert_eq!(
            (row.id, row.dir.as_path(), row.local.as_str(), row.target.as_str(), row.machine.as_deref(), row.configured),
            (added.id, Path::new("/far/cfg"), added.local.as_str(), "box/web:5432", Some("box"), false)
        );
        assert_eq!(reg.active(), 1);
        let port = port_of(&added.local);
        assert_eq!(forward_store::load(&store).unwrap(), vec![remote_saved(port)]);
        drop(reg);

        let (successor, _) = registry_at(&store);
        let h = successor.handle();
        let rows = h.list(None, true).unwrap();
        assert_eq!(rows.len(), 1, "{rows:?}");
        assert_eq!((rows[0].local.as_str(), rows[0].machine.as_deref()), (added.local.as_str(), Some("box")));
        assert_eq!(forward_store::load(&store).unwrap(), vec![remote_saved(port)], "restored as saved");
        assert_eq!(h.rm(rows[0].id).unwrap(), Removed { local: added.local.clone(), configured: false });
        assert!(h.list(None, true).unwrap().is_empty());
        assert_eq!(successor.active(), 0);
        assert_eq!(forward_store::load(&store).unwrap(), vec![]);
    }

    /// A saved remote forward of a machine no longer registered isn't
    /// restored and leaves the store.
    #[test]
    fn restore_drops_forwards_of_unregistered_machines() {
        let store = tmp("remote-restore").join("forwards.toml");
        forward_store::update(&store, |e| e.push(remote_saved(1))).unwrap();
        let (reg, _) = registry_at(&store);
        assert!(reg.handle().list(None, true).unwrap().is_empty());
        assert_eq!(forward_store::load(&store).unwrap(), vec![]);
    }

    /// `machine rm`: what each sync runs first drops the machine's forwards
    /// and their store entries, and only theirs; an inbound neighbor's go
    /// when it does. Called on a [`Daemon`] directly: a whole sync also
    /// reconciles this host's real state.
    #[test]
    fn a_removed_machines_forwards_are_dropped() {
        let store = tmp("remote-drop").join("forwards.toml");
        let machines_toml = store.with_file_name("machines.toml");
        let two = format!("{MACHINES}[machine.other]\ntarget = \"other.invalid\"\n");
        std::fs::write(&machines_toml, &two).unwrap();
        let changed = Arc::new(AtomicUsize::new(0));
        let seen = Arc::clone(&changed);
        let on_event: OnEvent = Box::new(move |e| {
            if e == Event::Changed {
                seen.fetch_add(1, Ordering::Relaxed);
            }
        });
        let inbound: Arc<Neighbors> = Arc::default();
        let routed_now: Arc<Mutex<Vec<String>>> = Arc::default();
        let names = Arc::clone(&routed_now);
        let routed: RoutedNames = Arc::new(move || names.lock().unwrap().clone());
        let known = Known { registry: machines_toml.clone(), inbound: Arc::clone(&inbound), routed };
        let mut d = Daemon::new(quiet, store.clone(), known, tmp("remote-drop-sock"), on_event, Arc::default());
        // A routed machine's forward, while it's routed.
        let into_r = || AddRequest { machine: Some("r".into()), ..remote_request() };
        assert_eq!(d.add(into_r()).unwrap_err().code, "not-found", "no routed `r` yet");
        routed_now.lock().unwrap().push("r".into());
        d.add(into_r()).unwrap();
        d.drop_unregistered();
        assert_eq!(d.rows(None, true).len(), 1, "a routed machine's forward lasts while it's routed");
        routed_now.lock().unwrap().clear();
        d.drop_unregistered();
        assert!(d.rows(None, true).is_empty(), "gone with it");
        let into_nb = || AddRequest { machine: Some("nb".into()), ..remote_request() };
        assert_eq!(d.add(into_nb()).unwrap_err().code, "not-found", "no neighbor `nb` yet");
        let up = inbound.announce("nb", "v", false, Default::default());
        d.add(into_nb()).unwrap();
        d.drop_unregistered();
        assert_eq!(d.rows(None, true).len(), 1, "a neighbor's forward lasts while it's up");
        drop(up);
        d.drop_unregistered();
        assert!(d.rows(None, true).is_empty(), "gone with it");
        assert!(forward_store::load(&store).unwrap().is_empty());

        let a = d.add(remote_request()).unwrap();
        let b = d.add(AddRequest { machine: Some("other".into()), ..remote_request() }).unwrap();
        d.poll();
        assert_eq!(d.rows(None, true).len(), 2);

        d.drop_unregistered();
        assert_eq!(d.rows(None, true).len(), 2, "both still registered");
        std::fs::write(&machines_toml, two.replace(MACHINES, "")).unwrap();
        let before = changed.load(Ordering::Relaxed);
        d.drop_unregistered();
        d.poll();
        let rows = d.rows(None, true);
        assert_eq!(rows.iter().map(|r| r.id).collect::<Vec<_>>(), [b.id]);
        assert_ne!(rows[0].id, a.id);
        assert_eq!(changed.load(Ordering::Relaxed), before + 1);
        let left = forward_store::load(&store).unwrap();
        assert_eq!(left.len(), 1);
        assert_eq!(left[0].machine.as_deref(), Some("other"));
        // A registry that doesn't load drops nothing.
        std::fs::write(&machines_toml, "not toml [").unwrap();
        d.drop_unregistered();
        assert_eq!(d.rows(None, true).len(), 1);
    }

    /// Every machine, whatever its kind, is reached from the socket dir, a
    /// `TUNNEL` stream; the request is the forward's.
    #[test]
    fn every_machine_tunnels_over_its_link() {
        let dir = Path::new("/run/devsandbox");
        let request = tunnel::Request { root: "/far/cfg".into(), instance: Some("web".into()), service: None, port: 5432 };
        assert_eq!(via(dir, request.clone()), tunnel::Via::Fleet { dir: dir.into(), request });
    }

    /// An open delivered from `box` for its `web`'s `port`.
    fn remote_open(port: u16, callback: bool) -> OpenRequest {
        OpenRequest {
            machine: Some("box".into()),
            dir: "/far/cfg".into(),
            instance: "web".into(),
            container_port: port,
            callback,
        }
    }

    #[test]
    fn an_open_into_an_unknown_machine_is_not_found() {
        let store = tmp("remote-open-unknown").join("forwards.toml");
        let (reg, _) = registry_at(&store);
        let e = reg.handle().open_forward(remote_open(3000, false)).unwrap_err();
        assert_eq!((e.code, e.message.as_str()), ("not-found", "no machine named `box` (devsandbox machine ls)"));
        assert!(reg.handle().list(None, true).unwrap().is_empty());
    }

    /// An open into a machine's instance is a remote `open` row, never in
    /// the store, reused like a local one (a user's ad-hoc remote forward
    /// too, a callback only on its own host port); `rm` leaves the store
    /// alone. As above, the first port is retried if taken, and no port is
    /// freed for a later bind.
    #[test]
    fn remote_open_forwards_reuse_never_persist_and_rm() {
        let store = tmp("remote-open").join("forwards.toml");
        std::fs::write(store.with_file_name("machines.toml"), MACHINES).unwrap();
        let (reg, events) = registry_at(&store);
        let h = reg.handle();
        let unsaved = || !store.exists() || forward_store::load(&store).unwrap().is_empty();

        let (port, callback) = first_callback(&h, |port| remote_open(port, true));
        assert_eq!(callback, OpenForward { host_port: port, reused: false });
        let rows = h.list(None, true).unwrap();
        assert_eq!(rows.len(), 1, "{rows:?}");
        let row = &rows[0];
        assert_eq!(
            (row.open, row.configured, row.machine.as_deref(), row.dir.as_path(), port_of(&row.local)),
            (true, false, Some("box"), Path::new("/far/cfg"), port)
        );
        assert_eq!(row.target, format!("box/web:{port}"));
        assert!(h.list(None, false).unwrap().is_empty(), "remote: only with `machines`");
        assert!(unsaved(), "never persisted");
        assert_eq!(reg.active(), 1);
        let reused = OpenForward { host_port: port, reused: true };
        assert_eq!(h.open_forward(remote_open(port, true)).unwrap(), reused);
        assert_eq!(h.open_forward(remote_open(port, false)).unwrap(), reused, "direct reuses it too");
        let elsewhere = OpenRequest { dir: "/far/other".into(), ..remote_open(port, false) };
        let other_root = h.open_forward(elsewhere).unwrap();
        assert!(!other_root.reused && other_root.host_port != port, "another root's instance: {other_root:?}");

        let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let taken = held.local_addr().unwrap().port();
        let direct = h.open_forward(remote_open(taken, false)).unwrap();
        assert!(!direct.reused);
        assert_ne!(direct.host_port, taken, "taken: Prefer walks up");
        assert_eq!(h.open_forward(remote_open(taken, false)).unwrap(), OpenForward { host_port: direct.host_port, reused: true });
        let e = h.open_forward(remote_open(taken, true)).unwrap_err();
        assert_eq!((e.code, e.message), ("bind-failed", format!("port {taken}: address in use")));
        let want = format!("web: port {taken} is taken; an OAuth callback to it won't reach web");
        assert!(events.lock().unwrap().contains(&Event::Status(want)));

        // A user's ad-hoc forward of the same instance port answers an open.
        let added = h.add(remote_request()).unwrap();
        let saved_now = forward_store::load(&store).unwrap();
        assert_eq!(saved_now, vec![remote_saved(port_of(&added.local))]);
        assert_eq!(h.open_forward(remote_open(5432, false)).unwrap(), OpenForward { host_port: port_of(&added.local), reused: true });

        let rows = h.list(None, true).unwrap();
        assert_eq!(rows.iter().filter(|r| r.open).count(), 3, "{rows:?}");
        let id = rows.iter().find(|r| port_of(&r.local) == port).unwrap().id;
        assert_eq!(h.rm(id).unwrap(), Removed { local: format!("127.0.0.1:{port}"), configured: false });
        assert_eq!(h.list(None, true).unwrap().len(), 3);
        assert_eq!(forward_store::load(&store).unwrap(), saved_now, "an open forward's rm touches no entry");
        drop(held);
        drop(reg);

        let (successor, _) = registry_at(&store);
        let rows = successor.handle().list(None, true).unwrap();
        assert_eq!(rows.len(), 1, "only the ad-hoc one is restored: {rows:?}");
        assert!(!rows[0].open);
    }

    /// A remote open forward stops after the idle time (an ad-hoc one
    /// doesn't), and with its machine, never touching the store. On a
    /// [`Daemon`] directly, the sweep given a later `now`.
    #[test]
    fn remote_open_forwards_expire_and_go_with_their_machine() {
        let store = tmp("remote-open-drop").join("forwards.toml");
        let machines_toml = store.with_file_name("machines.toml");
        std::fs::write(&machines_toml, MACHINES).unwrap();
        let known = Known { registry: machines_toml.clone(), inbound: Arc::default(), routed: Arc::new(Vec::new) };
        let mut d =
            Daemon::new(quiet, store.clone(), known, tmp("remote-open-drop-sock"), Box::new(|_| {}), Arc::default());
        let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let taken = held.local_addr().unwrap().port();
        let first = d.open(remote_open(taken, false)).unwrap();
        let adhoc = d.add(remote_request()).unwrap();
        let ids = |d: &Daemon| d.rows(None, true).into_iter().map(|r| r.id).collect::<Vec<_>>();
        assert_eq!(ids(&d).len(), 2);

        d.expire_open(Instant::now() + OPEN_FORWARD_IDLE - Duration::from_secs(60));
        assert_eq!(ids(&d).len(), 2, "not idle long enough");
        d.expire_open(Instant::now() + OPEN_FORWARD_IDLE);
        assert_eq!(ids(&d), [adhoc.id], "the open one expired");
        let saved_now = forward_store::load(&store).unwrap();
        assert_eq!(saved_now.len(), 1);

        let again = d.open(remote_open(taken, false)).unwrap();
        assert!(!again.reused, "{again:?} after {first:?}");
        d.remove(adhoc.id).unwrap();
        assert!(forward_store::load(&store).unwrap().is_empty());
        std::fs::remove_file(&store).unwrap();
        std::fs::write(&machines_toml, "").unwrap();
        d.drop_unregistered();
        assert!(d.rows(None, true).is_empty(), "gone with its machine");
        assert!(!store.exists(), "no store write for an open forward");
        drop(held);
    }

    /// A forward into an ssh machine dials its link's socket (a `TUNNEL`
    /// stream) on every spawn: the machine's refusal is the row's error.
    #[test]
    fn a_forward_into_an_ssh_machine_dials_its_link() {
        let base = tmp("remote-link");
        let store = base.join("forwards.toml");
        std::fs::write(store.with_file_name("machines.toml"), MACHINES).unwrap();
        let listener = std::os::unix::net::UnixListener::bind(super::super::endpoint::fleet_socket(&base, "box")).unwrap();
        let (seen, got) = mpsc::channel();
        std::thread::spawn(move || {
            for s in listener.incoming() {
                let Ok(mut s) = s else { return };
                let mut ch = [0u8; 1];
                if std::io::Read::read_exact(&mut s, &mut ch).is_err() || ch[0] != crate::devsbd::proto::channel::TUNNEL {
                    continue;
                }
                let request = super::super::fleet::tunnel::read_request(&mut s);
                let _ = std::io::Write::write_all(&mut s, tunnel::Header::Error { error: "no instance `web`".into() }.line().as_bytes());
                let _ = seen.send(request);
            }
        });
        let (reg, _) = registry_at(&store);
        let h = reg.handle();
        let added = h.add(remote_request()).unwrap();
        let want = tunnel::Request { root: "/far/cfg".into(), instance: Some("web".into()), service: None, port: 5432 };
        assert_eq!(got.recv_timeout(Duration::from_secs(10)).unwrap(), Ok(want));
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        loop {
            let rows = h.list(None, true).unwrap();
            if rows.iter().any(|r| r.id == added.id && r.state == "error: no instance `web`") {
                break;
            }
            assert!(std::time::Instant::now() < deadline, "{rows:?}");
            std::thread::sleep(Duration::from_millis(50));
        }
        drop(reg);
        let _ = std::fs::remove_dir_all(&base);
    }

    /// An add saves the bound port (an automatic one here), an rm removes only
    /// its entry, stopping the registry leaves the file alone, and a successor
    /// on the same store brings the forward back on the same host port.
    #[test]
    fn adds_persist_rm_removes_its_entry_and_a_successor_restores_them() {
        let root = tmp("persist-root");
        let canonical = root.canonicalize().unwrap();
        let store = tmp("persist").join("forwards.toml");
        let (reg, _) = registry_at(&store);
        let h = reg.handle();
        let a = h.add(request(&root, None, Some("db"))).unwrap();
        let b = h.add(request(&root, None, Some("db"))).unwrap();
        assert_eq!(
            forward_store::load(&store).unwrap(),
            vec![saved(&canonical, None, port_of(&a.local)), saved(&canonical, None, port_of(&b.local))]
        );
        h.rm(a.id).unwrap();
        assert_eq!(forward_store::load(&store).unwrap(), vec![saved(&canonical, None, port_of(&b.local))]);

        let text = std::fs::read_to_string(&store).unwrap();
        drop(reg);
        assert_eq!(std::fs::read_to_string(&store).unwrap(), text, "stopping is not a removal");

        let (successor, _) = registry_at(&store);
        let rows = successor.handle().list(None, false).unwrap();
        assert_eq!(rows.len(), 1, "{rows:?}");
        assert_eq!((rows[0].local.as_str(), &rows[0].dir, rows[0].configured), (b.local.as_str(), &canonical, false));
        assert_eq!(std::fs::read_to_string(&store).unwrap(), text, "restored as saved: no rewrite");
        // The restored forward is removable like any other.
        successor.handle().rm(rows[0].id).unwrap();
        assert_eq!(forward_store::load(&store).unwrap(), vec![]);
        drop(successor);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A saved port that's taken now: restored on an automatic port, which
    /// the store then records. An entry whose instance is gone from state is
    /// dropped (the name is chosen to be absurd, as above).
    #[test]
    fn restore_falls_back_from_a_taken_port_and_drops_removed_instances() {
        let root = tmp("restore-root").canonicalize().unwrap();
        let store = tmp("restore").join("forwards.toml");
        let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = taken.local_addr().unwrap().port();
        let ghost = saved(&root, Some("ghost-instance-xyz"), 1);
        forward_store::update(&store, |e| e.extend([saved(&root, None, port), ghost])).unwrap();

        let (reg, _) = registry_at(&store);
        let rows = reg.handle().list(None, false).unwrap();
        assert_eq!(rows.len(), 1, "{rows:?}");
        let now = port_of(&rows[0].local);
        assert_ne!(now, port);
        assert_eq!(forward_store::load(&store).unwrap(), vec![saved(&root, None, now)]);
        drop(reg);
        drop(taken);
        let _ = std::fs::remove_dir_all(&root);
    }
}