tauri-plugin-devtools 3.0.0-alpha.0

CrabNebula devtools for Tauri: Inspect, monitor, and understand your application with ease.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
mod server;

use devtools_core::aggregator::Aggregator;
use devtools_core::bridge_layer::BridgeLayer;
use devtools_core::layer::Layer;
use devtools_core::server::wire::tauri::tauri_server::TauriServer;
use devtools_core::server::{Server, ServerHandle};
use devtools_core::Command;
pub use devtools_core::Error;
use devtools_core::{Result, Shared};
use futures::FutureExt;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use tauri::{Manager, Runtime};
use tokio::sync::mpsc;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::Layer as _;

#[cfg(target_os = "ios")]
mod ios {
    use cocoa::base::id;
    use objc::*;

    const UTF8_ENCODING: usize = 4;
    pub struct NSString(pub id);

    impl NSString {
        pub fn new(s: &str) -> Self {
            // Safety: objc runtime calls are unsafe
            NSString(unsafe {
                let ns_string: id = msg_send![class!(NSString), alloc];
                let ns_string: id = msg_send![ns_string,
                                            initWithBytes:s.as_ptr()
                                            length:s.len()
                                            encoding:UTF8_ENCODING];

                // The thing is allocated in rust, the thing must be set to autorelease in rust to relinquish control
                // or it can not be released correctly in OC runtime
                let _: () = msg_send![ns_string, autorelease];

                ns_string
            })
        }
    }

    swift_rs::swift!(pub fn devtools_log(
      level: u8, message: *const std::ffi::c_void
    ));
}

pub struct Devtools {
    pub connection: ConnectionInfo,
    pub server_handle: ServerHandle,
}

fn init_plugin<R: Runtime>(
    addr: SocketAddr,
    publish_interval: Duration,
    aggregator: Aggregator,
    cmd_tx: mpsc::Sender<Command>,
) -> tauri::plugin::TauriPlugin<R> {
    tauri::plugin::Builder::new("probe")
        .setup(move |app_handle, _api| {
            let (health_reporter, health_service) = tonic_health::server::health_reporter();

            health_reporter
                .set_serving::<TauriServer<server::TauriService<R>>>()
                .now_or_never()
                .unwrap();

            let server = Server::new(
                cmd_tx,
                health_reporter,
                health_service,
                server::TauriService {
                    app_handle: app_handle.clone(),
                },
                server::MetaService {
                    app_handle: app_handle.clone(),
                },
                server::SourcesService {
                    app_handle: app_handle.clone(),
                },
            );
            let server_handle = server.handle();

            app_handle.manage(Devtools {
                connection: connection_info(&addr),
                server_handle,
            });

            #[cfg(not(target_os = "ios"))]
            print_link(&addr);

            #[cfg(target_os = "ios")]
            {
                std::thread::spawn(move || {
                    std::thread::sleep(std::time::Duration::from_secs(3));
                    print_link(&addr);
                });
            }

            // spawn the server and aggregator in a separate thread
            // so we don't interfere with the application we're trying to instrument
            // TODO find a way to move this out of the tauri plugin
            thread::spawn(move || {
                use tracing_subscriber::EnvFilter;
                let s = tracing_subscriber::fmt()
                    .with_env_filter(EnvFilter::from_default_env())
                    .finish();
                let _subscriber_guard = tracing::subscriber::set_default(s);

                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap();

                rt.block_on(async move {
                    let aggregator = tokio::spawn(aggregator.run(publish_interval));
                    server.run(addr).await.unwrap();
                    aggregator.abort();
                });
            });

            Ok(())
        })
        .build()
}

/// Initializes the global tracing subscriber.
///
/// See [`Builder::init`] for details and documentation.
///
/// # Panics
///
/// This function will panic if it is called more than once, or if another library has already initialized a global tracing subscriber.
#[must_use = "This function returns a TauriPlugin that needs to be added to the Tauri app in order to properly instrument it."]
pub fn init<R: Runtime>() -> tauri::plugin::TauriPlugin<R> {
    Builder::default().init()
}

