trusty-common 0.70.9

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Linux start / stop / restart for a trusty daemon, driven by a descriptor
//! (#11084, epic #11083 PHASE_1).
//!
//! Why: on Linux, `tctl restart` had no backend — every daemon except tm was
//! routed to launchd and failed, so daemons kept running binaries an upgrade had
//! already replaced. The existing per-daemon stop paths each had a defect: one
//! waited a fixed 3 s on health and never sent SIGKILL, one exited 0 while a
//! survivor remained, one signalled a pid it never identified. This module is
//! the one Linux backend those daemons move onto in PHASE_2, so the stop and
//! identity rules are written, and tested against real processes, once.
//!
//! What: every daemon detail comes from a [`DaemonDescriptor`] the caller
//! builds; nothing here names a daemon.
//!
//! - [`stop`] identifies the listener by the `SO_PEERCRED` peer pid of the
//!   descriptor's socket, pins it with a pidfd, checks its executable name,
//!   sends SIGTERM, waits for the pid to exit, sends SIGKILL after the stop
//!   grace, and then waits for the descriptor's [`StoppedSignal`]. It returns
//!   [`StopOutcome::Stopped`], [`StopOutcome::NotRunning`], or an error —
//!   [`LifecycleError::Survivor`] when the pid outlives SIGKILL.
//!   A socket that does not serve is `NotRunning` only when no process of
//!   the caller's uid is this instance — runs `binary` with every one of the
//!   descriptor's `liveness_args` and its `instance_env` values (#11098);
//!   otherwise it is [`LifecycleError::RunningUnserved`] and nothing is
//!   signalled. A sibling instance of the same binary does not count.
//! - [`start`] spawns `<install dir>/<binary>` detached, in the descriptor's
//!   `working_dir` and with only [`DaemonDescriptor::BASE_ENV`] plus its
//!   `env_passthrough` names from the caller's environment (#11098), and
//!   returns only once the spawned pid serves the socket. A failed start kills
//!   and reaps the child it spawned, so nothing it started is left running.
//! - [`restart`] is [`stop`], then [`start`]; `NotRunning` counts as stopped,
//!   and any stop error returns before a spawn. While the daemon serves, a
//!   restart first scans for another process that is this instance, which
//!   would make the start refuse, and returns
//!   [`LifecycleError::RestartBlocked`] before any signal (#11085).
//! - [`stop_pid`] and [`restart_pid`] act on a daemon the caller identified
//!   by pid, such as one whose socket bind failed (#11085). The pid is pinned
//!   and must be proven this instance — binary, `liveness_args`,
//!   `instance_env` and `instance_path_args` — and the socket unserved or
//!   served by that pid, before any signal.
//!
//! A process whose argv gives an `instance_path_args` flag only values naming
//! another path is a sibling, never this instance (#11085).
//!
//! Waits are condition waits: pid exit is a pidfd becoming readable, and the
//! stopped signal and readiness are polled conditions with a deadline. None of
//! them is a fixed sleep standing in for proof.
//!
//! Precondition: every async function here runs on a tokio runtime with IO and
//! time enabled, as every `uds::` function does.
//!
//! Test: `tests/linux_lifecycle.rs` runs each path against real child
//! processes; the unit tests are in `tests.rs`.
//!
//! [`DaemonDescriptor`]: crate::linux_lifecycle::DaemonDescriptor
//! [`StoppedSignal`]: crate::linux_lifecycle::StoppedSignal
//! [`StopOutcome::Stopped`]: crate::linux_lifecycle::StopOutcome::Stopped
//! [`StopOutcome::NotRunning`]: crate::linux_lifecycle::StopOutcome::NotRunning
//! [`LifecycleError::Survivor`]: crate::linux_lifecycle::LifecycleError::Survivor
//! [`LifecycleError::RunningUnserved`]: crate::linux_lifecycle::LifecycleError::RunningUnserved
//! [`DaemonDescriptor::BASE_ENV`]: crate::linux_lifecycle::DaemonDescriptor::BASE_ENV
//! [`stop`]: crate::linux_lifecycle::stop()
//! [`start`]: crate::linux_lifecycle::start()
//! [`restart`]: crate::linux_lifecycle::restart()
//! [`stop_pid`]: crate::linux_lifecycle::stop_pid()
//! [`restart_pid`]: crate::linux_lifecycle::restart_pid()
//! [`LifecycleError::RestartBlocked`]: crate::linux_lifecycle::LifecycleError::RestartBlocked

