|
| 1 | +//! `buzz listen` — persistent WebSocket stream of channel events (#2663 Option B). |
| 2 | +//! |
| 3 | +//! Prints one normalized JSON object per inbound EVENT matching the subscription |
| 4 | +//! filters (newline-delimited JSON on stdout). Uses the same NIP-42 / NIP-OA |
| 5 | +//! path as `publish_ephemeral_event`. |
| 6 | +
|
| 7 | +use std::io::Write; |
| 8 | +use std::sync::atomic::{AtomicBool, Ordering}; |
| 9 | +use std::sync::Arc; |
| 10 | +use std::time::Duration; |
| 11 | + |
| 12 | +use serde_json::json; |
| 13 | +use uuid::Uuid; |
| 14 | + |
| 15 | +use crate::client::{normalize_events, BuzzClient}; |
| 16 | +use crate::error::CliError; |
| 17 | +use crate::validate::validate_uuid; |
| 18 | + |
| 19 | +/// Default kinds for channel traffic (matches `messages get` defaults). |
| 20 | +const DEFAULT_KINDS: &[u32] = &[9, 40002, 40008, 45001, 45003]; |
| 21 | + |
| 22 | +fn parse_kinds(raw: Option<&str>) -> Result<Vec<u32>, CliError> { |
| 23 | + match raw { |
| 24 | + None => Ok(DEFAULT_KINDS.to_vec()), |
| 25 | + Some(s) if s.trim().is_empty() => Ok(DEFAULT_KINDS.to_vec()), |
| 26 | + Some(s) => { |
| 27 | + let mut out = Vec::new(); |
| 28 | + for part in s.split(',') { |
| 29 | + let part = part.trim(); |
| 30 | + if part.is_empty() { |
| 31 | + continue; |
| 32 | + } |
| 33 | + let k: u32 = part |
| 34 | + .parse() |
| 35 | + .map_err(|_| CliError::Usage(format!("invalid kind in --kinds: {part}")))?; |
| 36 | + out.push(k); |
| 37 | + } |
| 38 | + if out.is_empty() { |
| 39 | + return Err(CliError::Usage("--kinds must list at least one kind".into())); |
| 40 | + } |
| 41 | + Ok(out) |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/// Build subscription filter list for REQ. |
| 47 | +pub(crate) fn build_listen_filters( |
| 48 | + channels: &[String], |
| 49 | + mentions_of_me: bool, |
| 50 | + my_pubkey_hex: &str, |
| 51 | + kinds: &[u32], |
| 52 | +) -> Result<Vec<serde_json::Value>, CliError> { |
| 53 | + if channels.is_empty() && !mentions_of_me { |
| 54 | + return Err(CliError::Usage( |
| 55 | + "buzz listen requires --channel <UUID> and/or --mentions-of-me".into(), |
| 56 | + )); |
| 57 | + } |
| 58 | + for ch in channels { |
| 59 | + validate_uuid(ch)?; |
| 60 | + } |
| 61 | + |
| 62 | + let mut filters = Vec::new(); |
| 63 | + if !channels.is_empty() { |
| 64 | + filters.push(json!({ |
| 65 | + "kinds": kinds, |
| 66 | + "#h": channels, |
| 67 | + })); |
| 68 | + } |
| 69 | + if mentions_of_me { |
| 70 | + let mut f = json!({ |
| 71 | + "kinds": kinds, |
| 72 | + "#p": [my_pubkey_hex], |
| 73 | + }); |
| 74 | + if !channels.is_empty() { |
| 75 | + f["#h"] = json!(channels); |
| 76 | + } |
| 77 | + filters.push(f); |
| 78 | + } |
| 79 | + Ok(filters) |
| 80 | +} |
| 81 | + |
| 82 | +/// Optional POST of each event JSON body to `url` (Option A, best-effort). |
| 83 | +async fn post_webhook(client: &reqwest::Client, url: &str, body: &str) { |
| 84 | + if let Err(e) = client |
| 85 | + .post(url) |
| 86 | + .header("content-type", "application/json") |
| 87 | + .body(body.to_string()) |
| 88 | + .send() |
| 89 | + .await |
| 90 | + { |
| 91 | + eprintln!( |
| 92 | + "{}", |
| 93 | + json!({"error":"webhook","message": format!("{e}")}) |
| 94 | + ); |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +fn http_to_ws(http_url: &str) -> String { |
| 99 | + http_url |
| 100 | + .replace("https://", "wss://") |
| 101 | + .replace("http://", "ws://") |
| 102 | +} |
| 103 | + |
| 104 | +/// Run the listen loop until Ctrl-C or fatal error. |
| 105 | +pub async fn cmd_listen( |
| 106 | + client: &BuzzClient, |
| 107 | + channels: Vec<String>, |
| 108 | + mentions_of_me: bool, |
| 109 | + kinds_raw: Option<String>, |
| 110 | + webhook: Option<String>, |
| 111 | + reconnect: bool, |
| 112 | +) -> Result<(), CliError> { |
| 113 | + let kinds = parse_kinds(kinds_raw.as_deref())?; |
| 114 | + let my_pk = client.keys().public_key().to_hex(); |
| 115 | + let filters = build_listen_filters(&channels, mentions_of_me, &my_pk, &kinds)?; |
| 116 | + let ws_url = http_to_ws(client.relay_url()); |
| 117 | + let http = reqwest::Client::new(); |
| 118 | + let running = Arc::new(AtomicBool::new(true)); |
| 119 | + |
| 120 | + // Background Ctrl-C watcher (unix + windows via tokio::signal). |
| 121 | + { |
| 122 | + let r = running.clone(); |
| 123 | + tokio::spawn(async move { |
| 124 | + let _ = tokio::signal::ctrl_c().await; |
| 125 | + r.store(false, Ordering::SeqCst); |
| 126 | + }); |
| 127 | + } |
| 128 | + |
| 129 | + let mut backoff_ms: u64 = 500; |
| 130 | + const MAX_BACKOFF_MS: u64 = 30_000; |
| 131 | + |
| 132 | + while running.load(Ordering::SeqCst) { |
| 133 | + match listen_session( |
| 134 | + client, |
| 135 | + &ws_url, |
| 136 | + &filters, |
| 137 | + webhook.as_deref(), |
| 138 | + &http, |
| 139 | + running.clone(), |
| 140 | + ) |
| 141 | + .await |
| 142 | + { |
| 143 | + Ok(()) => { |
| 144 | + if !running.load(Ordering::SeqCst) { |
| 145 | + break; |
| 146 | + } |
| 147 | + if !reconnect { |
| 148 | + break; |
| 149 | + } |
| 150 | + } |
| 151 | + Err(e) => { |
| 152 | + if !running.load(Ordering::SeqCst) { |
| 153 | + break; |
| 154 | + } |
| 155 | + if !reconnect { |
| 156 | + return Err(e); |
| 157 | + } |
| 158 | + eprintln!( |
| 159 | + "{}", |
| 160 | + json!({ |
| 161 | + "error": "listen_reconnect", |
| 162 | + "message": e.to_string(), |
| 163 | + "backoff_ms": backoff_ms, |
| 164 | + }) |
| 165 | + ); |
| 166 | + } |
| 167 | + } |
| 168 | + if !reconnect || !running.load(Ordering::SeqCst) { |
| 169 | + break; |
| 170 | + } |
| 171 | + tokio::time::sleep(Duration::from_millis(backoff_ms)).await; |
| 172 | + backoff_ms = (backoff_ms.saturating_mul(2)).min(MAX_BACKOFF_MS); |
| 173 | + } |
| 174 | + Ok(()) |
| 175 | +} |
| 176 | + |
| 177 | +async fn listen_session( |
| 178 | + client: &BuzzClient, |
| 179 | + ws_url: &str, |
| 180 | + filters: &[serde_json::Value], |
| 181 | + webhook: Option<&str>, |
| 182 | + http: &reqwest::Client, |
| 183 | + running: Arc<AtomicBool>, |
| 184 | +) -> Result<(), CliError> { |
| 185 | + use buzz_ws_client::{NostrWsConnection, RelayMessage}; |
| 186 | + |
| 187 | + let mut conn = NostrWsConnection::connect_authenticated( |
| 188 | + ws_url, |
| 189 | + client.keys(), |
| 190 | + client.auth_tag(), |
| 191 | + ) |
| 192 | + .await |
| 193 | + .map_err(|e| CliError::Other(format!("websocket: {e}")))?; |
| 194 | + |
| 195 | + let sub_id = format!("buzz-listen-{}", &Uuid::new_v4().to_string()[..8]); |
| 196 | + let mut req = vec![json!("REQ"), json!(sub_id)]; |
| 197 | + for f in filters { |
| 198 | + req.push(f.clone()); |
| 199 | + } |
| 200 | + conn.send_raw(&json!(req)) |
| 201 | + .await |
| 202 | + .map_err(|e| CliError::Other(format!("websocket send: {e}")))?; |
| 203 | + |
| 204 | + while running.load(Ordering::SeqCst) { |
| 205 | + // Short poll so Ctrl-C can exit promptly. |
| 206 | + let msg = match conn.next_event(Duration::from_millis(500)).await { |
| 207 | + Ok(m) => m, |
| 208 | + Err(buzz_ws_client::WsClientError::Timeout) => continue, |
| 209 | + Err(e) => return Err(CliError::Other(format!("websocket: {e}"))), |
| 210 | + }; |
| 211 | + |
| 212 | + match msg { |
| 213 | + RelayMessage::Event { event, .. } => { |
| 214 | + let raw = serde_json::to_value(event.as_ref()) |
| 215 | + .map_err(|e| CliError::Other(format!("event serialize: {e}")))?; |
| 216 | + let line = normalize_events(std::slice::from_ref(&raw)); |
| 217 | + // normalize_events returns a JSON array; unwrap first element for NDJSON stream. |
| 218 | + let arr: Vec<serde_json::Value> = |
| 219 | + serde_json::from_str(&line).unwrap_or_default(); |
| 220 | + let body = arr.first().cloned().unwrap_or(raw); |
| 221 | + let text = serde_json::to_string(&body).unwrap_or_default(); |
| 222 | + println!("{text}"); |
| 223 | + let _ = std::io::stdout().flush(); |
| 224 | + if let Some(url) = webhook { |
| 225 | + post_webhook(http, url, &text).await; |
| 226 | + } |
| 227 | + } |
| 228 | + RelayMessage::Closed { message, .. } => { |
| 229 | + return Err(CliError::Other(format!("subscription closed: {message}"))); |
| 230 | + } |
| 231 | + RelayMessage::Notice { message } => { |
| 232 | + eprintln!("{}", json!({"notice": message})); |
| 233 | + } |
| 234 | + RelayMessage::Eose { .. } |
| 235 | + | RelayMessage::Ok(_) |
| 236 | + | RelayMessage::Auth { .. } |
| 237 | + | RelayMessage::Count { .. } => {} |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + let _ = conn.send_raw(&json!(["CLOSE", sub_id])).await; |
| 242 | + let _ = conn.disconnect().await; |
| 243 | + Ok(()) |
| 244 | +} |
| 245 | + |
| 246 | +#[cfg(test)] |
| 247 | +mod tests { |
| 248 | + use super::*; |
| 249 | + |
| 250 | + #[test] |
| 251 | + fn requires_channel_or_mentions() { |
| 252 | + let err = build_listen_filters(&[], false, &"a".repeat(64), DEFAULT_KINDS).unwrap_err(); |
| 253 | + assert!(matches!(err, CliError::Usage(_))); |
| 254 | + } |
| 255 | + |
| 256 | + #[test] |
| 257 | + fn channel_filter_uses_h_tag() { |
| 258 | + let ch = "11111111-1111-1111-1111-111111111111".to_string(); |
| 259 | + let f = build_listen_filters(&[ch.clone()], false, &"a".repeat(64), DEFAULT_KINDS).unwrap(); |
| 260 | + assert_eq!(f.len(), 1); |
| 261 | + assert_eq!(f[0]["#h"][0], ch); |
| 262 | + } |
| 263 | + |
| 264 | + #[test] |
| 265 | + fn mentions_filter_uses_p_tag() { |
| 266 | + let pk = "b".repeat(64); |
| 267 | + let f = build_listen_filters(&[], true, &pk, DEFAULT_KINDS).unwrap(); |
| 268 | + assert_eq!(f.len(), 1); |
| 269 | + assert_eq!(f[0]["#p"][0], pk); |
| 270 | + } |
| 271 | + |
| 272 | + #[test] |
| 273 | + fn both_channel_and_mentions_two_filters() { |
| 274 | + let ch = "11111111-1111-1111-1111-111111111111".to_string(); |
| 275 | + let pk = "c".repeat(64); |
| 276 | + let f = build_listen_filters(&[ch], true, &pk, DEFAULT_KINDS).unwrap(); |
| 277 | + assert_eq!(f.len(), 2); |
| 278 | + } |
| 279 | +} |
0 commit comments