/// Initializes the global tracing subscriber.
///
/// See [`Builder::try_init`] for details and documentation.
///
/// # Errors
///
/// This function will fail if it is called more than once, or if another library has already initialized a global tracing subscriber.
#[must_use = "This function returns a TauriPlugin that needs to be added to the Tauri app in order to properly instrument it."]
pub fn try_init<R: Runtime>() -> Result<tauri::plugin::TauriPlugin<R>> {
    Builder::default().try_init()
}

/// The builder can be use to customize the instrumentation.
pub struct Builder {
    host: IpAddr,
    port: u16,
    publish_interval: Duration,
    strict_port: bool,
    bridge_layer: BridgeLayer,
}

impl Default for Builder {
    fn default() -> Self {
        Self {
            #[cfg(any(target_os = "ios", target_os = "android"))]
            host: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
            #[cfg(not(any(target_os = "ios", target_os = "android")))]
            host: IpAddr::V4(Ipv4Addr::LOCALHOST),
            port: 3033,
            publish_interval: Duration::from_millis(200),
            strict_port: false,
            bridge_layer: BridgeLayer::new(Vec::new()),
        }
    }
}

impl Builder {
    /// Specify which IP addresses the instrumentation server should listen on.
    ///
    /// You can set this to [`Ipv4Addr::UNSPECIFIED`] to listen on all addresses, including LAN and public ones.
    ///
    /// **default:** [`Ipv4Addr::LOCALHOST`] on desktop, [`Ipv4Addr::UNSPECIFIED`] on mobile.
    pub fn host(&mut self, host: IpAddr) -> &mut Self {
        self.host = host;
        self
    }

    /// Specify the instrumentation server port.
    ///
    /// Currently `devtools` **does not** pick a random free port if the configured one
    /// is already taken, so you will need to configure a different one manually.
    ///
    /// **default:** `3033`
    pub fn port(&mut self, port: u16) -> &mut Self {
        self.port = port;
        self
    }

    /// By default the instrumentation will pick a free port if the default (or configured) one is
    /// no available. By setting this to `true` you can disable this behaviour and cause
    /// the server to abort instead.
    ///
    /// **default:** `false`
    pub fn strict_port(&mut self, strict: bool) -> &mut Self {
        self.strict_port = strict;
        self
    }

    /// Attaches the given logger to our tracing subscriber.
    ///
    /// Internally we will bridge all log events to this logger.
    ///
    /// This is particularly useful to have compatibility with tauri-plugin-log.
    pub fn attach_logger(&mut self, logger: Box<dyn log::Log>) -> &mut Self {
        self.bridge_layer.add_logger(logger);
        self
    }

    /// The interval in which updates are sent to the connected UI.
    ///
    /// You can tweak this setting to reduce the time between updates, when for example your app
    /// is generating a lot of events, the buffer might fill up and cause some events to get lost.
    ///
    /// **default:** `200ms`
    pub fn publish_interval(&mut self, interval: Duration) -> &mut Self {
        self.publish_interval = interval;
        self
    }

    /// Initializes the global tracing subscriber.
    ///
    /// This should be called as early in the execution of the app as possible.
    /// Any events that occur before initialization will be ignored.
    ///
    /// This function returns a [`tauri::plugin::TauriPlugin`] that needs to be added to the
    /// Tauri app in order to properly instrument it.
    ///
    /// # Example
    ///
    /// Make sure to check out the `examples` sub folder for a fully working setup.
    ///
    /// ```no_run
    /// let devtools_plugin = tauri_plugin_devtools::Builder::default().init();
    ///
    /// tauri::Builder::default()
    ///     .plugin(devtools_plugin)
    ///      // ... the rest of the tauri setup code
    /// #   .run(tauri::test::mock_context(tauri::test::noop_assets()))
    /// #   .expect("error while running tauri application");
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if it is called more than once, or if another library has already initialized a global tracing subscriber.
    #[must_use = "This function returns a TauriPlugin that needs to be added to the Tauri app in order to properly instrument it."]
    pub fn init<R: Runtime>(self) -> tauri::plugin::TauriPlugin<R> {
        self.try_init().unwrap()
    }

