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