ghwh 0.2.0

GitHub webhook events (PRs, issues, comments, reviews, CI, pushes) as JSON lines, for agents and scripts
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
//! ghwh: GitHub webhook events from your ghwh hub, one JSON object per line.
//!
//! The hub (a Cloudflare Worker, see the repo README) stores each event with an increasing `seq` and
//! serves them over a WebSocket at `<hub>/github/stream`:
//!   → {"auth": KEY, "since": SEQ, "all": true}      (no "auth": public repos only, if the hub allows it)
//!   ← {"type":"event","seq":N,"event":{…}}           replayed after SEQ, then live
//!   ← {"type":"hello","last":N,"first":M,"more":bool}  after the replay; more = replay was capped,
//!                                                    first = oldest seq the hub still keeps
//! `--state FILE` keeps the last seq handled, so an agent calling `ghwh wait --state …` in a loop gets
//! every event exactly once.

use clap::{Args, Parser, Subcommand};
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::time::{sleep, timeout_at, Instant};
use tokio_tungstenite::tungstenite::Message;

/// `since` that asks the hub for no replay: "start from now".
const NOW: u64 = 9_007_199_254_740_991;
const KINDS: [&str; 7] = ["pr", "issue", "comment", "review", "check", "push", "ping"];

#[derive(Parser)]
#[command(version, about = "GitHub webhook events from your ghwh hub, one JSON object per line.",
  after_help = "Hub and key: $GHWH_URL / $GHWH_KEY, else ~/.config/ghwh/config.json (written by `ghwh setup`).\n\
Without a key you only see public repos' events, if the hub serves them.\n\
Exit codes: 0 ok, 1 error, 2 unauthorized, 124 `wait` timed out.\n\n\
Agent loop:  ghwh wait --state ~/.ghwh/my-agent --repo owner/name -t 600")]
struct Cli {
    /// Hub URL, e.g. https://hooks.example.com (overrides $GHWH_URL and the config file).
    #[arg(long, global = true)]
    url: Option<String>,
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Print matching events as they arrive, forever (reconnects on its own).
    Tail(Run),
    /// Block until COUNT matching events arrive, print them, exit. For agents without a streaming tool.
    Wait {
        #[command(flatten)]
        run: Run,
        /// How many events to wait for.
        #[arg(long, short = 'n', default_value_t = 1)]
        count: usize,
        /// Give up after this many seconds (exit 124).
        #[arg(long, short = 't', default_value_t = 300)]
        timeout: u64,
    },
    /// Print the stored events (oldest first) and exit.
    List {
        #[command(flatten)]
        filter: Filter,
        /// Only events after this seq.
        #[arg(long, default_value_t = 0)]
        since: u64,
        /// At most this many (the newest).
        #[arg(long, default_value_t = 50)]
        limit: usize,
    },
    /// Show which hub and key are in use, and whether the stream answers.
    Status,
    /// Deploy a hub and hook repos, interactively (runs the npm package: bunx ghwh setup).
    Setup {
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
}

#[derive(Args, Clone)]
struct Run {
    #[command(flatten)]
    filter: Filter,
    /// Start after this seq (0 = everything the hub still keeps). Default: from now, or from --state.
    #[arg(long)]
    since: Option<u64>,
    /// File holding the last handled seq; read at start, updated after every printed event.
    #[arg(long)]
    state: Option<PathBuf>,
}

#[derive(Args, Clone, Default)]
struct Filter {
    /// owner/name, or owner/* (repeatable).
    #[arg(long, short = 'r')]
    repo: Vec<String>,
    /// pr, issue, comment, review, check, push, ping (repeatable; default all but ping).
    #[arg(long, short = 'k', value_parser = clap::builder::PossibleValuesParser::new(KINDS))]
    kind: Vec<String>,
    /// e.g. opened, closed, synchronize, created, submitted, completed, pushed (repeatable).
    #[arg(long, short = 'a')]
    action: Vec<String>,
    /// One readable line per event instead of JSON.
    #[arg(long)]
    text: bool,
}

impl Filter {
    fn matches(&self, ev: &Value) -> bool {
        let s = |k: &str| ev.get(k).and_then(Value::as_str).unwrap_or("");
        let kind = s("kind");
        let kind_ok = if self.kind.is_empty() { kind != "ping" } else { self.kind.iter().any(|k| k == kind) };
        let repo = s("repo").to_ascii_lowercase();
        let repo_ok = self.repo.is_empty()
            || self.repo.iter().any(|r| {
                let r = r.to_ascii_lowercase();
                match r.strip_suffix("/*") { Some(owner) => repo.starts_with(&format!("{owner}/")), None => r == repo }
            });
        let action_ok = self.action.is_empty() || self.action.iter().any(|a| a == s("action"));
        kind_ok && repo_ok && action_ok
    }

