1use 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
30const 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
47pub(crate) const LOG_BACKLOG: u64 = 8 << 20;
50
51const HOST_SAMPLE_BATCH: usize = 30;
54
55const EVENT_BUFFER: usize = 4096;
57
58#[derive(Debug, thiserror::Error)]
60pub enum StoreError {
61 #[error("{0}")]
63 Sqlite(#[from] rusqlite::Error),
64 #[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 found: u32,
72 supported: u32,
74 },
75 #[error("{0}")]
77 Io(#[from] std::io::Error),
78 #[error("a database read stopped: {0}")]
80 Join(#[from] tokio::task::JoinError),
81 #[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#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct RunnerRecord {
94 pub name: String,
96 pub repository: String,
98 pub profile: String,
100 pub slot: usize,
102 pub container: String,
104 pub started_at: u64,
106 pub memory_cap: Option<u64>,
108 pub cpu_cap: Option<u64>,
110 pub admission: Option<api::Admission>,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct SampleRecord {
117 pub runner: String,
119 pub at: u64,
121 pub cpu: u64,
123 pub cpu_usage: u64,
125 pub memory: u64,
127 pub network_received: u64,
129 pub network_sent: u64,
131 pub events: Events,
133}
134
135#[derive(Debug, Clone, Default, PartialEq, Eq)]
137pub struct Measured {
138 pub at: Option<u64>,
140 pub bytes: BTreeMap<String, u64>,
142}
143
144#[derive(Debug, Clone, Default, PartialEq, Eq)]
147pub struct Announced {
148 pub profiles: Vec<api::ProfileStatus>,
150 pub repositories: Vec<api::RepositoryStatus>,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct OpenJob {
157 pub id: u64,
159 pub repository: String,
161 pub state: api::JobState,
163 pub runner: Option<String>,
165 pub runner_removed_at: Option<u64>,
167 pub run_id: u64,
169 pub run_attempt: u32,
171 pub workflow: Option<String>,
173 pub queued_at: u64,
175 pub labels: Vec<String>,
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub struct LogPosition {
182 pub page: u64,
184 pub offset: u64,
186}
187
188#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
192pub struct MirrorPosition {
193 pub at: u64,
195 pub seen: u64,
197}
198
199#[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 position: Option<LogPosition>,
249 max_bytes: u64,
250 _backlog: OwnedSemaphorePermit,
252 },
253 Samples(Vec<SampleRecord>),
254 HostSample(api::HostSample),
255 MirrorBytes {
256 bytes: Vec<(String, u64)>,
257 until: MirrorPosition,
258 done: oneshot::Sender<bool>,
260 },
261 CacheSizes {
262 at: u64,
263 sizes: BTreeMap<String, u64>,
264 },
265 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 done: oneshot::Sender<bool>,
281 },
282 SizingIntent {
283 change: api::SizingChange,
284 done: oneshot::Sender<Option<i64>>,
286 },
287 SizingResolved {
288 id: i64,
289 resolution: Resolution,
290 done: oneshot::Sender<bool>,
292 },
293 Notify {
294 change: NotifyChange,
295 done: oneshot::Sender<bool>,
297 },
298 Flush(oneshot::Sender<()>),
299}
300
301#[derive(Debug)]
303enum NotifyChange {
304 Record {
306 target: String,
307 set: Vec<(String, u64)>,
308 remove: Vec<String>,
309 },
310 Keep(Vec<String>),
312}
313
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
316pub enum Resolution {
317 Done,
319 Failed,
321 Uncertain,
324}
325
326#[derive(Debug, Clone, Default, PartialEq, Eq)]
328pub struct AutoSizing {
329 pub last: BTreeMap<String, u64>,
331 pub pending: Vec<(i64, api::SizingChange)>,
333}
334
335#[derive(Debug, Clone)]
337pub struct Store {
338 writes: mpsc::UnboundedSender<Write>,
339 reader: Arc<Mutex<Connection>>,
340 pruner: Arc<Mutex<Connection>>,
342 closed: Arc<AtomicBool>,
344 held: Arc<Mutex<Vec<api::HostSample>>>,
347 latest_host: Arc<Mutex<Option<api::HostSample>>>,
349 latest_host_memory: Arc<Mutex<Option<api::HostMemory>>>,
351 latest_samples: Arc<Mutex<BTreeMap<String, SampleRecord>>>,
353 events: broadcast::Sender<Arc<EventEnvelope>>,
354 backlog: Arc<Semaphore>,
355}
356
357impl Store {
358 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 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 let _ = self.writes.send(write);
410 }
411
412 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 pub fn runner_started(&self, runner: RunnerRecord) {
422 self.send(Write::RunnerStarted(runner));
423 }
424
425 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 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 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 pub fn details(&self, details: JobDetails) {
453 self.send(Write::Details { details });
454 }
455
456 pub fn elsewhere(&self, details: JobDetails) {
458 self.send(Write::Elsewhere { details });
459 }
460
461 pub fn lost(&self, job: u64, at: u64) {
463 self.send(Write::Lost { job, at });
464 }
465
466 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 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 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 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 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 pub fn latest_sample(&self, runner: &str) -> Option<SampleRecord> {
528 lock(&self.latest_samples).get(runner).cloned()
529 }
530
531 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 pub fn runner_oom_killed(&self, runner: &str) {
542 self.send(Write::RunnerOomKilled(runner.to_owned()));
543 }
544
545 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 pub fn host_memory(&self, memory: api::HostMemory) {
555 *lock(&self.latest_host_memory) = Some(memory);
556 }
557
558 pub fn latest_host_memory(&self) -> Option<api::HostMemory> {
560 lock(&self.latest_host_memory).clone()
561 }
562
563 pub fn host_waited(&self, jobs: Vec<u64>, ms: u64) {
566 self.send(Write::HostWaited { jobs, ms });
567 }
568
569 pub fn latest_host_sample(&self) -> Option<api::HostSample> {
571 lock(&self.latest_host).clone()
572 }
573
574 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 pub fn cache_sizes(&self, at: u64, sizes: BTreeMap<String, u64>) {
584 self.send(Write::CacheSizes { at, sizes });
585 }
586
587 pub fn event(&self, event: Event) {
589 self.send(Write::Event(Box::new(event)));
590 }
591
592 pub fn record_made(&self, record: api::Record) {
594 self.send(Write::RecordMade(record));
595 }
596
597 pub fn record_skipped(&self, job: u64, why: String) {
599 self.send(Write::RecordSkipped { job, why });
600 }
601
602 pub fn record_removed(&self, job: u64, at: u64, by: api::RecordRemoval) {
604 self.send(Write::RecordRemoved { job, at, by });
605 }
606
607 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 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 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 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 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 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 pub fn close(&self) {
698 self.closed.store(true, Ordering::Relaxed);
699 }
700
701 pub async fn flush(&self) {
703 let (done, wait) = oneshot::channel();
704 self.send(Write::Flush(done));
705 let _ = wait.await;
706 }
707
708 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 Ok(tokio::task::spawn_blocking(move || query(&lock(&reader))).await??)
721 }
722
723 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 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 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 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 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 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 pub async fn auto_sizing(&self) -> Result<AutoSizing, StoreError> {
771 self.read(read::auto_sizing).await
772 }
773
774 pub fn announced(&self) -> Result<Announced, StoreError> {
777 Ok(read::announced(&lock(&self.reader))?)
778 }
779
780 pub fn paused_repositories(&self) -> Result<Vec<String>, StoreError> {
782 Ok(read::paused(&lock(&self.reader))?)
783 }
784
785 pub async fn host_samples(&self, since: u64) -> Result<Vec<api::HostSample>, StoreError> {
787 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 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 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 pub async fn sizing(&self, since: u64) -> Result<sizing::History, StoreError> {
811 self.read(move |db| read::sizing(db, since)).await
812 }
813
814 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 pub async fn last_event(&self) -> Result<u64, StoreError> {
821 self.read(read::last_event).await
822 }
823
824 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 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 pub async fn cache_sizes_now(&self) -> Result<Measured, StoreError> {
838 self.read(read::latest_cache_sizes).await
839 }
840
841 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 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 pub async fn open_jobs(&self) -> Result<Vec<OpenJob>, StoreError> {
854 self.read(read::open_jobs).await
855 }
856
857 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 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 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 pub async fn mirror_log_until(&self) -> Result<MirrorPosition, StoreError> {
880 self.read(read::mirror_log_until).await
881 }
882}
883
884pub 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 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
928fn 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 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
959fn 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
967fn 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
983fn 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;