lager-net 0.8.0

First-class Rust client for Lager box nets: drive power supplies, batteries, e-loads, GPIO, ADC, DAC, SPI, I2C, UART and more from cargo tests.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
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
//! Blocking client for the Lager box HTTP API (default feature).

use std::time::Duration;

use serde_json::Value;

use crate::auth::{self, GatewayAuth};
use crate::chunked::ChunkedReader;
use crate::error::{Error, Result};
use crate::nets::adc::Adc;
use crate::nets::arm::Arm;
use crate::nets::battery::Battery;
use crate::nets::ble::Ble;
use crate::nets::blufi::Blufi;
use crate::nets::custom::CustomNet;
use crate::nets::dac::Dac;
use crate::nets::debug::DebugNet;
use crate::nets::dfu::Dfu;
use crate::nets::eload::Eload;
use crate::nets::energy::EnergyAnalyzer;
use crate::nets::gpio::Gpio;
use crate::nets::hsm::Hsm;
use crate::nets::i2c::I2c;
use crate::nets::router::Router;
use crate::nets::scope::Scope;
use crate::nets::solar::Solar;
use crate::nets::spi::Spi;
use crate::nets::supply::Supply;
use crate::nets::thermocouple::Thermocouple;
use crate::nets::usb::UsbPort;
use crate::nets::watt::WattMeter;
use crate::nets::webcam::Webcam;
use crate::nets::wifi::Wifi;
use crate::wire::{
    self, BoxLock, BoxStatus, Health, HttpRequest, Method, NetRecord, NetState, Op, SafetyLimits,
    Timeout, UsbDeviceFilter, UsbDeviceInfo,
};
use crate::BOX_HOST_ENV;

/// A connection to one Lager box, over blocking HTTP.
///
/// Cheap to construct: no network traffic happens until the first call.
/// Net handles borrow the client, so a typical test creates one `LagerBox`
/// and any number of handles from it.
///
/// ```no_run
/// use lager::LagerBox;
///
/// fn main() -> lager::Result<()> {
///     let lager = LagerBox::connect("192.168.1.42")?;
///     let supply = lager.supply("supply1");
///     supply.set_voltage(3.3)?;
///     supply.enable()?;
///     let v = lager.adc("vbat_sense").read()?;
///     assert!((v - 3.3).abs() < 0.1);
///     supply.disable()
/// }
/// ```
pub struct LagerBox {
    base: String,
    debug_base: String,
    agent: ureq::Agent,
    default_timeout: Duration,
    auth: GatewayAuth,
}

/// Builder for [`LagerBox`], for overriding the default timeout, the
/// debug-service URL, and gateway auth.
pub struct LagerBoxBuilder {
    host: String,
    debug_url: Option<String>,
    default_timeout: Duration,
    bearer_token: Option<String>,
}

impl LagerBoxBuilder {
    /// Override the default HTTP timeout for quick commands (10s unless
    /// changed). Long-running actions (watt/energy windows,
    /// `wait_for_level`) still compute their own wider budgets.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.default_timeout = timeout;
        self
    }

    /// Override the debug-service base URL (default: the box host on port
    /// 8765). Use this when the debug service is reached through an SSH
    /// tunnel (e.g. `http://127.0.0.1:8765`). Also settable via the
    /// `LAGER_DEBUG_SERVICE_URL` environment variable.
    pub fn debug_service_url(mut self, url: impl Into<String>) -> Self {
        self.debug_url = Some(url.into());
        self
    }

    /// Attach `Authorization: Bearer <token>` to every request, for boxes
    /// behind an authenticating gateway. Also settable via the
    /// `LAGER_GATEWAY_TOKEN` environment variable.
    ///
    /// Without this, the crate reuses the Lager CLI's session
    /// (`lager login <auth_url>`, stored in `~/.lager_gateway_auth`)
    /// automatically when a gateway asks for auth, including transparent
    /// refresh of expired access tokens. Plain (ungated) boxes are
    /// unaffected either way.
    pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
        self.bearer_token = Some(token.into());
        self
    }

    /// Build the client.
    pub fn build(self) -> Result<LagerBox> {
        let base = wire::base_url(&self.host)?;
        let debug_base = match self.debug_url {
            Some(url) => wire::base_url_with_port(&url, wire::DEBUG_SERVICE_PORT)?,
            None => wire::service_base(&base, wire::DEBUG_SERVICE_PORT),
        };
        let auth = GatewayAuth::new(&base, self.bearer_token);
        Ok(LagerBox {
            base,
            debug_base,
            agent: ureq::AgentBuilder::new().build(),
            default_timeout: self.default_timeout,
            auth,
        })
    }
}