    fn render(&self, seq: u64, ev: &Value) -> String {
        if !self.text {
            let mut o = serde_json::Map::new();
            o.insert("seq".into(), seq.into());
            if let Some(m) = ev.as_object() { o.extend(m.clone()); }
            return Value::Object(o).to_string();
        }
        let s = |k: &str| ev.get(k).and_then(Value::as_str).unwrap_or("");
        let n = ev.get("number").and_then(Value::as_u64).map(|n| format!("#{n}")).unwrap_or_default();
        let short = |v: &str| v.chars().take(7).collect::<String>();
        let one_line = |v: &str, max: usize| {
            let l = v.lines().next().unwrap_or("");
            if l.chars().count() > max { format!("{}…", l.chars().take(max).collect::<String>()) } else { l.to_string() }
        };
        let (repo, author, url) = (s("repo"), s("author"), s("url"));
        let what = match s("kind") {
            "pr" if s("action") == "closed" && ev.get("merged").and_then(Value::as_bool) == Some(true) => {
                format!("{repo}{n} pr merged {:?} by {author}", s("title"))
            }
            "pr" | "issue" => {
                let label = if s("label").is_empty() { String::new() } else { format!(" [{}]", s("label")) };
                format!("{repo}{n} {} {}{label} {:?} by {author}", s("kind"), s("action"), s("title"))
            }
            "comment" => format!("{repo}{n} comment by {author}: {:?}", one_line(s("body"), 80)),
            "review" => format!("{repo}{n} review {} by {author}", s("state")),
            "check" => {
                let prs: Vec<String> = ev.get("prs").and_then(Value::as_array).map(|a| a.iter().map(|p| format!("#{p}")).collect()).unwrap_or_default();
                format!("{repo} check {:?} {} on {}@{}{}", s("name"), s("conclusion"), s("branch"), short(s("sha")),
                    if prs.is_empty() { String::new() } else { format!(" ({})", prs.join(" ")) })
            }
            "push" => format!("{repo} push {}@{} {:?} by {author}", s("branch"), short(s("sha")), s("message")),
            "ping" => format!("{repo} ping (hook {})", ev.get("hookId").unwrap_or(&Value::Null)),
            k => format!("{repo}{n} {k} {}", s("action")),
        };
        if url.is_empty() { format!("[{seq}] {what}") } else { format!("[{seq}] {what} {url}") }
    }
}

#[derive(Debug)]
enum Fail { Unauthorized, Other(String) }

/// Hub stream URL and key: flag / env first, then the config file `ghwh setup` writes.
struct Hub { stream: String, key: Option<String> }

fn config_path() -> Option<PathBuf> {
    if let Ok(p) = std::env::var("GHWH_CONFIG") { return Some(PathBuf::from(p)); }
    let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).filter(|p| p.is_absolute()).or_else(|| {
        std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(|h| PathBuf::from(h).join(".config"))
    })?;
    Some(base.join("ghwh").join("config.json"))
}

/// https://host, host, wss://host/github/stream … → wss://host/github/stream
fn stream_url(url: &str) -> String {
    let url = url.trim().trim_end_matches('/');
    let (scheme, rest) = match url.split_once("://") {
        Some(("http", r)) | Some(("ws", r)) => ("ws", r),
        Some((_, r)) => ("wss", r),
        None => if url.starts_with("localhost") || url.starts_with("127.0.0.1") { ("ws", url) } else { ("wss", url) },
    };
    let rest = rest.trim_end_matches("/github/stream").trim_end_matches("/github").trim_end_matches("/mcp");
    format!("{scheme}://{rest}/github/stream")
}

