forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.08.8 MiBb00f3f4Tahinli1 month ago147 commits

api.rs1063 lines, 37.9 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,
16};
17use forge_core::Error as CoreError;
18use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport};
19use futures_util::StreamExt;
20use http::header::HeaderValue;
21use serde_json::json;
22use std::collections::BTreeMap;
23use topcoat::context::{Cx, app_context};
24use topcoat::router::request::headers;
25use topcoat::router::response::Response;
26use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route};
27
28use crate::api::{self, Refusal};
29use crate::ci::{artifact_key, log_path};
30use crate::pages::repo::https_clone_url;
31use crate::self_update;
32use crate::state::AppState;
33
34path_param!(job_id);
35path_param!(artifact_name);
36
37/// Header carrying the byte offset of a log chunk.
38const LOG_OFFSET_HEADER: &str = "x-forge-log-offset";
39/// Header on a 409 log response carrying the size the server has.
40const LOG_SIZE_HEADER: &str = "x-forge-log-size";
41/// Largest log chunk, in bytes.
42const MAX_LOG_CHUNK: usize = 1024 * 1024;
43/// Largest JSON body on the runner routes, in bytes.
44const MAX_JSON_BODY: usize = 64 * 1024;
45/// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.
46const DEFAULT_RESERVE: u64 = 1 << 30;
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)) => {
84 crate::alerts::runner_seen(state, &runner.id).await;
85 Ok(runner)
86 }
87 Ok(None) => Err(unauthorized()),
88 Err(e) => Err(api::internal(e)),
89 }
90}
91
92/// The job behind the Bearer job token. Only Running jobs match, so a finished job gets 401.
93async fn job_from(state: &AppState, headers: &HeaderMap, job_id: &str) -> Result<CiJob, Refusal> {
94 let Some(token) = bearer_token(headers) else {
95 return Err(unauthorized());
96 };
97 match state.store.job_by_token(job_id, token).await {
98 Ok(Some(job)) => Ok(job),
99 Ok(None) => Err(unauthorized()),
100 Err(e) => Err(api::internal(e)),
101 }
102}
103
104/// Parses a JSON body of at most [`MAX_JSON_BODY`] bytes.
105async fn json_body<T: serde::de::DeserializeOwned>(body: Body) -> Result<T, Refusal> {
106 let bytes = api::read_body(body, MAX_JSON_BODY).await?;
107 serde_json::from_slice(&bytes).map_err(|e| {
108 Box::new(api::error(
109 StatusCode::BAD_REQUEST,
110 &format!("invalid JSON body: {e}"),
111 ))
112 })
113}
114
115fn valid_name(value: &str) -> bool {
116 !value.trim().is_empty() && value.len() <= MAX_NAME_BYTES && !value.contains(char::is_control)
117}
118
119/// `[A-Za-z0-9._+-]{1,128}`, and not starting with a dot.
120pub fn valid_artifact_name(name: &str) -> bool {
121 !name.is_empty()
122 && name.len() <= 128
123 && !name.starts_with('.')
124 && name
125 .bytes()
126 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-'))
127}
128
129// ---------------------------------------------------------------------------------------------
130// Registration and claims
131// ---------------------------------------------------------------------------------------------
132
133#[route(POST "/api/v1/ci/runners/register")]
134async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
135 let state = app_context::<AppState>(cx);
136 let request: RegisterRequest = match json_body(body).await {
137 Ok(request) => request,
138 Err(res) => return Ok(*res),
139 };
140 if !valid_name(&request.name) || request.labels.len() > MAX_LABELS {
141 return Ok(api::error(
142 StatusCode::UNPROCESSABLE_ENTITY,
143 "the runner name or labels are invalid",
144 ));
145 }
146 if request.labels.iter().any(|label| !valid_name(label)) {
147 return Ok(api::error(
148 StatusCode::UNPROCESSABLE_ENTITY,
149 "the runner name or labels are invalid",
150 ));
151 }
152 match state
153 .store
154 .register_runner(&request.token, request.name.trim(), &request.labels)
155 .await
156 {
157 Ok((runner, secret)) => {
158 state.ci_live.bump_runners();
159 let body = RegisterResponse {
160 runner_id: runner.id,
161 runner_secret: secret,
162 };
163 Ok(api::json(
164 StatusCode::CREATED,
165 &serde_json::to_value(&body).unwrap_or_default(),
166 ))
167 }
168 Err(CoreError::Invalid(_)) => Ok(api::error(
169 StatusCode::UNAUTHORIZED,
170 "the registration token is unknown, used or expired",
171 )),
172 Err(e) => Ok(*api::internal(e)),
173 }
174}
175
176#[route(POST "/api/v1/ci/runners/claim")]
177async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
178 let state = app_context::<AppState>(cx);
179 // The labels in the request are ignored: the labels stored at registration are used.
180 let runner = match runner_from(state, headers(cx)).await {
181 Ok(runner) => runner,
182 Err(res) => return Ok(*res),
183 };
184 // What the runner says about itself. An older runner sends only labels, and a body that does
185 // not parse is not worth failing a claim over.
186 let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await {
187 Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
188 Err(_) => ClaimRequest::default(),
189 };
190 // An older runner sends no free memory, and then the oldest compatible job is handed out.
191 let offer = request.free_memory_bytes.map(|free| MemoryOffer {
192 free,
193 budget: request.memory_budget_bytes,
194 default_reserve: request.reserve_memory_bytes.unwrap_or(DEFAULT_RESERVE),
195 });
196 note_report(
197 state,
198 &runner.id,
199 &RunnerReport {
200 memory_budget: request.memory_budget_bytes,
201 memory_free: request.free_memory_bytes,
202 memory_reserve: request.reserve_memory_bytes,
203 concurrency: request.concurrency,
204 version: request.version.filter(|v| v.len() <= 64),
205 cpus: request.cpus,
206 memory_bytes: request.memory_bytes,
207 build: request.build.filter(|v| v.len() <= 64),
208 boot_id: request.boot_id.filter(|v| v.len() <= 64),
209 capabilities: request
210 .capabilities
211 .into_iter()
212 .filter(|c| !c.is_empty() && c.len() <= 32 && !c.contains(','))
213 .take(16)
214 .collect(),
215 },
216 )
217 .await;
218 let mut res = claim_work(state, &runner, offer).await?;
219 // The override can change during the long poll, so it is read at answer time.
220 set_concurrency_header(state, &runner.id, &mut res).await;
221 set_memory_headers(state, &runner.id, &mut res).await;
222 set_restart_header(state, &runner.id, &mut res).await;
223 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
224 self_update::advertise(state, headers(cx), &mut res);
225 Ok(res)
226}
227
228/// Stores a runner's self report and wakes the admin pages when it changed something.
229async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {
230 match state.store.record_runner_report(runner_id, report).await {
231 Ok(true) => state.ci_live.bump_runners(),
232 Ok(false) => {}
233 Err(e) => tracing::warn!(error = %e, "ci: runner report not stored"),
234 }
235}
236
237/// Adds the admin's concurrency override to a claim answer. No header means no override.
238async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) {
239 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
240 return;
241 }
242 if let Ok(Some(n)) = state.store.runner_concurrency_override(runner_id).await
243 && let Ok(value) = HeaderValue::from_str(&n.to_string())
244 {
245 res.headers_mut().insert(CONCURRENCY_HEADER, value);
246 }
247}
248
249/// Adds the admin's memory budget and default reservation to a claim answer. No header means no
250/// override. An older runner ignores both.
251async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Response) {
252 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
253 return;
254 }
255 for (key, header) in [
256 ("limits.memory_budget", MEMORY_BUDGET_HEADER),
257 ("limits.reserve_memory", RESERVE_MEMORY_HEADER),
258 ] {
259 if let Ok(Some(text)) = state.store.runner_field_override(runner_id, key).await
260 && let Ok(value) = HeaderValue::from_str(&text)
261 {
262 res.headers_mut().insert(header, value);
263 }
264 }
265}
266
267/// The restart an admin asked for, in the wire type. `None` when nothing is pending.
268async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> {
269 let mode = state.store.runner_restart(runner_id).await.ok().flatten()?;
270 WireRestart::parse(mode.as_str())
271}
272
273/// Adds the pending restart request to a claim answer. Sent on every answer until the runner
274/// comes back with a new boot id. An older runner ignores the header.
275async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) {
276 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
277 return;
278 }
279 if let Some(mode) = pending_restart(state, runner_id).await {
280 res.headers_mut()
281 .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str()));
282 }
283}
284
285/// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
286/// starts, applies them to its in-memory config, then reports its effective config here.
287#[route(GET "/api/v1/ci/runners/config")]
288async fn runner_config_get(cx: &Cx) -> topcoat::Result<Response> {
289 let state = app_context::<AppState>(cx);
290 let runner = match runner_from(state, headers(cx)).await {
291 Ok(runner) => runner,
292 Err(res) => return Ok(*res),
293 };
294 Ok(overrides_response(&runner))
295}
296
297#[route(PUT "/api/v1/ci/runners/config")]
298async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result<Response> {
299 let state = app_context::<AppState>(cx);
300 let runner = match runner_from(state, headers(cx)).await {
301 Ok(runner) => runner,
302 Err(res) => return Ok(*res),
303 };
304 let report: RunnerConfigReport = match json_body(body).await {
305 Ok(report) => report,
306 Err(res) => return Ok(*res),
307 };
308 // Only known fields are kept, and the secret is never stored whatever the runner sent.
309 let mut config = report.config;
310 config.retain(|key, _| forge_core::ci::runner_field(key).is_some());
311 config.insert("runner_secret".into(), json!("<redacted>"));
312 match state
313 .store
314 .set_runner_reported_config(&runner.id, &config)
315 .await
316 {
317 Ok(true) => state.ci_live.bump_runners(),
318 Ok(false) => {}
319 Err(e) => return Ok(*api::internal(e)),
320 }
321 Ok(overrides_response(&runner))
322}
323
324fn overrides_response(runner: &CiRunner) -> Response {
325 let reply = RunnerConfigOverrides {
326 overrides: runner.config_overrides.clone(),
327 };
328 api::json(
329 StatusCode::OK,
330 &serde_json::to_value(reply).unwrap_or_default(),
331 )
332}
333
334async fn claim_work(
335 state: &AppState,
336 runner: &CiRunner,
337 offer: Option<MemoryOffer>,
338) -> topcoat::Result<Response> {
339 // Arm the wake-up before each attempt, so a job queued during the attempt is not missed.
340 // Producers use notify_waiters, which wakes every claimer, so a runner whose labels
341 // don't match a job re-arms and keeps waiting for the rest of the claim wait.
342 let waker = state.ci_waker.clone();
343 let wait = std::time::Duration::from_millis(state.config.ci.claim_wait_ms);
344 let deadline = tokio::time::Instant::now() + wait;
345 loop {
346 let mut woken = std::pin::pin!(waker.notified());
347 woken.as_mut().enable();
348
349 // A runner that is to restart gets no new job. It is answered at once, so it sees the
350 // request without waiting out the long poll.
351 if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) {
352 return Ok(empty(StatusCode::NO_CONTENT));
353 }
354 match try_claim(state, runner, offer).await {
355 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),
356 Ok(None) => {}
357 Err(res) => return Ok(*res),
358 }
359 if tokio::time::timeout_at(deadline, woken.as_mut())
360 .await
361 .is_err()
362 {
363 return Ok(empty(StatusCode::NO_CONTENT));
364 }
365 }
366}
367
368/// The running binary, for a runner that updates itself. 404 unless self-update is enabled.
369#[route(GET "/api/v1/ci/runners/binary")]
370async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {
371 let state = app_context::<AppState>(cx);
372 if let Err(res) = runner_from(state, headers(cx)).await {
373 return Ok(*res);
374 }
375 if !state.config.self_update.enabled {
376 return Ok(api::error(StatusCode::NOT_FOUND, "self-update is disabled"));
377 }
378 match self_update::binary_response().await {
379 Ok(res) => Ok(res),
380 Err(e) => {
381 tracing::error!(error = %e, "ci: serving the runner binary failed");
382 Ok(api::error(
383 StatusCode::INTERNAL_SERVER_ERROR,
384 "the binary is unavailable",
385 ))
386 }
387 }
388}
389
390fn assignment_response(assignment: &JobAssignment) -> Response {
391 api::json(
392 StatusCode::OK,
393 &serde_json::to_value(assignment).unwrap_or_default(),
394 )
395}
396
397fn empty(status: StatusCode) -> Response {
398 let mut res = Response::new(topcoat::router::Body::empty());
399 *res.status_mut() = status;
400 res
401}
402
403/// One claim attempt. Builds the assignment, including the secrets the job may see.
404async fn try_claim(
405 state: &AppState,
406 runner: &CiRunner,
407 offer: Option<MemoryOffer>,
408) -> Result<Option<JobAssignment>, Refusal> {
409 let Some((job, run, job_token)) = state
410 .store
411 .claim_job_fitting(runner, offer)
412 .await
413 .map_err(api::internal)?
414 else {
415 return Ok(None);
416 };
417 state.ci_live.bump_job(&job.id);
418 state.ci_live.bump_run(&run.id);
419 state.ci_live.bump_repo(&run.repo_id);
420 state.ci_live.bump_runners();
421 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
422 let repo = state
423 .store
424 .repo_by_id(&run.repo_id)
425 .await
426 .map_err(api::internal)?
427 .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?;
428
429 let secrets = if is_fork_run(state, &run).await? {
430 BTreeMap::new()
431 } else {
432 state
433 .store
434 .ci_secret_values(&run.repo_id, &spec.secrets)
435 .await
436 .map_err(api::internal)?
437 };
438
439 let (cache_key, cache_restore_keys) =
440 cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?;
441
442 Ok(Some(JobAssignment {
443 job_id: job.id,
444 job_token,
445 repo: format!("{}/{}", repo.owner_name, repo.name),
446 clone_url: https_clone_url(&state.config, &repo.owner_name, &repo.name),
447 commit: run.commit_oid,
448 git_ref: run.git_ref,
449 job_name: job.name,
450 image: spec.image,
451 run: spec.run,
452 env: spec.env,
453 secrets,
454 artifacts: spec.artifacts,
455 timeout_minutes: spec.timeout_minutes,
456 network: spec.network,
457 cache: spec.cache,
458 cache_key,
459 cache_restore_keys,
460 memory_bytes: spec.memory,
461 }))
462}
463
464/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base
465/// branch comes from its pull request record.
466async fn cache_scopes(
467 state: &AppState,
468 run: &CiRun,
469 default_branch: &str,
470 cache: &[String],
471) -> Result<(String, Vec<String>), Refusal> {
472 if cache.is_empty() {
473 return Ok((String::new(), Vec::new()));
474 }
475 let pull_base = match (run.trigger.as_str(), run.pull_number) {
476 ("pull_request", Some(number)) => state
477 .store
478 .pull_by_number(&run.repo_id, number)
479 .await
480 .map_err(api::internal)?
481 .map(|pull| pull.base_branch),
482 _ => None,
483 };
484 let scope = cache_scope(
485 &run.trigger,
486 &run.git_ref,
487 run.pull_number,
488 pull_base.as_deref(),
489 default_branch,
490 );
491 Ok(match scope {
492 Some(scope) => (scope.key, scope.restore_keys),
493 // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves.
494 None => (String::new(), Vec::new()),
495 })
496}
497
498/// The cache scope a run may write, and the read-only scopes it may restore from.
499#[derive(Debug, Clone, PartialEq, Eq)]
500struct CacheScope {
501 key: String,
502 restore_keys: Vec<String>,
503}
504
505/// Derives the cache scopes of a run. Returns `None` when no scope can be derived.
506///
507/// Only pull request runs get `pr:` keys and only non-pull-request runs get `ref:` keys. The
508/// choice follows the run's trigger, never the ref name, so a pull request from a branch named
509/// `main` still writes `pr:N`. A pull request run reads its base branch's cache, a branch or tag
510/// run reads the default branch's cache, and both fall back to nothing else.
511fn cache_scope(
512 trigger: &str,
513 git_ref: &str,
514 pull_number: Option<i64>,
515 pull_base: Option<&str>,
516 default_branch: &str,
517) -> Option<CacheScope> {
518 let default_ref = format!("ref:refs/heads/{default_branch}");
519 match trigger {
520 "pull_request" => {
521 let number = pull_number?;
522 let mut restore_keys = Vec::new();
523 if let Some(base) = pull_base {
524 restore_keys.push(format!("ref:refs/heads/{base}"));
525 }
526 if pull_base != Some(default_branch) {
527 restore_keys.push(default_ref);
528 }
529 Some(CacheScope {
530 key: format!("pr:{number}"),
531 restore_keys,
532 })
533 }
534 "push" | "tag" | "manual" | "schedule" => {
535 let restore_keys = if git_ref == format!("refs/heads/{default_branch}") {
536 Vec::new()
537 } else {
538 vec![default_ref]
539 };
540 Some(CacheScope {
541 key: format!("ref:{git_ref}"),
542 restore_keys,
543 })
544 }
545 _ => None,
546 }
547}
548
549/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such
550/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.
551async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {
552 if run.trigger != "pull_request" {
553 return Ok(false);
554 }
555 let Some(number) = run.pull_number else {
556 return Ok(true);
557 };
558 match state
559 .store
560 .pull_by_number(&run.repo_id, number)
561 .await
562 .map_err(api::internal)?
563 {
564 Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())),
565 None => Ok(true),
566 }
567}
568
569// ---------------------------------------------------------------------------------------------
570// Heartbeat, logs and artifacts
571// ---------------------------------------------------------------------------------------------
572
573#[route(POST "/api/v1/ci/jobs/{job_id}/heartbeat")]
574async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
575 let state = app_context::<AppState>(cx);
576 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
577 Ok(job) => job,
578 Err(res) => return Ok(*res),
579 };
580 match state.store.heartbeat(&job.id).await {
581 Ok(cancel) => {
582 // The runner says its live concurrency, and the answer carries the admin's override.
583 // A runner at its limit does not claim, so this is how it learns about a change.
584 let mut concurrency = None;
585 let mut restart = None;
586 if let Some(runner_id) = job.runner_id.as_deref() {
587 let said = headers(cx)
588 .get(CONCURRENCY_HEADER)
589 .and_then(|v| v.to_str().ok())
590 .and_then(|v| v.trim().parse::<u32>().ok());
591 note_report(
592 state,
593 runner_id,
594 &RunnerReport {
595 concurrency: said,
596 build: headers(cx)
597 .get(BUILD_HEADER)
598 .and_then(|v| v.to_str().ok())
599 .filter(|v| v.len() <= 64)
600 .map(str::to_owned),
601 ..RunnerReport::default()
602 },
603 )
604 .await;
605 concurrency = state
606 .store
607 .runner_concurrency_override(runner_id)
608 .await
609 .ok()
610 .flatten();
611 restart = pending_restart(state, runner_id).await;
612 }
613 Ok(api::json(
614 StatusCode::OK,
615 &serde_json::to_value(HeartbeatResponse {
616 cancel,
617 concurrency,
618 restart,
619 })
620 .unwrap_or_default(),
621 ))
622 }
623 Err(e) => Ok(*api::internal(e)),
624 }
625}
626
627/// Outcome of a log append.
628enum LogWrite {
629 /// The chunk is stored (or was dropped by the cap); the size is the new byte count.
630 Stored(u64),
631 /// This exact chunk was already stored: a retry. The size is unchanged.
632 Duplicate(u64),
633 /// The offset does not match the stored size.
634 Mismatch(u64),
635}
636
637#[route(POST "/api/v1/ci/jobs/{job_id}/logs")]
638async fn append_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
639 let state = app_context::<AppState>(cx);
640 let headers = headers(cx);
641 let job = match job_from(state, headers, path_param::<JobId>(cx)).await {
642 Ok(job) => job,
643 Err(res) => return Ok(*res),
644 };
645 let Some(offset) = headers
646 .get(LOG_OFFSET_HEADER)
647 .and_then(|value| value.to_str().ok())
648 .and_then(|value| value.parse::<u64>().ok())
649 else {
650 return Ok(api::error(
651 StatusCode::BAD_REQUEST,
652 "X-Forge-Log-Offset must be a byte offset",
653 ));
654 };
655 let chunk = match api::read_body(body, MAX_LOG_CHUNK).await {
656 Ok(chunk) => chunk,
657 Err(res) => return Ok(*res),
658 };
659 match write_log(state, &job, offset, &chunk).await {
660 Ok(LogWrite::Stored(size) | LogWrite::Duplicate(size)) => {
661 Ok(api::json(StatusCode::OK, &json!({ "size": size })))
662 }
663 Ok(LogWrite::Mismatch(size)) => {
664 let mut res = api::error(StatusCode::CONFLICT, "the log offset does not match");
665 res.headers_mut().insert(
666 http::HeaderName::from_static(LOG_SIZE_HEADER),
667 HeaderValue::from(size),
668 );
669 Ok(res)
670 }
671 Err(res) => Ok(*res),
672 }
673}
674
675/// Appends one chunk of raw log bytes. Offsets count the raw bytes the runner sent, which is
676/// `job.log_bytes`; the file holds the masked text, so its length may differ.
677async fn write_log(
678 state: &AppState,
679 job: &CiJob,
680 offset: u64,
681 chunk: &[u8],
682) -> Result<LogWrite, Refusal> {
683 let size = u64::try_from(job.log_bytes).unwrap_or(0);
684 let len = chunk.len() as u64;
685 if offset != size {
686 return Ok(if offset.checked_add(len) == Some(size) {
687 LogWrite::Duplicate(size)
688 } else {
689 LogWrite::Mismatch(size)
690 });
691 }
692 if chunk.is_empty() {
693 return Ok(LogWrite::Stored(size));
694 }
695
696 let masked = mask_for_job(state, job, chunk).await?;
697 let path = log_path(&state.config.data_dir, &job.id);
698 store_log_bytes(state, &path, &masked).await?;
699 state
700 .store
701 .add_log_bytes(&job.id, len as i64)
702 .await
703 .map_err(api::internal)?;
704 state.ci_live.bump_job(&job.id);
705 // The run page shows the last log lines, so its streams wake too. The page debounces.
706 state.ci_live.bump_run(&job.run_id);
707 if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
708 state.ci_live.bump_repo(&run.repo_id);
709 }
710 Ok(LogWrite::Stored(size + len))
711}
712
713/// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a
714/// secret split across two requests is masked by the runner, which holds back the boundary.
715async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec<u8>, Refusal> {
716 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
717 if spec.secrets.is_empty() {
718 return Ok(chunk.to_vec());
719 }
720 let Some(run) = state
721 .store
722 .run_by_id(&job.run_id)
723 .await
724 .map_err(api::internal)?
725 else {
726 return Err(api::internal("log for a job with no run"));
727 };
728 let values = state
729 .store
730 .ci_secret_values(&run.repo_id, &spec.secrets)
731 .await
732 .map_err(api::internal)?;
733 let masker = Masker::new(values.into_values());
734 let mut stream = masker.stream();
735 let mut out = stream.push(chunk);
736 out.extend(stream.finish());
737 Ok(out)
738}
739
740/// The bytes of `masked` that may be appended to a log of `current` bytes under a `cap`. Once the
741/// log reaches the cap nothing more is kept. When the new bytes do not fit, the part that does is
742/// kept and the marker follows it, so the file ends at exactly `cap` bytes.
743pub fn fit_to_cap(current: u64, cap: u64, masked: &[u8]) -> Vec<u8> {
744 if current >= cap {
745 return Vec::new();
746 }
747 let data_cap = cap.saturating_sub(TRUNCATED_MARKER.len() as u64);
748 let room = data_cap.saturating_sub(current);
749 if masked.len() as u64 <= room {
750 return masked.to_vec();
751 }
752 let mut out = masked[..room as usize].to_vec();
753 out.extend_from_slice(TRUNCATED_MARKER);
754 out
755}
756
757/// Appends masked bytes to the log file, stopping at the size cap with one marker line.
758async fn store_log_bytes(
759 state: &AppState,
760 path: &std::path::Path,
761 masked: &[u8],
762) -> Result<(), Refusal> {
763 use tokio::io::AsyncWriteExt;
764
765 let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
766 let current = match tokio::fs::metadata(path).await {
767 Ok(meta) => meta.len(),
768 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
769 Err(e) => return Err(api::internal(e)),
770 };
771 let out = fit_to_cap(current, cap, masked);
772 if out.is_empty() {
773 return Ok(());
774 }
775
776 if let Some(parent) = path.parent() {
777 tokio::fs::create_dir_all(parent)
778 .await
779 .map_err(api::internal)?;
780 }
781 let mut file = tokio::fs::OpenOptions::new()
782 .create(true)
783 .append(true)
784 .open(path)
785 .await
786 .map_err(api::internal)?;
787 file.write_all(&out).await.map_err(api::internal)?;
788 file.flush().await.map_err(api::internal)?;
789 Ok(())
790}
791
792#[route(PUT "/api/v1/ci/jobs/{job_id}/artifacts/{artifact_name}")]
793async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
794 let state = app_context::<AppState>(cx);
795 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
796 Ok(job) => job,
797 Err(res) => return Ok(*res),
798 };
799 let name = path_param::<ArtifactName>(cx);
800 if !valid_artifact_name(name) {
801 return Ok(api::error(
802 StatusCode::UNPROCESSABLE_ENTITY,
803 "the artifact name must be 1 to 128 of A-Z a-z 0-9 . _ + - and not start with a dot",
804 ));
805 }
806 match upload(state, &job, name, body).await {
807 Ok(artifact_id) => Ok(api::json(
808 StatusCode::CREATED,
809 &json!({ "id": artifact_id, "name": name }),
810 )),
811 Err(res) => Ok(*res),
812 }
813}
814
815/// Streams the body to a temporary blob, then records the artifact and moves the blob to its
816/// final key `ci/<artifact id>`. The id is only known once the row exists.
817async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result<String, Refusal> {
818 let max_artifacts = state.live().ci.max_artifacts_per_job;
819 let existing = state
820 .store
821 .list_artifacts(&job.id)
822 .await
823 .map_err(api::internal)?;
824 if existing.len() as u64 >= u64::from(max_artifacts) {
825 return Err(Box::new(api::error(
826 StatusCode::CONFLICT,
827 "the job has too many artifacts",
828 )));
829 }
830 if existing.iter().any(|artifact| artifact.name == name) {
831 return Err(Box::new(api::error(
832 StatusCode::CONFLICT,
833 "an artifact with this name already exists",
834 )));
835 }
836
837 let max_bytes = state.live().ci.max_artifact_mb.saturating_mul(MIB);
838 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());
839 let mut writer = state
840 .blobs
841 .begin(&temp_key, max_bytes)
842 .await
843 .map_err(api::internal)?;
844 let mut stream = std::pin::pin!(body.into_data_stream());
845 while let Some(next) = stream.next().await {
846 let outcome = match next {
847 Ok(chunk) => writer.push(&chunk).await.map_err(|e| (e, false)),
848 Err(_) => Err((CoreError::Invalid("upload interrupted".into()), true)),
849 };
850 if let Err((e, interrupted)) = outcome {
851 writer.abort().await;
852 return Err(upload_failure(e, interrupted));
853 }
854 }
855 let (size, sha256) = match writer.finish().await {
856 Ok(done) => done,
857 Err(e) => {
858 discard_temp(state, &temp_key).await;
859 return Err(api::internal(e));
860 }
861 };
862
863 let artifact = match state
864 .store
865 .add_artifact(&job.id, name, size as i64, &sha256)
866 .await
867 {
868 Ok(artifact) => artifact,
869 Err(e) => {
870 discard_temp(state, &temp_key).await;
871 return Err(match e {
872 CoreError::Invalid(message) => Box::new(api::error(StatusCode::CONFLICT, &message)),
873 other => api::internal(other),
874 });
875 }
876 };
877 let final_key = artifact_key(&artifact.id);
878 if let Err(e) = state.blobs.rename(&temp_key, &final_key).await {
879 discard_temp(state, &temp_key).await;
880 return Err(api::internal(e));
881 }
882 Ok(artifact.id)
883}
884
885/// Removes a temporary blob. A failure is logged; the blob is unreachable either way.
886async fn discard_temp(state: &AppState, key: &str) {
887 if let Err(e) = state.blobs.delete(key).await {
888 tracing::error!(error = %e, "ci: could not remove a temporary artifact blob");
889 }
890}
891
892fn upload_failure(e: CoreError, interrupted: bool) -> Refusal {
893 match e {
894 CoreError::Invalid(_) if !interrupted => Box::new(api::error(
895 StatusCode::PAYLOAD_TOO_LARGE,
896 "the artifact is larger than the upload limit",
897 )),
898 CoreError::Invalid(message) => Box::new(api::error(StatusCode::BAD_REQUEST, &message)),
899 other => api::internal(other),
900 }
901}
902
903// ---------------------------------------------------------------------------------------------
904// Finish
905// ---------------------------------------------------------------------------------------------
906
907#[route(POST "/api/v1/ci/jobs/{job_id}/finish")]
908async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
909 let state = app_context::<AppState>(cx);
910 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
911 Ok(job) => job,
912 Err(res) => return Ok(*res),
913 };
914 let request: FinishRequest = match json_body(body).await {
915 Ok(request) => request,
916 Err(res) => return Ok(*res),
917 };
918 let state_after = match request.outcome {
919 Outcome::Success => JobState::Success,
920 Outcome::Failure => JobState::Failure,
921 Outcome::Cancelled => JobState::Cancelled,
922 Outcome::Error => JobState::Error,
923 };
924 match finish_job(state, &job, state_after, &request).await {
925 Ok(state_name) => Ok(api::json(StatusCode::OK, &json!({ "state": state_name }))),
926 Err(res) => Ok(*res),
927 }
928}
929
930#[route(POST "/api/v1/ci/jobs/{job_id}/requeue")]
931async fn requeue(cx: &Cx, body: Body) -> topcoat::Result<Response> {
932 let state = app_context::<AppState>(cx);
933 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
934 Ok(job) => job,
935 Err(res) => return Ok(*res),
936 };
937 let request: RequeueRequest = match json_body(body).await {
938 Ok(request) => request,
939 Err(res) => return Ok(*res),
940 };
941 match state.store.requeue_job(&job.id).await {
942 Ok(true) => {}
943 Ok(false) => {
944 return Ok(api::error(StatusCode::CONFLICT, "the job is not running"));
945 }
946 Err(e) => return Ok(*api::internal(e)),
947 }
948 // The next attempt starts from a clean log with one line saying why.
949 let path = log_path(&state.config.data_dir, &job.id);
950 let reason = request.reason.replace(['\r', '\n'], " ");
951 let note = format!("requeued: {reason}. It will start again\n");
952 if let Some(parent) = path.parent()
953 && let Err(e) = tokio::fs::create_dir_all(parent).await
954 {
955 tracing::warn!(error = %e, "ci: log directory not created");
956 }
957 if let Err(e) = tokio::fs::write(&path, note).await {
958 tracing::warn!(error = %e, "ci: requeue log note not written");
959 }
960 state.ci_live.bump_job(&job.id);
961 state.ci_live.bump_run(&job.run_id);
962 state.ci_live.bump_runners();
963 if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
964 state.ci_live.bump_repo(&run.repo_id);
965 if let Ok(Some(fresh)) = state.store.job_by_id(&job.id).await {
966 crate::ci::sync_status(state, &run, &fresh).await;
967 }
968 }
969 state.ci_waker.notify_waiters();
970 Ok(api::json(StatusCode::OK, &json!({ "state": "queued" })))
971}
972
973/// Finishes the job, then syncs the statuses of the job and of every job whose state changed
974/// (skipped or queued by this finish). Wakes the claimers when something was queued, and the
975/// watchers of every job and run that changed.
976async fn finish_job(
977 state: &AppState,
978 job: &CiJob,
979 outcome: JobState,
980 request: &FinishRequest,
981) -> Result<&'static str, Refusal> {
982 let before: BTreeMap<String, JobState> = state
983 .store
984 .jobs_for_run(&job.run_id)
985 .await
986 .map_err(api::internal)?
987 .into_iter()
988 .map(|other| (other.id, other.state))
989 .collect();
990 let exit_code = request.exit_code.map(i64::from);
991 // The runner read the job cgroup's OOM counters. A count without the flag is believed too.
992 let oom_kills = match (request.oom_killed, request.oom_kills) {
993 (Some(false), _) => 0,
994 (_, Some(n)) => n.max(1),
995 (Some(true), None) => 1,
996 (None, None) => 0,
997 };
998 let run = state
999 .store
1000 .finish_job(&job.id, outcome, exit_code, request.message.as_deref())
1001 .await
1002 .map_err(api::internal)?;
1003
1004 if oom_kills > 0
1005 && let Err(e) = state.store.set_job_oom_kills(&job.id, oom_kills).await
1006 {
1007 tracing::warn!(error = %e, "ci: oom kills not stored");
1008 }
1009 let mut queued = false;
1010 let mut any_changed = false;
1011 for other in state
1012 .store
1013 .jobs_for_run(&job.run_id)
1014 .await
1015 .map_err(api::internal)?
1016 {
1017 let changed = before.get(&other.id) != Some(&other.state);
1018 if changed {
1019 any_changed = true;
1020 if other.state.is_terminal() {
1021 state.ci_live.close_job(&other.id);
1022 } else {
1023 state.ci_live.bump_job(&other.id);
1024 }
1025 }
1026 if other.id == job.id
1027 || (changed && matches!(other.state, JobState::Skipped | JobState::Queued))
1028 {
1029 queued |= other.state == JobState::Queued;
1030 crate::ci::sync_status(state, &run, &other).await;
1031 }
1032 }
1033 state.ci_live.bump_runners();
1034 if matches!(outcome, JobState::Failure | JobState::Error) {
1035 crate::alerts::job_ended(
1036 state,
1037 job,
1038 exit_code,
1039 request.message.as_deref(),
1040 oom_kills > 0,
1041 )
1042 .await;
1043 }
1044 if any_changed {
1045 state.ci_live.bump_run(&run.id);
1046 state.ci_live.bump_repo(&run.repo_id);
1047 }
1048 if queued {
1049 state.ci_waker.notify_waiters();
1050 }
1051 // A run that just went green may deploy the forge itself.
1052 self_update::maybe_deploy(state, &run).await;
1053 // A tag run that went green may publish a release. The request does not wait for it.
1054 if run.state == RunState::Success {
1055 let (state, run) = (state.clone(), run.clone());
1056 tokio::spawn(async move { crate::ci::release::on_run_finished(&state, &run).await });
1057 }
1058 Ok(run.state.as_str())
1059}
1060
1061#[cfg(test)]
1062#[path = "api_tests.rs"]
1063mod tests;