1use std::fs;
5use std::fs::File;
6use std::io::{Read, Seek, SeekFrom};
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, LazyLock};
9use std::time::Duration;
10
11use axum::extract::{Query, State};
12use axum::http::{HeaderMap, StatusCode};
13use axum::response::{IntoResponse, Response};
14use axum::routing::get;
15use axum::{Json, Router};
16use chrono::Utc;
17use serde::{Deserialize, Serialize};
18use tokio::task;
19
20use super::discovery;
21use super::network::{self, SECRET_HEADER};
22use super::registry;
23use crate::cli::task::stream::newest_output;
24use crate::store::{Task, TaskStore};
25use crate::sys::home;
26
27const BACKLOG_BYTES: u64 = 64 * 1024;
29
30const MAX_CHUNK_BYTES: u64 = 256 * 1024;
32
33static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
34 reqwest::Client::builder()
35 .connect_timeout(Duration::from_secs(3))
36 .timeout(Duration::from_secs(10))
37 .build()
38 .unwrap_or_default()
39});
40
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
43pub struct Cursor {
44 pub task: i64,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub file: Option<String>,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub offset: Option<u64>,
49}
50
51#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
53pub struct Chunk {
54 pub file: Option<String>,
55 pub offset: u64,
56 pub lines: Vec<String>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(tag = "kind", rename_all = "snake_case")]
61pub enum Output {
62 Lines(Chunk),
63 Offline {
65 node: String,
66 },
67}
68
69fn task_dirs(state: &Path, task: &Task) -> Vec<PathBuf> {
71 let name = task
72 .external_id
73 .clone()
74 .filter(|id| !id.is_empty())
75 .unwrap_or_else(|| format!("internal:{}", task.id));
76 let tasks = state.join(&task.repo).join("tasks");
77 vec![tasks.join(format!("{name}-review")), tasks.join(name)]
78}
79
80pub fn read_chunk(state: &Path, dirs: &[PathBuf], cursor: &Cursor) -> Chunk {
82 let Some(path) = newest_output(dirs) else {
83 return Chunk::default();
84 };
85 let file = path
86 .strip_prefix(state)
87 .unwrap_or(&path)
88 .display()
89 .to_string();
90 let len = fs::metadata(&path).map_or(0, |m| m.len());
91 let start = match cursor.offset {
93 Some(offset) if cursor.file.as_deref() == Some(file.as_str()) && offset <= len => offset,
94 _ => len.saturating_sub(BACKLOG_BYTES),
95 };
96 let skip_first = start > 0 && cursor.file.as_deref() != Some(file.as_str());
97 let mut buf = Vec::new();
98 let read = File::open(&path).and_then(|mut f| {
99 f.seek(SeekFrom::Start(start))?;
100 f.take(MAX_CHUNK_BYTES).read_to_end(&mut buf)
101 });
102 if read.is_err() {
103 return Chunk {
104 file: Some(file),
105 offset: start,
106 lines: Vec::new(),
107 };
108 }
109
110 let end = match buf.iter().rposition(|&b| b == b'\n') {
112 Some(i) => i + 1,
113 None if buf.len() as u64 == MAX_CHUNK_BYTES => buf.len(),
114 None => 0,
115 };
116 let mut lines: Vec<String> = String::from_utf8_lossy(&buf[..end])
117 .lines()
118 .map(String::from)
119 .collect();
120 if skip_first && !lines.is_empty() {
122 lines.remove(0);
123 }
124
125 Chunk {
126 file: Some(file),
127 offset: start + end as u64,
128 lines,
129 }
130}
131
132async fn read_local(task: &Task, cursor: Cursor) -> anyhow::Result<Chunk> {
133 let state = home::state_dir()?;
134 let dirs = task_dirs(&state, task);
135 Ok(task::spawn_blocking(move || read_chunk(&state, &dirs, &cursor)).await?)
136}
137
138#[derive(Clone)]
139struct App {
140 store: TaskStore,
141 secret: Arc<str>,
142}
143
144pub(crate) fn router(store: TaskStore, secret: Arc<str>) -> Router {
146 Router::new()
147 .route("/cluster/output", get(serve))
148 .with_state(App { store, secret })
149}
150
151async fn serve(State(a): State<App>, headers: HeaderMap, Query(cursor): Query<Cursor>) -> Response {
152 if !network::secret_ok(&a.secret, &headers) {
153 return StatusCode::UNAUTHORIZED.into_response();
154 }
155
156 let Ok(task) = a.store.get(cursor.task).await else {
157 return StatusCode::NOT_FOUND.into_response();
158 };
159 match read_local(&task, cursor).await {
160 Ok(chunk) => Json(chunk).into_response(),
161 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")).into_response(),
162 }
163}
164
165#[derive(Debug)]
167pub enum FetchError {
168 Unreachable(String),
170 Refused(StatusCode, String),
171}
172
173pub async fn fetch(addr: &str, secret: &str, cursor: &Cursor) -> Result<Chunk, FetchError> {
175 let res = CLIENT
176 .get(format!("http://{addr}/cluster/output"))
177 .header(SECRET_HEADER, secret)
178 .query(cursor)
179 .send()
180 .await
181 .map_err(|e| FetchError::Unreachable(e.to_string()))?;
182 let status = res.status();
183 if !status.is_success() {
184 let body = res.text().await.unwrap_or_default();
185 return Err(FetchError::Refused(status, body));
186 }
187
188 res.json()
189 .await
190 .map_err(|e| FetchError::Unreachable(e.to_string()))
191}
192
193fn member_addr(store: &TaskStore, name: &str) -> Option<String> {
195 let node = store.node()?;
196 let id = discovery::node_id(name);
197 let metrics = node.raft.metrics().borrow().clone();
198 metrics
199 .membership_config
200 .membership()
201 .nodes()
202 .find(|(member, _)| **member == id)
203 .map(|(_, n)| n.addr.clone())
204}
205
206pub async fn relay(store: &TaskStore, cursor: Cursor) -> anyhow::Result<Option<Output>> {
212 let Ok(task) = store.get(cursor.task).await else {
213 return Ok(None);
214 };
215 let remote = match (store.node(), task.owner_node.as_deref()) {
216 (Some(node), Some(owner)) if !node.name().is_empty() && owner != node.name() => node
217 .secret
218 .clone()
219 .map(|secret| (owner.to_string(), secret)),
220 _ => None,
221 };
222 let Some((owner, secret)) = remote else {
223 return Ok(Some(Output::Lines(read_local(&task, cursor).await?)));
224 };
225
226 let offline = registry::read(store)
227 .await
228 .unwrap_or_default()
229 .iter()
230 .any(|e| e.node == owner && !e.online_at(Utc::now()));
231 let Some(addr) = member_addr(store, &owner).filter(|_| !offline) else {
232 return Ok(Some(Output::Offline { node: owner }));
233 };
234 match fetch(&addr, &secret, &cursor).await {
235 Ok(chunk) => Ok(Some(Output::Lines(chunk))),
236 Err(FetchError::Unreachable(e)) => {
237 tracing::debug!(node = %owner, err = %e, "owner node did not answer an output request");
238 Ok(Some(Output::Offline { node: owner }))
239 }
240 Err(FetchError::Refused(StatusCode::NOT_FOUND, _)) => Ok(None),
241 Err(FetchError::Refused(status, body)) => {
242 anyhow::bail!("{owner} refused the output request ({status}): {body}")
243 }
244 }
245}
246
247#[cfg(test)]
248mod tests;