impl LagerBox {
    /// Connect to a box by host name, IP, `host:port`, or full URL.
    /// The port defaults to 9000 (the box HTTP server).
    pub fn connect(host: impl Into<String>) -> Result<Self> {
        Self::builder(host).build()
    }

    /// Connect to the box named by the `LAGER_BOX_HOST` environment
    /// variable.
    pub fn from_env() -> Result<Self> {
        let host = std::env::var(BOX_HOST_ENV)
            .map_err(|_| Error::Config(format!("{BOX_HOST_ENV} is not set")))?;
        Self::connect(host)
    }

    /// Start building a client with non-default settings.
    pub fn builder(host: impl Into<String>) -> LagerBoxBuilder {
        LagerBoxBuilder {
            host: host.into(),
            debug_url: std::env::var(crate::DEBUG_SERVICE_URL_ENV).ok(),
            default_timeout: wire::DEFAULT_TIMEOUT,
            bearer_token: None,
        }
    }

    /// The base URL this client talks to, e.g. `http://192.168.1.42:9000`.
    pub fn base_url(&self) -> &str {
        &self.base
    }

    // -- raw access --------------------------------------------------------

    /// Open a TCP stream to one of the box's debug ports: a GDB server
    /// (2331-2342), OpenOCD telnet (4444-4447) or TCL (6666-6669), or RTT
    /// telnet (9090-9097).
    ///
    /// On a box behind an authenticating gateway the ports are not
    /// published, so this asks the gateway for a tunnel: an HTTP `CONNECT`
    /// on the debug-service port, authorized with this client's own
    /// credential (the same pinned or refreshed token every other call
    /// carries, with the same single refresh-and-retry on a 401). The
    /// returned stream is then a plain byte pipe to that port, with
    /// `TCP_NODELAY` set and no timeouts.
    ///
    /// On a plain Lager box, whose own debug service answers the `CONNECT`
    /// with 501, it connects to the published port directly. Callers never
    /// need to know which kind of box they have.
    ///
    /// Start the debug server first ([`DebugNet::connect`]). A server that
    /// was just started can take a moment to open its port, so a 502
    /// (nothing listening) is retried every 250 ms for up to 5 s before it
    /// fails with [`Error::Box`] (status 502). No other refusal is retried. A
    /// gateway MAY close the tunnel when your access to the box is revoked,
    /// which the caller sees as the stream closing.
    ///
    /// ```no_run
    /// # fn main() -> lager::Result<()> {
    /// let lager_box = lager::LagerBox::connect("192.168.1.42")?;
    /// lager_box.debug("debug1").connect()?;
    /// let stream = lager_box.debug_tunnel(2331)?;
    /// // hand `stream` to any GDB remote-protocol client
    /// # drop(stream);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`DebugNet::connect`]: crate::nets::debug::DebugNet::connect
    pub fn debug_tunnel(&self, port: u16) -> Result<std::net::TcpStream> {
        use crate::tunnel::{self as tun, Refusal};

        // A debug server the box has only just started can take a moment
        // to open its port, and until it does the gateway answers 502. That
        // is the one refusal worth waiting out; every other one is final.
        let deadline = std::time::Instant::now() + tun::NOTHING_LISTENING_WAIT;
        let refusal = loop {
            match self.tunnel_authorized(port)? {
                Ok(stream) => return Ok(stream),
                Err(Refusal::NothingListening { .. })
                    if std::time::Instant::now() + tun::NOTHING_LISTENING_RETRY <= deadline =>
                {
                    std::thread::sleep(tun::NOTHING_LISTENING_RETRY);
                }
                Err(refusal) => break refusal,
            }
        };
        match refusal {
            Refusal::Unsupported { .. } => self.debug_port_direct(port, &refusal),
            other => Err(tun::refusal_error(&other, self.auth.box_host(), port)),
        }
    }

    /// One `CONNECT`, with the single refresh-and-retry after a 401 that
    /// every other call gets. A denial that stands becomes the error;
    /// any other refusal is handed back for the caller to act on.
    fn tunnel_authorized(
        &self,
        port: u16,
    ) -> Result<std::result::Result<std::net::TcpStream, crate::tunnel::Refusal>> {
        use crate::tunnel::Refusal;

        let token = self.current_token();
        let (status, auth_url) = match self.tunnel_once(port, token.as_deref())? {
            Err(Refusal::Denied { status, auth_url }) => (status, auth_url),
            other => return Ok(other),
        };
        self.auth.learn_auth_server(&auth_url);
        let fresh = if status == 401 && !self.auth.has_static_token() {
            self.auth
                .resolve_token_blocking(&auth_url, token.as_deref())
        } else {
            None
        };
        let Some(fresh) = fresh else {
            return Err(auth::denial_error(
                status,
                self.auth.box_host(),
                &auth_url,
                token.is_some(),
            ));
        };
        match self.tunnel_once(port, Some(&fresh))? {
            Err(Refusal::Denied { status, auth_url }) => Err(auth::denial_error(
                status,
                self.auth.box_host(),
                &auth_url,
                true,
            )),
            other => Ok(other),
        }
    }

