H6: isolated data directory for dev and live-check instances

`--data-dir DIR` / `LUTRA_DATA_DIR` move settings, the recovery journal,
the rendezvous file and the WebView2 user data folder into one directory.
`--control PORT` without either uses `<temp>/lutra-control/<port>/`. The
SHA-256-checked Phpactor cache stays shared from the user's data dir
(`Engine::share_tools_from`). An isolated instance never forwards to or
registers as the user's main instance; `rendezvous::dir()` honours
`LUTRA_DATA_DIR` after `LUTRA_RENDEZVOUS_DIR`, so the CLI finds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-25 13:03:31 +01:00
parent e5891ddeb4
commit ba70b0f43a
10 changed files with 418 additions and 29 deletions

View file

@ -8,6 +8,8 @@ use std::path::PathBuf;
pub struct Args {
/// Port for the JSON control channel (`--control PORT`).
pub control: Option<u16>,
/// Isolated data directory (`--data-dir PATH`), see [`crate::datadir`].
pub data_dir: Option<PathBuf>,
/// Folder or file to open.
pub path: Option<PathBuf>,
/// `--help` was given.
@ -17,9 +19,13 @@ pub struct Args {
}
/// Usage text for `--help`.
pub const USAGE: &str = "usage: lutra-desktop [--control PORT] [PATH]
pub const USAGE: &str = "usage: lutra-desktop [--control PORT] [--data-dir DIR] [PATH]
--control PORT serve the JSON control channel on 127.0.0.1:PORT
--control PORT serve the JSON control channel on 127.0.0.1:PORT; without
--data-dir or LUTRA_DATA_DIR the data lives in
<temp>/lutra-control/PORT
--data-dir DIR keep settings, the recovery journal and webview data in
DIR instead of the user's data (also: LUTRA_DATA_DIR)
--version print the version
--help print this help";
@ -41,8 +47,8 @@ pub fn parse_os(args: impl IntoIterator<Item = OsString>) -> Result<Args, String
/// Parses the arguments after the program name.
///
/// # Errors
/// A message for an unknown flag, a missing or invalid port, or more than one
/// path.
/// A message for an unknown flag, a missing or invalid port, a missing or
/// empty data directory, or more than one path.
pub fn parse(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
let mut parsed = Args::default();
let mut args = args.into_iter();
@ -51,11 +57,19 @@ pub fn parse(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
parsed.control = Some(port(value)?);
continue;
}
if let Some(value) = arg.strip_prefix("--data-dir=") {
parsed.data_dir = Some(data_dir(value)?);
continue;
}
match arg.as_str() {
"--control" => {
let value = args.next().ok_or("--control needs a port")?;
parsed.control = Some(port(&value)?);
}
"--data-dir" => {
let value = args.next().ok_or("--data-dir needs a directory")?;
parsed.data_dir = Some(data_dir(&value)?);
}
"--help" | "-h" => parsed.help = true,
"--version" | "-V" => parsed.version = true,
flag if flag.starts_with('-') => return Err(format!("unknown option {flag}")),
@ -81,6 +95,17 @@ fn port(value: &str) -> Result<u16, String> {
}
}
/// Parses a `--data-dir` value.
///
/// # Errors
/// A message if the value is empty.
fn data_dir(value: &str) -> Result<PathBuf, String> {
if value.is_empty() {
return Err("--data-dir needs a directory".into());
}
Ok(PathBuf::from(value))
}
#[cfg(test)]
mod tests {
use super::*;
@ -98,6 +123,17 @@ mod tests {
assert_eq!(p(&[]).unwrap(), Args::default());
}
#[test]
fn parses_data_dir() {
let a = p(&["--control", "7956", "--data-dir", "/tmp/iso", "x"]).unwrap();
assert_eq!(a.data_dir, Some(PathBuf::from("/tmp/iso")));
assert_eq!(a.path, Some(PathBuf::from("x")));
let b = p(&["--data-dir=/tmp/other"]).unwrap();
assert_eq!(b.data_dir, Some(PathBuf::from("/tmp/other")));
assert!(p(&["--data-dir"]).is_err());
assert!(p(&["--data-dir="]).is_err());
}
#[test]
fn rejects_bad_input() {
assert!(p(&["--control"]).is_err());

View file

@ -0,0 +1,232 @@
//! Where a desktop instance keeps its files.
//!
//! A normal start uses the user's data: Tauri's app config and app data
//! directories and the default WebView2 user data folder. An isolated
//! start keeps all of it in one directory instead: `settings.json`, the
//! recovery journal under `recovery/`, the rendezvous file and the
//! webview's own data under [`WEBVIEW_DIR`] (its local storage, so the
//! frontend's remembered state such as recent projects and window layout
//! is separate too). A start is isolated, in this order, when
//! - `--data-dir PATH` is given;
//! - `LUTRA_DATA_DIR` is set and not empty;
//! - `--control PORT` is given: the directory is
//! `<temp>/lutra-control/<port>/`, kept between runs so repeated checks
//! keep their state.
//!
//! This keeps development and live-check instances away from the user's
//! own settings and journal. The managed tools (the SHA-256-checked
//! Phpactor PHAR) stay shared from the user's data directory, so an
//! isolated instance does not download its own copy (see
//! [`lutra_engine::Engine::share_tools_from`]). An isolated instance never
//! forwards to, or registers as, the user's main instance (see
//! [`crate::instance`]).
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use lutra_control::rendezvous;
use lutra_engine::EngineConfig;
use crate::args::Args;
/// Folder for the webview's own data inside an isolated directory.
pub const WEBVIEW_DIR: &str = "webview";
/// Folder under the system temp directory for `--control` instances
/// without an explicit data directory.
pub const CONTROL_TEMP_DIR: &str = "lutra-control";
/// The isolated data directory of this start from its arguments,
/// `LUTRA_DATA_DIR` and the system temp directory; `None` for a normal
/// start that uses the user's data.
pub fn isolated(args: &Args) -> Option<PathBuf> {
isolated_dir(
args,
std::env::var_os(rendezvous::DATA_DIR_ENV),
&std::env::temp_dir(),
)
}
/// The isolated data directory for `args`, given the value of
/// `LUTRA_DATA_DIR` (`env`) and the temp directory (`temp`); see the
/// module docs for the order. A relative directory is made absolute
/// against the current directory, so it does not move if the app changes
/// its working directory.
pub fn isolated_dir(args: &Args, env: Option<OsString>, temp: &Path) -> Option<PathBuf> {
let dir = args
.data_dir
.clone()
.or_else(|| env.filter(|v| !v.is_empty()).map(PathBuf::from))
.or_else(|| {
args.control
.map(|port| temp.join(CONTROL_TEMP_DIR).join(port.to_string()))
})?;
Some(std::path::absolute(&dir).unwrap_or(dir))
}
/// The engine directories of an isolated instance: settings and the
/// journal both live in `dir`.
pub fn engine_config(dir: &Path) -> EngineConfig {
EngineConfig {
config_dir: dir.to_path_buf(),
data_dir: dir.to_path_buf(),
}
}
/// The webview's data folder inside an isolated directory.
pub fn webview_dir(dir: &Path) -> PathBuf {
dir.join(WEBVIEW_DIR)
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use lutra_control::client::Client;
use lutra_engine::Engine;
use serde_json::{Value, json};
use super::*;
use crate::host::Host;
use crate::instance;
fn control(port: u16) -> Args {
Args {
control: Some(port),
..Args::default()
}
}
#[test]
fn picks_the_flag_then_the_env_then_the_control_temp_dir() {
let tmp = tempfile::tempdir().unwrap();
let temp = tmp.path();
assert_eq!(isolated_dir(&Args::default(), None, temp), None);
assert_eq!(
isolated_dir(&Args::default(), Some(OsString::new()), temp),
None
);
assert_eq!(
isolated_dir(&control(7956), None, temp),
Some(temp.join("lutra-control").join("7956"))
);
let env = temp.join("env");
assert_eq!(
isolated_dir(&control(7956), Some(env.clone().into()), temp),
Some(env.clone())
);
let flag = Args {
data_dir: Some(temp.join("flag")),
..control(7956)
};
assert_eq!(
isolated_dir(&flag, Some(env.into()), temp),
Some(temp.join("flag"))
);
let relative = Args {
data_dir: Some(PathBuf::from("rel")),
..Args::default()
};
let resolved = isolated_dir(&relative, None, temp).unwrap();
assert!(resolved.is_absolute());
assert!(resolved.ends_with("rel"));
}
/// Lists every file under `dir`, relative to it.
fn files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(listing) = std::fs::read_dir(&d) else {
continue;
};
for entry in listing {
let path = entry.unwrap().path();
if path.is_dir() {
stack.push(path);
} else {
out.push(path.strip_prefix(dir).unwrap().to_path_buf());
}
}
}
out.sort();
out
}
#[test]
fn a_control_instance_leaves_the_user_data_dir_untouched() {
let tmp = tempfile::tempdir().unwrap();
let user = tmp.path().join("user-data");
std::fs::create_dir_all(&user).unwrap();
std::fs::write(
user.join("settings.json"),
"{\"appearance.theme\":\"lutra-light\"}",
)
.unwrap();
let before = files(&user);
let project = tmp.path().join("project");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(project.join("a.php"), "<?php\n").unwrap();
let args = control(7956);
let dir = isolated_dir(&args, None, &tmp.path().join("temp")).unwrap();
assert!(!dir.starts_with(&user));
if std::env::var_os(rendezvous::DIR_ENV).is_none() {
assert_eq!(instance::rendezvous_dir(&args, Some(&dir)), None);
}
assert!(!webview_dir(&dir).starts_with(&user));
let mut engine = Engine::with_config(engine_config(&dir)).unwrap();
engine.share_tools_from(user.clone());
engine.take_events();
engine
.execute("project.open", json!({"path": project}))
.unwrap();
let id = engine
.execute("file.open", json!({"path": "a.php"}))
.unwrap()
.value["id"]
.as_u64()
.unwrap();
let version = engine
.execute("buffer.get", json!({"id": id}))
.unwrap()
.value["version"]
.clone();
engine
.execute(
"buffer.edit",
json!({"id": id, "baseVersion": version,
"edits": [{"from": 6, "to": 6, "insert": "echo 1;\n"}]}),
)
.unwrap();
engine.flush_journal().unwrap();
let host: Arc<Host> = Host::new(engine);
let server = lutra_control::start(0, host.clone()).unwrap();
let mut client =
Client::connect(server.local_addr().port(), Duration::from_secs(5)).unwrap();
client
.execute(
"settings.set",
json!({"key": "appearance.theme", "value": "lutra-dark"}),
)
.unwrap();
assert_eq!(files(&user), before, "user data dir changed");
assert_eq!(
std::fs::read_to_string(user.join("settings.json")).unwrap(),
"{\"appearance.theme\":\"lutra-light\"}"
);
let stored: Value =
serde_json::from_str(&std::fs::read_to_string(dir.join("settings.json")).unwrap())
.unwrap();
assert_eq!(stored["appearance.theme"], "lutra-dark");
assert!(
files(&dir).iter().any(|f| f.starts_with("recovery")),
"journal in the isolated dir: {:?}",
files(&dir)
);
}
}

View file

@ -10,7 +10,10 @@
//!
//! A start with `--control PORT` is a development or automation instance:
//! it skips all of this, so several of them can run side by side, unless
//! `LUTRA_RENDEZVOUS_DIR` names a rendezvous directory for it.
//! `LUTRA_RENDEZVOUS_DIR` names a rendezvous directory for it. A start with
//! an isolated data directory (`--data-dir`, `LUTRA_DATA_DIR`, see
//! [`crate::datadir`]) keeps its rendezvous file there, so it never
//! forwards to, or registers as, the user's main instance.
use std::path::{Path, PathBuf};
use std::sync::Arc;
@ -25,14 +28,21 @@ use crate::host::Host;
/// How long a second start waits for the running instance to answer.
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
/// The rendezvous directory this start uses, `None` if it does not take
/// part in the single instance (see the module docs).
pub fn rendezvous_dir(args: &Args) -> Option<PathBuf> {
/// The rendezvous directory this start uses, given its isolated data
/// directory (`isolated`); `None` if it does not take part in the single
/// instance (see the module docs).
pub fn rendezvous_dir(args: &Args, isolated: Option<&Path>) -> Option<PathBuf> {
let explicit = std::env::var_os(rendezvous::DIR_ENV).is_some_and(|v| !v.is_empty());
if args.control.is_some() && !explicit {
if explicit {
return rendezvous::dir();
}
if args.control.is_some() {
return None;
}
rendezvous::dir()
match isolated {
Some(dir) => Some(dir.to_path_buf()),
None => rendezvous::dir(),
}
}
/// Forwards `path` to a running instance found through `dir`.
@ -116,8 +126,22 @@ mod tests {
control: Some(7937),
..Args::default()
};
assert_eq!(rendezvous_dir(&dev), None);
assert_eq!(rendezvous_dir(&Args::default()), rendezvous::dir());
assert_eq!(rendezvous_dir(&dev, None), None);
assert_eq!(rendezvous_dir(&dev, Some(Path::new("/iso"))), None);
if std::env::var_os(rendezvous::DATA_DIR_ENV).is_none() {
assert_eq!(rendezvous_dir(&Args::default(), None), rendezvous::dir());
}
}
#[test]
fn an_isolated_start_meets_only_its_own_instances() {
if std::env::var_os(rendezvous::DIR_ENV).is_some() {
return;
}
let iso = Path::new("/iso");
let dir = rendezvous_dir(&Args::default(), Some(iso));
assert_eq!(dir.as_deref(), Some(iso));
assert_ne!(dir, rendezvous::default_data_dir());
}
#[test]

View file

@ -6,11 +6,14 @@
//! (see [`host`]), opens the project given on the command line, and
//! optionally serves the JSON control channel (`--control PORT`). A normal
//! start is a single instance (see [`instance`]): a second start forwards
//! its path to the running app and exits.
//! its path to the running app and exits. A start with `--data-dir`,
//! `LUTRA_DATA_DIR` or `--control` keeps its files away from the user's
//! (see [`datadir`]).
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod args;
mod datadir;
mod host;
mod instance;
mod screenshot;
@ -53,18 +56,27 @@ fn main() -> ExitCode {
}
/// Forwards to a running instance if there is one; otherwise builds the
/// Tauri app, starts the engine with the app's config and data directories,
/// Tauri app, starts the engine with the app's config and data directories
/// (or the isolated data directory, sharing the user's managed tools),
/// the host, the control channel and the single-instance listener, and runs
/// the event loop. The window is created in the setup hook, which runs once
/// the event loop has started. A single-instance listener or rendezvous
/// file that cannot be set up is reported and the app runs without it.
///
/// # Errors
/// A message if a running instance refused the forwarded path, Tauri cannot
/// build the app or resolve its directories, the engine cannot start, or
/// the control port cannot be bound.
/// A message if a running instance refused the forwarded path, the
/// isolated data directory cannot be created, Tauri cannot build the app or
/// resolve its directories, the engine cannot start, or the control port
/// cannot be bound.
fn run(args: &args::Args) -> Result<(), String> {
let instance_dir = instance::rendezvous_dir(args);
let isolated = datadir::isolated(args);
if let Some(dir) = &isolated {
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create the data directory {}: {e}", dir.display()))?;
eprintln!("lutra: data directory {}", dir.display());
}
let webview_dir = isolated.as_deref().map(datadir::webview_dir);
let instance_dir = instance::rendezvous_dir(args, isolated.as_deref());
if let Some(dir) = &instance_dir
&& instance::forward(dir, args.path.as_deref())?
{
@ -90,6 +102,9 @@ fn run(args: &args::Args) -> Result<(), String> {
.inner_size(1200.0, 800.0)
.min_inner_size(640.0, 400.0)
.initialization_script(theme::init_script(&setting));
if let Some(dir) = &webview_dir {
window = window.data_directory(dir.clone());
}
if let Some(color) = token_color(&theme::resolve(&setting, None), "bg") {
window = window.background_color(color);
}
@ -106,7 +121,15 @@ fn run(args: &args::Args) -> Result<(), String> {
})
.build(tauri::generate_context!())
.map_err(|e| e.to_string())?;
let mut engine = Engine::with_config(engine_config(&app)?).map_err(|e| e.to_string())?;
let user = engine_config(&app)?;
let config = match &isolated {
Some(dir) => datadir::engine_config(dir),
None => user.clone(),
};
let mut engine = Engine::with_config(config).map_err(|e| e.to_string())?;
if isolated.is_some() {
engine.share_tools_from(user.data_dir);
}
engine.allow_downloads().map_err(|e| e.to_string())?;
let startup = engine.take_events();
let host = Host::new(engine);
@ -141,8 +164,9 @@ fn run(args: &args::Args) -> Result<(), String> {
Ok(())
}
/// The engine directories from Tauri's path resolver: the app config dir
/// for settings, the app data dir for the recovery journal.
/// The user's engine directories from Tauri's path resolver: the app config
/// dir for settings, the app data dir for the recovery journal and the
/// managed tools. Resolving creates nothing.
///
/// # Errors
/// A message if the platform has no such directories.