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