postvak-core 0.5.0

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

use anyhow::{Context, Result, bail};

use super::Client;
use crate::paths::{self, Paths};

const LAUNCHD_LABEL: &str = "io.github.postvak_app.postvak";
const SYSTEMD_UNIT: &str = "postvak";
const UNSUPPORTED: &str = "postvak service supports macOS and Linux";

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Target {
    Launchd,
    Systemd,
}

/// One command to run; a tolerated failure is not an error (booting out a service that is not loaded).
struct Step {
    args: Vec<String>,
    program: &'static str,
    tolerate_failure: bool,
}

impl Step {
    fn new(program: &'static str, args: &[&str], tolerate_failure: bool) -> Step {
        Step {
            args: args.iter().map(|arg| arg.to_string()).collect(),
            program,
            tolerate_failure,
        }
    }

    fn shown(&self) -> String {
        format!("{} {}", self.program, self.args.join(" "))
    }

    fn run(&self) -> Result<()> {
        let status = Command::new(self.program)
            .args(&self.args)
            .status()
            .with_context(|| format!("running `{}`", self.shown()))?;
        if !status.success() && !self.tolerate_failure {
            bail!("`{}` failed ({status})", self.shown());
        }
        Ok(())
    }
}

impl Target {
    pub fn current() -> Result<Target> {
        if cfg!(target_os = "macos") {
            Ok(Target::Launchd)
        } else if cfg!(target_os = "linux") {
            Ok(Target::Systemd)
        } else {
            bail!(UNSUPPORTED)
        }
    }

    pub fn file_name(self) -> &'static str {
        match self {
            Target::Launchd => "io.github.postvak_app.postvak.plist",
            Target::Systemd => "postvak.service",
        }
    }

    pub fn file(self, home: &Path) -> PathBuf {
        match self {
            Target::Launchd => home.join("Library/LaunchAgents").join(self.file_name()),
            Target::Systemd => home.join(".config/systemd/user").join(self.file_name()),
        }
    }

    /// `postvak_home` is the `POSTVAK_HOME` the service's daemon has to use, when one is set.
    fn text(self, exe: &Path, log: &Path, postvak_home: Option<&Path>) -> String {
        match self {
            Target::Launchd => plist(exe, log, postvak_home),
            Target::Systemd => unit(exe, postvak_home),
        }
    }

    fn install_steps(self, home: &Path, file: &Path) -> Result<Vec<Step>> {
        Ok(match self {
            Target::Launchd => {
                let domain = launchd_domain(home)?;
                let file = file.to_string_lossy();
                vec![
                    Step::new(
                        "launchctl",
                        &["bootout", &format!("{domain}/{LAUNCHD_LABEL}")],
                        true,
                    ),
                    Step::new("launchctl", &["bootstrap", &domain, &file], false),
                ]
            }
            Target::Systemd => vec![
                Step::new("systemctl", &["--user", "daemon-reload"], false),
                Step::new(
                    "systemctl",
                    &["--user", "enable", "--now", SYSTEMD_UNIT],
                    false,
                ),
            ],
        })
    }

    /// The first step stops the service; the rest run after the file is deleted.
    fn remove_steps(self, home: &Path) -> Result<Vec<Step>> {
        Ok(match self {
            Target::Launchd => vec![Step::new(
                "launchctl",
                &[
                    "bootout",
                    &format!("{}/{LAUNCHD_LABEL}", launchd_domain(home)?),
                ],
                true,
            )],
            Target::Systemd => vec![
                Step::new(
                    "systemctl",
                    &["--user", "disable", "--now", SYSTEMD_UNIT],
                    true,
                ),
                Step::new("systemctl", &["--user", "daemon-reload"], true),
            ],
        })
    }
}

/// The text to print; with `dry_run` nothing is written, stopped or run.
pub fn install(paths: &Paths, dry_run: bool) -> Result<String> {
    if let Some(id) = paths::flatpak_id() {
        return Ok(flatpak_steps(&id, true));
    }
    let target = Target::current()?;
    let home = home_dir()?;
    let file = target.file(&home);
    let exe = paths::stable_exe().context("finding this postvak")?;
    let text = target.text(&exe, &paths.daemon_log(), paths.home.as_deref());
    let steps = target.install_steps(&home, &file)?;
    if !dry_run {
        stop_running_daemon(paths)?;
        paths::write_atomic_keeping_dir_mode(&file, text.as_bytes())
            .with_context(|| format!("writing {}", file.display()))?;
        steps.iter().try_for_each(Step::run)?;
    }
    Ok(describe(
        dry_run,
        ("would write", "wrote"),
        &file,
        Some(&text),
        &steps,
    ))
}

/// The text to print; with `dry_run` nothing is stopped, run or deleted.
pub fn remove(dry_run: bool) -> Result<String> {
    if let Some(id) = paths::flatpak_id() {
        return Ok(flatpak_steps(&id, false));
    }
    let target = Target::current()?;
    let home = home_dir()?;
    let file = target.file(&home);
    let steps = target.remove_steps(&home)?;
    if !dry_run {
        steps[0].run()?;
        match std::fs::remove_file(&file) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(e).with_context(|| format!("deleting {}", file.display())),
        }
        steps[1..].iter().try_for_each(Step::run)?;
    }
    Ok(describe(
        dry_run,
        ("would delete", "deleted"),
        &file,
        None,
        &steps,
    ))
}

