Skip to main content

runnerd_core/
api.rs

1//! The daemon's JSON API, version 1: the request and response types every client deserializes, and the
2//! principal a transport authenticates. Plain data only: no I/O, no Docker or GitHub types, no secrets but a
3//! [`Pairing`]'s one-time link, which its `Debug` leaves out.
4//!
5//! Routes, all under the authenticated principal:
6//!
7//! | Route | Body |
8//! |---|---|
9//! | `GET /v1/status` | [`Status`] |
10//! | `POST /v1/repositories/{owner}/{name}/pause?`[`PauseQuery`] | [`Paused`]; 409 [`Busy`] while it runs a job |
11//! | `POST /v1/repositories/{owner}/{name}/resume` | none, 204 |
12//! | `POST /v1/repositories/pause?`[`PauseQuery`] | [`Paused`]; 409 [`Busy`] while any runs a job, pausing none |
13//! | `POST /v1/repositories/resume` | none, 204: every repository resumed |
14//! | `POST /v1/profiles/{name}/reseed` | none, 202; 409 while it reseeds; `cache.reseeded` when done |
15//! | `POST /v1/caches/{name}/clean` | none, 204; 409 [`Busy`] while a runner uses it |
16//! | `GET /v1/config` | [`ConfigFile`] |
17//! | `POST /v1/config/check` | TOML in, [`ConfigCheck`] |
18//! | `PUT /v1/config` | TOML in, [`ConfigCheck`]; 422 [`ConfigCheck`] when invalid |
19//! | `GET /v1/doctor` | [`Doctor`] |
20//! | `POST /v1/shutdown` | [`ShutdownRequest`] in, 202 [`ShutdownAnswer`] |
21//! | `GET /v1/dashboard` | [`Dashboard`] |
22//! | `POST /v1/dashboard/sign-out` | none, 204 |
23//! | `POST /v1/dashboard/pairings?`[`PairingQuery`] | [`Pairings`]; 409 when the dashboard is off or has no `[web] origins` |
24//! | `GET /v1/jobs?`[`JobQuery`] | [`JobPage`] |
25//! | `GET /v1/jobs/{id}` | [`Job`] |
26//! | `GET /v1/jobs/{id}/samples` | [`SampleSeries`] |
27//! | `GET /v1/jobs/{id}/logs?`[`LogQuery`] | `text/plain`, one line per log line |
28//! | `GET /v1/host/samples?`[`HostSampleQuery`] | [`HostSamples`] |
29//! | `GET /v1/stats?`[`StatsQuery`] | [`Stats`] |
30//! | `GET /v1/activity?`[`ActivityQuery`] | [`Activity`] |
31//! | `GET /v1/sizing?`[`SizingQuery`] | [`Sizing`] |
32//! | `GET /v1/insights?`[`InsightsQuery`] | [`Insights`] |
33//! | `GET /v1/digest` | [`Digest`] |
34//! | `GET /v1/savings` | [`Savings`] |
35//! | `POST /v1/notify/test?`[`NotifyTestQuery`] | [`NotifyTest`]; 404 without `[notify]` targets or with no such one |
36//! | `GET /v1/caches` | [`Caches`] |
37//! | `GET /v1/caches/history?`[`CacheHistoryQuery`] | [`CacheHistory`] |
38//! | `GET /v1/events?`[`EventQuery`] | `text/event-stream` of [`EventEnvelope`] |
39//! | `GET /v1/records` | [`Records`] |
40//! | `DELETE /v1/records/{job}` | [`RemovedRecords`]; 409 while a shell is open in it |
41//! | `DELETE /v1/records?`[`RemoveRecordsQuery`] | [`RemovedRecords`]; records with an open shell stay |
42//! | `POST /v1/records/{job}/shell?`[`ShellQuery`] | `Upgrade:` [`SHELL_PROTOCOL`], 101, then the shell's terminal; 409 when the budget is full |
43//!
44//! Errors carry an [`ErrorResponse`].
45
46use serde::{Deserialize, Serialize};
47
48mod admission;
49mod budget;
50mod control;
51mod events;
52mod insights;
53mod jobs;
54mod labels;
55mod records;
56mod results;
57mod savings;
58mod sizing;
59mod slots;
60mod stats;
61mod storage;
62mod tone;
63mod units;
64
65pub use admission::{Admission, AdmissionPolicy, Basis, CpuAdmission, JobPeak, cores, cpus};
66pub use budget::{
67    BudgetParts, ClosedKind, ClosedPart, FreePart, HeldKind, HeldPart, Reading, SlotPart,
68};
69pub use control::{
70    Busy, Check, CheckStatus, ConfigCheck, ConfigFile, Doctor, PauseQuery, Paused, ReplaceQuery,
71    RunningJob,
72};
73pub use events::{Event, EventEnvelope, EventQuery, RunnerFailure};
74pub use insights::{
75    AutoNote, Delivery, Digest, INSIGHT_DAYS, INSIGHT_DAYS_MAX, Insight, InsightKind, Insights,
76    InsightsQuery, LongWait, Notification, NotifyEvent, NotifyTest, NotifyTestQuery, Priority,
77    RepositoryWaits, RunLink, Severity, WaitSpread, WeekWaits,
78};
79pub use jobs::{
80    Activity, ActivityQuery, Bucket, BuildCacheCounts, BuildCacheStats, CacheHistory,
81    CacheHistoryQuery, CacheKind, CacheSize, CacheVolume, Caches, ChartLine, ChartLineKind,
82    ChartLines, Holder, HostMemory, HostSample, HostSampleQuery, HostSamples, Job, JobMetrics,
83    JobPage, JobQuery, JobRunner, JobState, JobSummary, JobTitle, Limit, LimitSource, Limits,
84    LogQuery, LogSummary, Milestone, Outcome, OutcomeKind, Phase, PhaseKind, Pressure,
85    RunComparison, Sample, SampleSeries, SampleUsage, Started, Stats, StatsQuery, StatsRow, Step,
86    Swap, Timeline, Total, host_margin, job_title,
87};
88pub use labels::{Column, View};
89pub use records::{
90    Record, RecordLimits, RecordNote, RecordRemoval, Records, RemoveRecordsQuery, RemovedRecords,
91    SHELL_PROTOCOL, ShellQuery,
92};
93pub use results::{force_pause_consequence, reseed_requested, reseeded};
94pub use savings::{
95    Period, PricedRun, PricedRunner, Pricing, PricingHistory, SELF_HOSTED_RATE, SavedWindow,
96    Savings, Sku, Usd, Visibility, billed_minutes, reads_since,
97};
98pub use sizing::{
99    Advice, AutoPlan, GRANULE, JobSizing, MemoryBound, MemoryHold, Need, PAGE_CACHE_ROOM, Peaks,
100    ProfilePlan, ProfileSizing, Resize, RevertCause, SAMPLE_INTERVAL, SLOT_DISK, Sizing,
101    SizingChange, SizingHold, SizingQuery, SizingRefused, SizingRevert, Spread, Starts, need,
102    period, sampled_note,
103};
104pub use slots::{Figure, Health, SlotState};
105pub use stats::StatsSummary;
106pub use storage::{
107    ACTIONS_CACHE, BUILD_CACHE_TOOLS, BuildCacheActivity, CacheLimit, RECORDS_NEAR_FULL,
108    RecordState, actions_cache_place, records_near_full,
109};
110pub use tone::{Tone, Toned};
111#[cfg(feature = "host")]
112pub(crate) use units::days_from_civil;
113pub use units::{ago, cores_used, cpu_time, duration, in_cores};
114
115/// Who sent a request, as the transport authenticated it. Handlers get it from one place, so a new transport only
116/// has to produce one.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(rename_all = "kebab-case", tag = "kind")]
119pub enum Principal {
120    /// The user the daemon runs as, on the local Unix socket.
121    LocalOwner {
122        /// The Unix user ID the socket's peer runs as.
123        uid: u32,
124    },
125}
126
127/// `GET /v1/status`: what the daemon serves and runs right now.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
129pub struct Status {
130    /// The daemon's version, from its `Cargo.toml`.
131    pub version: String,
132    /// Set once the daemon stops polling to shut down. [`Status::stopping_line`] says how.
133    pub shutting_down: bool,
134    /// How it stops, once it does; absent from a daemon before it said.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub stopping: Option<Stopping>,
137    /// The memory budget and what runners use of it.
138    pub budget: Budget,
139    /// Every configured profile with its slots.
140    pub profiles: Vec<ProfileStatus>,
141    /// Every configured repository.
142    pub repositories: Vec<RepositoryStatus>,
143    /// Queued jobs the repositories' runners can take and none holds yet, at the last poll, oldest first. No event
144    /// carries the list: `job.queued` announces a job, `job.started` and `job.finished` its leaving the queue.
145    /// A repository whose last listing failed, as while GitHub rate-limits runnerd, or that is no longer polled
146    /// because runnerd is shutting down, shows no jobs here, while the history keeps its jobs queued.
147    pub queued: Vec<QueuedJob>,
148}
149
150/// The memory budget runners and the mirror share, in bytes.
151#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
152pub struct Budget {
153    /// The systemd slice runner containers run in.
154    pub slice: String,
155    /// The slice's `MemoryMax`; `None` when it is unlimited.
156    pub memory_max: Option<u64>,
157    /// Memory the running containers reserve: the runners' caps, or under measured admission the larger of each
158    /// runner's predicted peak and its last sampled memory, nothing for one whose container is gone, and the caps of
159    /// the seed containers, shells and the mirror.
160    pub memory_in_use: u64,
161    /// What pooling takes off `memory_in_use` (ADR 0099); absent while it takes nothing.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub pooled: Option<Pooled>,
164    /// What a new runner must fit in beside them.
165    pub admission: AdmissionPolicy,
166    /// Under measured admission, whether the slice is at the high-water mark, so no runner starts.
167    pub held: bool,
168    /// The mirror's part of `memory_in_use`: its cap while it is enabled or still running, else 0.
169    pub mirror_memory: u64,
170    /// The seed containers' part of `memory_in_use`, one per profile that reseeds, by profile name.
171    pub seed_memory: Vec<SeedMemory>,
172    /// The shells' part of `memory_in_use`, one per shell open in a record, by job.
173    pub shell_memory: Vec<ShellMemory>,
174    /// What the host's memory leaves runners beside its other programs, from a recent reading of it; absent
175    /// without one.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub host: Option<HostBudget>,
178    /// The CPU budget, under `[host] cpu_overcommit`. Absent without one.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub cpu: Option<CpuBudget>,
181    /// The CPUs the slice may use, in millicores: its `AllowedCPUs` or the host's, less under a lower `CPUQuota`,
182    /// whether or not a CPU budget admits runners. The runners' CPU limits are quotas that may add up past it.
183    /// Absent when it could not be read.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub slice_cpus: Option<u64>,
186}
187
188/// The count the budgets go by while pooling takes something off `Budget::memory_in_use` (ADR 0099).
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
190pub struct Pooled {
191    /// What it takes off, in bytes.
192    pub credit: u64,
193    /// `Budget::memory_in_use` less `credit`: what new runners fit beside under `MemoryMax`. The host's limit reads
194    /// `memory_in_use`.
195    pub counted: u64,
196    /// How many runners the credit counts on.
197    pub runners: u64,
198}
199
200/// What the host's memory leaves the runners (ADR 0055). New runners fit in the lower of `MemoryMax` and
201/// `limit`; running ones are never stopped for it.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct HostBudget {
204    /// The reading it comes from.
205    pub memory: HostMemory,
206    /// What the slice may hold now: what its runners hold without page cache plus the host's `MemAvailable`, less
207    /// a margin kept free for the host's page cache; with a ceiling, plus what the host can still grow by
208    /// (`HostMemory::growable`, ADR 0084).
209    pub limit: u64,
210    /// What that leaves new runners beside what the running ones reserve, in bytes.
211    pub spare: u64,
212    /// Whether the host's tasks stall for memory (`full` pressure), so no runner starts until they stop.
213    pub stalled: bool,
214}
215
216impl HostBudget {
217    /// Whether the host itself lacks `needs` bytes for a new runner: its tasks stall, `HostMemory::room` is less, or
218    /// that room is under one more margin, so `MemAvailable` is under twice the plain margin, the line `host::stalls`
219    /// reads. There a small job fits only by what the host is about to run out of, and what closing programs frees is
220    /// what starts it. Otherwise a job the host limit holds waits for what runs, whose reservations reach the limit
221    /// (ADR 0103).
222    pub fn short_of(&self, needs: u64) -> bool {
223        let room = self.memory.room();
224        self.stalled || needs > room || room < host_margin(self.memory.grown())
225    }
226}
227
228/// Why a job waits for the host's limit, needing `needs` bytes with `free` left of it, by the latest reading: for what
229/// runs, or for a host that lacks the room, whose programs it names.
230fn host_reason(needs: u64, free: u64, host: Option<&HostBudget>) -> String {
231    let size = |bytes: u64| crate::config::ByteSize(bytes).to_string();
232    if let Some(host) = host.filter(|host| !host.short_of(needs)) {
233        return format!(
234            "The host has {}, but what runs may still grow into it: needs {}; {} of the {} it leaves the slice is free",
235            host.memory.available_line(),
236            size(needs),
237            size(free),
238            size(host.limit)
239        );
240    }
241    let reason = if host.is_some_and(|host| host.stalled) {
242        "The host is short of memory: its programs stall waiting for it, so nothing starts"
243            .to_owned()
244    } else {
245        format!(
246            "The host is short of memory: needs {}; the host has {} to spare",
247            size(needs),
248            size(free)
249        )
250    };
251    match host {
252        Some(host) => format!("{reason}; {}", host.memory.outside_line()),
253        None => reason,
254    }
255}
256
257/// Hundredths of a percent as a percentage: `1.5%`, `12%`.
258pub fn percent(hundredths: u32) -> String {
259    let whole = hundredths / 100;
260    match hundredths % 100 / 10 {
261        0 => format!("{whole}%"),
262        tenth => format!("{whole}.{tenth}%"),
263    }
264}
265
266/// The CPU budget runners share, in millicores.
267#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
268pub struct CpuBudget {
269    /// The CPUs the slice may use: its `AllowedCPUs` or the host's, less under a lower `CPUQuota`.
270    pub cpus: u64,
271    /// Those times `cpu_overcommit`: what the runners' reservations must fit.
272    pub budget: u64,
273    /// What the runners reserve: each its predicted average CPU under measured admission, else its `cpus`.
274    pub in_use: u64,
275    /// Whether a queued job waits for CPU that memory and a slot have room for.
276    pub held: bool,
277}
278
279impl CpuBudget {
280    /// The budget's line as clients show it beside memory, such as `CPU 4.5 of 32 CPUs reserved` or, while a job
281    /// waits for it, `CPU 30 of 32 CPUs reserved; a job waits for CPU`.
282    pub fn line(&self) -> String {
283        let mut line = format!(
284            "CPU {} of {} CPUs reserved",
285            cores(self.in_use),
286            cores(self.budget)
287        );
288        if self.held {
289            line.push_str("; a job waits for CPU");
290        }
291        line
292    }
293}
294
295impl Budget {
296    /// How runners are admitted, as clients add it to the budget's line: nothing under caps, else `by predicted
297    /// peaks`, and why nothing starts while the slice is at the high-water mark.
298    pub fn admission_note(&self) -> Option<&'static str> {
299        match (self.admission, self.held) {
300            (AdmissionPolicy::Caps, _) => None,
301            (AdmissionPolicy::Measured, false) => Some("by predicted peaks"),
302            (AdmissionPolicy::Measured, true) => Some(
303                "by predicted peaks; the slice is past 90% of its MemoryMax, so no runner starts",
304            ),
305        }
306    }
307}
308
309/// A shell container's memory cap: its record's profile's limit when the shell opened.
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311pub struct ShellMemory {
312    /// The job whose record the shell runs.
313    pub job: u64,
314    /// Its cap in bytes.
315    pub memory: u64,
316}
317
318/// A seed container's memory cap: its profile's limit when the reseed started, or, for a requested reseed whose
319/// profile drained, the room it holds until it starts.
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
321pub struct SeedMemory {
322    /// The profile it reseeds.
323    pub profile: String,
324    /// Its cap in bytes.
325    pub memory: u64,
326}
327
328/// A runner profile and what runs in its slots.
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330pub struct ProfileStatus {
331    /// The name under `[profiles]` in `runnerd.toml`.
332    pub name: String,
333    /// The image its runners run, such as `runnerd-runner:base`.
334    pub image: String,
335    /// CPUs per slot.
336    pub cpus: u32,
337    /// Bytes per slot.
338    pub memory: u64,
339    /// Set while slot 1's layers become the profile's snapshot.
340    pub reseeding: bool,
341    /// Index 0 is slot 1.
342    pub slots: Vec<SlotStatus>,
343}
344
345/// One slot of a profile: room for one job.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347pub struct SlotStatus {
348    /// 1-based.
349    pub slot: usize,
350    /// `None` when the slot is free.
351    pub runner: Option<RunnerStatus>,
352}
353
354/// A runner registered for one job, in its container.
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356pub struct RunnerStatus {
357    /// `owner/name` the runner is registered on.
358    pub repository: String,
359    /// The runner's name, also its container's.
360    pub name: String,
361    /// The runner's ID on GitHub.
362    pub runner_id: u64,
363    /// The Docker container ID.
364    pub container: String,
365    /// Whether it runs a job, as GitHub or its log reports it: its log names the job before GitHub lists it busy.
366    pub busy: bool,
367    /// Seconds since the Unix epoch.
368    pub started_at: u64,
369    /// What it takes of the budget: its cap under caps; under measured admission the larger of its predicted peak
370    /// and its last sampled memory.
371    pub reserved: u64,
372    /// A warm runner: idle, and no queued job of its repository waits for it; it takes the next one GitHub hands
373    /// out.
374    pub warm: bool,
375}
376
377/// A configured repository and its queue.
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
379pub struct RepositoryStatus {
380    /// `owner/name` on GitHub.
381    pub name: String,
382    /// Its pools in config order, one per `[[repositories]]` entry: a job runs in the one whose labels match it
383    /// (ADR 0058).
384    pub pools: Vec<PoolStatus>,
385    /// Paused repositories get no new runners; their running jobs finish.
386    pub paused: bool,
387    /// Its jobs in `Status::queued`: queued ones none of its runners took yet, those no pool serves too.
388    pub queued_jobs: usize,
389}
390
391/// One of a repository's pools: its runners in one profile.
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
393pub struct PoolStatus {
394    /// The profile its jobs run in.
395    pub profile: String,
396    /// The labels its runners register with.
397    pub labels: Vec<String>,
398    /// Its jobs in `Status::queued`: those its labels match.
399    pub queued_jobs: usize,
400}
401
402/// A queued job runners of this daemon can take, as GitHub listed it at the last poll.
403#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
404pub struct QueuedJob {
405    /// GitHub's job ID.
406    pub id: u64,
407    /// The repository whose runners can take it, `owner/name`.
408    pub repository: String,
409    /// The profile of its repository's pool whose labels match it; `None` when no pool's do.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub profile: Option<String>,
412    /// The workflow run it belongs to.
413    pub run_id: u64,
414    /// 1 for the first attempt of the run, higher for re-runs.
415    pub run_attempt: u32,
416    /// The workflow's name.
417    pub workflow: Option<String>,
418    /// The job's name in the workflow.
419    pub name: String,
420    /// The branch the run is for.
421    pub branch: Option<String>,
422    /// The job's page on GitHub.
423    pub url: Option<String>,
424    /// When GitHub queued it, in seconds since the Unix epoch; 0 if GitHub did not say.
425    pub queued_at: u64,
426    /// Why no runner has it yet, as the last plan saw it. `None` before the daemon has planned with it, and while
427    /// it shuts down.
428    #[serde(default, skip_serializing_if = "Option::is_none")]
429    pub waiting: Option<Waiting>,
430}
431
432/// The slot of an idle runner of `job`'s repository, in its pool's profile when known, such as `jvm 2`.
433fn starting_for(job: &QueuedJob, status: &Status) -> Option<String> {
434    status
435        .profiles
436        .iter()
437        .filter(|profile| job.profile.as_ref().is_none_or(|own| *own == profile.name))
438        .find_map(|profile| {
439            profile
440                .slots
441                .iter()
442                .find(|slot| {
443                    slot.runner
444                        .as_ref()
445                        .is_some_and(|runner| runner.repository == job.repository && !runner.busy)
446                })
447                .map(|slot| format!("{}\u{a0}{}", profile.name, slot.slot))
448        })
449}
450
451impl QueuedJob {
452    /// Where it runs, as every client names it: its repository, and its pool's profile when the repository has
453    /// several pools in `status`, such as `halyard/ledger · light`.
454    pub fn place(&self, status: &Status) -> String {
455        let pools = status
456            .repositories
457            .iter()
458            .find(|repository| repository.name == self.repository)
459            .map_or(0, |repository| repository.pools.len());
460        match self.profile.as_deref().filter(|_| pools > 1) {
461            Some(profile) => format!("{}\u{a0}· {profile}", self.repository),
462            None => self.repository.clone(),
463        }
464    }
465}
466
467impl RepositoryStatus {
468    /// The profile of its first pool, which every client colours it by.
469    pub fn first_profile(&self) -> &str {
470        self.pools.first().map_or("", |pool| pool.profile.as_str())
471    }
472
473    /// Its pools' profiles, as every client lists them on one line: `jvm` or `jvm + light`.
474    pub fn profiles(&self) -> String {
475        self.pools
476            .iter()
477            .map(|pool| pool.profile.as_str())
478            .collect::<Vec<_>>()
479            .join(" + ")
480    }
481
482    /// The profile of its pool whose labels match a job asking for `labels`, as the daemon picks it.
483    pub fn pool_for(&self, labels: &[String]) -> Option<String> {
484        self.pools
485            .iter()
486            .find(|pool| crate::config::labels_match(labels, &pool.labels))
487            .map(|pool| pool.profile.clone())
488    }
489}
490
491/// What failed, that holds a repository's runners back for a while.
492#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
493#[serde(rename_all = "kebab-case")]
494pub enum HoldCause {
495    /// Its runners ended without connecting, so without taking a job (ADR 0104).
496    NoJob,
497    /// Its runners connected and ended without a job, one after the other.
498    IdleExits,
499    /// GitHub did not register its runner.
500    Register,
501    /// Docker did not start its runner's container.
502    Start,
503}
504
505/// Why a queued job has no runner of its own yet. Jobs are served oldest first; each takes the first of these that
506/// holds for it.
507#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
508#[serde(rename_all = "kebab-case", tag = "kind")]
509pub enum Waiting {
510    /// Its repository is paused.
511    Paused,
512    /// Runners of its repository failed, so none starts before `until` (seconds since the Unix epoch).
513    Backoff {
514        /// When runners may start again.
515        until: u64,
516        /// What failed.
517        cause: HoldCause,
518    },
519    /// A runner started for it and waits for GitHub to hand it the job: a runner takes any job its labels match,
520    /// so not necessarily this one.
521    RunnerStarting,
522    /// Slot 1 of its profile is becoming the profile's snapshot, so none of the profile's slots starts.
523    Reseeding {
524        /// The profile.
525        profile: String,
526    },
527    /// Its profile's image is being pulled, so none of the profile's slots starts.
528    PullingImage {
529        /// The profile.
530        profile: String,
531    },
532    /// Every slot of its profile holds a runner.
533    NoSlot {
534        /// The profile.
535        profile: String,
536    },
537    /// What its runner would reserve does not fit the memory budget left. Under measured admission, `free` is 0
538    /// while the slice is at the high-water mark (`Budget::held`).
539    Memory {
540        /// What its runner would reserve, in bytes.
541        needs: u64,
542        /// What the budget has left, in bytes.
543        free: u64,
544    },
545    /// What its runner would reserve does not fit what the host's memory has to spare beside its other programs
546    /// (`HostBudget::spare`), though it fits the slice's budget. `free` is 0 while the host's tasks stall for memory
547    /// (`HostBudget::stalled`).
548    HostMemory {
549        /// What its runner would reserve, in bytes.
550        needs: u64,
551        /// What the host has to spare, in bytes.
552        free: u64,
553    },
554    /// What its runner would reserve does not fit the CPU budget left, in millicores.
555    Cpu {
556        /// What its runner would reserve.
557        needs: u64,
558        /// What the CPU budget has left.
559        free: u64,
560    },
561    /// An older job has waited long enough for CPU that no younger one takes CPU before it.
562    BehindCpu {
563        /// The older job's ID.
564        job: u64,
565    },
566    /// An older job has waited long enough for memory that no younger one starts before it (ADR 0096).
567    BehindMemory {
568        /// The older job's ID.
569        job: u64,
570    },
571    /// An older job is about to have a runner start for it, which takes the slot, memory or CPU this one would
572    /// otherwise start with: what holds it is that start, not what runs now.
573    BehindStart {
574        /// The older job's ID.
575        job: u64,
576    },
577    /// No pool of its repository has every label it asks for, so no runner of this daemon can take it (ADR 0058).
578    NoPool {
579        /// The labels it asks for.
580        labels: Vec<String>,
581    },
582    /// A reason from a newer daemon than this client knows, so a reason added later does not keep the client from
583    /// reading the status.
584    #[serde(other)]
585    Unknown,
586}
587
588/// What a [`Waiting`] reason waits on, which clients draw it by.
589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
590pub enum WaitKind {
591    /// Something the owner can act on: a pause, runners that failed to take a job, or labels no pool serves.
592    Act,
593    /// Something that clears by itself shortly: a runner starting, a reseed, an image pull, an older job's start.
594    Soon,
595    /// Room: a slot, memory or CPU that a running job holds.
596    Full,
597    /// A reason this client does not know (`Waiting::Unknown`), drawn neutral.
598    Other,
599}
600
601impl Waiting {
602    /// What it waits on.
603    pub fn kind(&self) -> WaitKind {
604        match self {
605            Waiting::Paused | Waiting::Backoff { .. } | Waiting::NoPool { .. } => WaitKind::Act,
606            Waiting::Unknown => WaitKind::Other,
607            Waiting::RunnerStarting
608            | Waiting::Reseeding { .. }
609            | Waiting::PullingImage { .. }
610            | Waiting::BehindStart { .. } => WaitKind::Soon,
611            Waiting::NoSlot { .. }
612            | Waiting::Memory { .. }
613            | Waiting::HostMemory { .. }
614            | Waiting::Cpu { .. }
615            | Waiting::BehindCpu { .. }
616            | Waiting::BehindMemory { .. } => WaitKind::Full,
617        }
618    }
619
620    /// Why `job` waits, in the owner's words with the numbers that hold it, as every client says it: such as
621    /// `All 2 node slots are busy` or `Needs 9G of memory; 2.5G of the budget is free`. `status` is the one `job`
622    /// is queued in, which names the slot of a starting runner and the older job one waits behind.
623    pub fn reason(&self, job: &QueuedJob, status: &Status, now: u64) -> String {
624        let size = |bytes: u64| crate::config::ByteSize(bytes).to_string();
625        let older_name = |id: u64| {
626            status
627                .queued
628                .iter()
629                .find(|candidate| candidate.id == id)
630                .map_or_else(|| "an older job".to_owned(), |older| older.name.clone())
631        };
632        match self {
633            Waiting::Paused => format!("{} is paused", job.repository),
634            Waiting::Unknown => "Waits for a reason this client does not know yet".to_owned(),
635            Waiting::NoPool { labels } if labels.is_empty() => {
636                "It asks for no labels, so no profile serves it".to_owned()
637            }
638            Waiting::NoPool { labels } => format!(
639                "No profile serves the {} {}",
640                if labels.len() == 1 { "label" } else { "labels" },
641                labels.join(", ")
642            ),
643            Waiting::Backoff { until, cause } => format!(
644                "{}; retrying in {}",
645                match cause {
646                    HoldCause::NoJob => "Runners failed to take a job",
647                    HoldCause::IdleExits => "Runners ended without a job after waiting for one",
648                    HoldCause::Register => "Runners cannot register with GitHub",
649                    HoldCause::Start => "Runners cannot start",
650                },
651                duration(until.saturating_sub(now))
652            ),
653            Waiting::RunnerStarting => match starting_for(job, status) {
654                Some(slot) => format!("A runner is starting for it in {slot}"),
655                None => "A runner is starting for it".to_owned(),
656            },
657            Waiting::Reseeding { profile } => format!("{profile} is rebuilding its snapshot"),
658            Waiting::PullingImage { profile } => format!("Pulling {profile}'s image"),
659            Waiting::NoSlot { profile } => {
660                let slots = status
661                    .profiles
662                    .iter()
663                    .find(|candidate| &candidate.name == profile)
664                    .map_or(0, |profile| profile.slots.len());
665                if slots == 1 {
666                    format!("The {profile} slot is busy")
667                } else {
668                    format!("All {slots} {profile} slots are busy")
669                }
670            }
671            Waiting::Memory { .. } if status.budget.held => {
672                "The slice is past 90% of its MemoryMax, so nothing starts".to_owned()
673            }
674            Waiting::Memory { needs, free } => format!(
675                "Needs {} of memory; {} of the budget is free",
676                size(*needs),
677                size(*free)
678            ),
679            Waiting::HostMemory { needs, free } => {
680                host_reason(*needs, *free, status.budget.host.as_ref())
681            }
682            Waiting::Cpu { needs, free } => {
683                format!(
684                    "Needs {}; {} are free",
685                    cpus(*needs),
686                    admission::free_cores(*free)
687                )
688            }
689            Waiting::BehindCpu { job: older } => {
690                format!("Behind {}, which waits for CPU", older_name(*older))
691            }
692            Waiting::BehindMemory { job: older } => {
693                format!("Behind {}, which waits for memory", older_name(*older))
694            }
695            Waiting::BehindStart { job: older } => {
696                format!(
697                    "Next after {}, whose runner starts first",
698                    older_name(*older)
699                )
700            }
701        }
702    }
703}
704
705/// `GET /v1/dashboard`: the dashboard's `[web]` settings, as the daemon read them when it started.
706#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
707pub struct Dashboard {
708    /// `[web] open`: the one of `[web] origins` that `runnerctl web` opens the dashboard on; the loopback address
709    /// when none.
710    #[serde(default, skip_serializing_if = "Option::is_none")]
711    pub open: Option<String>,
712}
713
714/// `POST /v1/dashboard/pairings`: which of `[web] origins` to make a link for.
715#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
716pub struct PairingQuery {
717    /// One of `[web] origins`; each of them when none.
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub origin: Option<String>,
720}
721
722/// `POST /v1/dashboard/pairings`: fresh one-time links that sign a device in to the dashboard.
723#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
724pub struct Pairings {
725    /// One per origin asked for.
726    pub links: Vec<Pairing>,
727}
728
729/// A link that signs one device in to the dashboard on `origin`, and nowhere else, within `lifetime`.
730#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
731pub struct Pairing {
732    /// One of `[web] origins`.
733    pub origin: String,
734    /// The link with its one-time code: a credential, which `Debug` leaves out.
735    pub url: String,
736    /// Seconds it works for from when it was made.
737    pub lifetime: u64,
738}
739
740impl std::fmt::Debug for Pairing {
741    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
742        formatter
743            .debug_struct("Pairing")
744            .field("origin", &self.origin)
745            .field("lifetime", &self.lifetime)
746            .finish_non_exhaustive()
747    }
748}
749
750/// `POST /v1/shutdown`.
751#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
752pub struct ShutdownRequest {
753    /// Kill running jobs and delete their runners instead of waiting for them.
754    #[serde(default)]
755    pub force: bool,
756}
757
758/// What `POST /v1/shutdown` answers: how the daemon stops now, which a stop asked for earlier may have made more
759/// urgent than the request.
760#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
761pub struct ShutdownAnswer {
762    /// How it stops.
763    pub stopping: Stopping,
764}
765
766/// How a stopping daemon treats running jobs (ADR 0091).
767#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
768#[serde(rename_all = "kebab-case")]
769pub enum Stopping {
770    /// `runnerd stop`: it waits for running jobs, then removes every runner.
771    WaitsForJobs,
772    /// A signal: it removes idle runners and leaves running jobs to the next start.
773    LeavesJobs,
774    /// `runnerd stop --force` or a second signal: it kills running jobs.
775    KillsJobs,
776    /// A kind of stop from a newer daemon than this client knows, so one added later does not keep the client from
777    /// reading the status.
778    #[serde(other)]
779    Unknown,
780}
781
782impl Stopping {
783    /// What it does, as every client says it: `shutting down: waits for running jobs`.
784    pub fn line(self) -> &'static str {
785        match self {
786            Stopping::WaitsForJobs => "shutting down: waits for running jobs",
787            Stopping::LeavesJobs => "shutting down: leaves running jobs to the next start",
788            Stopping::KillsJobs => "shutting down: kills running jobs",
789            Stopping::Unknown => "shutting down",
790        }
791    }
792}
793
794impl Status {
795    /// What a stopping daemon does, as every client says it ([`Stopping::line`]); `shutting down` from a daemon
796    /// that does not say how; `None` while it runs.
797    pub fn stopping_line(&self) -> Option<&'static str> {
798        match (self.stopping, self.shutting_down) {
799            (Some(stopping), _) => Some(stopping.line()),
800            (None, true) => Some("shutting down"),
801            (None, false) => None,
802        }
803    }
804}
805
806/// The body of every error response.
807#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
808pub struct ErrorResponse {
809    /// What went wrong, for people to read.
810    pub message: String,
811}