forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB51b2bbfTahinli1 month ago19 commits

api.rs787 lines, 27.1 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, RunState};
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 let (cache_key, cache_restore_keys) =
274 cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?;
275
276 Ok(Some(JobAssignment {
277 job_id: job.id,
278 job_token,
279 repo: format!("{}/{}", repo.owner_name, repo.name),
280 clone_url: https_clone_url(&state.config, &repo.owner_name, &repo.name),
281 commit: run.commit_oid,
282 git_ref: run.git_ref,
283 job_name: job.name,
284 image: spec.image,
285 run: spec.run,
286 env: spec.env,
287 secrets,
288 artifacts: spec.artifacts,
289 timeout_minutes: spec.timeout_minutes,
290 network: spec.network,
291 cache: spec.cache,
292 cache_key,
293 cache_restore_keys,
294 }))
295}
296
297/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base
298/// branch comes from its pull request record.
299async fn cache_scopes(
300 state: &AppState,
301 run: &CiRun,
302 default_branch: &str,
303 cache: &[String],
304) -> Result<(String, Vec<String>), Refusal> {
305 if cache.is_empty() {
306 return Ok((String::new(), Vec::new()));
307 }
308 let pull_base = match (run.trigger.as_str(), run.pull_number) {
309 ("pull_request", Some(number)) => state
310 .store
311 .pull_by_number(&run.repo_id, number)
312 .await
313 .map_err(api::internal)?
314 .map(|pull| pull.base_branch),
315 _ => None,
316 };
317 let scope = cache_scope(
318 &run.trigger,
319 &run.git_ref,
320 run.pull_number,
321 pull_base.as_deref(),
322 default_branch,
323 );
324 Ok(match scope {
325 Some(scope) => (scope.key, scope.restore_keys),
326 // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves.
327 None => (String::new(), Vec::new()),
328 })
329}
330
331/// The cache scope a run may write, and the read-only scopes it may restore from.
332#[derive(Debug, Clone, PartialEq, Eq)]
333struct CacheScope {
334 key: String,
335 restore_keys: Vec<String>,
336}
337
338/// Derives the cache scopes of a run. Returns `None` when no scope can be derived.
339///
340/// Only pull request runs get `pr:` keys and only non-pull-request runs get `ref:` keys. The
341/// choice follows the run's trigger, never the ref name, so a pull request from a branch named
342/// `main` still writes `pr:N`. A pull request run reads its base branch's cache, a branch or tag
343/// run reads the default branch's cache, and both fall back to nothing else.
344fn cache_scope(
345 trigger: &str,
346 git_ref: &str,
347 pull_number: Option<i64>,
348 pull_base: Option<&str>,
349 default_branch: &str,
350) -> Option<CacheScope> {
351 let default_ref = format!("ref:refs/heads/{default_branch}");
352 match trigger {
353 "pull_request" => {
354 let number = pull_number?;
355 let mut restore_keys = Vec::new();
356 if let Some(base) = pull_base {
357 restore_keys.push(format!("ref:refs/heads/{base}"));
358 }
359 if pull_base != Some(default_branch) {
360 restore_keys.push(default_ref);
361 }
362 Some(CacheScope {
363 key: format!("pr:{number}"),
364 restore_keys,
365 })
366 }
367 "push" | "tag" | "manual" | "schedule" => {
368 let restore_keys = if git_ref == format!("refs/heads/{default_branch}") {
369 Vec::new()
370 } else {
371 vec![default_ref]
372 };
373 Some(CacheScope {
374 key: format!("ref:{git_ref}"),
375 restore_keys,
376 })
377 }
378 _ => None,
379 }
380}
381
382/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such
383/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.
384async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {
385 if run.trigger != "pull_request" {
386 return Ok(false);
387 }
388 let Some(number) = run.pull_number else {
389 return Ok(true);
390 };
391 match state
392 .store
393 .pull_by_number(&run.repo_id, number)
394 .await
395 .map_err(api::internal)?
396 {
397 Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())),
398 None => Ok(true),
399 }
400}
401
402// ---------------------------------------------------------------------------------------------
403// Heartbeat, logs and artifacts
404// ---------------------------------------------------------------------------------------------
405
406#[route(POST "/api/v1/ci/jobs/{job_id}/heartbeat")]
407async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
408 let state = app_context::<AppState>(cx);
409 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
410 Ok(job) => job,
411 Err(res) => return Ok(*res),
412 };
413 match state.store.heartbeat(&job.id).await {
414 Ok(cancel) => Ok(api::json(
415 StatusCode::OK,
416 &serde_json::to_value(HeartbeatResponse { cancel }).unwrap_or_default(),
417 )),
418 Err(e) => Ok(*api::internal(e)),
419 }
420}
421
422/// Outcome of a log append.
423enum LogWrite {
424 /// The chunk is stored (or was dropped by the cap); the size is the new byte count.
425 Stored(u64),
426 /// This exact chunk was already stored: a retry. The size is unchanged.
427 Duplicate(u64),
428 /// The offset does not match the stored size.
429 Mismatch(u64),
430}
431
432#[route(POST "/api/v1/ci/jobs/{job_id}/logs")]
433async fn append_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
434 let state = app_context::<AppState>(cx);
435 let headers = headers(cx);
436 let job = match job_from(state, headers, path_param::<JobId>(cx)).await {
437 Ok(job) => job,
438 Err(res) => return Ok(*res),
439 };
440 let Some(offset) = headers
441 .get(LOG_OFFSET_HEADER)
442 .and_then(|value| value.to_str().ok())
443 .and_then(|value| value.parse::<u64>().ok())
444 else {
445 return Ok(api::error(
446 StatusCode::BAD_REQUEST,
447 "X-Forge-Log-Offset must be a byte offset",
448 ));
449 };
450 let chunk = match api::read_body(body, MAX_LOG_CHUNK).await {
451 Ok(chunk) => chunk,
452 Err(res) => return Ok(*res),
453 };
454 match write_log(state, &job, offset, &chunk).await {
455 Ok(LogWrite::Stored(size) | LogWrite::Duplicate(size)) => {
456 Ok(api::json(StatusCode::OK, &json!({ "size": size })))
457 }
458 Ok(LogWrite::Mismatch(size)) => {
459 let mut res = api::error(StatusCode::CONFLICT, "the log offset does not match");
460 res.headers_mut().insert(
461 http::HeaderName::from_static(LOG_SIZE_HEADER),
462 HeaderValue::from(size),
463 );
464 Ok(res)
465 }
466 Err(res) => Ok(*res),
467 }
468}
469
470/// Appends one chunk of raw log bytes. Offsets count the raw bytes the runner sent, which is
471/// `job.log_bytes`; the file holds the masked text, so its length may differ.
472async fn write_log(
473 state: &AppState,
474 job: &CiJob,
475 offset: u64,
476 chunk: &[u8],
477) -> Result<LogWrite, Refusal> {
478 let size = u64::try_from(job.log_bytes).unwrap_or(0);
479 let len = chunk.len() as u64;
480 if offset != size {
481 return Ok(if offset.checked_add(len) == Some(size) {
482 LogWrite::Duplicate(size)
483 } else {
484 LogWrite::Mismatch(size)
485 });
486 }
487 if chunk.is_empty() {
488 return Ok(LogWrite::Stored(size));
489 }
490
491 let masked = mask_for_job(state, job, chunk).await?;
492 let path = log_path(&state.config.data_dir, &job.id);
493 store_log_bytes(state, &path, &masked).await?;
494 state
495 .store
496 .add_log_bytes(&job.id, len as i64)
497 .await
498 .map_err(api::internal)?;
499 state.ci_live.bump_job(&job.id);
500 Ok(LogWrite::Stored(size + len))
501}
502
503/// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a
504/// secret split across two requests is masked by the runner, which holds back the boundary.
505async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec<u8>, Refusal> {
506 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
507 if spec.secrets.is_empty() {
508 return Ok(chunk.to_vec());
509 }
510 let Some(run) = state
511 .store
512 .run_by_id(&job.run_id)
513 .await
514 .map_err(api::internal)?
515 else {
516 return Err(api::internal("log for a job with no run"));
517 };
518 let values = state
519 .store
520 .ci_secret_values(&run.repo_id, &spec.secrets)
521 .await
522 .map_err(api::internal)?;
523 let masker = Masker::new(values.into_values());
524 let mut stream = masker.stream();
525 let mut out = stream.push(chunk);
526 out.extend(stream.finish());
527 Ok(out)
528}
529
530/// The bytes of `masked` that may be appended to a log of `current` bytes under a `cap`. Once the
531/// log reaches the cap nothing more is kept. When the new bytes do not fit, the part that does is
532/// kept and the marker follows it, so the file ends at exactly `cap` bytes.
533pub fn fit_to_cap(current: u64, cap: u64, masked: &[u8]) -> Vec<u8> {
534 if current >= cap {
535 return Vec::new();
536 }
537 let data_cap = cap.saturating_sub(TRUNCATED_MARKER.len() as u64);
538 let room = data_cap.saturating_sub(current);
539 if masked.len() as u64 <= room {
540 return masked.to_vec();
541 }
542 let mut out = masked[..room as usize].to_vec();
543 out.extend_from_slice(TRUNCATED_MARKER);
544 out
545}
546
547/// Appends masked bytes to the log file, stopping at the size cap with one marker line.
548async fn store_log_bytes(
549 state: &AppState,
550 path: &std::path::Path,
551 masked: &[u8],
552) -> Result<(), Refusal> {
553 use tokio::io::AsyncWriteExt;
554
555 let cap = state.config.ci.max_log_mb.saturating_mul(MIB);
556 let current = match tokio::fs::metadata(path).await {
557 Ok(meta) => meta.len(),
558 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
559 Err(e) => return Err(api::internal(e)),
560 };
561 let out = fit_to_cap(current, cap, masked);
562 if out.is_empty() {
563 return Ok(());
564 }
565
566 if let Some(parent) = path.parent() {
567 tokio::fs::create_dir_all(parent)
568 .await
569 .map_err(api::internal)?;
570 }
571 let mut file = tokio::fs::OpenOptions::new()
572 .create(true)
573 .append(true)
574 .open(path)
575 .await
576 .map_err(api::internal)?;
577 file.write_all(&out).await.map_err(api::internal)?;
578 file.flush().await.map_err(api::internal)?;
579 Ok(())
580}
581
582#[route(PUT "/api/v1/ci/jobs/{job_id}/artifacts/{artifact_name}")]
583async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
584 let state = app_context::<AppState>(cx);
585 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
586 Ok(job) => job,
587 Err(res) => return Ok(*res),
588 };
589 let name = path_param::<ArtifactName>(cx);
590 if !valid_artifact_name(name) {
591 return Ok(api::error(
592 StatusCode::UNPROCESSABLE_ENTITY,
593 "the artifact name must be 1 to 128 of A-Z a-z 0-9 . _ + - and not start with a dot",
594 ));
595 }
596 match upload(state, &job, name, body).await {
597 Ok(artifact_id) => Ok(api::json(
598 StatusCode::CREATED,
599 &json!({ "id": artifact_id, "name": name }),
600 )),
601 Err(res) => Ok(*res),
602 }
603}
604
605/// Streams the body to a temporary blob, then records the artifact and moves the blob to its
606/// final key `ci/<artifact id>`. The id is only known once the row exists.
607async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result<String, Refusal> {
608 let max_artifacts = state.config.ci.max_artifacts_per_job;
609 let existing = state
610 .store
611 .list_artifacts(&job.id)
612 .await
613 .map_err(api::internal)?;
614 if existing.len() as u64 >= u64::from(max_artifacts) {
615 return Err(Box::new(api::error(
616 StatusCode::CONFLICT,
617 "the job has too many artifacts",
618 )));
619 }
620 if existing.iter().any(|artifact| artifact.name == name) {
621 return Err(Box::new(api::error(
622 StatusCode::CONFLICT,
623 "an artifact with this name already exists",
624 )));
625 }
626
627 let max_bytes = state.config.ci.max_artifact_mb.saturating_mul(MIB);
628 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());
629 let mut writer = state
630 .blobs
631 .begin(&temp_key, max_bytes)
632 .await
633 .map_err(api::internal)?;
634 let mut stream = std::pin::pin!(body.into_data_stream());
635 while let Some(next) = stream.next().await {
636 let outcome = match next {
637 Ok(chunk) => writer.push(&chunk).await.map_err(|e| (e, false)),
638 Err(_) => Err((CoreError::Invalid("upload interrupted".into()), true)),
639 };
640 if let Err((e, interrupted)) = outcome {
641 writer.abort().await;
642 return Err(upload_failure(e, interrupted));
643 }
644 }
645 let (size, sha256) = match writer.finish().await {
646 Ok(done) => done,
647 Err(e) => {
648 discard_temp(state, &temp_key).await;
649 return Err(api::internal(e));
650 }
651 };
652
653 let artifact = match state
654 .store
655 .add_artifact(&job.id, name, size as i64, &sha256)
656 .await
657 {
658 Ok(artifact) => artifact,
659 Err(e) => {
660 discard_temp(state, &temp_key).await;
661 return Err(match e {
662 CoreError::Invalid(message) => Box::new(api::error(StatusCode::CONFLICT, &message)),
663 other => api::internal(other),
664 });
665 }
666 };
667 let final_key = artifact_key(&artifact.id);
668 if let Err(e) = state.blobs.rename(&temp_key, &final_key).await {
669 discard_temp(state, &temp_key).await;
670 return Err(api::internal(e));
671 }
672 Ok(artifact.id)
673}
674
675/// Removes a temporary blob. A failure is logged; the blob is unreachable either way.
676async fn discard_temp(state: &AppState, key: &str) {
677 if let Err(e) = state.blobs.delete(key).await {
678 tracing::error!(error = %e, "ci: could not remove a temporary artifact blob");
679 }
680}
681
682fn upload_failure(e: CoreError, interrupted: bool) -> Refusal {
683 match e {
684 CoreError::Invalid(_) if !interrupted => Box::new(api::error(
685 StatusCode::PAYLOAD_TOO_LARGE,
686 "the artifact is larger than the upload limit",
687 )),
688 CoreError::Invalid(message) => Box::new(api::error(StatusCode::BAD_REQUEST, &message)),
689 other => api::internal(other),
690 }
691}
692
693// ---------------------------------------------------------------------------------------------
694// Finish
695// ---------------------------------------------------------------------------------------------
696
697#[route(POST "/api/v1/ci/jobs/{job_id}/finish")]
698async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
699 let state = app_context::<AppState>(cx);
700 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
701 Ok(job) => job,
702 Err(res) => return Ok(*res),
703 };
704 let request: FinishRequest = match json_body(body).await {
705 Ok(request) => request,
706 Err(res) => return Ok(*res),
707 };
708 let state_after = match request.outcome {
709 Outcome::Success => JobState::Success,
710 Outcome::Failure => JobState::Failure,
711 Outcome::Cancelled => JobState::Cancelled,
712 Outcome::Error => JobState::Error,
713 };
714 match finish_job(state, &job, state_after, &request).await {
715 Ok(state_name) => Ok(api::json(StatusCode::OK, &json!({ "state": state_name }))),
716 Err(res) => Ok(*res),
717 }
718}
719
720/// Finishes the job, then syncs the statuses of the job and of every job whose state changed
721/// (skipped or queued by this finish). Wakes the claimers when something was queued, and the
722/// watchers of every job and run that changed.
723async fn finish_job(
724 state: &AppState,
725 job: &CiJob,
726 outcome: JobState,
727 request: &FinishRequest,
728) -> Result<&'static str, Refusal> {
729 let before: BTreeMap<String, JobState> = state
730 .store
731 .jobs_for_run(&job.run_id)
732 .await
733 .map_err(api::internal)?
734 .into_iter()
735 .map(|other| (other.id, other.state))
736 .collect();
737 let exit_code = request.exit_code.map(i64::from);
738 let run = state
739 .store
740 .finish_job(&job.id, outcome, exit_code, request.message.as_deref())
741 .await
742 .map_err(api::internal)?;
743
744 let mut queued = false;
745 let mut any_changed = false;
746 for other in state
747 .store
748 .jobs_for_run(&job.run_id)
749 .await
750 .map_err(api::internal)?
751 {
752 let changed = before.get(&other.id) != Some(&other.state);
753 if changed {
754 any_changed = true;
755 if other.state.is_terminal() {
756 state.ci_live.close_job(&other.id);
757 } else {
758 state.ci_live.bump_job(&other.id);
759 }
760 }
761 if other.id == job.id
762 || (changed && matches!(other.state, JobState::Skipped | JobState::Queued))
763 {
764 queued |= other.state == JobState::Queued;
765 crate::ci::sync_status(state, &run, &other).await;
766 }
767 }
768 if any_changed {
769 state.ci_live.bump_run(&run.id);
770 state.ci_live.bump_repo(&run.repo_id);
771 }
772 if queued {
773 state.ci_waker.notify_waiters();
774 }
775 // A run that just went green may deploy the forge itself.
776 self_update::maybe_deploy(state, &run).await;
777 // A tag run that went green may publish a release. The request does not wait for it.
778 if run.state == RunState::Success {
779 let (state, run) = (state.clone(), run.clone());
780 tokio::spawn(async move { crate::ci::release::on_run_finished(&state, &run).await });
781 }
782 Ok(run.state.as_str())
783}
784
785#[cfg(test)]
786#[path = "api_tests.rs"]
787mod tests;