forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiBb25287eTahinli1 month ago13 commits

api.rs691 lines, 23.8 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 FinishRequest, HeartbeatResponse, JobAssignment, Outcome, RegisterRequest, RegisterResponse,
13};
14use forge_core::Error as CoreError;
15use forge_core::ci::{CiJob, CiRun, CiRunner, JobState};
16use futures_util::StreamExt;
17use http::header::HeaderValue;
18use serde_json::json;
19use std::collections::BTreeMap;
20use topcoat::context::{Cx, app_context};
21use topcoat::router::request::headers;
22use topcoat::router::response::Response;
23use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route};
24
25use crate::api::{self, Refusal};
26use crate::ci::{artifact_key, log_path};
27use crate::pages::repo::https_clone_url;
28use crate::self_update;
29use crate::state::AppState;
30
31path_param!(job_id);
32path_param!(artifact_name);
33
34/// Header carrying the byte offset of a log chunk.
35const LOG_OFFSET_HEADER: &str = "x-forge-log-offset";
36/// Header on a 409 log response carrying the size the server has.
37const LOG_SIZE_HEADER: &str = "x-forge-log-size";
38/// Largest log chunk, in bytes.
39const MAX_LOG_CHUNK: usize = 1024 * 1024;
40/// Largest JSON body on the runner routes, in bytes.
41const MAX_JSON_BODY: usize = 64 * 1024;
42/// How long a claim waits for work before answering 204.
43#[cfg(not(test))]
44const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_secs(25);
45#[cfg(test)]
46const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_millis(50);
47/// Longest runner name or label, in bytes.
48const MAX_NAME_BYTES: usize = 64;
49/// Most labels a runner may register.
50const MAX_LABELS: usize = 32;
51/// Text appended once when the log cap is reached.
52const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n";
53const MIB: u64 = 1024 * 1024;
54
55/// Bearer token from the `Authorization` header, or `None`.
56fn bearer_token(headers: &HeaderMap) -> Option<&str> {
57 let value = headers.get(http::header::AUTHORIZATION)?.to_str().ok()?;
58 let (scheme, rest) = value.split_once(' ')?;
59 if !scheme.eq_ignore_ascii_case("bearer") {
60 return None;
61 }
62 let token = rest.trim();
63 (!token.is_empty()).then_some(token)
64}
65
66fn unauthorized() -> Refusal {
67 Box::new(api::error(
68 StatusCode::UNAUTHORIZED,
69 "authentication required",
70 ))
71}
72
73/// The runner behind the Bearer secret. Disabled runners get 403.
74async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result<CiRunner, Refusal> {
75 let Some(secret) = bearer_token(headers) else {
76 return Err(unauthorized());
77 };
78 match state.store.runner_by_secret(secret).await {
79 Ok(Some(runner)) if runner.disabled => Err(Box::new(api::error(
80 StatusCode::FORBIDDEN,
81 "the runner is disabled",
82 ))),
83 Ok(Some(runner)) => Ok(runner),
84 Ok(None) => Err(unauthorized()),
85 Err(e) => Err(api::internal(e)),
86 }
87}
88
89/// The job behind the Bearer job token. Only Running jobs match, so a finished job gets 401.
90async fn job_from(state: &AppState, headers: &HeaderMap, job_id: &str) -> Result<CiJob, Refusal> {
91 let Some(token) = bearer_token(headers) else {
92 return Err(unauthorized());
93 };
94 match state.store.job_by_token(job_id, token).await {
95 Ok(Some(job)) => Ok(job),
96 Ok(None) => Err(unauthorized()),
97 Err(e) => Err(api::internal(e)),
98 }
99}
100
101/// Parses a JSON body of at most [`MAX_JSON_BODY`] bytes.
102async fn json_body<T: serde::de::DeserializeOwned>(body: Body) -> Result<T, Refusal> {
103 let bytes = api::read_body(body, MAX_JSON_BODY).await?;
104 serde_json::from_slice(&bytes).map_err(|e| {
105 Box::new(api::error(
106 StatusCode::BAD_REQUEST,
107 &format!("invalid JSON body: {e}"),
108 ))
109 })
110}
111
112fn valid_name(value: &str) -> bool {
113 !value.trim().is_empty() && value.len() <= MAX_NAME_BYTES && !value.contains(char::is_control)
114}
115
116/// `[A-Za-z0-9._+-]{1,128}`, and not starting with a dot.
117pub fn valid_artifact_name(name: &str) -> bool {
118 !name.is_empty()
119 && name.len() <= 128
120 && !name.starts_with('.')
121 && name
122 .bytes()
123 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-'))
124}
125
126// ---------------------------------------------------------------------------------------------
127// Registration and claims
128// ---------------------------------------------------------------------------------------------
129
130#[route(POST "/api/v1/ci/runners/register")]
131async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
132 let state = app_context::<AppState>(cx);
133 let request: RegisterRequest = match json_body(body).await {
134 Ok(request) => request,
135 Err(res) => return Ok(*res),
136 };
137 if !valid_name(&request.name) || request.labels.len() > MAX_LABELS {
138 return Ok(api::error(
139 StatusCode::UNPROCESSABLE_ENTITY,
140 "the runner name or labels are invalid",
141 ));
142 }
143 if request.labels.iter().any(|label| !valid_name(label)) {
144 return Ok(api::error(
145 StatusCode::UNPROCESSABLE_ENTITY,
146 "the runner name or labels are invalid",
147 ));
148 }
149 match state
150 .store
151 .register_runner(&request.token, request.name.trim(), &request.labels)
152 .await
153 {
154 Ok((runner, secret)) => {
155 let body = RegisterResponse {
156 runner_id: runner.id,
157 runner_secret: secret,
158 };
159 Ok(api::json(
160 StatusCode::CREATED,
161 &serde_json::to_value(&body).unwrap_or_default(),
162 ))
163 }
164 Err(CoreError::Invalid(_)) => Ok(api::error(
165 StatusCode::UNAUTHORIZED,
166 "the registration token is unknown, used or expired",
167 )),
168 Err(e) => Ok(*api::internal(e)),
169 }
170}
171
172#[route(POST "/api/v1/ci/runners/claim")]
173async fn claim(cx: &Cx) -> topcoat::Result<Response> {
174 let mut res = claim_work(cx).await?;
175 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
176 self_update::advertise(app_context::<AppState>(cx), headers(cx), &mut res);
177 Ok(res)
178}
179
180async fn claim_work(cx: &Cx) -> topcoat::Result<Response> {
181 let state = app_context::<AppState>(cx);
182 // The labels in the request are ignored: the labels stored at registration are used.
183 let runner = match runner_from(state, headers(cx)).await {
184 Ok(runner) => runner,
185 Err(res) => return Ok(*res),
186 };
187
188 // Arm the wake-up before each attempt, so a job queued during the attempt is not missed.
189 // Producers use notify_waiters, which wakes every claimer, so a runner whose labels
190 // don't match a job re-arms and keeps waiting for the rest of CLAIM_WAIT.
191 let waker = state.ci_waker.clone();
192 let deadline = tokio::time::Instant::now() + CLAIM_WAIT;
193 loop {
194 let mut woken = std::pin::pin!(waker.notified());
195 woken.as_mut().enable();
196
197 match try_claim(state, &runner).await {
198 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),
199 Ok(None) => {}
200 Err(res) => return Ok(*res),
201 }
202 if tokio::time::timeout_at(deadline, woken.as_mut())
203 .await
204 .is_err()
205 {
206 return Ok(empty(StatusCode::NO_CONTENT));
207 }
208 }
209}
210
211/// The running binary, for a runner that updates itself. 404 unless self-update is enabled.
212#[route(GET "/api/v1/ci/runners/binary")]
213async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {
214 let state = app_context::<AppState>(cx);
215 if let Err(res) = runner_from(state, headers(cx)).await {
216 return Ok(*res);
217 }
218 if !state.config.self_update.enabled {
219 return Ok(api::error(StatusCode::NOT_FOUND, "self-update is disabled"));
220 }
221 match self_update::binary_response().await {
222 Ok(res) => Ok(res),
223 Err(e) => {
224 tracing::error!(error = %e, "ci: serving the runner binary failed");
225 Ok(api::error(
226 StatusCode::INTERNAL_SERVER_ERROR,
227 "the binary is unavailable",
228 ))
229 }
230 }
231}
232
233fn assignment_response(assignment: &JobAssignment) -> Response {
234 api::json(
235 StatusCode::OK,
236 &serde_json::to_value(assignment).unwrap_or_default(),
237 )
238}
239
240fn empty(status: StatusCode) -> Response {
241 let mut res = Response::new(topcoat::router::Body::empty());
242 *res.status_mut() = status;
243 res
244}
245
246/// One claim attempt. Builds the assignment, including the secrets the job may see.
247async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssignment>, Refusal> {
248 let Some((job, run, job_token)) = state.store.claim_job(runner).await.map_err(api::internal)?
249 else {
250 return Ok(None);
251 };
252 state.ci_live.bump_job(&job.id);
253 state.ci_live.bump_run(&run.id);
254 state.ci_live.bump_repo(&run.repo_id);
255 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
256 let repo = state
257 .store
258 .repo_by_id(&run.repo_id)
259 .await
260 .map_err(api::internal)?
261 .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?;
262
263 let secrets = if is_fork_run(state, &run).await? {
264 BTreeMap::new()
265 } else {
266 state
267 .store
268 .ci_secret_values(&run.repo_id, &spec.secrets)
269 .await
270 .map_err(api::internal)?
271 };
272
273 Ok(Some(JobAssignment {
274 job_id: job.id,
275 job_token,
276 repo: format!("{}/{}", repo.owner_name, repo.name),
277 clone_url: https_clone_url(&state.config, &repo.owner_name, &repo.name),
278 commit: run.commit_oid,
279 git_ref: run.git_ref,
280 job_name: job.name,
281 image: spec.image,
282 run: spec.run,
283 env: spec.env,
284 secrets,
285 artifacts: spec.artifacts,
286 timeout_minutes: spec.timeout_minutes,
287 network: spec.network,
288 }))
289}
290
291/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such
292/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.
293async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {
294 if run.trigger != "pull_request" {
295 return Ok(false);
296 }
297 let Some(number) = run.pull_number else {
298 return Ok(true);
299 };
300 match state
301 .store
302 .pull_by_number(&run.repo_id, number)
303 .await
304 .map_err(api::internal)?
305 {
306 Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())),
307 None => Ok(true),
308 }
309}
310
311// ---------------------------------------------------------------------------------------------
312// Heartbeat, logs and artifacts
313// ---------------------------------------------------------------------------------------------
314
315#[route(POST "/api/v1/ci/jobs/{job_id}/heartbeat")]
316async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
317 let state = app_context::<AppState>(cx);
318 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
319 Ok(job) => job,
320 Err(res) => return Ok(*res),
321 };
322 match state.store.heartbeat(&job.id).await {
323 Ok(cancel) => Ok(api::json(
324 StatusCode::OK,
325 &serde_json::to_value(HeartbeatResponse { cancel }).unwrap_or_default(),
326 )),
327 Err(e) => Ok(*api::internal(e)),
328 }
329}
330
331/// Outcome of a log append.
332enum LogWrite {
333 /// The chunk is stored (or was dropped by the cap); the size is the new byte count.
334 Stored(u64),
335 /// This exact chunk was already stored: a retry. The size is unchanged.
336 Duplicate(u64),
337 /// The offset does not match the stored size.
338 Mismatch(u64),
339}
340
341#[route(POST "/api/v1/ci/jobs/{job_id}/logs")]
342async fn append_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
343 let state = app_context::<AppState>(cx);
344 let headers = headers(cx);
345 let job = match job_from(state, headers, path_param::<JobId>(cx)).await {
346 Ok(job) => job,
347 Err(res) => return Ok(*res),
348 };
349 let Some(offset) = headers
350 .get(LOG_OFFSET_HEADER)
351 .and_then(|value| value.to_str().ok())
352 .and_then(|value| value.parse::<u64>().ok())
353 else {
354 return Ok(api::error(
355 StatusCode::BAD_REQUEST,
356 "X-Forge-Log-Offset must be a byte offset",
357 ));
358 };
359 let chunk = match api::read_body(body, MAX_LOG_CHUNK).await {
360 Ok(chunk) => chunk,
361 Err(res) => return Ok(*res),
362 };
363 match write_log(state, &job, offset, &chunk).await {
364 Ok(LogWrite::Stored(size) | LogWrite::Duplicate(size)) => {
365 Ok(api::json(StatusCode::OK, &json!({ "size": size })))
366 }
367 Ok(LogWrite::Mismatch(size)) => {
368 let mut res = api::error(StatusCode::CONFLICT, "the log offset does not match");
369 res.headers_mut().insert(
370 http::HeaderName::from_static(LOG_SIZE_HEADER),
371 HeaderValue::from(size),
372 );
373 Ok(res)
374 }
375 Err(res) => Ok(*res),
376 }
377}
378
379/// Appends one chunk of raw log bytes. Offsets count the raw bytes the runner sent, which is
380/// `job.log_bytes`; the file holds the masked text, so its length may differ.
381async fn write_log(
382 state: &AppState,
383 job: &CiJob,
384 offset: u64,
385 chunk: &[u8],
386) -> Result<LogWrite, Refusal> {
387 let size = u64::try_from(job.log_bytes).unwrap_or(0);
388 let len = chunk.len() as u64;
389 if offset != size {
390 return Ok(if offset.checked_add(len) == Some(size) {
391 LogWrite::Duplicate(size)
392 } else {
393 LogWrite::Mismatch(size)
394 });
395 }
396 if chunk.is_empty() {
397 return Ok(LogWrite::Stored(size));
398 }
399
400 let masked = mask_for_job(state, job, chunk).await?;
401 let path = log_path(&state.config.data_dir, &job.id);
402 store_log_bytes(state, &path, &masked).await?;
403 state
404 .store
405 .add_log_bytes(&job.id, len as i64)
406 .await
407 .map_err(api::internal)?;
408 state.ci_live.bump_job(&job.id);
409 Ok(LogWrite::Stored(size + len))
410}
411
412/// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a
413/// secret split across two requests is masked by the runner, which holds back the boundary.
414async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec<u8>, Refusal> {
415 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
416 if spec.secrets.is_empty() {
417 return Ok(chunk.to_vec());
418 }
419 let Some(run) = state
420 .store
421 .run_by_id(&job.run_id)
422 .await
423 .map_err(api::internal)?
424 else {
425 return Err(api::internal("log for a job with no run"));
426 };
427 let values = state
428 .store
429 .ci_secret_values(&run.repo_id, &spec.secrets)
430 .await
431 .map_err(api::internal)?;
432 let masker = Masker::new(values.into_values());
433 let mut stream = masker.stream();
434 let mut out = stream.push(chunk);
435 out.extend(stream.finish());
436 Ok(out)
437}
438
439/// The bytes of `masked` that may be appended to a log of `current` bytes under a `cap`. Once the
440/// log reaches the cap nothing more is kept. When the new bytes do not fit, the part that does is
441/// kept and the marker follows it, so the file ends at exactly `cap` bytes.
442pub fn fit_to_cap(current: u64, cap: u64, masked: &[u8]) -> Vec<u8> {
443 if current >= cap {
444 return Vec::new();
445 }
446 let data_cap = cap.saturating_sub(TRUNCATED_MARKER.len() as u64);
447 let room = data_cap.saturating_sub(current);
448 if masked.len() as u64 <= room {
449 return masked.to_vec();
450 }
451 let mut out = masked[..room as usize].to_vec();
452 out.extend_from_slice(TRUNCATED_MARKER);
453 out
454}
455
456/// Appends masked bytes to the log file, stopping at the size cap with one marker line.
457async fn store_log_bytes(
458 state: &AppState,
459 path: &std::path::Path,
460 masked: &[u8],
461) -> Result<(), Refusal> {
462 use tokio::io::AsyncWriteExt;
463
464 let cap = state.config.ci.max_log_mb.saturating_mul(MIB);
465 let current = match tokio::fs::metadata(path).await {
466 Ok(meta) => meta.len(),
467 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
468 Err(e) => return Err(api::internal(e)),
469 };
470 let out = fit_to_cap(current, cap, masked);
471 if out.is_empty() {
472 return Ok(());
473 }
474
475 if let Some(parent) = path.parent() {
476 tokio::fs::create_dir_all(parent)
477 .await
478 .map_err(api::internal)?;
479 }
480 let mut file = tokio::fs::OpenOptions::new()
481 .create(true)
482 .append(true)
483 .open(path)
484 .await
485 .map_err(api::internal)?;
486 file.write_all(&out).await.map_err(api::internal)?;
487 file.flush().await.map_err(api::internal)?;
488 Ok(())
489}
490
491#[route(PUT "/api/v1/ci/jobs/{job_id}/artifacts/{artifact_name}")]
492async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
493 let state = app_context::<AppState>(cx);
494 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
495 Ok(job) => job,
496 Err(res) => return Ok(*res),
497 };
498 let name = path_param::<ArtifactName>(cx);
499 if !valid_artifact_name(name) {
500 return Ok(api::error(
501 StatusCode::UNPROCESSABLE_ENTITY,
502 "the artifact name must be 1 to 128 of A-Z a-z 0-9 . _ + - and not start with a dot",
503 ));
504 }
505 match upload(state, &job, name, body).await {
506 Ok(artifact_id) => Ok(api::json(
507 StatusCode::CREATED,
508 &json!({ "id": artifact_id, "name": name }),
509 )),
510 Err(res) => Ok(*res),
511 }
512}
513
514/// Streams the body to a temporary blob, then records the artifact and moves the blob to its
515/// final key `ci/<artifact id>`. The id is only known once the row exists.
516async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result<String, Refusal> {
517 let max_artifacts = state.config.ci.max_artifacts_per_job;
518 let existing = state
519 .store
520 .list_artifacts(&job.id)
521 .await
522 .map_err(api::internal)?;
523 if existing.len() as u64 >= u64::from(max_artifacts) {
524 return Err(Box::new(api::error(
525 StatusCode::CONFLICT,
526 "the job has too many artifacts",
527 )));
528 }
529 if existing.iter().any(|artifact| artifact.name == name) {
530 return Err(Box::new(api::error(
531 StatusCode::CONFLICT,
532 "an artifact with this name already exists",
533 )));
534 }
535
536 let max_bytes = state.config.ci.max_artifact_mb.saturating_mul(MIB);
537 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());
538 let mut writer = state
539 .blobs
540 .begin(&temp_key, max_bytes)
541 .await
542 .map_err(api::internal)?;
543 let mut stream = std::pin::pin!(body.into_data_stream());
544 while let Some(next) = stream.next().await {
545 let outcome = match next {
546 Ok(chunk) => writer.push(&chunk).await.map_err(|e| (e, false)),
547 Err(_) => Err((CoreError::Invalid("upload interrupted".into()), true)),
548 };
549 if let Err((e, interrupted)) = outcome {
550 writer.abort().await;
551 return Err(upload_failure(e, interrupted));
552 }
553 }
554 let (size, sha256) = match writer.finish().await {
555 Ok(done) => done,
556 Err(e) => {
557 discard_temp(state, &temp_key).await;
558 return Err(api::internal(e));
559 }
560 };
561
562 let artifact = match state
563 .store
564 .add_artifact(&job.id, name, size as i64, &sha256)
565 .await
566 {
567 Ok(artifact) => artifact,
568 Err(e) => {
569 discard_temp(state, &temp_key).await;
570 return Err(match e {
571 CoreError::Invalid(message) => Box::new(api::error(StatusCode::CONFLICT, &message)),
572 other => api::internal(other),
573 });
574 }
575 };
576 let final_key = artifact_key(&artifact.id);
577 if let Err(e) = state.blobs.rename(&temp_key, &final_key).await {
578 discard_temp(state, &temp_key).await;
579 return Err(api::internal(e));
580 }
581 Ok(artifact.id)
582}
583
584/// Removes a temporary blob. A failure is logged; the blob is unreachable either way.
585async fn discard_temp(state: &AppState, key: &str) {
586 if let Err(e) = state.blobs.delete(key).await {
587 tracing::error!(error = %e, "ci: could not remove a temporary artifact blob");
588 }
589}
590
591fn upload_failure(e: CoreError, interrupted: bool) -> Refusal {
592 match e {
593 CoreError::Invalid(_) if !interrupted => Box::new(api::error(
594 StatusCode::PAYLOAD_TOO_LARGE,
595 "the artifact is larger than the upload limit",
596 )),
597 CoreError::Invalid(message) => Box::new(api::error(StatusCode::BAD_REQUEST, &message)),
598 other => api::internal(other),
599 }
600}
601
602// ---------------------------------------------------------------------------------------------
603// Finish
604// ---------------------------------------------------------------------------------------------
605
606#[route(POST "/api/v1/ci/jobs/{job_id}/finish")]
607async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
608 let state = app_context::<AppState>(cx);
609 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
610 Ok(job) => job,
611 Err(res) => return Ok(*res),
612 };
613 let request: FinishRequest = match json_body(body).await {
614 Ok(request) => request,
615 Err(res) => return Ok(*res),
616 };
617 let state_after = match request.outcome {
618 Outcome::Success => JobState::Success,
619 Outcome::Failure => JobState::Failure,
620 Outcome::Cancelled => JobState::Cancelled,
621 Outcome::Error => JobState::Error,
622 };
623 match finish_job(state, &job, state_after, &request).await {
624 Ok(state_name) => Ok(api::json(StatusCode::OK, &json!({ "state": state_name }))),
625 Err(res) => Ok(*res),
626 }
627}
628
629/// Finishes the job, then syncs the statuses of the job and of every job whose state changed
630/// (skipped or queued by this finish). Wakes the claimers when something was queued, and the
631/// watchers of every job and run that changed.
632async fn finish_job(
633 state: &AppState,
634 job: &CiJob,
635 outcome: JobState,
636 request: &FinishRequest,
637) -> Result<&'static str, Refusal> {
638 let before: BTreeMap<String, JobState> = state
639 .store
640 .jobs_for_run(&job.run_id)
641 .await
642 .map_err(api::internal)?
643 .into_iter()
644 .map(|other| (other.id, other.state))
645 .collect();
646 let exit_code = request.exit_code.map(i64::from);
647 let run = state
648 .store
649 .finish_job(&job.id, outcome, exit_code, request.message.as_deref())
650 .await
651 .map_err(api::internal)?;
652
653 let mut queued = false;
654 let mut any_changed = false;
655 for other in state
656 .store
657 .jobs_for_run(&job.run_id)
658 .await
659 .map_err(api::internal)?
660 {
661 let changed = before.get(&other.id) != Some(&other.state);
662 if changed {
663 any_changed = true;
664 if other.state.is_terminal() {
665 state.ci_live.close_job(&other.id);
666 } else {
667 state.ci_live.bump_job(&other.id);
668 }
669 }
670 if other.id == job.id
671 || (changed && matches!(other.state, JobState::Skipped | JobState::Queued))
672 {
673 queued |= other.state == JobState::Queued;
674 crate::ci::sync_status(state, &run, &other).await;
675 }
676 }
677 if any_changed {
678 state.ci_live.bump_run(&run.id);
679 state.ci_live.bump_repo(&run.repo_id);
680 }
681 if queued {
682 state.ci_waker.notify_waiters();
683 }
684 // A run that just went green may deploy the forge itself.
685 self_update::maybe_deploy(state, &run).await;
686 Ok(run.state.as_str())
687}
688
689#[cfg(test)]
690#[path = "api_tests.rs"]
691mod tests;