Skip to main content

trusty_code/log_drain/
scheduler.rs

1//! The `tcode serve` daemon's log-drain scheduler (#6537).
2//!
3//! Why: `trusty_common::log_drain::run_tick` is one pass with no memory of
4//! what it last did. This is the interval loop that makes it a running
5//! service — spawned once, fire-and-forget, from `serve::build_router`
6//! (mirrors how `trusty-agents`' `api::server::routes::serve_with_config`
7//! spawns its own background tasks, and how trusty-mpm's
8//! `daemon::log_drain::log_drain_loop` runs beside `orphan_gc_loop`). A tcode
9//! daemon exits with its whole process, so an ungraceful loop shutdown loses
10//! nothing the next pass would not reattempt.
11//! What: [`spawn`] starts the loop as a background task; each iteration
12//! re-reads `log_drain.yaml` (an operator's edit takes effect without a
13//! restart) and calls `trusty_common::log_drain::run_tick` — the pass itself
14//! (resolve, connect, `run_once`, log the verdict) now lives there, shared
15//! with trusty-agents' identical scheduler (#6537 code-review fix round).
16//! `state_dir` — where the local idempotency-manifest cache lives — is a
17//! parameter of [`spawn`] rather than resolved with
18//! `crate::paths::private_state::private_state_dir()` inside this file: the
19//! production call site (`serve::build_router`) supplies the real
20//! `~/.trusty-code/log-drain`, and every test drives `tick` with a tempdir
21//! instead, so no test ever touches a real home directory.
22//! Test: `tests`.
23
24use std::path::{Path, PathBuf};
25use std::time::Duration;
26
27use tracing::{info, warn};
28use trusty_common::log_drain::{DrainOutcome, run_tick};
29
30use super::config::{LogDrainConfig, load_config};
31use super::resolve::DEFAULT_INTERVAL_SECS;
32
33const CRATE_NAME: &str = "trusty-code";
34const DEFAULT_INCLUDE: &str = "tcode.log*";
35
36/// Start the interval loop as a background task.
37///
38/// `project_root` is `binding.root().map(Path::to_path_buf)` — `None` for a
39/// projectless daemon. `log_root` is `crate::logging::file_log_dir()`.
40/// `state_dir` is where the local idempotency manifest cache lives — the
41/// production call site passes `~/.trusty-code/log-drain`.
42pub fn spawn(project_root: Option<PathBuf>, log_root: PathBuf, state_dir: PathBuf) {
43    tokio::task::spawn(run_loop(project_root, log_root, state_dir));
44}
45
46/// Tick forever: reload config, one pass, then sleep for whatever interval
47/// that pass named (or [`DEFAULT_INTERVAL_SECS`] on a config-load error, so a
48/// startup typo does not spin-loop).
49async fn run_loop(project_root: Option<PathBuf>, log_root: PathBuf, state_dir: PathBuf) {
50    let default_interval = Duration::from_secs(DEFAULT_INTERVAL_SECS);
51    loop {
52        let interval = match load_config() {
53            Ok(cfg) => {
54                let (outcome, interval) =
55                    tick(&cfg, project_root.as_deref(), &log_root, &state_dir).await;
56                match outcome {
57                    DrainOutcome::Success => info!("log_drain: pass complete"),
58                    DrainOutcome::SkippedDisabled => {}
59                    DrainOutcome::Failed => warn!("log_drain: pass failed; retrying next tick"),
60                }
61                interval
62            }
63            Err(e) => {
64                warn!("log_drain: {e}");
65                default_interval
66            }
67        };
68        tokio::time::sleep(interval).await;
69    }
70}
71
72/// One full pass over an already-loaded config — a thin wrapper over
73/// `trusty_common::log_drain::run_tick` naming this daemon's own crate and
74/// include glob. Returns the outcome and the interval the NEXT sleep should
75/// use.
76async fn tick(
77    cfg: &LogDrainConfig,
78    project_root: Option<&Path>,
79    log_root: &Path,
80    state_dir: &Path,
81) -> (DrainOutcome, Duration) {
82    run_tick(
83        cfg,
84        log_root,
85        project_root,
86        state_dir,
87        CRATE_NAME,
88        DEFAULT_INCLUDE,
89    )
90    .await
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    /// Disabled config: `tick` never touches the destination or the network.
98    #[tokio::test]
99    async fn opt_out_skips_the_pass() {
100        let log_root = tempfile::tempdir().expect("tempdir");
101        std::fs::write(log_root.path().join("tcode.log"), "hello\n").expect("seed log");
102        let state_dir = tempfile::tempdir().expect("tempdir");
103
104        let (outcome, interval) = tick(
105            &LogDrainConfig::default(),
106            None,
107            log_root.path(),
108            state_dir.path(),
109        )
110        .await;
111        assert_eq!(outcome, DrainOutcome::SkippedDisabled);
112        assert_eq!(interval, Duration::from_secs(DEFAULT_INTERVAL_SECS));
113    }
114
115    /// An enabled plan against a `file://` destination uploads the seeded log
116    /// file on the first tick — into the INJECTED `state_dir`, never a real
117    /// `~/.trusty-code/log-drain` (#6537 code-review fix round) — and a
118    /// second tick — nothing changed — is idempotent (the manifest dedupes):
119    /// `run_once` was genuinely invoked with the CONFIGURED destination both
120    /// times, not skipped.
121    #[tokio::test]
122    async fn an_enabled_tick_uploads_into_the_injected_state_dir_and_is_idempotent() {
123        let log_root = tempfile::tempdir().expect("tempdir");
124        std::fs::write(log_root.path().join("tcode.log"), "hello\n").expect("seed log");
125        let dest_dir = tempfile::tempdir().expect("tempdir");
126        let state_dir = tempfile::tempdir().expect("tempdir");
127
128        let cfg = LogDrainConfig {
129            enabled: Some(true),
130            destination: Some(format!("file://{}", dest_dir.path().display())),
131            owner: Some("acme".to_string()),
132            project: Some("widgets".to_string()),
133            ..LogDrainConfig::default()
134        };
135
136        let (first, _) = tick(&cfg, None, log_root.path(), state_dir.path()).await;
137        assert_eq!(first, DrainOutcome::Success);
138        // The object landed under the configured destination's own tree,
139        // proving `tick` connected to what the config named rather than some
140        // default.
141        let uploaded = std::fs::read_dir(dest_dir.path().join("acme").join("widgets"))
142            .expect("read the target's key prefix")
143            .count();
144        assert!(
145            uploaded > 0,
146            "run_once must have written under acme/widgets"
147        );
148        assert!(
149            std::fs::read_dir(state_dir.path())
150                .expect("read state_dir")
151                .count()
152                > 0,
153            "the manifest cache must land under the injected state_dir, not a real home directory"
154        );
155
156        let (second, _) = tick(&cfg, None, log_root.path(), state_dir.path()).await;
157        assert_eq!(
158            second,
159            DrainOutcome::Success,
160            "an unchanged file must still report success, not re-error, on the next tick"
161        );
162    }
163
164    /// `tick` reports `Failed`, never a panic, when the destination cannot be
165    /// reached — a `file://` path nested under a regular FILE cannot be
166    /// created.
167    #[tokio::test]
168    async fn an_unreachable_destination_reports_failed() {
169        let log_root = tempfile::tempdir().expect("tempdir");
170        let state_dir = tempfile::tempdir().expect("tempdir");
171        let blocker = tempfile::NamedTempFile::new().expect("tempfile");
172        let cfg = LogDrainConfig {
173            enabled: Some(true),
174            destination: Some(format!(
175                "file://{}",
176                blocker.path().join("nested").display()
177            )),
178            owner: Some("acme".to_string()),
179            project: Some("widgets".to_string()),
180            ..LogDrainConfig::default()
181        };
182
183        let (outcome, _) = tick(&cfg, None, log_root.path(), state_dir.path()).await;
184        assert_eq!(outcome, DrainOutcome::Failed);
185    }
186
187    /// A malformed config (bad destination) reports `Failed` rather than
188    /// panicking the loop.
189    #[tokio::test]
190    async fn a_config_error_reports_failed() {
191        let log_root = tempfile::tempdir().expect("tempdir");
192        let state_dir = tempfile::tempdir().expect("tempdir");
193        let cfg = LogDrainConfig {
194            destination: Some("ftp://nope".to_string()),
195            ..LogDrainConfig::default()
196        };
197        let (outcome, interval) = tick(&cfg, None, log_root.path(), state_dir.path()).await;
198        assert_eq!(outcome, DrainOutcome::Failed);
199        assert_eq!(interval, Duration::from_secs(DEFAULT_INTERVAL_SECS));
200    }
201}