OXYGENHUB
# 3e3cc9475ab3 oxygenflow / crates / flow-core / src / api.rs
12.4 KiB · Rust · last changed Jetstream: runners share images peer to peer 23 days ago source blame history raw
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>,
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>,
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>,
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>>,
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>>,
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,
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>>,
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>,
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>,
55
}
56
57
/// A runner's place in the image swarm: the address peers reach it on and
58
/// the site it is in; peers are only ever in the same site.
59
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
60
pub struct SwarmAddr {
61
    pub addr: String,
62
    #[serde(default)]
63
    pub site: String,
64
}
65
66
/// `POST /flow/swarm/announce`: a runner starting, continuing or ending a
67
/// fetch of `image`.
68
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69
pub struct Announce {
70
    pub image: String,
71
    /// `fetching`, `done` or `stopped`.
72
    pub state: String,
73
}
74
75
/// The hub's answer to an announce: the peers to ask, and the ticket that
76
/// admits this runner to them.
77
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
78
pub struct Announced {
79
    pub ticket: String,
80
    pub peers: Vec<SwarmPeer>,
81
    /// Announce again after this many seconds while still fetching.
82
    pub interval_s: u64,
83
}
84
85
/// A peer in the swarm for one image.
86
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
87
pub struct SwarmPeer {
88
    pub runner: i64,
89
    pub name: String,
90
    pub addr: String,
91
    /// It holds the whole image (rather than fetching it now).
92
    pub complete: bool,
93
}
94
95
/// A runner's own measurements, sent with every claim (spec §11.1): cheap
96
/// ones taken each time, the speed from a short benchmark run at start and
97
/// again while idle. Whole numbers, so a claim compares exactly.
98
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
99
pub struct Facts {
100
    /// Free disk where jobs' disks are made, in MiB.
101
    #[serde(default, skip_serializing_if = "Option::is_none")]
102
    pub free_disk_mib: Option<u64>,
103
    /// The 1-minute load average, times 100.
104
    #[serde(default, skip_serializing_if = "Option::is_none")]
105
    pub load_x100: Option<u32>,
106
    /// The benchmark's score: 100 on the reference machine (Earth), twice
107
    /// as fast scoring 200.
108
    #[serde(default, skip_serializing_if = "Option::is_none")]
109
    pub speed: Option<u32>,
110
    /// The speed class, 1 (slow) to 5 (fast); each class twice the one
111
    /// below (spec §11.1).
112
    #[serde(default, skip_serializing_if = "Option::is_none")]
113
    pub speed_class: Option<u8>,
114
    /// The kernel release.
115
    #[serde(default, skip_serializing_if = "Option::is_none")]
116
    pub kernel: Option<String>,
117
}
118
119
impl Facts {
120
    /// The class of a speed score: 3 for the reference machine's 100, each
121
    /// class a factor of two.
122
    pub fn class_of(speed: u32) -> u8 {
123
        match speed {
124
            0..=34 => 1,
125
            35..=69 => 2,
126
            70..=139 => 3,
127
            140..=279 => 4,
128
            _ => 5,
129
        }
130
    }
131
}
132
133
/// A runner's description: shown on the hub's Runners page, and what
134
/// scheduling by label and architecture will match.
135
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
136
pub struct RunnerInfo {
137
    /// `x86_64`, `aarch64`, `riscv64`, …
138
    pub arch: String,
139
    pub os: String,
140
    /// The `flow` version.
141
    pub version: String,
142
    /// From flow.toml `[runner] labels`.
143
    #[serde(default)]
144
    pub labels: Vec<String>,
145
    /// Jobs at once, and the memory (MiB) and vCPUs they share.
146
    pub max_jobs: u32,
147
    #[serde(default)]
148
    pub memory_mib: Option<u32>,
149
    #[serde(default)]
150
    pub cpus: Option<u32>,
151
}
152
153
impl RunnerInfo {
154
    /// This machine and build, with the given labels and capacity.
155
    pub fn here(labels: Vec<String>, max_jobs: u32, memory_mib: Option<u32>, cpus: Option<u32>) -> RunnerInfo {
156
        RunnerInfo {
157
            arch: std::env::consts::ARCH.into(),
158
            os: std::env::consts::OS.into(),
159
            version: env!("CARGO_PKG_VERSION").into(),
160
            labels,
161
            max_jobs,
162
            memory_mib,
163
            cpus,
164
        }
165
    }
166
}
167
168
/// `POST /api/v1/flow/runners/register`: exchange a one-time registration
169
/// token from the hub for a runner credential, binding the runner's
170
/// signing identity to it.
171
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
172
pub struct Register {
173
    pub token: String,
174
    pub name: String,
175
    /// The runner's Oxygen identity, hex of its encoding: its key signs
176
    /// every receipt, and the hub accepts no other for this runner.
177
    pub identity: String,
178
    pub info: RunnerInfo,
179
}
180
181
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
182
pub struct Registered {
183
    pub id: i64,
184
    pub name: String,
185
    /// The runner's bearer token from now on; shown once.
186
    pub credential: String,
187
}
188
189
/// A pinned subrepo to put in the workspace: `repo`'s state `heads`, at `path`.
190
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
191
pub struct SubrepoInput {
192
    pub path: String,
193
    /// `owner/name` on the hub.
194
    pub repo: String,
195
    pub clone_url: String,
196
    pub heads: Vec<String>,
197
}
198
199
/// A secret for a job, as the hub supplies it (spec §9): written by the
200
/// runner at `path` in the sandbox, 0400, on an in-memory mount; never in
201
/// the environment, the receipt or an artifact.
202
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
203
pub struct SecretInput {
204
    pub name: String,
205
    pub path: String,
206
    pub value: String,
207
}
208
209
/// A claimed job: everything the runner needs, nothing more.
210
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
211
pub struct Claim {
212
    pub job_id: i64,
213
    pub run_id: i64,
214
    /// `owner/name`.
215
    pub repo: String,
216
    /// Where to fetch the repository from (`oxy` wire protocol).
217
    pub clone_url: String,
218
    /// Read access to this repository only, until the job finishes.
219
    pub token: String,
220
    /// The state to build, as full change hashes.
221
    pub heads: Vec<String>,
222
    /// Hex BLAKE3 of the canonical pipeline.
223
    pub pipeline_hash: String,
224
    pub job: Job,
225
    pub sandbox: Sandbox,
226
    /// The hub's limit for this job.
227
    pub timeout_s: u64,
228
    /// Subrepos the state pins (Oxygen spec §7.8) that the job may read,
229
    /// fetched with the same token and written at their paths.
230
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
231
    pub subrepos: Vec<SubrepoInput>,
232
    /// The state's hash on the hub (what checks are keyed by).
233
    #[serde(default, skip_serializing_if = "String::is_empty")]
234
    pub state: String,
235
    /// The bookmark the run is for.
236
    #[serde(default, skip_serializing_if = "String::is_empty")]
237
    pub bookmark: String,
238
    /// The run's number within its repository.
239
    #[serde(default)]
240
    pub run_number: i64,
241
    /// Variables the hub holds for the repository (its site's, its
242
    /// organisation's and its own, inner overriding outer; oxygenhub#102).
243
    /// Set under `FLOW_*` and under the pipeline's own `env`, so they are
244
    /// part of the job's environment and of its receipt. Never secrets:
245
    /// those are mounted, not put in the environment (spec §9).
246
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
247
    pub env: std::collections::BTreeMap<String, String>,
248
    /// The secrets the job declares (`secret` blocks), as the hub holds
249
    /// them for the repository (oxygenhub#107).
250
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
251
    pub secrets: Vec<SecretInput>,
252
}
253
254
impl Claim {
255
    /// What a job is told about what it builds (docs/m0.md §4):
256
    /// `FLOW_REPO`, `FLOW_STATE`, `FLOW_HEADS` (full hashes joined with
257
    /// `+`), `FLOW_BOOKMARK`, `FLOW_RUN` and `FLOW_JOB`. Unknown values are
258
    /// left out.
259
    pub fn flow_env(&self) -> Vec<(String, String)> {
260
        let mut v = vec![
261
            ("FLOW_REPO".to_string(), self.repo.clone()),
262
            ("FLOW_HEADS".to_string(), self.heads.join("+")),
263
            ("FLOW_JOB".to_string(), self.job.name.clone()),
264
        ];
265
        if !self.state.is_empty() {
266
            v.push(("FLOW_STATE".into(), self.state.clone()));
267
        }
268
        if !self.bookmark.is_empty() {
269
            v.push(("FLOW_BOOKMARK".into(), self.bookmark.clone()));
270
        }
271
        if self.run_number > 0 {
272
            v.push(("FLOW_RUN".into(), self.run_number.to_string()));
273
        }
274
        for (k, val) in &self.env {
275
            if !v.iter().any(|(n, _)| n == k) {
276
                v.push((k.clone(), val.clone()));
277
            }
278
        }
279
        v
280
    }
281
}
282
283
/// One line of output (docs/m0.md §2).
284
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
285
pub struct Record {
286
    /// Milliseconds since the job started.
287
    pub t: u64,
288
    /// `out`, `err`, `console` (the VM outside the job) or `flow` (the runner).
289
    pub stream: String,
290
    pub text: String,
291
}
292
293
/// `POST /api/v1/flow/jobs/{id}/decline` (spec §11.5): the runner will
294
/// not run a job it was handed, and says why. The hub queues the job
295
/// again and offers it to this runner no more until its profile changes.
296
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
297
pub struct Decline {
298
    pub reason: String,
299
}
300
301
/// `POST /api/v1/flow/jobs/{id}/log`.
302
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
303
pub struct LogBatch {
304
    pub records: Vec<Record>,
305
}
306
307
/// `POST /api/v1/flow/jobs/{id}/finish`.
308
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
309
pub struct Finish {
310
    /// The job's exit code; absent when the runner could not run it.
311
    pub exit_code: Option<i32>,
312
    pub duration_ms: u64,
313
    pub receipt: Option<Receipt>,
314
    /// The receipt bound to the job's state and signed by the runner
315
    /// (Oxygen spec §14.6), hex of the signed receipt's bytes.
316
    #[serde(default, skip_serializing_if = "Option::is_none")]
317
    pub signed_receipt: Option<String>,
318
    /// Why the runner could not run the job (rootfs missing, VM failed).
319
    pub error: Option<String>,
320
}
321
322
/// Longest text of one record the hub keeps; longer lines are cut.
323
pub const MAX_RECORD_TEXT: usize = 16 * 1024;
324
/// Most records the hub keeps per job; later ones are dropped with a note.
325
pub const MAX_RECORDS: usize = 50_000;