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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Raft between orch nodes. Only coordination state goes through the log, the design is in
//! `docs/specs/2026-10-26-multi-machine-cluster-design.md`.

pub(crate) mod apply;
pub mod config;
pub mod discovery;
pub mod local;
pub mod network;
pub mod progress;
mod storage;
pub mod version;

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::error;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::io;
use std::io::Cursor;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use openraft::error::{ClientWriteError, InstallSnapshotError, RPCError, RaftError, Unreachable};
use openraft::network::{RPCOption, RaftNetwork, RaftNetworkFactory};
use openraft::raft::{
    AppendEntriesRequest, AppendEntriesResponse, InstallSnapshotRequest, InstallSnapshotResponse,
    VoteRequest, VoteResponse,
};
use openraft::storage::Adaptor;
use openraft::{BasicNode, SnapshotPolicy};

use crate::config as crate_config;
use crate::store::TaskStore;
use futures::future::join_all;

pub use crate::store::{Command, Reply, Request};
pub use storage::RaftStore;
use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::sync::watch;
use tokio::time;
use tokio::time::Instant;
use version::{Version, Versions};

pub type NodeId = u64;

openraft::declare_raft_types!(
    pub TypeConfig:
        D = Request,
        R = Reply,
);

pub type Raft = openraft::Raft<TypeConfig>;

/// A `cluster:` section turns the cluster on. Without one, orch writes straight to SQLite as it always has
pub fn enabled() -> bool {
    crate_config::get("cluster.secret").is_ok_and(|s| !s.is_empty())
}

/// Start this machine's node from the `cluster:` section and the tailnet. A learner keeps asking
/// the cluster to add it until a member proves the secret and takes it
pub async fn start(store: &TaskStore, raft_db: &Path) -> anyhow::Result<Node> {
    let cfg = config::ClusterConfig::load()?
        .ok_or_else(|| anyhow::anyhow!("no cluster.secret in the config"))?;
    let tailnet = discovery::status().await?;
    let plan = config::plan(&cfg, &tailnet)?;
    tracing::info!(
        name = %plan.name,
        addr = %plan.addr,
        elect = plan.elect,
        learner = plan.learner,
        "starting cluster node"
    );
    let node = start_node(
        store,
        raft_db,
        NodeConfig {
            name: plan.name.clone(),
            id: plan.id,
            addr: plan.addr.clone(),
            secret: cfg.secret.clone(),
            voters: plan.voters.clone(),
            elect: plan.elect,
            version: Version::current(),
            auto_upgrade: cfg.auto_upgrade,
        },
    )
    .await?;
    if plan.learner {
        tokio::spawn(join_loop(node.clone(), plan, cfg));
    }

    Ok(node)
}

async fn join_loop(node: Node, plan: config::Plan, cfg: config::ClusterConfig) {
    loop {
        let member = node
            .raft
            .metrics()
            .borrow()
            .membership_config
            .membership()
            .nodes()
            .any(|(id, _)| *id == plan.id);
        if member {
            return;
        }

        if let Ok(tailnet) = discovery::status().await {
            for peer in tailnet.peers.iter().filter(|p| p.online) {
                let addr = format!("{}:{}", peer.ip, cfg.port);
                let Some(hello) = network::probe(&addr, &cfg.secret, Some(&peer.name)).await else {
                    continue;
                };
                if let Some(v) = hello.version {
                    node.versions.saw_peer(v);
                }

                let join = network::Join {
                    id: plan.id,
                    addr: plan.addr.clone(),
                };
                match network::send_join(&addr, &cfg.secret, &join).await {
                    Ok(()) => tracing::info!(via = %peer.name, "joined the cluster as a learner"),
                    Err(e) => tracing::warn!(via = %peer.name, err = %e, "join refused"),
                }

                break;
            }
        }

        time::sleep(Duration::from_secs(30)).await;
    }
}

/// One member as the leader sees it, for `orch nodes`
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Member {
    pub id: NodeId,
    pub addr: String,
    pub voter: bool,
    pub leader: bool,
    pub me: bool,
    /// None when the node did not answer, or runs an orch from before versions were reported
    #[serde(default)]
    pub version: Option<Version>,
    /// The version the node needs before it applies again
    #[serde(default)]
    pub needs_upgrade: Option<Version>,
    /// Set when the node answered `hello` and proved the secret, and always for this machine
    #[serde(default)]
    pub answered: Option<Answered>,
}

