Skip to main content

orch/store/cluster/
output.rs

1//! Session output from the node that runs a task. A node reads `output.json` from its own state
2//! dir and sends complete lines over the cluster listener. Output never goes into the Raft log
3
4use 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
27/// Replayed when a viewer first opens a file, as the local tail does
28const BACKLOG_BYTES: u64 = 64 * 1024;
29
30/// The most one request returns, so a viewer far behind catches up over several requests
31const 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/// What a viewer asks for: a task, and where it stopped reading. A different `file` starts over
42#[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/// Complete lines after the cursor. `file` is relative to the state dir and changes with each attempt
52#[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    /// The node that runs the task does not answer
64    Offline {
65        node: String,
66    },
67}
68
69/// The task dir and its review dir, named as the runner names them
70fn 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
80/// The lines of the task's newest output file after the cursor. Stateless, so any viewer can ask
81pub 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    // A new attempt or a truncated file starts over from the backlog
92    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    // Only whole lines go out, unless one line fills the whole chunk
111    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    // The backlog starts mid-line
121    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
144/// `GET /cluster/output` on the cluster listener. It serves only tasks in this node's store
145pub(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/// Why a fetch from a peer failed
166#[derive(Debug)]
167pub enum FetchError {
168    /// No connection, or no answer in time
169    Unreachable(String),
170    Refused(StatusCode, String),
171}
172
173/// Ask the node at `addr` for the output after `cursor`
174pub 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
193/// The cluster address of the member named `name`. A node's Raft id comes from its name
194fn 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
206/**
207 * The task's output, read here when this node runs it and fetched from its owner otherwise. A
208 * single node, a task no node took yet and a task this node owns read the local state dir, so
209 * without a cluster this is the local tail
210 **/
211pub 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;