/// What to do by hand: the sandbox cannot write the host's systemd folder, and the unit must go through `flatpak run`.
fn flatpak_steps(app_id: &str, install: bool) -> String {
    let file = format!("~/.config/systemd/user/{}", Target::Systemd.file_name());
    if install {
        let text = unit_running(&format!("flatpak run {app_id}"), None);
        format!(
            "the Flatpak cannot write the host's systemd folder; save this as {file}:\n{}\nthen run: \
             systemctl --user daemon-reload && systemctl --user enable --now {SYSTEMD_UNIT}",
            text.trim_end()
        )
    } else {
        format!(
            "the Flatpak cannot change the host's systemd folder; run: systemctl --user disable --now {SYSTEMD_UNIT} \
             && rm {file} && systemctl --user daemon-reload"
        )
    }
}

/// A daemon already running holds the lock the service's daemon needs.
fn stop_running_daemon(paths: &Paths) -> Result<()> {
    if let Some(client) = Client::connect_any_version(paths)? {
        client.stop_and_wait(paths)?;
    }
    Ok(())
}

/// `verbs` is the (dry run, done) wording of the file change.
fn describe(
    dry_run: bool,
    verbs: (&str, &str),
    file: &Path,
    text: Option<&str>,
    steps: &[Step],
) -> String {
    let (verb, run) = if dry_run {
        (verbs.0, "would run")
    } else {
        (verbs.1, "ran")
    };
    let mut out = format!("{verb} {}", file.display());
    if let Some(text) = text {
        let _ = write!(out, ":\n{}", text.trim_end());
    }
    for step in steps {
        let _ = write!(out, "\n{run}: {}", step.shown());
    }
    out
}

fn home_dir() -> Result<PathBuf> {
    directories::BaseDirs::new()
        .map(|dirs| dirs.home_dir().to_path_buf())
        .context("no home directory found")
}

/// `gui/<uid>`; the uid is the home directory's owner, which avoids a libc call.
fn launchd_domain(home: &Path) -> Result<String> {
    let uid = std::fs::metadata(home)
        .with_context(|| format!("reading {}", home.display()))?
        .uid();
    Ok(format!("gui/{uid}"))
}

pub fn plist(exe: &Path, log: &Path, postvak_home: Option<&Path>) -> String {
    plist_with_path(
        exe,
        log,
        std::env::var("PATH").ok().as_deref(),
        postvak_home,
    )
}

fn plist_with_path(
    exe: &Path,
    log: &Path,
    path: Option<&str>,
    postvak_home: Option<&Path>,
) -> String {
    let exe = crate::notify::escape_markup(&exe.to_string_lossy());
    let log = crate::notify::escape_markup(&log.to_string_lossy());
    let variables: Vec<(&str, String)> = [
        path.map(|path| ("PATH", path.to_string())),
        postvak_home.map(|home| ("POSTVAK_HOME", home.to_string_lossy().into_owned())),
    ]
    .into_iter()
    .flatten()
    .collect();
    let environment = if variables.is_empty() {
        String::new()
    } else {
        let entries: String = variables
            .iter()
            .map(|(key, value)| {
                format!(
                    "        <key>{key}</key>\n        <string>{}</string>\n",
                    crate::notify::escape_markup(value)
                )
            })
            .collect();
        format!("    <key>EnvironmentVariables</key>\n    <dict>\n{entries}    </dict>\n")
    };
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{LAUNCHD_LABEL}</string>
    <key>ProgramArguments</key>
    <array>
        <string>{exe}</string>
        <string>run</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>{log}</string>
    <key>StandardErrorPath</key>
    <string>{log}</string>
{environment}</dict>
</plist>
"#
    )
}

pub fn unit(exe: &Path, postvak_home: Option<&Path>) -> String {
    unit_running(&systemd_quoted(&exe.to_string_lossy()), postvak_home)
}

/// `command` is already quoted for systemd.
fn unit_running(command: &str, postvak_home: Option<&Path>) -> String {
    let environment = postvak_home.map_or_else(String::new, |home| {
        format!(
            "Environment={}\n",
            systemd_quoted(&format!("POSTVAK_HOME={}", home.to_string_lossy()))
        )
    });
    format!(
        "[Unit]\nDescription=Postvak mail sync\n\n[Service]\n{environment}ExecStart={command} run\nRestart=always\nRestartSec=10\n\n[Install]\nWantedBy=default.target\n"
    )
}

