Skip to main content

runnerd_core/
store.rs

1//! The job history: a SQLite database of jobs, their runners, steps, samples and logs, the events clients resume
2//! from, cache sizes, the paused repositories and where the notifier got to. Owns the schema and its migrations, the one writer and the event
3//! broadcast. Writes are messages to a writer thread, so the engine never waits on the disk; reads and pruning run
4//! on Tokio's blocking pool, pruning on its own connection, a batch at a time. It decides nothing about scheduling
5//! and stores no secret: no token, no JIT config, no runner `_diag` log.
6
7use std::collections::BTreeMap;
8use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
9use std::path::{Path, PathBuf};
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, Mutex, TryLockError};
12use std::time::Duration;
13
14use rusqlite::{Connection, OpenFlags};
15use tokio::sync::{OwnedSemaphorePermit, Semaphore, broadcast, mpsc, oneshot};
16use tracing::warn;
17
18use crate::api::{self, Event, EventEnvelope};
19use crate::config::History;
20use crate::github::{JobDetails, QueuedJob};
21use crate::observe::metrics::Events;
22use crate::scheduler::warm;
23use crate::sizing;
24use crate::sync::lock;
25
26mod prune;
27mod read;
28mod write;
29
30/// The schema's migrations, in order; the database's `user_version` is how many ran.
31const MIGRATIONS: &[&str] = &[
32    include_str!("store/migrations/0001_history.sql"),
33    include_str!("store/migrations/0002_runner_caps.sql"),
34    include_str!("store/migrations/0003_paused.sql"),
35    include_str!("store/migrations/0004_prune.sql"),
36    include_str!("store/migrations/0005_announced_profiles.sql"),
37    include_str!("store/migrations/0006_records.sql"),
38    include_str!("store/migrations/0007_admission.sql"),
39    include_str!("store/migrations/0008_memory_without_page_cache.sql"),
40    include_str!("store/migrations/0009_auto_sizing.sql"),
41    include_str!("store/migrations/0010_auto_sizing_cpus.sql"),
42    include_str!("store/migrations/0011_notify.sql"),
43    include_str!("store/migrations/0012_build_cache.sql"),
44];
45
46/// Bytes of log lines sent and not yet stored, at most: a job's capture waits beyond it, so a noisy job or a slow
47/// disk holds back that job's log, not the daemon's memory.
48pub(crate) const LOG_BACKLOG: u64 = 8 << 20;
49
50/// Host samples the writer holds before it stores them in one transaction: a minute's worth. One transaction per
51/// sample wrote about 300 MB a day to an idle daemon's WAL. A crash loses the samples held.
52const HOST_SAMPLE_BATCH: usize = 30;
53
54/// How many events a slow client may fall behind before its stream ends; it reconnects with `Last-Event-ID`.
55const EVENT_BUFFER: usize = 4096;
56
57/// Why the database cannot be used.
58#[derive(Debug, thiserror::Error)]
59pub enum StoreError {
60    /// SQLite failed.
61    #[error("{0}")]
62    Sqlite(#[from] rusqlite::Error),
63    /// A newer runnerd wrote the database.
64    #[error(
65        "the job history database is version {found}, newer than the {supported} this runnerd reads; \
66         run a newer runnerd or move the database aside"
67    )]
68    Newer {
69        /// The database's version.
70        found: u32,
71        /// The newest version this build knows.
72        supported: u32,
73    },
74    /// The directory or file cannot be created.
75    #[error("{0}")]
76    Io(#[from] std::io::Error),
77    /// A blocking read did not finish.
78    #[error("a database read stopped: {0}")]
79    Join(#[from] tokio::task::JoinError),
80    /// The database's `-wal` file holds changes not yet in it, and this user cannot open the database the way that
81    /// reads them.
82    #[error(
83        "{} holds changes not yet in the job history, which this user cannot read; run runnerd doctor as the user \
84         the daemon runs as",
85        .0.display()
86    )]
87    Unread(PathBuf),
88}
89
90/// A runner container as the history records it.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct RunnerRecord {
93    /// The runner's name, also its container's.
94    pub name: String,
95    /// `owner/name`.
96    pub repository: String,
97    /// The profile it runs in.
98    pub profile: String,
99    /// 1-based.
100    pub slot: usize,
101    /// The Docker container ID.
102    pub container: String,
103    /// When the container started, in milliseconds since the epoch.
104    pub started_at: u64,
105    /// The container's memory cap in bytes.
106    pub memory_cap: Option<u64>,
107    /// The container's CPU limit in millicores.
108    pub cpu_cap: Option<u64>,
109    /// How it was admitted; `None` for one a restart adopted.
110    pub admission: Option<api::Admission>,
111}
112
113/// One sample of one runner's container.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct SampleRecord {
116    /// The runner.
117    pub runner: String,
118    /// When, in milliseconds since the epoch.
119    pub at: u64,
120    /// Millicores over the interval before it.
121    pub cpu: u64,
122    /// CPU time so far, in microseconds.
123    pub cpu_usage: u64,
124    /// Bytes without page cache (`observe::metrics::Usage::memory`).
125    pub memory: u64,
126    /// Bytes received since the container started.
127    pub network_received: u64,
128    /// Bytes sent since the container started.
129    pub network_sent: u64,
130    /// The container's `memory.events` so far.
131    pub events: Events,
132}
133
134/// The last measurement of the cache volumes.
135#[derive(Debug, Clone, Default, PartialEq, Eq)]
136pub struct Measured {
137    /// When it was taken (seconds); none before the first measurement.
138    pub at: Option<u64>,
139    /// Each volume's size in bytes, by name.
140    pub bytes: BTreeMap<String, u64>,
141}
142
143/// The profiles and repositories as the stored events last announced them: what clients resuming after those
144/// events have.
145#[derive(Debug, Clone, Default, PartialEq, Eq)]
146pub struct Announced {
147    /// The last `profile.changed` of each profile not removed since, by name.
148    pub profiles: Vec<api::ProfileStatus>,
149    /// The last `repository.changed` of each repository not removed since, by name.
150    pub repositories: Vec<api::RepositoryStatus>,
151}
152
153/// A job the history has not closed, as the engine needs it after a restart.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct OpenJob {
156    /// GitHub's job ID.
157    pub id: u64,
158    /// `owner/name`.
159    pub repository: String,
160    /// `Queued` or `Running`.
161    pub state: api::JobState,
162    /// Its runner, once one took it.
163    pub runner: Option<String>,
164    /// When its runner was removed, in milliseconds since the epoch.
165    pub runner_removed_at: Option<u64>,
166    /// The workflow run it belongs to.
167    pub run_id: u64,
168    /// 1 for the run's first attempt.
169    pub run_attempt: u32,
170    /// The workflow's name, when known.
171    pub workflow: Option<String>,
172    /// When GitHub queued it, in milliseconds since the epoch.
173    pub queued_at: u64,
174}
175
176/// Where a job's log capture continues: the runner's page file and the byte offset in it.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub struct LogPosition {
179    /// The page number, from 1.
180    pub page: u64,
181    /// Bytes of that page already stored as lines.
182    pub offset: u64,
183}
184
185/// How far the mirror's log was counted: the time of the last response counted, in nanoseconds since the epoch as
186/// Docker logs it, and how many responses logged at exactly that time were counted, so the next read counts the
187/// ones it was too early to see.
188#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
189pub struct MirrorPosition {
190    /// Nanoseconds since the epoch.
191    pub at: u64,
192    /// Responses logged at `at` already counted.
193    pub seen: u64,
194}
195
196/// What the writer thread is asked to do, in order.
197#[derive(Debug)]
198enum Write {
199    Queued {
200        repository: String,
201        job: QueuedJob,
202    },
203    RunnerStarted(RunnerRecord),
204    RunnerAdmission {
205        runner: String,
206        admission: api::Admission,
207    },
208    RunnerOomKilled(String),
209    BuildCache {
210        runner: String,
211        counts: api::BuildCacheCounts,
212    },
213    RunnerRemoved {
214        runner: String,
215        at: u64,
216    },
217    RunnersGone {
218        running: Vec<String>,
219        at: u64,
220    },
221    Claimed {
222        job: u64,
223        run_id: u64,
224        runner: String,
225        at: u64,
226    },
227    Details {
228        details: JobDetails,
229    },
230    Elsewhere {
231        details: JobDetails,
232    },
233    Lost {
234        job: u64,
235        at: u64,
236    },
237    Log {
238        job: u64,
239        lines: Vec<String>,
240        /// Where the capture resumes once these lines are stored; `None` for all but the last part of a batch.
241        position: Option<LogPosition>,
242        max_bytes: u64,
243        /// The lines' share of `LOG_BACKLOG`, given back once they are stored.
244        _backlog: OwnedSemaphorePermit,
245    },
246    Samples(Vec<SampleRecord>),
247    HostSample(api::HostSample),
248    MirrorBytes {
249        bytes: Vec<(String, u64)>,
250        until: MirrorPosition,
251        /// Whether the count committed.
252        done: oneshot::Sender<bool>,
253    },
254    CacheSizes {
255        at: u64,
256        sizes: BTreeMap<String, u64>,
257    },
258    /// Boxed: an event with a job's summary is many times the other writes' size.
259    Event(Box<Event>),
260    RecordMade(api::Record),
261    RecordSkipped {
262        job: u64,
263        why: String,
264    },
265    RecordRemoved {
266        job: u64,
267        at: u64,
268        by: api::RecordRemoval,
269    },
270    Paused {
271        repositories: Vec<String>,
272        /// Whether it committed.
273        done: oneshot::Sender<bool>,
274    },
275    SizingIntent {
276        change: api::SizingChange,
277        /// Its row, once it committed.
278        done: oneshot::Sender<Option<i64>>,
279    },
280    SizingResolved {
281        id: i64,
282        resolution: Resolution,
283        /// Whether it committed.
284        done: oneshot::Sender<bool>,
285    },
286    Notify {
287        change: NotifyChange,
288        /// Whether it committed.
289        done: oneshot::Sender<bool>,
290    },
291    Flush(oneshot::Sender<()>),
292}
293
294/// What the notifier records.
295#[derive(Debug)]
296enum NotifyChange {
297    /// Sets a target's keys and removes others.
298    Record {
299        target: String,
300        set: Vec<(String, u64)>,
301        remove: Vec<String>,
302    },
303    /// Forgets every target but these.
304    Keep(Vec<String>),
305}
306
307/// What became of a pending auto sizing change.
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub enum Resolution {
310    /// The config file has it: announced as `sizing.changed`.
311    Done,
312    /// The file was not written.
313    Failed,
314    /// Left pending, and the config no longer says whether it was written: it keeps its interval and stays listed,
315    /// with what it replaced.
316    Uncertain,
317}
318
319/// Auto sizing as the history keeps it: when each profile last changed, and changes not yet known to be written.
320#[derive(Debug, Clone, Default, PartialEq, Eq)]
321pub struct AutoSizing {
322    /// The latest pending or done change of each profile, in seconds, however old.
323    pub last: BTreeMap<String, u64>,
324    /// Changes recorded before their file was written and not resolved since, by row.
325    pub pending: Vec<(i64, api::SizingChange)>,
326}
327
328/// The job history. Cloning shares it.
329#[derive(Debug, Clone)]
330pub struct Store {
331    writes: mpsc::UnboundedSender<Write>,
332    reader: Arc<Mutex<Connection>>,
333    /// Taken with `try_lock`, so one prune runs at a time; one that panicked midway left rows the next one deletes.
334    pruner: Arc<Mutex<Connection>>,
335    /// Set by `close`: a running prune stops after its batch, and none starts.
336    closed: Arc<AtomicBool>,
337    /// Host samples sent and not yet stored, oldest first; reads include them. The writer removes them once stored.
338    // Locked with `sync::lock`: every critical section is a push, a copy or a drain.
339    held: Arc<Mutex<Vec<api::HostSample>>>,
340    /// The last host sample sent, for admission to read without a query.
341    latest_host: Arc<Mutex<Option<api::HostSample>>>,
342    /// Each running runner's last sample, for admission to read without a query.
343    latest_samples: Arc<Mutex<BTreeMap<String, SampleRecord>>>,
344    events: broadcast::Sender<Arc<EventEnvelope>>,
345    backlog: Arc<Semaphore>,
346}
347
348impl Store {
349    /// Opens the database at `path`, creating it and its directory (mode 0700) if missing, and migrates it to the
350    /// latest version. Refuses a database a newer runnerd wrote.
351    pub fn open(path: &Path) -> Result<Store, StoreError> {
352        if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
353            std::fs::DirBuilder::new()
354                .recursive(true)
355                .mode(0o700)
356                .create(dir)?;
357        }
358        // Owner-only, as SQLite then makes its `-wal` and `-shm` files: logs may say more than the owner wants shared.
359        std::fs::OpenOptions::new()
360            .create(true)
361            .append(true)
362            .mode(0o600)
363            .open(path)?;
364        let mut db = Connection::open(path)?;
365        configure(&db)?;
366        migrate(&mut db)?;
367        let reader = Connection::open_with_flags(
368            path,
369            OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
370        )?;
371        configure(&reader)?;
372        let pruner = Connection::open(path)?;
373        configure(&pruner)?;
374        let (events, _) = broadcast::channel(EVENT_BUFFER);
375        let (writes, receiver) = mpsc::unbounded_channel();
376        let thread_events = events.clone();
377        let held = Arc::new(Mutex::new(Vec::new()));
378        let thread_held = held.clone();
379        std::thread::Builder::new()
380            .name("runnerd-store".to_owned())
381            .spawn(move || write::run(db, receiver, &thread_events, &thread_held))?;
382        Ok(Store {
383            writes,
384            reader: Arc::new(Mutex::new(reader)),
385            pruner: Arc::new(Mutex::new(pruner)),
386            closed: Arc::new(AtomicBool::new(false)),
387            held,
388            latest_host: Arc::new(Mutex::new(None)),
389            latest_samples: Arc::new(Mutex::new(BTreeMap::new())),
390            events,
391            backlog: Arc::new(Semaphore::new(
392                usize::try_from(LOG_BACKLOG).unwrap_or(usize::MAX),
393            )),
394        })
395    }
396
397    fn send(&self, write: Write) {
398        // Fails only once the writer thread is gone, after a SQLite error it logged.
399        let _ = self.writes.send(write);
400    }
401
402    /// Records a queued job the repository's runners may run; announces it the first time.
403    pub fn queued(&self, repository: &str, job: &QueuedJob) {
404        self.send(Write::Queued {
405            repository: repository.to_owned(),
406            job: job.clone(),
407        });
408    }
409
410    /// Records a runner container that started, or one an earlier daemon started and this one adopted.
411    pub fn runner_started(&self, runner: RunnerRecord) {
412        self.send(Write::RunnerStarted(runner));
413    }
414
415    /// Records that a runner's container and registration were removed at `at` (ms).
416    pub fn runner_removed(&self, runner: &str, at: u64) {
417        lock(&self.latest_samples).remove(runner);
418        self.send(Write::RunnerRemoved {
419            runner: runner.to_owned(),
420            at,
421        });
422    }
423
424    /// Records every runner the history holds open, except the `running` ones, removed at `at` (ms): what recovery
425    /// found gone, so it stops counting as holding a slot.
426    pub fn runners_gone(&self, running: Vec<String>, at: u64) {
427        lock(&self.latest_samples).retain(|runner, _| running.contains(runner));
428        self.send(Write::RunnersGone { running, at });
429    }
430
431    /// Records that a runner took a job at `at` (ms).
432    pub fn claimed(&self, job: u64, run_id: u64, runner: &str, at: u64) {
433        self.send(Write::Claimed {
434            job,
435            run_id,
436            runner: runner.to_owned(),
437            at,
438        });
439    }
440
441    /// Records a running job's progress and steps as GitHub reports them; announces changed steps.
442    pub fn details(&self, details: JobDetails) {
443        self.send(Write::Details { details });
444    }
445
446    /// Closes a queued job that left the queue without a runner of this daemon.
447    pub fn elsewhere(&self, details: JobDetails) {
448        self.send(Write::Elsewhere { details });
449    }
450
451    /// Closes a job whose container is gone and that GitHub did not report completed in time.
452    pub fn lost(&self, job: u64, at: u64) {
453        self.send(Write::Lost { job, at });
454    }
455
456    /// Appends log lines to a job, up to `max_bytes` per job, and records where the capture continues. Waits while
457    /// `LOG_BACKLOG` bytes of lines are waiting to be stored; a larger batch goes in parts, each waiting its turn.
458    pub async fn log(&self, job: u64, lines: Vec<String>, position: LogPosition, max_bytes: u64) {
459        let size = |line: &String| line.len() as u64 + 1;
460        let mut lines = lines.into_iter().map(|mut line| {
461            // No line takes the whole backlog; the capture already cuts lines far shorter.
462            if size(&line) > LOG_BACKLOG {
463                let mut end = usize::try_from(LOG_BACKLOG / 2).unwrap_or(usize::MAX);
464                while !line.is_char_boundary(end) {
465                    end -= 1;
466                }
467                line.truncate(end);
468            }
469            line
470        });
471        let mut next = lines.next();
472        loop {
473            let (mut part, mut bytes) = (Vec::new(), 0);
474            while let Some(line) = next.take_if(|line| bytes + size(line) <= LOG_BACKLOG) {
475                bytes += size(&line);
476                part.push(line);
477                next = lines.next();
478            }
479            let last = next.is_none();
480            let share = u32::try_from(bytes.max(1)).unwrap_or(u32::MAX);
481            // The semaphore is never closed.
482            let Ok(backlog) = self.backlog.clone().acquire_many_owned(share).await else {
483                return;
484            };
485            self.send(Write::Log {
486                job,
487                lines: part,
488                position: last.then_some(position),
489                max_bytes,
490                _backlog: backlog,
491            });
492            if last {
493                return;
494            }
495        }
496    }
497
498    /// Records samples of runner containers.
499    pub fn samples(&self, samples: Vec<SampleRecord>) {
500        let mut latest = lock(&self.latest_samples);
501        for sample in &samples {
502            latest.insert(sample.runner.clone(), sample.clone());
503        }
504        drop(latest);
505        self.send(Write::Samples(samples));
506    }
507
508    /// Records a sample of the slice and sends it to every subscriber at once; it is stored with the next ones, a
509    /// minute's worth in one transaction, or at `flush`.
510    pub fn host_sample(&self, sample: api::HostSample) {
511        *lock(&self.latest_host) = Some(sample.clone());
512        lock(&self.held).push(sample.clone());
513        self.send(Write::HostSample(sample));
514    }
515
516    /// A runner's last sample, stored or not; `None` before its first sample or once it is removed.
517    pub fn latest_sample(&self, runner: &str) -> Option<SampleRecord> {
518        lock(&self.latest_samples).get(runner).cloned()
519    }
520
521    /// Records what a runner reserves now, when measured admission changed it after the start.
522    pub fn runner_admission(&self, runner: &str, admission: api::Admission) {
523        self.send(Write::RunnerAdmission {
524            runner: runner.to_owned(),
525            admission,
526        });
527    }
528
529    /// Records that Docker saw the kernel kill a process in a runner's container for memory, which its samples may
530    /// have missed: one in the last interval before the container stopped.
531    pub fn runner_oom_killed(&self, runner: &str) {
532        self.send(Write::RunnerOomKilled(runner.to_owned()));
533    }
534
535    /// Adds what the shared build cache served a runner and took from it, and records whether its job could write.
536    pub fn build_cache(&self, runner: &str, counts: api::BuildCacheCounts) {
537        self.send(Write::BuildCache {
538            runner: runner.to_owned(),
539            counts,
540        });
541    }
542
543    /// The last host sample sent, stored or not; `None` before the first.
544    pub fn latest_host_sample(&self) -> Option<api::HostSample> {
545        lock(&self.latest_host).clone()
546    }
547
548    /// Adds bytes the mirror served to runners, counted from its log up to `until`, and says whether that was
549    /// stored: if not, the caller counts the same lines again.
550    pub async fn mirror_bytes(&self, bytes: Vec<(String, u64)>, until: MirrorPosition) -> bool {
551        let (done, committed) = oneshot::channel();
552        self.send(Write::MirrorBytes { bytes, until, done });
553        committed.await.unwrap_or(false)
554    }
555
556    /// Records volume sizes in bytes, by name, measured at `at` (ms).
557    pub fn cache_sizes(&self, at: u64, sizes: BTreeMap<String, u64>) {
558        self.send(Write::CacheSizes { at, sizes });
559    }
560
561    /// Stores a durable event, or sends a live one, to every subscriber.
562    pub fn event(&self, event: Event) {
563        self.send(Write::Event(Box::new(event)));
564    }
565
566    /// Records that a failed job's runner was kept as `record`, and announces it.
567    pub fn record_made(&self, record: api::Record) {
568        self.send(Write::RecordMade(record));
569    }
570
571    /// Records why a failed job's runner was not kept.
572    pub fn record_skipped(&self, job: u64, why: String) {
573        self.send(Write::RecordSkipped { job, why });
574    }
575
576    /// Records that a job's record was removed at `at` (ms), and why, and announces it.
577    pub fn record_removed(&self, job: u64, at: u64, by: api::RecordRemoval) {
578        self.send(Write::RecordRemoved { job, at, by });
579    }
580
581    /// Records the paused repositories, all of them, in place of the ones recorded before. The write is sent at
582    /// once, in order with every other; the future says whether it committed.
583    pub fn paused(&self, repositories: Vec<String>) -> impl Future<Output = bool> + use<> {
584        let (done, committed) = oneshot::channel();
585        self.send(Write::Paused { repositories, done });
586        async move { committed.await.unwrap_or(false) }
587    }
588
589    /// Records a change auto sizing is about to write, as pending, before the file is, synced to disk. The future
590    /// has its row once it committed, `None` if it did not: then nothing may be written.
591    pub fn sizing_intent(
592        &self,
593        change: api::SizingChange,
594    ) -> impl Future<Output = Option<i64>> + use<> {
595        let (done, committed) = oneshot::channel();
596        self.send(Write::SizingIntent { change, done });
597        async move { committed.await.ok().flatten() }
598    }
599
600    /// Records what became of a pending change, synced to disk; a done one is announced as `sizing.changed` in the
601    /// same transaction. The future says whether it committed.
602    pub fn sizing_resolved(
603        &self,
604        id: i64,
605        resolution: Resolution,
606    ) -> impl Future<Output = bool> + use<> {
607        let (done, committed) = oneshot::channel();
608        self.send(Write::SizingResolved {
609            id,
610            resolution,
611            done,
612        });
613        async move { committed.await.unwrap_or(false) }
614    }
615
616    /// Records what the notifier delivered to a target: sets `set`'s keys and removes `remove`'s, in one
617    /// transaction. The future says whether it committed.
618    pub fn notify_record(
619        &self,
620        target: &str,
621        set: Vec<(String, u64)>,
622        remove: Vec<String>,
623    ) -> impl Future<Output = bool> + use<> {
624        let (done, committed) = oneshot::channel();
625        self.send(Write::Notify {
626            change: NotifyChange::Record {
627                target: target.to_owned(),
628                set,
629                remove,
630            },
631            done,
632        });
633        async move { committed.await.unwrap_or(false) }
634    }
635
636    /// Forgets what the notifier kept for every target but `targets`. The future says whether it committed.
637    pub fn notify_keep(&self, targets: Vec<String>) -> impl Future<Output = bool> + use<> {
638        let (done, committed) = oneshot::channel();
639        self.send(Write::Notify {
640            change: NotifyChange::Keep(targets),
641            done,
642        });
643        async move { committed.await.unwrap_or(false) }
644    }
645
646    /// Deletes what is older than `history` keeps, at `now` (ms), off the writer, in batches the writer's
647    /// transactions fit between. A prune while the last one runs does nothing. The handle finishes with it; dropping
648    /// it lets it run.
649    pub fn prune(&self, now: u64, history: &History) -> tokio::task::JoinHandle<()> {
650        let pruner = self.pruner.clone();
651        let closed = self.closed.clone();
652        let history = history.clone();
653        tokio::task::spawn_blocking(move || {
654            let db = match pruner.try_lock() {
655                Ok(db) => db,
656                Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
657                Err(TryLockError::WouldBlock) => return,
658            };
659            let db = prune::Db {
660                connection: &db,
661                stop: &closed,
662            };
663            if !db.stop.load(Ordering::Relaxed) {
664                prune::run(&db, now, &history);
665            }
666        })
667    }
668
669    /// Stops a running prune after its batch, and any later one before it starts, so a shutdown does not wait for
670    /// one. What a stopped prune left, the next daemon's deletes. Writes go on as before.
671    pub fn close(&self) {
672        self.closed.store(true, Ordering::Relaxed);
673    }
674
675    /// Waits until every write sent before is done.
676    pub async fn flush(&self) {
677        let (done, wait) = oneshot::channel();
678        self.send(Write::Flush(done));
679        let _ = wait.await;
680    }
681
682    /// Every event from now on, durable or live. Subscribe before reading what was stored, then skip what the read
683    /// returned, and nothing is missed or sent twice.
684    pub fn subscribe(&self) -> broadcast::Receiver<Arc<EventEnvelope>> {
685        self.events.subscribe()
686    }
687
688    async fn read<T: Send + 'static>(
689        &self,
690        query: impl FnOnce(&Connection) -> rusqlite::Result<T> + Send + 'static,
691    ) -> Result<T, StoreError> {
692        let reader = self.reader.clone();
693        // A panic during a read leaves the connection usable: reads change nothing.
694        Ok(tokio::task::spawn_blocking(move || query(&lock(&reader))).await??)
695    }
696
697    /// One page of jobs, newest first.
698    pub async fn jobs(&self, query: api::JobQuery) -> Result<api::JobPage, StoreError> {
699        self.read(move |db| read::jobs(db, &query)).await
700    }
701
702    /// A job with its steps.
703    pub async fn job(&self, id: u64) -> Result<Option<api::Job>, StoreError> {
704        self.read(move |db| read::job(db, id)).await
705    }
706
707    /// A job's samples, oldest first; `None` if there is no such job.
708    pub async fn job_samples(
709        &self,
710        id: u64,
711        interval: Duration,
712    ) -> Result<Option<api::SampleSeries>, StoreError> {
713        self.read(move |db| read::job_samples(db, id, interval))
714            .await
715    }
716
717    /// Up to `limit` log lines of a job from line `from`, with their numbers.
718    pub async fn log_lines(
719        &self,
720        job: u64,
721        from: u64,
722        limit: u64,
723    ) -> Result<Vec<(u64, String)>, StoreError> {
724        self.read(move |db| read::log_lines(db, job, from, limit))
725            .await
726    }
727
728    /// Up to `limit` durable events after `after`, oldest first.
729    pub async fn events_after(
730        &self,
731        after: u64,
732        limit: u64,
733    ) -> Result<Vec<EventEnvelope>, StoreError> {
734        self.read(move |db| read::events_after(db, after, limit))
735            .await
736    }
737
738    /// The changes auto sizing wrote since `since` (ms), oldest first.
739    pub async fn sizing_changes(&self, since: u64) -> Result<Vec<api::SizingChange>, StoreError> {
740        self.read(move |db| read::sizing_changes(db, since)).await
741    }
742
743    /// When each profile last changed, and the changes still pending.
744    pub async fn auto_sizing(&self) -> Result<AutoSizing, StoreError> {
745        self.read(read::auto_sizing).await
746    }
747
748    /// The profiles and repositories as the stored events last announced them, so a restarted daemon announces
749    /// only what changed since, including what its config no longer has. Blocks on the database: for startup.
750    pub fn announced(&self) -> Result<Announced, StoreError> {
751        Ok(read::announced(&lock(&self.reader))?)
752    }
753
754    /// The repositories recorded paused, for the engine to start with. Blocks on the database: for startup.
755    pub fn paused_repositories(&self) -> Result<Vec<String>, StoreError> {
756        Ok(read::paused(&lock(&self.reader))?)
757    }
758
759    /// The slice's samples since `since` (seconds), oldest first, the ones not yet stored included.
760    pub async fn host_samples(&self, since: u64) -> Result<Vec<api::HostSample>, StoreError> {
761        // Copied before the read: the writer removes a sample only once it is stored, so each one is in the copy,
762        // the read, or both.
763        let held = lock(&self.held).clone();
764        let mut samples = self.read(move |db| read::host_samples(db, since)).await?;
765        let stored = samples.last().map_or(0, |sample| sample.at);
766        samples.extend(
767            held.into_iter()
768                .filter(|sample| sample.at >= since && sample.at > stored),
769        );
770        Ok(samples)
771    }
772
773    /// The jobs runnerd's runners started and finished from `since` until `now` (seconds).
774    pub async fn activity(&self, since: u64, now: u64) -> Result<api::Activity, StoreError> {
775        self.read(move |db| read::activity(db, since, now)).await
776    }
777
778    /// Finished jobs per repository and bucket.
779    pub async fn stats(&self, query: api::StatsQuery, now: u64) -> Result<api::Stats, StoreError> {
780        self.read(move |db| read::stats(db, &query, now)).await
781    }
782
783    /// What sizing reads: the finished jobs queued at or after `since` (ms) and the runners since.
784    pub async fn sizing(&self, since: u64) -> Result<sizing::History, StoreError> {
785        self.read(move |db| read::sizing(db, since)).await
786    }
787
788    /// The jobs completed or lost that were queued at or after `since` (ms), as insights read them.
789    pub async fn insights(&self, since: u64) -> Result<Vec<crate::insights::Run>, StoreError> {
790        self.read(move |db| read::insights(db, since)).await
791    }
792
793    /// The newest durable event's ID; 0 before the first.
794    pub async fn last_event(&self) -> Result<u64, StoreError> {
795        self.read(read::last_event).await
796    }
797
798    /// What the notifier kept for each target, by target, then key.
799    pub async fn notify_state(
800        &self,
801    ) -> Result<BTreeMap<String, BTreeMap<String, u64>>, StoreError> {
802        self.read(read::notify_state).await
803    }
804
805    /// The jobs queued at or after `since` (ms), whatever became of them, as warm runners learn from them.
806    pub async fn warm(&self, since: u64) -> Result<Vec<warm::Seen>, StoreError> {
807        self.read(move |db| read::warm(db, since)).await
808    }
809
810    /// The last measurement of every volume, with its time (seconds), by name.
811    pub async fn cache_sizes_now(&self) -> Result<Measured, StoreError> {
812        self.read(read::latest_cache_sizes).await
813    }
814
815    /// What the build cache served and took from the runners started since `since` (ms), summed.
816    pub async fn build_cache_since(&self, since: u64) -> Result<api::BuildCacheCounts, StoreError> {
817        self.read(move |db| read::build_cache_since(db, since))
818            .await
819    }
820
821    /// Every volume measurement since `since` (seconds).
822    pub async fn cache_history(&self, since: u64) -> Result<Vec<api::CacheSize>, StoreError> {
823        self.read(move |db| read::cache_history(db, since)).await
824    }
825
826    /// The jobs not yet closed, for the engine after a restart.
827    pub async fn open_jobs(&self) -> Result<Vec<OpenJob>, StoreError> {
828        self.read(read::open_jobs).await
829    }
830
831    /// The job a runner took, if the history knows it.
832    pub async fn runner_job(&self, runner: &str) -> Result<Option<u64>, StoreError> {
833        let runner = runner.to_owned();
834        self.read(move |db| read::runner_job(db, &runner)).await
835    }
836
837    /// Where a job's log capture continues.
838    pub async fn log_position(&self, job: u64) -> Result<LogPosition, StoreError> {
839        self.read(move |db| read::log_position(db, job)).await
840    }
841
842    /// How far the mirror's log was counted.
843    pub async fn mirror_log_until(&self) -> Result<MirrorPosition, StoreError> {
844        self.read(read::mirror_log_until).await
845    }
846}
847
848/// What sizing reads from the database at `path`, opened read-only and not migrated, as `runnerd doctor` reads it
849/// while no daemon runs; `None` when there is no database yet. In a directory it may write, SQLite keeps the
850/// `-wal` and `-shm` files a read of a WAL database needs next to it; in one it may not, it reads the file as it is,
851/// or refuses when the `-wal` holds changes the file does not have yet.
852pub fn sizing_at(path: &Path, since: u64) -> Result<Option<sizing::History>, StoreError> {
853    if !path.exists() {
854        return Ok(None);
855    }
856    let read = |path: &str, flags| -> Result<sizing::History, StoreError> {
857        let db = Connection::open_with_flags(path, flags)?;
858        db.busy_timeout(Duration::from_secs(5))?;
859        sizing_of(&db, since)
860    };
861    let name = path.to_string_lossy();
862    match read(&name, OpenFlags::SQLITE_OPEN_READ_ONLY) {
863        Err(StoreError::Sqlite(error))
864            if matches!(
865                error.sqlite_error_code(),
866                Some(rusqlite::ErrorCode::ReadOnly | rusqlite::ErrorCode::CannotOpen)
867            ) =>
868        {
869            // No `-shm` can be made: read the file alone, unless the `-wal` holds what it lacks.
870            let mut wal = path.as_os_str().to_owned();
871            wal.push("-wal");
872            let wal = PathBuf::from(wal);
873            if std::fs::metadata(&wal).is_ok_and(|wal| wal.len() > 0) {
874                return Err(StoreError::Unread(wal));
875            }
876            let uri = format!(
877                "file:{}?mode=ro&immutable=1",
878                name.replace('%', "%25")
879                    .replace('?', "%3f")
880                    .replace('#', "%23")
881            );
882            read(
883                &uri,
884                OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI,
885            )
886        }
887        history => history,
888    }
889    .map(Some)
890}
891
892/// What sizing reads from a database of any version this build knows, without migrating it.
893fn sizing_of(db: &Connection, since: u64) -> Result<sizing::History, StoreError> {
894    let found: u32 = db.pragma_query_value(None, "user_version", |row| row.get(0))?;
895    let supported = u32::try_from(MIGRATIONS.len()).unwrap_or(u32::MAX);
896    if found > supported {
897        return Err(StoreError::Newer { found, supported });
898    }
899    if found == 0 {
900        return Ok(sizing::History::default());
901    }
902    // Columns sizing reads that later versions added: before them, a temporary view gives each runner none.
903    let added = match found {
904        1 => {
905            "NULL AS memory_cap, NULL AS cpu_cap, NULL AS admission, NULL AS oom_kills, NULL AS ooms, \
906             NULL AS memory_measure"
907        }
908        2..=6 => "NULL AS admission, NULL AS oom_kills, NULL AS ooms, NULL AS memory_measure",
909        7 => "NULL AS ooms, NULL AS memory_measure",
910        _ => "",
911    };
912    if !added.is_empty() {
913        db.execute_batch(&format!(
914            "CREATE TEMP VIEW runners AS SELECT *, {added} FROM main.runners"
915        ))?;
916    }
917    Ok(read::sizing(db, since)?)
918}
919
920/// WAL, so the API reads while the writer writes; a busy timeout instead of an immediate error.
921fn configure(db: &Connection) -> rusqlite::Result<()> {
922    db.pragma_update(None, "journal_mode", "wal")?;
923    db.pragma_update(None, "synchronous", "normal")?;
924    db.pragma_update(None, "foreign_keys", "on")?;
925    db.busy_timeout(Duration::from_secs(5))
926}
927
928/// Runs the migrations the database lacks, each in its own transaction with its new version.
929fn migrate(db: &mut Connection) -> Result<(), StoreError> {
930    let found: u32 = db.pragma_query_value(None, "user_version", |row| row.get(0))?;
931    let supported = u32::try_from(MIGRATIONS.len()).unwrap_or(u32::MAX);
932    if found > supported {
933        return Err(StoreError::Newer { found, supported });
934    }
935    for (version, migration) in (1..).zip(MIGRATIONS).skip(found as usize) {
936        let transaction = db.transaction()?;
937        transaction.execute_batch(migration)?;
938        transaction.pragma_update(None, "user_version", version)?;
939        transaction.commit()?;
940    }
941    Ok(())
942}
943
944/// Logs a failed write; the writer goes on with the next one.
945fn logged<T>(what: &str, result: rusqlite::Result<T>) -> Option<T> {
946    result
947        .map_err(|error| warn!("job history: cannot {what}: {error}"))
948        .ok()
949}
950
951#[cfg(test)]
952mod tests;