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