/// systemd expands `%` specifiers and `$` variables and unquotes `"` and `\` in ExecStart and Environment, so a value
/// needs all four escaped inside its quotes.
fn systemd_quoted(text: &str) -> String {
    let escaped = text
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('%', "%%")
        .replace('$', "$$");
    format!("\"{escaped}\"")
}

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

    #[test]
    fn a_flatpak_prints_a_unit_that_runs_the_app_through_flatpak() {
        let text = flatpak_steps("io.github.postvak_app.postvak", true);
        assert!(
            text.contains("ExecStart=flatpak run io.github.postvak_app.postvak run\n"),
            "{text}"
        );
        assert!(
            text.contains("~/.config/systemd/user/postvak.service"),
            "{text}"
        );
        assert!(
            text.contains("systemctl --user enable --now postvak"),
            "{text}"
        );
        let text = flatpak_steps("io.github.postvak_app.postvak", false);
        assert!(
            text.contains("systemctl --user disable --now postvak"),
            "{text}"
        );
    }

    #[test]
    fn the_launchd_plist_runs_the_binary_at_login_and_keeps_it_alive() {
        let text = plist(
            Path::new("/opt/homebrew/bin/postvak"),
            Path::new("/Users/me/Library/Application Support/postvak/daemon.log"),
            None,
        );
        for needle in [
            "<string>io.github.postvak_app.postvak</string>",
            "<string>/opt/homebrew/bin/postvak</string>",
            "<string>run</string>",
            "<key>RunAtLoad</key>",
            "<key>KeepAlive</key>",
            "<key>EnvironmentVariables</key>",
            "daemon.log",
        ] {
            assert!(text.contains(needle), "{needle} missing:\n{text}");
        }
    }

    #[test]
    fn the_plist_escapes_xml_in_paths() {
        let text = plist(Path::new("/a&b/postvak"), Path::new("/x/<log>"), None);
        assert!(text.contains("/a&amp;b/postvak"), "{text}");
        assert!(text.contains("/x/&lt;log&gt;"), "{text}");
    }

    #[test]
    fn the_systemd_unit_always_restarts() {
        let text = unit(Path::new("/home/me/.cargo/bin/postvak"), None);
        assert!(text.contains("ExecStart=\"/home/me/.cargo/bin/postvak\" run"));
        assert!(text.contains("Restart=always\nRestartSec=10\n"));
        assert!(text.contains("WantedBy=default.target"));
    }

    #[test]
    fn the_systemd_exec_start_survives_spaces_percent_and_dollar_signs() {
        let text = unit(Path::new("/home/me/my bin/50%/$HOME/postvak"), None);
        assert!(
            text.contains("ExecStart=\"/home/me/my bin/50%%/$$HOME/postvak\" run"),
            "{text}"
        );
    }

    #[test]
    fn the_plist_has_no_environment_without_a_path() {
        let text = plist_with_path(Path::new("/bin/postvak"), Path::new("/x/log"), None, None);
        assert!(!text.contains("EnvironmentVariables"), "{text}");
        assert!(text.contains("</dict>\n</plist>"), "{text}");
    }

    #[test]
    fn the_service_keeps_a_postvak_home() {
        let home = Path::new("/tmp/50% <me>");
        let text = plist_with_path(
            Path::new("/bin/postvak"),
            Path::new("/x/log"),
            Some("/bin"),
            Some(home),
        );
        assert!(
            text.contains("<key>PATH</key>\n        <string>/bin</string>\n        <key>POSTVAK_HOME</key>\n        <string>/tmp/50% &lt;me&gt;</string>\n    </dict>"),
            "{text}"
        );
        let text = unit(Path::new("/bin/postvak"), Some(home));
        assert!(
            text.contains("Environment=\"POSTVAK_HOME=/tmp/50%% <me>\"\nExecStart="),
            "{text}"
        );
        assert!(!unit(Path::new("/bin/postvak"), None).contains("Environment="));
    }

    #[test]
    fn removing_the_systemd_unit_reloads_systemd_after_the_file_is_gone() {
        let steps = Target::Systemd.remove_steps(Path::new("/home/me")).unwrap();
        let shown: Vec<_> = steps.iter().map(Step::shown).collect();
        assert_eq!(
            shown,
            [
                "systemctl --user disable --now postvak",
                "systemctl --user daemon-reload"
            ]
        );
        assert!(steps.iter().all(|step| step.tolerate_failure));
    }

    #[test]
    fn a_dry_run_install_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths::under(dir.path());
        let before = target_stamp();
        let text = install(&paths, true).unwrap();
        assert_eq!(target_stamp(), before);
        assert!(
            text.contains(Target::current().unwrap().file_name()),
            "{text}"
        );
        assert!(
            text.contains("launchctl") || text.contains("systemctl"),
            "{text}"
        );
        assert!(text.contains("run"), "{text}");
    }

    #[test]
    fn a_dry_run_remove_names_the_file_and_the_command() {
        let before = target_stamp();
        let text = remove(true).unwrap();
        assert_eq!(target_stamp(), before);
        assert!(
            text.contains(Target::current().unwrap().file_name()),
            "{text}"
        );
        assert!(
            text.contains("bootout") || text.contains("disable"),
            "{text}"
        );
    }

    /// Whether the real service file exists and when it last changed; a dry run must leave both alone.
    fn target_stamp() -> Option<std::time::SystemTime> {
        let target = Target::current().unwrap();
        std::fs::metadata(target.file(&home_dir().unwrap()))
            .and_then(|meta| meta.modified())
            .ok()
    }
}