orch-cli 0.119.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
//! Client for orch-relay, which receives the GitHub App's webhooks on Cloudflare. orch connects
//! out, so it needs no endpoint. The contract is PROTOCOL.md in the orch-relay repository

use crate::store::TaskStore;
use futures::{SinkExt, StreamExt};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::mpsc::UnboundedSender;
use tokio::time;
use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest};

const CURSOR_KEY: &str = "relay_cursor";
const PING_EVERY: Duration = Duration::from_secs(300);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_BACKOFF_SECS: u64 = 300;
// A shorter session keeps the backoff growing, so a relay that closes each socket at once is not
// hit every second, every request counts toward its daily limit
const STABLE_SESSION: Duration = Duration::from_secs(60);

/// What the relay client tells the engine
#[derive(Debug)]
pub(crate) enum Signal {
    Connected,
    Disconnected,
    /// The relay deleted events this client never read
    Gap,
    Event(Event),
}

/// One delivery. The engine reads the item it names from GitHub and never uses the payload as data
#[derive(Debug, Clone, Default)]
pub(crate) struct Event {
    pub name: String,
    pub action: String,
    pub repo: String,
    /// `None` when the relay truncated a payload over 1 MB
    pub payload: Option<serde_json::Value>,
}

#[derive(serde::Deserialize)]
struct Incoming {
    #[serde(rename = "type")]
    kind: String,
    #[serde(default)]
    seq: i64,
    #[serde(default)]
    event: String,
    #[serde(default)]
    action: String,
    #[serde(default)]
    repo: String,
    #[serde(default)]
    payload: Option<serde_json::Value>,
    #[serde(default)]
    truncated: bool,
}

/// Keeps one stream open for the life of the daemon, reconnecting with backoff
pub(crate) async fn run(
    url: String,
    token: String,
    store: Arc<TaskStore>,
    signals: UnboundedSender<Signal>,
) {
    let mut backoff = 1;

    loop {
        let started = Instant::now();
        match session(&url, &token, &store, &signals, PING_EVERY).await {
            Ok(()) => tracing::warn!("relay stream closed, reconnecting"),
            Err(e) => tracing::warn!(err = %e, "relay stream failed, reconnecting"),
        }
        let _ = signals.send(Signal::Disconnected);

        let wait = retry_after(backoff, started.elapsed());
        time::sleep(Duration::from_secs(wait)).await;
        backoff = (wait * 2).min(MAX_BACKOFF_SECS);
    }
}

/// Seconds to wait before the next connect
fn retry_after(backoff: u64, lasted: Duration) -> u64 {
    if lasted >= STABLE_SESSION { 1 } else { backoff }
}

async fn session(
    url: &str,
    token: &str,
    store: &TaskStore,
    signals: &UnboundedSender<Signal>,
    ping_every: Duration,
) -> anyhow::Result<()> {
    let ws_url = format!("{}/ws", url.trim_end_matches('/'))
        .replacen("https://", "wss://", 1)
        .replacen("http://", "ws://", 1);
    let mut request = ws_url.into_client_request()?;
    request
        .headers_mut()
        .insert("authorization", format!("Bearer {token}").parse()?);
    let (mut ws, _) = time::timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(request))
        .await
        .map_err(|_| anyhow::anyhow!("relay connect timed out"))??;

    let after = cursor(store).await;
    let hello = serde_json::json!({ "v": 1, "type": "hello", "after": after });
    ws.send(Message::Text(hello.to_string())).await?;
    tracing::info!(after, "relay stream connected");
    let _ = signals.send(Signal::Connected);

    let mut ping = time::interval(ping_every);
    ping.tick().await;
    // True from a ping until any message arrives, so a socket that stays silent for a whole
    // interval after a ping is dead
    let mut awaiting = false;

    loop {
        tokio::select! {
            _ = ping.tick() => {
                if awaiting {
                    anyhow::bail!("relay stream idle, no pong");
                }

                ws.send(Message::Text("ping".to_string())).await?;
                awaiting = true;
            }
            msg = ws.next() => match msg {
                None => return Ok(()),
                Some(msg) => {
                    awaiting = false;
                    match msg? {
                    Message::Text(text) => handle(&text, store, signals).await,
                    Message::Close(_) => return Ok(()),
                    _ => {}
                    }
                }
            },
        }
    }
}

