use std::path::Path; use std::time::Duration; use forge_ci::proto::{ BUILD_HEADER, CAP_RESTART, CAP_RUNNER_LOG, CAP_RUNNER_METRICS, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, RESTART_HEADER, RegisterRequest, RegisterResponse, RestartMode, RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch, }; use reqwest::StatusCode; use reqwest::header::{CONTENT_LENGTH, HeaderMap}; use serde::de::DeserializeOwned; use sha2::{Digest, Sha256}; use tokio::io::AsyncWriteExt; 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"; const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target"; const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256"; const BINARY_PATH: &str = "/api/v1/ci/runners/binary"; const CONFIG_PATH: &str = "/api/v1/ci/runners/config"; const RUNNER_LOG_PATH: &str = "/api/v1/ci/runners/log"; const RUNNER_METRICS_PATH: &str = "/api/v1/ci/runners/metrics"; #[derive(Debug, thiserror::Error)] pub enum ClientError { #[error("http: {0}")] Http(#[from] reqwest::Error), #[error("forge answered {status}{}", if body.is_empty() { String::new() } else { format!(": {body}") })] Status { status: StatusCode, body: String }, #[error("local io: {0}")] Io(#[from] std::io::Error), #[error("protocol: {0}")] Protocol(String), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LogAck { Accepted, Resync(u64), } #[derive(Clone, Debug)] pub struct ClaimReply { pub job: Option, pub binary_sha256: Option, pub concurrency: Option, pub restart: Option, } #[derive(Clone, Debug)] pub struct ForgeClient { http: reqwest::Client, base: String, } impl ForgeClient { 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) } 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 } pub async fn claim( &self, runner_secret: &str, labels: &[String], ) -> Result { self.claim_with(runner_secret, labels, None).await } pub async fn claim_with( &self, runner_secret: &str, labels: &[String], concurrency: 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_RUNNER_LOG.to_owned(), CAP_RUNNER_METRICS.to_owned(), ], }; 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 mut reply = ClaimReply { job: None, binary_sha256, concurrency: advertised_concurrency(resp.headers()), restart: advertised_restart(resp.headers()), }; match resp.status() { StatusCode::NO_CONTENT => Ok(reply), status if status.is_success() => { reply.job = Some(resp.json().await?); Ok(reply) } _ => Err(status_error(resp).await), } } pub async fn unregister(&self, runner_secret: &str) -> Result<(), ClientError> { let resp = self .http .delete(self.url("/api/v1/ci/runners/self")) .bearer_auth(runner_secret) .timeout(REQUEST_TIMEOUT) .send() .await?; empty_or_error(resp).await } pub async fn stopped(&self, runner_secret: &str) -> Result<(), ClientError> { let resp = self .http .post(self.url("/api/v1/ci/runners/stopped")) .bearer_auth(runner_secret) .timeout(REQUEST_TIMEOUT) .send() .await?; empty_or_error(resp).await } 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 } 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 } pub async fn post_runner_log( &self, runner_secret: &str, batch: &RunnerLogBatch, ) -> Result { let resp = self .http .post(self.url(RUNNER_LOG_PATH)) .bearer_auth(runner_secret) .json(batch) .timeout(REQUEST_TIMEOUT) .send() .await?; json_or_error(resp).await } pub async fn post_runner_metrics( &self, runner_secret: &str, batch: &RunnerMetricsBatch, ) -> Result<(), ClientError> { let resp = self .http .post(self.url(RUNNER_METRICS_PATH)) .bearer_auth(runner_secret) .json(batch) .timeout(REQUEST_TIMEOUT) .send() .await?; empty_or_error(resp).await } 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())) } 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), } } pub async fn heartbeat( &self, job_id: &str, job_token: &str, ) -> Result { self.heartbeat_with(job_id, job_token, None).await } 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 } 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?; empty_or_error(resp).await } 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?; empty_or_error(resp).await } } 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()) } fn advertised_concurrency(headers: &HeaderMap) -> Option { headers .get(CONCURRENCY_HEADER)? .to_str() .ok()? .trim() .parse() .ok() } fn advertised_restart(headers: &HeaderMap) -> Option { RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?) } struct HostFacts { cpus: Option, memory_bytes: Option, } fn host_facts() -> HostFacts { let cpus = std::thread::available_parallelism() .ok() .and_then(|n| u32::try_from(n.get()).ok()); HostFacts { cpus, memory_bytes: crate::memory::host_total(), } } 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 empty_or_error(resp: reqwest::Response) -> Result<(), ClientError> { if resp.status().is_success() { Ok(()) } else { Err(status_error(resp).await) } } async fn status_error(resp: reqwest::Response) -> ClientError { let status = resp.status(); let body = short_body(&resp.text().await.unwrap_or_default()); ClientError::Status { status, body } } fn short_body(text: &str) -> String { let text = text.trim_start(); if text.starts_with('<') { return String::new(); } text.split_whitespace() .collect::>() .join(" ") .chars() .take(512) .collect() } #[cfg(test)] mod tests { use super::*; #[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); } }