use std::io;
use std::path::Path;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use http_body_util::{BodyExt, StreamBody};
use hyper::body::{Frame, Incoming};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH};
use hyper::{Method, Request, Response, StatusCode};
use serde::Deserialize;
use tracing::debug;
use super::actions::{json, passed_headers, read};
use super::serve::{Body, drain, status};
use super::{Inner, valid_segment};
use crate::sync::lock;
pub(super) const API: &str = "turbo/v8/artifacts";
pub(super) const TOOL: &str = "turbo";
pub(super) const ENDPOINTS: [&str; 3] = ["", "/status", "/events"];
const TOKEN: &str = "runnerd";
const VERCEL_API: &str = "https://vercel.com/api";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const READ_TIMEOUT: Duration = Duration::from_secs(60);
const MAX_QUERY: usize = 1 << 20;
pub(super) async fn handle(
inner: &Inner,
repository: &str,
endpoint: &str,
request: Request<Incoming>,
) -> Response<Body> {
match (endpoint, request.method()) {
("", &Method::POST) => query(inner, repository, request.into_body()).await,
("/status", &Method::GET) => json(&serde_json::json!({ "status": "enabled" })),
("/events", &Method::POST) => {
drain(request.into_body()).await;
status(StatusCode::OK)
}
_ => status(StatusCode::METHOD_NOT_ALLOWED),
}
}
#[derive(Deserialize)]
struct Query {
hashes: Vec<String>,
}
async fn query(inner: &Inner, repository: &str, body: Incoming) -> Response<Body> {
let Some(query) = read(body, MAX_QUERY)
.await
.and_then(|body| serde_json::from_slice::<Query>(&body).ok())
else {
return status(StatusCode::BAD_REQUEST);
};
let state = lock(&inner.state);
let hits: serde_json::Map<String, serde_json::Value> = query
.hashes
.into_iter()
.map(|hash| {
let known = valid_segment(&hash)
&& state
.entries
.contains_key(&Path::new(repository).join(TOOL).join(&hash));
let hit = if known {
serde_json::json!({ "taskDurationMs": 0 })
} else {
serde_json::Value::Null
};
(hash, hit)
})
.collect();
drop(state);
json(&serde_json::Value::Object(hits))
}
pub(super) fn foreign(request: &Request<Incoming>) -> bool {
request
.headers()
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split_once(' '))
.is_some_and(|(scheme, token)| {
scheme.eq_ignore_ascii_case("bearer") && token.trim() != TOKEN
})
}
#[derive(Debug)]
pub(super) struct Vercel {
origin: Mutex<String>,
client: OnceLock<Option<reqwest::Client>>,
}
impl Vercel {
pub(super) fn new() -> Vercel {
Vercel {
origin: Mutex::new(VERCEL_API.to_owned()),
client: OnceLock::new(),
}
}
#[cfg(test)]
pub(super) fn set_origin(&self, origin: &str) {
*lock(&self.origin) = origin.to_owned();
}
fn client(&self) -> Option<&reqwest::Client> {
self.client
.get_or_init(|| {
crate::github::install_crypto_provider();
reqwest::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.read_timeout(READ_TIMEOUT)
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|error| debug!("cannot make Vercel's client: {error}"))
.ok()
})
.as_ref()
}
}
pub(super) async fn pass(inner: &Inner, request: Request<Incoming>) -> Response<Body> {
let (parts, body) = request.into_parts();
let Some(client) = inner.vercel.client() else {
return status(StatusCode::BAD_GATEWAY);
};
let path = parts.uri.path_and_query().map_or("", |path| path.as_str());
let url = format!(
"{}{}",
lock(&inner.vercel.origin),
path.strip_prefix("/turbo").unwrap_or_default()
);
let sent = client
.request(parts.method, url)
.headers(passed_headers(&parts.headers))
.body(reqwest::Body::wrap(body))
.send()
.await;
let answer = match sent {
Ok(answer) => answer,
Err(error) => {
debug!(
"cannot pass a request to Vercel's API: {}",
error.without_url()
);
return status(StatusCode::BAD_GATEWAY);
}
};
let code = answer.status();
let mut headers = passed_headers(answer.headers());
if let Some(length) = answer.headers().get(CONTENT_LENGTH) {
headers.insert(CONTENT_LENGTH, length.clone());
}
let chunks = futures_util::stream::unfold(Some(answer), |answer| async move {
let mut answer = answer?;
match answer.chunk().await {
Ok(Some(chunk)) => Some((Ok(Frame::data(chunk)), Some(answer))),
Ok(None) => None,
Err(error) => Some((Err(io::Error::other(error.without_url())), None)),
}
});
let mut response = Response::new(BodyExt::boxed_unsync(StreamBody::new(chunks)));
*response.status_mut() = code;
*response.headers_mut() = headers;
response
}