runnerd-core 0.1.5

Config, domain logic and API types shared by runnerd and its clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! The build cache's HTTP on a runner's socket: each tool's paths mapped to entries of the runner's repository, the
//! lookups and uploads counted for that runner. Every path a tool may use is an entry's; nothing reads or writes
//! outside the repository's entries. It must not log a request's headers, which may carry a tool's token.

use std::convert::Infallible;
use std::io;
use std::path::PathBuf;
use std::sync::Arc;

use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::{BodyExt, Empty, StreamBody};
use hyper::body::{Bytes, Frame, Incoming};
use hyper::header::CONTENT_LENGTH;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
use tokio::sync::watch;
use tracing::debug;

use super::{Inner, Upload, Writes, charge, valid_segment};
use crate::sync::lock;

pub(super) type Body = UnsyncBoxBody<Bytes, io::Error>;

/// The tools whose requests it answers, each with the path of its API before its keys: `/<tool>/<api><key>`. Each
/// reads with `GET`, a 404 being a miss, and writes with `PUT`; Bazel's keys are `ac/<sha256>` and `cas/<sha256>`,
/// sccache's `<a>/<b>/<c>/<key>`, Turborepo's and Nx's a task's hash. An entry's path leaves out the API's:
/// `<tool>/<key>`.
const TOOLS: [(&str, &str); 5] = [
    ("gradle", ""),
    ("sccache", ""),
    ("bazel", ""),
    (super::turbo::TOOL, "v8/artifacts/"),
    ("nx", "v1/cache/"),
];

/// Path segments a key may have at most: sccache's take four.
const MAX_SEGMENTS: usize = 8;

/// How much of an entry a read sends at a time.
const CHUNK: usize = 64 << 10;

/// Serves one connection of `runner`'s until either end closes it.
pub(super) async fn connection(inner: Arc<Inner>, runner: String, stream: UnixStream) {
    let service = service_fn(move |request| {
        let inner = inner.clone();
        let runner = runner.clone();
        async move { Ok::<_, Infallible>(handle(&inner, &runner, request).await) }
    });
    if let Err(error) = http1::Builder::new()
        .serve_connection(TokioIo::new(stream), service)
        .await
    {
        debug!("a build cache connection ended: {error}");
    }
}