mod error;
mod instance;
mod liveness;
pub mod passthrough;
mod pid;
mod process;
mod start;
mod stop;
#[cfg(test)]
mod tests;

use std::ffi::OsString;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;

pub use error::LifecycleError;
pub use liveness::ProcessTable;
pub use pid::{
    restart_pid, restart_pid_with, restart_pid_with_table, stop_pid, stop_pid_with,
    stop_pid_with_table,
};
pub use process::{PinnedProcess, Signal};
pub use start::{
    RestartOutcome, StartOutcome, restart, restart_with, restart_with_table, start,
    start_with_table,
};
pub use stop::{KernelDelivery, SignalDelivery, StopOutcome, stop, stop_with, stop_with_table};

/// How long one connect attempt may take before the answer is "inconclusive".
pub(crate) const PROBE_TIMEOUT: Duration = Duration::from_millis(500);

/// Interval between checks of a polled condition (stopped signal, readiness).
pub(crate) const POLL_INTERVAL: Duration = Duration::from_millis(20);

/// What must hold, after the pid has exited, before `stop` reports `Stopped`.
///
/// Why: a daemon's socket can close before its pid exits, and a lock can be
/// held after it — so "stopped" is a per-daemon fact the caller names, never
/// something this module guesses. `bind_singleton`'s `<socket>.lock` is held
/// only while binding, so it is deliberately not offered as a signal.
/// What: [`StoppedSignal::SocketRefuses`] — the socket file is absent or
/// refuses connections. [`StoppedSignal::LockFree`] — an exclusive `flock` on
/// the named file can be taken (an absent file counts as free).
/// Test: `stop_returns_stopped_promptly_after_a_clean_exit`,
/// `stop_with_lock_signal_is_not_stopped_while_another_process_holds_the_lock`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StoppedSignal {
    /// The pid has exited and the socket refuses connections.
    SocketRefuses,
    /// The pid has exited and this lock file's `flock` is free.
    LockFree(PathBuf),
}

