Skip to main content

SideCar/
Spawn.rs

1// DEPENDENCY: This module file was created to resolve a missing module error.
2// The original Spawn.rs was located at Source/Source/SideCar/Spawn.rs in an
3// unusual directory structure. Consider refactoring the directory structure to
4// avoid duplicate/confusing module locations.
5
6use std::fs;
7
8use tauri::{AppHandle, Manager};
9// Note: Mist crate has lib name "Mist", so we use that for imports
10use Mist::dns_port;
11// DEPENDENCY: Add tauri-plugin-shell to Cargo.toml dependencies for Tauri 2.x shell support
12use tauri_plugin_shell::ShellExt;
13
14const DNS_OVERRIDE:&str = include_str!("../Resource/dns-override.js");
15
16/// Spawns a Node.js sidecar with DNS override configured to use the local
17/// Hickory DNS server.
18///
19/// This function:
20/// 1. Creates the app data directory if it doesn't exist
21/// 2. Writes the DNS override JavaScript file to the app data directory
22/// 3. Configures the sidecar process with NODE_OPTIONS to require the DNS
23///    override script
24/// 4. Sets the Resolve environment variable with the local DNS server address
25/// 5. Spawns the sidecar process
26///
27/// # Parameters
28///
29/// * `app` - The Tauri app handle, used to access the app data directory and
30///   shell
31/// * `sidecar_name` - The name of the sidecar executable to spawn
32///
33/// # Returns
34///
35/// Returns `Ok(())` if the sidecar was spawned successfully, or an error if:
36/// - The app data directory couldn't be created or accessed
37/// - The DNS override file couldn't be written
38/// - The sidecar couldn't be found or spawned
39///
40/// # Example
41///
42/// ```rust,no_run
43/// use tauri::Manager;
44/// use SideCar::Spawn::spawn_node_sidecar;
45///
46/// #[tauri::command]
47/// fn launch_sidecar(app:tauri::AppHandle) -> Result<(), String> {
48/// 	spawn_node_sidecar(&app, "my-sidecar").map_err(|e| e.to_string())?;
49/// 	Ok(())
50/// }
51/// ```
52pub fn spawn_node_sidecar(app:&AppHandle, sidecar_name:&str) -> anyhow::Result<()> {
53	// Ensure app data directory exists
54	let data_dir = app.path().app_data_dir()?;
55
56	fs::create_dir_all(&data_dir)?;
57
58	// Write DNS override script to app data directory
59	let override_path = data_dir.join("dns-override.js");
60
61	fs::write(&override_path, DNS_OVERRIDE)?;
62
63	// Get the DNS server port from Mist module
64	let port = dns_port();
65
66	let node_opts = format!("--require {}", override_path.display());
67
68	// Spawn the sidecar with DNS configuration
69	app.shell()
70		.sidecar(sidecar_name)?
71		.env("NODE_OPTIONS", &node_opts)
72		.env("Resolve", format!("127.0.0.1:{port}"))
73		.spawn()?;
74
75	Ok(())
76}