Skip to main content

orch/store/cluster/
local.rs

1//! The localhost endpoint the CLI sends replicated writes to, so they go through the daemon's log
2
3use std::env;
4use std::fs;
5use std::fs::OpenOptions;
6use std::io::Write;
7use std::os::unix::fs::OpenOptionsExt;
8use std::path::Path;
9use std::path::PathBuf;
10use std::process;
11use std::sync::{Arc, LazyLock};
12use std::time::Duration;
13
14use axum::extract::State;
15use axum::http::{HeaderMap, StatusCode, header};
16use axum::response::{IntoResponse, Response};
17use axum::routing::{get, post};
18use axum::{Json, Router};
19use subtle::ConstantTimeEq;
20use tokio::fs as tokio_fs;
21use tokio::net::TcpListener;
22use tokio::task;
23
24use super::progress::{Record, Report};
25use super::{Command, Reply};
26use crate::store::TaskStore;
27use crate::store::cluster::discovery;
28use crate::sys::home;
29use futures::future::BoxFuture;
30
31static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
32    reqwest::Client::builder()
33        .timeout(Duration::from_secs(30))
34        .build()
35        .unwrap_or_default()
36});
37
38/// Where the CLI reaches the daemon, and the token that proves the caller can read `~/.orch`
39#[derive(Debug, Clone)]
40pub struct Endpoint {
41    pub url: String,
42    pub token: String,
43}
44
45fn port_path() -> anyhow::Result<PathBuf> {
46    if cfg!(test) {
47        Ok(env::temp_dir().join("orch-test-state").join("cluster.port"))
48    } else {
49        Ok(home::state_dir()?.join("cluster.port"))
50    }
51}
52
53/// Handles an `orch progress` report on the daemon, which commits and pushes in the task worktree
54pub type ProgressFn = Arc<
55    dyn Fn(TaskStore, String, Report) -> BoxFuture<'static, anyhow::Result<Record>> + Send + Sync,
56>;
57
58#[derive(Clone)]
59struct App {
60    store: TaskStore,
61    on_progress: ProgressFn,
62    token: Arc<str>,
63    host: Arc<str>,
64}
65
66/// Serve `POST /write` on 127.0.0.1 and record the port, a fresh token and the pid for the CLI
67pub async fn serve(store: TaskStore, on_progress: ProgressFn) -> anyhow::Result<Endpoint> {
68    let listener = TcpListener::bind("127.0.0.1:0").await?;
69    let port = listener.local_addr()?.port();
70    let token = format!(
71        "{}{}",
72        uuid::Uuid::new_v4().simple(),
73        uuid::Uuid::new_v4().simple()
74    );
75    write_private(&port_path()?, &format!("{port} {token} {}", process::id()))?;
76    let app = Router::new()
77        .route("/write", post(write))
78        .route("/progress", post(progress))
79        .route("/nodes", get(nodes))
80        .with_state(App {
81            store,
82            on_progress,
83            token: Arc::from(token.as_str()),
84            host: Arc::from(format!("127.0.0.1:{port}")),
85        });
86    tokio::spawn(async move {
87        if let Err(e) = axum::serve(listener, app).await {
88            tracing::warn!(err = %e, "cluster write endpoint stopped");
89        }
90    });
91    tracing::info!(port, "cluster write endpoint started on 127.0.0.1");
92    Ok(Endpoint {
93        url: format!("http://127.0.0.1:{port}/write"),
94        token,
95    })
96}
97
98/// Owner-only file, written to a temp name and renamed so a reader never sees half of it
99pub(crate) fn write_private(path: &Path, body: &str) -> anyhow::Result<()> {
100    if let Some(parent) = path.parent() {
101        fs::create_dir_all(parent)?;
102    }
103
104    let tmp = path.with_extension(format!("tmp.{}", process::id()));
105    let mut file = OpenOptions::new()
106        .write(true)
107        .create(true)
108        .truncate(true)
109        .mode(0o600)
110        .open(&tmp)?;
111    file.write_all(body.as_bytes())?;
112    fs::rename(&tmp, path)?;
113    Ok(())
114}
115
116fn authorized(app: &App, headers: &HeaderMap) -> bool {
117    // A rebound DNS name sends its own Host, so only the literal address passes
118    let host_ok = headers
119        .get(header::HOST)
120        .is_some_and(|h| h.as_bytes() == app.host.as_bytes());
121    let given = headers
122        .get(header::AUTHORIZATION)
123        .and_then(|v| v.to_str().ok())
124        .and_then(|v| v.strip_prefix("Bearer "))
125        .unwrap_or("");
126    let token_ok: bool = given.as_bytes().ct_eq(app.token.as_bytes()).into();
127    host_ok && token_ok
128}
129
130async fn write(State(app): State<App>, headers: HeaderMap, Json(cmd): Json<Command>) -> Response {
131    if !authorized(&app, &headers) {
132        return StatusCode::UNAUTHORIZED.into_response();
133    }
134
135    // The store writes local state directly, so a command that carries any came from outside it
136    if let Err(e) = cmd.check_replicable() {
137        return Json(Reply::Err(format!("{e:#}"))).into_response();
138    }
139
140    Json(match app.store.write(cmd).await {
141        Ok(reply) => reply,
142        Err(e) => Reply::Err(format!("{e:#}")),
143    })
144    .into_response()
145}
146
147async fn progress(
148    State(app): State<App>,
149    headers: HeaderMap,
150    Json(report): Json<Report>,
151) -> Response {
152    if !authorized(&app, &headers) {
153        return StatusCode::UNAUTHORIZED.into_response();
154    }
155
156    let node = discovery::status()
157        .await
158        .map_or_else(|_| "local".to_string(), |t| t.me.name);
159    match (app.on_progress)(app.store.clone(), node, report).await {
160        Ok(record) => Json(record).into_response(),
161        Err(e) => (StatusCode::BAD_REQUEST, format!("{e:#}")).into_response(),
162    }
163}
164
165async fn nodes(State(app): State<App>, headers: HeaderMap) -> Response {
166    if !authorized(&app, &headers) {
167        return StatusCode::UNAUTHORIZED.into_response();
168    }
169
170    let members = app.store.node().map(super::members).unwrap_or_default();
171    Json(members).into_response()
172}
173
174pub async fn fetch_nodes(endpoint: &Endpoint) -> anyhow::Result<Vec<super::Member>> {
175    let url = endpoint.url.replace("/write", "/nodes");
176    let res = CLIENT.get(url).bearer_auth(&endpoint.token).send().await?;
177    Ok(res.error_for_status()?.json().await?)
178}
179
180/// Send an `orch progress` report to the daemon, which commits, pushes and records it
181pub async fn send_progress(endpoint: &Endpoint, report: &Report) -> anyhow::Result<Record> {
182    let url = endpoint.url.replace("/write", "/progress");
183    let res = CLIENT
184        .post(url)
185        .bearer_auth(&endpoint.token)
186        .json(report)
187        .send()
188        .await?;
189    let status = res.status();
190    if !status.is_success() {
191        anyhow::bail!(
192            "orch service refused the report ({status}): {}",
193            res.text().await?
194        );
195    }
196
197    Ok(res.json().await?)
198}
199
200pub async fn cleanup() {
201    if let Ok(path) = port_path() {
202        let _ = tokio_fs::remove_file(path).await;
203    }
204}
205
206/// The running daemon's endpoint. A file left by a daemon that is gone names nothing
207pub async fn daemon_endpoint() -> Option<Endpoint> {
208    let body = tokio_fs::read_to_string(port_path().ok()?).await.ok()?;
209    let mut parts = body.split_whitespace();
210    let port: u16 = parts.next()?.parse().ok()?;
211    let token = parts.next()?.to_string();
212    let pid: u32 = parts.next()?.parse().ok()?;
213    let alive = task::spawn_blocking(move || home::pid_is_orch_serve(pid))
214        .await
215        .ok()?;
216    alive.then(|| Endpoint {
217        url: format!("http://127.0.0.1:{port}/write"),
218        token,
219    })
220}
221
222pub(crate) async fn send(endpoint: &Endpoint, cmd: &Command) -> reqwest::Result<Reply> {
223    CLIENT
224        .post(&endpoint.url)
225        .bearer_auth(&endpoint.token)
226        .json(cmd)
227        .send()
228        .await?
229        .error_for_status()?
230        .json()
231        .await
232}