    /// The bearer token this client attaches to the box, refreshed if it
    /// was near expiry, or `None` for a plain box that needs none.
    ///
    /// An escape hatch for raw HTTP calls the typed API does not cover
    /// yet: send it as `Authorization: Bearer <token>`. Prefer a typed
    /// method where one exists, since it also handles the refresh-and-retry
    /// after a 401. Tokens are short-lived, so call this again for each raw
    /// request rather than keeping the value.
    ///
    /// When the box has not been contacted yet, this makes one request
    /// (`GET /health`) to learn whether it is gated. A gated box with no
    /// usable session fails with [`Error::AuthRequired`].
    pub fn bearer_token(&self) -> Result<Option<String>> {
        if let Some(token) = self.current_token() {
            return Ok(Some(token));
        }
        if self.auth.auth_url().is_none() {
            // A gated box denies this and the crate learns its auth server,
            // retrying with a stored session; a plain box just answers.
            self.health()?;
            if let Some(token) = self.current_token() {
                return Ok(Some(token));
            }
        }
        match self.auth.auth_url() {
            None => Ok(None),
            Some(auth_url) => Err(Error::AuthRequired {
                box_host: self.auth.box_host().to_string(),
                message: format!("box {} requires sign-in", self.auth.box_host()),
                auth_url,
            }),
        }
    }

    /// One `CONNECT` round trip. `Ok(Ok(stream))` is an open tunnel;
    /// `Ok(Err(refusal))` is an answer other than 200.
    fn tunnel_once(
        &self,
        port: u16,
        token: Option<&str>,
    ) -> Result<std::result::Result<std::net::TcpStream, crate::tunnel::Refusal>> {
        use std::io::{Read, Write};

        use crate::tunnel::{self as tun, Refusal};

        let (host, service_port) = tun::host_port(&self.debug_base)?;
        let context = format!("debug tunnel via {host}:{service_port}");
        let mut stream = connect_tcp(&host, service_port, self.default_timeout)?;
        let io = |e| tun::io_error(&context, e);
        stream
            .set_read_timeout(Some(self.default_timeout))
            .map_err(io)?;
        stream
            .set_write_timeout(Some(self.default_timeout))
            .map_err(io)?;
        stream
            .write_all(&tun::connect_request(port, self.auth.box_host(), token))
            .map_err(io)?;

        // One byte at a time, so not a single tunnel byte past the blank
        // line is taken out of the socket: a GDB server may speak first.
        let mut head = Vec::with_capacity(256);
        let mut byte = [0u8; 1];
        while !head.ends_with(b"\r\n\r\n") {
            if head.len() >= tun::MAX_HEAD_BYTES {
                return Ok(Err(Refusal::Unsupported { status: None }));
            }
            match stream.read(&mut byte) {
                // A peer that hangs up mid-head does not do CONNECT.
                Ok(0) => return Ok(Err(Refusal::Unsupported { status: None })),
                Ok(_) => head.push(byte[0]),
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                Err(e) => return Err(io(e)),
            }
        }
        let Some(head) = tun::parse_head(&head) else {
            return Ok(Err(Refusal::Unsupported { status: None }));
        };
        if head.status == 200 {
            stream.set_read_timeout(None).map_err(io)?;
            stream.set_write_timeout(None).map_err(io)?;
            stream.set_nodelay(true).map_err(io)?;
            return Ok(Ok(stream));
        }
        let mut body = vec![0u8; head.content_length.min(tun::MAX_BODY_BYTES)];
        let got = stream.read(&mut body).unwrap_or(0);
        let body = String::from_utf8_lossy(&body[..got]).trim().to_string();
        Ok(Err(tun::classify(&head, body)))
    }

