Skip to main content

tauri_plugin_socketio/
registry.rs

1//! The registry of named clients, the subscriptions that forward them to webviews, and the
2//! server acks waiting for an answer from a webview.
3//!
4//! Each client has one [`Hub`]: a single pair of listeners on the client that fans events and
5//! states out to the client's subscriptions. Subscriptions are plain records in the hub, so
6//! ending one drops its channel at once; the hub's lock orders every message of a client.
7//!
8//! Lock order: `clients` → a hub's `state`. Hub callbacks (the client's event task) take only
9//! their hub's lock, and no lock is held across an await.
10
11use std::collections::{HashMap, HashSet};
12use std::fmt;
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
15use std::time::{Duration, Instant};
16
17use socketio_next::{
18    AckSender, Client, ClientBuilder, ConnectionState, Event, ListenerId, Payload,
19};
20use tauri::ipc::Channel;
21use tokio::sync::watch;
22
23use crate::models::{Access, ClientInfo, Dynamic, Message, State};
24use crate::{Error, Result};
25
26/// Server acks wait this long for the webview's answer, then are forgotten.
27pub const ACK_TTL: Duration = Duration::from_secs(120);
28/// At most this many server acks of one client wait for one webview; past it the webview's own
29/// oldest is forgotten (never another webview's).
30pub const MAX_PENDING_ACKS_PER_WEBVIEW: usize = 256;
31/// At most this many subscriptions per webview (over all clients).
32pub const MAX_SUBSCRIPTIONS_PER_WEBVIEW: usize = 64;
33/// How long a JS `connect` waits for the client's event task to forward the connected state.
34const SETTLE: Duration = Duration::from_secs(2);
35
36/// Identifies one subscription (unique for the life of the app).
37pub type SubscriptionId = u64;
38
39/// Named socket.io clients shared by Rust and the webviews. Get it with
40/// [`SocketIoExt::socketio`](crate::SocketIoExt::socketio); cheap to clone.
41///
42/// Ids are unique: [`connect`](Self::connect) and [`insert`](Self::insert) fail with
43/// [`Error::AlreadyExists`] for an id in use, so a client is never replaced behind the back of
44/// whoever holds it. [`remove`](Self::remove) it first. [`reserve`](Self::reserve) an id in
45/// `setup` when Rust registers it later: webviews then cannot take it.
46#[derive(Clone, Default)]
47pub struct SocketIo {
48    inner: Arc<Inner>,
49}
50
51#[derive(Default)]
52struct Inner {
53    clients: Mutex<HashMap<String, Entry>>,
54    reserved: Mutex<HashSet<String>>,
55    /// Connects in flight: their ids and subscription slots.
56    pending: Mutex<Pending>,
57    /// Bumped when a webview loads a new page: a JS connect that started before is stale.
58    generations: Mutex<HashMap<String, u64>>,
59    /// URL prefixes a webview may connect to; empty: any.
60    allowed: Vec<url::Url>,
61    next_sub: AtomicU64,
62}
63
64struct Entry {
65    client: Client,
66    access: Access,
67    hub: Arc<Hub>,
68    /// The hub's listeners when they were added after the client was built (`insert`).
69    listeners: Vec<ListenerId>,
70    /// Auth, headers and query a webview may replace (clients a webview connected).
71    dynamic: Option<Arc<Mutex<Dynamic>>>,
72}
73
74/// Fans one client out to its subscriptions; keeps the acks offered to webviews.
75struct Hub {
76    state: Mutex<HubState>,
77    /// Counts forwarded states, so `connect` can wait for the connected one.
78    forwarded: watch::Sender<u64>,
79}
80
81struct HubState {
82    subs: HashMap<SubscriptionId, Sub>,
83    /// The last state forwarded: the snapshot new subscriptions start from.
84    last: Option<State>,
85    acks: HashMap<u64, PendingAck>,
86    next_ack: u64,
87    /// Server acks are offered to webviews: Full clients, until they disconnect.
88    offer_acks: bool,
89    /// Removed from the registry: forwards nothing more.
90    closed: bool,
91}
92
93struct Sub {
94    channel: Channel<Message>,
95    events: Option<HashSet<String>>,
96    /// The webview it belongs to; `None` for subscriptions made from Rust (no acks offered).
97    webview: Option<String>,
98}
99
100struct PendingAck {
101    sender: AckSender,
102    at: Instant,
103    /// The webviews it was offered to; the first answer from one of them wins.
104    webviews: Vec<String>,
105}
106
107/// A subscription before it is attached: what the webview asked for.
108pub(crate) struct SubscribeArgs {
109    pub events: Option<Vec<String>>,
110    pub channel: Channel<Message>,
111    pub webview: Option<String>,
112}
113
114impl SubscribeArgs {
115    fn into_sub(self) -> Sub {
116        Sub {
117            channel: self.channel,
118            events: self.events.map(|e| e.into_iter().collect()),
119            webview: self.webview,
120        }
121    }
122}
123
124fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
125    m.lock().unwrap_or_else(PoisonError::into_inner)
126}
127
128impl fmt::Debug for SocketIo {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        f.debug_struct("SocketIo")
131            .field("clients", &self.ids())
132            .field("reserved", &lock(&self.inner.reserved).len())
133            .field("allowed_urls", &self.inner.allowed.len())
134            .finish()
135    }
136}
137
138impl SocketIo {
139    pub(crate) fn with_allowed(allowed: Vec<url::Url>) -> Self {
140        SocketIo {
141            inner: Arc::new(Inner {
142                allowed,
143                ..Inner::default()
144            }),
145        }
146    }
147
148    /// Keeps `id` for Rust: a webview's `connect` with it fails with [`Error::Reserved`], while
149    /// [`connect`](Self::connect) and [`insert`](Self::insert) from Rust work. Call it in
150    /// `setup` (it is synchronous) for every id Rust registers later, so no page script can
151    /// take the id first. Reservations last for the life of the app.
152    pub fn reserve(&self, id: impl Into<String>) {
153        lock(&self.inner.reserved).insert(id.into());
154    }
155
156    /// Builds `builder`, connects and registers the client under `id` with [`Access::Full`].
157    /// Fails with the connect error, or [`Error::AlreadyExists`] (then the new client is
158    /// dropped, which closes it).
159    pub async fn connect(&self, id: impl Into<String>, builder: ClientBuilder) -> Result<Client> {
160        Ok(self.connect_with(id.into(), builder, None, None).await?.0)
161    }
162
163    /// The webview's connect: reservations, the URL allow-list and the subscription cap apply;
164    /// the subscription is attached before connecting (no event after CONNECT is missed) and
165    /// starts with a snapshot of the connected state.
166    pub(crate) async fn connect_from_webview(
167        &self,
168        id: String,
169        url: &str,
170        engine_path: Option<&str>,
171        builder: ClientBuilder,
172        dynamic: Arc<Mutex<Dynamic>>,
173        sub: SubscribeArgs,
174    ) -> Result<(SubscriptionId, State)> {
175        if lock(&self.inner.reserved).contains(&id) {
176            return Err(Error::Reserved(id));
177        }
178        if !self.url_allowed(url, engine_path) {
179            return Err(Error::UrlNotAllowed);
180        }
181        let (_, sub) = self
182            .connect_with(id, builder, Some(sub), Some(dynamic))
183            .await?;
184        Ok(sub.expect("a subscription was given"))
185    }
186
187    async fn connect_with(
188        &self,
189        id: String,
190        builder: ClientBuilder,
191        sub: Option<SubscribeArgs>,
192        dynamic: Option<Arc<Mutex<Dynamic>>>,
193    ) -> Result<(Client, Option<(SubscriptionId, State)>)> {
194        let webview = sub.as_ref().and_then(|s| s.webview.clone());
195        // The id and (for a webview) one subscription slot are held while connecting, so
196        // concurrent connects can neither share an id nor exceed the cap.
197        let pending = {
198            let clients = lock(&self.inner.clients);
199            let mut pending = lock(&self.inner.pending);
200            if clients.contains_key(&id) || pending.ids.contains(&id) {
201                return Err(Error::AlreadyExists(id));
202            }
203            if let Some(label) = &webview {
204                let held = pending.slots.get(label).copied().unwrap_or_default();
205                check_cap(&clients, label, held)?;
206                *pending.slots.entry(label.clone()).or_default() += 1;
207            }
208            pending.ids.insert(id.clone());
209            PendingGuard {
210                inner: &self.inner,
211                id: id.clone(),
212                webview: webview.clone(),
213            }
214        };
215        let generation = webview.as_deref().map(|l| self.generation(l));
216        let hub = Hub::new(true);
217        let sub_id = sub.map(|args| {
218            let sub_id = self.next_sub();
219            lock(&hub.state).subs.insert(sub_id, args.into_sub());
220            sub_id
221        });
222        let (on_event, on_state) = (Arc::clone(&hub), Arc::clone(&hub));
223        let client = builder
224            .on_any(move |event: Event, _: Client| {
225                on_event.event(event);
226                std::future::ready(())
227            })
228            .on_state_change(move |state: ConnectionState, _: Client| {
229                on_state.state(&state);
230                std::future::ready(())
231            })
232            .connect()
233            .await?;
234        #[cfg(test)]
235        let id_for_test = id.clone();
236        {
237            let mut clients = lock(&self.inner.clients);
238            if clients.contains_key(&id) {
239                return Err(Error::AlreadyExists(id));
240            }
241            clients.insert(
242                id,
243                Entry {
244                    client: client.clone(),
245                    access: Access::Full,
246                    hub: Arc::clone(&hub),
247                    listeners: Vec::new(),
248                    dynamic,
249                },
250            );
251            // registered: the client and its subscription count from here, the pending id
252            // and slot do not any more
253            drop(pending);
254        }
255        #[cfg(test)]
256        tests::after_insert(&id_for_test).await;
257        let Some(sub_id) = sub_id else {
258            return Ok((client, None));
259        };
260        // The page that asked reloaded meanwhile: its subscription would talk to the new page.
261        if let (Some(label), Some(before)) = (&webview, generation) {
262            if self.generation(label) != before {
263                hub.remove_sub(sub_id, None);
264            }
265        }
266        hub.settle(&client).await;
267        let state = hub.snapshot_to(sub_id, &client);
268        Ok((client, Some((sub_id, state))))
269    }
270
271    /// Registers a client built elsewhere, e.g. by Rust code that must stay free of Tauri.
272    /// With [`Access::ReadOnly`] the webview can observe it but never emit, ack or disconnect
273    /// it, whatever its capabilities allow. The registry keeps a clone; the client lives until
274    /// it is removed and every other clone is dropped.
275    pub fn insert(&self, id: impl Into<String>, client: Client, access: Access) -> Result<()> {
276        let id = id.into();
277        let mut clients = lock(&self.inner.clients);
278        if clients.contains_key(&id) {
279            return Err(Error::AlreadyExists(id));
280        }
281        let hub = Hub::new(access == Access::Full);
282        let (on_event, on_state) = (Arc::clone(&hub), Arc::clone(&hub));
283        let listeners = vec![
284            client.on_any(move |event: Event, _: Client| {
285                on_event.event(event);
286                std::future::ready(())
287            }),
288            client.on_state_change(move |state: ConnectionState, _: Client| {
289                on_state.state(&state);
290                std::future::ready(())
291            }),
292        ];
293        clients.insert(
294            id,
295            Entry {
296                client,
297                access,
298                hub,
299                listeners,
300                dynamic: None,
301            },
302        );
303        Ok(())
304    }
305
306    /// A clone of the client registered under `id`.
307    pub fn get(&self, id: &str) -> Option<Client> {
308        lock(&self.inner.clients).get(id).map(|e| e.client.clone())
309    }
310
311    /// The access the webview has to `id`.
312    pub fn access(&self, id: &str) -> Option<Access> {
313        lock(&self.inner.clients).get(id).map(|e| e.access)
314    }
315
316    /// The registered ids, sorted.
317    pub fn ids(&self) -> Vec<String> {
318        let mut ids: Vec<_> = lock(&self.inner.clients).keys().cloned().collect();
319        ids.sort();
320        ids
321    }
322
323    /// Unregisters `id`: its subscriptions end (their channels are dropped) and its pending
324    /// server acks are forgotten. Does **not** disconnect: the client is handed back (call
325    /// [`Client::disconnect`] on it, or drop it; dropping the last clone closes it).
326    pub fn remove(&self, id: &str) -> Option<Client> {
327        let entry = lock(&self.inner.clients).remove(id)?;
328        Some(entry.release())
329    }
330
331    /// Forwards the client's state transitions and events (all, or only `events`) to
332    /// `channel` as [`Message`]s, starting with a snapshot of the current state. Ends with
333    /// [`unsubscribe`](Self::unsubscribe), [`remove`](Self::remove) or when a send fails.
334    /// Server acks are not offered to subscriptions made from Rust (answer them in a handler).
335    pub fn subscribe(
336        &self,
337        id: &str,
338        events: Option<Vec<String>>,
339        channel: Channel<Message>,
340    ) -> Result<SubscriptionId> {
341        Ok(self
342            .subscribe_with(
343                id,
344                SubscribeArgs {
345                    events,
346                    channel,
347                    webview: None,
348                },
349            )?
350            .0)
351    }
352
353    pub(crate) fn subscribe_with(
354        &self,
355        id: &str,
356        args: SubscribeArgs,
357    ) -> Result<(SubscriptionId, State)> {
358        let clients = lock(&self.inner.clients);
359        if let Some(label) = &args.webview {
360            let held = lock(&self.inner.pending)
361                .slots
362                .get(label)
363                .copied()
364                .unwrap_or_default();
365            check_cap(&clients, label, held)?;
366        }
367        let entry = clients
368            .get(id)
369            .ok_or_else(|| Error::UnknownClient(id.to_owned()))?;
370        let sub_id = self.next_sub();
371        let client = &entry.client;
372        let state = entry
373            .hub
374            .attach(sub_id, args.into_sub(), || State::from(&client.state()));
375        Ok((sub_id, state))
376    }
377
378    /// Stops a subscription; `false` when it was gone already.
379    pub fn unsubscribe(&self, id: &str, subscription: SubscriptionId) -> bool {
380        self.unsubscribe_from(id, subscription, None)
381    }
382
383    /// `webview`: only that webview's subscription (the webview's `unsubscribe`).
384    pub(crate) fn unsubscribe_from(
385        &self,
386        id: &str,
387        subscription: SubscriptionId,
388        webview: Option<&str>,
389    ) -> bool {
390        lock(&self.inner.clients)
391            .get(id)
392            .is_some_and(|e| e.hub.remove_sub(subscription, webview))
393    }
394
395    /// A webview starts a new page or is gone: its subscriptions end, its acks are forgotten,
396    /// and a JS connect it started meanwhile does not attach.
397    pub(crate) fn drop_webview(&self, label: &str) {
398        *lock(&self.inner.generations)
399            .entry(label.to_owned())
400            .or_default() += 1;
401        for entry in lock(&self.inner.clients).values() {
402            entry.hub.drop_webview(label);
403        }
404    }
405
406    fn generation(&self, label: &str) -> u64 {
407        lock(&self.inner.generations)
408            .get(label)
409            .copied()
410            .unwrap_or_default()
411    }
412
413    fn next_sub(&self) -> SubscriptionId {
414        self.inner.next_sub.fetch_add(1, Ordering::Relaxed) + 1
415    }
416
417    /// The connection goes where an allowed prefix says: same scheme, host and port, and the
418    /// **engine.io path** (the `path` option, default `/socket.io/`; the URL's own path is the
419    /// namespace and replaced by it) under the prefix's path on a `/` boundary. The namespace
420    /// is not part of the check. No allow-list: anything.
421    pub(crate) fn url_allowed(&self, url: &str, engine_path: Option<&str>) -> bool {
422        if self.inner.allowed.is_empty() {
423            return true;
424        }
425        // dot segments and backslashes are refused outright: they mean something else to the
426        // URL parser (and to some servers) than to a prefix comparison
427        if let Some(path) = engine_path {
428            let lower = path.to_ascii_lowercase();
429            if path.contains("..")
430                || lower.contains("%2e")
431                || lower.contains("%25")
432                || lower.contains("%u")
433                || path.contains('\\')
434                || path.chars().any(char::is_control)
435            {
436                return false;
437            }
438        }
439        // the URL the connection really uses, built by socketio-next itself
440        let mut builder = ClientBuilder::new(url);
441        if let Some(path) = engine_path {
442            builder = builder.path(path);
443        }
444        let Ok(engine) = builder.engine_url() else {
445            return false;
446        };
447        let path = engine.path();
448        self.inner.allowed.iter().any(|p| {
449            let base = p.path().trim_end_matches('/');
450            p.scheme() == engine.scheme()
451                && p.host_str() == engine.host_str()
452                && p.port_or_known_default() == engine.port_or_known_default()
453                && (base.is_empty() || path.strip_prefix(base).is_some_and(|r| r.starts_with('/')))
454        })
455    }
456
457    /// The client for a webview command that drives it: [`Access::Full`] only.
458    pub(crate) fn full(&self, id: &str) -> Result<Client> {
459        match lock(&self.inner.clients).get(id) {
460            None => Err(Error::UnknownClient(id.to_owned())),
461            Some(e) if e.access == Access::ReadOnly => Err(Error::AccessDenied(id.to_owned())),
462            Some(e) => Ok(e.client.clone()),
463        }
464    }
465
466    /// `client` for observing commands (any access).
467    pub(crate) fn any(&self, id: &str) -> Result<Client> {
468        self.get(id)
469            .ok_or_else(|| Error::UnknownClient(id.to_owned()))
470    }
471
472    /// Disconnects a [`Access::Full`] client and unregisters it. Its subscriptions see the
473    /// final `closed` state; no server ack is offered any more.
474    pub(crate) async fn disconnect(&self, id: &str) -> Result<()> {
475        let entry = {
476            let mut clients = lock(&self.inner.clients);
477            match clients.get(id).map(|e| e.access) {
478                None => return Err(Error::UnknownClient(id.to_owned())),
479                Some(Access::ReadOnly) => return Err(Error::AccessDenied(id.to_owned())),
480                Some(Access::Full) => clients.remove(id).expect("checked under the lock"),
481            }
482        };
483        entry.hub.stop_acks();
484        let result = entry.client.disconnect().await;
485        entry.release();
486        Ok(result?)
487    }
488
489    /// Changes what the next connect attempt of `id` sends (a client a webview connected,
490    /// [`Access::Full`]): `f` edits its auth, headers and query.
491    pub(crate) fn configure(&self, id: &str, f: impl FnOnce(&mut Dynamic)) -> Result<()> {
492        let clients = lock(&self.inner.clients);
493        let entry = clients
494            .get(id)
495            .ok_or_else(|| Error::UnknownClient(id.to_owned()))?;
496        if entry.access == Access::ReadOnly {
497            return Err(Error::AccessDenied(id.to_owned()));
498        }
499        let dynamic = entry
500            .dynamic
501            .as_ref()
502            .ok_or_else(|| Error::NotConfigurable(id.to_owned()))?;
503        f(&mut crate::models::lock(dynamic));
504        Ok(())
505    }
506
507    /// A client a webview connected ([`Access::Full`], not registered from Rust): what
508    /// `reconnect` may restart.
509    pub(crate) fn webview_client(&self, id: &str) -> Result<Client> {
510        let clients = lock(&self.inner.clients);
511        let entry = clients
512            .get(id)
513            .ok_or_else(|| Error::UnknownClient(id.to_owned()))?;
514        if entry.access == Access::ReadOnly {
515            return Err(Error::AccessDenied(id.to_owned()));
516        }
517        if entry.dynamic.is_none() {
518            return Err(Error::NotConfigurable(id.to_owned()));
519        }
520        Ok(entry.client.clone())
521    }
522
523    /// Answers server ack `ack_id` of client `id`, offered to `webview`.
524    pub(crate) fn ack(&self, id: &str, ack_id: u64, webview: &str, payload: Payload) -> Result<()> {
525        let hub = {
526            let clients = lock(&self.inner.clients);
527            match clients.get(id) {
528                None => return Err(Error::UnknownClient(id.to_owned())),
529                Some(e) if e.access == Access::ReadOnly => {
530                    return Err(Error::AccessDenied(id.to_owned()));
531                }
532                Some(e) => Arc::clone(&e.hub),
533            }
534        };
535        let sender = hub
536            .take_ack(ack_id, webview)
537            .ok_or(Error::UnknownAck(ack_id))?;
538        Ok(sender.send(payload)?)
539    }
540
541    pub(crate) fn list(&self) -> Vec<ClientInfo> {
542        let clients = lock(&self.inner.clients);
543        let mut out: Vec<_> = clients
544            .iter()
545            .map(|(id, e)| ClientInfo {
546                id: id.clone(),
547                access: e.access,
548                namespace: e.client.namespace().to_owned(),
549                state: State::from(&e.client.state()),
550            })
551            .collect();
552        out.sort_by(|a, b| a.id.cmp(&b.id));
553        out
554    }
555
556    #[cfg(test)]
557    fn hub(&self, id: &str) -> Arc<Hub> {
558        Arc::clone(&lock(&self.inner.clients)[id].hub)
559    }
560}
561
562/// Ids and subscription slots held by connects in flight.
563#[derive(Default)]
564struct Pending {
565    ids: HashSet<String>,
566    slots: HashMap<String, usize>,
567}
568
569/// Gives the pending id and slot back when the connect ends (success or failure; on success
570/// the client and its subscription are registered by then).
571struct PendingGuard<'a> {
572    inner: &'a Inner,
573    id: String,
574    webview: Option<String>,
575}
576
577impl Drop for PendingGuard<'_> {
578    fn drop(&mut self) {
579        let mut pending = lock(&self.inner.pending);
580        pending.ids.remove(&self.id);
581        if let Some(label) = &self.webview {
582            if let Some(n) = pending.slots.get_mut(label) {
583                *n = n.saturating_sub(1);
584            }
585        }
586    }
587}
588
589fn check_cap(clients: &HashMap<String, Entry>, label: &str, held: usize) -> Result<()> {
590    let count: usize = clients.values().map(|e| e.hub.count(label)).sum::<usize>() + held;
591    if count >= MAX_SUBSCRIPTIONS_PER_WEBVIEW {
592        return Err(Error::TooManySubscriptions(MAX_SUBSCRIPTIONS_PER_WEBVIEW));
593    }
594    Ok(())
595}
596
597impl Entry {
598    /// Ends the hub and takes its listeners off the client; hands the client back.
599    fn release(self) -> Client {
600        self.hub.close();
601        for id in self.listeners {
602            self.client.off_listener(id);
603        }
604        self.client
605    }
606}
607
608impl Hub {
609    fn new(offer_acks: bool) -> Arc<Hub> {
610        Arc::new(Hub {
611            state: Mutex::new(HubState {
612                subs: HashMap::new(),
613                last: None,
614                acks: HashMap::new(),
615                next_ack: 0,
616                offer_acks,
617                closed: false,
618            }),
619            forwarded: watch::Sender::new(0),
620        })
621    }
622
623    fn event(&self, event: Event) {
624        let mut st = lock(&self.state);
625        if st.closed || st.subs.is_empty() {
626            return;
627        }
628        let name = event.name().to_owned();
629        let wanted = |s: &Sub| s.events.as_ref().is_none_or(|e| e.contains(&name));
630        // One ack id per server ack, offered to every webview that gets the event.
631        let mut ack_id = None;
632        if let Some(sender) = event.ack_sender().filter(|_| st.offer_acks) {
633            let mut webviews: Vec<String> = st
634                .subs
635                .values()
636                .filter(|s| wanted(s))
637                .filter_map(|s| s.webview.clone())
638                .collect();
639            webviews.sort();
640            webviews.dedup();
641            if !webviews.is_empty() {
642                st.acks.retain(|_, a| a.at.elapsed() < ACK_TTL);
643                for label in &webviews {
644                    st.make_room(label);
645                }
646                st.next_ack += 1;
647                let id = st.next_ack;
648                st.acks.insert(
649                    id,
650                    PendingAck {
651                        sender,
652                        at: Instant::now(),
653                        webviews,
654                    },
655                );
656                ack_id = Some(id);
657            }
658        }
659        let args: crate::Args = event.into_payload().into();
660        st.send_all(|s| {
661            wanted(s).then(|| Message::Event {
662                event: name.clone(),
663                args: args.clone(),
664                ack_id: ack_id.filter(|_| s.webview.is_some()),
665            })
666        });
667    }
668
669    fn state(&self, state: &ConnectionState) {
670        self.forward_state(State::from(state));
671    }
672
673    fn forward_state(&self, state: State) {
674        let mut st = lock(&self.state);
675        if st.closed {
676            return;
677        }
678        st.last = Some(state.clone());
679        st.send_all(|_| {
680            Some(Message::State {
681                state: state.clone(),
682                snapshot: false,
683            })
684        });
685        drop(st);
686        self.forwarded.send_modify(|n| *n += 1);
687    }
688
689    /// Waits (bounded) until the event task forwarded a state past the initial connect, so a
690    /// snapshot taken now is the connected state and nothing older follows it.
691    async fn settle(&self, client: &Client) {
692        let mut rx = self.forwarded.subscribe();
693        let settled = |hub: &Hub| {
694            !matches!(
695                lock(&hub.state).last,
696                None | Some(State::Connecting { attempt: 0 })
697            )
698        };
699        let _ = tokio::time::timeout(SETTLE, async {
700            while !settled(self) && !client.state().is_closed() {
701                if rx.changed().await.is_err() {
702                    return;
703                }
704            }
705        })
706        .await;
707    }
708
709    /// Sends the snapshot (the last forwarded state, else the client's) as the first state
710    /// message of `sub`, under the lock that orders every message of this client.
711    fn snapshot_to(&self, sub: SubscriptionId, client: &Client) -> State {
712        self.snapshot_or(sub, || State::from(&client.state()))
713    }
714
715    fn snapshot_or(&self, sub: SubscriptionId, fallback: impl FnOnce() -> State) -> State {
716        Self::snapshot_locked(&mut lock(&self.state), sub, fallback)
717    }
718
719    /// Adds `sub` and sends its snapshot in one critical section: the snapshot is its very
720    /// first message.
721    fn attach(&self, id: SubscriptionId, sub: Sub, fallback: impl FnOnce() -> State) -> State {
722        let mut st = lock(&self.state);
723        st.subs.insert(id, sub);
724        Self::snapshot_locked(&mut st, id, fallback)
725    }
726
727    fn snapshot_locked(
728        st: &mut HubState,
729        sub: SubscriptionId,
730        fallback: impl FnOnce() -> State,
731    ) -> State {
732        let state = st.last.clone().unwrap_or_else(fallback);
733        if let Some(s) = st.subs.get(&sub) {
734            let message = Message::State {
735                state: state.clone(),
736                snapshot: true,
737            };
738            if s.channel.send(message).is_err() {
739                st.subs.remove(&sub);
740            }
741        }
742        state
743    }
744
745    fn remove_sub(&self, sub: SubscriptionId, webview: Option<&str>) -> bool {
746        let mut st = lock(&self.state);
747        match st.subs.get(&sub) {
748            Some(s) if webview.is_none_or(|w| s.webview.as_deref() == Some(w)) => {
749                st.subs.remove(&sub);
750                true
751            }
752            _ => false,
753        }
754    }
755
756    fn drop_webview(&self, label: &str) {
757        let mut st = lock(&self.state);
758        st.subs.retain(|_, s| s.webview.as_deref() != Some(label));
759        st.acks.retain(|_, a| {
760            a.webviews.retain(|w| w != label);
761            !a.webviews.is_empty()
762        });
763    }
764
765    fn count(&self, label: &str) -> usize {
766        lock(&self.state)
767            .subs
768            .values()
769            .filter(|s| s.webview.as_deref() == Some(label))
770            .count()
771    }
772
773    fn take_ack(&self, ack_id: u64, webview: &str) -> Option<AckSender> {
774        let mut st = lock(&self.state);
775        let ok = st
776            .acks
777            .get(&ack_id)
778            .is_some_and(|a| a.at.elapsed() < ACK_TTL && a.webviews.iter().any(|w| w == webview));
779        ok.then(|| st.acks.remove(&ack_id).expect("checked").sender)
780    }
781
782    fn stop_acks(&self) {
783        let mut st = lock(&self.state);
784        st.offer_acks = false;
785        st.acks.clear();
786    }
787
788    fn close(&self) {
789        let mut st = lock(&self.state);
790        st.closed = true;
791        st.subs.clear();
792        st.acks.clear();
793    }
794}
795
796impl HubState {
797    /// Sends `make(sub)` to every subscription it returns a message for; a failed send (the
798    /// webview is gone) ends that subscription.
799    fn send_all(&mut self, make: impl Fn(&Sub) -> Option<Message>) {
800        self.subs.retain(|_, s| match make(s) {
801            Some(message) => s.channel.send(message).is_ok(),
802            None => true,
803        });
804    }
805
806    /// Keeps `label` under its ack budget by forgetting its own oldest offer.
807    ///
808    /// ponytail: O(pending acks) per server ack, bounded by the per-webview budget times the
809    /// webviews; an ordered queue per webview if that shows up in a profile.
810    fn make_room(&mut self, label: &str) {
811        let mine = || {
812            self.acks
813                .iter()
814                .filter(|(_, a)| a.webviews.iter().any(|w| w == label))
815        };
816        if mine().count() < MAX_PENDING_ACKS_PER_WEBVIEW {
817            return;
818        }
819        let Some(oldest) = mine().min_by_key(|(_, a)| a.at).map(|(id, _)| *id) else {
820            return;
821        };
822        let ack = self.acks.get_mut(&oldest).expect("found above");
823        ack.webviews.retain(|w| w != label);
824        if ack.webviews.is_empty() {
825            self.acks.remove(&oldest);
826        }
827    }
828}
829
830#[cfg(test)]
831mod tests {
832    use super::*;
833    use std::sync::OnceLock;
834    use tokio::sync::Notify;
835
836    /// (client id, reached, go): the connect of that id (only: other tests run in parallel)
837    /// waits right after it registered its client.
838    type Pause = (String, Arc<Notify>, Arc<Notify>);
839    static PAUSE: OnceLock<Mutex<Option<Pause>>> = OnceLock::new();
840
841    pub(super) async fn after_insert(id: &str) {
842        let pause = lock(PAUSE.get_or_init(Mutex::default)).clone();
843        if let Some((target, reached, go)) = pause {
844            if target == id {
845                reached.notify_one();
846                go.notified().await;
847            }
848        }
849    }
850
851    /// Once the client is registered, its pending id and slot are given back (they counted
852    /// twice against the cap while the connect settled).
853    #[tokio::test(flavor = "multi_thread")]
854    async fn a_registered_connect_holds_no_pending_slot() {
855        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
856            let io = SocketIo::default();
857            let (reached, go) = (Arc::new(Notify::new()), Arc::new(Notify::new()));
858            *lock(PAUSE.get_or_init(Mutex::default)) =
859                Some(("p".into(), Arc::clone(&reached), Arc::clone(&go)));
860            let (ch, _rx) = channel();
861            let connecting = {
862                let io = io.clone();
863                tokio::spawn(async move {
864                    let url = conformance_server();
865                    let builder = ClientBuilder::new(url.clone());
866                    io.connect_from_webview(
867                        "p".into(),
868                        &url,
869                        None,
870                        builder,
871                        Default::default(),
872                        sub(ch, "w"),
873                    )
874                    .await
875                })
876            };
877            reached.notified().await;
878            *lock(PAUSE.get().unwrap()) = None;
879            {
880                let pending = lock(&io.inner.pending);
881                assert!(pending.ids.is_empty(), "the id is still pending");
882                assert_eq!(pending.slots.get("w").copied().unwrap_or_default(), 0);
883            }
884            go.notify_one();
885            connecting.await.unwrap().unwrap();
886            io.remove("p").unwrap().disconnect().await.unwrap();
887        })
888        .await
889        .expect("test `a_registered_connect_holds_no_pending_slot` timed out")
890    }
891    use socketio_next_testing::{conformance_server, socket_io_server};
892    use tauri::ipc::InvokeResponseBody;
893
894    fn channel() -> (
895        Channel<Message>,
896        std::sync::mpsc::Receiver<serde_json::Value>,
897    ) {
898        let (tx, rx) = std::sync::mpsc::channel();
899        let channel = Channel::new(move |body| {
900            if let InvokeResponseBody::Json(json) = body {
901                let _ = tx.send(serde_json::from_str(&json).unwrap());
902            }
903            Ok(())
904        });
905        (channel, rx)
906    }
907
908    fn sub(channel: Channel<Message>, webview: &str) -> SubscribeArgs {
909        SubscribeArgs {
910            events: None,
911            channel,
912            webview: Some(webview.to_owned()),
913        }
914    }
915
916    /// A real server event with an ack (they are only made by the client): `question`.
917    async fn question(client_events: &mut tokio::sync::mpsc::UnboundedReceiver<Event>) -> Event {
918        loop {
919            let e = client_events.recv().await.unwrap();
920            if e.name() == "question" {
921                return e;
922            }
923        }
924    }
925
926    async fn asking_client() -> (Client, tokio::sync::mpsc::UnboundedReceiver<Event>) {
927        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
928        let client = ClientBuilder::new(conformance_server())
929            .on("question", move |event: Event, _: Client| {
930                let _ = tx.send(event);
931                std::future::ready(())
932            })
933            .connect()
934            .await
935            .unwrap();
936        (client, rx)
937    }
938
939    /// Finding 7: once a disconnect started, server acks are no longer offered or kept.
940    #[tokio::test(flavor = "multi_thread")]
941    async fn no_acks_are_minted_after_stop_acks() {
942        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
943            let (client, mut events) = asking_client().await;
944            let hub = Hub::new(true);
945            let (ch, rx) = channel();
946            lock(&hub.state).subs.insert(1, sub(ch, "w").into_sub());
947            client.emit("ask", ()).unwrap();
948            let q = question(&mut events).await;
949            hub.stop_acks();
950            hub.event(q);
951            let m = rx.recv_timeout(Duration::from_secs(5)).unwrap();
952            assert_eq!(m["event"], "question");
953            assert!(m.get("ackId").is_none(), "{m}");
954            assert!(lock(&hub.state).acks.is_empty());
955            client.disconnect().await.unwrap();
956        })
957        .await
958        .expect("test `no_acks_are_minted_after_stop_acks` timed out")
959    }
960
961    /// Finding 3: a webview's flood of acks forgets only its own oldest offers.
962    #[tokio::test(flavor = "multi_thread")]
963    async fn ack_budget_is_per_webview() {
964        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
965            let (client, mut events) = asking_client().await;
966            let hub = Hub::new(true);
967            let (greedy, _g) = channel();
968            let (polite, polite_rx) = channel();
969            lock(&hub.state)
970                .subs
971                .insert(1, sub(greedy, "greedy").into_sub());
972            // the polite webview gets the first question only
973            lock(&hub.state)
974                .subs
975                .insert(2, sub(polite, "polite").into_sub());
976            client.emit("ask", ()).unwrap();
977            hub.event(question(&mut events).await);
978            let first = polite_rx.recv_timeout(Duration::from_secs(5)).unwrap()["ackId"]
979                .as_u64()
980                .unwrap();
981            hub.remove_sub(2, None);
982            let q = question_with_ack(&client, &mut events).await;
983            for _ in 0..MAX_PENDING_ACKS_PER_WEBVIEW + 10 {
984                hub.event(q.clone());
985            }
986            let greedy_count = lock(&hub.state)
987                .acks
988                .values()
989                .filter(|a| a.webviews.iter().any(|w| w == "greedy"))
990                .count();
991            assert_eq!(greedy_count, MAX_PENDING_ACKS_PER_WEBVIEW);
992            assert!(
993                hub.take_ack(first, "greedy").is_none(),
994                "greedy's own oldest went"
995            );
996            assert!(
997                hub.take_ack(first, "polite").is_some(),
998                "the polite webview kept its ack"
999            );
1000            client.disconnect().await.unwrap();
1001        })
1002        .await
1003        .expect("test `ack_budget_is_per_webview` timed out")
1004    }
1005
1006    async fn question_with_ack(
1007        client: &Client,
1008        events: &mut tokio::sync::mpsc::UnboundedReceiver<Event>,
1009    ) -> Event {
1010        client.emit("ask", ()).unwrap();
1011        question(events).await
1012    }
1013
1014    /// Finding 8: one server ack, one ack id for every subscription, answered once.
1015    #[tokio::test(flavor = "multi_thread")]
1016    async fn one_ack_id_per_server_ack() {
1017        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
1018            let (client, mut events) = asking_client().await;
1019            let hub = Hub::new(true);
1020            let (a, a_rx) = channel();
1021            let (b, b_rx) = channel();
1022            lock(&hub.state).subs.insert(1, sub(a, "w1").into_sub());
1023            lock(&hub.state).subs.insert(2, sub(b, "w2").into_sub());
1024            hub.event(question_with_ack(&client, &mut events).await);
1025            let ida = a_rx.recv_timeout(Duration::from_secs(5)).unwrap()["ackId"].clone();
1026            let idb = b_rx.recv_timeout(Duration::from_secs(5)).unwrap()["ackId"].clone();
1027            assert_eq!(ida, idb);
1028            let id = ida.as_u64().unwrap();
1029            assert!(hub.take_ack(id, "w3").is_none(), "not offered to w3");
1030            assert!(hub.take_ack(id, "w2").is_some());
1031            assert!(hub.take_ack(id, "w1").is_none(), "answered once");
1032            client.disconnect().await.unwrap();
1033        })
1034        .await
1035        .expect("test `one_ack_id_per_server_ack` timed out")
1036    }
1037
1038    /// Finding 5: the snapshot is the first state message and nothing older follows it, even
1039    /// while states are being forwarded.
1040    #[test]
1041    fn snapshot_is_ordered_with_transitions() {
1042        let hub = Hub::new(true);
1043        let (ch0, _rx0) = channel();
1044        lock(&hub.state).subs.insert(1, sub(ch0, "w").into_sub());
1045        let writer = {
1046            let hub = Arc::clone(&hub);
1047            std::thread::spawn(move || {
1048                for attempt in 1..=2000 {
1049                    hub.forward_state(State::Connecting { attempt });
1050                }
1051            })
1052        };
1053        // subscribe while the writer runs
1054        let mut seqs = Vec::new();
1055        for n in 0..20u64 {
1056            let (ch, rx) = channel();
1057            let snapshot = hub.attach(100 + n, sub(ch, "w").into_sub(), || State::Connecting {
1058                attempt: 0,
1059            });
1060            seqs.push((snapshot, rx));
1061        }
1062        writer.join().unwrap();
1063        for (snapshot, rx) in seqs {
1064            let attempts: Vec<u64> = rx
1065                .try_iter()
1066                .map(|m| m["state"]["attempt"].as_u64().unwrap())
1067                .collect();
1068            let State::Connecting { attempt } = snapshot else {
1069                unreachable!()
1070            };
1071            assert_eq!(attempts[0], u64::from(attempt), "the snapshot comes first");
1072            assert!(
1073                attempts.windows(2).all(|w| w[0] < w[1]),
1074                "ordered: {attempts:?}"
1075            );
1076        }
1077    }
1078
1079    /// The real `snapshot_to` with the client fallback and the last forwarded state.
1080    #[tokio::test(flavor = "multi_thread")]
1081    async fn snapshot_uses_the_last_forwarded_state() {
1082        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
1083            let client = ClientBuilder::new(socket_io_server())
1084                .connect()
1085                .await
1086                .unwrap();
1087            let hub = Hub::new(true);
1088            let (ch, rx) = channel();
1089            lock(&hub.state).subs.insert(1, sub(ch, "w").into_sub());
1090            assert!(
1091                matches!(hub.snapshot_to(1, &client), State::Connected { .. }),
1092                "fallback"
1093            );
1094            hub.forward_state(State::Disconnected {
1095                reason: "transport close".into(),
1096                error: None,
1097            });
1098            let (ch2, rx2) = channel();
1099            lock(&hub.state).subs.insert(2, sub(ch2, "w").into_sub());
1100            assert!(matches!(
1101                hub.snapshot_to(2, &client),
1102                State::Disconnected { .. }
1103            ));
1104            assert_eq!(rx2.recv().unwrap()["snapshot"], true);
1105            assert_eq!(rx.recv().unwrap()["state"]["status"], "connected");
1106            client.disconnect().await.unwrap();
1107        })
1108        .await
1109        .expect("test `snapshot_uses_the_last_forwarded_state` timed out")
1110    }
1111
1112    /// Finding 4: a page reload while its connect is in flight leaves no subscription.
1113    #[tokio::test(flavor = "multi_thread")]
1114    async fn reload_during_connect_attaches_nothing() {
1115        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
1116            let io = SocketIo::default();
1117            let (ch, _rx) = channel();
1118            let connecting = {
1119                let io = io.clone();
1120                tokio::spawn(async move {
1121                    // /slow answers CONNECT after 200 ms
1122                    let url = format!("{}/slow", socket_io_server());
1123                    let builder = ClientBuilder::new(url.clone());
1124                    io.connect_from_webview(
1125                        "slow".into(),
1126                        &url,
1127                        None,
1128                        builder,
1129                        Default::default(),
1130                        sub(ch, "w"),
1131                    )
1132                    .await
1133                })
1134            };
1135            tokio::time::sleep(Duration::from_millis(50)).await;
1136            io.drop_webview("w");
1137            connecting.await.unwrap().unwrap();
1138            assert_eq!(io.hub("slow").count("w"), 0);
1139            io.remove("slow").unwrap().disconnect().await.unwrap();
1140        })
1141        .await
1142        .expect("test `reload_during_connect_attaches_nothing` timed out")
1143    }
1144
1145    #[tokio::test(flavor = "multi_thread")]
1146    async fn a_reloaded_webview_loses_its_subscriptions_and_acks() {
1147        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
1148            let io = SocketIo::default();
1149            io.connect("c", ClientBuilder::new(conformance_server()))
1150                .await
1151                .unwrap();
1152            let (a, _) = channel();
1153            let (b, _) = channel();
1154            let (sa, _) = io.subscribe_with("c", sub(a, "a")).unwrap();
1155            let (sb, _) = io.subscribe_with("c", sub(b, "b")).unwrap();
1156            io.drop_webview("a");
1157            assert!(!io.unsubscribe("c", sa));
1158            assert!(io.unsubscribe("c", sb));
1159            io.remove("c").unwrap().disconnect().await.unwrap();
1160        })
1161        .await
1162        .expect("test `a_reloaded_webview_loses_its_subscriptions_and_acks` timed out")
1163    }
1164
1165    #[test]
1166    fn url_allow_list() {
1167        let io = SocketIo::with_allowed(vec![
1168            url::Url::parse("https://api.example.com").unwrap(),
1169            url::Url::parse("wss://rt.example.com/v1/").unwrap(),
1170        ]);
1171        let ok = |url: &str, path: Option<&str>| io.url_allowed(url, path);
1172        assert!(ok("https://api.example.com", None));
1173        assert!(ok(
1174            "https://api.example.com:443/admin?x=1",
1175            Some("/anything/")
1176        ));
1177        assert!(!ok("https://api.example.com.evil.com", None));
1178        assert!(!ok("https://api.example.com:8443", None));
1179        assert!(!ok("http://api.example.com", None));
1180        // the engine.io path is what is checked: the URL's path is only the namespace
1181        assert!(ok("wss://rt.example.com", Some("/v1/socket.io")));
1182        assert!(ok("wss://rt.example.com/v1", Some("v1/")));
1183        assert!(
1184            !ok("wss://rt.example.com/v1", None),
1185            "default /socket.io/ is outside /v1/"
1186        );
1187        assert!(!ok("wss://rt.example.com/v1/chat", Some("/v10/")));
1188        assert!(!ok("not a url", None));
1189        assert!(SocketIo::default().url_allowed("http://anything", Some("/x/")));
1190        // dot segments and backslashes cannot climb out of the prefix
1191        for path in [
1192            "/v1/../admin/",
1193            "/v1/%2e%2e/admin/",
1194            "/v1/%2E%2E/admin/",
1195            "/v1/..\\admin/",
1196            "/v1/.%2e/admin/",
1197            // the URL parser drops tabs and newlines: these are `..` once parsed
1198            "/v1/.\n./admin/",
1199            "/v1/\t../admin/",
1200            "/v1/%252e%252e/admin/",
1201            "/v1/%u002e%u002e/admin/",
1202        ] {
1203            assert!(!ok("wss://rt.example.com", Some(path)), "{path:?}");
1204        }
1205        // a plain path inside the prefix passes the textual checks and the resolution
1206        assert!(ok("wss://rt.example.com", Some("/v1/./socket.io/")));
1207        // only the resolved URL gets this right: `/v1/./socket.io/` is `/v1/socket.io/`,
1208        // inside a prefix of exactly that path (the raw text is not)
1209        let deep = SocketIo::with_allowed(vec![
1210            url::Url::parse("wss://rt.example.com/v1/socket.io/").unwrap(),
1211        ]);
1212        assert!(deep.url_allowed("wss://rt.example.com", Some("/v1/./socket.io/")));
1213        assert!(!deep.url_allowed("wss://rt.example.com", Some("/v1/./other/")));
1214    }
1215
1216    #[test]
1217    fn unknown_ids() {
1218        let io = SocketIo::default();
1219        let channel = Channel::new(|_: InvokeResponseBody| Ok(()));
1220        assert!(matches!(
1221            io.subscribe("x", None, channel),
1222            Err(Error::UnknownClient(_))
1223        ));
1224        assert!(matches!(io.full("x"), Err(Error::UnknownClient(_))));
1225        assert!(matches!(
1226            io.ack("x", 1, "w", Payload::empty()),
1227            Err(Error::UnknownClient(_))
1228        ));
1229        assert!(!io.unsubscribe("x", 1));
1230        assert!(io.remove("x").is_none());
1231        assert!(io.ids().is_empty());
1232    }
1233}