|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse, json, os, signal, sys, time |
| 4 | +from typing import Any, Dict, List, Optional |
| 5 | +from libby.libby import Libby |
| 6 | + |
| 7 | +DEFAULT_SELF_ID = "cli" |
| 8 | +DEFAULT_BIND = "tcp://127.0.0.1:56001" |
| 9 | + |
| 10 | +def _parse_addr_kv(kv: str) -> tuple[str, str]: |
| 11 | + if "=" not in kv: |
| 12 | + raise argparse.ArgumentTypeError("Expected 'peerId=tcp://host:port'") |
| 13 | + k, v = kv.split("=", 1) |
| 14 | + k, v = k.strip(), v.strip() |
| 15 | + if not k or not v: |
| 16 | + raise argparse.ArgumentTypeError("Expected 'peerId=tcp://host:port'") |
| 17 | + return k, v |
| 18 | + |
| 19 | +def _load_book(path: Optional[str]) -> Dict[str, str]: |
| 20 | + if not path: |
| 21 | + return {} |
| 22 | + with open(path, "r", encoding="utf-8") as f: |
| 23 | + data = json.load(f) |
| 24 | + if not isinstance(data, dict): |
| 25 | + raise SystemExit("--book JSON must be an object mapping peer->endpoint") |
| 26 | + return {str(k): str(v) for k, v in data.items()} |
| 27 | + |
| 28 | +def _parse_json(s: Optional[str]) -> Dict[str, Any]: |
| 29 | + if not s: |
| 30 | + return {} |
| 31 | + try: |
| 32 | + return json.loads(s) |
| 33 | + except Exception as ex: |
| 34 | + raise SystemExit(f"--data must be JSON: {ex}") |
| 35 | + |
| 36 | +def _self_id(ns: argparse.Namespace) -> str: |
| 37 | + return ns.self_id or os.environ.get("LIBBY_SELF_ID", DEFAULT_SELF_ID) |
| 38 | + |
| 39 | +def _bind(ns: argparse.Namespace) -> str: |
| 40 | + return ns.bind or os.environ.get("LIBBY_BIND", DEFAULT_BIND) |
| 41 | + |
| 42 | +def _mk_libby(self_id: str, bind: str, book: Dict[str, str]) -> Libby: |
| 43 | + lib = Libby.zmq( |
| 44 | + self_id=self_id, |
| 45 | + bind=bind, |
| 46 | + address_book=book, |
| 47 | + keys=[], |
| 48 | + callback=None, |
| 49 | + discover=True, |
| 50 | + discover_interval_s=2.0, |
| 51 | + hello_on_start=True, |
| 52 | + ) |
| 53 | + try: |
| 54 | + lib.hello() |
| 55 | + except Exception: |
| 56 | + pass |
| 57 | + return lib |
| 58 | + |
| 59 | +def cmd_req(ns: argparse.Namespace) -> int: |
| 60 | + book = _load_book(ns.book) |
| 61 | + for kv in ns.addr or []: |
| 62 | + k, v = _parse_addr_kv(kv); book[k] = v |
| 63 | + |
| 64 | + self_id = _self_id(ns) |
| 65 | + bind = _bind(ns) |
| 66 | + payload = _parse_json(ns.data) |
| 67 | + |
| 68 | + lib: Optional[Libby] = None |
| 69 | + try: |
| 70 | + lib = _mk_libby(self_id, bind, book) |
| 71 | + ttl_ms = int(ns.ttl_ms) if ns.ttl_ms is not None else int(ns.timeout * 1000.0) |
| 72 | + res = lib.rpc(ns.peer, ns.key, payload, ttl_ms=ttl_ms) |
| 73 | + print(json.dumps(res, indent=2 if ns.raw_json else 2)) |
| 74 | + return 0 if res.get("status") == "delivered" else 2 |
| 75 | + except KeyboardInterrupt: |
| 76 | + return 130 |
| 77 | + except Exception as ex: |
| 78 | + print(f"libby-cli req: {ex}", file=sys.stderr) |
| 79 | + return 2 |
| 80 | + finally: |
| 81 | + if lib: |
| 82 | + try: lib.stop() |
| 83 | + except Exception: pass |
| 84 | + |
| 85 | +def cmd_sub(ns: argparse.Namespace) -> int: |
| 86 | + topics: List[str] = ns.topics |
| 87 | + if not topics: |
| 88 | + print("sub: provide at least one topic", file=sys.stderr) |
| 89 | + return 2 |
| 90 | + |
| 91 | + book = _load_book(ns.book) |
| 92 | + for kv in ns.addr or []: |
| 93 | + k, v = _parse_addr_kv(kv); book[k] = v |
| 94 | + |
| 95 | + self_id = _self_id(ns) |
| 96 | + bind = _bind(ns) |
| 97 | + |
| 98 | + lib: Optional[Libby] = None |
| 99 | + stop = False |
| 100 | + |
| 101 | + def on_sig(_s, _f): |
| 102 | + nonlocal stop; stop = True |
| 103 | + |
| 104 | + signal.signal(signal.SIGINT, on_sig) |
| 105 | + signal.signal(signal.SIGTERM, on_sig) |
| 106 | + |
| 107 | + try: |
| 108 | + lib = _mk_libby(self_id, bind, book) |
| 109 | + |
| 110 | + def _printer(msg): |
| 111 | + try: |
| 112 | + print(json.dumps( |
| 113 | + {"source": msg.env.sourceid, "topic": msg.env.key, "payload": msg.env.payload}, |
| 114 | + indent=2 if ns.raw_json else 2, |
| 115 | + )) |
| 116 | + except Exception as ex: |
| 117 | + print(f"[event decode error] {ex}", file=sys.stderr) |
| 118 | + |
| 119 | + for t in topics: |
| 120 | + lib.listen(t, _printer) |
| 121 | + lib.subscribe(*topics) |
| 122 | + |
| 123 | + print(f"[libby sub] up: id={self_id} bind={bind} topics={topics}") |
| 124 | + while not stop: |
| 125 | + time.sleep(0.25) |
| 126 | + return 0 |
| 127 | + except KeyboardInterrupt: |
| 128 | + return 130 |
| 129 | + except Exception as ex: |
| 130 | + print(f"libby-cli sub: {ex}", file=sys.stderr) |
| 131 | + return 2 |
| 132 | + finally: |
| 133 | + if lib: |
| 134 | + try: lib.stop() |
| 135 | + except Exception: pass |
| 136 | + print("[libby sub] stopped") |
| 137 | + |
| 138 | +def build_parser() -> argparse.ArgumentParser: |
| 139 | + ap = argparse.ArgumentParser( |
| 140 | + prog="libby-cli", |
| 141 | + description="Simple Libby CLI: request a key or subscribe to topics." |
| 142 | + ) |
| 143 | + sub = ap.add_subparsers(dest="cmd", required=True) |
| 144 | + |
| 145 | + def common(p): |
| 146 | + p.add_argument("--self-id", help=f"Local peer id (default: {DEFAULT_SELF_ID} or $LIBBY_SELF_ID)") |
| 147 | + p.add_argument("--bind", help=f"Local ROUTER bind (default: {DEFAULT_BIND} or $LIBBY_BIND)") |
| 148 | + p.add_argument("--book", help="Path to JSON {peer_id:'tcp://host:port'}") |
| 149 | + p.add_argument("--addr", action="append", metavar="peer=tcp://host:port", |
| 150 | + help="Add/override address-book entry (repeatable)") |
| 151 | + p.add_argument("--raw-json", action="store_true", help="Pretty-print JSON") |
| 152 | + |
| 153 | + pr = sub.add_parser("req", help="Send a keyed request (RPC) to a peer and print the response") |
| 154 | + common(pr) |
| 155 | + pr.add_argument("-p", "--peer", required=True, help="Destination peer id") |
| 156 | + pr.add_argument("-k", "--key", required=True, help="Key to request (service name)") |
| 157 | + pr.add_argument("-d", "--data", help="JSON payload to send (default: {})") |
| 158 | + pr.add_argument("--timeout", type=float, default=8.0, help="Timeout seconds (default 8.0)") |
| 159 | + pr.add_argument("--ttl-ms", type=int, help="Override TTL ms (default: timeout*1000)") |
| 160 | + pr.set_defaults(func=cmd_req) |
| 161 | + |
| 162 | + ps = sub.add_parser("sub", help="Subscribe to one or more topics and print publishes") |
| 163 | + common(ps) |
| 164 | + ps.add_argument("topics", nargs="+", help="Topic(s) to subscribe to") |
| 165 | + ps.set_defaults(func=cmd_sub) |
| 166 | + |
| 167 | + return ap |
| 168 | + |
| 169 | +def main(argv: Optional[List[str]] = None) -> int: |
| 170 | + ns = build_parser().parse_args(argv) |
| 171 | + return ns.func(ns) |
| 172 | + |
| 173 | +if __name__ == "__main__": |
| 174 | + raise SystemExit(main()) |
0 commit comments