    /// No tunnel: connect to the published port, as on a plain box. When
    /// that fails and the `CONNECT` carried a token -- the box is known to
    /// be gated, or a token is pinned -- the answer is the "gateway predates
    /// tunnels" error rather than a bare connection failure. A pinned token
    /// never teaches the client the box's auth server (no denial happens),
    /// so without this a pinned caller behind an old gateway saw only a
    /// connect timeout.
    fn debug_port_direct(
        &self,
        port: u16,
        refusal: &crate::tunnel::Refusal,
    ) -> Result<std::net::TcpStream> {
        let host = self.auth.box_host();
        match connect_tcp(host, port, self.default_timeout) {
            Ok(stream) => {
                let _ = stream.set_nodelay(true);
                Ok(stream)
            }
            Err(_) if self.auth.has_static_token() || self.auth.auth_url().is_some() => {
                Err(crate::tunnel::refusal_error(refusal, host, port))
            }
            Err(e) => Err(e),
        }
    }

    // -- transport ---------------------------------------------------------

    /// Send one request against the port-9000 server.
    pub(crate) fn execute(&self, req: &HttpRequest) -> Result<(u16, Value)> {
        self.execute_at(&self.base, req)
    }

    /// Send one request against the debug service (port 8765).
    pub(crate) fn execute_debug(&self, req: &HttpRequest) -> Result<(u16, Value)> {
        self.execute_at(&self.debug_base, req)
    }

    /// Send one request against an arbitrary base URL and return
    /// `(status, parsed JSON body)`. Attaches gateway auth when known, and
    /// handles a gateway denial by resolving credentials (CLI session
    /// store, with transparent refresh) and retrying once.
    fn execute_at(&self, base: &str, req: &HttpRequest) -> Result<(u16, Value)> {
        let token = self.current_token();
        let (status, gateway, resp_body) = self.send_once(base, req, token.as_deref())?;

        let Some(auth_url) = gateway else {
            return Ok((status, resp_body));
        };
        // Gateway denial: learn the box→auth-server mapping (like the CLI),
        // then retry once with a credential the gateway has not just seen.
        self.auth.learn_auth_server(&auth_url);
        if status == 401 && !self.auth.has_static_token() {
            if let Some(fresh) = self
                .auth
                .resolve_token_blocking(&auth_url, token.as_deref())
            {
                let (status, gateway, resp_body) = self.send_once(base, req, Some(&fresh))?;
                let Some(auth_url) = gateway else {
                    return Ok((status, resp_body));
                };
                return Err(auth::denial_error(
                    status,
                    self.auth.box_host(),
                    &auth_url,
                    true,
                ));
            }
        }
        Err(auth::denial_error(
            status,
            self.auth.box_host(),
            &auth_url,
            token.is_some(),
        ))
    }

    /// Token to attach right now: builder/env token, cached session token,
    /// or a store lookup when the box is already known to be gated.
    /// `pub(crate)`: the Socket.IO session openers (uart, rtt) attach it to
    /// their handshake too.
    pub(crate) fn current_token(&self) -> Option<String> {
        if let Some(token) = self.auth.cached_token() {
            return Some(token);
        }
        if self.auth.wants_store_token() {
            let auth_url = self.auth.auth_url()?;
            return self.auth.resolve_token_blocking(&auth_url, None);
        }
        None
    }

    /// One HTTP round-trip. Returns `(status, gateway_denial_auth_url,
    /// body)`; the auth URL is `Some` only for a gateway denial (401/403/
    /// 503 carrying the discovery header).
    fn send_once(
        &self,
        base: &str,
        req: &HttpRequest,
        token: Option<&str>,
    ) -> Result<(u16, Option<String>, Value)> {
        let url = format!("{}{}", base, req.path);
        let mut r = match req.method {
            Method::Get => self.agent.request("GET", &url),
            Method::Post => self.agent.request("POST", &url),
            Method::Put => self.agent.request("PUT", &url),
        };
        match req.timeout {
            Timeout::Default => r = r.timeout(self.default_timeout),
            Timeout::After(d) => r = r.timeout(d),
            Timeout::Unbounded => {}
        }
        if let Some(token) = token {
            r = r.set("Authorization", &format!("Bearer {token}"));
        }
        let outcome = match (&req.method, &req.body) {
            (Method::Post | Method::Put, Some(body)) => r.send_json(body.clone()),
            _ => r.call(),
        };
        let resp = match outcome {
            Ok(resp) => resp,
            // ureq reports 4xx/5xx as Err(Status); the box still sends a
            // JSON error body we need to surface.
            Err(ureq::Error::Status(_, resp)) => resp,
            Err(ureq::Error::Transport(t)) => {
                let msg = t.to_string();
                return if msg.to_ascii_lowercase().contains("timed out")
                    || msg.to_ascii_lowercase().contains("timeout")
                {
                    Err(Error::Timeout(msg))
                } else {
                    Err(Error::Connection(msg))
                };
            }
        };
        let status = resp.status();
        let gateway = if auth::is_denial(status) {
            resp.header(auth::DISCOVERY_HEADER).map(str::to_string)
        } else {
            None
        };
        let body: Value = match resp.into_json() {
            Ok(body) => body,
            Err(e) if status < 400 => return Err(Error::Decode(format!("non-JSON response: {e}"))),
            // Error responses (incl. gateway denials) may have no JSON body.
            Err(_) => Value::Null,
        };
        if gateway.is_none() && status >= 400 && body.is_null() {
            return Err(Error::Box {
                status,
                message: format!("HTTP {status} (non-JSON body)"),
            });
        }
        Ok((status, gateway, body))
    }