fn hub(flag: Option<String>) -> Result<Hub, String> {
    let env = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
    let file: Option<Value> = config_path().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok());
    let from_file = |k: &str| file.as_ref().and_then(|f| f.get(k)).and_then(Value::as_str).map(str::to_string).filter(|v| !v.is_empty());
    let url = flag.or_else(|| env("GHWH_URL")).or_else(|| from_file("url")).ok_or_else(|| {
        format!("no hub configured: run `bunx ghwh setup`, or set GHWH_URL (and GHWH_KEY){}",
            config_path().map(|p| format!(" — looked in {}", p.display())).unwrap_or_default())
    })?;
    Ok(Hub { stream: stream_url(&url), key: env("GHWH_KEY").or_else(|| from_file("key")) })
}

fn read_state(p: &Path) -> Option<u64> { std::fs::read_to_string(p).ok()?.trim().parse().ok() }

fn write_state(p: &Path, seq: u64) -> std::io::Result<()> {
    if let Some(dir) = p.parent() { if !dir.as_os_str().is_empty() { std::fs::create_dir_all(dir)?; } }
    let tmp = p.with_extension("tmp");
    std::fs::write(&tmp, format!("{seq}\n"))?;
    std::fs::rename(tmp, p)
}

/// What a connection reports back to the caller.
enum Frame { Event(u64, Value), Hello { last: u64, first: u64, more: bool } }

/// One connection: authenticate, then hand every frame to `on` until it returns false, the socket
/// ends, or `deadline` passes. Returns Ok(true) if `on` asked to stop, Ok(false) at the deadline.
async fn session(hub: &Hub, since: u64, deadline: Option<Instant>, on: &mut dyn FnMut(Frame) -> bool) -> Result<bool, Fail> {
    let connect = tokio_tungstenite::connect_async(hub.stream.as_str());
    let (mut ws, _) = match deadline {
        Some(d) => match timeout_at(d, connect).await { Ok(r) => r, Err(_) => return Ok(false) },
        None => connect.await,
    }
    .map_err(|e| Fail::Other(format!("connect {}: {e}", hub.stream)))?;
    let mut hello = json!({ "since": since, "all": true });
    if let Some(k) = &hub.key { hello["auth"] = k.clone().into(); }
    ws.send(Message::Text(hello.to_string().into())).await.map_err(|e| Fail::Other(format!("send: {e}")))?;
    let mut ping = tokio::time::interval(Duration::from_secs(30));
    ping.tick().await;
    loop {
        let next = async {
            tokio::select! {
                m = ws.next() => Some(m),
                _ = ping.tick() => None,
            }
        };
        let got = match deadline {
            Some(d) => match timeout_at(d, next).await { Ok(g) => g, Err(_) => return Ok(false) },
            None => next.await,
        };
        let msg = match got {
            None => { ws.send(Message::Text("ping".into())).await.map_err(|e| Fail::Other(format!("ping: {e}")))?; continue; }
            Some(None) => return Err(Fail::Other("connection closed".into())),
            Some(Some(Err(e))) => return Err(Fail::Other(format!("read: {e}"))),
            Some(Some(Ok(m))) => m,
        };
        match msg {
            Message::Text(t) => {
                let Ok(v) = serde_json::from_str::<Value>(t.as_str()) else { continue }; // "pong"
                let frame = match v.get("type").and_then(Value::as_str) {
                    Some("event") => match (v.get("seq").and_then(Value::as_u64), v.get("event")) {
                        (Some(s), Some(e)) => Frame::Event(s, e.clone()),
                        _ => continue,
                    },
                    Some("hello") => Frame::Hello {
                        last: v.get("last").and_then(Value::as_u64).unwrap_or(0),
                        first: v.get("first").and_then(Value::as_u64).unwrap_or(0),
                        more: v.get("more").and_then(Value::as_bool).unwrap_or(false),
                    },
                    _ => continue,
                };
                if !on(frame) { let _ = ws.close(None).await; return Ok(true); }
            }
            Message::Close(c) => {
                if c.as_ref().map(|c| u16::from(c.code)) == Some(4001) { return Err(Fail::Unauthorized); }
                return Err(Fail::Other(format!("closed by hub: {}", c.map(|c| c.reason.to_string()).unwrap_or_default())));
            }
            _ => {}
        }
    }
}

