OXYGENHUB
# f201e1bc5bcd oxygenflow / crates / flow-core / src / api.rs
15.6 KiB · Rust · last changed Checkpoints: a handed-back job resumes (refs #77) 10 days ago source blame history raw
e0918b88 Andy McCall 1
//! The runner API between OxygenHub and `flow runner` (docs/m0.md §5).
2
//! Both sides use these types, so they cannot drift.
3
4
use crate::pipeline::{Job, Sandbox};
5
use crate::receipt::Receipt;
6
use serde::{Deserialize, Serialize};
7
8
/// `POST /api/v1/flow/claim`.
9
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
10
pub struct ClaimRequest {
11
    /// The runner's name, shown on job pages.
12
    pub runner: String,
13
    /// Tiers this runner can run (`microvm`, `syscall`).
14
    pub runtimes: Vec<String>,
bb643c25 Andy McCall ↶ 15
    /// Memory the runner has free for another job, in MiB: the hub hands
16
    /// out only a job whose sandbox fits. Absent: no limit.
17
    #[serde(default, skip_serializing_if = "Option::is_none")]
18
    pub free_memory_mib: Option<u32>,
19
    /// vCPUs the runner has free for another job. Absent: no limit.
20
    #[serde(default, skip_serializing_if = "Option::is_none")]
21
    pub free_cpus: Option<u32>,
f98a8f78 Andy McCall ↶ 22
    /// What the runner is, for the hub's Runners page.
23
    #[serde(default, skip_serializing_if = "Option::is_none")]
24
    pub info: Option<RunnerInfo>,
8c0a4e3a Andy McCall ↶ 25
    /// The rootfs images the runner holds (BLAKE3 hex, as pipelines pin
26
    /// them): the hub offers only jobs whose image is among them
27
    /// (oxygenhub#73). Absent: the runner does not say, and any job may be
28
    /// offered.
29
    #[serde(default, skip_serializing_if = "Option::is_none")]
30
    pub images: Option<Vec<String>>,
1abadd4a Andy McCall ↶ 31
    /// The architecture of each image it holds, by hash, as the image's
32
    /// manifest records it (spec §11.2): the hub offers a job only to a
33
    /// runner whose architecture its image is for.
34
    #[serde(default, skip_serializing_if = "Option::is_none")]
35
    pub image_archs: Option<std::collections::BTreeMap<String, String>>,
4cf0c99a Andy McCall ↶ 36
    /// Whether the runner fetches a job's image from the hub when it lacks
37
    /// it (oxygenflow#39): the hub may then offer it jobs whose image only
38
    /// the hub holds.
39
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
40
    pub fetches_images: bool,
1daca0b6 Andy McCall ↶ 41
    /// The jobs this runner holds now: running, or finished with a result
42
    /// not yet reported. The hub ends any other job it has as running on
43
    /// this runner, which the runner lost by restarting or never received
44
    /// (oxygenhub#71). Absent: the runner does not say.
45
    #[serde(default, skip_serializing_if = "Option::is_none")]
46
    pub holding: Option<Vec<i64>>,
62829d15 Andy McCall ↶ 47
    /// What the runner measured about itself just now (spec §11.1,
48
    /// docs/jetstream.md §6). Absent: an older runner.
49
    #[serde(default, skip_serializing_if = "Option::is_none")]
50
    pub facts: Option<Facts>,
b14aeaae Andy McCall ↶ 51
    /// Where this runner serves image chunks to its peers (docs/jetstream.md
52
    /// §8.1). Absent: it is not in a swarm.
53
    #[serde(default, skip_serializing_if = "Option::is_none")]
54
    pub swarm: Option<SwarmAddr>,
82cf6e91 Andy McCall ↶ 55
    /// The build caches this runner holds a disk of (oxygenflow#51), each
56
    /// [`cache_slot`] of a repository and job, so the hub can send a job
57
    /// where its cache is. Absent: an older runner.
58
    #[serde(default, skip_serializing_if = "Option::is_none")]
59
    pub caches: Option<Vec<String>>,
1e6b9fb1 Andy McCall ↶ 60
    /// When each of [`ClaimRequest::caches`] last kept a disk, Unix ms, so
61
    /// the hub can send a job to the runner whose copy is freshest when
62
    /// several hold one (oxygenflow#54). Absent: an older runner.
63
    #[serde(default, skip_serializing_if = "Option::is_none")]
64
    pub cache_times: Option<std::collections::BTreeMap<String, u64>>,
82cf6e91 Andy McCall ↶ 65
}
66
67
/// A name safe as one path segment: kept readable, with a short hash so
68
/// two names that clean up alike stay apart. The build cache's pool is laid
69
/// out by these (oxygenflow#28).
70
pub fn segment(s: &str) -> String {
71
    let clean: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).take(48).collect();
72
    format!("{clean}-{}", &blake3::hash(s.as_bytes()).to_hex()[..8])
73
}
74
75
/// Where a repository's job keeps its build caches, as runners report
76
/// them in [`ClaimRequest::caches`] (oxygenflow#51): `repo/job`, each part
77
/// a [`segment`].
78
pub fn cache_slot(repo: &str, job: &str) -> String {
79
    format!("{}/{}", segment(repo), segment(job))
b14aeaae Andy McCall ↶ 80
}
81
ecce3719 Andy McCall ↶ 82
/// A runner's place in the image swarm: the address peers reach it on,
83
/// the site it is in (peers are only ever in the same site), and the
84
/// BLAKE3 of its TLS certificate, which peers check it by.
b14aeaae Andy McCall ↶ 85
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
86
pub struct SwarmAddr {
87
    pub addr: String,
88
    #[serde(default)]
89
    pub site: String,
ecce3719 Andy McCall ↶ 90
    #[serde(default)]
91
    pub cert: String,
b14aeaae Andy McCall ↶ 92
}
93
94
/// `POST /flow/swarm/announce`: a runner starting, continuing or ending a
95
/// fetch of `image`.
96
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
97
pub struct Announce {
98
    pub image: String,
99
    /// `fetching`, `done` or `stopped`.
100
    pub state: String,
101
}
102
103
/// The hub's answer to an announce: the peers to ask, and the ticket that
104
/// admits this runner to them.
105
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
106
pub struct Announced {
107
    pub ticket: String,
108
    pub peers: Vec<SwarmPeer>,
109
    /// Announce again after this many seconds while still fetching.
110
    pub interval_s: u64,
111
}
112
113
/// A peer in the swarm for one image.
114
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
115
pub struct SwarmPeer {
116
    pub runner: i64,
117
    pub name: String,
118
    pub addr: String,
ecce3719 Andy McCall ↶ 119
    /// The BLAKE3 of its TLS certificate: a peer that shows another is not
120
    /// this runner.
121
    pub cert: String,
b14aeaae Andy McCall ↶ 122
    /// It holds the whole image (rather than fetching it now).
123
    pub complete: bool,
62829d15 Andy McCall ↶ 124
}
125
126
/// A runner's own measurements, sent with every claim (spec §11.1): cheap
127
/// ones taken each time, the speed from a short benchmark run at start and
128
/// again while idle. Whole numbers, so a claim compares exactly.
129
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
130
pub struct Facts {
131
    /// Free disk where jobs' disks are made, in MiB.
132
    #[serde(default, skip_serializing_if = "Option::is_none")]
133
    pub free_disk_mib: Option<u64>,
134
    /// The 1-minute load average, times 100.
135
    #[serde(default, skip_serializing_if = "Option::is_none")]
136
    pub load_x100: Option<u32>,
137
    /// The benchmark's score: 100 on the reference machine (Earth), twice
138
    /// as fast scoring 200.
139
    #[serde(default, skip_serializing_if = "Option::is_none")]
140
    pub speed: Option<u32>,
141
    /// The speed class, 1 (slow) to 5 (fast); each class twice the one
142
    /// below (spec §11.1).
143
    #[serde(default, skip_serializing_if = "Option::is_none")]
144
    pub speed_class: Option<u8>,
145
    /// The kernel release.
146
    #[serde(default, skip_serializing_if = "Option::is_none")]
147
    pub kernel: Option<String>,
148
}
149
150
impl Facts {
151
    /// The class of a speed score: 3 for the reference machine's 100, each
152
    /// class a factor of two.
153
    pub fn class_of(speed: u32) -> u8 {
154
        match speed {
155
            0..=34 => 1,
156
            35..=69 => 2,
157
            70..=139 => 3,
158
            140..=279 => 4,
159
            _ => 5,
160
        }
161
    }
f98a8f78 Andy McCall ↶ 162
}
163
164
/// A runner's description: shown on the hub's Runners page, and what
165
/// scheduling by label and architecture will match.
166
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
167
pub struct RunnerInfo {
168
    /// `x86_64`, `aarch64`, `riscv64`, …
169
    pub arch: String,
170
    pub os: String,
171
    /// The `flow` version.
172
    pub version: String,
173
    /// From flow.toml `[runner] labels`.
174
    #[serde(default)]
175
    pub labels: Vec<String>,
176
    /// Jobs at once, and the memory (MiB) and vCPUs they share.
177
    pub max_jobs: u32,
178
    #[serde(default)]
179
    pub memory_mib: Option<u32>,
180
    #[serde(default)]
181
    pub cpus: Option<u32>,
182
}
183
184
impl RunnerInfo {
185
    /// This machine and build, with the given labels and capacity.
186
    pub fn here(labels: Vec<String>, max_jobs: u32, memory_mib: Option<u32>, cpus: Option<u32>) -> RunnerInfo {
187
        RunnerInfo {
188
            arch: std::env::consts::ARCH.into(),
189
            os: std::env::consts::OS.into(),
190
            version: env!("CARGO_PKG_VERSION").into(),
191
            labels,
192
            max_jobs,
193
            memory_mib,
194
            cpus,
195
        }
196
    }
197
}
198
199
/// `POST /api/v1/flow/runners/register`: exchange a one-time registration
200
/// token from the hub for a runner credential, binding the runner's
201
/// signing identity to it.
202
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
203
pub struct Register {
204
    pub token: String,
205
    pub name: String,
206
    /// The runner's Oxygen identity, hex of its encoding: its key signs
207
    /// every receipt, and the hub accepts no other for this runner.
208
    pub identity: String,
209
    pub info: RunnerInfo,
210
}
211
212
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
213
pub struct Registered {
214
    pub id: i64,
215
    pub name: String,
216
    /// The runner's bearer token from now on; shown once.
217
    pub credential: String,
e0918b88 Andy McCall 218
}
219
c23d5191 Andy McCall ↶ 220
/// A pinned subrepo to put in the workspace: `repo`'s state `heads`, at `path`.
221
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
222
pub struct SubrepoInput {
223
    pub path: String,
224
    /// `owner/name` on the hub.
225
    pub repo: String,
226
    pub clone_url: String,
227
    pub heads: Vec<String>,
228
}
229
e2c12561 Andy McCall ↶ 230
/// A secret for a job, as the hub supplies it (spec §9): written by the
231
/// runner at `path` in the sandbox, 0400, on an in-memory mount; never in
232
/// the environment, the receipt or an artifact.
233
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
234
pub struct SecretInput {
235
    pub name: String,
236
    pub path: String,
237
    pub value: String,
238
}
239
e0918b88 Andy McCall 240
/// A claimed job: everything the runner needs, nothing more.
241
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
242
pub struct Claim {
243
    pub job_id: i64,
244
    pub run_id: i64,
245
    /// `owner/name`.
246
    pub repo: String,
247
    /// Where to fetch the repository from (`oxy` wire protocol).
248
    pub clone_url: String,
249
    /// Read access to this repository only, until the job finishes.
250
    pub token: String,
251
    /// The state to build, as full change hashes.
252
    pub heads: Vec<String>,
253
    /// Hex BLAKE3 of the canonical pipeline.
254
    pub pipeline_hash: String,
255
    pub job: Job,
256
    pub sandbox: Sandbox,
257
    /// The hub's limit for this job.
258
    pub timeout_s: u64,
c23d5191 Andy McCall ↶ 259
    /// Subrepos the state pins (Oxygen spec §7.8) that the job may read,
260
    /// fetched with the same token and written at their paths.
261
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
262
    pub subrepos: Vec<SubrepoInput>,
c4285535 Andy McCall ↶ 263
    /// The state's hash on the hub (what checks are keyed by).
264
    #[serde(default, skip_serializing_if = "String::is_empty")]
265
    pub state: String,
266
    /// The bookmark the run is for.
267
    #[serde(default, skip_serializing_if = "String::is_empty")]
268
    pub bookmark: String,
269
    /// The run's number within its repository.
270
    #[serde(default)]
271
    pub run_number: i64,
c58efc6a Andy McCall ↶ 272
    /// Variables the hub holds for the repository (its site's, its
273
    /// organisation's and its own, inner overriding outer; oxygenhub#102).
274
    /// Set under `FLOW_*` and under the pipeline's own `env`, so they are
275
    /// part of the job's environment and of its receipt. Never secrets:
276
    /// those are mounted, not put in the environment (spec §9).
277
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
278
    pub env: std::collections::BTreeMap<String, String>,
e2c12561 Andy McCall ↶ 279
    /// The secrets the job declares (`secret` blocks), as the hub holds
280
    /// them for the repository (oxygenhub#107).
281
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
282
    pub secrets: Vec<SecretInput>,
46fe2c81 Andy McCall ↶ 283
    /// The job's inputs (oxygenflow#58), in the job's order, each with the
284
    /// blob the producing job's receipt names: fetched from
285
    /// `/api/v1/flow/jobs/{job_id}/inputs/{index}` and checked against it.
286
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
287
    pub inputs: Vec<ArtifactInput>,
1b160d37 Andy McCall ↶ 288
    /// How long the job is expected to take, from its recent passing runs,
289
    /// when the hub has learned it (#76): a runner leaving with some notice
290
    /// finishes a job whose rest fits it and hands back the others.
291
    #[serde(default, skip_serializing_if = "Option::is_none")]
292
    pub expected_ms: Option<u64>,
f201e1bc Andy McCall ↶ 293
    /// The checkpoint an earlier attempt saved before its runner handed the
294
    /// job back (oxygenflow#77): the blob to fetch from
295
    /// `/api/v1/flow/jobs/{job_id}/checkpoint` and check, then restore
296
    /// before the job runs.
297
    #[serde(default, skip_serializing_if = "Option::is_none")]
298
    pub checkpoint: Option<String>,
46fe2c81 Andy McCall ↶ 299
}
300
301
/// An artifact a job takes (oxygenflow#58), as the hub hands it over.
302
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
303
pub struct ArtifactInput {
304
    pub artifact: String,
305
    /// The producing job.
306
    pub from: String,
307
    /// Where it goes, under `/src`.
308
    pub path: String,
309
    /// The Oxygen blob reference its receipt names, hex.
310
    pub blob: String,
c4285535 Andy McCall ↶ 311
}
312
313
impl Claim {
314
    /// What a job is told about what it builds (docs/m0.md §4):
315
    /// `FLOW_REPO`, `FLOW_STATE`, `FLOW_HEADS` (full hashes joined with
316
    /// `+`), `FLOW_BOOKMARK`, `FLOW_RUN` and `FLOW_JOB`. Unknown values are
317
    /// left out.
318
    pub fn flow_env(&self) -> Vec<(String, String)> {
319
        let mut v = vec![
320
            ("FLOW_REPO".to_string(), self.repo.clone()),
321
            ("FLOW_HEADS".to_string(), self.heads.join("+")),
322
            ("FLOW_JOB".to_string(), self.job.name.clone()),
323
        ];
324
        if !self.state.is_empty() {
325
            v.push(("FLOW_STATE".into(), self.state.clone()));
326
        }
327
        if !self.bookmark.is_empty() {
328
            v.push(("FLOW_BOOKMARK".into(), self.bookmark.clone()));
329
        }
330
        if self.run_number > 0 {
331
            v.push(("FLOW_RUN".into(), self.run_number.to_string()));
332
        }
c58efc6a Andy McCall ↶ 333
        for (k, val) in &self.env {
334
            if !v.iter().any(|(n, _)| n == k) {
335
                v.push((k.clone(), val.clone()));
336
            }
337
        }
c4285535 Andy McCall ↶ 338
        v
339
    }
e0918b88 Andy McCall 340
}
341
342
/// One line of output (docs/m0.md §2).
343
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
344
pub struct Record {
345
    /// Milliseconds since the job started.
346
    pub t: u64,
347
    /// `out`, `err`, `console` (the VM outside the job) or `flow` (the runner).
348
    pub stream: String,
349
    pub text: String,
350
}
351
b11e30f5 Andy McCall ↶ 352
/// `POST /api/v1/flow/jobs/{id}/decline` (spec §11.5): the runner will
353
/// not run a job it was handed, and says why. The hub queues the job
354
/// again and offers it to this runner no more until its profile changes.
355
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
356
pub struct Decline {
357
    pub reason: String,
358
}
359
e0918b88 Andy McCall 360
/// `POST /api/v1/flow/jobs/{id}/log`.
361
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
362
pub struct LogBatch {
363
    pub records: Vec<Record>,
364
}
365
366
/// `POST /api/v1/flow/jobs/{id}/finish`.
367
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
368
pub struct Finish {
369
    /// The job's exit code; absent when the runner could not run it.
370
    pub exit_code: Option<i32>,
371
    pub duration_ms: u64,
372
    pub receipt: Option<Receipt>,
47c1d64d Andy McCall ↶ 373
    /// The receipt bound to the job's state and signed by the runner
374
    /// (Oxygen spec §14.6), hex of the signed receipt's bytes.
375
    #[serde(default, skip_serializing_if = "Option::is_none")]
376
    pub signed_receipt: Option<String>,
e0918b88 Andy McCall 377
    /// Why the runner could not run the job (rootfs missing, VM failed).
378
    pub error: Option<String>,
8f211e20 Andy McCall ↶ 379
    /// The most disk the job's disks and workspace took, in MiB, and the
380
    /// most memory its sandbox held (oxygenflow#41): the hub learns from
381
    /// them what the job's next run needs.
382
    #[serde(default, skip_serializing_if = "Option::is_none")]
383
    pub peak_disk_mib: Option<u64>,
384
    #[serde(default, skip_serializing_if = "Option::is_none")]
385
    pub peak_memory_mib: Option<u64>,
e0918b88 Andy McCall 386
}
387
388
/// Longest text of one record the hub keeps; longer lines are cut.
389
pub const MAX_RECORD_TEXT: usize = 16 * 1024;
390
/// Most records the hub keeps per job; later ones are dropped with a note.
391
pub const MAX_RECORDS: usize = 50_000;