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