orch-cli 0.112.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Raft RPCs and forwarded writes between nodes, JSON over HTTP like `../agents-coordination`.
//! Every request carries the cluster secret, so reaching the port is not enough to join

use std::error;
use std::fmt::Write as _;
use std::sync::{Arc, LazyLock};
use std::time::Duration;

use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use hmac::Hmac;
use hmac::Mac;
use openraft::BasicNode;
use openraft::error::ClientWriteError;
use openraft::error::{
    InstallSnapshotError, NetworkError, RPCError, RaftError, RemoteError, Unreachable,
};
use openraft::network::{RPCOption, RaftNetwork, RaftNetworkFactory};
use openraft::raft::{
    AppendEntriesRequest, AppendEntriesResponse, InstallSnapshotRequest, InstallSnapshotResponse,
    VoteRequest, VoteResponse,
};
use reqwest::header::HeaderValue;
use serde::Serialize;
use serde::de::DeserializeOwned;
use subtle::ConstantTimeEq;

use super::version::{Version, Versions};
use super::{NodeId, Raft, Reply, Request, TypeConfig};

const SECRET_HEADER: &str = "x-orch-cluster-secret";
const NONCE_HEADER: &str = "x-orch-nonce";
const PROOF_HEADER: &str = "x-orch-proof";
/// The sender's orch version on every Raft RPC, so each node learns what its peers run
const VERSION_HEADER: &str = "x-orch-version";

static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
    reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .unwrap_or_default()
});

#[derive(Clone)]
struct App {
    raft: Raft,
    secret: Arc<str>,
    me: Arc<Hello>,
    /// The address peers dial, bound into every proof so a proof relayed through another host fails
    addr: Arc<str>,
    versions: Arc<Versions>,
}

/// What a node says about itself to a peer that found it on the tailnet
#[derive(Debug, Clone, PartialEq, Serialize, serde::Deserialize)]
pub struct Hello {
    pub name: String,
    pub id: NodeId,
    pub witness: bool,
    #[serde(default)]
    pub leader: Option<NodeId>,
    #[serde(default)]
    pub term: u64,
    /// HMAC of the prober's nonce and this name, so the prober knows the peer holds the secret
    #[serde(default)]
    pub proof: String,
    /// None from a node older than version reports
    #[serde(default)]
    pub version: Option<Version>,
    /// The version the node needs before it applies again
    #[serde(default)]
    pub needs_upgrade: Option<Version>,
    /// The node upgrades itself, so a lower node waits its turn behind it
    #[serde(default)]
    pub auto_upgrade: bool,
    /// Why the node's last upgrade failed
    #[serde(default)]
    pub upgrade_error: Option<String>,
}

/// HMAC-SHA256 under the cluster secret, in hex. Proves the secret without sending it
fn mac(secret: &str, parts: &[&str]) -> String {
    let mut m =
        Hmac::<sha2::Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes any key");
    for part in parts {
        m.update(part.as_bytes());
        m.update(b"\0");
    }

    let bytes = m.finalize().into_bytes();
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(out, "{b:02x}");
    }
    out
}

/// A node asking the leader to add it as a learner
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
pub struct Join {
    pub id: NodeId,
    pub addr: String,
}

fn authorized(app: &App, headers: &HeaderMap) -> bool {
    let given = headers
        .get(SECRET_HEADER)
        .map(HeaderValue::as_bytes)
        .unwrap_or_default();
    let ok: bool = given.ct_eq(app.secret.as_bytes()).into();
    if ok
        && let Some(v) = headers
            .get(VERSION_HEADER)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok())
    {
        app.versions.saw_peer(v);
    }

    ok
}

pub(crate) fn router(
    raft: Raft,
    secret: Arc<str>,
    me: Hello,
    addr: String,
    versions: Arc<Versions>,
) -> Router {
    Router::new()
        .route("/raft/append", post(append))
        .route("/raft/snapshot", post(snapshot))
        .route("/raft/vote", post(vote))
        .route("/cluster/write", post(write))
        .route("/cluster/hello", get(hello))
        .route("/cluster/join", post(join))
        .with_state(App {
            raft,
            secret,
            me: Arc::new(me),
            addr: Arc::from(addr),
            versions,
        })
}

/// Answers only a prober that proves the secret, and proves it back, so neither side sends it
async fn hello(State(a): State<App>, headers: HeaderMap) -> Response {
    let header = |name: &str| {
        headers
            .get(name)
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_string()
    };
    let nonce = header(NONCE_HEADER);
    let expected = mac(&a.secret, &["probe", &nonce, &a.addr]);
    let proven: bool = header(PROOF_HEADER)
        .as_bytes()
        .ct_eq(expected.as_bytes())
        .into();
    if nonce.len() < 16 || !proven {
        return StatusCode::UNAUTHORIZED.into_response();
    }

    let m = a.raft.metrics().borrow().clone();
    Json(Hello {
        leader: m.current_leader,
        term: m.current_term,
        proof: mac(&a.secret, &["hello", &nonce, &a.me.name, &a.addr]),
        needs_upgrade: a.versions.needs_upgrade(),
        upgrade_error: a.versions.upgrade_error(),
        ..(*a.me).clone()
    })
    .into_response()
}

