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