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