Skip to main content

s2_kit/connect/client/
lan.rs

1//! The operations only LAN endpoints implement.
2//!
3//! The wire types and the reasoning are in [`proto::lan`](crate::connect::proto::lan);
4//! this is the HTTP that carries them.
5
6use alloc::vec::Vec;
7
8use crate::connect::proto::{
9    CancelPreparePairing, EndpointDescription, LONG_POLL_TIMEOUT, NodeDescription, PreparePairing,
10    WaitForPairing, WaitInstruction,
11};
12use crate::connect::tls::TlsPolicy;
13
14use super::http::{Error, Http};
15
16/// Asks a LAN endpoint what it is, before anyone has decided to pair with it.
17#[derive(Debug)]
18pub struct LanClient {
19    http: Http,
20    /// A second connection, for the one operation that is meant to block.
21    ///
22    /// `waitForPairing` is held open by the server for up to
23    /// [`LONG_POLL_HOLD`](crate::connect::proto::LONG_POLL_HOLD); a client whose timeout
24    /// is the ordinary one would abandon every request a fraction before the answer it
25    /// asked for arrived, and would look to its user like an endpoint that never responds.
26    long_poll: Http,
27}
28
29impl LanClient {
30    /// Point at an endpoint's base URL — unversioned, as DNS-SD advertises it; the
31    /// version is read from its index on the first request.
32    ///
33    /// The certificate is self-signed and unverified, exactly as during pairing — and
34    /// nothing this client returns is authenticated. It is material for a user interface,
35    /// not a basis for a decision. See [`proto::lan`](crate::connect::proto::lan).
36    pub fn new(base_url: &str) -> Result<Self, Error> {
37        Ok(Self {
38            http: Http::new(
39                base_url,
40                &TlsPolicy::LanPairingOnly,
41                super::Pairing::REQUEST_TIMEOUT,
42            )?,
43            long_poll: Http::new(
44                base_url,
45                &TlsPolicy::LanPairingOnly,
46                core::time::Duration::from(LONG_POLL_TIMEOUT),
47            )?,
48        })
49    }
50
51    /// `GET /v1/endpoint` — the endpoint's own description.
52    pub async fn endpoint(&self) -> Result<EndpointDescription, Error> {
53        self.http.get("getEndpoint", "endpoint").await
54    }
55
56    /// `GET /v1/nodes` — every node this endpoint hosts.
57    ///
58    /// Note that the schema returns bare [`NodeDescription`]s, with no
59    /// [`NodeIdAlias`](crate::connect::proto::NodeIdAlias) — so a user interface can show
60    /// a list but cannot tell which entry a pairing code's alias names
61    /// (erratum E21).
62    pub async fn nodes(&self) -> Result<Vec<NodeDescription>, Error> {
63        self.http.get("getNodes", "nodes").await
64    }
65
66    /// `POST /v1/preparePairing` — "the end user has started the process on the client".
67    ///
68    /// A hint that lets the server show the pairing code at the moment the user is looking
69    /// for it. Best effort by design: "When a preparePairing is called, it is not
70    /// guaranteed that a call to pairingRequest or cancelPreparePairing will follow."
71    pub async fn prepare_pairing(&self, body: &PreparePairing) -> Result<(), Error> {
72        self.http
73            .post_empty("preparePairing", "preparePairing", None, Some(body))
74            .await
75    }
76
77    /// `POST /v1/cancelPreparePairing` — the user changed their mind.
78    pub async fn cancel_prepare_pairing(&self, body: &CancelPreparePairing) -> Result<(), Error> {
79        self.http
80            .post_empty(
81                "cancelPreparePairing",
82                "cancelPreparePairing",
83                None,
84                Some(body),
85            )
86            .await
87    }
88
89    /// `POST /v1/waitForPairing` — hold a request open until the endpoint has something
90    /// to say.
91    ///
92    /// This is how a Resource Manager that is "purely an HTTPS client" — no listening
93    /// socket, nothing for a CEM to dial — takes part in a pairing at all: it asks the
94    /// other endpoint what to do, and the answer arrives whenever a person presses a
95    /// button there. The server holds the request for up to
96    /// [`LONG_POLL_HOLD`](crate::connect::proto::LONG_POLL_HOLD) and then answers `204`,
97    /// read here as an empty list; that is not an error, it is "nothing yet, ask again".
98    ///
99    /// `S2C §Long-polling`: "the client can represent multiple nodes so the request body
100    /// and the response contains a list", and the server "may only provide at most one
101    /// item for each clientNodeId". Call it in a loop:
102    ///
103    /// ```no_run
104    /// # use s2_kit::connect::client::LanClient;
105    /// # use s2_kit::connect::proto::{WaitAction, WaitForPairing};
106    /// # async fn poll(client: &LanClient, mine: Vec<WaitForPairing>) -> Result<(), Box<dyn std::error::Error>> {
107    /// loop {
108    ///     for instruction in client.wait_for_pairing(&mine).await? {
109    ///         match instruction.action {
110    ///             WaitAction::RequestPairing => { /* start `Pairing::run` now */ }
111    ///             WaitAction::SendNodeDescription => { /* answer with descriptions */ }
112    ///             _ => {}
113    ///         }
114    ///     }
115    /// }
116    /// # }
117    /// ```
118    pub async fn wait_for_pairing(
119        &self,
120        nodes: &[WaitForPairing],
121    ) -> Result<Vec<WaitInstruction>, Error> {
122        Ok(self
123            .long_poll
124            .post_or_no_content("waitForPairing", "waitForPairing", None, &nodes)
125            .await?
126            .unwrap_or_default())
127    }
128}