tauri_plugin_socketio/lib.rs
1//! Tauri 2 plugin for [socketio-next](https://docs.rs/socketio-next): one registry of named
2//! Socket.IO clients that Rust and the webviews share. Guide:
3//! <https://s00d.github.io/rust-socketio/tauri/setup>.
4//!
5//! - Rust registers clients with [`SocketIo::connect`] (built and connected here) or
6//! [`SocketIo::insert`] (built elsewhere, e.g. by Tauri-free core code), optionally
7//! [`Access::ReadOnly`] so the webview may only observe them.
8//! - JS (`tauri-plugin-socketio-api`) connects its own clients or attaches to registered ones;
9//! events and state transitions reach it over a per-subscription IPC channel, in order.
10//!
11//! ```no_run
12//! use socketio_next::ClientBuilder;
13//! use tauri_plugin_socketio::{Access, SocketIoExt};
14//!
15//! // `tauri::Builder::default()` in an app
16//! fn app<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
17//! builder
18//! .plugin(tauri_plugin_socketio::init())
19//! .setup(|app| {
20//! // before any await: no page script can take the id first
21//! app.socketio().reserve("core");
22//! let handle = app.handle().clone();
23//! tauri::async_runtime::spawn(async move {
24//! // e.g. built by a crate that knows nothing about Tauri
25//! let client = ClientBuilder::new("http://localhost:3000").connect().await?;
26//! handle.socketio().insert("core", client, Access::ReadOnly)?;
27//! Ok::<_, tauri_plugin_socketio::Error>(())
28//! });
29//! Ok(())
30//! })
31//! }
32//! ```
33#![cfg_attr(docsrs, feature(doc_cfg))]
34
35use tauri::plugin::TauriPlugin;
36use tauri::webview::PageLoadEvent;
37use tauri::{AppHandle, Manager, RunEvent, Runtime, Webview, WindowEvent};
38
39mod commands;
40mod error;
41mod models;
42mod registry;
43
44pub use error::{Error, ErrorPayload, Result};
45pub use models::{Access, Args, ClientInfo, Link, Message, State};
46pub use registry::{
47 ACK_TTL, MAX_CLIENTS_PER_WEBVIEW, MAX_PENDING_ACKS_PER_WEBVIEW, MAX_SUBSCRIPTIONS_PER_WEBVIEW,
48 SocketIo, SubscriptionId,
49};
50/// The client crate, re-exported.
51pub use socketio_next;
52
53/// `app.socketio()` on anything that is a [`Manager`] (`App`, `AppHandle`, `Window`,
54/// `Webview`, ...). Panics when the plugin is not registered ([`init`]).
55pub trait SocketIoExt<R: Runtime> {
56 /// The client registry.
57 fn socketio(&self) -> &SocketIo;
58}
59
60impl<R: Runtime, T: Manager<R>> SocketIoExt<R> for T {
61 fn socketio(&self) -> &SocketIo {
62 self.state::<SocketIo>().inner()
63 }
64}
65
66/// The plugin with the default configuration: [`Builder::new().build()`](Builder).
67pub fn init<R: Runtime>() -> TauriPlugin<R> {
68 Builder::new().build()
69}
70
71/// Configures the plugin (id `socketio`).
72///
73/// Subscriptions of a webview end when it starts loading a new page or its window is
74/// destroyed, so a reload never leaves listeners behind.
75#[derive(Debug, Default)]
76pub struct Builder {
77 allowed: Vec<url::Url>,
78}
79
80impl Builder {
81 /// No URL restriction.
82 pub fn new() -> Self {
83 Builder::default()
84 }
85
86 /// Lets the webview `connect` only to URLs under `prefix` (same scheme, host and port;
87 /// the path must start with the prefix's path on a `/` boundary). Call it once per
88 /// allowed server; without any call every URL is allowed. Rust's
89 /// [`SocketIo::connect`] and [`SocketIo::insert`] are never restricted.
90 ///
91 /// The socket runs in Rust, so the app's CSP `connect-src` does **not** apply to it: with
92 /// `allow-connect`, a page script could otherwise open connections anywhere with any
93 /// headers.
94 ///
95 /// # Panics
96 ///
97 /// When `prefix` is not an absolute URL (a configuration bug, found at startup).
98 pub fn allow_url_prefix(mut self, prefix: impl AsRef<str>) -> Self {
99 let prefix = prefix.as_ref();
100 let url = url::Url::parse(prefix)
101 .unwrap_or_else(|e| panic!("tauri-plugin-socketio: bad URL prefix: {e}"));
102 self.allowed.push(url);
103 self
104 }
105
106 /// The plugin.
107 pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
108 let allowed = self.allowed;
109 tauri::plugin::Builder::new("socketio")
110 .invoke_handler(tauri::generate_handler![
111 commands::connect,
112 commands::disconnect,
113 commands::emit,
114 commands::emit_with_ack,
115 commands::ack,
116 commands::subscribe,
117 commands::unsubscribe,
118 commands::list,
119 commands::state,
120 commands::link_info,
121 commands::set_auth,
122 commands::set_headers,
123 commands::set_query,
124 commands::reconnect,
125 ])
126 .setup(move |app, _api| {
127 app.manage(SocketIo::with_allowed(allowed));
128 Ok(())
129 })
130 .on_page_load(|webview, payload| page_load(webview, payload.event()))
131 .on_event(run_event)
132 .build()
133 }
134}
135
136/// A new page starts loading: the old page's subscriptions and acks go.
137fn page_load<R: Runtime>(webview: &Webview<R>, event: PageLoadEvent) {
138 if event == PageLoadEvent::Started {
139 if let Some(io) = webview.try_state::<SocketIo>() {
140 io.drop_webview(webview.label());
141 }
142 }
143}
144
145/// A window is destroyed: its webview's subscriptions, acks and the clients it connected go.
146fn run_event<R: Runtime>(app: &AppHandle<R>, event: &RunEvent) {
147 if let RunEvent::WindowEvent {
148 label,
149 event: WindowEvent::Destroyed,
150 ..
151 } = event
152 {
153 window_destroyed(app, label);
154 }
155}
156
157fn window_destroyed<R: Runtime>(app: &AppHandle<R>, label: &str) {
158 if let Some(io) = app.try_state::<SocketIo>() {
159 io.drop_webview(label);
160 // the clients it connected go with it (a reload keeps them: they survive page loads)
161 let io = SocketIo::clone(&io);
162 let label = label.to_owned();
163 tauri::async_runtime::spawn(async move { io.disconnect_owned(&label).await });
164 }
165}
166
167/// The hooks with the events tauri passes them. tauri's mock runtime emits neither page loads
168/// nor `Destroyed`, so that tauri calls them is not covered here (nor `run_event`'s one-line
169/// match); what they do is.
170#[cfg(test)]
171mod tests {
172 use super::*;
173 use tauri::ipc::{Channel, InvokeResponseBody};
174 use tauri::test::{mock_builder, mock_context, noop_assets};
175
176 #[test]
177 fn the_hooks_end_the_webview_subscriptions() {
178 let app = mock_builder()
179 .plugin(init())
180 .build(mock_context(noop_assets()))
181 .unwrap();
182 let webview = tauri::WebviewWindowBuilder::new(&app, "w", Default::default())
183 .build()
184 .unwrap();
185 let io = app.socketio().clone();
186 let client = tauri::async_runtime::block_on(io.connect(
187 "c",
188 socketio_next::ClientBuilder::new(socketio_next_testing::conformance_server()),
189 ))
190 .unwrap();
191 let sub = || {
192 io.subscribe_with(
193 "c",
194 registry::SubscribeArgs {
195 events: None,
196 channel: Channel::new(|_: InvokeResponseBody| Ok(())),
197 webview: Some("w".into()),
198 },
199 )
200 .unwrap()
201 .0
202 };
203 let s = sub();
204 page_load(webview.as_ref(), PageLoadEvent::Finished);
205 assert!(io.unsubscribe("c", s), "a finished load keeps it");
206 let s = sub();
207 page_load(webview.as_ref(), PageLoadEvent::Started);
208 assert!(!io.unsubscribe("c", s), "a new page ends it");
209 let s = sub();
210 // RunEvent is non_exhaustive (not constructible here); run_event only matches it
211 window_destroyed(app.handle(), "w");
212 assert!(!io.unsubscribe("c", s), "a destroyed window ends it");
213 tauri::async_runtime::block_on(client.disconnect()).unwrap();
214 }
215}