    /// Execute one typed operation against a command endpoint.
    pub(crate) fn run<T>(&self, op: Op<T>) -> Result<T> {
        let (status, body) = self.execute(&op.req)?;
        let resp = wire::parse_command(status, body)?;
        (op.parse)(resp)
    }

    /// Open a streaming response body against the debug service (used by
    /// RTT). Returns the raw byte reader.
    pub(crate) fn stream_debug(
        &self,
        req: &HttpRequest,
    ) -> Result<Box<dyn std::io::Read + Send + Sync>> {
        let token = self.current_token();
        match self.stream_debug_once(req, token.as_deref()) {
            // Gateway denial (only a 401 maps to AuthRequired): resolve
            // credentials from the CLI session store — avoiding the token
            // the gateway just rejected — and retry once, like execute_at.
            Err(Error::AuthRequired {
                box_host,
                auth_url,
                message,
            }) if !self.auth.has_static_token() => {
                match self
                    .auth
                    .resolve_token_blocking(&auth_url, token.as_deref())
                {
                    Some(fresh) => self.stream_debug_once(req, Some(&fresh)),
                    None => Err(Error::AuthRequired {
                        box_host,
                        auth_url,
                        message,
                    }),
                }
            }
            other => other,
        }
    }

    fn stream_debug_once(
        &self,
        req: &HttpRequest,
        token: Option<&str>,
    ) -> Result<Box<dyn std::io::Read + Send + Sync>> {
        let url = format!("{}{}", self.debug_base, req.path);
        let mut r = self.agent.request("POST", &url);
        match req.timeout {
            Timeout::Default => r = r.timeout(self.default_timeout),
            Timeout::After(d) => r = r.timeout(d),
            Timeout::Unbounded => {}
        }
        if let Some(token) = token {
            r = r.set("Authorization", &format!("Bearer {token}"));
        }
        let outcome = match &req.body {
            Some(body) => r.send_json(body.clone()),
            None => r.call(),
        };
        match outcome {
            Ok(resp) => {
                // The debug service frames its stream as chunked under an
                // HTTP/1.0 status line, where ureq leaves the framing in
                // the body; decode it here. Over HTTP/1.1 ureq already has.
                let hand_framed = resp.http_version().eq_ignore_ascii_case("HTTP/1.0")
                    && resp
                        .header("transfer-encoding")
                        .is_some_and(|te| te.trim().eq_ignore_ascii_case("chunked"));
                let reader = resp.into_reader();
                Ok(if hand_framed {
                    Box::new(ChunkedReader::new(reader))
                } else {
                    reader
                })
            }
            Err(ureq::Error::Status(status, resp)) => {
                if auth::is_denial(status) {
                    if let Some(auth_url) = resp.header(auth::DISCOVERY_HEADER) {
                        let auth_url = auth_url.to_string();
                        self.auth.learn_auth_server(&auth_url);
                        return Err(auth::denial_error(
                            status,
                            self.auth.box_host(),
                            &auth_url,
                            token.is_some(),
                        ));
                    }
                }
                let body: Value = resp.into_json().unwrap_or(Value::Null);
                Err(wire::parse_debug(status, body).unwrap_err())
            }
            Err(ureq::Error::Transport(t)) => Err(Error::Connection(t.to_string())),
        }
    }

    /// Resolve a debug net's full saved record (needed by the debug service,
    /// which reads probe fields out of the record).
    pub(crate) fn debug_net_record(&self, name: &str) -> Result<Value> {
        let records = self.nets_raw()?;
        crate::nets::debug::find_debug_record(records, name)
    }

    /// Raw saved-net records (untyped), with the same `/nets/list` ->
    /// `/uart/nets/list` fallback as [`LagerBox::nets`].
    fn nets_raw(&self) -> Result<Vec<Value>> {
        let body = match self.get_json("/nets/list") {
            Ok(body) => body,
            Err(primary) => self.get_json("/uart/nets/list").map_err(|_| primary)?,
        };
        Ok(wire::nets_list_values(body))
    }

