use std::fs;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use tokio::task;
use super::discovery;
use super::network::{self, SECRET_HEADER};
use super::registry;
use crate::cli::task::stream::newest_output;
use crate::store::{Task, TaskStore};
use crate::sys::home;
const BACKLOG_BYTES: u64 = 64 * 1024;
const MAX_CHUNK_BYTES: u64 = 256 * 1024;
static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
reqwest::Client::builder()
.connect_timeout(Duration::from_secs(3))
.timeout(Duration::from_secs(10))
.build()
.unwrap_or_default()
});
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cursor {
pub task: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub offset: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Chunk {
pub file: Option<String>,
pub offset: u64,
pub lines: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Output {
Lines(Chunk),
Offline {
node: String,
},
}
fn task_dirs(state: &Path, task: &Task) -> Vec<PathBuf> {
let name = task
.external_id
.clone()
.filter(|id| !id.is_empty())
.unwrap_or_else(|| format!("internal:{}", task.id));
let tasks = state.join(&task.repo).join("tasks");
vec![tasks.join(format!("{name}-review")), tasks.join(name)]
}
pub fn read_chunk(state: &Path, dirs: &[PathBuf], cursor: &Cursor) -> Chunk {
let Some(path) = newest_output(dirs) else {
return Chunk::default();
};
let file = path
.strip_prefix(state)
.unwrap_or(&path)
.display()
.to_string();
let len = fs::metadata(&path).map_or(0, |m| m.len());
let start = match cursor.offset {
Some(offset) if cursor.file.as_deref() == Some(file.as_str()) && offset <= len => offset,
_ => len.saturating_sub(BACKLOG_BYTES),
};
let skip_first = start > 0 && cursor.file.as_deref() != Some(file.as_str());
let mut buf = Vec::new();
let read = File::open(&path).and_then(|mut f| {
f.seek(SeekFrom::Start(start))?;
f.take(MAX_CHUNK_BYTES).read_to_end(&mut buf)
});
if read.is_err() {
return Chunk {
file: Some(file),
offset: start,
lines: Vec::new(),
};
}
let end = match buf.iter().rposition(|&b| b == b'\n') {
Some(i) => i + 1,
None if buf.len() as u64 == MAX_CHUNK_BYTES => buf.len(),
None => 0,
};
let mut lines: Vec<String> = String::from_utf8_lossy(&buf[..end])
.lines()
.map(String::from)
.collect();
if skip_first && !lines.is_empty() {
lines.remove(0);
}
Chunk {
file: Some(file),
offset: start + end as u64,
lines,
}
}
async fn read_local(task: &Task, cursor: Cursor) -> anyhow::Result<Chunk> {
let state = home::state_dir()?;
let dirs = task_dirs(&state, task);
Ok(task::spawn_blocking(move || read_chunk(&state, &dirs, &cursor)).await?)
}
#[derive(Clone)]
struct App {
store: TaskStore,
secret: Arc<str>,
}
pub(crate) fn router(store: TaskStore, secret: Arc<str>) -> Router {
Router::new()
.route("/cluster/output", get(serve))
.with_state(App { store, secret })
}
async fn serve(State(a): State<App>, headers: HeaderMap, Query(cursor): Query<Cursor>) -> Response {
if !network::secret_ok(&a.secret, &headers) {
return StatusCode::UNAUTHORIZED.into_response();
}
let Ok(task) = a.store.get(cursor.task).await else {
return StatusCode::NOT_FOUND.into_response();
};
match read_local(&task, cursor).await {
Ok(chunk) => Json(chunk).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")).into_response(),
}
}
#[derive(Debug)]
pub enum FetchError {
Unreachable(String),
Refused(StatusCode, String),
}
pub async fn fetch(addr: &str, secret: &str, cursor: &Cursor) -> Result<Chunk, FetchError> {
let res = CLIENT
.get(format!("http://{addr}/cluster/output"))
.header(SECRET_HEADER, secret)
.query(cursor)
.send()
.await
.map_err(|e| FetchError::Unreachable(e.to_string()))?;
let status = res.status();
if !status.is_success() {
let body = res.text().await.unwrap_or_default();
return Err(FetchError::Refused(status, body));
}
res.json()
.await
.map_err(|e| FetchError::Unreachable(e.to_string()))
}
fn member_addr(store: &TaskStore, name: &str) -> Option<String> {
let node = store.node()?;
let id = discovery::node_id(name);
let metrics = node.raft.metrics().borrow().clone();
metrics
.membership_config
.membership()
.nodes()
.find(|(member, _)| **member == id)
.map(|(_, n)| n.addr.clone())
}
pub async fn relay(store: &TaskStore, cursor: Cursor) -> anyhow::Result<Option<Output>> {
let Ok(task) = store.get(cursor.task).await else {
return Ok(None);
};
let remote = match (store.node(), task.owner_node.as_deref()) {
(Some(node), Some(owner)) if !node.name().is_empty() && owner != node.name() => node
.secret
.clone()
.map(|secret| (owner.to_string(), secret)),
_ => None,
};
let Some((owner, secret)) = remote else {
return Ok(Some(Output::Lines(read_local(&task, cursor).await?)));
};
let offline = registry::read(store)
.await
.unwrap_or_default()
.iter()
.any(|e| e.node == owner && !e.online_at(Utc::now()));
let Some(addr) = member_addr(store, &owner).filter(|_| !offline) else {
return Ok(Some(Output::Offline { node: owner }));
};
match fetch(&addr, &secret, &cursor).await {
Ok(chunk) => Ok(Some(Output::Lines(chunk))),
Err(FetchError::Unreachable(e)) => {
tracing::debug!(node = %owner, err = %e, "owner node did not answer an output request");
Ok(Some(Output::Offline { node: owner }))
}
Err(FetchError::Refused(StatusCode::NOT_FOUND, _)) => Ok(None),
Err(FetchError::Refused(status, body)) => {
anyhow::bail!("{owner} refused the output request ({status}): {body}")
}
}
}
#[cfg(test)]
mod tests;