marathon-engine 0.1.2

The part of Marathon that runs: keeps the Mac awake, keeps time, answers the command
//! Local socket IPC. Whoever holds the lock file is the one server; it
//! listens on a socket in a private (0700) folder and answers one JSON
//! request line per connection.

use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::{self, BufRead, BufReader, Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};

use marathon_core::protocol::{Reply, Request, from_line, to_line};

use crate::Engine;

const IO_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_LINE: u64 = 64 * 1024;
const STACK: usize = 256 * 1024;

/// `~/Library/Application Support/Marathon`, or `$MARATHON_DIR` if set
/// (used by tests).
pub fn support_dir() -> PathBuf {
    if let Some(dir) = std::env::var_os("MARATHON_DIR") {
        return dir.into();
    }
    let home = std::env::var_os("HOME").unwrap_or_else(|| "/tmp".into());
    PathBuf::from(home).join("Library/Application Support/Marathon")
}

fn socket_path() -> PathBuf {
    support_dir().join("marathon.sock")
}

/// Sends one request to the running server.
pub fn request(req: &Request) -> io::Result<Reply> {
    let stream = UnixStream::connect(socket_path())?;
    set_timeouts(&stream)?;
    (&stream).write_all(to_line(req).as_bytes())?;
    let line = read_line(&stream)?;
    if line.is_empty() {
        return Err(io::ErrorKind::UnexpectedEof.into());
    }
    from_line(&line).map_err(io::Error::other)
}

fn set_timeouts(stream: &UnixStream) -> io::Result<()> {
    stream.set_read_timeout(Some(IO_TIMEOUT))?;
    stream.set_write_timeout(Some(IO_TIMEOUT))
}

/// Reads one line, capped so a bad peer cannot make us buffer forever.
fn read_line(stream: &UnixStream) -> io::Result<String> {
    let mut line = String::new();
    BufReader::new(stream.take(MAX_LINE)).read_line(&mut line)?;
    Ok(line)
}

/// True when `err` from [`request`] means no server is running, including
/// one that hung up because it was exiting.
pub fn is_no_server(err: &io::Error) -> bool {
    matches!(
        err.kind(),
        io::ErrorKind::NotFound
            | io::ErrorKind::ConnectionRefused
            | io::ErrorKind::ConnectionReset
            | io::ErrorKind::UnexpectedEof
    )
}

/// The running socket server. Dropping it does not stop it; it lives as
/// long as the process.
pub struct Server {
    /// Read-held while a request is answered; `quiesce` takes it for writing.
    busy: Arc<RwLock<()>>,
    _lock: File,
}

impl Server {
    /// Becomes the server for `engine`. If another process serves, waits
    /// up to `wait` for it to exit (`Duration::MAX`: as long as it takes),
    /// then fails with `WouldBlock`.
    pub fn start(engine: Engine, wait: Duration) -> io::Result<Server> {
        let dir = support_dir();
        fs::create_dir_all(&dir)?;
        fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?;
        let lock = OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(dir.join("marathon.lock"))?;
        acquire(&lock, wait)?;
        // We hold the lock, so any socket file left behind is stale.
        let path = socket_path();
        crate::store::remove(&path)?;
        let listener = UnixListener::bind(&path)?;
        // Serving makes this process the one that keeps the saved state.
        engine.start_saving();
        let busy = Arc::new(RwLock::new(()));
        let b = busy.clone();
        thread::Builder::new()
            .name("marathon-ipc".into())
            .stack_size(STACK)
            .spawn(move || {
                for stream in listener.incoming() {
                    let Ok(stream) = stream else {
                        // e.g. out of file descriptors: back off, don't spin.
                        thread::sleep(Duration::from_millis(100));
                        continue;
                    };
                    // One thread per client, so a stalled client delays no one.
                    let (engine, b) = (engine.clone(), b.clone());
                    let _ = thread::Builder::new()
                        .name("marathon-client".into())
                        .stack_size(STACK)
                        .spawn(move || {
                            let _guard = b.read().unwrap_or_else(|e| e.into_inner());
                            // A client that hangs up early is not our problem.
                            let _ = answer(&engine, stream);
                        });
                }
            })?;
        Ok(Server { busy, _lock: lock })
    }

    /// Serves `engine` for the rest of the process as the app. If the CLI's
    /// background helper is serving, it is asked to release its session,
    /// which moves here once its lock is ours. Fails with `AlreadyExists`
    /// if another app serves, or anything else serves and won't answer.
    pub fn take_over(engine: &Engine) -> io::Result<()> {
        let deadline = Instant::now() + Duration::from_secs(3);
        let released = loop {
            match Server::start(engine.clone(), Duration::ZERO) {
                Ok(server) => return server.keep(),
                Err(e) if e.kind() != io::ErrorKind::WouldBlock => return Err(e),
                Err(_) => {}
            }
            match request(&Request::Release) {
                Ok(Ok(theirs)) => break theirs.session,
                Ok(Err(e)) => return Err(io::Error::new(io::ErrorKind::AlreadyExists, e)),
                // It may be exiting right now; look again shortly.
                Err(_) if Instant::now() < deadline => thread::sleep(Duration::from_millis(20)),
                Err(e) => {
                    return Err(io::Error::new(
                        io::ErrorKind::AlreadyExists,
                        format!("another Marathon process serves and does not answer: {e}"),
                    ));
                }
            }
        };
        // The helper exits once released. Its session moves here only if
        // we take over promptly; if a new helper slipped in first, its
        // newer sessions win and we serve once it is done.
        match Server::start(engine.clone(), Duration::from_secs(3)) {
            Ok(server) => {
                if let Some(session) = released {
                    engine.start(session)?;
                }
                server.keep()
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                let engine = engine.clone();
                thread::Builder::new()
                    .name("marathon-takeover".into())
                    .stack_size(STACK)
                    .spawn(move || {
                        if let Err(e) = Server::start(engine, Duration::MAX).and_then(Server::keep)
                        {
                            eprintln!("Marathon: can't take over from the CLI helper: {e}");
                        }
                    })?;
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    /// Keeps serving until the process exits (the lock must stay open).
    pub fn keep(self) -> io::Result<()> {
        std::mem::forget(self);
        Ok(())
    }

    /// Runs `f` while no request is being answered, so a reply already
    /// being written is never cut off by `f` exiting the process.
    pub fn quiesce<R>(&self, f: impl FnOnce() -> R) -> R {
        let _guard = self.busy.write().unwrap_or_else(|e| e.into_inner());
        f()
    }
}

/// Locks `lock`, polling for up to `wait`, or blocking for `Duration::MAX`.
fn acquire(lock: &File, wait: Duration) -> io::Result<()> {
    if wait == Duration::MAX {
        return lock.lock();
    }
    let deadline = Instant::now() + wait;
    loop {
        match lock.try_lock() {
            Ok(()) => return Ok(()),
            Err(TryLockError::Error(e)) => return Err(e),
            Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
                thread::sleep(Duration::from_millis(10))
            }
            Err(TryLockError::WouldBlock) => return Err(io::ErrorKind::WouldBlock.into()),
        }
    }
}

fn answer(engine: &Engine, stream: UnixStream) -> io::Result<()> {
    set_timeouts(&stream)?;
    let reply: Reply = from_line(&read_line(&stream)?).and_then(|req| engine.handle(req));
    (&stream).write_all(to_line(&reply).as_bytes())
}