async fn handle(inner: &Arc<Inner>, runner: &str, request: Request<Incoming>) -> Response<Body> {
    let Some(repository) = lock(&inner.state)
        .runners
        .get(runner)
        .map(|open| open.repository.clone())
    else {
        return status(StatusCode::SERVICE_UNAVAILABLE);
    };
    let path = request.uri().path().trim_start_matches('/').to_owned();
    if path.starts_with(super::actions::TWIRP) || path.starts_with(super::actions::BLOBS) {
        return super::actions::handle(inner, runner, request).await;
    }
    if (path == super::turbo::TOOL || path.starts_with("turbo/")) && super::turbo::foreign(&request)
    {
        return super::turbo::pass(inner, request).await;
    }
    if let Some(endpoint) = path.strip_prefix(super::turbo::API)
        && super::turbo::ENDPOINTS.contains(&endpoint)
    {
        return super::turbo::handle(inner, &repository, endpoint, request).await;
    }
    let Some((tool, rest)) = path.split_once('/').and_then(|(name, rest)| {
        let (tool, api) = TOOLS.iter().find(|(tool, _)| *tool == name)?;
        Some((*tool, rest.strip_prefix(api)?))
    }) else {
        return status(StatusCode::NOT_FOUND);
    };
    let segments: Vec<&str> = rest.split('/').collect();
    if segments.len() > MAX_SEGMENTS || !segments.iter().all(|segment| valid_segment(segment)) {
        return status(StatusCode::NOT_FOUND);
    }
    let mut entry = PathBuf::from(&repository);
    entry.push(tool);
    entry.extend(&segments);
    // A tool's own probe, such as sccache's `.sccache_check`, is not a lookup of a build's.
    let counted = !segments.last().is_some_and(|last| last.starts_with('.'));
    match *request.method() {
        Method::GET => read(inner, runner, entry, counted, ReadKind::Body).await,
        Method::HEAD => read(inner, runner, entry, false, ReadKind::Head).await,
        Method::PUT => write(inner, runner, entry, request.into_body()).await,
        _ => status(StatusCode::METHOD_NOT_ALLOWED),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReadKind {
    Body,
    Head,
}

async fn read(
    inner: &Inner,
    runner: &str,
    entry: PathBuf,
    counted: bool,
    kind: ReadKind,
) -> Response<Body> {
    let known = lock(&inner.state).entries.contains_key(&entry);
    let file = if known {
        tokio::fs::File::open(inner.root.join(&entry)).await.ok()
    } else {
        None
    };
    // The file's own length: an upload stored meanwhile may have replaced the entry the index knew.
    let opened = match file {
        Some(file) => file
            .metadata()
            .await
            .ok()
            .map(|metadata| (file, metadata.len())),
        None => None,
    };
    let Some((file, bytes)) = opened else {
        if counted && let Some(open) = lock(&inner.state).runners.get_mut(runner) {
            open.counts.misses += 1;
        }
        return status(StatusCode::NOT_FOUND);
    };
    if counted {
        if let Some(open) = lock(&inner.state).runners.get_mut(runner) {
            open.counts.hits += 1;
            open.counts.read_bytes += bytes;
        }
        inner.touch(&entry);
    }
    let body = match kind {
        ReadKind::Head => Empty::new().map_err(|never| match never {}).boxed_unsync(),
        ReadKind::Body => {
            let chunks = futures_util::stream::unfold(file, |mut file| async move {
                let mut chunk = vec![0; CHUNK];
                match file.read(&mut chunk).await {
                    Ok(0) => None,
                    Ok(read) => {
                        chunk.truncate(read);
                        Some((Ok(Frame::data(Bytes::from(chunk))), file))
                    }
                    Err(error) => Some((Err(error), file)),
                }
            });
            BodyExt::boxed_unsync(StreamBody::new(chunks))
        }
    };
    let mut response = Response::new(body);
    response.headers_mut().insert(CONTENT_LENGTH, bytes.into());
    response
}

async fn write(inner: &Inner, runner: &str, entry: PathBuf, body: Incoming) -> Response<Body> {
    use hyper::body::Body as _;

    let (writes, max_size) = {
        let state = lock(&inner.state);
        let writes = state.runners.get(runner).map(|open| open.writes.current());
        (writes, state.max_size)
    };
    let refused = || {
        if let Some(open) = lock(&inner.state).runners.get_mut(runner) {
            open.counts.refused += 1;
        }
        accepted()
    };
    // Bazel sends every blob of its outputs again, having no way to ask which the cache has.
    let length = body.size_hint().exact();
    let same = length.is_some_and(|length| {
        lock(&inner.state)
            .entries
            .get(&entry)
            .is_some_and(|known| known.bytes == length)
    });
    if same && writes == Some(Writes::Allowed) {
        drain(body).await;
        // Still in use, though only ever sent again: Bazel's blobs an action's result needs.
        inner.touch(&entry);
        return accepted();
    }
    match writes {
        None => return status(StatusCode::SERVICE_UNAVAILABLE),
        // Read in full and dropped: a tool whose upload is cut off may stop using the cache for the rest of the
        // build.
        Some(Writes::Refused) => {
            drain(body).await;
            return refused();
        }
        Some(Writes::Allowed | Writes::Undecided) => {}
    }
    let mut receiving = Receiving::new(inner, runner, max_size, Purpose::Build);
    match receive(&mut receiving, body).await {
        Ok(true) => {}
        Ok(false) => return refused(),
        Err(error) => {
            debug!("{runner}: a build cache upload failed: {error}");
            return status(StatusCode::INTERNAL_SERVER_ERROR);
        }
    }
    let upload = receiving.into_upload(entry);
    let (writes, upload) = {
        let mut state = lock(&inner.state);
        match state.runners.get_mut(runner) {
            Some(open) => match open.writes.hold(upload) {
                Ok(()) => return accepted(),
                Err(upload) => (Some(open.writes.current()), upload),
            },
            None => (None, upload),
        }
    };
    if writes == Some(Writes::Allowed) {
        // Renames: quick, and on the daemon's own file system.
        inner.store(runner, upload);
        accepted()
    } else {
        inner.remove_uploads(Some(runner), &[upload]);
        refused()
    }
}

/// What an upload is for, which says whether its runner's decision still lets it in.
#[derive(Debug, Clone, Copy)]
pub(super) enum Purpose {
    /// A tool's entry: kept unless the job may not write.
    Build,
    /// A block or the archive of GitHub Actions cache save `id`: kept while the save takes uploads.
    Save(u64),
}

/// An upload being received. Unless it becomes an `Upload`, its file goes and the uploads' room it took is given
/// back, also when its connection is cut midway, as when its runner is removed.
pub(super) struct Receiving<'inner> {
    inner: &'inner Inner,
    runner: &'inner str,
    file: PathBuf,
    bytes: u64,
    /// The uploads' room it took: what its bytes count for (`charge`).
    room: u64,
    /// The size limit when it started.
    max_size: u64,
    purpose: Purpose,
    /// Changes when its runner's writes are decided; `None` when its runner is not open.
    decided: Option<watch::Receiver<()>>,
}

impl<'inner> Receiving<'inner> {
    /// An upload of `runner`'s for `purpose` to a new file of the uploads' directory, under the size limit `max_size`
    /// it started with.
    pub(super) fn new(
        inner: &'inner Inner,
        runner: &'inner str,
        max_size: u64,
        purpose: Purpose,
    ) -> Receiving<'inner> {
        let (file, decided) = {
            let mut state = lock(&inner.state);
            state.next_upload += 1;
            let decided = state
                .runners
                .get(runner)
                .map(|open| open.decided.subscribe());
            (inner.uploads.join(state.next_upload.to_string()), decided)
        };
        Receiving {
            inner,
            runner,
            file,
            bytes: 0,
            room: 0,
            max_size,
            purpose,
            decided,
        }
    }

    /// Whether its runner's decision, as far as it is made, still lets it in.
    fn wanted(&self) -> bool {
        lock(&self.inner.state)
            .runners
            .get(self.runner)
            .is_some_and(|open| match self.purpose {
                Purpose::Build => open.writes.current() != Writes::Refused,
                Purpose::Save(id) => super::actions::takes_uploads(&open.saves, id),
            })
    }

    /// Takes the room `length` more bytes need, unless the upload would pass a quarter of the size limit, as no entry
    /// may, or the uploads' room runs out.
    fn grow(&mut self, length: u64) -> bool {
        let bytes = self.bytes + length;
        let more = charge(bytes).saturating_sub(self.room);
        if bytes > self.max_size / 4
            || more > 0 && !self.inner.reserve(self.runner, more, self.max_size)
        {
            return false;
        }
        self.bytes = bytes;
        self.room += more;
        true
    }

    /// Removes its file and gives back its room now, before the rest of its body is read and dropped: a sender that
    /// stalls holds nothing. Its file must be closed first.
    fn give_up(&mut self) {
        let _ = std::fs::remove_file(&self.file);
        self.inner.release(Some(self.runner), self.room);
        self.file = PathBuf::new();
        self.bytes = 0;
        self.room = 0;
    }

    pub(super) fn into_upload(mut self, entry: PathBuf) -> Upload {
        Upload {
            file: std::mem::take(&mut self.file),
            entry,
            bytes: std::mem::take(&mut self.bytes),
            room: std::mem::take(&mut self.room),
        }
    }
}