/// Everything the lifecycle needs to know about one daemon.
///
/// Why: the module must not assume any daemon (P-a keeps tm off it; the other
/// daemons differ in socket, lock and args), so every detail is caller data.
/// The caller resolves its data dir and derives the socket path, lock path and
/// spawn args from it; this type carries the resolved values.
/// What: `binary` is both the file name under `install_dir` that [`start`]
/// spawns and the executable name [`stop`] requires of the socket's peer.
/// `stop_grace` bounds the SIGTERM wait, `kill_wait` bounds the SIGKILL wait
/// and the stopped-signal wait, and `ready_timeout` bounds [`start`].
/// `liveness_args` tells the daemon from a stdio bridge of the same binary
/// when the socket does not answer, and `instance_env` and
/// `instance_path_args` tell this instance from a sibling instance of it;
/// `working_dir`, `env_passthrough` and `instance_env` shape the spawned
/// process (#11098, #11085).
/// `#[non_exhaustive]`: build it with [`DaemonDescriptor::new`] or
/// [`DaemonDescriptor::with_install_dir`], then assign the public fields.
/// Test: `descriptor_rejects_a_binary_name_with_a_path_separator`,
/// `descriptor_new_uses_the_canonical_bin_dir`,
/// `descriptor_rejects_bad_spawn_and_liveness_fields`,
/// `descriptor_pins_the_data_dir_override_as_its_default_instance_key`,
/// `descriptor_rejects_bad_instance_path_args`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DaemonDescriptor {
    /// File name of the daemon binary; never a path.
    pub binary: String,
    /// Directory the binary is spawned from.
    pub install_dir: PathBuf,
    /// The daemon's Unix-domain socket.
    pub socket: PathBuf,
    /// Arguments passed to the binary on spawn.
    pub spawn_args: Vec<String>,
    /// Which condition proves the daemon stopped.
    pub stopped_signal: StoppedSignal,
    /// SIGTERM-to-SIGKILL grace.
    pub stop_grace: Duration,
    /// Bound on the post-SIGKILL exit wait and on the stopped-signal wait.
    pub kill_wait: Duration,
    /// Bound on `start`'s readiness wait.
    pub ready_timeout: Duration,
    /// Arguments only the daemon carries (#11098).
    ///
    /// When the socket does not serve, a live process of the caller's uid
    /// whose executable is `binary` and whose argv (after `argv[0]`) holds
    /// every one of these as a whole argument means the daemon still runs:
    /// `stop` and `start` refuse with [`LifecycleError::RunningUnserved`].
    /// Empty (the default) counts every process of `binary`, stdio bridges
    /// included, which fails closed for the scan; [`stop_pid`] and
    /// [`restart_pid`] refuse an empty list (#11085). A consumer sets the
    /// daemon-only arguments, such as `["serve", "--foreground"]`.
    pub liveness_args: Vec<String>,
    /// The spawned daemon's working directory; `/` by default (#11098).
    ///
    /// Never the caller's cwd, which can hold a `.env.local` the daemon would
    /// load (#9161). Must be absolute.
    pub working_dir: PathBuf,
    /// Names copied from the caller's environment, when set, on top of
    /// [`DaemonDescriptor::BASE_ENV`]; nothing else reaches the daemon (#11098).
    pub env_passthrough: Vec<String>,
    /// The environment that makes this daemon instance this one (#11098).
    ///
    /// Each entry is a variable name and the value this instance runs with;
    /// `None` means unset. [`start`] spawns the daemon with exactly these
    /// values, over `BASE_ENV` and `env_passthrough`. When the socket does not
    /// serve, a process that matches `binary` and `liveness_args` is this
    /// instance only when its `/proc/<pid>/environ` holds every value, unset
    /// equal to unset; any other is a sibling (another data dir, a sandbox)
    /// and is ignored. An unreadable `environ` is
    /// [`LifecycleError::InstanceUnreadable`], never a skip.
    ///
    /// The constructors set `TRUSTY_DATA_DIR_OVERRIDE` to the caller's value.
    /// A consumer adds every other variable that selects its data dir or
    /// socket — trusty-search adds `TRUSTY_DATA_DIR` — and puts any argv that
    /// does so, such as `--data-dir <dir>`, in `liveness_args` as well, and
    /// the flag in `instance_path_args`.
    /// Empty counts every argv match as this instance.
    pub instance_env: Vec<(String, Option<OsString>)>,
    /// Argv flags whose value names the instance's directory (#11085).
    ///
    /// Each entry is a flag, such as `--data-dir`, and the absolute path this
    /// instance runs with — for the default instance, the default directory.
    /// A process that matches `binary` and `liveness_args` but gives the flag
    /// (`--data-dir X` or `--data-dir=X`) only values naming another path is a
    /// sibling, whatever its environment, and the scan ignores it. A process
    /// without the flag is unaffected. Values are compared by path components,
    /// then by `canonicalize`; a relative or unresolvable value, or a flag
    /// with no value, counts as this instance for the scan, never as a
    /// sibling, and [`stop_pid`] and [`restart_pid`] refuse such a process
    /// with [`LifecycleError::InstanceUndecided`]. List each
    /// alias of a flag as its own entry. Empty (the default) changes nothing.
    /// This field does not touch `spawn_args`.
    pub instance_path_args: Vec<(String, PathBuf)>,
}

