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.
51 seen: BTreeMap<NodeId, WaitingNode>,
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 /// The most nodes one poll may ask about. "The client can represent multiple nodes" is
63 /// not "the client can represent every node".
64 pub(super) const MAX_PER_POLL: usize = 32;
65
66 /// Tell a client node to do something the next time it asks.
67 ///
68 /// Replaces whatever was queued for that node, because the actions supersede one
69 /// another: a `cancelPreparePairing` after a `preparePairing` is not two things to do.
70 pub(super) fn instruct(&self, client: NodeId, action: WaitAction) {
71 if let Ok(mut state) = self.state.lock() {
72 // Bounded for the same reason as `seen`, and by the same number — except that
73 // this map is only ever grown by the *host*, so a full one is a bug in the
74 // host rather than an attack. Dropping the new entry rather than an old one
75 // keeps the actions already promised.
76 if state.pending.len() < Self::MAX_WAITING || state.pending.contains_key(&client) {
77 state.pending.insert(client, action);
78 }
79 }
80 self.woken.notify_waiters();
81 }
82
83 /// Everything the endpoint has learned from nodes that are waiting.
84 pub(super) fn waiting(&self) -> Vec<(NodeId, WaitingNode)> {
85 self.state.lock().map_or_else(
86 |_| Vec::new(),
87 |state| {
88 state
89 .seen
90 .iter()
91 .map(|(id, node)| (*id, node.clone()))
92 .collect()
93 },
94 )
95 }
96
97 /// Record what this poll told us, and take whatever is queued for its nodes.
98 fn take(&self, nodes: &[WaitForPairing]) -> Vec<WaitInstruction> {
99 let Ok(mut state) = self.state.lock() else {
100 return Vec::new();
101 };
102 let mut out = Vec::new();
103 for node in nodes.iter().take(Self::MAX_PER_POLL) {
104 // Remembering a node is what an unauthenticated caller can make us do, so it
105 // is the step that is bounded. Answering one we already know about is not:
106 // an entry that exists costs nothing to update, and a device that has been
107 // polling for a week must not be forgotten because a stranger filled the map.
108 if !state.seen.contains_key(&node.client_node_id)
109 && state.seen.len() >= Self::MAX_WAITING
110 {
111 continue;
112 }
113 let seen = state.seen.entry(node.client_node_id).or_default();
114 // A poll that carries a description is the answer to `sendNodeDescription`;
115 // one that does not must not erase what we were told last time.
116 if node.client_node_description.is_some() {
117 seen.description.clone_from(&node.client_node_description);
118 }
119 if node.client_endpoint_description.is_some() {
120 seen.endpoint.clone_from(&node.client_endpoint_description);
121 }
122 seen.error = node.error_message;
123
124 if let Some(action) = state.pending.remove(&node.client_node_id) {
125 out.push(WaitInstruction {
126 client_node_id: node.client_node_id,
127 action,
128 });
129 }
130 }
131 out
132 }
133
134 /// Answer a poll: at once if there is something to say, otherwise after the hold.
135 ///
136 /// The empty answer is not a failure — `S2C §Long-polling` has the server reply "just
137 /// before the request would time out", and the client asks again. A wake-up meant for
138 /// another node ends this request early with an empty list, which costs one more
139 /// request; tracking which waiter each instruction is for would cost a missed wake-up
140 /// twenty-five seconds.
141 pub(super) async fn poll(&self, nodes: &[WaitForPairing]) -> Vec<WaitInstruction> {
142 let ready = self.take(nodes);
143 if !ready.is_empty() {
144 return ready;
145 }
146 // Register as a waiter *before* looking again. `notify_waiters` only wakes
147 // waiters that are already registered, and `notified()` does not register until
148 // it is first polled — so without `enable()` an instruction queued on another
149 // thread between this check and the first poll is one this request sleeps
150 // through for a full twenty-five seconds.
151 let woken = self.woken.notified();
152 tokio::pin!(woken);
153 woken.as_mut().enable();
154
155 let ready = self.take(nodes);
156 if !ready.is_empty() {
157 return ready;
158 }
159 let hold = core::time::Duration::from(LONG_POLL_HOLD);
160 if tokio::time::timeout(hold, woken).await.is_err() {
161 return Vec::new();
162 }
163 self.take(nodes)
164 }
165}