forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

api.rs1343 lines, 48.4 KiBHistoryRawDownload
1//! Runner and job API under `/api/v1/ci` (see docs/ci.md, Runner protocol).
2//!
3//! Runners authenticate with `Authorization: Bearer <runner secret>`. A job's routes take
4//! `Authorization: Bearer <job token>`, which `job_by_token` accepts only while the job is Running.
5//! The job token also works as a read-only git credential, see `git_http::job_token_read`.
6//!
7//! Every response is JSON except the empty 204 of an empty claim and the body of a log append.
8
9use forge_ci::config::JobSpec;
10use forge_ci::mask::Masker;
11use forge_ci::proto::{
12 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
13 JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER,
14 RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart,
15 RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch,
16};
17use forge_core::Error as CoreError;
18use forge_core::ci::{
19 CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RunState, RunnerReport,
20};
21use futures_util::StreamExt;
22use http::header::HeaderValue;
23use serde_json::json;
24use std::collections::BTreeMap;
25use topcoat::context::{Cx, context};
26use topcoat::router::request::headers;
27use topcoat::router::response::Response;
28use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route};
29
30use crate::api::{self, Refusal};
31use crate::ci::{artifact_key, log_path};
32use crate::self_update;
33use crate::state::AppState;
34use crate::views::{bytes_text, https_clone_url};
35
36path_param!(job_id);
37path_param!(artifact_name);
38
39/// Header carrying the byte offset of a log chunk.
40const LOG_OFFSET_HEADER: &str = "x-forge-log-offset";
41/// Header on a 409 log response carrying the size the server has.
42const LOG_SIZE_HEADER: &str = "x-forge-log-size";
43/// Largest log chunk, in bytes.
44const MAX_LOG_CHUNK: usize = 1024 * 1024;
45/// Longest line the step scan waits for. A longer line with no newline is passed over, so a log
46/// with no newlines is not read again and again.
47const MAX_STEP_LINE: usize = 1024 * 1024;
48/// Largest JSON body on the runner routes, in bytes.
49const MAX_JSON_BODY: usize = 64 * 1024;
50/// Largest runner log batch, in bytes. A batch holds at most 1000 lines of up to 4 KiB each.
51const MAX_LOG_BATCH: usize = 1024 * 1024;
52/// Largest metrics batch read: 400 samples of about 150 bytes each fit well inside it.
53const MAX_METRICS_BATCH: usize = 256 * 1024;
54/// Most samples one metrics batch may carry.
55const MAX_METRICS_SAMPLES: usize = 400;
56/// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.
57const DEFAULT_RESERVE: u64 = 1 << 30;
58/// Longest runner name or label, in bytes.
59const MAX_NAME_BYTES: usize = 64;
60/// Most labels a runner may register.
61const MAX_LABELS: usize = 32;
62/// Text appended once when the log cap is reached.
63const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n";
64const MIB: u64 = 1024 * 1024;
65
66/// Bearer token from the `Authorization` header, or `None`.
67fn bearer_token(headers: &HeaderMap) -> Option<&str> {
68 let value = headers.get(http::header::AUTHORIZATION)?.to_str().ok()?;
69 let (scheme, rest) = value.split_once(' ')?;
70 if !scheme.eq_ignore_ascii_case("bearer") {
71 return None;
72 }
73 let token = rest.trim();
74 (!token.is_empty()).then_some(token)
75}
76
77fn unauthorized() -> Refusal {
78 Box::new(api::error(
79 StatusCode::UNAUTHORIZED,
80 "authentication required",
81 ))
82}
83
84/// The runner behind the Bearer secret. Disabled runners get 403.
85async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result<CiRunner, Refusal> {
86 let Some(secret) = bearer_token(headers) else {
87 return Err(unauthorized());
88 };
89 match state.store.runner_by_secret(secret).await {
90 Ok(Some(runner)) if runner.disabled => Err(Box::new(api::error(
91 StatusCode::FORBIDDEN,
92 "the runner is disabled",
93 ))),
94 Ok(Some(runner)) => {
95 crate::alerts::runner_seen(state, &runner.id).await;
96 // The stamp above is written, so a page that reads it after the wake sees it.
97 state.ci_live.note_runner_online(&runner.id, true);
98 Ok(runner)
99 }
100 Ok(None) => Err(unauthorized()),
101 Err(e) => Err(api::internal(e)),
102 }
103}
104
105/// The job behind the Bearer job token. Only Running jobs match, so a finished job gets 401.
106async fn job_from(state: &AppState, headers: &HeaderMap, job_id: &str) -> Result<CiJob, Refusal> {
107 let Some(token) = bearer_token(headers) else {
108 return Err(unauthorized());
109 };
110 match state.store.job_by_token(job_id, token).await {
111 Ok(Some(job)) => Ok(job),
112 Ok(None) => Err(unauthorized()),
113 Err(e) => Err(api::internal(e)),
114 }
115}
116
117/// Parses a JSON body of at most [`MAX_JSON_BODY`] bytes.
118async fn json_body<T: serde::de::DeserializeOwned>(body: Body) -> Result<T, Refusal> {
119 let bytes = api::read_body(body, MAX_JSON_BODY).await?;
120 serde_json::from_slice(&bytes).map_err(|e| {
121 Box::new(api::error(
122 StatusCode::BAD_REQUEST,
123 &format!("invalid JSON body: {e}"),
124 ))
125 })
126}
127
128fn valid_name(value: &str) -> bool {
129 !value.trim().is_empty() && value.len() <= MAX_NAME_BYTES && !value.contains(char::is_control)
130}
131
132/// `[A-Za-z0-9._+-]{1,128}`, and not starting with a dot.
133pub fn valid_artifact_name(name: &str) -> bool {
134 !name.is_empty()
135 && name.len() <= 128
136 && !name.starts_with('.')
137 && name
138 .bytes()
139 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-'))
140}
141
142// ---------------------------------------------------------------------------------------------
143// Registration and claims
144// ---------------------------------------------------------------------------------------------
145
146#[route(POST "/api/v1/ci/runners/register")]
147async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
148 let state = context::<AppState>(cx);
149 let request: RegisterRequest = match json_body(body).await {
150 Ok(request) => request,
151 Err(res) => return Ok(*res),
152 };
153 if !valid_name(&request.name) || request.labels.len() > MAX_LABELS {
154 return Ok(api::error(
155 StatusCode::UNPROCESSABLE_ENTITY,
156 "the runner name or labels are invalid",
157 ));
158 }
159 if request.labels.iter().any(|label| !valid_name(label)) {
160 return Ok(api::error(
161 StatusCode::UNPROCESSABLE_ENTITY,
162 "the runner name or labels are invalid",
163 ));
164 }
165 match state
166 .store
167 .register_runner(&request.token, request.name.trim(), &request.labels)
168 .await
169 {
170 Ok((runner, secret)) => {
171 state.ci_live.bump_runners();
172 let body = RegisterResponse {
173 runner_id: runner.id,
174 runner_secret: secret,
175 };
176 Ok(api::json(
177 StatusCode::CREATED,
178 &serde_json::to_value(&body).unwrap_or_default(),
179 ))
180 }
181 Err(CoreError::Invalid(_)) => Ok(api::error(
182 StatusCode::UNAUTHORIZED,
183 "the registration token is unknown, used or expired",
184 )),
185 Err(e) => Ok(*api::internal(e)),
186 }
187}
188
189#[route(POST "/api/v1/ci/runners/claim")]
190async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
191 let state = context::<AppState>(cx);
192 // The labels in the request are ignored: the labels stored at registration are used, plus the
193 // arch and OS the runner reports, so `runs_on = ["aarch64"]` needs no admin to type a label.
194 let mut runner = match runner_from(state, headers(cx)).await {
195 Ok(runner) => runner,
196 Err(res) => return Ok(*res),
197 };
198 let target = headers(cx)
199 .get(crate::self_update::TARGET_HEADER)
200 .and_then(|v| v.to_str().ok());
201 for label in target_labels(target) {
202 if !runner.labels.contains(&label) {
203 runner.labels.push(label);
204 }
205 }
206 // What the runner says about itself. An older runner sends only labels, and a body that does
207 // not parse is not worth failing a claim over.
208 let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await {
209 Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
210 Err(_) => ClaimRequest::default(),
211 };
212 // An older runner sends no free memory, and then the oldest compatible job is handed out.
213 let offer = request.free_memory_bytes.map(|free| MemoryOffer {
214 free,
215 budget: request.memory_budget_bytes,
216 default_reserve: request.reserve_memory_bytes.unwrap_or(DEFAULT_RESERVE),
217 });
218 note_report(
219 state,
220 &runner.id,
221 &RunnerReport {
222 memory_budget: request.memory_budget_bytes,
223 memory_free: request.free_memory_bytes,
224 memory_reserve: request.reserve_memory_bytes,
225 concurrency: request.concurrency,
226 version: request.version.filter(|v| v.len() <= 64),
227 cpus: request.cpus,
228 memory_bytes: request.memory_bytes,
229 build: request.build.filter(|v| v.len() <= 64),
230 boot_id: request.boot_id.filter(|v| v.len() <= 64),
231 capabilities: request
232 .capabilities
233 .into_iter()
234 .filter(|c| !c.is_empty() && c.len() <= 32 && !c.contains(','))
235 .take(16)
236 .collect(),
237 },
238 )
239 .await;
240 let mut res = claim_work(state, &runner, offer).await?;
241 // The override can change during the long poll, so it is read at answer time.
242 set_concurrency_header(state, &runner.id, &mut res).await;
243 set_memory_headers(state, &runner.id, &mut res).await;
244 set_restart_header(state, &runner.id, &mut res).await;
245 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
246 self_update::advertise(state, headers(cx), &mut res);
247 Ok(res)
248}
249
250/// The labels a runner's reported `<arch>-<os>` target stands for: the arch, the OS and the whole
251/// target, such as `x86_64`, `linux` and `x86_64-linux`. Nothing for a missing or odd target.
252fn target_labels(target: Option<&str>) -> Vec<String> {
253 let Some(target) = target else {
254 return Vec::new();
255 };
256 let plain = |part: &str| {
257 !part.is_empty()
258 && part.len() <= 32
259 && part
260 .bytes()
261 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
262 };
263 match target.split_once('-') {
264 Some((arch, os)) if plain(arch) && plain(os) => {
265 vec![arch.to_owned(), os.to_owned(), target.to_owned()]
266 }
267 _ => Vec::new(),
268 }
269}
270
271/// Stores a runner's self report and wakes the admin pages when it changed something.
272async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {
273 match state.store.record_runner_report(runner_id, report).await {
274 Ok(true) => state.ci_live.bump_runners(),
275 Ok(false) => {}
276 Err(e) => tracing::warn!(error = %e, "ci: runner report not stored"),
277 }
278}
279
280/// Adds the admin's concurrency override to a claim answer. No header means no override.
281async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) {
282 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
283 return;
284 }
285 if let Ok(Some(n)) = state.store.runner_concurrency_override(runner_id).await
286 && let Ok(value) = HeaderValue::from_str(&n.to_string())
287 {
288 res.headers_mut().insert(CONCURRENCY_HEADER, value);
289 }
290}
291
292/// Adds the admin's memory budget and default reservation to a claim answer. No header means no
293/// override. An older runner ignores both.
294async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Response) {
295 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
296 return;
297 }
298 for (key, header) in [
299 ("limits.memory_budget", MEMORY_BUDGET_HEADER),
300 ("limits.reserve_memory", RESERVE_MEMORY_HEADER),
301 ] {
302 if let Ok(Some(text)) = state.store.runner_field_override(runner_id, key).await
303 && let Ok(value) = HeaderValue::from_str(&text)
304 {
305 res.headers_mut().insert(header, value);
306 }
307 }
308}
309
310/// The restart an admin asked for, in the wire type. `None` when nothing is pending.
311async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> {
312 let mode = state.store.runner_restart(runner_id).await.ok().flatten()?;
313 WireRestart::parse(mode.as_str())
314}
315
316/// Adds the pending restart request to a claim answer. Sent on every answer until the runner
317/// comes back with a new boot id. An older runner ignores the header.
318async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) {
319 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
320 return;
321 }
322 if let Some(mode) = pending_restart(state, runner_id).await {
323 res.headers_mut()
324 .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str()));
325 }
326}
327
328/// `POST /api/v1/ci/runners/log`: a batch of the runner's own log lines. Answers the next line
329/// number the forge wants for this boot id, so the runner resends what was lost.
330#[route(POST "/api/v1/ci/runners/log")]
331async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
332 let state = context::<AppState>(cx);
333 let runner = match runner_from(state, headers(cx)).await {
334 Ok(runner) => runner,
335 Err(res) => return Ok(*res),
336 };
337 let bytes = match api::read_body(body, MAX_LOG_BATCH).await {
338 Ok(bytes) => bytes,
339 Err(res) => return Ok(*res),
340 };
341 let batch: RunnerLogBatch = match serde_json::from_slice(&bytes) {
342 Ok(batch) => batch,
343 Err(e) => {
344 return Ok(api::error(
345 StatusCode::BAD_REQUEST,
346 &format!("invalid JSON body: {e}"),
347 ));
348 }
349 };
350 if batch.boot_id.is_empty() || batch.boot_id.len() > 64 {
351 return Ok(api::error(
352 StatusCode::UNPROCESSABLE_ENTITY,
353 "the boot id is missing or too long",
354 ));
355 }
356 let next_seq = state.runner_logs.ingest(&runner.id, &batch);
357 state.ci_live.bump_runners();
358 let ack = serde_json::to_value(RunnerLogAck { next_seq }).unwrap_or_default();
359 Ok(api::json(StatusCode::OK, &ack))
360}
361
362/// `POST /api/v1/ci/runners/metrics`: host usage samples of the runner, for the graphs on its admin
363/// page. Answers 204 with no body.
364#[route(POST "/api/v1/ci/runners/metrics")]
365async fn runner_metrics(cx: &Cx, body: Body) -> topcoat::Result<Response> {
366 let state = context::<AppState>(cx);
367 let runner = match runner_from(state, headers(cx)).await {
368 Ok(runner) => runner,
369 Err(res) => return Ok(*res),
370 };
371 let bytes = match api::read_body(body, MAX_METRICS_BATCH).await {
372 Ok(bytes) => bytes,
373 Err(res) => return Ok(*res),
374 };
375 let batch: RunnerMetricsBatch = match serde_json::from_slice(&bytes) {
376 Ok(batch) => batch,
377 Err(e) => {
378 return Ok(api::error(
379 StatusCode::BAD_REQUEST,
380 &format!("invalid JSON body: {e}"),
381 ));
382 }
383 };
384 if batch.samples.len() > MAX_METRICS_SAMPLES {
385 return Ok(api::error(
386 StatusCode::UNPROCESSABLE_ENTITY,
387 "too many samples in one batch",
388 ));
389 }
390 state.runner_metrics.ingest(&runner.id, &batch);
391 state.ci_live.bump_runners();
392 Ok(empty(StatusCode::NO_CONTENT))
393}
394
395/// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
396/// starts, applies them to its in-memory config, then reports its effective config here.
397#[route(GET "/api/v1/ci/runners/config")]
398async fn runner_config_get(cx: &Cx) -> topcoat::Result<Response> {
399 let state = context::<AppState>(cx);
400 let runner = match runner_from(state, headers(cx)).await {
401 Ok(runner) => runner,
402 Err(res) => return Ok(*res),
403 };
404 Ok(overrides_response(&runner))
405}
406
407#[route(PUT "/api/v1/ci/runners/config")]
408async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result<Response> {
409 let state = context::<AppState>(cx);
410 let runner = match runner_from(state, headers(cx)).await {
411 Ok(runner) => runner,
412 Err(res) => return Ok(*res),
413 };
414 let report: RunnerConfigReport = match json_body(body).await {
415 Ok(report) => report,
416 Err(res) => return Ok(*res),
417 };
418 // Only known fields are kept, and the secret is never stored whatever the runner sent.
419 let mut config = report.config;
420 config.retain(|key, _| forge_core::ci::runner_field(key).is_some());
421 config.insert("runner_secret".into(), json!("<redacted>"));
422 match state
423 .store
424 .set_runner_reported_config(&runner.id, &config)
425 .await
426 {
427 Ok(true) => state.ci_live.bump_runners(),
428 Ok(false) => {}
429 Err(e) => return Ok(*api::internal(e)),
430 }
431 Ok(overrides_response(&runner))
432}
433
434fn overrides_response(runner: &CiRunner) -> Response {
435 let reply = RunnerConfigOverrides {
436 overrides: runner.config_overrides.clone(),
437 };
438 api::json(
439 StatusCode::OK,
440 &serde_json::to_value(reply).unwrap_or_default(),
441 )
442}
443
444async fn claim_work(
445 state: &AppState,
446 runner: &CiRunner,
447 offer: Option<MemoryOffer>,
448) -> topcoat::Result<Response> {
449 // Arm the wake-up before each attempt, so a job queued during the attempt is not missed.
450 // Producers use notify_waiters, which wakes every claimer, so a runner whose labels
451 // don't match a job re-arms and keeps waiting for the rest of the claim wait.
452 let waker = state.ci_waker.clone();
453 let wait = std::time::Duration::from_millis(state.config.ci.claim_wait_ms);
454 let deadline = tokio::time::Instant::now() + wait;
455 loop {
456 let mut woken = std::pin::pin!(waker.notified());
457 woken.as_mut().enable();
458
459 // A runner that is to restart gets no new job. It is answered at once, so it sees the
460 // request without waiting out the long poll.
461 if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) {
462 note_restart_pending(state, runner).await;
463 return Ok(empty(StatusCode::NO_CONTENT));
464 }
465 match try_claim(state, runner, offer).await {
466 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),
467 Ok(None) => {}
468 Err(res) => return Ok(*res),
469 }
470 if tokio::time::timeout_at(deadline, woken.as_mut())
471 .await
472 .is_err()
473 {
474 note_idle(state, runner, offer).await;
475 return Ok(empty(StatusCode::NO_CONTENT));
476 }
477 }
478}
479
480/// Writes to the runner's log that a restart is holding back the queued jobs. Writes nothing when
481/// no job is queued, so an idle runner does not fill its log.
482async fn note_restart_pending(state: &AppState, runner: &CiRunner) {
483 let Ok(skips) = state.store.queue_skips(runner, None).await else {
484 return;
485 };
486 if skips.queued > 0 {
487 note_runner(
488 state,
489 &runner.id,
490 "a restart is pending, not handing out jobs",
491 );
492 }
493}
494
495/// Writes to the runner's log why a long poll ended with no job while work is queued. Writes
496/// nothing when no job is queued.
497async fn note_idle(state: &AppState, runner: &CiRunner, offer: Option<MemoryOffer>) {
498 let skips = match state.store.queue_skips(runner, offer).await {
499 Ok(skips) => skips,
500 Err(e) => {
501 tracing::warn!(error = %e, "ci: counting the queued jobs failed");
502 return;
503 }
504 };
505 if let Some(text) = idle_text(&skips, offer.map(|o| o.free)) {
506 note_runner(state, &runner.id, &text);
507 }
508}
509
510/// Stores a forge note in the runner's log and wakes the admin pages when it was written.
511fn note_runner(state: &AppState, runner_id: &str, text: &str) {
512 if state.runner_logs.note(runner_id, text) {
513 state.ci_live.bump_runners();
514 }
515}
516
517/// The reason a runner got no job, from the queued jobs it could not take. `None` when no job is
518/// queued. `free` is the memory the runner offered, when it offered any.
519fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> {
520 if skips.queued == 0 {
521 return None;
522 }
523 let mut parts = vec![format!(
524 "{} queued {}",
525 skips.queued,
526 if skips.queued == 1 { "job" } else { "jobs" }
527 )];
528 if skips.lacking_labels > 0 {
529 parts.push(format!(
530 "{} need labels this runner lacks ({})",
531 skips.lacking_labels,
532 skips.missing_labels.join(", ")
533 ));
534 }
535 if let (true, Some(need), Some(free)) = (skips.too_big > 0, skips.smallest_need, free) {
536 parts.push(format!(
537 "{} waiting for memory: smallest needs {}, {} free",
538 skips.too_big,
539 bytes_text(need),
540 bytes_text(free)
541 ));
542 }
543 if let (Some(need), Some(free)) = (skips.starved_need, free) {
544 parts.push(format!(
545 "{} held back: a job queued over {} min ago needs {}, {} free, so no smaller job \
546 starts until running jobs finish and it fits",
547 skips.held_behind,
548 forge_core::ci::STARVE_AFTER_SECS / 60,
549 bytes_text(need),
550 bytes_text(free)
551 ));
552 }
553 Some(parts.join("; "))
554}
555
556/// The running binary, for a runner that updates itself. 404 unless self-update is enabled.
557#[route(GET "/api/v1/ci/runners/binary")]
558async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {
559 let state = context::<AppState>(cx);
560 if let Err(res) = runner_from(state, headers(cx)).await {
561 return Ok(*res);
562 }
563 if !state.config.self_update.enabled {
564 return Ok(api::error(StatusCode::NOT_FOUND, "self-update is disabled"));
565 }
566 match self_update::binary_response().await {
567 Ok(res) => Ok(res),
568 Err(e) => {
569 tracing::error!(error = %e, "ci: serving the runner binary failed");
570 Ok(api::error(
571 StatusCode::INTERNAL_SERVER_ERROR,
572 "the binary is unavailable",
573 ))
574 }
575 }
576}
577
578fn assignment_response(assignment: &JobAssignment) -> Response {
579 api::json(
580 StatusCode::OK,
581 &serde_json::to_value(assignment).unwrap_or_default(),
582 )
583}
584
585fn empty(status: StatusCode) -> Response {
586 let mut res = Response::new(topcoat::router::Body::empty());
587 *res.status_mut() = status;
588 res
589}
590
591/// One claim attempt. Builds the assignment, including the secrets the job may see.
592async fn try_claim(
593 state: &AppState,
594 runner: &CiRunner,
595 offer: Option<MemoryOffer>,
596) -> Result<Option<JobAssignment>, Refusal> {
597 let Some((job, run, job_token)) = state
598 .store
599 .claim_job_fitting(runner, offer)
600 .await
601 .map_err(api::internal)?
602 else {
603 return Ok(None);
604 };
605 state.ci_live.bump_job(&job.id);
606 state.ci_live.bump_run(&run.id);
607 state.ci_live.bump_repo(&run.repo_id);
608 state.ci_live.bump_runners();
609 // The next refusal is written again, and this job is written now.
610 state.runner_logs.clear_note(&runner.id);
611 note_runner(
612 state,
613 &runner.id,
614 &format!("took job {} of run #{}", job.name, run.number),
615 );
616 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
617 let repo = state
618 .store
619 .repo_by_id(&run.repo_id)
620 .await
621 .map_err(api::internal)?
622 .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?;
623
624 let secrets = if is_fork_run(state, &run).await? {
625 BTreeMap::new()
626 } else {
627 state
628 .store
629 .ci_secret_values(&run.repo_id, &spec.secrets)
630 .await
631 .map_err(api::internal)?
632 };
633
634 let (cache_key, cache_restore_keys) =
635 cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?;
636
637 Ok(Some(JobAssignment {
638 job_id: job.id,
639 job_token,
640 repo: format!("{}/{}", repo.owner_name, repo.name),
641 clone_url: https_clone_url(&state.config, &repo.owner_name, &repo.name),
642 commit: run.commit_oid,
643 git_ref: run.git_ref,
644 job_name: job.name,
645 image: spec.image,
646 run: spec.run,
647 env: spec.env,
648 secrets,
649 artifacts: spec.artifacts,
650 timeout_minutes: spec.timeout_minutes,
651 network: spec.network,
652 cache: spec.cache,
653 cache_key,
654 cache_restore_keys,
655 memory_bytes: spec.memory,
656 }))
657}
658
659/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base
660/// branch comes from its pull request record.
661async fn cache_scopes(
662 state: &AppState,
663 run: &CiRun,
664 default_branch: &str,
665 cache: &[String],
666) -> Result<(String, Vec<String>), Refusal> {
667 if cache.is_empty() {
668 return Ok((String::new(), Vec::new()));
669 }
670 let pull_base = match (run.trigger.as_str(), run.pull_number) {
671 ("pull_request", Some(number)) => state
672 .store
673 .pull_by_number(&run.repo_id, number)
674 .await
675 .map_err(api::internal)?
676 .map(|pull| pull.base_branch),
677 _ => None,
678 };
679 let scope = cache_scope(
680 &run.trigger,
681 &run.git_ref,
682 run.pull_number,
683 pull_base.as_deref(),
684 default_branch,
685 );
686 Ok(match scope {
687 Some(scope) => (scope.key, scope.restore_keys),
688 // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves.
689 None => (String::new(), Vec::new()),
690 })
691}
692
693/// The cache scope a run may write, and the read-only scopes it may restore from.
694#[derive(Debug, Clone, PartialEq, Eq)]
695struct CacheScope {
696 key: String,
697 restore_keys: Vec<String>,
698}
699
700/// Derives the cache scopes of a run. Returns `None` when no scope can be derived.
701///
702/// Only pull request runs get `pr:` keys and only non-pull-request runs get `ref:` keys. The
703/// choice follows the run's trigger, never the ref name, so a pull request from a branch named
704/// `main` still writes `pr:N`. A pull request run reads its base branch's cache, a branch or tag
705/// run reads the default branch's cache, and both fall back to nothing else.
706fn cache_scope(
707 trigger: &str,
708 git_ref: &str,
709 pull_number: Option<i64>,
710 pull_base: Option<&str>,
711 default_branch: &str,
712) -> Option<CacheScope> {
713 let default_ref = format!("ref:refs/heads/{default_branch}");
714 match trigger {
715 "pull_request" => {
716 let number = pull_number?;
717 let mut restore_keys = Vec::new();
718 if let Some(base) = pull_base {
719 restore_keys.push(format!("ref:refs/heads/{base}"));
720 }
721 if pull_base != Some(default_branch) {
722 restore_keys.push(default_ref);
723 }
724 Some(CacheScope {
725 key: format!("pr:{number}"),
726 restore_keys,
727 })
728 }
729 "push" | "tag" | "manual" | "schedule" => {
730 let restore_keys = if git_ref == format!("refs/heads/{default_branch}") {
731 Vec::new()
732 } else {
733 vec![default_ref]
734 };
735 Some(CacheScope {
736 key: format!("ref:{git_ref}"),
737 restore_keys,
738 })
739 }
740 _ => None,
741 }
742}
743
744/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such
745/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.
746async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {
747 if run.trigger != "pull_request" {
748 return Ok(false);
749 }
750 let Some(number) = run.pull_number else {
751 return Ok(true);
752 };
753 match state
754 .store
755 .pull_by_number(&run.repo_id, number)
756 .await
757 .map_err(api::internal)?
758 {
759 Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())),
760 None => Ok(true),
761 }
762}
763
764// ---------------------------------------------------------------------------------------------
765// Heartbeat, logs and artifacts
766// ---------------------------------------------------------------------------------------------
767
768#[route(POST "/api/v1/ci/jobs/{job_id}/heartbeat")]
769async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
770 let state = context::<AppState>(cx);
771 let job = match job_from(state, headers(cx), job_id(cx)).await {
772 Ok(job) => job,
773 Err(res) => return Ok(*res),
774 };
775 match state.store.heartbeat(&job.id).await {
776 Ok(cancel) => {
777 // The runner says its live concurrency, and the answer carries the admin's override.
778 // A runner at its limit does not claim, so this is how it learns about a change.
779 let mut concurrency = None;
780 let mut restart = None;
781 if let Some(runner_id) = job.runner_id.as_deref() {
782 if let Err(e) = state.store.touch_runner(runner_id).await {
783 tracing::warn!(error = %e, "ci: runner last-seen not stored");
784 }
785 // A busy runner only heartbeats here. Its state is read only when it is not
786 // recorded online, so a steady heartbeat costs a map lookup.
787 if !state.ci_live.runner_recorded_online(runner_id) {
788 let disabled = state
789 .store
790 .runner_disabled(runner_id)
791 .await
792 .unwrap_or(false);
793 state.ci_live.note_runner_online(runner_id, !disabled);
794 }
795 let said = headers(cx)
796 .get(CONCURRENCY_HEADER)
797 .and_then(|v| v.to_str().ok())
798 .and_then(|v| v.trim().parse::<u32>().ok());
799 note_report(
800 state,
801 runner_id,
802 &RunnerReport {
803 concurrency: said,
804 build: headers(cx)
805 .get(BUILD_HEADER)
806 .and_then(|v| v.to_str().ok())
807 .filter(|v| v.len() <= 64)
808 .map(str::to_owned),
809 ..RunnerReport::default()
810 },
811 )
812 .await;
813 concurrency = state
814 .store
815 .runner_concurrency_override(runner_id)
816 .await
817 .ok()
818 .flatten();
819 restart = pending_restart(state, runner_id).await;
820 }
821 Ok(api::json(
822 StatusCode::OK,
823 &serde_json::to_value(HeartbeatResponse {
824 cancel,
825 concurrency,
826 restart,
827 })
828 .unwrap_or_default(),
829 ))
830 }
831 Err(e) => Ok(*api::internal(e)),
832 }
833}
834
835/// Outcome of a log append.
836enum LogWrite {
837 /// The chunk is stored (or was dropped by the cap); the size is the new byte count.
838 Stored(u64),
839 /// This exact chunk was already stored: a retry. The size is unchanged.
840 Duplicate(u64),
841 /// The offset does not match the stored size.
842 Mismatch(u64),
843}
844
845#[route(POST "/api/v1/ci/jobs/{job_id}/logs")]
846async fn append_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
847 let state = context::<AppState>(cx);
848 let headers = headers(cx);
849 let job = match job_from(state, headers, job_id(cx)).await {
850 Ok(job) => job,
851 Err(res) => return Ok(*res),
852 };
853 let Some(offset) = headers
854 .get(LOG_OFFSET_HEADER)
855 .and_then(|value| value.to_str().ok())
856 .and_then(|value| value.parse::<u64>().ok())
857 else {
858 return Ok(api::error(
859 StatusCode::BAD_REQUEST,
860 "X-Forge-Log-Offset must be a byte offset",
861 ));
862 };
863 let chunk = match api::read_body(body, MAX_LOG_CHUNK).await {
864 Ok(chunk) => chunk,
865 Err(res) => return Ok(*res),
866 };
867 match write_log(state, &job, offset, &chunk).await {
868 Ok(LogWrite::Stored(size) | LogWrite::Duplicate(size)) => {
869 Ok(api::json(StatusCode::OK, &json!({ "size": size })))
870 }
871 Ok(LogWrite::Mismatch(size)) => {
872 let mut res = api::error(StatusCode::CONFLICT, "the log offset does not match");
873 res.headers_mut().insert(
874 http::HeaderName::from_static(LOG_SIZE_HEADER),
875 HeaderValue::from(size),
876 );
877 Ok(res)
878 }
879 Err(res) => Ok(*res),
880 }
881}
882
883/// Appends one chunk of raw log bytes. Offsets count the raw bytes the runner sent, which is
884/// `job.log_bytes`; the file holds the masked text, so its length may differ.
885async fn write_log(
886 state: &AppState,
887 job: &CiJob,
888 offset: u64,
889 chunk: &[u8],
890) -> Result<LogWrite, Refusal> {
891 let size = u64::try_from(job.log_bytes).unwrap_or(0);
892 let len = chunk.len() as u64;
893 if offset != size {
894 return Ok(if offset.checked_add(len) == Some(size) {
895 LogWrite::Duplicate(size)
896 } else {
897 LogWrite::Mismatch(size)
898 });
899 }
900 if chunk.is_empty() {
901 return Ok(LogWrite::Stored(size));
902 }
903
904 let masked = mask_for_job(state, job, chunk).await?;
905 let path = log_path(&state.config.data_dir, &job.id);
906 store_log_bytes(state, &path, &masked).await?;
907 state
908 .store
909 .add_log_bytes(&job.id, len as i64)
910 .await
911 .map_err(api::internal)?;
912 // A failure here must not fail the append: the runner would retry it and read a duplicate.
913 if let Err(e) = record_steps(state, &job.id, &path).await {
914 tracing::warn!(error = %e, job = %job.id, "ci: could not record job steps");
915 }
916 state.ci_live.bump_job(&job.id);
917 // The run page shows the last log lines, so its streams wake too. The page debounces.
918 state.ci_live.bump_run(&job.run_id);
919 if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
920 state.ci_live.bump_repo(&run.repo_id);
921 }
922 Ok(LogWrite::Stored(size + len))
923}
924
925/// Scans the file's log from the last scanned byte for step marks and stores them. The file is read,
926/// not the chunk: it holds the masked text, and its offsets are the ones the job page seeks to.
927async fn record_steps(
928 state: &AppState,
929 job_id: &str,
930 path: &std::path::Path,
931) -> Result<(), CoreError> {
932 use tokio::io::{AsyncReadExt, AsyncSeekExt};
933
934 let (scanned, mut depth) = state.store.step_scan(job_id).await?;
935 let mut file = match tokio::fs::File::open(path).await {
936 Ok(file) => file,
937 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
938 Err(e) => return Err(e.into()),
939 };
940 file.seek(std::io::SeekFrom::Start(scanned)).await?;
941 let mut bytes = Vec::new();
942 file.read_to_end(&mut bytes).await?;
943 let found = forge_ci::steps::scan(&bytes, scanned, &mut depth);
944 let used = if found.consumed == 0 && bytes.len() >= MAX_STEP_LINE {
945 bytes.len()
946 } else {
947 found.consumed
948 };
949 if used == 0 {
950 return Ok(());
951 }
952 state
953 .store
954 .apply_step_scan(job_id, scanned + used as u64, depth, &found.marks)
955 .await
956}
957
958/// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a
959/// secret split across two requests is masked by the runner, which holds back the boundary.
960async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec<u8>, Refusal> {
961 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
962 if spec.secrets.is_empty() {
963 return Ok(chunk.to_vec());
964 }
965 let Some(run) = state
966 .store
967 .run_by_id(&job.run_id)
968 .await
969 .map_err(api::internal)?
970 else {
971 return Err(api::internal("log for a job with no run"));
972 };
973 let values = state
974 .store
975 .ci_secret_values(&run.repo_id, &spec.secrets)
976 .await
977 .map_err(api::internal)?;
978 let masker = Masker::new(values.into_values());
979 let mut stream = masker.stream();
980 let mut out = stream.push(chunk);
981 out.extend(stream.finish());
982 Ok(out)
983}
984
985/// The bytes of `masked` that may be appended to a log of `current` bytes under a `cap`. Once the
986/// log reaches the cap nothing more is kept. When the new bytes do not fit, the part that does is
987/// kept and the marker follows it, so the file ends at exactly `cap` bytes.
988pub fn fit_to_cap(current: u64, cap: u64, masked: &[u8]) -> Vec<u8> {
989 if current >= cap {
990 return Vec::new();
991 }
992 let data_cap = cap.saturating_sub(TRUNCATED_MARKER.len() as u64);
993 let room = data_cap.saturating_sub(current);
994 if masked.len() as u64 <= room {
995 return masked.to_vec();
996 }
997 let mut out = masked[..room as usize].to_vec();
998 out.extend_from_slice(TRUNCATED_MARKER);
999 out
1000}
1001
1002/// Appends masked bytes to the log file, stopping at the size cap with one marker line.
1003async fn store_log_bytes(
1004 state: &AppState,
1005 path: &std::path::Path,
1006 masked: &[u8],
1007) -> Result<(), Refusal> {
1008 use tokio::io::AsyncWriteExt;
1009
1010 let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
1011 let current = match tokio::fs::metadata(path).await {
1012 Ok(meta) => meta.len(),
1013 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
1014 Err(e) => return Err(api::internal(e)),
1015 };
1016 let out = fit_to_cap(current, cap, masked);
1017 if out.is_empty() {
1018 return Ok(());
1019 }
1020
1021 if let Some(parent) = path.parent() {
1022 tokio::fs::create_dir_all(parent)
1023 .await
1024 .map_err(api::internal)?;
1025 }
1026 let mut file = tokio::fs::OpenOptions::new()
1027 .create(true)
1028 .append(true)
1029 .open(path)
1030 .await
1031 .map_err(api::internal)?;
1032 file.write_all(&out).await.map_err(api::internal)?;
1033 file.flush().await.map_err(api::internal)?;
1034 Ok(())
1035}
1036
1037#[route(PUT "/api/v1/ci/jobs/{job_id}/artifacts/{artifact_name}")]
1038async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
1039 let state = context::<AppState>(cx);
1040 let job = match job_from(state, headers(cx), job_id(cx)).await {
1041 Ok(job) => job,
1042 Err(res) => return Ok(*res),
1043 };
1044 let name = artifact_name(cx);
1045 if !valid_artifact_name(name) {
1046 return Ok(api::error(
1047 StatusCode::UNPROCESSABLE_ENTITY,
1048 "the artifact name must be 1 to 128 of A-Z a-z 0-9 . _ + - and not start with a dot",
1049 ));
1050 }
1051 match upload(state, &job, name, body).await {
1052 Ok(artifact_id) => {
1053 // The job's artifact list and its run's artifact list show the new one. The run page
1054 // follows its repo's stream, so the repo wakes too.
1055 state.ci_live.bump_job(&job.id);
1056 state.ci_live.bump_run(&job.run_id);
1057 if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
1058 state.ci_live.bump_repo(&run.repo_id);
1059 }
1060 // A new artifact may push the store past its disk limit. Enforce it now, not at the
1061 // next daily purge. The request does not wait for it.
1062 let state = state.clone();
1063 tokio::spawn(async move { crate::ci::reaper::purge_once(&state).await });
1064 Ok(api::json(
1065 StatusCode::CREATED,
1066 &json!({ "id": artifact_id, "name": name }),
1067 ))
1068 }
1069 Err(res) => Ok(*res),
1070 }
1071}
1072
1073/// Streams the body to a temporary blob, then records the artifact and moves the blob to its
1074/// final key `ci/<artifact id>`. The id is only known once the row exists.
1075async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result<String, Refusal> {
1076 let max_artifacts = state.live().ci.max_artifacts_per_job;
1077 let existing = state
1078 .store
1079 .list_artifacts(&job.id)
1080 .await
1081 .map_err(api::internal)?;
1082 if existing.len() as u64 >= u64::from(max_artifacts) {
1083 return Err(Box::new(api::error(
1084 StatusCode::CONFLICT,
1085 "the job has too many artifacts",
1086 )));
1087 }
1088 if existing.iter().any(|artifact| artifact.name == name) {
1089 return Err(Box::new(api::error(
1090 StatusCode::CONFLICT,
1091 "an artifact with this name already exists",
1092 )));
1093 }
1094
1095 // One artifact is held to its own limit and to what is left of the job's total.
1096 let used: u64 = existing
1097 .iter()
1098 .map(|artifact| u64::try_from(artifact.size).unwrap_or(0))
1099 .sum();
1100 let left = state
1101 .live()
1102 .ci
1103 .max_job_artifacts_mb
1104 .saturating_mul(MIB)
1105 .saturating_sub(used);
1106 if left == 0 {
1107 return Err(Box::new(api::error(
1108 StatusCode::CONFLICT,
1109 "the job's artifacts have reached their total size limit",
1110 )));
1111 }
1112 let max_bytes = state
1113 .live()
1114 .ci
1115 .max_artifact_mb
1116 .saturating_mul(MIB)
1117 .min(left);
1118 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());
1119 let mut writer = state
1120 .blobs
1121 .begin(&temp_key, max_bytes)
1122 .await
1123 .map_err(api::internal)?;
1124 let mut stream = std::pin::pin!(body.into_data_stream());
1125 while let Some(next) = stream.next().await {
1126 let outcome = match next {
1127 Ok(chunk) => writer.push(&chunk).await.map_err(|e| (e, false)),
1128 Err(_) => Err((CoreError::Invalid("upload interrupted".into()), true)),
1129 };
1130 if let Err((e, interrupted)) = outcome {
1131 writer.abort().await;
1132 return Err(upload_failure(e, interrupted));
1133 }
1134 }
1135 let (size, sha256) = match writer.finish().await {
1136 Ok(done) => done,
1137 Err(e) => {
1138 discard_temp(state, &temp_key).await;
1139 return Err(api::internal(e));
1140 }
1141 };
1142
1143 let artifact = match state
1144 .store
1145 .add_artifact(&job.id, name, size as i64, &sha256)
1146 .await
1147 {
1148 Ok(artifact) => artifact,
1149 Err(e) => {
1150 discard_temp(state, &temp_key).await;
1151 return Err(match e {
1152 CoreError::Invalid(message) => Box::new(api::error(StatusCode::CONFLICT, &message)),
1153 other => api::internal(other),
1154 });
1155 }
1156 };
1157 let final_key = artifact_key(&artifact.id);
1158 if let Err(e) = state.blobs.rename(&temp_key, &final_key).await {
1159 discard_temp(state, &temp_key).await;
1160 return Err(api::internal(e));
1161 }
1162 Ok(artifact.id)
1163}
1164
1165/// Removes a temporary blob. A failure is logged; the blob is unreachable either way.
1166async fn discard_temp(state: &AppState, key: &str) {
1167 if let Err(e) = state.blobs.delete(key).await {
1168 tracing::error!(error = %e, "ci: could not remove a temporary artifact blob");
1169 }
1170}
1171
1172fn upload_failure(e: CoreError, interrupted: bool) -> Refusal {
1173 match e {
1174 CoreError::Invalid(_) if !interrupted => Box::new(api::error(
1175 StatusCode::PAYLOAD_TOO_LARGE,
1176 "the artifact is larger than the upload limit",
1177 )),
1178 CoreError::Invalid(message) => Box::new(api::error(StatusCode::BAD_REQUEST, &message)),
1179 other => api::internal(other),
1180 }
1181}
1182
1183// ---------------------------------------------------------------------------------------------
1184// Finish
1185// ---------------------------------------------------------------------------------------------
1186
1187#[route(POST "/api/v1/ci/jobs/{job_id}/finish")]
1188async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
1189 let state = context::<AppState>(cx);
1190 let job = match job_from(state, headers(cx), job_id(cx)).await {
1191 Ok(job) => job,
1192 Err(res) => return Ok(*res),
1193 };
1194 let request: FinishRequest = match json_body(body).await {
1195 Ok(request) => request,
1196 Err(res) => return Ok(*res),
1197 };
1198 let state_after = match request.outcome {
1199 Outcome::Success => JobState::Success,
1200 Outcome::Failure => JobState::Failure,
1201 Outcome::Cancelled => JobState::Cancelled,
1202 Outcome::Error => JobState::Error,
1203 };
1204 match finish_job(state, &job, state_after, &request).await {
1205 Ok(state_name) => Ok(api::json(StatusCode::OK, &json!({ "state": state_name }))),
1206 Err(res) => Ok(*res),
1207 }
1208}
1209
1210#[route(POST "/api/v1/ci/jobs/{job_id}/requeue")]
1211async fn requeue(cx: &Cx, body: Body) -> topcoat::Result<Response> {
1212 let state = context::<AppState>(cx);
1213 let job = match job_from(state, headers(cx), job_id(cx)).await {
1214 Ok(job) => job,
1215 Err(res) => return Ok(*res),
1216 };
1217 let request: RequeueRequest = match json_body(body).await {
1218 Ok(request) => request,
1219 Err(res) => return Ok(*res),
1220 };
1221 match state.store.requeue_job(&job.id).await {
1222 Ok(true) => {}
1223 Ok(false) => {
1224 return Ok(api::error(StatusCode::CONFLICT, "the job is not running"));
1225 }
1226 Err(e) => return Ok(*api::internal(e)),
1227 }
1228 // The next attempt starts from a clean log with one line saying why.
1229 let path = log_path(&state.config.data_dir, &job.id);
1230 let reason = request.reason.replace(['\r', '\n'], " ");
1231 let note = format!("requeued: {reason}. It will start again\n");
1232 if let Some(parent) = path.parent()
1233 && let Err(e) = tokio::fs::create_dir_all(parent).await
1234 {
1235 tracing::warn!(error = %e, "ci: log directory not created");
1236 }
1237 if let Err(e) = tokio::fs::write(&path, note).await {
1238 tracing::warn!(error = %e, "ci: requeue log note not written");
1239 }
1240 state.ci_live.bump_job(&job.id);
1241 state.ci_live.bump_run(&job.run_id);
1242 state.ci_live.bump_runners();
1243 if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
1244 state.ci_live.bump_repo(&run.repo_id);
1245 if let Ok(Some(fresh)) = state.store.job_by_id(&job.id).await {
1246 crate::ci::sync_status(state, &run, &fresh).await;
1247 }
1248 }
1249 state.ci_waker.notify_waiters();
1250 Ok(api::json(StatusCode::OK, &json!({ "state": "queued" })))
1251}
1252
1253/// Finishes the job, then syncs the statuses of the job and of every job whose state changed
1254/// (skipped or queued by this finish). Wakes the claimers when something was queued, and the
1255/// watchers of every job and run that changed.
1256async fn finish_job(
1257 state: &AppState,
1258 job: &CiJob,
1259 outcome: JobState,
1260 request: &FinishRequest,
1261) -> Result<&'static str, Refusal> {
1262 let before: BTreeMap<String, JobState> = state
1263 .store
1264 .jobs_for_run(&job.run_id)
1265 .await
1266 .map_err(api::internal)?
1267 .into_iter()
1268 .map(|other| (other.id, other.state))
1269 .collect();
1270 let exit_code = request.exit_code.map(i64::from);
1271 // The runner read the job cgroup's OOM counters. A count without the flag is believed too.
1272 let oom_kills = match (request.oom_killed, request.oom_kills) {
1273 (Some(false), _) => 0,
1274 (_, Some(n)) => n.max(1),
1275 (Some(true), None) => 1,
1276 (None, None) => 0,
1277 };
1278 let run = state
1279 .store
1280 .finish_job(&job.id, outcome, exit_code, request.message.as_deref())
1281 .await
1282 .map_err(api::internal)?;
1283
1284 if oom_kills > 0
1285 && let Err(e) = state.store.set_job_oom_kills(&job.id, oom_kills).await
1286 {
1287 tracing::warn!(error = %e, "ci: oom kills not stored");
1288 }
1289 let mut queued = false;
1290 let mut any_changed = false;
1291 for other in state
1292 .store
1293 .jobs_for_run(&job.run_id)
1294 .await
1295 .map_err(api::internal)?
1296 {
1297 let changed = before.get(&other.id) != Some(&other.state);
1298 if changed {
1299 any_changed = true;
1300 if other.state.is_terminal() {
1301 state.ci_live.close_job(&other.id);
1302 } else {
1303 state.ci_live.bump_job(&other.id);
1304 }
1305 }
1306 if other.id == job.id
1307 || (changed && matches!(other.state, JobState::Skipped | JobState::Queued))
1308 {
1309 queued |= other.state == JobState::Queued;
1310 crate::ci::sync_status(state, &run, &other).await;
1311 }
1312 }
1313 state.ci_live.bump_runners();
1314 if matches!(outcome, JobState::Failure | JobState::Error) {
1315 crate::alerts::job_ended(
1316 state,
1317 job,
1318 exit_code,
1319 request.message.as_deref(),
1320 oom_kills > 0,
1321 )
1322 .await;
1323 }
1324 if any_changed {
1325 state.ci_live.bump_run(&run.id);
1326 state.ci_live.bump_repo(&run.repo_id);
1327 }
1328 if queued {
1329 state.ci_waker.notify_waiters();
1330 }
1331 // A run that just went green may deploy the forge itself.
1332 self_update::maybe_deploy(state, &run).await;
1333 // A tag run that went green may publish a release. The request does not wait for it.
1334 if run.state == RunState::Success {
1335 let (state, run) = (state.clone(), run.clone());
1336 tokio::spawn(async move { crate::ci::release::on_run_finished(&state, &run).await });
1337 }
1338 Ok(run.state.as_str())
1339}
1340
1341#[cfg(test)]
1342#[path = "api_tests.rs"]
1343mod tests;