Skip to main content

s2_kit/connect/server/
longpoll.rs

1//! The long-polling queue behind `POST /v1/waitForPairing`.
2//!
3//! `S2C §Long-polling` exists for one kind of node: a Resource Manager that is "purely an
4//! HTTPS client", with no listening socket. Nothing can dial it, so it dials out and holds
5//! a request open, and the endpoint answers when a person presses a button there.
6//!
7//! That makes this the one place where an S2 Connect server has something to *say* rather
8//! than something to answer: a queue per client node, a wake-up when something is added,
9//! and a hold of [`LONG_POLL_HOLD`] before answering "nothing yet".
10
11use alloc::collections::BTreeMap;
12use alloc::vec::Vec;
13
14use crate::connect::proto::{
15    EndpointDescription, LONG_POLL_HOLD, NodeDescription, NodeId, WaitAction, WaitForPairing,
16    WaitInstruction,
17};
18
19/// What an endpoint knows about one node that is waiting to be told what to do.
20#[derive(Debug, Clone, Default)]
21pub struct WaitingNode {
22    /// The node's own description, once it has sent one.
23    ///
24    /// Absent until the endpoint asks with [`WaitAction::SendNodeDescription`]: a node
25    /// merely checking in should not describe itself every twenty-five seconds.
26    pub description: Option<NodeDescription>,
27    /// Where it is.
28    pub endpoint: Option<EndpointDescription>,
29    /// Why it says it cannot proceed, if it said so.
30    pub error: Option<crate::connect::proto::WaitErrorMessage>,
31}
32
33/// The queue of instructions a long-polling endpoint has for its clients.
34///
35/// Cheap to clone: everything is behind one lock and one notifier.
36#[derive(Debug, Default)]
37pub(super) struct LongPoll {
38    state: std::sync::Mutex<State>,
39    /// Woken whenever an instruction is queued, so a held request answers at once instead
40    /// of after the rest of its twenty-five seconds.
41    woken: tokio::sync::Notify,
42}
43
44#[derive(Debug, Default)]
45struct State {
46    /// At most one pending action per client node: `S2C §Long-polling` says the server
47    /// "may only provide at most one item for each clientNodeId", and a queue that grew
48    /// would hand out an action the user has already cancelled.
49    pending: BTreeMap<NodeId, WaitAction>,
50    /// What each polling node has told us about itself, and when it last polled.
51    seen: BTreeMap<NodeId, (WaitingNode, std::time::Instant)>,
52}
53
54impl LongPoll {
55    /// The most nodes one endpoint will remember across long polls.
56    ///
57    /// `waitForPairing` needs no bearer and its body is a *list* of identifiers the caller
58    /// chose, so a map that grew one entry per identifier would be unbounded memory driven
59    /// by unauthenticated input. A LAN endpoint talks to tens of devices.
60    pub(super) const MAX_WAITING: usize = 256;
61
62    /// How long a node that stopped polling is remembered.
63    ///
64    /// Without expiry the bound above is a trap: anyone on the subnet posts 256 invented
65    /// identifiers once, the table is full for ever, and every genuine device after that
66    /// is ignored. A device that is really waiting polls every twenty seconds; one silent
67    /// for five minutes has gone, and its slot is free again.
68    pub(super) const SEEN_TTL: core::time::Duration = core::time::Duration::from_mins(5);
69
70    /// The most nodes one poll may ask about. "The client can represent multiple nodes" is
71    /// not "the client can represent every node".
72    pub(super) const MAX_PER_POLL: usize = 32;
73
74    /// Tell a client node to do something the next time it asks.
75    ///
76    /// Replaces whatever was queued for that node, because the actions supersede one
77    /// another: a `cancelPreparePairing` after a `preparePairing` is not two things to do.
78    pub(super) fn instruct(&self, client: NodeId, action: WaitAction) {
79        if let Ok(mut state) = self.state.lock() {
80            // Bounded for the same reason as `seen`, and by the same number — except that
81            // this map is only ever grown by the *host*, so a full one is a bug in the
82            // host rather than an attack. Dropping the new entry rather than an old one
83            // keeps the actions already promised.
84            if state.pending.len() < Self::MAX_WAITING || state.pending.contains_key(&client) {
85                state.pending.insert(client, action);
86            }
87        }
88        self.woken.notify_waiters();
89    }
90
91    /// Everything the endpoint has learned from nodes that are waiting.
92    pub(super) fn waiting(&self) -> Vec<(NodeId, WaitingNode)> {
93        self.state.lock().map_or_else(
94            |_| Vec::new(),
95            |state| {
96                state
97                    .seen
98                    .iter()
99                    .map(|(id, (node, _))| (*id, node.clone()))
100                    .collect()
101            },
102        )
103    }
104
105    /// Record what this poll told us, and take whatever is queued for its nodes.
106    fn take(&self, nodes: &[WaitForPairing]) -> Vec<WaitInstruction> {
107        let Ok(mut state) = self.state.lock() else {
108            return Vec::new();
109        };
110        let now = std::time::Instant::now();
111        state
112            .seen
113            .retain(|_, (_, at)| now.saturating_duration_since(*at) < Self::SEEN_TTL);
114        let mut out = Vec::new();
115        for node in nodes.iter().take(Self::MAX_PER_POLL) {
116            // Remembering a node is what an unauthenticated caller can make us do, so it
117            // is the step that is bounded. Answering one we already know about is not:
118            // an entry that exists costs nothing to update, and a device that has been
119            // polling for a week must not be forgotten because a stranger filled the map.
120            if !state.seen.contains_key(&node.client_node_id)
121                && state.seen.len() >= Self::MAX_WAITING
122            {
123                continue;
124            }
125            let (seen, at) = state
126                .seen
127                .entry(node.client_node_id)
128                .or_insert_with(|| (WaitingNode::default(), now));
129            *at = now;
130            // A poll that carries a description is the answer to `sendNodeDescription`;
131            // one that does not must not erase what we were told last time.
132            if node.client_node_description.is_some() {
133                seen.description.clone_from(&node.client_node_description);
134            }
135            if node.client_endpoint_description.is_some() {
136                seen.endpoint.clone_from(&node.client_endpoint_description);
137            }
138            seen.error = node.error_message;
139
140            if let Some(action) = state.pending.remove(&node.client_node_id) {
141                out.push(WaitInstruction {
142                    client_node_id: node.client_node_id,
143                    action,
144                });
145            }
146        }
147        out
148    }
149
150    /// Answer a poll: at once if there is something to say, otherwise after the hold.
151    ///
152    /// The empty answer is not a failure — `S2C §Long-polling` has the server reply "just
153    /// before the request would time out", and the client asks again. A wake-up meant for
154    /// another node ends this request early with an empty list, which costs one more
155    /// request; tracking which waiter each instruction is for would cost a missed wake-up
156    /// twenty-five seconds.
157    pub(super) async fn poll(&self, nodes: &[WaitForPairing]) -> Vec<WaitInstruction> {
158        let ready = self.take(nodes);
159        if !ready.is_empty() {
160            return ready;
161        }
162        // Register as a waiter *before* looking again. `notify_waiters` only wakes
163        // waiters that are already registered, and `notified()` does not register until
164        // it is first polled — so without `enable()` an instruction queued on another
165        // thread between this check and the first poll is one this request sleeps
166        // through for a full twenty-five seconds.
167        let woken = self.woken.notified();
168        tokio::pin!(woken);
169        woken.as_mut().enable();
170
171        let ready = self.take(nodes);
172        if !ready.is_empty() {
173            return ready;
174        }
175        let hold = core::time::Duration::from(LONG_POLL_HOLD);
176        if tokio::time::timeout(hold, woken).await.is_err() {
177            return Vec::new();
178        }
179        self.take(nodes)
180    }
181}