async fn cursor(store: &TaskStore) -> i64 {
    store
        .kv_get(CURSOR_KEY)
        .await
        .ok()
        .flatten()
        .and_then(|v| v.parse().ok())
        .unwrap_or(0)
}

/// An event is a hint to re-read GitHub, never a command, so orch acts on what it reads there
pub(crate) async fn handle(text: &str, store: &TaskStore, signals: &UnboundedSender<Signal>) {
    if text == "pong" {
        return;
    }

    let msg: Incoming = match serde_json::from_str(text) {
        Ok(msg) => msg,
        Err(e) => {
            tracing::warn!(err = %e, "unreadable relay message");
            return;
        }
    };

    match msg.kind.as_str() {
        "gap" => {
            tracing::warn!("relay deleted events this client never read, syncing every project");
            let _ = signals.send(Signal::Gap);
        }
        "event" => {
            // An orch PR closes its issue, so `issues` `closed` also covers a merged PR
            if msg.event == "issues" && msg.action == "closed" {
                let number = msg
                    .payload
                    .as_ref()
                    .and_then(|p| p.pointer("/issue/number"))
                    .and_then(serde_json::Value::as_i64);

                if let Some(number) = number {
                    let key = format!("dep_blocker_read_at:{}#{number}", msg.repo);

                    if let Err(e) = store.kv_delete(&key).await {
                        tracing::warn!(err = %e, key, "failed to release a closed blocker");
                    }
                }
            }

            if let Err(e) = store.kv_set(CURSOR_KEY, &msg.seq.to_string()).await {
                tracing::warn!(err = %e, seq = msg.seq, "failed to store the relay cursor");
            }

            let _ = signals.send(Signal::Event(Event {
                name: msg.event,
                action: msg.action,
                repo: msg.repo,
                payload: msg.payload.filter(|_| !msg.truncated),
            }));
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use tokio::net::TcpListener;
    use tokio::sync::mpsc;
    use tokio::sync::mpsc::UnboundedReceiver;
    use tokio_tungstenite::tungstenite::handshake::server::Request;
    use tokio_tungstenite::tungstenite::handshake::server::Response;

    use super::*;

    fn drain(rx: &mut UnboundedReceiver<Signal>) -> Vec<Signal> {
        let mut out = Vec::new();
        while let Ok(signal) = rx.try_recv() {
            out.push(signal);
        }
        out
    }

    #[tokio::test]
    async fn an_event_stores_the_cursor_and_passes_the_event_on() {
        let store = TaskStore::open_memory().await.unwrap();
        let (tx, mut rx) = mpsc::unbounded_channel();
        handle(
            r#"{"type":"event","seq":7,"event":"pull_request","action":"opened","repo":"o/r","payload":{"number":3}}"#,
            &store,
            &tx,
        )
        .await;

        assert_eq!(cursor(&store).await, 7);
        let signals = drain(&mut rx);
        assert!(matches!(
            signals.as_slice(),
            [Signal::Event(Event { name, repo, payload: Some(_), .. })]
                if name == "pull_request" && repo == "o/r"
        ));
    }

    #[tokio::test]
    async fn a_truncated_event_keeps_its_name_and_repo_and_drops_the_payload() {
        let store = TaskStore::open_memory().await.unwrap();
        let (tx, mut rx) = mpsc::unbounded_channel();
        handle(
            r#"{"type":"event","seq":8,"event":"issues","action":"opened","repo":"o/r","truncated":true}"#,
            &store,
            &tx,
        )
        .await;

        let signals = drain(&mut rx);
        assert!(matches!(
            signals.as_slice(),
            [Signal::Event(Event { name, repo, payload: None, .. })]
                if name == "issues" && repo == "o/r"
        ));
    }

    #[tokio::test]
    async fn a_closed_issue_releases_its_blocker_cache_entry() {
        let store = TaskStore::open_memory().await.unwrap();
        store
            .kv_set("dep_blocker_read_at:o/r#12", "1")
            .await
            .unwrap();
        store
            .kv_set("dep_blocker_read_at:o/r#13", "1")
            .await
            .unwrap();
        handle(
            r#"{"type":"event","seq":1,"event":"issues","action":"closed","repo":"o/r","payload":{"issue":{"number":12}}}"#,
            &store,
            &mpsc::unbounded_channel().0,
        )
        .await;

        assert_eq!(
            store.kv_get("dep_blocker_read_at:o/r#12").await.unwrap(),
            None
        );
        assert!(
            store
                .kv_get("dep_blocker_read_at:o/r#13")
                .await
                .unwrap()
                .is_some()
        );
    }

    #[tokio::test]
    async fn a_gap_is_passed_on_and_keeps_the_cursor() {
        let store = TaskStore::open_memory().await.unwrap();
        store.kv_set(CURSOR_KEY, "3").await.unwrap();
        let (tx, mut rx) = mpsc::unbounded_channel();
        handle(r#"{"type":"gap","oldest":50}"#, &store, &tx).await;

        assert_eq!(cursor(&store).await, 3);
        assert!(matches!(drain(&mut rx).as_slice(), [Signal::Gap]));
    }

    #[tokio::test]
    async fn pong_and_unknown_messages_change_nothing() {
        let store = TaskStore::open_memory().await.unwrap();
        let (tx, mut rx) = mpsc::unbounded_channel();
        handle("pong", &store, &tx).await;
        handle("not json", &store, &tx).await;

        assert_eq!(cursor(&store).await, 0);
        assert!(drain(&mut rx).is_empty());
    }

    #[expect(
        clippy::result_large_err,
        reason = "the handshake callback returns tungstenite's large error type"
    )]
    #[tokio::test]
    async fn a_session_says_hello_with_the_cursor_and_applies_events() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (tcp, _) = listener.accept().await.unwrap();
            let mut auth = String::new();
            let mut ws =
                tokio_tungstenite::accept_hdr_async(tcp, |req: &Request, res: Response| {
                    auth = req
                        .headers()
                        .get("authorization")
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or_default()
                        .to_string();
                    Ok(res)
                })
                .await
                .unwrap();
            let hello = ws.next().await.unwrap().unwrap().into_text().unwrap();
            let event = r#"{"type":"event","seq":9,"event":"issues","action":"opened","repo":"o/r","payload":{}}"#;
            ws.send(Message::Text(event.to_string())).await.unwrap();
            ws.close(None).await.unwrap();
            (auth, hello)
        });

        let store = TaskStore::open_memory().await.unwrap();
        store.kv_set(CURSOR_KEY, "4").await.unwrap();
        let (tx, mut rx) = mpsc::unbounded_channel();
        session(&format!("http://{addr}"), "tok", &store, &tx, PING_EVERY)
            .await
            .unwrap();

        let (auth, hello) = server.await.unwrap();
        assert_eq!(auth, "Bearer tok");
        let hello: serde_json::Value = serde_json::from_str(&hello).unwrap();
        assert_eq!(
            hello,
            serde_json::json!({ "v": 1, "type": "hello", "after": 4 })
        );
        assert_eq!(cursor(&store).await, 9);
        assert!(matches!(
            drain(&mut rx).as_slice(),
            [Signal::Connected, Signal::Event(_)]
        ));
    }

    #[tokio::test]
    async fn a_silent_server_ends_the_session_with_an_error() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (tcp, _) = listener.accept().await.unwrap();
            let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
            while ws.next().await.is_some() {}
        });

        let store = TaskStore::open_memory().await.unwrap();
        let err = time::timeout(
            Duration::from_secs(5),
            session(
                &format!("http://{addr}"),
                "tok",
                &store,
                &mpsc::unbounded_channel().0,
                Duration::from_millis(50),
            ),
        )
        .await
        .expect("session should end on its own")
        .unwrap_err();

        assert!(err.to_string().contains("no pong"));
        server.abort();
    }

    #[test]
    fn a_socket_closed_at_once_keeps_the_backoff_growing() {
        let quick = Duration::from_secs(1);
        let mut backoff = 1;
        let mut waits = Vec::new();

        for _ in 0..12 {
            let wait = retry_after(backoff, quick);
            waits.push(wait);
            backoff = (wait * 2).min(MAX_BACKOFF_SECS);
        }

        assert_eq!(waits[..9], [1, 2, 4, 8, 16, 32, 64, 128, 256]);
        assert_eq!(waits[9..], [300, 300, 300]);
        assert_eq!(retry_after(300, STABLE_SESSION), 1);
    }
}