/// Keep a stream going across reconnects. `on` gets (seq, event) for new matching events and returns
/// false to stop. Returns Ok(true) when `on` stopped it, Ok(false) at the deadline.
async fn follow(hub: &Hub, run: &Run, deadline: Option<Instant>, mut on: impl FnMut(u64, &Value) -> bool) -> Result<bool, Fail> {
    let mut since = run.since.or_else(|| run.state.as_deref().and_then(read_state)).unwrap_or(NOW);
    let mut backoff = 1u64;
    let mut warned_gap = false;
    loop {
        let (mut stop, mut again) = (false, false);
        let start = since; // where this connection's replay began
        let res = session(hub, since, deadline, &mut |f| {
            match f {
                Frame::Hello { last, first, more } => {
                    backoff = 1;
                    // Hello comes after the replay, so compare with where the replay began. (A `wait`
                    // that gets its events during the replay stops before hello and can't warn.)
                    if start != NOW && start > 0 && first > start + 1 && !warned_gap {
                        eprintln!("ghwh: events {}..{} were dropped from the hub before we read them (it keeps the last 1000)", start + 1, first - 1);
                        warned_gap = true;
                    }
                    if since == NOW { since = last; }
                    else if since > last { eprintln!("ghwh: the hub's log restarted (at {last}, we were at {since}); reading it from the start"); since = 0; again = true; return false; }
                    else if more { again = true; return false; } // replay was capped: fetch the rest
                    else { since = since.max(last); } // seen everything visible up to `last`
                }
                Frame::Event(seq, ev) => {
                    if since != NOW && seq <= since { return true; }
                    since = seq;
                    if run.filter.matches(&ev) && !on(seq, &ev) { stop = true; return false; }
                }
            }
            true
        })
        .await;
        match res {
            Ok(true) if again => continue,
            Ok(true) => return Ok(stop),
            Ok(false) => return Ok(false),
            Err(Fail::Unauthorized) => return Err(Fail::Unauthorized),
            Err(Fail::Other(e)) => {
                if deadline.is_some_and(|d| Instant::now() >= d) { return Ok(false); }
                eprintln!("ghwh: {e}; reconnecting in {backoff}s");
                sleep(Duration::from_secs(backoff)).await;
                backoff = (backoff * 2).min(60);
            }
        }
    }
}

fn emit(line: &str) -> bool {
    let mut out = std::io::stdout().lock();
    writeln!(out, "{line}").and_then(|_| out.flush()).is_ok() // false once the reader is gone
}

#[tokio::main(flavor = "current_thread")]
async fn main() {
    let cli = Cli::parse();
    let code = match real_main(cli).await {
        Ok(c) => c,
        Err(Fail::Unauthorized) => { eprintln!("ghwh: unauthorized (check GHWH_KEY or the key in the config file; without a key the hub must serve public events)"); 2 }
        Err(Fail::Other(e)) => { eprintln!("ghwh: {e}"); 1 }
    };
    std::process::exit(code);
}

/// `ghwh setup` lives in the npm package (it drives wrangler and gh); run it with bunx or npx.
fn setup(args: &[String]) -> i32 {
    let pkg = format!("ghwh@{}", env!("CARGO_PKG_VERSION"));
    for (cmd, pre) in [("bunx", vec![pkg.as_str()]), ("npx", vec!["-y", pkg.as_str()])] {
        match std::process::Command::new(cmd).args(&pre).arg("setup").args(args).status() {
            Ok(s) => return s.code().unwrap_or(1),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => { eprintln!("ghwh: {cmd}: {e}"); return 1; }
        }
    }
    eprintln!("ghwh: setup needs Bun or Node.js (it runs `bunx {pkg} setup`). Install one, or follow the manual guide: https://github.com/snomiao/github-webhooks/blob/main/docs/manual-setup.md");
    1
}