    fn get_json(&self, path: &str) -> Result<Value> {
        let (status, body) = self.execute(&wire::get(path))?;
        if status != 200 {
            return Err(Error::Box {
                status,
                message: body
                    .get("error")
                    .and_then(Value::as_str)
                    .unwrap_or("request failed")
                    .to_string(),
            });
        }
        Ok(body)
    }

    // -- box-level queries --------------------------------------------------

    /// List every net configured on the box (full saved records).
    ///
    /// Falls back to the older `/uart/nets/list` shape for box images that
    /// predate `/nets/list`, like the Lager CLI does.
    pub fn nets(&self) -> Result<Vec<NetRecord>> {
        match self.get_json("/nets/list") {
            Ok(body) => wire::nets_from_body(body),
            Err(primary) => match self.get_json("/uart/nets/list") {
                Ok(body) => wire::nets_from_body(body),
                Err(_) => Err(primary),
            },
        }
    }

    /// Check that the box HTTP server is up.
    pub fn health(&self) -> Result<Health> {
        let body = self.get_json("/health")?;
        serde_json::from_value(body).map_err(Into::into)
    }

    /// Box status: version, configured nets, and endpoint capabilities.
    pub fn status(&self) -> Result<BoxStatus> {
        let body = self.get_json("/status")?;
        serde_json::from_value(body).map_err(Into::into)
    }

    /// Enumerate USB devices on the box's bus from sysfs (lsusb-like).
    ///
    /// A few milliseconds per call with no exclusive device access, so it
    /// is safe to poll frequently — e.g. reading the DUT's iSerial to see
    /// what it re-enumerated as after a hub power-cycle or DFU detach.
    ///
    /// Requires box software >= 0.33.0; older boxes fail with
    /// [`Error::UnsupportedByBox`].
    pub fn usb_devices(&self) -> Result<Vec<UsbDeviceInfo>> {
        self.usb_devices_matching(&UsbDeviceFilter::default())
    }

    /// Like [`LagerBox::usb_devices`], with box-side vid/pid/serial
    /// filters.
    pub fn usb_devices_matching(&self, filter: &UsbDeviceFilter) -> Result<Vec<UsbDeviceInfo>> {
        match self.execute(&wire::usb_devices(filter)) {
            Ok((status, body)) => wire::parse_usb_devices(status, body),
            Err(e) => Err(wire::map_route_missing(e, wire::usb_devices_unsupported)),
        }
    }

    // -- box lock / reservation ----------------------------------------------

    fn lock_call(&self, req: &HttpRequest) -> Result<BoxLock> {
        match self.execute(req) {
            Ok((status, body)) => wire::parse_lock(status, body),
            Err(e) => Err(wire::map_route_missing(e, wire::lock_unsupported)),
        }
    }

    /// Current box lock state (`GET /lock`); `locked: false` when free.
    pub fn lock_status(&self) -> Result<BoxLock> {
        self.lock_call(&wire::lock_status())
    }

    /// Claim the box for `user` (an eternal `holder_type: "user"` lock,
    /// exactly like `lager boxes lock`). Re-acquiring your own lock
    /// refreshes it; a box held by someone else fails with
    /// [`Error::Box`] (HTTP 409) naming the holder.
    pub fn lock(&self, user: &str) -> Result<BoxLock> {
        self.lock_call(&wire::lock_acquire(user, "user", None))
    }

    /// Claim the box with an explicit holder type and TTL.
    /// `ttl_seconds: None` means the lock never auto-expires; with a TTL,
    /// keep the lock alive via [`LagerBox::lock_heartbeat`].
    pub fn lock_with(
        &self,
        user: &str,
        holder_type: &str,
        ttl_seconds: Option<u64>,
    ) -> Result<BoxLock> {
        self.lock_call(&wire::lock_acquire(user, holder_type, ttl_seconds))
    }

    /// Refresh a TTL lock's heartbeat. Fails with [`Error::Box`] when the
    /// box is not locked (HTTP 404) or held by someone else (HTTP 403).
    pub fn lock_heartbeat(&self, user: &str) -> Result<BoxLock> {
        self.lock_call(&wire::lock_heartbeat(user))
    }

    /// Release `user`'s box lock. Releasing an already-unlocked box
    /// succeeds; a box held by someone else fails with [`Error::Box`]
    /// (HTTP 403).
    pub fn unlock(&self, user: &str) -> Result<()> {
        self.lock_call(&wire::unlock(user, false)).map(|_| ())
    }

    /// Release the box lock even when held by another user
    /// (`lager boxes unlock --force`).
    pub fn unlock_force(&self, user: &str) -> Result<()> {
        self.lock_call(&wire::unlock(user, true)).map(|_| ())
    }

