//! Installable scheduled synchronization and durable run diagnostics.
#[cfg(test)]
use std::cell::RefCell;
use std::env;
use std::ffi::OsStr;
use std::fs;
use std::io::{Seek, SeekFrom, Write};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};
use clap::ValueEnum;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tempfile::{NamedTempFile, tempfile};
use crate::error::{DaloError, DaloResult};
use crate::store::{self, StorePaths};
const AUTOSYNC_SCHEMA_VERSION: u32 = 1;
/// Upper bound for each append-only scheduler log before it is trimmed to its
/// most recent tail. The native scheduler appends every run's output, so
/// without this the logs would grow without bound over months of hourly runs.
const MAX_AUTOSYNC_LOG_BYTES: u64 = 1 << 20; // 1 MiB
const CRON_BEGIN_PREFIX: &str = "# BEGIN dalo autosync ";
const CRON_END_PREFIX: &str = "# END dalo autosync ";
const INVOKED_EXECUTABLE_ENV: &str = "DALO_INVOKED_EXECUTABLE";
/// Supported user-facing autosync schedules.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum AutosyncSchedule {
/// Run once per hour.
Hourly,
/// Run once per day.
Daily,
/// Run once per week.
Weekly,
}
impl AutosyncSchedule {
/// Stable config and output label.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Hourly => "hourly",
Self::Daily => "daily",
Self::Weekly => "weekly",
}
}
/// Approximate seconds between two runs on this schedule.
#[must_use]
pub const fn interval_secs(self) -> u64 {
match self {
Self::Hourly => 3_600,
Self::Daily => 86_400,
Self::Weekly => 604_800,
}
}
}
/// Native scheduler selected for this installation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SchedulerBackend {
/// macOS per-user launchd agent.
Launchd,
/// Linux systemd user timer.
Systemd,
/// Per-user crontab fallback.
Cron,
}
impl SchedulerBackend {
/// Stable output label.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Launchd => "launchd",
Self::Systemd => "systemd",
Self::Cron => "cron",
}
}
}
/// Persisted scheduler installation metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AutosyncInstallState {
/// Persisted schema version.
pub schema_version: u32,
/// Native scheduler backend.
pub backend: SchedulerBackend,
/// Configured schedule.
pub schedule: AutosyncSchedule,
/// Absolute Dalo executable path installed into the scheduler.
pub executable: PathBuf,
/// Absolute store path installed into the scheduler.
pub store: PathBuf,
/// Scheduler label, timer stem, or cron marker ID.
pub identifier: String,
/// Native artifact paths, or `crontab` for the cron fallback.
pub artifacts: Vec<String>,
/// Installation timestamp.
pub installed_at_unix: u64,
}
/// Durable outcome of a scheduled synchronization attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutosyncRunOutcome {
/// The runner started but has not recorded a terminal outcome yet.
Running,
/// Synchronization completed safely.
Succeeded,
/// The store was busy and this attempt intentionally did no work.
Skipped,
/// A fail-closed condition prevented completion.
Blocked,
}
impl AutosyncRunOutcome {
/// Stable output label.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Running => "running",
Self::Succeeded => "succeeded",
Self::Skipped => "skipped",
Self::Blocked => "blocked",
}
}
}
/// Persisted status of the latest scheduled attempt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AutosyncRunState {
/// Persisted schema version.
pub schema_version: u32,
/// Unix timestamp of the latest attempt.
pub last_attempted_at_unix: u64,
/// Unix timestamp of the latest successful attempt.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_successful_at_unix: Option<u64>,
/// Latest terminal or in-progress outcome.
pub outcome: AutosyncRunOutcome,
/// Actionable detail for skipped or blocked runs.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
/// Full autosync status rendered by the CLI and embedded in `dalo status`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AutosyncStatusReport {
/// Whether config.toml declares autosync enabled.
pub configured: bool,
/// Whether Dalo installation metadata exists.
pub installed: bool,
/// Whether the native scheduler currently reports the job enabled.
pub enabled: bool,
/// Installed scheduler backend.
#[serde(skip_serializing_if = "Option::is_none")]
pub backend: Option<SchedulerBackend>,
/// Installed schedule.
#[serde(skip_serializing_if = "Option::is_none")]
pub schedule: Option<AutosyncSchedule>,
/// Installed executable.
#[serde(skip_serializing_if = "Option::is_none")]
pub executable: Option<PathBuf>,
/// Installed store path.
#[serde(skip_serializing_if = "Option::is_none")]
pub store: Option<PathBuf>,
/// Scheduler label or marker.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier: Option<String>,
/// Native scheduler artifacts.
pub artifacts: Vec<String>,
/// Native scheduler inspection failure, when durable metadata remains readable.
#[serde(skip_serializing_if = "Option::is_none")]
pub scheduler_error: Option<String>,
/// Why the job is installed but not currently enabled, when that applies.
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled_reason: Option<String>,
/// Durable status from the latest scheduled attempt.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_run: Option<AutosyncRunState>,
}
/// Install or uninstall command result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AutosyncMutationReport {
/// `installed`, `updated`, `unchanged`, `uninstalled`, or `would_*`.
pub action: String,
/// Whether no state was mutated.
pub dry_run: bool,
/// Resulting or planned status.
pub status: AutosyncStatusReport,
}
#[derive(Debug)]
struct CommandResult {
success: bool,
stdout: String,
stderr: String,
status: String,
}
trait CommandRunner {
fn run(&self, program: &str, args: &[String], input: Option<&str>)
-> DaloResult<CommandResult>;
}
struct SystemCommandRunner;
impl CommandRunner for SystemCommandRunner {
fn run(
&self,
program: &str,
args: &[String],
input: Option<&str>,
) -> DaloResult<CommandResult> {
let mut command = Command::new(program);
command
.args(args)
// This runner only executes scheduler control/inspection commands
// (crontab, launchctl, systemctl) whose output dalo parses, never
// user-facing text. Force a stable C locale for all of them --
// intentionally global, not just the `crontab -l` empty-crontab
// parse -- so parsing never depends on the caller's `LANG`/`LC_*`.
.env("LC_ALL", "C")
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let stdin_file = input
.map(|input| {
// Dalo deliberately restores SIGPIPE for its own stdout. Scheduler
// input must not share that pipe behavior: if `crontab -` exits
// before reading, a pipe write would kill dalo before rollback.
let mut file = tempfile()?;
file.write_all(input.as_bytes())?;
file.flush()?;
file.seek(SeekFrom::Start(0))?;
Ok::<_, std::io::Error>(file)
})
.transpose()?;
if let Some(file) = stdin_file {
command.stdin(Stdio::from(file));
} else {
command.stdin(Stdio::null());
}
let child = command.spawn().map_err(|error| {
DaloError::Io(std::io::Error::new(
error.kind(),
format!("could not run `{program}`: {error}"),
))
})?;
let output = child.wait_with_output()?;
Ok(CommandResult {
success: output.status.success(),
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
status: output.status.to_string(),
})
}
}
/// Install or update the current user's native autosync job.
pub fn install(
paths: &StorePaths,
schedule: Option<AutosyncSchedule>,
dry_run: bool,
) -> DaloResult<AutosyncMutationReport> {
let schedule = schedule
.or(read_install_state(paths)?.map(|state| state.schedule))
.or_else(|| {
store::read_config(paths)
.ok()
.and_then(|config| config.settings.sync_interval)
.and_then(|value| schedule_from_str(&value))
})
.unwrap_or(AutosyncSchedule::Daily);
let runner = SystemCommandRunner;
let backend = detect_backend(&runner)?;
let executable = scheduler_executable()?;
let home = user_home()?;
install_with(
paths,
schedule,
dry_run,
backend,
&executable,
&home,
&runner,
)
}
fn scheduler_executable() -> DaloResult<PathBuf> {
let current = env::current_exe()?;
let invoked = env::args_os().next().map(PathBuf::from);
let launcher = env::var_os(INVOKED_EXECUTABLE_ENV).map(PathBuf::from);
let cwd = env::current_dir()?;
let search_path = env::var_os("PATH");
let install_channel = env::var("DALO_INSTALL_CHANNEL").ok();
select_scheduler_executable(
¤t,
invoked.as_deref(),
launcher.as_deref(),
&cwd,
search_path.as_deref(),
install_channel.as_deref(),
)
}
fn select_scheduler_executable(
current: &Path,
invoked: Option<&Path>,
launcher: Option<&Path>,
cwd: &Path,
search_path: Option<&OsStr>,
install_channel: Option<&str>,
) -> DaloResult<PathBuf> {
if install_channel == Some("npx") {
return Err(DaloError::StateError {
reason: "autosync cannot use the temporary npx launcher; install getdalo globally with `npm install --global getdalo`, or use another persistent Dalo installation"
.to_owned(),
});
}
if install_channel == Some("npm") {
let launcher = launcher
.and_then(|path| resolve_invoked_path(path, cwd, search_path))
.filter(|path| executable_available(path))
.ok_or_else(|| DaloError::StateError {
reason: "autosync could not resolve the persistent npm launcher; reinstall getdalo globally and retry"
.to_owned(),
})?;
return stable_executable(launcher);
}
if let Some(candidate) = invoked
.and_then(|path| resolve_invoked_path(path, cwd, search_path))
.filter(|path| executable_available(path) && same_executable(path, current))
{
return stable_executable(candidate);
}
stable_executable(current.to_path_buf())
}
fn resolve_invoked_path(
invoked: &Path,
cwd: &Path,
search_path: Option<&OsStr>,
) -> Option<PathBuf> {
if invoked.is_absolute() {
return Some(invoked.to_path_buf());
}
if invoked.components().count() > 1 {
return Some(cwd.join(invoked));
}
search_path.and_then(|path| {
env::split_paths(path)
.map(|directory| {
if directory.as_os_str().is_empty() {
cwd.join(invoked)
} else if directory.is_absolute() {
directory.join(invoked)
} else {
cwd.join(directory).join(invoked)
}
})
.find(|candidate| executable_available(candidate))
})
}
fn same_executable(candidate: &Path, current: &Path) -> bool {
matches!(
(candidate.canonicalize(), current.canonicalize()),
(Ok(candidate), Ok(current)) if candidate == current
)
}
fn stable_executable(executable: PathBuf) -> DaloResult<PathBuf> {
if version_managed_executable(&executable) {
return Err(DaloError::StateError {
reason: format!(
"autosync resolved the version-managed executable `{}`; invoke Dalo through a persistent symlink or launcher and retry",
executable.display()
),
});
}
Ok(executable)
}
fn version_managed_executable(executable: &Path) -> bool {
let components = executable
.components()
.filter_map(|component| component.as_os_str().to_str())
.collect::<Vec<_>>();
[
Path::new("/opt/homebrew/Cellar"),
Path::new("/usr/local/Cellar"),
Path::new("/home/linuxbrew/.linuxbrew/Cellar"),
]
.iter()
.any(|cellar| executable.starts_with(cellar))
|| components.windows(2).any(|pair| pair == [".npm", "_npx"])
|| components.windows(2).any(|pair| pair == [".cache", "dalo"])
}
fn schedule_from_str(value: &str) -> Option<AutosyncSchedule> {
match value {
"hourly" => Some(AutosyncSchedule::Hourly),
"daily" => Some(AutosyncSchedule::Daily),
"weekly" => Some(AutosyncSchedule::Weekly),
_ => None,
}
}
/// Remove the installed native autosync job idempotently.
pub fn uninstall(paths: &StorePaths, dry_run: bool) -> DaloResult<AutosyncMutationReport> {
let home = user_home().ok();
uninstall_with(paths, dry_run, &SystemCommandRunner, home.as_deref())
}
/// Inspect scheduler installation and durable run state.
pub fn status(paths: &StorePaths) -> DaloResult<AutosyncStatusReport> {
status_with(paths, &SystemCommandRunner)
}
/// Mark a scheduled run as started and return its attempt timestamp.
pub fn begin_run(paths: &StorePaths) -> DaloResult<u64> {
let attempted = now_unix();
let previous = read_run_state(paths)?;
write_run_state(
paths,
&AutosyncRunState {
schema_version: AUTOSYNC_SCHEMA_VERSION,
last_attempted_at_unix: attempted,
last_successful_at_unix: previous.and_then(|state| state.last_successful_at_unix),
outcome: AutosyncRunOutcome::Running,
reason: None,
},
)?;
Ok(attempted)
}
/// Persist the terminal outcome for a scheduled run.
pub fn finish_run(
paths: &StorePaths,
attempted: u64,
outcome: AutosyncRunOutcome,
reason: Option<String>,
) -> DaloResult<AutosyncRunState> {
let previous = read_run_state(paths)?;
let last_successful_at_unix = if outcome == AutosyncRunOutcome::Succeeded {
Some(now_unix())
} else {
previous.and_then(|state| state.last_successful_at_unix)
};
let state = AutosyncRunState {
schema_version: AUTOSYNC_SCHEMA_VERSION,
last_attempted_at_unix: attempted,
last_successful_at_unix,
outcome,
reason,
};
write_run_state(paths, &state)?;
Ok(state)
}
fn install_with(
paths: &StorePaths,
schedule: AutosyncSchedule,
dry_run: bool,
backend: SchedulerBackend,
executable: &Path,
home: &Path,
runner: &dyn CommandRunner,
) -> DaloResult<AutosyncMutationReport> {
if !executable.is_file() {
return Err(DaloError::StateError {
reason: format!(
"autosync requires a stable executable file, but `{}` is unavailable",
executable.display()
),
});
}
if fs::metadata(executable)?.permissions().mode() & 0o111 == 0 {
return Err(DaloError::StateError {
reason: format!(
"autosync executable `{}` is not executable",
executable.display()
),
});
}
for path in [
executable,
&paths.root,
home,
&paths.autosync_log_file,
&paths.autosync_error_log_file,
] {
let Some(path_text) = path.to_str() else {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "scheduler paths must be valid UTF-8 so native artifacts can preserve them exactly"
.to_owned(),
});
};
if path_text.chars().any(char::is_control) {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "scheduler paths must not contain control characters".to_owned(),
});
}
if backend == SchedulerBackend::Cron && path_text.contains('\\') {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "cron fallback cannot safely encode paths containing backslashes; install a systemd user manager or move the path"
.to_owned(),
});
}
}
let config = store::read_config(paths)?;
let previous = read_install_state(paths)?;
let mut state = planned_state(paths, backend, schedule, executable, home);
if let Some(previous) = &previous
&& same_install(previous, &state)
{
state.installed_at_unix = previous.installed_at_unix;
}
let config_matches = config.settings.autosync
&& config.settings.sync_interval.as_deref() == Some(schedule.as_str());
let action = if previous
.as_ref()
.is_some_and(|old| same_install(old, &state))
&& config_matches
{
"unchanged"
} else if previous.is_some() {
"updated"
} else {
"installed"
};
if dry_run {
let planned_action = match action {
"installed" => "would_install",
"updated" => "would_update",
_ => "unchanged",
};
return Ok(AutosyncMutationReport {
action: planned_action.to_owned(),
dry_run: true,
status: report_from_state(Some(state), true, read_run_state(paths)?, true),
});
}
if let Some(old) = &previous
&& !same_install(old, &state)
{
disable_scheduler(old, runner)?;
if let Err(error) = remove_artifacts(old) {
restore_previous_install(paths, Some(old), runner);
return Err(error);
}
}
if let Err(error) = write_artifacts(paths, &state) {
restore_previous_install(paths, previous.as_ref(), runner);
return Err(error);
}
if let Err(error) = persist_install(paths, &state, &config) {
let _ = remove_artifacts(&state);
restore_install_metadata(paths, previous.as_ref(), &config);
restore_previous_install(paths, previous.as_ref(), runner);
return Err(error);
}
if let Err(error) = enable_scheduler(paths, &state, runner) {
let _ = disable_scheduler(&state, runner);
let _ = remove_artifacts(&state);
restore_install_metadata(paths, previous.as_ref(), &config);
restore_previous_install(paths, previous.as_ref(), runner);
return Err(error);
}
Ok(AutosyncMutationReport {
action: action.to_owned(),
dry_run: false,
status: report_from_state(Some(state), true, read_run_state(paths)?, true),
})
}
fn uninstall_with(
paths: &StorePaths,
dry_run: bool,
runner: &dyn CommandRunner,
home: Option<&Path>,
) -> DaloResult<AutosyncMutationReport> {
let (state, invalid_state) = match read_install_state(paths) {
Ok(state) => (state, false),
Err(DaloError::FileParse { .. } | DaloError::UnsupportedSchema { .. })
if paths.autosync_file.exists() =>
{
(None, true)
}
Err(error) => return Err(error),
};
let original_config = store::read_config(paths)?;
let configured = original_config.settings.autosync;
let had_install_state = state.is_some() || invalid_state;
if dry_run {
return Ok(AutosyncMutationReport {
action: if had_install_state || configured {
"would_uninstall"
} else {
"unchanged"
}
.to_owned(),
dry_run: true,
status: report_from_state(None, false, read_run_state(paths)?, false),
});
}
let mut recovery_errors = Vec::new();
if invalid_state {
store::backup_corrupt_file(&paths.autosync_file)?;
recovery_errors = recover_install_without_state(paths, home, runner);
}
if let Some(state) = &state {
disable_scheduler(state, runner)?;
if let Err(error) = remove_artifacts(state) {
restore_previous_install(paths, Some(state), runner);
return Err(error);
}
if state.backend == SchedulerBackend::Systemd
&& let Err(error) = require_success(
"systemctl",
&["--user".to_owned(), "daemon-reload".to_owned()],
runner,
None,
)
{
restore_previous_install(paths, Some(state), runner);
return Err(error);
}
}
let mut config = original_config.clone();
config.settings.autosync = false;
config.settings.sync_interval = None;
if let Err(error) = store::write_config(paths, &config) {
restore_previous_install(paths, state.as_ref(), runner);
return Err(error);
}
if paths.autosync_file.exists()
&& let Err(error) = fs::remove_file(&paths.autosync_file)
{
let _ = store::write_config(paths, &original_config);
restore_previous_install(paths, state.as_ref(), runner);
return Err(error.into());
}
if paths.autosync_run_file.exists()
&& let Err(error) = fs::remove_file(&paths.autosync_run_file)
{
if !invalid_state {
let _ = store::write_config(paths, &original_config);
restore_previous_install(paths, state.as_ref(), runner);
}
return Err(error.into());
}
// Autosync logs are append-only with no rotation, so they would otherwise
// outlive the install indefinitely. Remove them best-effort: a leftover log
// must never block an otherwise-successful uninstall.
for log in [&paths.autosync_log_file, &paths.autosync_error_log_file] {
if log.exists() {
let _ = fs::remove_file(log);
}
}
let mut status = report_from_state(None, false, read_run_state(paths)?, false);
if !recovery_errors.is_empty() {
status.scheduler_error = Some(format!(
"autosync recovery could not clean every native scheduler artifact: {}",
recovery_errors.join("; ")
));
}
Ok(AutosyncMutationReport {
action: if had_install_state || configured {
"uninstalled"
} else {
"unchanged"
}
.to_owned(),
dry_run: false,
status,
})
}
fn recover_install_without_state(
paths: &StorePaths,
home: Option<&Path>,
runner: &dyn CommandRunner,
) -> Vec<String> {
let mut errors = Vec::new();
if let Some(home) = home {
#[cfg(target_os = "macos")]
recover_backend_without_state(paths, home, SchedulerBackend::Launchd, runner, &mut errors);
#[cfg(target_os = "linux")]
recover_backend_without_state(paths, home, SchedulerBackend::Systemd, runner, &mut errors);
} else {
#[cfg(any(target_os = "macos", target_os = "linux"))]
errors.push(
"HOME is not set, so native scheduler artifact paths could not be reconstructed"
.to_owned(),
);
}
recover_backend_without_state(
paths,
home.unwrap_or_else(|| Path::new(".")),
SchedulerBackend::Cron,
runner,
&mut errors,
);
errors
}
fn recover_backend_without_state(
paths: &StorePaths,
home: &Path,
backend: SchedulerBackend,
runner: &dyn CommandRunner,
errors: &mut Vec<String>,
) {
// Recovery only needs the identifier and artifact paths. `planned_state`
// derives both solely from the store root and backend; the placeholder
// schedule and executable never affect the cleanup targets.
let state = planned_state(
paths,
backend,
AutosyncSchedule::Daily,
Path::new("dalo"),
home,
);
if let Err(error) = disable_scheduler(&state, runner) {
errors.push(format!("could not disable {}: {error}", backend.as_str()));
}
if let Err(error) = remove_artifacts(&state) {
errors.push(format!(
"could not remove {} artifacts: {error}",
backend.as_str()
));
}
if backend == SchedulerBackend::Systemd
&& let Err(error) = require_success(
"systemctl",
&["--user".to_owned(), "daemon-reload".to_owned()],
runner,
None,
)
{
errors.push(format!(
"could not reload systemd after artifact cleanup: {error}"
));
}
}
fn restore_previous_install(
paths: &StorePaths,
previous: Option<&AutosyncInstallState>,
runner: &dyn CommandRunner,
) {
if let Some(previous) = previous {
let _ = write_artifacts(paths, previous);
let _ = write_install_state(paths, previous);
let _ = enable_scheduler(paths, previous, runner);
}
}
fn restore_install_metadata(
paths: &StorePaths,
previous: Option<&AutosyncInstallState>,
original_config: &crate::config::UserConfig,
) {
if let Some(previous) = previous {
let _ = write_install_state(paths, previous);
} else {
let _ = fs::remove_file(&paths.autosync_file);
}
let _ = store::write_config(paths, original_config);
}
fn persist_install(
paths: &StorePaths,
state: &AutosyncInstallState,
original_config: &crate::config::UserConfig,
) -> DaloResult<()> {
write_install_state(paths, state)?;
let mut config = original_config.clone();
config.settings.autosync = true;
config.settings.sync_interval = Some(state.schedule.as_str().to_owned());
if let Err(error) = store::write_config(paths, &config) {
let _ = fs::remove_file(&paths.autosync_file);
return Err(error);
}
Ok(())
}
fn status_with(paths: &StorePaths, runner: &dyn CommandRunner) -> DaloResult<AutosyncStatusReport> {
let state = read_install_state(paths)?;
let configured = if paths.config_file.exists() {
store::read_config(paths).is_ok_and(|config| config.settings.autosync)
} else {
false
};
let mut scheduler_error = None;
let mut disabled_reason = None;
let enabled = match &state {
Some(state) => {
let artifacts_present = state.backend == SchedulerBackend::Cron
|| state
.artifacts
.iter()
.all(|artifact| Path::new(artifact).is_file());
if !artifacts_present {
disabled_reason = Some("native scheduler artifacts are missing".to_owned());
false
} else if !executable_available(&state.executable) {
disabled_reason = Some(format!(
"recorded executable `{}` is missing or not executable",
state.executable.display()
));
false
} else if state.store != paths.root {
disabled_reason = Some(format!(
"installed store path `{}` no longer matches this store `{}`",
state.store.display(),
paths.root.display()
));
false
} else {
match scheduler_enabled(state, runner) {
Ok(true) => true,
Ok(false) => {
disabled_reason =
Some("the native scheduler reports the job disabled".to_owned());
false
}
Err(error) => {
scheduler_error = Some(error.to_string());
disabled_reason =
Some("the native scheduler state could not be inspected".to_owned());
false
}
}
}
}
None => false,
};
let mut report = report_from_state(state, enabled, read_run_state(paths)?, configured);
report.scheduler_error = scheduler_error;
report.disabled_reason = disabled_reason;
Ok(report)
}
pub(crate) fn executable_available(path: &Path) -> bool {
fs::metadata(path)
.is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
}
/// Number of schedule intervals after which a run still marked `running` is
/// treated as stale — a runner that was interrupted before it could persist a
/// terminal outcome (for example a SIGKILL or a power loss mid-sync).
pub const STALE_RUNNING_INTERVALS: u64 = 2;
/// Whether a run persisted as `running` has been in that state long enough to
/// be an interrupted run rather than one still in progress. `schedule` is the
/// installed schedule when known; without it a daily cadence is assumed.
#[must_use]
pub fn running_run_is_stale(
run: &AutosyncRunState,
schedule: Option<AutosyncSchedule>,
now: u64,
) -> bool {
if run.outcome != AutosyncRunOutcome::Running {
return false;
}
let interval = schedule.map_or_else(
|| AutosyncSchedule::Daily.interval_secs(),
AutosyncSchedule::interval_secs,
);
now.saturating_sub(run.last_attempted_at_unix)
> interval.saturating_mul(STALE_RUNNING_INTERVALS)
}
fn report_from_state(
state: Option<AutosyncInstallState>,
enabled: bool,
last_run: Option<AutosyncRunState>,
configured: bool,
) -> AutosyncStatusReport {
AutosyncStatusReport {
configured,
installed: state.is_some(),
enabled,
backend: state.as_ref().map(|state| state.backend),
schedule: state.as_ref().map(|state| state.schedule),
executable: state.as_ref().map(|state| state.executable.clone()),
store: state.as_ref().map(|state| state.store.clone()),
identifier: state.as_ref().map(|state| state.identifier.clone()),
artifacts: state.map_or_else(Vec::new, |state| state.artifacts),
scheduler_error: None,
disabled_reason: None,
last_run,
}
}
#[cfg(target_os = "macos")]
fn detect_backend(runner: &dyn CommandRunner) -> DaloResult<SchedulerBackend> {
let _ = runner.run("launchctl", &["version".to_owned()], None)?;
Ok(SchedulerBackend::Launchd)
}
#[cfg(target_os = "linux")]
fn detect_backend(runner: &dyn CommandRunner) -> DaloResult<SchedulerBackend> {
if runner
.run(
"systemctl",
&["--user".to_owned(), "show-environment".to_owned()],
None,
)
.is_ok_and(|result| result.success)
{
return Ok(SchedulerBackend::Systemd);
}
if read_crontab(runner).is_ok() {
return Ok(SchedulerBackend::Cron);
}
Err(DaloError::StateError {
reason: "no supported user scheduler is available (launchd, systemd --user, or crontab)"
.to_owned(),
})
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn detect_backend(runner: &dyn CommandRunner) -> DaloResult<SchedulerBackend> {
if read_crontab(runner).is_ok() {
Ok(SchedulerBackend::Cron)
} else {
Err(DaloError::StateError {
reason:
"no supported user scheduler is available (launchd, systemd --user, or crontab)"
.to_owned(),
})
}
}
fn planned_state(
paths: &StorePaths,
backend: SchedulerBackend,
schedule: AutosyncSchedule,
executable: &Path,
home: &Path,
) -> AutosyncInstallState {
let hash = store_hash(&paths.root);
let (identifier, artifacts) = match backend {
SchedulerBackend::Launchd => {
let identifier = format!("dev.dalo.autosync.{hash}");
let artifact = home
.join("Library/LaunchAgents")
.join(format!("{identifier}.plist"));
(identifier, vec![artifact.display().to_string()])
}
SchedulerBackend::Systemd => {
let identifier = format!("dalo-autosync-{hash}");
let root = home.join(".config/systemd/user");
(
identifier.clone(),
vec![
root.join(format!("{identifier}.service"))
.display()
.to_string(),
root.join(format!("{identifier}.timer"))
.display()
.to_string(),
],
)
}
SchedulerBackend::Cron => {
let identifier = format!("dalo-autosync-{hash}");
(identifier, vec!["crontab".to_owned()])
}
};
AutosyncInstallState {
schema_version: AUTOSYNC_SCHEMA_VERSION,
backend,
schedule,
executable: executable.to_path_buf(),
store: paths.root.clone(),
identifier,
artifacts,
installed_at_unix: now_unix(),
}
}
fn same_install(left: &AutosyncInstallState, right: &AutosyncInstallState) -> bool {
left.schema_version == right.schema_version
&& left.backend == right.backend
&& left.schedule == right.schedule
&& left.executable == right.executable
&& left.store == right.store
&& left.identifier == right.identifier
&& left.artifacts == right.artifacts
}
fn write_artifacts(paths: &StorePaths, state: &AutosyncInstallState) -> DaloResult<()> {
match state.backend {
SchedulerBackend::Launchd => {
write_text_atomic(
Path::new(&state.artifacts[0]),
&render_launchd(paths, state),
)?;
}
SchedulerBackend::Systemd => {
write_text_atomic(
Path::new(&state.artifacts[0]),
&render_systemd_service(paths, state),
)?;
write_text_atomic(Path::new(&state.artifacts[1]), &render_systemd_timer(state))?;
}
SchedulerBackend::Cron => {}
}
Ok(())
}
fn remove_artifacts(state: &AutosyncInstallState) -> DaloResult<()> {
if state.backend == SchedulerBackend::Cron {
return Ok(());
}
for artifact in &state.artifacts {
let path = Path::new(artifact);
if path.exists() {
fs::remove_file(path)?;
}
}
Ok(())
}
fn enable_scheduler(
paths: &StorePaths,
state: &AutosyncInstallState,
runner: &dyn CommandRunner,
) -> DaloResult<()> {
match state.backend {
SchedulerBackend::Launchd => {
let domain = launchd_domain(runner)?;
let artifact = state.artifacts[0].clone();
let _ = runner.run(
"launchctl",
&["bootout".to_owned(), domain.clone(), artifact.clone()],
None,
);
require_success(
"launchctl",
&["bootstrap".to_owned(), domain.clone(), artifact],
runner,
None,
)?;
require_success(
"launchctl",
&[
"enable".to_owned(),
format!("{domain}/{}", state.identifier),
],
runner,
None,
)
.map(|_| ())
}
SchedulerBackend::Systemd => {
require_success(
"systemctl",
&["--user".to_owned(), "daemon-reload".to_owned()],
runner,
None,
)?;
require_success(
"systemctl",
&[
"--user".to_owned(),
"enable".to_owned(),
"--now".to_owned(),
format!("{}.timer", state.identifier),
],
runner,
None,
)
.map(|_| ())
}
SchedulerBackend::Cron => install_cron(paths, state, runner),
}
}
fn disable_scheduler(state: &AutosyncInstallState, runner: &dyn CommandRunner) -> DaloResult<()> {
match state.backend {
SchedulerBackend::Launchd => {
let domain = launchd_domain(runner)?;
let loaded = runner
.run(
"launchctl",
&["print".to_owned(), format!("{domain}/{}", state.identifier)],
None,
)?
.success;
if loaded {
require_success(
"launchctl",
&["bootout".to_owned(), domain, state.artifacts[0].clone()],
runner,
None,
)?;
}
Ok(())
}
SchedulerBackend::Systemd => {
let disable = runner.run(
"systemctl",
&[
"--user".to_owned(),
"disable".to_owned(),
"--now".to_owned(),
format!("{}.timer", state.identifier),
],
None,
)?;
if !disable.success && !scheduler_absent(&disable.stderr) {
return Err(DaloError::CommandFailed {
program: "systemctl".to_owned(),
args: format!("--user disable --now {}.timer", state.identifier),
cwd: env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
status: disable.status,
stderr: disable.stderr.trim().to_owned(),
});
}
require_success(
"systemctl",
&["--user".to_owned(), "daemon-reload".to_owned()],
runner,
None,
)?;
Ok(())
}
SchedulerBackend::Cron => remove_cron(state, runner),
}
}
fn scheduler_absent(stderr: &str) -> bool {
let stderr = stderr.to_ascii_lowercase();
stderr.contains("does not exist")
|| stderr.contains("not loaded")
|| stderr.contains("not found")
}
fn scheduler_enabled(state: &AutosyncInstallState, runner: &dyn CommandRunner) -> DaloResult<bool> {
match state.backend {
SchedulerBackend::Launchd => {
let domain = launchd_domain(runner)?;
Ok(runner
.run(
"launchctl",
&["print".to_owned(), format!("{domain}/{}", state.identifier)],
None,
)?
.success)
}
SchedulerBackend::Systemd => {
let unit = format!("{}.timer", state.identifier);
let enabled = runner
.run(
"systemctl",
&["--user".to_owned(), "is-enabled".to_owned(), unit.clone()],
None,
)?
.success;
let active = runner
.run(
"systemctl",
&["--user".to_owned(), "is-active".to_owned(), unit],
None,
)?
.success;
Ok(enabled && active)
}
SchedulerBackend::Cron => {
Ok(read_crontab(runner)?.contains(&cron_begin(&state.identifier)))
}
}
}
fn launchd_domain(runner: &dyn CommandRunner) -> DaloResult<String> {
let result = require_success("id", &["-u".to_owned()], runner, None)?;
let uid = result.stdout.trim();
if uid.is_empty() || !uid.chars().all(|character| character.is_ascii_digit()) {
return Err(DaloError::StateError {
reason: "could not determine the current numeric user ID for launchd".to_owned(),
});
}
Ok(format!("gui/{uid}"))
}
fn install_cron(
paths: &StorePaths,
state: &AutosyncInstallState,
runner: &dyn CommandRunner,
) -> DaloResult<()> {
rewrite_crontab(runner, |current| {
let without = strip_cron_block(current, &state.identifier)?;
let block = render_cron(paths, state);
Ok(if without.trim().is_empty() {
block
} else {
format!("{}\n{}", without.trim_end(), block)
})
})
}
fn remove_cron(state: &AutosyncInstallState, runner: &dyn CommandRunner) -> DaloResult<()> {
rewrite_crontab(runner, |current| {
strip_cron_block(current, &state.identifier)
})
}
/// Rewrite a crontab while minimizing the stale-snapshot window. The crontab
/// interface has no compare-and-swap operation, so a concurrent edit can never
/// be ruled out completely; validating a first snapshot and re-reading directly
/// before the write preserves edits that arrive while dalo prepares its update.
fn rewrite_crontab(
runner: &dyn CommandRunner,
update: impl Fn(&str) -> DaloResult<String>,
) -> DaloResult<()> {
let initial = read_crontab(runner)?;
let _ = update(&initial)?;
let latest = read_crontab(runner)?;
let content = update(&latest)?;
require_success("crontab", &["-".to_owned()], runner, Some(&content))?;
Ok(())
}
fn read_crontab(runner: &dyn CommandRunner) -> DaloResult<String> {
let args = ["-l".to_owned()];
let result = runner.run("crontab", &args, None)?;
if result.success || result.stderr.to_ascii_lowercase().contains("no crontab") {
Ok(result.stdout)
} else {
Err(DaloError::CommandFailed {
program: "crontab".to_owned(),
args: "-l".to_owned(),
cwd: env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
status: result.status,
stderr: result.stderr.trim().to_owned(),
})
}
}
fn require_success(
program: &str,
args: &[String],
runner: &dyn CommandRunner,
input: Option<&str>,
) -> DaloResult<CommandResult> {
let result = runner.run(program, args, input)?;
if result.success {
Ok(result)
} else {
Err(DaloError::CommandFailed {
program: program.to_owned(),
args: args.join(" "),
cwd: env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
status: result.status,
stderr: result.stderr.trim().to_owned(),
})
}
}
fn render_launchd(paths: &StorePaths, state: &AutosyncInstallState) -> String {
let (hour, minute) = schedule_time(&state.store);
let calendar = match state.schedule {
AutosyncSchedule::Hourly => format!("<key>Minute</key><integer>{minute}</integer>"),
AutosyncSchedule::Daily => format!(
"<key>Hour</key><integer>{hour}</integer><key>Minute</key><integer>{minute}</integer>"
),
AutosyncSchedule::Weekly => format!(
"<key>Weekday</key><integer>0</integer><key>Hour</key><integer>{hour}</integer><key>Minute</key><integer>{minute}</integer>"
),
};
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key><string>{}</string>\n <key>ProgramArguments</key>\n <array>\n <string>{}</string>\n <string>--store</string>\n <string>{}</string>\n <string>autosync</string>\n <string>run</string>\n </array>\n <key>StartCalendarInterval</key><dict>{calendar}</dict>\n <key>ProcessType</key><string>Background</string>\n <key>StandardOutPath</key><string>{}</string>\n <key>StandardErrorPath</key><string>{}</string>\n</dict>\n</plist>\n",
xml_escape(&state.identifier),
xml_escape(&state.executable.display().to_string()),
xml_escape(&state.store.display().to_string()),
xml_escape(&paths.autosync_log_file.display().to_string()),
xml_escape(&paths.autosync_error_log_file.display().to_string())
)
}
fn render_systemd_service(paths: &StorePaths, state: &AutosyncInstallState) -> String {
format!(
"[Unit]\nDescription=Dalo scheduled synchronization\n\n[Service]\nType=oneshot\nExecStart={} --store {} autosync run\nStandardOutput={}\nStandardError={}\n",
systemd_quote(&state.executable),
systemd_quote(&state.store),
systemd_append_value(&paths.autosync_log_file),
systemd_append_value(&paths.autosync_error_log_file)
)
}
fn render_systemd_timer(state: &AutosyncInstallState) -> String {
let (hour, minute) = schedule_time(&state.store);
let calendar = match state.schedule {
AutosyncSchedule::Hourly => format!("*-*-* *:{minute:02}:00"),
AutosyncSchedule::Daily => format!("*-*-* {hour:02}:{minute:02}:00"),
AutosyncSchedule::Weekly => format!("Sun *-*-* {hour:02}:{minute:02}:00"),
};
format!(
"[Unit]\nDescription=Run Dalo synchronization on schedule\n\n[Timer]\nOnCalendar={calendar}\nPersistent=true\nRandomizedDelaySec=15m\nUnit={}.service\n\n[Install]\nWantedBy=timers.target\n",
state.identifier
)
}
fn render_cron(paths: &StorePaths, state: &AutosyncInstallState) -> String {
let (hour, minute) = schedule_time(&state.store);
let expression = match state.schedule {
AutosyncSchedule::Hourly => format!("{minute} * * * *"),
AutosyncSchedule::Daily => format!("{minute} {hour} * * *"),
AutosyncSchedule::Weekly => format!("{minute} {hour} * * 0"),
};
format!(
"{}\n{expression} {} --store {} autosync run >> {} 2>> {}\n{}\n",
cron_begin(&state.identifier),
cron_shell_quote(&state.executable),
cron_shell_quote(&state.store),
cron_shell_quote(&paths.autosync_log_file),
cron_shell_quote(&paths.autosync_error_log_file),
cron_end(&state.identifier)
)
}
fn cron_begin(identifier: &str) -> String {
format!("{CRON_BEGIN_PREFIX}{identifier}")
}
fn cron_end(identifier: &str) -> String {
format!("{CRON_END_PREFIX}{identifier}")
}
fn strip_cron_block(content: &str, identifier: &str) -> DaloResult<String> {
let begin = cron_begin(identifier);
let end = cron_end(identifier);
let mut output = Vec::new();
let mut skipping = false;
for line in content.lines() {
if line == begin {
if skipping {
return Err(DaloError::StateError {
reason: format!(
"cron fallback contains duplicate start markers for `{identifier}`"
),
});
}
skipping = true;
continue;
}
if line == end {
if !skipping {
return Err(DaloError::StateError {
reason: format!(
"cron fallback contains an unmatched end marker for `{identifier}`"
),
});
}
skipping = false;
continue;
}
if !skipping {
output.push(line);
}
}
let mut rendered = output.join("\n");
if !rendered.is_empty() {
rendered.push('\n');
}
if skipping {
return Err(DaloError::StateError {
reason: format!("cron fallback has no end marker for `{identifier}`"),
});
}
Ok(rendered)
}
fn schedule_time(store: &Path) -> (u8, u8) {
let digest = Sha256::digest(store.as_os_str().as_encoded_bytes());
(digest[0] % 6, digest[1] % 60)
}
fn store_hash(store: &Path) -> String {
Sha256::digest(store.as_os_str().as_encoded_bytes())
.iter()
.take(6)
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn xml_escape(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn systemd_quote(path: &Path) -> String {
format!("\"{}\"", systemd_exec_escape(path))
}
fn systemd_exec_escape(path: &Path) -> String {
path.display()
.to_string()
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('%', "%%")
.replace('$', "$$")
}
fn systemd_append_value(path: &Path) -> String {
format!("append:{}", path.display().to_string().replace('%', "%%"))
}
fn shell_quote(path: &Path) -> String {
format!("'{}'", path.display().to_string().replace('\'', "'\"'\"'"))
}
fn cron_shell_quote(path: &Path) -> String {
shell_quote(path).replace('%', "\\%")
}
fn write_text_atomic(path: &Path, content: &str) -> DaloResult<()> {
let parent = path.parent().ok_or_else(|| DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "scheduler artifact has no parent directory".to_owned(),
})?;
fs::create_dir_all(parent)?;
let mut temp = NamedTempFile::new_in(parent)?;
temp.write_all(content.as_bytes())?;
temp.flush()?;
temp.as_file().sync_all()?;
temp.persist(path).map_err(|error| error.error)?;
fs::File::open(parent)?.sync_all()?;
Ok(())
}
fn read_install_state(paths: &StorePaths) -> DaloResult<Option<AutosyncInstallState>> {
if !paths.autosync_file.exists() {
return Ok(None);
}
let content = fs::read_to_string(&paths.autosync_file)?;
let state: AutosyncInstallState =
toml::from_str(&content).map_err(|error| DaloError::FileParse {
path: paths.autosync_file.clone(),
reason: error.to_string(),
})?;
if state.schema_version != AUTOSYNC_SCHEMA_VERSION {
return Err(DaloError::UnsupportedSchema {
path: paths.autosync_file.clone(),
version: state.schema_version,
supported: AUTOSYNC_SCHEMA_VERSION,
});
}
// The scheduler code indexes `artifacts` by position (launchd/systemd read
// fixed slots). A schema-valid but short array would panic on index; treat
// it as corrupt so the uninstall recovery path can quarantine it instead.
let required_artifacts = match state.backend {
SchedulerBackend::Launchd => 1,
SchedulerBackend::Systemd => 2,
SchedulerBackend::Cron => 0,
};
if state.artifacts.len() < required_artifacts {
return Err(DaloError::FileParse {
path: paths.autosync_file.clone(),
reason: format!(
"{} backend requires {required_artifacts} scheduler artifact path(s), found {}",
state.backend.as_str(),
state.artifacts.len()
),
});
}
Ok(Some(state))
}
fn write_install_state(paths: &StorePaths, state: &AutosyncInstallState) -> DaloResult<()> {
store::write_toml_atomic(&paths.autosync_file, state)
}
/// Cap the append-only scheduler logs before a scheduled run adds to them.
///
/// The native scheduler (cron `>>`, systemd `append:`, launchd `StandardOutPath`)
/// appends this run's stdout/stderr to these files with no rotation of its own.
/// Trimming here—before the run produces any output—keeps only the most recent
/// tail. Best-effort: a trim failure must never abort a scheduled sync.
pub fn trim_scheduler_logs(paths: &StorePaths) {
for log in [&paths.autosync_log_file, &paths.autosync_error_log_file] {
let _ = trim_log_to_tail(log, MAX_AUTOSYNC_LOG_BYTES);
}
}
fn trim_log_to_tail(path: &Path, max_bytes: u64) -> DaloResult<()> {
let metadata = match fs::metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
};
if metadata.len() <= max_bytes {
return Ok(());
}
let content = fs::read(path)?;
// Keep the last `max_bytes`, advanced to the next line boundary so the
// retained log starts at a clean entry rather than mid-line. If the window
// has no newline at all (a pathological single oversized/binary line),
// fall back to the raw window so the most recent bytes survive rather than
// discarding the whole log.
let window_start = content.len().saturating_sub(max_bytes as usize);
let tail_start = content[window_start..]
.iter()
.position(|&byte| byte == b'\n')
.map_or(window_start, |offset| window_start + offset + 1);
let mut trimmed = b"... [older autosync log output truncated by dalo] ...\n".to_vec();
trimmed.extend_from_slice(&content[tail_start..]);
// Rewrite in place (same inode) so the scheduler's already-open append fd
// keeps writing this run's output after the retained tail.
fs::write(path, &trimmed)?;
Ok(())
}
fn read_run_state(paths: &StorePaths) -> DaloResult<Option<AutosyncRunState>> {
if !paths.autosync_run_file.exists() {
return Ok(None);
}
let content = fs::read_to_string(&paths.autosync_run_file)?;
let state: AutosyncRunState =
toml::from_str(&content).map_err(|error| DaloError::FileParse {
path: paths.autosync_run_file.clone(),
reason: error.to_string(),
})?;
if state.schema_version != AUTOSYNC_SCHEMA_VERSION {
return Err(DaloError::UnsupportedSchema {
path: paths.autosync_run_file.clone(),
version: state.schema_version,
supported: AUTOSYNC_SCHEMA_VERSION,
});
}
Ok(Some(state))
}
fn write_run_state(paths: &StorePaths, state: &AutosyncRunState) -> DaloResult<()> {
store::write_toml_atomic(&paths.autosync_run_file, state)
}
fn user_home() -> DaloResult<PathBuf> {
env::var_os("HOME")
.filter(|home| !home.is_empty())
.map(PathBuf::from)
.ok_or_else(|| DaloError::StorePath {
reason: "HOME is not set; cannot locate the user scheduler directory".to_owned(),
})
}
pub(crate) fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
type RecordedCall = (String, Vec<String>, Option<String>);
#[cfg(test)]
#[derive(Default)]
struct FakeRunner {
calls: RefCell<Vec<RecordedCall>>,
crontab: RefCell<String>,
crontab_after_next_read: RefCell<Option<String>>,
fail_programs: RefCell<Vec<String>>,
observe_enable_paths: RefCell<Option<StorePaths>>,
observed_enable_install: RefCell<Option<AutosyncInstallState>>,
observed_enable_config: RefCell<Option<crate::config::UserConfig>>,
}
#[cfg(test)]
impl CommandRunner for FakeRunner {
fn run(
&self,
program: &str,
args: &[String],
input: Option<&str>,
) -> DaloResult<CommandResult> {
self.calls
.borrow_mut()
.push((program.to_owned(), args.to_vec(), input.map(str::to_owned)));
if self
.fail_programs
.borrow()
.iter()
.any(|failing| failing == program)
{
return Ok(CommandResult {
success: false,
stdout: String::new(),
stderr: "forced cleanup failure".to_owned(),
status: "1".to_owned(),
});
}
if program == "id" {
return Ok(CommandResult {
success: true,
stdout: "501\n".to_owned(),
stderr: String::new(),
status: "0".to_owned(),
});
}
if program == "crontab" && args == ["-l"] {
let crontab = self.crontab.borrow().clone();
if let Some(updated) = self.crontab_after_next_read.borrow_mut().take() {
*self.crontab.borrow_mut() = updated;
}
return Ok(CommandResult {
success: true,
stdout: crontab,
stderr: String::new(),
status: "0".to_owned(),
});
}
if program == "crontab" && args == ["-"] {
if let Some(paths) = self.observe_enable_paths.borrow().as_ref() {
*self.observed_enable_install.borrow_mut() = Some(
read_install_state(paths)
.expect("install state should be readable while enabling")
.expect("install state should exist while enabling"),
);
*self.observed_enable_config.borrow_mut() = Some(
store::read_config(paths).expect("config should be readable while enabling"),
);
}
*self.crontab.borrow_mut() = input.unwrap_or_default().to_owned();
}
Ok(CommandResult {
success: true,
stdout: String::new(),
stderr: String::new(),
status: "0".to_owned(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn setup() -> (tempfile::TempDir, StorePaths, PathBuf, PathBuf) {
let temp = tempfile::tempdir().expect("tempdir should be created");
let store = temp.path().join("store");
store::init_store(store.clone(), false).expect("store should initialize");
let home = temp.path().join("home with spaces");
fs::create_dir_all(&home).expect("home should exist");
let executable = temp.path().join("bin/dalo '%$pecial");
fs::create_dir_all(executable.parent().expect("binary has parent"))
.expect("binary dir should exist");
fs::write(&executable, "binary").expect("binary should exist");
let mut permissions = fs::metadata(&executable)
.expect("binary metadata readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&executable, permissions).expect("binary should be executable");
(temp, StorePaths::new(store), home, executable)
}
#[test]
fn scheduler_executable_should_preserve_invoked_symlink_from_path() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let cellar_binary = temp.path().join("Cellar/dalo/0.9.0/bin/dalo");
fs::create_dir_all(cellar_binary.parent().expect("binary has parent"))
.expect("cellar directory should exist");
fs::write(&cellar_binary, "binary").expect("binary should exist");
let mut permissions = fs::metadata(&cellar_binary)
.expect("binary metadata readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&cellar_binary, permissions).expect("binary should be executable");
let stable_directory = temp.path().join("homebrew/bin");
fs::create_dir_all(&stable_directory).expect("stable directory should exist");
let stable_binary = stable_directory.join("dalo");
std::os::unix::fs::symlink(&cellar_binary, &stable_binary)
.expect("stable symlink should be created");
let selected = select_scheduler_executable(
&cellar_binary,
Some(Path::new("dalo")),
None,
temp.path(),
Some(stable_directory.as_os_str()),
None,
)
.expect("stable PATH entry should be selected");
assert_eq!(selected, stable_binary);
assert!(selected.is_symlink());
}
#[test]
fn scheduler_executable_should_use_global_npm_launcher_instead_of_cache_binary() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let cache_binary = temp
.path()
.join(".cache/dalo/0.9.0/aarch64-apple-darwin/dalo");
let launcher = temp.path().join("bin/dalo");
for executable in [&cache_binary, &launcher] {
fs::create_dir_all(executable.parent().expect("executable has parent"))
.expect("executable directory should exist");
fs::write(executable, "binary").expect("executable should exist");
let mut permissions = fs::metadata(executable)
.expect("executable metadata readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(executable, permissions).expect("file should be executable");
}
let selected = select_scheduler_executable(
&cache_binary,
Some(&cache_binary),
Some(&launcher),
temp.path(),
None,
Some("npm"),
)
.expect("global npm launcher should be selected");
assert_eq!(selected, launcher);
}
#[test]
fn scheduler_executable_should_reject_temporary_or_version_managed_paths() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let cache_binary = temp.path().join(".cache/dalo/0.9.0/target/dalo");
fs::create_dir_all(cache_binary.parent().expect("binary has parent"))
.expect("cache directory should exist");
fs::write(&cache_binary, "binary").expect("binary should exist");
let mut permissions = fs::metadata(&cache_binary)
.expect("binary metadata readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&cache_binary, permissions).expect("binary should be executable");
let cached_error = select_scheduler_executable(
&cache_binary,
Some(&cache_binary),
None,
temp.path(),
None,
None,
)
.expect_err("version-managed cache paths should be rejected");
assert!(
cached_error
.to_string()
.contains("version-managed executable")
);
let npx_error = select_scheduler_executable(
&cache_binary,
Some(&cache_binary),
None,
temp.path(),
None,
Some("npx"),
)
.expect_err("temporary npx launchers should be rejected");
assert!(npx_error.to_string().contains("temporary npx launcher"));
}
#[test]
fn version_managed_executable_should_anchor_homebrew_cellar_prefixes() {
assert!(version_managed_executable(Path::new(
"/opt/homebrew/Cellar/dalo/0.9.0/bin/dalo"
)));
assert!(version_managed_executable(Path::new(
"/usr/local/Cellar/dalo/0.9.0/bin/dalo"
)));
assert!(version_managed_executable(Path::new(
"/home/linuxbrew/.linuxbrew/Cellar/dalo/0.9.0/bin/dalo"
)));
assert!(!version_managed_executable(Path::new(
"/home/user/Cellar/dalo/bin/dalo"
)));
}
#[test]
fn scheduler_executable_should_reject_version_managed_npm_launcher_override() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let cache_launcher = temp.path().join(".cache/dalo/0.9.0/bin/dalo");
fs::create_dir_all(cache_launcher.parent().expect("launcher has parent"))
.expect("cache directory should exist");
fs::write(&cache_launcher, "launcher").expect("launcher should exist");
let mut permissions = fs::metadata(&cache_launcher)
.expect("launcher metadata readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&cache_launcher, permissions).expect("launcher should be executable");
let error = select_scheduler_executable(
&cache_launcher,
Some(&cache_launcher),
Some(&cache_launcher),
temp.path(),
None,
Some("npm"),
)
.expect_err("npm launcher overrides should use the version-managed guard");
assert!(error.to_string().contains("version-managed executable"));
}
#[test]
fn generated_scheduler_artifacts_should_preserve_exact_paths() {
let (_temp, paths, home, executable) = setup();
for backend in [
SchedulerBackend::Launchd,
SchedulerBackend::Systemd,
SchedulerBackend::Cron,
] {
let state = planned_state(&paths, backend, AutosyncSchedule::Daily, &executable, &home);
match backend {
SchedulerBackend::Launchd => {
let artifact = render_launchd(&paths, &state);
assert!(artifact.contains("dalo '%$pecial"));
assert!(artifact.contains("<string>--store</string>"));
}
SchedulerBackend::Systemd => {
let artifact = render_systemd_service(&paths, &state);
assert!(artifact.contains("ExecStart=\""));
assert!(artifact.contains(" --store \""));
assert!(artifact.contains("%%"));
assert!(artifact.contains(&format!(
"StandardOutput=append:{}",
paths
.autosync_log_file
.display()
.to_string()
.replace('%', "%%")
)));
assert!(artifact.contains(&format!(
"StandardError=append:{}",
paths
.autosync_error_log_file
.display()
.to_string()
.replace('%', "%%")
)));
assert!(!artifact.contains("StandardOutput=\"append:"));
assert!(!artifact.contains("StandardError=\"append:"));
}
SchedulerBackend::Cron => {
let artifact = render_cron(&paths, &state);
assert!(artifact.contains("'\"'\"'"));
assert!(artifact.contains("\\%"));
assert!(artifact.contains("autosync run"));
}
}
}
}
#[test]
fn systemd_log_targets_should_preserve_non_specifier_path_characters() {
let (_temp, paths, home, executable) = setup();
let paths = StorePaths::new(paths.root.with_file_name(r#"store "$%\path"#));
let state = planned_state(
&paths,
SchedulerBackend::Systemd,
AutosyncSchedule::Daily,
&executable,
&home,
);
let artifact = render_systemd_service(&paths, &state);
assert!(artifact.contains(&format!(
"StandardOutput=append:{}",
paths
.autosync_log_file
.display()
.to_string()
.replace('%', "%%")
)));
assert!(artifact.contains(&format!(
"StandardError=append:{}",
paths
.autosync_error_log_file
.display()
.to_string()
.replace('%', "%%")
)));
}
#[test]
fn weekly_schedule_should_use_sunday_for_every_backend() {
let (_temp, paths, home, executable) = setup();
let launchd = planned_state(
&paths,
SchedulerBackend::Launchd,
AutosyncSchedule::Weekly,
&executable,
&home,
);
assert!(
render_launchd(&paths, &launchd).contains("<key>Weekday</key><integer>0</integer>")
);
let systemd = planned_state(
&paths,
SchedulerBackend::Systemd,
AutosyncSchedule::Weekly,
&executable,
&home,
);
assert!(render_systemd_timer(&systemd).contains("OnCalendar=Sun "));
let cron = planned_state(
&paths,
SchedulerBackend::Cron,
AutosyncSchedule::Weekly,
&executable,
&home,
);
assert!(render_cron(&paths, &cron).contains(" * * 0 "));
}
#[test]
fn install_should_persist_state_before_enabling_scheduler() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
*runner.observe_enable_paths.borrow_mut() = Some(paths.clone());
install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect("install should succeed");
let state = runner
.observed_enable_install
.borrow_mut()
.take()
.expect("scheduler enable should observe the persisted install state");
let config = runner
.observed_enable_config
.borrow_mut()
.take()
.expect("scheduler enable should observe the persisted config");
assert_eq!(state.schedule, AutosyncSchedule::Daily);
assert!(config.settings.autosync);
assert_eq!(config.settings.sync_interval.as_deref(), Some("daily"));
}
#[cfg(unix)]
#[test]
fn system_runner_should_report_an_early_stdin_close_as_a_command_failure() {
let temp = tempfile::tempdir().expect("temporary directory should be created");
let command = temp.path().join("close-stdin");
fs::write(&command, "#!/bin/sh\nexec 0<&-\nexit 1\n")
.expect("command fixture should be written");
let mut permissions = fs::metadata(&command)
.expect("command fixture metadata should be readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&command, permissions).expect("command fixture should be executable");
let result = SystemCommandRunner
.run(
command.to_str().expect("command path should be UTF-8"),
&[],
Some(&"x".repeat(1024 * 1024)),
)
.expect("an early child exit should be returned as a command result");
assert!(!result.success);
}
#[test]
fn install_should_roll_back_persisted_metadata_when_enabling_fails() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
runner.fail_programs.borrow_mut().push("crontab".to_owned());
install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect_err("a scheduler failure should fail the install");
assert!(!paths.autosync_file.exists());
let config = store::read_config(&paths).expect("config should remain readable");
assert!(!config.settings.autosync);
assert!(config.settings.sync_interval.is_none());
}
#[test]
fn install_and_uninstall_should_be_idempotent_for_every_backend() {
for backend in [
SchedulerBackend::Launchd,
SchedulerBackend::Systemd,
SchedulerBackend::Cron,
] {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
let first = install_with(
&paths,
AutosyncSchedule::Hourly,
false,
backend,
&executable,
&home,
&runner,
)
.expect("first install should succeed");
assert_eq!(first.action, "installed");
let second = install_with(
&paths,
AutosyncSchedule::Hourly,
false,
backend,
&executable,
&home,
&runner,
)
.expect("second install should succeed");
assert_eq!(second.action, "unchanged");
assert!(
store::read_config(&paths)
.expect("config parses")
.settings
.autosync
);
let updated = install_with(
&paths,
AutosyncSchedule::Weekly,
false,
backend,
&executable,
&home,
&runner,
)
.expect("schedule update should succeed");
assert_eq!(updated.action, "updated");
let installed_status = status_with(&paths, &runner).expect("status should succeed");
assert!(installed_status.configured);
assert!(installed_status.installed);
assert!(installed_status.enabled);
let started = begin_run(&paths).expect("scheduled run should begin");
finish_run(
&paths,
started,
AutosyncRunOutcome::Blocked,
Some("review required".to_owned()),
)
.expect("blocked run should persist");
assert!(paths.autosync_run_file.exists());
let removed = uninstall_with(&paths, false, &runner, Some(&home))
.expect("first uninstall should succeed");
assert_eq!(removed.action, "uninstalled");
assert!(removed.status.last_run.is_none());
assert!(!paths.autosync_run_file.exists());
let repeated = uninstall_with(&paths, false, &runner, Some(&home))
.expect("second uninstall should succeed");
assert_eq!(repeated.action, "unchanged");
assert!(
!store::read_config(&paths)
.expect("config parses")
.settings
.autosync
);
}
}
#[test]
fn running_run_is_stale_should_detect_interrupted_runs() {
let running = AutosyncRunState {
schema_version: AUTOSYNC_SCHEMA_VERSION,
last_attempted_at_unix: 1_000_000,
last_successful_at_unix: None,
outcome: AutosyncRunOutcome::Running,
reason: None,
};
let interval = AutosyncSchedule::Daily.interval_secs();
// Still within the grace window: treated as in progress, not stale.
assert!(!running_run_is_stale(
&running,
Some(AutosyncSchedule::Daily),
1_000_000 + interval,
));
// Well past the grace window: treated as an interrupted run.
assert!(running_run_is_stale(
&running,
Some(AutosyncSchedule::Daily),
1_000_000 + interval * 3,
));
// Terminal outcomes are never stale, regardless of age.
let succeeded = AutosyncRunState {
outcome: AutosyncRunOutcome::Succeeded,
..running
};
assert!(!running_run_is_stale(
&succeeded,
Some(AutosyncSchedule::Daily),
u64::MAX,
));
}
#[test]
fn uninstall_should_remove_autosync_logs() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect("install should succeed");
fs::write(&paths.autosync_log_file, "log line\n").expect("log should be written");
fs::write(&paths.autosync_error_log_file, "err line\n")
.expect("error log should be written");
uninstall_with(&paths, false, &runner, Some(&home)).expect("uninstall should succeed");
assert!(
!paths.autosync_log_file.exists(),
"stdout log should be removed on uninstall"
);
assert!(
!paths.autosync_error_log_file.exists(),
"stderr log should be removed on uninstall"
);
}
#[test]
fn trim_log_to_tail_keeps_recent_tail_and_marks_truncation() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let log = temp.path().join("autosync.log");
let mut content = String::new();
for index in 0..50 {
content.push_str(&format!("line {index}\n"));
}
fs::write(&log, &content).expect("log should be written");
let original_len = fs::metadata(&log).expect("metadata").len();
trim_log_to_tail(&log, 40).expect("trim should succeed");
let trimmed = fs::read_to_string(&log).expect("trimmed log should read");
assert!(fs::metadata(&log).expect("metadata").len() < original_len);
assert!(trimmed.contains("truncated by dalo"));
// The most recent lines survive; the oldest are dropped.
assert!(trimmed.contains("line 49\n"));
assert!(!trimmed.contains("line 0\n"));
// Every retained line (after the marker) is whole.
for line in trimmed.lines().skip(1) {
assert!(line.starts_with("line "), "unexpected partial line: {line}");
}
}
#[test]
fn trim_log_to_tail_keeps_tail_bytes_when_the_window_has_no_newline() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let log = temp.path().join("autosync.log");
// A single oversized line with no newline must not lose all content.
fs::write(&log, "x".repeat(200)).expect("log should be written");
trim_log_to_tail(&log, 40).expect("trim should succeed");
let trimmed = fs::read(&log).expect("trimmed log should read");
let marker_end = trimmed
.iter()
.position(|&byte| byte == b'\n')
.expect("marker should be present")
+ 1;
// The most recent 40 bytes survive rather than being discarded.
assert_eq!(&trimmed[marker_end..], vec![b'x'; 40].as_slice());
}
#[test]
fn trim_log_to_tail_leaves_small_logs_untouched() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let log = temp.path().join("autosync.log");
fs::write(&log, "small\n").expect("log should be written");
trim_log_to_tail(&log, 1024).expect("trim should succeed");
assert_eq!(
fs::read_to_string(&log).expect("log should read"),
"small\n"
);
}
#[test]
fn trim_log_to_tail_is_a_noop_for_a_missing_file() {
let temp = tempfile::tempdir().expect("tempdir should be created");
let log = temp.path().join("missing.log");
trim_log_to_tail(&log, 1024).expect("a missing log is not an error");
assert!(!log.exists());
}
#[test]
fn uninstall_dry_run_should_keep_autosync_logs() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect("install should succeed");
fs::write(&paths.autosync_log_file, "log line\n").expect("log should be written");
uninstall_with(&paths, true, &runner, Some(&home))
.expect("dry-run uninstall should succeed");
assert!(
paths.autosync_log_file.exists(),
"dry-run uninstall must not remove logs"
);
}
#[test]
fn status_should_explain_a_disabled_job() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect("install should succeed");
fs::remove_file(&executable).expect("executable should be removable");
let status = status_with(&paths, &runner).expect("status should succeed");
assert!(status.installed);
assert!(!status.enabled);
let reason = status
.disabled_reason
.expect("a disabled job should explain the cause");
assert!(
reason.contains("executable"),
"reason should name the missing executable: {reason}"
);
}
#[test]
fn uninstall_should_recover_from_corrupt_install_state() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
#[cfg(target_os = "macos")]
let native_backend = SchedulerBackend::Launchd;
#[cfg(target_os = "linux")]
let native_backend = SchedulerBackend::Systemd;
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
let native_backend = SchedulerBackend::Cron;
install_with(
&paths,
AutosyncSchedule::Hourly,
false,
native_backend,
&executable,
&home,
&runner,
)
.expect("native install should succeed");
let cron_state = planned_state(
&paths,
SchedulerBackend::Cron,
AutosyncSchedule::Hourly,
&executable,
&home,
);
install_cron(&paths, &cron_state, &runner).expect("cron block should be installed");
let attempted = begin_run(&paths).expect("run state should be created");
finish_run(
&paths,
attempted,
AutosyncRunOutcome::Blocked,
Some("review required".to_owned()),
)
.expect("run state should be persisted");
fs::write(&paths.autosync_file, "not = [valid toml")
.expect("install state should be corrupted");
let calls_before_dry_run = runner.calls.borrow().len();
let preview = uninstall_with(&paths, true, &runner, Some(&home))
.expect("recovery dry-run should succeed");
assert_eq!(preview.action, "would_uninstall");
assert!(paths.autosync_file.exists());
assert_eq!(runner.calls.borrow().len(), calls_before_dry_run);
let report = uninstall_with(&paths, false, &runner, Some(&home))
.expect("corrupt install state should be recoverable");
assert_eq!(report.action, "uninstalled");
assert!(report.status.scheduler_error.is_none());
assert!(!paths.autosync_file.exists());
assert!(!paths.autosync_run_file.exists());
assert!(
!store::read_config(&paths)
.expect("config should remain readable")
.settings
.autosync
);
assert!(
!runner
.crontab
.borrow()
.contains(&cron_begin(&cron_state.identifier))
);
for artifact in planned_state(
&paths,
native_backend,
AutosyncSchedule::Daily,
&executable,
&home,
)
.artifacts
{
if artifact != "crontab" {
assert!(!Path::new(&artifact).exists());
}
}
let backups = fs::read_dir(&paths.root)
.expect("store should be readable")
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().into_string().ok())
.filter(|name| name.starts_with("autosync.toml.corrupt-"))
.collect::<Vec<_>>();
assert_eq!(backups.len(), 1);
install_with(
&paths,
AutosyncSchedule::Daily,
true,
native_backend,
&executable,
&home,
&runner,
)
.expect("a clean reinstall preview should succeed after recovery");
}
#[test]
fn uninstall_should_quarantine_newer_schema_install_state() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
let mut state = planned_state(
&paths,
SchedulerBackend::Cron,
AutosyncSchedule::Daily,
&executable,
&home,
);
state.schema_version = AUTOSYNC_SCHEMA_VERSION + 1;
write_install_state(&paths, &state).expect("newer state should be written");
let report = uninstall_with(&paths, false, &runner, Some(&home))
.expect("newer-schema state should be recoverable");
assert_eq!(report.action, "uninstalled");
assert!(!paths.autosync_file.exists());
assert!(
fs::read_dir(&paths.root)
.expect("store should be readable")
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().into_string().ok())
.any(|name| name.starts_with("autosync.toml.corrupt-"))
);
}
#[test]
fn corrupt_state_recovery_should_clear_metadata_after_scheduler_cleanup_failures() {
let (_temp, paths, home, _executable) = setup();
fs::write(&paths.autosync_file, "not = [valid toml")
.expect("install state should be corrupted");
let runner = FakeRunner::default();
runner
.fail_programs
.borrow_mut()
.extend(["id", "launchctl", "systemctl", "crontab"].map(str::to_owned));
let report = uninstall_with(&paths, false, &runner, Some(&home))
.expect("scheduler failures should not wedge corrupt-state recovery");
assert_eq!(report.action, "uninstalled");
assert!(!paths.autosync_file.exists());
assert!(
report
.status
.scheduler_error
.as_deref()
.is_some_and(|error| error.contains("could not clean every"))
);
}
#[test]
fn read_install_state_should_reject_state_with_missing_artifacts() {
let (_temp, paths, home, executable) = setup();
let mut state = planned_state(
&paths,
SchedulerBackend::Launchd,
AutosyncSchedule::Daily,
&executable,
&home,
);
// A launchd state indexes artifacts[0]; an empty array must be rejected
// as corrupt rather than panic on out-of-bounds indexing.
state.artifacts.clear();
write_install_state(&paths, &state).expect("state should be written");
assert!(matches!(
read_install_state(&paths),
Err(DaloError::FileParse { .. })
));
let runner = FakeRunner::default();
let report = uninstall_with(&paths, false, &runner, Some(&home))
.expect("short-artifact install state should be recoverable");
assert_eq!(report.action, "uninstalled");
assert!(!paths.autosync_file.exists());
assert!(
fs::read_dir(&paths.root)
.expect("store should be readable")
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().into_string().ok())
.any(|name| name.starts_with("autosync.toml.corrupt-"))
);
}
#[test]
fn uninstall_should_not_quarantine_temporarily_unreadable_install_state() {
let (_temp, paths, home, executable) = setup();
let state = planned_state(
&paths,
SchedulerBackend::Cron,
AutosyncSchedule::Daily,
&executable,
&home,
);
write_install_state(&paths, &state).expect("valid state should be written");
let mut permissions = fs::metadata(&paths.autosync_file)
.expect("state metadata should be readable")
.permissions();
permissions.set_mode(0o000);
fs::set_permissions(&paths.autosync_file, permissions)
.expect("state should be made unreadable");
// The superuser bypasses permission bits (common in CI containers), so
// the "unreadable state" precondition this test relies on cannot hold
// there. Skip rather than fail spuriously when the file stays readable.
if fs::read(&paths.autosync_file).is_ok() {
return;
}
let runner = FakeRunner::default();
let result = uninstall_with(&paths, false, &runner, Some(&home));
let state_remained = paths.autosync_file.exists();
if state_remained {
let mut permissions = fs::metadata(&paths.autosync_file)
.expect("state metadata should remain readable")
.permissions();
permissions.set_mode(0o600);
fs::set_permissions(&paths.autosync_file, permissions)
.expect("state permissions should be restored");
}
assert!(matches!(result, Err(DaloError::Io(_))));
assert!(state_remained);
assert!(
!fs::read_dir(&paths.root)
.expect("store should be readable")
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().into_string().ok())
.any(|name| name.starts_with("autosync.toml.corrupt-"))
);
}
#[test]
fn dry_run_should_not_write_artifacts_config_or_scheduler_state() {
let (_temp, paths, home, executable) = setup();
let config_before = fs::read(&paths.config_file).expect("config readable");
let runner = FakeRunner::default();
let report = install_with(
&paths,
AutosyncSchedule::Weekly,
true,
SchedulerBackend::Systemd,
&executable,
&home,
&runner,
)
.expect("dry-run should succeed");
assert_eq!(report.action, "would_install");
assert!(!paths.autosync_file.exists());
assert_eq!(
fs::read(&paths.config_file).expect("config readable"),
config_before
);
assert!(runner.calls.borrow().is_empty());
}
#[test]
fn install_should_reject_scheduler_path_control_characters() {
let (_temp, paths, home, _executable) = setup();
let executable = home.join("dalo\nunsafe");
fs::write(&executable, "binary").expect("binary should exist");
let mut permissions = fs::metadata(&executable)
.expect("binary metadata readable")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&executable, permissions).expect("binary should be executable");
let error = install_with(
&paths,
AutosyncSchedule::Daily,
true,
SchedulerBackend::Cron,
&executable,
&home,
&FakeRunner::default(),
)
.expect_err("control characters must be rejected");
assert!(error.to_string().contains("control characters"));
}
#[test]
fn run_state_should_preserve_last_success_across_skip() {
let (_temp, paths, _home, _executable) = setup();
let first = begin_run(&paths).expect("run should begin");
finish_run(&paths, first, AutosyncRunOutcome::Succeeded, None)
.expect("success should persist");
let successful = read_run_state(&paths)
.expect("state readable")
.expect("state exists")
.last_successful_at_unix;
let second = begin_run(&paths).expect("second run should begin");
finish_run(
&paths,
second,
AutosyncRunOutcome::Skipped,
Some("store lock held by pid=42".to_owned()),
)
.expect("skip should persist");
let state = read_run_state(&paths)
.expect("state readable")
.expect("state exists");
assert_eq!(state.last_successful_at_unix, successful);
assert_eq!(state.outcome, AutosyncRunOutcome::Skipped);
}
#[test]
fn cron_install_should_preserve_unrelated_edits_made_before_the_final_read() {
let (_temp, paths, home, executable) = setup();
let state = planned_state(
&paths,
SchedulerBackend::Cron,
AutosyncSchedule::Daily,
&executable,
&home,
);
let runner = FakeRunner::default();
*runner.crontab.borrow_mut() = "5 4 * * * /usr/bin/backup\n".to_owned();
*runner.crontab_after_next_read.borrow_mut() =
Some("5 4 * * * /usr/bin/backup\n6 4 * * * /usr/bin/rotate\n".to_owned());
install_cron(&paths, &state, &runner).expect("cron install should succeed");
let crontab = runner.crontab.borrow();
assert!(crontab.contains("/usr/bin/backup"));
assert!(crontab.contains("/usr/bin/rotate"));
assert!(crontab.contains(&cron_begin(&state.identifier)));
}
#[test]
fn cron_remove_should_preserve_unrelated_edits_made_before_the_final_read() {
let (_temp, paths, home, executable) = setup();
let state = planned_state(
&paths,
SchedulerBackend::Cron,
AutosyncSchedule::Daily,
&executable,
&home,
);
let runner = FakeRunner::default();
let dalo_block = render_cron(&paths, &state);
*runner.crontab.borrow_mut() = format!("5 4 * * * /usr/bin/backup\n{dalo_block}");
*runner.crontab_after_next_read.borrow_mut() = Some(format!(
"5 4 * * * /usr/bin/backup\n6 4 * * * /usr/bin/rotate\n{dalo_block}"
));
remove_cron(&state, &runner).expect("cron removal should succeed");
let crontab = runner.crontab.borrow();
assert!(crontab.contains("/usr/bin/backup"));
assert!(crontab.contains("/usr/bin/rotate"));
assert!(!crontab.contains(&cron_begin(&state.identifier)));
}
#[test]
fn cron_update_should_preserve_unrelated_entries() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
*runner.crontab.borrow_mut() = "5 4 * * * /usr/bin/backup\n".to_owned();
install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect("cron install should succeed");
install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect("cron reinstall should succeed");
let crontab = runner.crontab.borrow();
assert!(crontab.contains("/usr/bin/backup"));
assert_eq!(crontab.matches(CRON_BEGIN_PREFIX).count(), 1);
}
#[test]
fn cron_update_should_fail_closed_on_malformed_owned_block() {
let (_temp, paths, home, executable) = setup();
let runner = FakeRunner::default();
let state = planned_state(
&paths,
SchedulerBackend::Cron,
AutosyncSchedule::Daily,
&executable,
&home,
);
let original = format!(
"{}\n5 4 * * * /usr/bin/backup\n",
cron_begin(&state.identifier)
);
*runner.crontab.borrow_mut() = original.clone();
let error = install_with(
&paths,
AutosyncSchedule::Daily,
false,
SchedulerBackend::Cron,
&executable,
&home,
&runner,
)
.expect_err("malformed owned block should fail");
assert!(error.to_string().contains("no end marker"));
assert_eq!(*runner.crontab.borrow(), original);
}
}