async fn real_main(cli: Cli) -> Result<i32, Fail> {
    if let Cmd::Setup { args } = &cli.cmd { return Ok(setup(args)); }
    let hub = hub(cli.url).map_err(Fail::Other)?;
    let save = |state: &Option<PathBuf>, seq: u64| {
        if let Some(p) = state { if let Err(e) = write_state(p, seq) { eprintln!("ghwh: state {}: {e}", p.display()); } }
    };
    match cli.cmd {
        Cmd::Setup { .. } => unreachable!(),
        Cmd::Tail(run) => {
            let r = follow(&hub, &run, None, |seq, ev| {
                let ok = emit(&run.filter.render(seq, ev));
                if ok { save(&run.state, seq); }
                ok
            });
            tokio::select! {
                r = r => r.map(|_| 0),
                _ = tokio::signal::ctrl_c() => Ok(130),
            }
        }
        Cmd::Wait { run, count, timeout } => {
            let deadline = Instant::now() + Duration::from_secs(timeout);
            let mut n = 0;
            follow(&hub, &run, Some(deadline), |seq, ev| {
                if !emit(&run.filter.render(seq, ev)) { return false; }
                save(&run.state, seq);
                n += 1;
                n < count.max(1)
            })
            .await?;
            Ok(if n > 0 { 0 } else { 124 })
        }
        Cmd::List { filter, since, limit } => {
            let mut rows: Vec<(u64, Value)> = Vec::new();
            let deadline = Some(Instant::now() + Duration::from_secs(30));
            let mut since = since;
            loop {
                let (mut done, mut reset) = (false, false);
                let ok = session(&hub, since, deadline, &mut |f| match f {
                    Frame::Event(seq, ev) => { since = since.max(seq); if filter.matches(&ev) { rows.push((seq, ev)); } true }
                    Frame::Hello { last, more, .. } => { reset = since > last && rows.is_empty(); done = !more; false }
                })
                .await?;
                if !ok { return Err(Fail::Other("timed out".into())); }
                if reset { since = 0; continue; }
                if done { break; }
            }
            let skip = rows.len().saturating_sub(limit);
            for (seq, ev) in &rows[skip..] { if !emit(&filter.render(*seq, ev)) { break; } }
            Ok(0)
        }
        Cmd::Status => {
            println!("hub:    {}", hub.stream);
            println!("key:    {}", if hub.key.is_some() { "set" } else { "none (public repos only)" });
            if let Some(p) = config_path() { println!("config: {}{}", p.display(), if p.exists() { "" } else { " (missing)" }); }
            let mut last = None;
            let deadline = Some(Instant::now() + Duration::from_secs(15));
            match session(&hub, NOW, deadline, &mut |f| { if let Frame::Hello { last: l, .. } = f { last = Some(l); } false }).await {
                Ok(true) => { println!("stream: ok, last seq {}", last.unwrap_or(0)); Ok(0) }
                Ok(false) => Err(Fail::Other("stream: no answer within 15s".into())),
                Err(e) => Err(e),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stream_urls() {
        assert_eq!(stream_url("https://hooks.example.com"), "wss://hooks.example.com/github/stream");
        assert_eq!(stream_url("hooks.example.com/"), "wss://hooks.example.com/github/stream");
        assert_eq!(stream_url("wss://hooks.example.com/github/stream"), "wss://hooks.example.com/github/stream");
        assert_eq!(stream_url("https://hooks.example.com/mcp"), "wss://hooks.example.com/github/stream");
        assert_eq!(stream_url("http://localhost:8787"), "ws://localhost:8787/github/stream");
        assert_eq!(stream_url("localhost:8787"), "ws://localhost:8787/github/stream");
    }

    #[test]
    fn filters() {
        let ev = json!({"kind": "pr", "action": "opened", "repo": "Acme/App"});
        let f = |repo: &[&str], kind: &[&str]| Filter { repo: repo.iter().map(|s| s.to_string()).collect(), kind: kind.iter().map(|s| s.to_string()).collect(), ..Default::default() };
        assert!(f(&[], &[]).matches(&ev));
        assert!(f(&["acme/*"], &[]).matches(&ev));
        assert!(f(&["acme/app"], &["pr"]).matches(&ev));
        assert!(!f(&["acm/*"], &[]).matches(&ev));
        assert!(!f(&[], &["issue"]).matches(&ev));
        assert!(!f(&[], &[]).matches(&json!({"kind": "ping", "repo": "acme/app"})));
    }

    #[test]
    fn json_lines_put_seq_first() {
        let line = Filter::default().render(5, &json!({"kind": "push", "repo": "a/b"}));
        assert!(line.starts_with(r#"{"seq":5,"#), "{line}");
    }
}