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