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