    /// Initializes the global tracing subscriber.
    ///
    /// This should be called as early in the execution of the app as possible.
    /// Any events that occur before initialization will be ignored.
    ///
    /// This function returns a [`tauri::plugin::TauriPlugin`] that needs to be added to the
    /// Tauri app in order to properly instrument it.
    ///
    /// # Example
    ///
    /// Make sure to check out the `examples` sub folder for a fully working setup.
    ///
    /// ```no_run
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let devtools_plugin = tauri_plugin_devtools::Builder::default().try_init()?;
    ///
    ///     tauri::Builder::default()
    ///         .plugin(devtools_plugin)
    ///          // ... the rest of the tauri setup code
    /// #       .run(tauri::test::mock_context(tauri::test::noop_assets()))
    /// #       .expect("error while running tauri application");
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This function will fail if it is called more than once, or if another library has already initialized a global tracing subscriber.
    #[must_use = "This function returns a TauriPlugin that needs to be added to the Tauri app in order to properly instrument it."]
    pub fn try_init<R: Runtime>(self) -> Result<tauri::plugin::TauriPlugin<R>> {
        // set up data channels & shared data
        let shared = Arc::new(Shared::default());
        let (event_tx, event_rx) = mpsc::channel(512);
        let (cmd_tx, cmd_rx) = mpsc::channel(256);

        // set up components
        let layer = Layer::new(shared.clone(), event_tx);
        let aggregator = Aggregator::new(shared, event_rx, cmd_rx);

        // initialize early so we don't miss any spans
        tracing_subscriber::registry()
            .with(layer.with_filter(tracing_subscriber::filter::LevelFilter::TRACE))
            .with(
                self.bridge_layer
                    .with_filter(tracing_subscriber::filter::LevelFilter::TRACE),
            )
            .try_init()
            .map_err(devtools_core::Error::from)?;

        let mut port = self.port;
        if !self.strict_port && !port_is_available(&self.host, port) {
            port = (1025..65535)
                .find(|port| port_is_available(&self.host, *port))
                .ok_or(Error::NoFreePorts)?;
        }

        let addr = SocketAddr::new(self.host, port);

        let plugin = init_plugin(addr, self.publish_interval, aggregator, cmd_tx);
        Ok(plugin)
    }
}

fn port_is_available(host: &IpAddr, port: u16) -> bool {
    TcpListener::bind(SocketAddr::new(*host, port)).is_ok()
}

pub struct ConnectionInfo {
    pub host: IpAddr,
    pub port: u16,
}

fn connection_info(addr: &SocketAddr) -> ConnectionInfo {
    ConnectionInfo {
        host: if addr.ip() == Ipv4Addr::UNSPECIFIED {
            #[cfg(target_os = "ios")]
            {
                local_ip_address::list_afinet_netifas()
                    .and_then(|ifas| {
                        ifas.into_iter()
                            .find_map(|(name, addr)| {
                                if name == "en0" && !addr.is_loopback() && addr.is_ipv4() {
                                    Some(addr)
                                } else {
                                    None
                                }
                            })
                            .ok_or(local_ip_address::Error::LocalIpAddressNotFound)
                    })
                    .unwrap_or_else(|_| local_ip_address::local_ip().unwrap_or_else(|_| addr.ip()))
            }
            #[cfg(not(target_os = "ios"))]
            {
                local_ip_address::local_ip().unwrap_or_else(|_| addr.ip())
            }
        } else {
            addr.ip()
        },
        port: addr.port(),
    }
}