    /// Claim the box for `user` and release the claim when the returned
    /// guard drops (best-effort; call [`BoxLockGuard::unlock`] to surface
    /// release errors).
    pub fn lock_guard(&self, user: impl Into<String>) -> Result<BoxLockGuard<'_>> {
        let user = user.into();
        self.lock(&user)?;
        Ok(BoxLockGuard {
            client: self,
            user,
            released: false,
        })
    }

    // -- per-net safety limits ------------------------------------------------

    /// Set the safety limits on a saved net (`PUT /nets/<name>/safety-limits`,
    /// box >= 0.35.0). Returns the limits the box applied.
    ///
    /// The PUT **replaces** the net's whole limits record: fields left `None`
    /// in `limits` are removed from the net, not preserved. Read the current
    /// limits first ([`LagerBox::safety_limits`]) if you mean to change one
    /// ceiling and keep the rest. An all-`None` `limits` clears the record,
    /// same as [`LagerBox::clear_safety_limits`].
    ///
    /// The ceilings are enforced by the box's hardware service, out of reach
    /// of test scripts; a setpoint (or inline `ovp=`/`ocp=` trip) above a
    /// ceiling is refused before it touches the instrument. Older boxes fail
    /// with [`Error::UnsupportedByBox`]; validation refusals (`max_power`,
    /// non-positive ceilings) and an unknown net come back as [`Error::Box`].
    pub fn set_safety_limits(
        &self,
        name: &str,
        limits: &SafetyLimits,
    ) -> Result<Option<SafetyLimits>> {
        match self.execute(&wire::safety_limits_set(name, limits)) {
            Ok((status, body)) => wire::parse_safety_limits(status, body),
            Err(e) => Err(wire::map_route_missing(e, wire::safety_limits_unsupported)),
        }
    }

    /// Remove a net's safety limits, returning it to unrestricted.
    pub fn clear_safety_limits(&self, name: &str) -> Result<()> {
        self.set_safety_limits(name, &SafetyLimits::default())
            .map(|_| ())
    }

    /// Brief live state for every saved net (`GET /nets/state`,
    /// box >= 0.34.0): what `lager nets state` shows. One entry per saved
    /// net; an instrument that is slow, wedged or absent yields
    /// `state: None` with a reason rather than failing the request, so this
    /// is safe to call as a bench health check. Older boxes fail with
    /// [`Error::UnsupportedByBox`].
    pub fn nets_state(&self) -> Result<Vec<NetState>> {
        match self.execute(&wire::nets_state()) {
            Ok((status, body)) => wire::parse_nets_state(status, body),
            Err(e) => Err(wire::map_route_missing(e, wire::nets_state_unsupported)),
        }
    }

    /// Read the safety limits configured on a saved net, via `/nets/list`.
    /// `Ok(None)` means the net exists and is unrestricted; a missing net is
    /// an [`Error::Box`] with status 404.
    pub fn safety_limits(&self, name: &str) -> Result<Option<SafetyLimits>> {
        let nets = self.nets()?;
        nets.iter()
            .find(|rec| rec.name == name)
            .map(|rec| rec.safety_limits)
            .ok_or_else(|| Error::Box {
                status: 404,
                message: format!("no saved net named '{name}' on this box"),
            })
    }

    // -- net handle constructors ---------------------------------------------

    /// Handle for a power-supply net.
    pub fn supply(&self, name: impl Into<String>) -> Supply<'_> {
        Supply {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a battery-simulator net.
    pub fn battery(&self, name: impl Into<String>) -> Battery<'_> {
        Battery {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for an electronic-load net.
    pub fn eload(&self, name: impl Into<String>) -> Eload<'_> {
        Eload {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a solar-simulator net (EA PSB photovoltaic mode).
    pub fn solar(&self, name: impl Into<String>) -> Solar<'_> {
        Solar {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a GPIO net.
    pub fn gpio(&self, name: impl Into<String>) -> Gpio<'_> {
        Gpio {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for an ADC net.
    pub fn adc(&self, name: impl Into<String>) -> Adc<'_> {
        Adc {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a DAC net.
    pub fn dac(&self, name: impl Into<String>) -> Dac<'_> {
        Dac {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a thermocouple net.
    pub fn thermocouple(&self, name: impl Into<String>) -> Thermocouple<'_> {
        Thermocouple {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a watt-meter net.
    pub fn watt_meter(&self, name: impl Into<String>) -> WattMeter<'_> {
        WattMeter {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for an energy-analyzer net.
    pub fn energy_analyzer(&self, name: impl Into<String>) -> EnergyAnalyzer<'_> {
        EnergyAnalyzer {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for an SPI bus net.
    pub fn spi(&self, name: impl Into<String>) -> Spi<'_> {
        Spi {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for an I2C bus net.
    pub fn i2c(&self, name: impl Into<String>) -> I2c<'_> {
        I2c {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a USB hub port net.
    pub fn usb(&self, name: impl Into<String>) -> UsbPort<'_> {
        UsbPort {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a robot-arm net (Rotrics Dexarm).
    pub fn arm(&self, name: impl Into<String>) -> Arm<'_> {
        Arm {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a webcam net (MJPEG streaming).
    pub fn webcam(&self, name: impl Into<String>) -> Webcam<'_> {
        Webcam {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a net driven by a custom driver installed on the box
    /// (box >= 0.59.0). See [`crate::nets::custom`].
    pub fn custom(&self, name: impl Into<String>) -> CustomNet<'_> {
        CustomNet {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a router net (MikroTik RouterOS).
    pub fn router(&self, name: impl Into<String>) -> Router<'_> {
        Router {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for the box's BLE adapter (box-level, not a saved net).
    pub fn ble(&self) -> Ble<'_> {
        Ble { client: self }
    }

    /// Handle for the box's WiFi interface (box-level, not a saved net).
    pub fn wifi(&self) -> Wifi<'_> {
        Wifi { client: self }
    }

    /// Handle for BluFi (ESP32 WiFi provisioning over BLE; box-level).
    pub fn blufi(&self) -> Blufi<'_> {
        Blufi { client: self }
    }

    /// Handle for box-side DFU via dfu-util (box-level, not a saved net).
    pub fn dfu(&self) -> Dfu<'_> {
        Dfu { client: self }
    }

    /// Handle for a debug-probe net (flash/erase/reset/read_memory/RTT).
    /// Talks to the box debug service on port 8765.
    pub fn debug(&self, name: impl Into<String>) -> DebugNet<'_> {
        DebugNet {
            client: self,
            name: name.into(),
            record: Default::default(),
        }
    }

    /// Handle for an oscilloscope net, the instrument or one of its
    /// channels (box >= 0.55.0). See [`crate::nets::scope`].
    pub fn scope(&self, name: impl Into<String>) -> Scope<'_> {
        Scope {
            client: self,
            name: name.into(),
        }
    }

    /// Handle for a YubiHSM 2 net (box >= 0.59.0). See [`crate::nets::hsm`].
    pub fn hsm(&self, name: impl Into<String>) -> Hsm<'_> {
        Hsm {
            client: self,
            name: name.into(),
        }
    }

    /// Open a streaming UART session on a UART net.
    ///
    /// Connects a Socket.IO session to the box's `/uart` namespace and
    /// starts streaming. Only one session per net (box-enforced).
    #[cfg(feature = "uart")]
    pub fn uart(&self, name: impl Into<String>) -> Result<crate::nets::uart::Uart> {
        crate::nets::uart::Uart::open(&self.base, name.into(), self.current_token())
    }
}

/// RAII box-lock claim from [`LagerBox::lock_guard`]: releases the lock on
/// drop (best-effort — a drop cannot surface errors, so tests that must
/// know the release worked should call [`BoxLockGuard::unlock`]).
pub struct BoxLockGuard<'a> {
    client: &'a LagerBox,
    user: String,
    released: bool,
}

impl BoxLockGuard<'_> {
    /// The user holding this claim.
    pub fn user(&self) -> &str {
        &self.user
    }

    /// Release the lock now, surfacing any error.
    pub fn unlock(mut self) -> Result<()> {
        self.released = true;
        self.client.unlock(&self.user)
    }
}

impl Drop for BoxLockGuard<'_> {
    fn drop(&mut self) {
        if !self.released {
            let _ = self.client.unlock(&self.user);
        }
    }
}

/// TCP connect with a timeout, trying every address the host resolves to.
fn connect_tcp(host: &str, port: u16, timeout: Duration) -> Result<std::net::TcpStream> {
    use std::net::ToSocketAddrs;

    let context = format!("{host}:{port}");
    let addrs = (host, port)
        .to_socket_addrs()
        .map_err(|e| Error::Connection(format!("{context}: {e}")))?;
    let mut last = None;
    for addr in addrs {
        match std::net::TcpStream::connect_timeout(&addr, timeout) {
            Ok(stream) => return Ok(stream),
            Err(e) => last = Some(e),
        }
    }
    Err(match last {
        Some(e) => crate::tunnel::io_error(&context, e),
        None => Error::Connection(format!("{context}: no address")),
    })
}