//! HTTP client for the forge runner API (contract section 4). //! //! Runner calls (register, claim) authenticate with the runner secret. Job calls (logs, //! heartbeat, artifacts, finish) authenticate with the per-job token. use std::path::Path; use std::time::Duration; use forge_ci::proto::{ BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest, RestartMode, RunnerConfigOverrides, RunnerConfigReport, }; use reqwest::StatusCode; use reqwest::header::{CONTENT_LENGTH, HeaderMap}; use serde::de::DeserializeOwned; use sha2::{Digest, Sha256}; use tokio::io::AsyncWriteExt; /// The claim long-poll is 25s on the forge side, so 35s leaves room for the response. pub const CLAIM_TIMEOUT: Duration = Duration::from_secs(35); const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); const LOG_TIMEOUT: Duration = Duration::from_secs(60); const ARTIFACT_TIMEOUT: Duration = Duration::from_secs(60 * 60); const BINARY_TIMEOUT: Duration = Duration::from_secs(10 * 60); const HEADER_LOG_OFFSET: &str = "X-Forge-Log-Offset"; const HEADER_LOG_SIZE: &str = "X-Forge-Log-Size"; /// Sent on every claim: `-` of this runner, for example `x86_64-linux`. const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target"; /// On a claim response: the sha256 (hex) of the forge's own binary, if the forge advertises one. const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256"; /// `GET`: the forge's binary, for a runner that is updating itself. const BINARY_PATH: &str = "/api/v1/ci/runners/binary"; const CONFIG_PATH: &str = "/api/v1/ci/runners/config"; /// Errors from talking to the forge. #[derive(Debug, thiserror::Error)] pub enum ClientError { #[error("http: {0}")] Http(#[from] reqwest::Error), #[error("forge answered {status}: {body}")] Status { status: StatusCode, body: String }, #[error("local io: {0}")] Io(#[from] std::io::Error), #[error("protocol: {0}")] Protocol(String), } /// The forge's answer to a log chunk. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LogAck { /// The chunk was stored (or was already stored, which is an idempotent retry). Accepted, /// The forge holds a different number of bytes. The runner must continue from this size. Resync(u64), } /// The forge's answer to a claim. #[derive(Clone, Debug)] pub struct ClaimReply { /// The job assigned to this runner, or `None` when there is nothing to run (204). pub job: Option, /// The sha256 (lowercase hex) of the forge's binary, when the response advertises one. pub binary_sha256: Option, /// The concurrency an admin set in the web UI. `None` means no override. pub concurrency: Option, /// A restart an admin asked for, from the `Forge-Runner-Restart` header. pub restart: Option, /// The memory budget an admin set (`6g`). `None` means no override. pub memory_budget: Option, /// The default reservation an admin set (`1g`). `None` means no override. pub reserve_memory: Option, } /// What a claim tells the forge about the runner's memory. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MemoryClaim { /// Budget minus running reservations: the forge hands out only a job that fits. pub free: u64, pub budget: u64, /// What a job without `memory` reserves. pub reserve: u64, } /// A client for one forge base URL. #[derive(Clone, Debug)] pub struct ForgeClient { http: reqwest::Client, base: String, } impl ForgeClient { /// Builds a client for `base_url`, for example `https://forge.example`. pub fn new(base_url: &str) -> Result { let http = reqwest::Client::builder() .user_agent(concat!("forge-runner/", env!("CARGO_PKG_VERSION"))) .connect_timeout(Duration::from_secs(10)) .build()?; Ok(Self { http, base: base_url.trim_end_matches('/').to_owned(), }) } fn url(&self, path: &str) -> String { format!("{}{}", self.base, path) } /// `POST /api/v1/ci/runners/register`. pub async fn register(&self, req: &RegisterRequest) -> Result { let resp = self .http .post(self.url("/api/v1/ci/runners/register")) .json(req) .timeout(REQUEST_TIMEOUT) .send() .await?; json_or_error(resp).await } /// `POST /api/v1/ci/runners/claim`. A 204 means nothing to run, and the reply has no job. pub async fn claim( &self, runner_secret: &str, labels: &[String], ) -> Result { self.claim_with(runner_secret, labels, None, None).await } /// Like [`ForgeClient::claim`], and also reports the runner's live `concurrency` and its host /// facts (version, CPUs, memory) for the forge's admin page. pub async fn claim_with( &self, runner_secret: &str, labels: &[String], concurrency: Option, memory: Option, ) -> Result { let host = host_facts(); let req = ClaimRequest { labels: labels.to_vec(), concurrency: concurrency.and_then(|n| u32::try_from(n).ok()), version: Some(env!("CARGO_PKG_VERSION").to_owned()), cpus: host.cpus, memory_bytes: host.memory_bytes, build: Some(forge_ci::build::display()), boot_id: Some(crate::restart::boot_id().to_owned()), capabilities: vec![CAP_RESTART.to_owned(), CAP_REQUEUE.to_owned()], free_memory_bytes: memory.map(|m| m.free), memory_budget_bytes: memory.map(|m| m.budget), reserve_memory_bytes: memory.map(|m| m.reserve), }; let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); let resp = self .http .post(self.url("/api/v1/ci/runners/claim")) .bearer_auth(runner_secret) .header(HEADER_RUNNER_TARGET, target) .json(&req) .timeout(CLAIM_TIMEOUT) .send() .await?; let binary_sha256 = advertised_sha256(resp.headers()); let concurrency = advertised_concurrency(resp.headers()); let restart = advertised_restart(resp.headers()); let memory_budget = header_text(resp.headers(), MEMORY_BUDGET_HEADER); let reserve_memory = header_text(resp.headers(), RESERVE_MEMORY_HEADER); match resp.status() { StatusCode::NO_CONTENT => Ok(ClaimReply { job: None, binary_sha256, concurrency, restart, memory_budget, reserve_memory, }), status if status.is_success() => Ok(ClaimReply { job: Some(resp.json().await?), binary_sha256, concurrency, restart, memory_budget, reserve_memory, }), _ => Err(status_error(resp).await), } } /// `GET /api/v1/ci/runners/config`: the overrides an admin set for this runner. pub async fn get_config( &self, runner_secret: &str, ) -> Result { let resp = self .http .get(self.url(CONFIG_PATH)) .bearer_auth(runner_secret) .timeout(REQUEST_TIMEOUT) .send() .await?; json_or_error(resp).await } /// `PUT /api/v1/ci/runners/config`: reports the runner's effective config (secrets redacted). pub async fn put_config( &self, runner_secret: &str, report: &RunnerConfigReport, ) -> Result { let resp = self .http .put(self.url(CONFIG_PATH)) .bearer_auth(runner_secret) .json(report) .timeout(REQUEST_TIMEOUT) .send() .await?; json_or_error(resp).await } /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised /// value and syncs the file. pub async fn download_binary( &self, runner_secret: &str, dest: &Path, ) -> Result { let mut resp = self .http .get(self.url(BINARY_PATH)) .bearer_auth(runner_secret) .timeout(BINARY_TIMEOUT) .send() .await?; if !resp.status().is_success() { return Err(status_error(resp).await); } let mut file = tokio::fs::File::create(dest).await?; let mut hasher = Sha256::new(); while let Some(chunk) = resp.chunk().await? { hasher.update(&chunk); file.write_all(&chunk).await?; } file.flush().await?; Ok(hex::encode(hasher.finalize())) } /// `POST /api/v1/ci/jobs/{id}/logs` with the byte offset of `body` in the job log. pub async fn post_logs( &self, job_id: &str, job_token: &str, offset: u64, body: Vec, ) -> Result { let resp = self .http .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/logs"))) .bearer_auth(job_token) .header(HEADER_LOG_OFFSET, offset.to_string()) .header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8") .body(body) .timeout(LOG_TIMEOUT) .send() .await?; match resp.status() { StatusCode::CONFLICT => { let size = resp .headers() .get(HEADER_LOG_SIZE) .and_then(|v| v.to_str().ok()) .and_then(|v| v.parse::().ok()) .ok_or_else(|| { ClientError::Protocol("409 without a valid X-Forge-Log-Size".into()) })?; Ok(LogAck::Resync(size)) } status if status.is_success() => Ok(LogAck::Accepted), _ => Err(status_error(resp).await), } } /// `POST /api/v1/ci/jobs/{id}/heartbeat`. pub async fn heartbeat( &self, job_id: &str, job_token: &str, ) -> Result { self.heartbeat_with(job_id, job_token, None).await } /// Like [`ForgeClient::heartbeat`], and also tells the forge the runner's live `concurrency`. pub async fn heartbeat_with( &self, job_id: &str, job_token: &str, concurrency: Option, ) -> Result { let mut req = self .http .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/heartbeat"))) .bearer_auth(job_token) .timeout(REQUEST_TIMEOUT); if let Some(n) = concurrency { req = req.header(CONCURRENCY_HEADER, n.to_string()); } req = req.header(BUILD_HEADER, forge_ci::build::display()); json_or_error(req.send().await?).await } /// `PUT /api/v1/ci/jobs/{id}/artifacts/{name}`, streaming the file from disk. pub async fn upload_artifact( &self, job_id: &str, job_token: &str, name: &str, path: &Path, ) -> Result<(), ClientError> { let file = tokio::fs::File::open(path).await?; let len = file.metadata().await?.len(); let stream = tokio_util::io::ReaderStream::new(file); let resp = self .http .put(self.url(&format!("/api/v1/ci/jobs/{job_id}/artifacts/{name}"))) .bearer_auth(job_token) .header(CONTENT_LENGTH, len) .body(reqwest::Body::wrap_stream(stream)) .timeout(ARTIFACT_TIMEOUT) .send() .await?; if resp.status().is_success() { Ok(()) } else { Err(status_error(resp).await) } } /// `POST /api/v1/ci/jobs/{id}/finish`. pub async fn finish( &self, job_id: &str, job_token: &str, req: &FinishRequest, ) -> Result<(), ClientError> { let resp = self .http .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/finish"))) .bearer_auth(job_token) .json(req) .timeout(REQUEST_TIMEOUT) .send() .await?; if resp.status().is_success() { Ok(()) } else { Err(status_error(resp).await) } } /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place. pub async fn requeue( &self, job_id: &str, job_token: &str, reason: &str, ) -> Result<(), ClientError> { let resp = self .http .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/requeue"))) .bearer_auth(job_token) .json(&RequeueRequest { reason: reason.to_owned(), }) .timeout(REQUEST_TIMEOUT) .send() .await?; if resp.status().is_success() { Ok(()) } else { Err(status_error(resp).await) } } } /// The `Forge-Binary-Sha256` header, trimmed and lowercased. An empty value counts as absent. fn advertised_sha256(headers: &HeaderMap) -> Option { headers .get(HEADER_BINARY_SHA256)? .to_str() .ok() .map(|v| v.trim().to_ascii_lowercase()) .filter(|v| !v.is_empty()) } /// The `Forge-Runner-Concurrency` header, when it holds a number. fn advertised_concurrency(headers: &HeaderMap) -> Option { headers .get(CONCURRENCY_HEADER)? .to_str() .ok()? .trim() .parse() .ok() } /// The `Forge-Runner-Restart` header, when it holds a mode this runner knows. fn advertised_restart(headers: &HeaderMap) -> Option { RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?) } /// Cheap facts about the host that help an admin size the runner's concurrency. struct HostFacts { cpus: Option, memory_bytes: Option, } fn header_text(headers: &HeaderMap, name: &str) -> Option { headers .get(name) .and_then(|v| v.to_str().ok()) .map(|v| v.trim().to_owned()) .filter(|v| !v.is_empty() && v.len() <= 32) } fn host_facts() -> HostFacts { let cpus = std::thread::available_parallelism() .ok() .and_then(|n| u32::try_from(n.get()).ok()); let memory_bytes = std::fs::read_to_string("/proc/meminfo") .ok() .and_then(|text| parse_mem_total(&text)); HostFacts { cpus, memory_bytes } } /// `MemTotal` of `/proc/meminfo`, in bytes. The file reports kibibytes. fn parse_mem_total(meminfo: &str) -> Option { let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?; let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; kib.checked_mul(1024) } async fn json_or_error(resp: reqwest::Response) -> Result { if resp.status().is_success() { Ok(resp.json().await?) } else { Err(status_error(resp).await) } } async fn status_error(resp: reqwest::Response) -> ClientError { let status = resp.status(); let body: String = resp .text() .await .unwrap_or_default() .chars() .take(512) .collect(); ClientError::Status { status, body } } #[cfg(test)] mod tests { use super::*; #[test] fn reads_mem_total_in_bytes() { let text = "MemTotal: 16384 kB\nMemFree: 100 kB\n"; assert_eq!(parse_mem_total(text), Some(16384 * 1024)); assert_eq!(parse_mem_total("nothing"), None); } #[test] fn restart_header_must_name_a_mode() { let mut headers = HeaderMap::new(); assert_eq!(advertised_restart(&headers), None); headers.insert(RESTART_HEADER, "drain".parse().unwrap()); assert_eq!(advertised_restart(&headers), Some(RestartMode::Drain)); headers.insert(RESTART_HEADER, "now".parse().unwrap()); assert_eq!(advertised_restart(&headers), Some(RestartMode::Now)); headers.insert(RESTART_HEADER, "later".parse().unwrap()); assert_eq!(advertised_restart(&headers), None); } #[test] fn concurrency_header_must_be_a_number() { let mut headers = HeaderMap::new(); assert_eq!(advertised_concurrency(&headers), None); headers.insert(CONCURRENCY_HEADER, "3".parse().unwrap()); assert_eq!(advertised_concurrency(&headers), Some(3)); headers.insert(CONCURRENCY_HEADER, "many".parse().unwrap()); assert_eq!(advertised_concurrency(&headers), None); } }