/// Adds the caller as a learner on the leader, or sends it on to the leader
async fn join(State(a): State<App>, headers: HeaderMap, Json(req): Json<Join>) -> Response {
    if !authorized(&a, &headers) {
        return StatusCode::UNAUTHORIZED.into_response();
    }

    let node = BasicNode::new(&req.addr);
    match a.raft.add_learner(req.id, node, false).await {
        Ok(_) => StatusCode::OK.into_response(),
        Err(RaftError::APIError(ClientWriteError::ForwardToLeader(f))) => match f.leader_node {
            Some(leader) => match send_join(&leader.addr, &a.secret, &req).await {
                Ok(()) => StatusCode::OK.into_response(),
                Err(e) => (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
            },
            None => (StatusCode::SERVICE_UNAVAILABLE, "no leader yet").into_response(),
        },
        Err(e) => (StatusCode::SERVICE_UNAVAILABLE, e.to_string()).into_response(),
    }
}

pub async fn send_join(addr: &str, secret: &str, req: &Join) -> anyhow::Result<()> {
    let res = CLIENT
        .post(format!("http://{addr}/cluster/join"))
        .header(SECRET_HEADER, secret)
        .json(req)
        .send()
        .await?;
    anyhow::ensure!(
        res.status().is_success(),
        "join refused by {addr} ({}): {}",
        res.status(),
        res.text().await?
    );
    Ok(())
}

/// Ask a host found on the tailnet who it is. The secret never leaves this node. Both proofs cover
/// the address dialed, and the answer must carry the name Tailscale gives that address, so a host
/// that relays a real member's answer is rejected
pub async fn probe(addr: &str, secret: &str, expect_name: Option<&str>) -> Option<Hello> {
    let nonce = uuid::Uuid::new_v4().simple().to_string();
    let res = CLIENT
        .get(format!("http://{addr}/cluster/hello"))
        .header(NONCE_HEADER, &nonce)
        .header(PROOF_HEADER, mac(secret, &["probe", &nonce, addr]))
        .timeout(Duration::from_secs(1))
        .send()
        .await
        .ok()?;
    let hello: Hello = res.error_for_status().ok()?.json().await.ok()?;
    if expect_name.is_some_and(|name| name != hello.name) {
        return None;
    }

    let expected = mac(secret, &["hello", &nonce, &hello.name, addr]);
    let proven: bool = hello.proof.as_bytes().ct_eq(expected.as_bytes()).into();
    proven.then_some(hello)
}

async fn append(
    State(a): State<App>,
    headers: HeaderMap,
    Json(req): Json<AppendEntriesRequest<TypeConfig>>,
) -> Response {
    if !authorized(&a, &headers) {
        return StatusCode::UNAUTHORIZED.into_response();
    }

    Json(a.raft.append_entries(req).await).into_response()
}

async fn snapshot(
    State(a): State<App>,
    headers: HeaderMap,
    Json(req): Json<InstallSnapshotRequest<TypeConfig>>,
) -> Response {
    if !authorized(&a, &headers) {
        return StatusCode::UNAUTHORIZED.into_response();
    }

    Json(a.raft.install_snapshot(req).await).into_response()
}

async fn vote(
    State(a): State<App>,
    headers: HeaderMap,
    Json(req): Json<VoteRequest<NodeId>>,
) -> Response {
    if !authorized(&a, &headers) {
        return StatusCode::UNAUTHORIZED.into_response();
    }

    Json(a.raft.vote(req).await).into_response()
}

/// A write a follower forwarded. It is proposed here and never forwarded again, so writes cannot loop
async fn write(State(a): State<App>, headers: HeaderMap, Json(req): Json<Request>) -> Response {
    if !authorized(&a, &headers) {
        return StatusCode::UNAUTHORIZED.into_response();
    }

    if let Err(e) = req.cmd.check_replicable() {
        return (StatusCode::BAD_REQUEST, e.to_string()).into_response();
    }

    if let Some(v) = req.version {
        a.versions.saw_peer(v);
        // It could not apply the entry, so it stops here and lets a node that can lead
        if a.versions.mine().is_some_and(|mine| v > mine) {
            a.versions.hold(v);
        }
    }

    // A node that stopped applying steps aside, so the sender waits for the next leader
    if let Some(needed) = a.versions.needs_upgrade() {
        return (
            StatusCode::MISDIRECTED_REQUEST,
            format!("this node needs orch {needed} and steps aside as leader"),
        )
            .into_response();
    }

    match a.raft.client_write(req).await {
        Ok(r) => Json(r.data).into_response(),
        // Refused before anything was proposed, so the sender may safely try another node
        Err(e @ RaftError::APIError(ClientWriteError::ForwardToLeader(_))) => {
            (StatusCode::MISDIRECTED_REQUEST, e.to_string()).into_response()
        }
        Err(e) => (StatusCode::SERVICE_UNAVAILABLE, e.to_string()).into_response(),
    }
}

/// Why a forwarded write failed. Only `NotApplied` is safe to send again
#[derive(Debug)]
pub(crate) enum ForwardError {
    /// The connection was refused, or the node said it is not the leader
    NotApplied(String),
    /// It may or may not have been applied, so it must not be sent again
    Unknown(anyhow::Error),
}

pub(crate) async fn forward(
    addr: &str,
    secret: &str,
    req: &Request,
) -> Result<Reply, ForwardError> {
    let res = CLIENT
        .post(format!("http://{addr}/cluster/write"))
        .header(SECRET_HEADER, secret)
        .json(req)
        .send()
        .await
        .map_err(|e| {
            if e.is_connect() {
                ForwardError::NotApplied(e.to_string())
            } else {
                ForwardError::Unknown(e.into())
            }
        })?;
    let status = res.status();
    if status == StatusCode::MISDIRECTED_REQUEST {
        let body = res.text().await.unwrap_or_default();
        return Err(ForwardError::NotApplied(format!(
            "{addr} is not the leader: {body}"
        )));
    }

    if !status.is_success() {
        let body = res.text().await.unwrap_or_default();
        return Err(ForwardError::Unknown(anyhow::anyhow!(
            "leader at {addr} refused the write ({status}): {body}"
        )));
    }

    res.json()
        .await
        .map_err(|e| ForwardError::Unknown(e.into()))
}

pub(crate) struct HttpNetwork {
    pub secret: Arc<str>,
    pub version: Version,
}

impl RaftNetworkFactory<TypeConfig> for HttpNetwork {
    type Network = Peer;

    async fn new_client(&mut self, target: NodeId, node: &BasicNode) -> Peer {
        Peer {
            target,
            addr: node.addr.clone(),
            secret: Arc::clone(&self.secret),
            version: self.version.to_string(),
        }
    }
}

pub(crate) struct Peer {
    target: NodeId,
    addr: String,
    secret: Arc<str>,
    version: String,
}

impl Peer {
    async fn send<Req, Resp, E>(
        &self,
        path: &str,
        req: Req,
        option: &RPCOption,
    ) -> Result<Resp, RPCError<NodeId, BasicNode, RaftError<NodeId, E>>>
    where
        Req: Serialize,
        Resp: DeserializeOwned,
        E: error::Error + DeserializeOwned,
    {
        let res = CLIENT
            .post(format!("http://{}/raft/{path}", self.addr))
            .header(SECRET_HEADER, &*self.secret)
            .header(VERSION_HEADER, &self.version)
            .timeout(option.hard_ttl())
            .json(&req)
            .send()
            .await
            .map_err(|e| {
                if e.is_connect() {
                    RPCError::Unreachable(Unreachable::new(&e))
                } else {
                    RPCError::Network(NetworkError::new(&e))
                }
            })?;
        let res = res
            .error_for_status()
            .map_err(|e| RPCError::Network(NetworkError::new(&e)))?;
        let body: Result<Resp, RaftError<NodeId, E>> = res
            .json()
            .await
            .map_err(|e| RPCError::Network(NetworkError::new(&e)))?;
        body.map_err(|e| RPCError::RemoteError(RemoteError::new(self.target, e)))
    }
}

impl RaftNetwork<TypeConfig> for Peer {
    async fn append_entries(
        &mut self,
        req: AppendEntriesRequest<TypeConfig>,
        option: RPCOption,
    ) -> Result<AppendEntriesResponse<NodeId>, RPCError<NodeId, BasicNode, RaftError<NodeId>>> {
        self.send("append", req, &option).await
    }

    async fn install_snapshot(
        &mut self,
        req: InstallSnapshotRequest<TypeConfig>,
        option: RPCOption,
    ) -> Result<
        InstallSnapshotResponse<NodeId>,
        RPCError<NodeId, BasicNode, RaftError<NodeId, InstallSnapshotError>>,
    > {
        self.send("snapshot", req, &option).await
    }

    async fn vote(
        &mut self,
        req: VoteRequest<NodeId>,
        option: RPCOption,
    ) -> Result<VoteResponse<NodeId>, RPCError<NodeId, BasicNode, RaftError<NodeId>>> {
        self.send("vote", req, &option).await
    }
}