impl DaemonDescriptor {
    /// Default SIGTERM grace.
    pub const DEFAULT_STOP_GRACE: Duration = Duration::from_secs(10);
    /// Default post-SIGKILL wait.
    pub const DEFAULT_KILL_WAIT: Duration = Duration::from_secs(5);
    /// Default readiness bound.
    pub const DEFAULT_READY_TIMEOUT: Duration = Duration::from_secs(30);

    /// The variables every spawned daemon gets from the caller, when set.
    ///
    /// Why: #11098 — the daemon must not inherit the caller's environment
    /// wholesale (tokens, API keys, a parent-death stamp), but it needs its
    /// home, search path, locale and XDG dirs to find its data.
    /// `TRUSTY_DATA_DIR_OVERRIDE` and `TRUSTY_SANDBOX` are here because
    /// dropping them would move a sandboxed caller's daemon onto the real data
    /// dir and the real `.env.local` tiers. No other `TRUSTY_*` name is: some
    /// carry credentials. A daemon-specific variable goes in `env_passthrough`.
    /// Test: `daemon_env_carries_the_base_and_the_allowlist_only`.
    pub const BASE_ENV: &'static [&'static str] = &[
        "HOME",
        "USER",
        "LOGNAME",
        "PATH",
        "LANG",
        "LC_ALL",
        "LC_CTYPE",
        "LC_MESSAGES",
        "TZ",
        "TMPDIR",
        "XDG_RUNTIME_DIR",
        "XDG_DATA_HOME",
        "XDG_CONFIG_HOME",
        "XDG_CACHE_HOME",
        "XDG_STATE_HOME",
        crate::data_dir::DATA_DIR_OVERRIDE_ENV,
        // The `.env.local` loader's opt-out (`credentials::dotenv::SANDBOX_ENV_VAR`).
        "TRUSTY_SANDBOX",
    ];

    /// A descriptor whose install dir is [`crate::bin_resolve::canonical_bin_dir`].
    ///
    /// Why: the install dir is where `cargo install` and `tctl upgrade` put the
    /// binary; spawning from it, never `$PATH` or `current_exe()`, is what makes
    /// a restart run the new binary.
    /// What: fails with [`LifecycleError::NoInstallDir`] when neither
    /// `CARGO_HOME` nor a home directory resolves, and with
    /// [`LifecycleError::InvalidDescriptor`] for a bad binary name.
    /// Test: `descriptor_new_uses_the_canonical_bin_dir`.
    pub fn new(
        binary: impl Into<String>,
        socket: impl Into<PathBuf>,
        stopped_signal: StoppedSignal,
    ) -> Result<Self, LifecycleError> {
        let install_dir =
            crate::bin_resolve::canonical_bin_dir().ok_or(LifecycleError::NoInstallDir)?;
        Self::with_install_dir(binary, install_dir, socket, stopped_signal)
    }

    /// A descriptor with an explicit install dir.
    ///
    /// Test: `descriptor_rejects_a_binary_name_with_a_path_separator`.
    pub fn with_install_dir(
        binary: impl Into<String>,
        install_dir: impl Into<PathBuf>,
        socket: impl Into<PathBuf>,
        stopped_signal: StoppedSignal,
    ) -> Result<Self, LifecycleError> {
        let desc = Self {
            binary: binary.into(),
            install_dir: install_dir.into(),
            socket: socket.into(),
            spawn_args: Vec::new(),
            stopped_signal,
            stop_grace: Self::DEFAULT_STOP_GRACE,
            kill_wait: Self::DEFAULT_KILL_WAIT,
            ready_timeout: Self::DEFAULT_READY_TIMEOUT,
            liveness_args: Vec::new(),
            working_dir: PathBuf::from("/"),
            env_passthrough: Vec::new(),
            // #11098: the override is what tells a sandbox from production.
            instance_env: vec![(
                crate::data_dir::DATA_DIR_OVERRIDE_ENV.to_string(),
                std::env::var_os(crate::data_dir::DATA_DIR_OVERRIDE_ENV),
            )],
            instance_path_args: Vec::new(),
        };
        desc.validate()?;
        Ok(desc)
    }

    /// The absolute program [`start`] spawns: `<install_dir>/<binary>`.
    pub fn program(&self) -> PathBuf {
        self.install_dir.join(&self.binary)
    }

    /// Re-checked at every entry point, because the fields are public.
    ///
    /// Test: `descriptor_rejects_a_binary_name_with_a_path_separator`.
    pub(crate) fn validate(&self) -> Result<(), LifecycleError> {
        let bad = |reason: &str| {
            Err(LifecycleError::InvalidDescriptor {
                reason: reason.to_string(),
            })
        };
        if self.binary.is_empty() || self.binary == "." || self.binary == ".." {
            return bad("binary name is empty or a dot entry");
        }
        if self.binary.contains('/') {
            return bad("binary must be a file name, not a path");
        }
        if !self.install_dir.is_absolute() {
            return bad("install_dir must be absolute");
        }
        if self.socket.as_os_str().is_empty() {
            return bad("socket path is empty");
        }
        // #11098: a relative cwd would resolve against the caller's cwd.
        if !self.working_dir.is_absolute() {
            return bad("working_dir must be absolute");
        }
        // No argv element holds a NUL, so such an arg would never match and a
        // running daemon would read as not running.
        if self.liveness_args.iter().any(|a| a.contains('\0')) {
            return bad("liveness_args must not contain NUL");
        }
        let bad_name = |n: &str| n.is_empty() || n.contains('=') || n.contains('\0');
        if self.env_passthrough.iter().any(|n| bad_name(n)) {
            return bad("env_passthrough names must be non-empty, without '=' or NUL");
        }
        // #11098: a NUL value cannot be spawned, and two values for one name
        // can never both match, so a running instance would read as stopped.
        let mut names = std::collections::HashSet::new();
        for (name, value) in &self.instance_env {
            if bad_name(name) || !names.insert(name.as_str()) {
                return bad("instance_env names must be unique, non-empty, without '=' or NUL");
            }
            if value
                .as_ref()
                .is_some_and(|v| v.as_encoded_bytes().contains(&0))
            {
                return bad("instance_env values must not contain NUL");
            }
        }
        // #11085: a relative path never rules a sibling out, so it could never
        // tell one apart; `=` would make `<flag>=<value>` ambiguous.
        let mut flags = std::collections::HashSet::new();
        for (flag, path) in &self.instance_path_args {
            if bad_name(flag) || !flags.insert(flag.as_str()) {
                return bad(
                    "instance_path_args flags must be unique, non-empty, without '=' or NUL",
                );
            }
            if !path.is_absolute() || path.as_os_str().as_encoded_bytes().contains(&0) {
                return bad("instance_path_args paths must be absolute, without NUL");
            }
        }
        Ok(())
    }
}

/// Whether the stop signal's lock file can be locked right now.
///
/// What: opens the file read-only (absent is free) and tries an exclusive,
/// non-blocking `flock`, releasing it at once.
/// Test: `stop_with_lock_signal_returns_stopped_once_the_lock_is_released`.
pub(crate) fn lock_is_free(lock: &Path) -> Result<bool, LifecycleError> {
    let file = match std::fs::File::open(lock) {
        Ok(f) => f,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(true),
        Err(source) => {
            return Err(LifecycleError::Io {
                context: format!("open lock {}", lock.display()),
                source,
            });
        }
    };
    match file.try_lock() {
        Ok(()) => Ok(true),
        Err(std::fs::TryLockError::WouldBlock) => Ok(false),
        Err(std::fs::TryLockError::Error(source)) => Err(LifecycleError::Io {
            context: format!("flock {}", lock.display()),
            source,
        }),
    }
}