impl Drop for Receiving<'_> {
    fn drop(&mut self) {
        if !self.file.as_os_str().is_empty() {
            let _ = std::fs::remove_file(&self.file);
            self.inner.release(Some(self.runner), self.room);
        }
    }
}

/// Writes the body to the upload's file; false once it passes a quarter of the size limit, the uploads' room runs out
/// or its runner's decision no longer lets it in, which it heeds while the body stalls too. An empty body takes room
/// too, before its file is made.
pub(super) async fn receive(receiving: &mut Receiving<'_>, mut body: Incoming) -> io::Result<bool> {
    let mut decided = receiving.decided.take();
    // After subscribing: a decision made since is seen here or by `decided`.
    if !receiving.wanted() || !receiving.grow(0) {
        receiving.give_up();
        drain(body).await;
        return Ok(false);
    }
    let mut out = tokio::fs::File::create(&receiving.file).await?;
    loop {
        tokio::select! {
            frame = body.frame() => {
                let Some(frame) = frame else {
                    break;
                };
                let frame = frame.map_err(io::Error::other)?;
                if let Ok(data) = frame.into_data() {
                    if !receiving.grow(data.len() as u64) {
                        close(out).await;
                        receiving.give_up();
                        drain(body).await;
                        return Ok(false);
                    }
                    out.write_all(&data).await?;
                }
            }
            Some(Ok(())) = changed(&mut decided) => {
                if !receiving.wanted() {
                    close(out).await;
                    receiving.give_up();
                    drain(body).await;
                    return Ok(false);
                }
            }
        }
    }
    out.flush().await?;
    Ok(true)
}

/// Closes an upload's file once its writes in flight end: removed while open, its blocks stay taken until then.
async fn close(out: tokio::fs::File) {
    drop(out.into_std().await);
}

/// Waits for `decided` to change; `None` at once without one.
async fn changed(
    decided: &mut Option<watch::Receiver<()>>,
) -> Option<Result<(), watch::error::RecvError>> {
    Some(decided.as_mut()?.changed().await)
}

pub(super) async fn drain(mut body: Incoming) {
    while let Some(Ok(_)) = body.frame().await {}
}

/// What an upload gets, stored or not: a tool told its upload failed may stop using the cache for the rest of the
/// build, reads included.
fn accepted() -> Response<Body> {
    status(StatusCode::OK)
}

pub(super) fn status(code: StatusCode) -> Response<Body> {
    let mut response = Response::new(Empty::new().map_err(|never| match never {}).boxed_unsync());
    *response.status_mut() = code;
    response
}