/// What a node that answered says about its upgrades
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Answered {
    pub auto_upgrade: bool,
    /// Why the node's last upgrade failed
    pub upgrade_error: Option<String>,
}

/// The members with the version each one reports. Peers are asked over `hello`, which proves the secret
pub async fn describe(node: &Node) -> Vec<Member> {
    let mut members = members(node);
    let Some(secret) = node.secret.clone() else {
        return members;
    };
    let asks = members.iter().filter(|m| !m.me).map(|m| {
        let secret = Arc::clone(&secret);
        let addr = m.addr.clone();
        async move { (addr.clone(), network::probe(&addr, &secret, None).await) }
    });
    let answers: BTreeMap<String, network::Hello> = join_all(asks)
        .await
        .into_iter()
        .filter_map(|(addr, hello)| hello.map(|h| (addr, h)))
        .collect();
    for m in members.iter_mut().filter(|m| !m.me) {
        if let Some(hello) = answers.get(&m.addr) {
            m.version = hello.version;
            m.needs_upgrade = hello.needs_upgrade;
            m.answered = Some(Answered {
                auto_upgrade: hello.auto_upgrade,
                upgrade_error: hello.upgrade_error.clone(),
            });
            if let Some(v) = hello.version {
                node.versions.saw_peer(v);
            }
        }
    }

    members
}

pub fn members(node: &Node) -> Vec<Member> {
    let m = node.raft.metrics().borrow().clone();
    let membership = m.membership_config.membership();
    let voters: BTreeSet<NodeId> = membership.voter_ids().collect();
    membership
        .nodes()
        .map(|(id, n)| {
            let me = *id == m.id;
            Member {
                id: *id,
                addr: n.addr.clone(),
                voter: voters.contains(id),
                leader: m.current_leader == Some(*id),
                me,
                version: me.then(|| node.versions.mine()).flatten(),
                needs_upgrade: me.then(|| node.versions.needs_upgrade()).flatten(),
                answered: me.then(|| Answered {
                    auto_upgrade: node.versions.auto_upgrade(),
                    upgrade_error: node.versions.upgrade_error(),
                }),
            }
        })
        .collect()
}

/// Id of the node when orch runs alone
pub const SINGLE_NODE_ID: NodeId = 1;

fn config() -> anyhow::Result<openraft::Config> {
    Ok(openraft::Config {
        cluster_name: "orch".into(),
        heartbeat_interval: 250,
        election_timeout_min: 1000,
        election_timeout_max: 2000,
        snapshot_policy: SnapshotPolicy::LogsSinceLast(1000),
        ..Default::default()
    }
    .validate()?)
}

/// A running node. The store holds one and sends every replicated write through it
#[derive(Clone)]
pub struct Node {
    pub raft: Raft,
    /// None on a single node, which has no peers to forward to
    secret: Option<Arc<str>>,
    server: Option<Arc<Notify>>,
    versions: Arc<Versions>,
}

impl Debug for Node {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Node")
            .field("server", &self.server.is_some())
            .finish_non_exhaustive()
    }
}

impl Node {
    /// Propose on this node, or forward to the leader when this node follows. During an election
    /// the leader can be unknown or stale, so it waits and tries again, but only a write that was
    /// certainly not applied is sent again
    pub async fn write(&self, req: Request) -> anyhow::Result<Reply> {
        let deadline = Instant::now() + Duration::from_secs(10);
        // A held node is stepping aside as leader, so the write waits for the next one
        while let Some(needed) = self.needs_upgrade()
            && self.raft_leader()
        {
            if Instant::now() >= deadline {
                anyhow::bail!("this node needs orch {needed} and no other node took the lead");
            }

            time::sleep(Duration::from_millis(200)).await;
        }

        loop {
            let err = match self.raft.client_write(req.clone()).await {
                Ok(r) => return Ok(r.data),
                Err(e) => e,
            };
            let RaftError::APIError(ClientWriteError::ForwardToLeader(f)) = &err else {
                return Err(err.into());
            };
            let Some(secret) = &self.secret else {
                return Err(err.into());
            };
            let reason = match &f.leader_node {
                Some(leader) => match network::forward(&leader.addr, secret, &req).await {
                    Ok(reply) => return Ok(reply),
                    Err(network::ForwardError::Unknown(e)) => return Err(e),
                    Err(network::ForwardError::NotApplied(why)) => why,
                },
                None => "no leader known".to_string(),
            };
            if Instant::now() >= deadline {
                anyhow::bail!("no leader took the write: {reason}");
            }

            time::sleep(Duration::from_millis(200)).await;
        }
    }