fn print_link(addr: &SocketAddr) {
    let url = if option_env!("__DEVTOOLS_LOCAL_DEVELOPMENT").is_some() {
        "http://localhost:5173/dash/"
    } else {
        "https://devtools.crabnebula.dev/dash/"
    };

    let connection = connection_info(addr);
    let url = format!("{url}{}/{}", connection.host, connection.port);

    #[cfg(target_os = "ios")]
    unsafe {
        ios::devtools_log(
            3,
            ios::NSString::new(
                format!(
                    r"
   {} {}{}
   {}   Local:   {}
",
                    "Tauri Devtools",
                    "v",
                    env!("CARGO_PKG_VERSION"),
                    "->",
                    url
                )
                .as_str(),
            )
            .0 as _,
        );
    }

    #[cfg(not(target_os = "ios"))]
    {
        use colored::Colorize;
        println!(
            r"
   {} {}{}
   {}   Local:   {}
",
            "Tauri Devtools".bright_purple(),
            "v".purple(),
            env!("CARGO_PKG_VERSION").purple(),
            "".bright_purple(),
            url.underline().blue()
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn send_request_retrying(
        client: &reqwest::Client,
        request: &reqwest::Request,
    ) -> reqwest::Response {
        let mut last_error = None;

        // The server starts listening on a background thread.
        // Give it a few retries so the test is more reliable.
        for _ in 0..10 {
            match client.execute(request.try_clone().unwrap()).await {
                Ok(response) => return response,
                Err(error) => {
                    last_error = Some(error);
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            }
        }

        panic!("failed to connect to the devtools server: {last_error:?}");
    }

    #[tokio::test]
    async fn plugin_supports_dynamic_cors_allowlist() {
        // Allocate an ephemeral port.
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);

        // Setup plugin.
        let shared = Arc::new(Shared::default());
        let (_event_tx, event_rx) = mpsc::channel(1);
        let (cmd_tx, cmd_rx) = mpsc::channel(1);
        let aggregator = Aggregator::new(shared, event_rx, cmd_rx);
        let plugin = init_plugin(addr, Duration::from_millis(200), aggregator, cmd_tx);

        // Register to mock app.
        let app = tauri::test::mock_builder()
            .plugin(plugin)
            .build(tauri::test::mock_context(tauri::test::noop_assets()))
            .unwrap();

        // Retrieve the Devtools state handle.
        let devtools = app
            .try_state::<Devtools>()
            .expect("the plugin should expose Devtools as managed state");

        // Use a clearly unrelated origin that isn't allowed by default.
        let origin = "https://dynamic-origin.example";
        let client = reqwest::Client::new();
        let req = client
            .get(format!("http://{addr}"))
            .header("origin", origin)
            .build()
            .unwrap();

        // First reset to default Prod origins.
        devtools.server_handle.reset_defaults(false);
        let response = send_request_retrying(&client, &req).await;
        assert!(
            response
                .headers()
                .get("access-control-allow-origin")
                .is_none(),
            "the origin must not be allowed before using the server handle; ensure \
             __DEVTOOLS_LOCAL_DEVELOPMENT is not set while compiling this test"
        );

        // Then add it as allowed and assert again.
        devtools.server_handle.allow_origin(origin.parse().unwrap());
        let response = send_request_retrying(&client, &req).await;
        let allowed_origin = response
            .headers()
            .get("access-control-allow-origin")
            .expect("the dynamically added origin should be allowed");
        assert_eq!(allowed_origin, origin);

        // Finally check the development behavior is to reflect any domain.
        devtools.server_handle.reset_defaults(true);
        let response = send_request_retrying(&client, &req).await;
        let allowed_origin = response
            .headers()
            .get("access-control-allow-origin")
            .expect("development should reflect any origin");
        assert_eq!(allowed_origin, origin);

        let other_origin = "https://dev-origin.example";
        let response = send_request_retrying(
            &client,
            &client
                .get(format!("http://{addr}"))
                .header("origin", other_origin)
                .build()
                .unwrap(),
        )
        .await;
        let allowed_origin = response
            .headers()
            .get("access-control-allow-origin")
            .expect("development should reflect any origin");
        assert_eq!(allowed_origin, other_origin);
    }
}