Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-coord/src/board/cli.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-coord / src / board / cli.rs` 713 lines ยท 25634 bytes Raw Blame History 1 //! `synapse-coord board ...`: the command-line face of the board. 2 //! 3 //! Output is one compact JSON object per line on stdout: events first, then one summary 4 //! object carrying `"ok"` and the [`UNTRUSTED_NOTICE`](super::UNTRUSTED_NOTICE). `--human` 5 //! prints readable lines instead. Exit codes: 0 ok, 1 usage or I/O error, 2 a named 6 //! refusal (the summary's `"error"` is [`BoardError::name`]). 7 //! 8 //! ```text 9 //! synapse-coord board [--board-root DIR] [--expect-board-id HEX] [--session S] [--human] ... 10 //! init create the board (BOARD_ID) if absent 11 //! id print the mission id 12 //! register [--ttl SECS] bind a tag to this session 13 //! unregister release this session's tag 14 //! whoami print this session's tag and session id 15 //! agents every tag binding (operator view) 16 //! post --thread T --topic P [--kind K] [--to TAG]... [--parent ID] [--idem KEY] 17 //! [--ref REPO KIND VALUE]... (--text S | --text-file F) 18 //! [--pointer-whisper STORE TOP DIR] 19 //! read [--from acked|delivered] [--after ID] [--limit N] [--peek] [--mine] [--all] 20 //! inbox [--limit N] unread events addressed to a tag (operator view) 21 //! subscribe (--topic T | --thread T) follow a topic or thread 22 //! unsubscribe (--topic T | --thread T) 23 //! subscriptions 24 //! watch [--timeout-ms N] [--limit N] [--from delivered|acked] [--follow N] [--stamp] 25 //! ack | ack --accept-gap 26 //! compact --keep-since ID [--expire-cursors] 27 //! check index/journal agreement (read-only) 28 //! recover reconcile a torn tail now (normally done by post) 29 //! ``` 30 //! 31 //! Environment fallbacks: `SYNAPSE_BOARD_ROOT`, `SYNAPSE_BOARD_ID`, and for the session 32 //! `SYNAPSE_BOARD_SESSION` then `CRUMB_SESSION`. 33 34 use super::frame::{compact, num_u64}; 35 use super::{ 36 Board, BoardError, BoardId, Delivered, Kind, Post, ReadBatch, Ref, RefKind, Resume, Sub, Wake, 37 MAX_TEXT_BYTES, UNTRUSTED_NOTICE, 38 }; 39 use crate::json::J; 40 use crate::{CoordStore, Holder, NoOracle, Workspace}; 41 use std::io::Write; 42 use std::path::PathBuf; 43 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 44 45 /// Default `watch` timeout. 46 const DEFAULT_WATCH_MS: u64 = 30_000; 47 const DEFAULT_LIMIT: usize = 256; 48 49 enum Fail { 50 Usage(String), 51 Board(BoardError), 52 } 53 54 impl From for Fail { 55 fn from(e: BoardError) -> Fail { 56 Fail::Board(e) 57 } 58 } 59 60 fn usage(m: impl Into) -> Fail { 61 Fail::Usage(m.into()) 62 } 63 64 struct Ctx { 65 root: Option, 66 expect: Option, 67 session: Option, 68 human: bool, 69 out: std::io::StdoutLock<'static>, 70 } 71 72 impl Ctx { 73 fn board(&self) -> Result { 74 let root = self 75 .root 76 .clone() 77 .ok_or_else(|| usage("--board-root (or SYNAPSE_BOARD_ROOT) is required"))?; 78 Ok(match self.expect { 79 Some(id) => Board::open_expecting(root, id)?, 80 None => Board::open(root)?, 81 }) 82 } 83 84 fn session(&self) -> Result<&str, Fail> { 85 self.session.as_deref().ok_or_else(|| { 86 usage("--session (or SYNAPSE_BOARD_SESSION / CRUMB_SESSION) is required") 87 }) 88 } 89 90 fn line(&mut self, j: &J) { 91 let mut b = compact(j); 92 b.push(b'\n'); 93 let _ = self.out.write_all(&b); 94 } 95 96 /// A readable line, printed only under `--human`. 97 fn human(&mut self, s: &str) { 98 if self.human { 99 let _ = writeln!(self.out, "{s}"); 100 } 101 } 102 103 fn summary(&mut self, cmd: &str, mut o: J) { 104 if self.human { 105 let _ = self.out.flush(); 106 return; 107 } 108 let mut s = J::obj(); 109 s.set("ok", J::True); 110 s.set("cmd", J::str(cmd)); 111 if let J::Obj(kv) = &mut o { 112 for (k, v) in std::mem::take(kv) { 113 s.set(&String::from_utf8_lossy(&k), v); 114 } 115 } 116 s.set("untrusted", J::str(UNTRUSTED_NOTICE)); 117 self.line(&s); 118 let _ = self.out.flush(); 119 } 120 121 fn event(&mut self, d: &Delivered, stamp: Option) { 122 if self.human { 123 let e = &d.event; 124 let to = if e.to.is_empty() { 125 String::new() 126 } else { 127 format!(" -> {}", e.to.join(",")) 128 }; 129 let flag = if d.addressed { " [to you]" } else { "" }; 130 self.human(&format!( 131 "#{} {} {}{to}{flag} ({} / {}): {}", 132 e.id, 133 e.kind.as_str(), 134 e.from_tag, 135 e.thread, 136 e.topic, 137 e.text.replace('\n', "\n ") 138 )); 139 return; 140 } 141 let mut j = d.event.to_json(); 142 j.set("addressed", if d.addressed { J::True } else { J::False }); 143 if let Some(ns) = stamp { 144 j.set("recv_unix_ns", J::Num(ns.to_string().into_bytes())); 145 } 146 self.line(&j); 147 } 148 149 fn batch(&mut self, cmd: &str, b: &ReadBatch, stamp: Option) { 150 if self.human { 151 self.human(&format!("-- {UNTRUSTED_NOTICE} --")); 152 } 153 for d in &b.events { 154 self.event(d, stamp); 155 } 156 if self.human && b.events.is_empty() { 157 self.human("(nothing new)"); 158 } 159 let mut o = J::obj(); 160 o.set("count", num_u64(b.events.len() as u64)); 161 o.set("after", num_u64(b.after)); 162 o.set("through", num_u64(b.through)); 163 o.set("more", if b.more { J::True } else { J::False }); 164 o.set("base", num_u64(b.base)); 165 o.set("last", num_u64(b.last)); 166 if let Some(t) = b.torn_entry { 167 o.set("in_flight", num_u64(t)); 168 } 169 self.summary(cmd, o); 170 } 171 } 172 173 fn now_ns() -> u128 { 174 SystemTime::now() 175 .duration_since(UNIX_EPOCH) 176 .map(|d| d.as_nanos()) 177 .unwrap_or(0) 178 } 179 180 struct Args(Vec); 181 182 impl Args { 183 fn take(&mut self, flag: &str) -> Result { 184 if self.0.is_empty() { 185 return Err(usage(format!("{flag} needs a value"))); 186 } 187 Ok(self.0.remove(0)) 188 } 189 fn num(&mut self, flag: &str) -> Result { 190 let v = self.take(flag)?; 191 v.parse() 192 .map_err(|_| usage(format!("{flag} needs a number, got {v:?}"))) 193 } 194 fn next_flag(&mut self) -> Option { 195 if self.0.is_empty() { 196 None 197 } else { 198 Some(self.0.remove(0)) 199 } 200 } 201 } 202 203 fn resume(s: &str) -> Result { 204 match s { 205 "acked" => Ok(Resume::Acked), 206 "delivered" => Ok(Resume::Delivered), 207 _ => Err(usage(format!("--from takes acked or delivered, got {s:?}"))), 208 } 209 } 210 211 /// Run a board subcommand; returns the process exit code. 212 pub fn run(args: &[String]) -> i32 { 213 let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); 214 let mut ctx = Ctx { 215 root: env("SYNAPSE_BOARD_ROOT").map(PathBuf::from), 216 expect: None, 217 session: env("SYNAPSE_BOARD_SESSION").or_else(|| env("CRUMB_SESSION")), 218 human: false, 219 out: std::io::stdout().lock(), 220 }; 221 let mut a = Args(args.to_vec()); 222 let mut expect = env("SYNAPSE_BOARD_ID"); 223 let r = (|| -> Result<(), Fail> { 224 while a.0.first().is_some_and(|f| f.starts_with("--")) { 225 let f = a.0.remove(0); 226 match f.as_str() { 227 "--board-root" => ctx.root = Some(a.take(&f)?.into()), 228 "--expect-board-id" => expect = Some(a.take(&f)?), 229 "--session" => ctx.session = Some(a.take(&f)?), 230 "--human" => ctx.human = true, 231 _ => return Err(usage(format!("unknown flag {f}"))), 232 } 233 } 234 if let Some(h) = expect { 235 ctx.expect = Some( 236 BoardId::parse_hex(&h) 237 .ok_or_else(|| usage(format!("--expect-board-id: not a board id: {h:?}")))?, 238 ); 239 } 240 let verb = a.next_flag().ok_or_else(|| usage("missing verb"))?; 241 dispatch(&mut ctx, &verb, a) 242 })(); 243 match r { 244 Ok(()) => 0, 245 Err(Fail::Usage(m)) => { 246 eprintln!("synapse-coord board: {m}"); 247 1 248 } 249 Err(Fail::Board(e)) => { 250 let mut o = J::obj(); 251 o.set("ok", J::False); 252 o.set("error", J::str(e.name())); 253 o.set("message", J::str(&e.to_string())); 254 ctx.line(&o); 255 let _ = ctx.out.flush(); 256 eprintln!("synapse-coord board: {}: {e}", e.name()); 257 match e { 258 BoardError::Io { .. } => 1, 259 _ => 2, 260 } 261 } 262 } 263 } 264 265 fn dispatch(ctx: &mut Ctx, verb: &str, mut a: Args) -> Result<(), Fail> { 266 match verb { 267 "init" => { 268 let root = ctx 269 .root 270 .clone() 271 .ok_or_else(|| usage("--board-root (or SYNAPSE_BOARD_ROOT) is required"))?; 272 let b = Board::init(root)?; 273 if let Some(e) = ctx.expect { 274 if e != b.id() { 275 return Err(BoardError::BoardIdMismatch { 276 root: b.root().to_path_buf(), 277 expected: e, 278 found: b.id(), 279 } 280 .into()); 281 } 282 } 283 ctx.human(&b.mission()); 284 let mut o = J::obj(); 285 o.set("mission", J::str(&b.mission())); 286 o.set("root", J::str(&b.root().display().to_string())); 287 ctx.summary("init", o); 288 } 289 "id" => { 290 let b = ctx.board()?; 291 ctx.human(&b.mission()); 292 let mut o = J::obj(); 293 o.set("mission", J::str(&b.mission())); 294 ctx.summary("id", o); 295 } 296 "register" => { 297 let tag = a.take("register ")?; 298 let mut ttl = None; 299 while let Some(f) = a.next_flag() { 300 match f.as_str() { 301 "--ttl" => ttl = Some(a.num(&f)? as i64), 302 _ => return Err(usage(format!("register: unknown argument {f}"))), 303 } 304 } 305 let b = ctx.board()?; 306 let r = b.register(ctx.session()?, &tag, ttl)?; 307 ctx.human(&format!("{} = {}", r.me.tag, r.me.session)); 308 let mut o = J::obj(); 309 o.set("tag", J::str(&r.me.tag)); 310 o.set("session", J::str(&r.me.session)); 311 o.set("refreshed", if r.refreshed { J::True } else { J::False }); 312 o.set("expires_at", J::num(r.expires_at)); 313 ctx.summary("register", o); 314 } 315 "unregister" => { 316 let b = ctx.board()?; 317 let me = b.unregister(ctx.session()?)?; 318 let mut o = J::obj(); 319 o.set("tag", J::str(&me.tag)); 320 ctx.summary("unregister", o); 321 } 322 "whoami" => { 323 let b = ctx.board()?; 324 let me = b.whoami(ctx.session()?)?; 325 ctx.human(&format!("{} {}", me.tag, me.session)); 326 let mut o = J::obj(); 327 o.set("tag", J::str(&me.tag)); 328 o.set("session", J::str(&me.session)); 329 o.set("mission", J::str(&b.mission())); 330 ctx.summary("whoami", o); 331 } 332 "agents" => { 333 let b = ctx.board()?; 334 let all = b.agents()?; 335 for (tag, session, live) in &all { 336 if ctx.human { 337 ctx.human(&format!( 338 "{tag} {session}{}", 339 if *live { "" } else { " (expired)" } 340 )); 341 } else { 342 let mut j = J::obj(); 343 j.set("tag", J::str(tag)); 344 j.set("session", J::str(session)); 345 j.set("live", if *live { J::True } else { J::False }); 346 ctx.line(&j); 347 } 348 } 349 let mut o = J::obj(); 350 o.set("count", num_u64(all.len() as u64)); 351 ctx.summary("agents", o); 352 } 353 "post" => post(ctx, a)?, 354 "read" => read(ctx, a)?, 355 "inbox" => { 356 let tag = a.take("inbox ")?; 357 let mut limit = DEFAULT_LIMIT; 358 while let Some(f) = a.next_flag() { 359 match f.as_str() { 360 "--limit" => limit = a.num(&f)? as usize, 361 _ => return Err(usage(format!("inbox: unknown argument {f}"))), 362 } 363 } 364 let b = ctx.board()?; 365 let batch = b.inbox(&tag, limit)?; 366 ctx.batch("inbox", &batch, None); 367 } 368 "subscribe" | "unsubscribe" => { 369 let sub = match (a.next_flag().as_deref(), a.next_flag()) { 370 (Some("--topic"), Some(t)) => Sub::Topic(t), 371 (Some("--thread"), Some(t)) => Sub::Thread(t), 372 _ => return Err(usage(format!("{verb} (--topic T | --thread T)"))), 373 }; 374 let b = ctx.board()?; 375 let s = if verb == "subscribe" { 376 b.subscribe(ctx.session()?, &sub)? 377 } else { 378 b.unsubscribe(ctx.session()?, &sub)? 379 }; 380 subs_summary(ctx, verb, &s); 381 } 382 "subscriptions" => { 383 let b = ctx.board()?; 384 let s = b.subscriptions(ctx.session()?)?; 385 subs_summary(ctx, "subscriptions", &s); 386 } 387 "watch" => watch(ctx, a)?, 388 "ack" => { 389 let b = ctx.board()?; 390 let what = a.take("ack | ack --accept-gap")?; 391 let c = if what == "--accept-gap" { 392 b.accept_gap(ctx.session()?)? 393 } else { 394 let id = what 395 .parse() 396 .map_err(|_| usage(format!("ack needs an id, got {what:?}")))?; 397 b.ack(ctx.session()?, id)? 398 }; 399 let mut o = J::obj(); 400 o.set("acked", num_u64(c.acked)); 401 o.set("delivered", num_u64(c.delivered)); 402 ctx.summary("ack", o); 403 } 404 "compact" => { 405 let mut keep = None; 406 let mut expire = false; 407 while let Some(f) = a.next_flag() { 408 match f.as_str() { 409 "--keep-since" => keep = Some(a.num(&f)?), 410 "--expire-cursors" => expire = true, 411 _ => return Err(usage(format!("compact: unknown argument {f}"))), 412 } 413 } 414 let keep = keep.ok_or_else(|| usage("compact --keep-since ID"))?; 415 let b = ctx.board()?; 416 let r = b.compact(keep, expire)?; 417 let mut o = J::obj(); 418 o.set("base", num_u64(r.base)); 419 o.set("last", num_u64(r.last)); 420 o.set("dropped_events", num_u64(r.dropped_events)); 421 o.set("bytes_before", num_u64(r.bytes_before)); 422 o.set("bytes_after", num_u64(r.bytes_after)); 423 o.set("expired", super::frame::j_list(&r.expired)); 424 ctx.summary("compact", o); 425 } 426 "check" => { 427 let b = ctx.board()?; 428 let r = b.check()?; 429 for p in &r.problems { 430 if ctx.human { 431 ctx.human(&format!("problem: {p}")); 432 } else { 433 let mut j = J::obj(); 434 j.set("problem", J::str(p)); 435 ctx.line(&j); 436 } 437 } 438 if !r.ok() { 439 let mut o = J::obj(); 440 o.set("ok", J::False); 441 o.set("error", J::str("CheckFailed")); 442 o.set("problems", num_u64(r.problems.len() as u64)); 443 ctx.line(&o); 444 eprintln!( 445 "synapse-coord board: CheckFailed: {} problem(s)", 446 r.problems.len() 447 ); 448 let _ = ctx.out.flush(); 449 std::process::exit(2); 450 } 451 ctx.human(&format!("ok: events {}..={}", r.base, r.last)); 452 let mut o = J::obj(); 453 o.set("base", num_u64(r.base)); 454 o.set("last", num_u64(r.last)); 455 o.set("events", num_u64(r.events)); 456 o.set("journal_bytes", num_u64(r.journal_bytes)); 457 ctx.summary("check", o); 458 } 459 "recover" => { 460 let b = ctx.board()?; 461 let r = b.recover()?; 462 let mut o = J::obj(); 463 o.set( 464 "torn_tail_at", 465 r.torn_tail_at.map(num_u64).unwrap_or(J::Null), 466 ); 467 o.set("torn_bytes", num_u64(r.torn_bytes)); 468 o.set( 469 "adopted", 470 J::Arr(r.adopted.iter().map(|i| num_u64(*i)).collect()), 471 ); 472 o.set( 473 "dropped_table_entry", 474 if r.dropped_table_entry { 475 J::True 476 } else { 477 J::False 478 }, 479 ); 480 o.set( 481 "table_rebuilt", 482 if r.table_rebuilt { J::True } else { J::False }, 483 ); 484 o.set( 485 "rebuilt_after_boot", 486 if r.rebuilt_after_boot { 487 J::True 488 } else { 489 J::False 490 }, 491 ); 492 ctx.summary("recover", o); 493 } 494 _ => return Err(usage(format!("unknown verb {verb:?}"))), 495 } 496 Ok(()) 497 } 498 499 fn subs_summary(ctx: &mut Ctx, cmd: &str, s: &super::Subscriptions) { 500 ctx.human(&format!( 501 "topics: {}\nthreads: {}", 502 s.topics.join(", "), 503 s.threads.join(", ") 504 )); 505 let mut o = J::obj(); 506 o.set("topics", super::frame::j_list(&s.topics)); 507 o.set("threads", super::frame::j_list(&s.threads)); 508 ctx.summary(cmd, o); 509 } 510 511 fn post(ctx: &mut Ctx, mut a: Args) -> Result<(), Fail> { 512 let (mut thread, mut topic, mut kind) = (None, None, Kind::Finding); 513 let (mut to, mut refs) = (Vec::new(), Vec::new()); 514 let (mut parent, mut idem, mut text, mut pointer) = (None, None, None, None); 515 while let Some(f) = a.next_flag() { 516 match f.as_str() { 517 "--thread" => thread = Some(a.take(&f)?), 518 "--topic" => topic = Some(a.take(&f)?), 519 "--kind" => { 520 let k = a.take(&f)?; 521 kind = Kind::parse(&k).ok_or_else(|| usage(format!("unknown kind {k:?}")))?; 522 } 523 "--to" => to.push(a.take(&f)?), 524 "--parent" => parent = Some(a.num(&f)?), 525 "--idem" => idem = Some(a.take(&f)?), 526 "--ref" => { 527 let repo = a.take(&f)?; 528 let k = a.take(&f)?; 529 let value = a.take(&f)?; 530 let kind = 531 RefKind::parse(&k).ok_or_else(|| usage(format!("unknown ref kind {k:?}")))?; 532 refs.push(Ref { repo, kind, value }); 533 } 534 "--text" => text = Some(a.take(&f)?), 535 "--text-file" => { 536 let p = PathBuf::from(a.take(&f)?); 537 let b = crate::record::read_bounded(&p, MAX_TEXT_BYTES as u64) 538 .map_err(BoardError::from)? 539 .ok_or_else(|| usage(format!("{} does not exist", p.display())))?; 540 text = Some( 541 String::from_utf8(b) 542 .map_err(|_| usage(format!("{} is not UTF-8", p.display())))?, 543 ); 544 } 545 "--pointer-whisper" => { 546 pointer = Some((a.take(&f)?, a.take(&f)?, a.take(&f)?)); 547 } 548 _ => return Err(usage(format!("post: unknown argument {f}"))), 549 } 550 } 551 let thread = thread.ok_or_else(|| usage("post needs --thread"))?; 552 let topic = topic.ok_or_else(|| usage("post needs --topic"))?; 553 let text = text.ok_or_else(|| usage("post needs --text or --text-file"))?; 554 let b = ctx.board()?; 555 let me = b.whoami(ctx.session()?)?; 556 let mut p = Post::new(&me, &thread, &topic, kind, &text); 557 p.to = to; 558 p.parent = parent; 559 p.idem = idem; 560 p.refs = refs; 561 let r = b.post(&p)?; 562 let mut o = J::obj(); 563 o.set("id", num_u64(r.id)); 564 o.set("mission", J::str(&r.mission.to_hex())); 565 o.set("dedup", if r.dedup { J::True } else { J::False }); 566 o.set("woke", num_u64(r.woke as u64)); 567 if let Some(t) = r.recovery.torn_tail_at { 568 o.set("torn_tail_at", num_u64(t)); 569 } 570 if !r.recovery.adopted.is_empty() { 571 o.set( 572 "adopted", 573 J::Arr(r.recovery.adopted.iter().map(|i| num_u64(*i)).collect()), 574 ); 575 } 576 if r.recovery.rebuilt_after_boot { 577 o.set("rebuilt_after_boot", J::True); 578 } 579 let mut pointer_err = None; 580 if let Some((store, top, dir)) = pointer { 581 let cs = CoordStore::open(store); 582 let ws = Workspace::with_oracle(top, Holder::default(), Box::new(NoOracle)); 583 match b.pointer_whisper(&cs, &ws, &me.tag, &dir, r.id) { 584 Ok(()) => o.set("pointer_whisper", J::str(&b.pointer_text(r.id))), 585 Err(e) => { 586 o.set("pointer_whisper_error", J::str(&e.to_string())); 587 pointer_err = Some(e); 588 } 589 } 590 } 591 ctx.human(&format!( 592 "posted #{}{}", 593 r.id, 594 if r.dedup { " (already posted)" } else { "" } 595 )); 596 ctx.summary("post", o); 597 match pointer_err { 598 // The post is committed; only the optional pointer failed. 599 Some(e) => Err(Fail::Board(e)), 600 None => Ok(()), 601 } 602 } 603 604 fn read(ctx: &mut Ctx, mut a: Args) -> Result<(), Fail> { 605 let (mut from, mut after, mut limit) = (Resume::Acked, None, DEFAULT_LIMIT); 606 let (mut peek, mut mine, mut all) = (false, false, false); 607 while let Some(f) = a.next_flag() { 608 match f.as_str() { 609 "--from" => from = resume(&a.take(&f)?)?, 610 "--after" => after = Some(a.num(&f)?), 611 "--limit" => limit = a.num(&f)? as usize, 612 "--peek" => peek = true, 613 "--mine" => mine = true, 614 "--all" => all = true, 615 _ => return Err(usage(format!("read: unknown argument {f}"))), 616 } 617 } 618 let b = ctx.board()?; 619 let batch = if all { 620 b.read_all(after, limit)? 621 } else { 622 let session = ctx.session()?.to_string(); 623 if mine || peek || after.is_some() { 624 // Pure reads: the shared cursor never moves. 625 let start = match after { 626 Some(x) => x, 627 None => { 628 let me = b.whoami(&session)?; 629 b.start_after(&me.tag, from)? 630 } 631 }; 632 if mine { 633 b.read_mine(&session, start, limit)? 634 } else { 635 b.read_since(&session, start, limit)? 636 } 637 } else { 638 b.deliver(&session, limit, from)? 639 } 640 }; 641 ctx.batch("read", &batch, None); 642 Ok(()) 643 } 644 645 fn watch(ctx: &mut Ctx, mut a: Args) -> Result<(), Fail> { 646 let (mut timeout, mut limit, mut from) = (DEFAULT_WATCH_MS, DEFAULT_LIMIT, Resume::Delivered); 647 let (mut follow, mut stamp) = (None, false); 648 while let Some(f) = a.next_flag() { 649 match f.as_str() { 650 "--timeout-ms" => timeout = a.num(&f)?, 651 "--limit" => limit = a.num(&f)? as usize, 652 "--from" => from = resume(&a.take(&f)?)?, 653 "--follow" => follow = Some(a.num(&f)?), 654 "--stamp" => stamp = true, 655 _ => return Err(usage(format!("watch: unknown argument {f}"))), 656 } 657 } 658 let b = ctx.board()?; 659 let session = ctx.session()?.to_string(); 660 // Bind before the first read so a post between read and wait still wakes us. 661 let w = b.watcher(&session)?; 662 let want = follow.unwrap_or(1); 663 let mut got = 0u64; 664 let mut wakes = 0u64; 665 let mut timed_out = false; 666 let mut first_from = Some(from); 667 let mut last: Option; 668 loop { 669 let r = first_from.take().unwrap_or(Resume::Delivered); 670 let batch = b.deliver(&session, limit, r)?; 671 let ns = stamp.then(now_ns); 672 for d in &batch.events { 673 ctx.event(d, ns); 674 } 675 let _ = ctx.out.flush(); 676 got += batch.events.len() as u64; 677 last = Some(batch); 678 if got >= want { 679 break; 680 } 681 if last.as_ref().is_some_and(|l| l.more) { 682 continue; 683 } 684 let t0 = Instant::now(); 685 match w.wait(Duration::from_millis(timeout))? { 686 Wake::Woke(_) => wakes += 1, 687 Wake::TimedOut => { 688 // A lost datagram costs latency, never an event: read once more. 689 let batch = b.deliver(&session, limit, Resume::Delivered)?; 690 let ns = stamp.then(now_ns); 691 for d in &batch.events { 692 ctx.event(d, ns); 693 } 694 got += batch.events.len() as u64; 695 last = Some(batch); 696 if got >= want || t0.elapsed() >= Duration::from_millis(timeout) { 697 timed_out = got < want; 698 break; 699 } 700 } 701 } 702 } 703 let mut o = J::obj(); 704 o.set("count", num_u64(got)); 705 o.set("wakes", num_u64(wakes)); 706 o.set("timed_out", if timed_out { J::True } else { J::False }); 707 if let Some(l) = last { 708 o.set("through", num_u64(l.through)); 709 o.set("last", num_u64(l.last)); 710 } 711 ctx.summary("watch", o); 712 Ok(()) 713 }