    /// The node that runs the leader's phases. A node that stopped applying never does
    pub fn is_leader(&self) -> bool {
        self.raft_leader() && self.needs_upgrade().is_none()
    }

    fn raft_leader(&self) -> bool {
        let m = self.raft.metrics();
        let m = m.borrow();
        m.current_leader == Some(m.id)
    }

    /// The version this node stamps on its writes. None on a single node
    pub fn version(&self) -> Option<Version> {
        self.versions.mine()
    }

    /// The version this node needs before it applies again, or None while it applies
    pub fn needs_upgrade(&self) -> Option<Version> {
        self.versions.needs_upgrade()
    }

    /// The highest version a peer that proved the secret reported
    pub fn highest_peer_version(&self) -> Option<Version> {
        self.versions.highest_peer()
    }

    /// What this node knows about versions, shared with its listener
    pub fn versions(&self) -> &Arc<Versions> {
        &self.versions
    }

    /// This node's id in the Raft group
    pub fn id(&self) -> NodeId {
        self.raft.metrics().borrow().id
    }

    pub async fn stop(self) {
        if let Some(server) = self.server {
            server.notify_one();
        }

        let _ = self.raft.shutdown().await;
    }
}

/// How one node of a cluster starts: its id, the address it listens on, the shared secret, the
/// voters to initialize with, and whether it may lead (a witness may not)
pub struct NodeConfig {
    pub name: String,
    pub id: NodeId,
    pub addr: String,
    pub secret: String,
    pub voters: BTreeMap<NodeId, String>,
    pub elect: bool,
    /// `Version::current()` outside tests, which start nodes of different versions in one process
    pub version: Version,
    /// `cluster.auto_upgrade`
    pub auto_upgrade: bool,
}

impl Debug for NodeConfig {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodeConfig")
            .field("name", &self.name)
            .field("id", &self.id)
            .field("addr", &self.addr)
            .field("voters", &self.voters)
            .field("elect", &self.elect)
            .field("version", &self.version)
            .field("auto_upgrade", &self.auto_upgrade)
            .finish_non_exhaustive()
    }
}

/// Start a one-node cluster over `store`, with its log in `raft_db`, and route the store's
/// replicated writes through it
pub async fn start_single(store: &TaskStore, raft_db: &Path) -> anyhow::Result<Node> {
    let raft_store = RaftStore::open(raft_db, store.clone()).await?;
    let (log, sm) = Adaptor::new(raft_store);
    let raft = Raft::new(SINGLE_NODE_ID, Arc::new(config()?), NoNetwork, log, sm).await?;
    let members = BTreeMap::from([(SINGLE_NODE_ID, BasicNode::default())]);
    // A restart finds the membership in the log, and initialize refuses a second time
    if let Err(e) = raft.initialize(members).await {
        tracing::debug!(err = %e, "raft already initialized");
    }

    raft.wait(Some(Duration::from_secs(10)))
        .current_leader(SINGLE_NODE_ID, "single node leads")
        .await?;
    let node = Node {
        raft,
        secret: None,
        server: None,
        versions: Arc::new(Versions::new(None)),
    };
    store.attach_node(node.clone());
    Ok(node)
}

/// Start one node of a cluster and serve its RPCs on `cfg.addr`. Every voter initializes with
/// the same membership, which openraft accepts, so no voter is special
pub async fn start_node(
    store: &TaskStore,
    raft_db: &Path,
    cfg: NodeConfig,
) -> anyhow::Result<Node> {
    let listener = TcpListener::bind(&cfg.addr).await?;
    start_node_on(store, raft_db, cfg, listener).await
}

/// Like `start_node`, with a listener the caller already bound. `cfg.addr` is the address peers use
pub async fn start_node_on(
    store: &TaskStore,
    raft_db: &Path,
    cfg: NodeConfig,
    listener: TcpListener,
) -> anyhow::Result<Node> {
    let secret: Arc<str> = Arc::from(cfg.secret);
    let versions = Arc::new(Versions::new(Some(cfg.version)).with_auto_upgrade(cfg.auto_upgrade));
    let raft_store = RaftStore::open_with(raft_db, store.clone(), Arc::clone(&versions)).await?;
    let (log, sm) = Adaptor::new(raft_store);
    let config = openraft::Config {
        enable_elect: cfg.elect,
        ..config()?
    }
    .validate()?;
    let network = network::HttpNetwork {
        secret: Arc::clone(&secret),
        version: cfg.version,
    };
    let raft = Raft::new(cfg.id, Arc::new(config), network, log, sm).await?;
    tokio::spawn(step_aside(raft.clone(), versions.subscribe()));
    let me = network::Hello {
        name: cfg.name,
        id: cfg.id,
        witness: !cfg.elect,
        leader: None,
        term: 0,
        proof: String::new(),
        version: Some(cfg.version),
        needs_upgrade: None,
        auto_upgrade: cfg.auto_upgrade,
        upgrade_error: None,
    };
    let app = network::router(
        raft.clone(),
        Arc::clone(&secret),
        me,
        cfg.addr.clone(),
        Arc::clone(&versions),
    );
    let stop = Arc::new(Notify::new());
    let stopped = Arc::clone(&stop);
    tokio::spawn(async move {
        // Graceful shutdown also closes kept-alive connections, which would keep answering for a stopped node
        let served = axum::serve(listener, app)
            .with_graceful_shutdown(async move { stopped.notified().await })
            .await;
        if let Err(e) = served {
            tracing::warn!(err = %e, "cluster listener stopped");
        }
    });
    // initialize starts an election whatever enable_elect says, so a witness waits for the leader
    if cfg.elect && versions.needs_upgrade().is_none() && !cfg.voters.is_empty() {
        let members: BTreeMap<NodeId, BasicNode> = cfg
            .voters
            .into_iter()
            .map(|(id, addr)| (id, BasicNode::new(addr)))
            .collect();
        if let Err(e) = raft.initialize(members).await {
            tracing::debug!(err = %e, "raft already initialized");
        }
    }

    let node = Node {
        raft,
        secret: Some(secret),
        server: Some(stop),
        versions,
    };
    store.attach_node(node.clone());
    Ok(node)
}

/**
 * A node that stopped applying must not lead. openraft 0.9 has no call to hand the lead over, so
 * the node stops electing and stops sending heartbeats, and the other voters elect a leader once
 * its lease runs out. It keeps voting and receiving the log
 **/
async fn step_aside(raft: Raft, mut needs: watch::Receiver<Option<Version>>) {
    loop {
        if needs.borrow_and_update().is_some() {
            raft.runtime_config().elect(false);
            raft.runtime_config().heartbeat(false);
            return;
        }

        if needs.changed().await.is_err() {
            return;
        }
    }
}

/// A single node never sends an RPC. The tailnet transport replaces this
struct NoNetwork;

impl RaftNetworkFactory<TypeConfig> for NoNetwork {
    type Network = NoNetwork;

    async fn new_client(&mut self, _target: NodeId, _node: &BasicNode) -> NoNetwork {
        NoNetwork
    }
}

fn unreachable<E: error::Error>() -> RPCError<NodeId, BasicNode, E> {
    RPCError::Unreachable(Unreachable::new(&io::Error::other(
        "no network on a single node",
    )))
}

impl RaftNetwork<TypeConfig> for NoNetwork {
    async fn append_entries(
        &mut self,
        _req: AppendEntriesRequest<TypeConfig>,
        _option: RPCOption,
    ) -> Result<AppendEntriesResponse<NodeId>, RPCError<NodeId, BasicNode, RaftError<NodeId>>> {
        Err(unreachable())
    }

    async fn install_snapshot(
        &mut self,
        _req: InstallSnapshotRequest<TypeConfig>,
        _option: RPCOption,
    ) -> Result<
        InstallSnapshotResponse<NodeId>,
        RPCError<NodeId, BasicNode, RaftError<NodeId, InstallSnapshotError>>,
    > {
        Err(unreachable())
    }

    async fn vote(
        &mut self,
        _req: VoteRequest<NodeId>,
        _option: RPCOption,
    ) -> Result<VoteResponse<NodeId>, RPCError<NodeId, BasicNode, RaftError<NodeId>>> {
        Err(unreachable())
    }
}

#[cfg(test)]
mod tests;