asterism 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/asterism/cli.rb CHANGED
@@ -8,6 +8,8 @@
8
8
  # asterism object list 'games/games/*' / object info games/games/othello1
9
9
  # asterism object find join # the objects that have join
10
10
  # asterism status get games/games # echo: as it changes, hz: how often
11
+ # asterism topic list 'games/*' # the topics put on, with their types
12
+ # asterism topic info games/games/othello1/state
11
13
  # asterism object get games/games/othello1 state # the next put there
12
14
  # asterism call games/games/othello1 view '"<token>"'
13
15
  # asterism ping / watch / tree / mcp # as before
@@ -21,10 +23,29 @@
21
23
  # and reads what docs/protocol.md lets anyone read. It calls a method only
22
24
  # with `call` (and the MCP bridge only the methods --allow names). What it
23
25
  # can see is what the router lets it see: with a console's .tar, its role.
26
+ #
27
+ # Inside another program (a console's bridge) it runs on that program's
28
+ # connection instead of opening one:
29
+ #
30
+ # cli = Asterism::CLI.new(out: io, err: io, env: {}, net: conn,
31
+ # stop: -> { asked_to_stop }, permit: ->(plan) { nil })
32
+ # cli.run(%w[node list])
33
+ #
34
+ # net: the Asterism::Connection to use (it is neither started nor closed here; what
35
+ # a command subscribes to or hooks onto it is released when the command
36
+ # ends); stop: asked often while a command streams (watch, echo, hz, get,
37
+ # ping), true ends it as Ctrl-C does; permit: asked once the words are read
38
+ # (an Asterism::CLI::Plan: the command, whether it reads or calls, the
39
+ # object and method it calls), returns nil to go on or the reason it may
40
+ # not (printed; CLI#refused keeps it). Such a command line takes no
41
+ # --router / --credentials / --peer / --node / --app, runs neither mcp nor
42
+ # completion, takes long options only as written in full, and prints
43
+ # --help to its out.
24
44
  require "asterism"
25
45
  require "optparse"
26
46
  require "json"
27
47
  require "securerandom"
48
+ require_relative "cli/commands"
28
49
  require_relative "cli/literal"
29
50
  require_relative "cli/survey"
30
51
  require_relative "cli/allow"
@@ -35,56 +56,6 @@ require_relative "cli/values"
35
56
 
36
57
  module Asterism
37
58
  class CLI
38
- # The nouns and their verbs: verb => [its arguments, what it does].
39
- NOUNS = {
40
- "node" => {
41
- "list" => ["", "the nodes, a name a line"],
42
- "info" => ["NODE", "one node: its profile, applications (with their statuses) and objects"]
43
- },
44
- "app" => {
45
- "list" => ["", "the applications, node/app a line"],
46
- "info" => ["NODE/APP", "one application: its status and its objects"]
47
- },
48
- "object" => {
49
- "list" => ["[PATTERN]", "the objects, node/app/object a line (PATTERN: * and ** for whole parts)"],
50
- "info" => ["PATH", "one object (node/app/object): its description and its methods"],
51
- "find" => ["METHOD", "the objects that have the method (* as a wildcard)"],
52
- "get" => ["PATH [KEY]", "the next value the application puts on PATH/KEY (its own keys; KEY: ** " \
53
- "by default; --timeout 5.0)"],
54
- "echo" => ["PATH [KEY]", "the values it puts there as they come (the text: what changed; --once: " \
55
- "the first; --raw: each whole)"]
56
- },
57
- "status" => {
58
- "get" => ["NODE/APP", "an application's status, now"],
59
- "echo" => ["NODE/APP", "its status, then each change as it comes (--once: now, once)"],
60
- "hz" => ["NODE/APP", "how often it changes: the rate, the intervals' min / max / std dev"]
61
- }
62
- }.freeze
63
-
64
- # The commands without a noun: name => [its arguments, what it does].
65
- COMMANDS = {
66
- "call" => ["PATH METHOD [ARG...]", "calls a method; each ARG is JSON, else a Ruby literal, else text"],
67
- "ping" => ["PATH", "round trips: PATH node/app/object (its meta) or node (its profile); " \
68
- "--call METHOD [ARG...] times a call instead"],
69
- "watch" => ["", "nodes, applications and objects coming and going, and status changes"],
70
- "tree" => ["", "nodes > applications (with their status) > objects (--methods: their methods)"],
71
- "mcp" => ["", "an MCP server on stdio (needs the mcp gem): the listings as tools, and the methods " \
72
- "--allow names"],
73
- "completion" => ["bash|zsh", "the shell's Tab completion: source <(asterism completion bash)"],
74
- "version" => ["", "the gem's version"]
75
- }.freeze
76
-
77
- # The older names, kept with their output.
78
- ALIASES = {
79
- "nodes" => "the nodes, their applications (with their statuses) and profiles, in one listing",
80
- "objects" => "[PATTERN] the objects with their descriptions and methods (object info of each)",
81
- "echo" => "ping"
82
- }.freeze
83
-
84
- # The options that take a value (what __complete skips over).
85
- VALUE_OPTIONS = %w[--router --credentials --peer --node --app -o --output --timeout --settle --duration --count
86
- --interval --call --kwargs --allow --period --window].freeze
87
-
88
59
  def self.usage
89
60
  col = 30
90
61
  line = lambda do |name, args, what|
@@ -130,20 +101,38 @@ module Asterism
130
101
  new(out: out, err: err, env: env).run(argv.dup)
131
102
  end
132
103
 
133
- def initialize(out: $stdout, err: $stderr, env: ENV)
104
+ # The reason permit: gave for not running the command (nil: it ran).
105
+ attr_reader :refused
106
+
107
+ def initialize(out: $stdout, err: $stderr, env: ENV, net: nil, stop: nil, permit: nil)
134
108
  @out = out
135
109
  @err = err
136
110
  @env = env
111
+ @given_net = net
112
+ @stop = stop
113
+ @permit = permit
114
+ @held = []
137
115
  @lock = Mutex.new
138
116
  @last_status = {}
139
117
  @opts = { timeout: 2.0, settle: 1.5, format: nil, count: 5, interval: 0.2, allow: [], period: 1.0,
140
118
  window: 1000 }
141
119
  end
142
120
 
121
+ # Whether this command line runs on a connection it was given (net:).
122
+ def embedded?
123
+ !@given_net.nil?
124
+ end
125
+
126
+ # Whether stop: asks the command to end.
127
+ def stopped?
128
+ @stop ? @stop.call : false
129
+ end
130
+
143
131
  def run(argv)
144
132
  cmd = argv.shift
145
133
  case cmd
146
134
  when nil, "help", "-h", "--help"
135
+ return 2 unless permitted?(Plan.new(key: "help", kind: :read, args: argv.dup, options: {}))
147
136
  if cmd == "help" && NOUNS.key?(argv.first)
148
137
  @out.puts CLI.noun_usage(argv.first)
149
138
  return 0
@@ -151,9 +140,11 @@ module Asterism
151
140
  @out.puts USAGE
152
141
  return cmd.nil? ? 2 : 0
153
142
  when "version", "--version", "-v"
143
+ return 2 unless permitted?(Plan.new(key: "version", kind: :read, args: [], options: {}))
154
144
  @out.puts "asterism #{::Asterism::VERSION}"
155
145
  return 0
156
146
  when "__complete"
147
+ return 2 unless permitted?(Plan.new(key: "__complete", kind: :read, args: argv.dup, options: {}))
157
148
  return cmd_complete(argv)
158
149
  end
159
150
  key = cmd
@@ -173,8 +164,10 @@ module Asterism
173
164
  @err.puts "asterism: unknown command #{cmd.inspect}\n\n#{USAGE}"
174
165
  return 2
175
166
  end
167
+ return embedded_run(key, argv) if embedded?
176
168
  rest = parser(key).parse(argv)
177
- send("cmd_#{key == 'echo' ? 'ping' : key.tr(' ', '_')}", rest)
169
+ return 2 unless permitted?(plan(key, rest))
170
+ run_command(key, rest)
178
171
  rescue OptionParser::ParseError, ArgumentError => e
179
172
  @err.puts "asterism: #{e.message}"
180
173
  2
@@ -188,17 +181,70 @@ module Asterism
188
181
  0
189
182
  end
190
183
 
184
+ def run_command(key, rest)
185
+ send("cmd_#{key == 'echo' ? 'ping' : key.tr(' ', '_')}", rest)
186
+ end
187
+
188
+ # A command on the connection given (net:): no connection options, no
189
+ # mcp or completion, --help printed to out (see the top of this file).
190
+ def embedded_run(key, argv)
191
+ if LOCAL.include?(key)
192
+ return 2 unless permitted?(Plan.new(key: key, kind: :local, args: argv.dup, options: {}))
193
+ raise ArgumentError, "#{key} runs only as a program of its own (asterism #{key})"
194
+ end
195
+ words = argv.take_while { _1 != "--" }
196
+ given = words.find { CONNECTION_OPTIONS.include?(_1.split("=", 2)[0]) }
197
+ raise ArgumentError, "#{given.split('=', 2)[0]}: this command line runs on the connection it was given" if given
198
+ if words.any? { %w[-h --help].include?(_1) }
199
+ @out.puts parser(key).help
200
+ return 0
201
+ end
202
+ rest = parser(key).parse(argv)
203
+ return 2 unless permitted?(plan(key, rest))
204
+ run_command(key, rest)
205
+ end
206
+
207
+ # The Plan of a command whose words were read (rest: its positional
208
+ # arguments).
209
+ def plan(key, rest)
210
+ kind = CLI.kind(key, call: @opts[:call])
211
+ path = rest[0]
212
+ method = kind == :call ? (key == "call" ? rest[1] : @opts[:call]) : nil
213
+ Plan.new(key: key, kind: kind, path: path, method: method, args: rest.dup,
214
+ options: @opts.reject { |k, _| k == :allow }.merge(allow: @opts[:allow].dup))
215
+ end
216
+
217
+ # Asks permit: (when given) about the plan; prints the reason it gives.
218
+ def permitted?(plan)
219
+ return true unless @permit
220
+ why = @permit.call(plan)
221
+ return true if why.nil?
222
+ @refused = why.to_s
223
+ @err.puts "asterism: #{@refused}"
224
+ false
225
+ end
226
+
191
227
  # The options of a command (key: "tree", "node info", ...).
192
228
  def parser(key)
193
229
  OptionParser.new do |o|
194
230
  args = (NOUNS.dig(*key.split(" ")) || COMMANDS[key] || [""])[0]
195
231
  o.banner = "Usage: asterism #{key} #{args} [options]".squeeze(" ")
232
+ if embedded?
233
+ # Long options only as written in full (no --cal for --call), and
234
+ # none of OptionParser's own (--help, --version, the completion
235
+ # scripts): they print to $stdout and exit the process.
236
+ o.require_exact = true
237
+ o.base.long.clear
238
+ o.base.short.clear
239
+ end
196
240
  unless key == "completion"
197
- o.on("--router LOCATOR", "a router (tcp/HOST:7447)") { @opts[:router] = _1 }
198
- o.on("--credentials TAR", "a console's .tar") { @opts[:credentials] = _1 }
199
- o.on("--peer LOCATOR", "a direct peer link to a node listening there (no router)") { @opts[:peer] = _1 }
200
- o.on("--node NAME", "this node's ID (default: the certificate's name, or cli-<6 hex>)") { @opts[:node] = _1 }
201
- o.on("--app NAME", "this application's name (default: cli-<4 hex>)") { @opts[:app] = _1 }
241
+ unless embedded?
242
+ o.on("--router LOCATOR", "a router (tcp/HOST:7447)") { @opts[:router] = _1 }
243
+ o.on("--credentials TAR", "a console's .tar") { @opts[:credentials] = _1 }
244
+ o.on("--peer LOCATOR", "a direct peer link to a node listening there (no router)") { @opts[:peer] = _1 }
245
+ o.on("--node NAME", "this node's ID (default: the certificate's name, or cli-<6 hex>)") { @opts[:node] = _1 }
246
+ o.on("--app NAME", "this application's name (default: cli-<4 hex>)") { @opts[:app] = _1 }
247
+ end
202
248
  unless key == "mcp"
203
249
  o.on("-o", "--output FORMAT", %w[json yaml], "json or yaml instead of text (the same content)") do
204
250
  @opts[:format] = _1.to_sym
@@ -296,8 +342,9 @@ module Asterism
296
342
  end
297
343
 
298
344
  # Connects, starts the receiving thread, waits for the tokens and yields
299
- # the Net and a Survey.
300
- def connect(app_prefix: "cli")
345
+ # the connection and a Survey.
346
+ def connect(app_prefix: "cli", &blk)
347
+ return connect_given(&blk) if embedded?
301
348
  router, creds, peer = network
302
349
  if router.nil? && creds.nil? && peer.nil?
303
350
  raise ArgumentError, "where is the network? --router tcp/HOST:7447 or --credentials FILE.tar " \
@@ -313,13 +360,51 @@ module Asterism
313
360
  locator = peer
314
361
  kw[:mode] = :peer
315
362
  end
316
- ::Asterism.profile(name: app_prefix == "mcp" ? "asterism MCP" : "asterism CLI")
317
363
  ::Asterism.connect(locator, **kw) do |net|
364
+ net.profile(name: app_prefix == "mcp" ? "asterism MCP" : "asterism CLI")
318
365
  net.on_error { |e, where| @err.puts "asterism: #{where}: #{e.class}: #{e.message}" }
319
366
  net.start
320
- survey = Survey.new(timeout: @opts[:timeout])
367
+ @net = net
368
+ survey = Survey.new(net, timeout: @opts[:timeout])
321
369
  survey.settle(@opts[:settle])
322
- yield net, survey
370
+ begin
371
+ yield net, survey
372
+ ensure
373
+ release_held
374
+ @net = nil
375
+ end
376
+ end
377
+ end
378
+
379
+ # The connection given (net:): yields it and a Survey; nothing is
380
+ # started, waited for or closed (its tokens are known already). What
381
+ # the command subscribed to or hooked onto it is released at the end.
382
+ def connect_given
383
+ raise ::Asterism::Disconnected, "the connection is not there" unless @given_net.connected?
384
+ @net = @given_net
385
+ yield @given_net, Survey.new(@given_net, timeout: @opts[:timeout])
386
+ ensure
387
+ release_held
388
+ end
389
+
390
+ # Something a command keeps until it ends (released when it does): a
391
+ # subscription or liveliness watch (closed), or [:join / :leave, block]
392
+ # given to on_join / on_leave (taken off). Returns it.
393
+ def hold(thing)
394
+ @lock.synchronize { @held << thing }
395
+ thing
396
+ end
397
+
398
+ def release_held
399
+ held = @lock.synchronize { @held.slice!(0..) }
400
+ held.reverse_each do |h|
401
+ case h
402
+ in [:join, blk] then @net&.off_join(blk)
403
+ in [:leave, blk] then @net&.off_leave(blk)
404
+ else h.close
405
+ end
406
+ rescue StandardError
407
+ nil
323
408
  end
324
409
  end
325
410
 
@@ -427,25 +512,32 @@ module Asterism
427
512
  connect do |net, sv|
428
513
  own = "#{net.node_id}/#{net.app}"
429
514
  sv.statuses.sort.each { |path, st| event("status", path, status: st, now: true) }
430
- net.on_join { |n| event("join", n, what: "node") }
431
- net.on_leave { |n| event("leave", n, what: "node") }
432
- net.session.liveliness_watch("asterism/**") do |key, alive|
515
+ net.on_join(&hold([:join, proc { |n| event("join", n, what: "node") }])[1])
516
+ net.on_leave(&hold([:leave, proc { |n| event("leave", n, what: "node") }])[1])
517
+ hold(net.zenoh.liveliness_watch("asterism/**") do |key, alive|
433
518
  # The tokens alive at the start come first, in one burst: not news.
434
519
  next unless @watch_started
435
520
  path = key.delete_prefix("asterism/")
436
521
  next if path == own || path.start_with?("#{own}/")
437
- what = { 2 => "app", 3 => "object" }[path.count("/") + 1]
438
- event(alive ? "join" : "leave", path, what: what) if what
439
- end
440
- net.session.subscribe(Survey::STATUS_ALL) do |sample|
522
+ parts = path.split("/")
523
+ if parts.size == 3
524
+ event(alive ? "join" : "leave", path, what: "object")
525
+ elsif (pr = ::Asterism.token_protocol(parts))
526
+ # An application's token says its protocol (docs/protocol.md 6.1).
527
+ app = parts[0, 2].join("/")
528
+ what = pr == ::Asterism::PROTOCOL ? "app" : "app (protocol #{pr})"
529
+ event(alive ? "join" : "leave", app, what: what)
530
+ end
531
+ end)
532
+ hold(net.zenoh.subscribe(Survey::STATUS_ALL) do |sample|
441
533
  got = ::Asterism::Status.parse(sample.key, sample.payload)
442
534
  event("status", "#{got[0]}/#{got[1]}", status: got[2]) if got && "#{got[0]}/#{got[1]}" != own
443
- end
444
- net.session.subscribe(Survey::PROFILES_ALL) do |sample|
535
+ end)
536
+ hold(net.zenoh.subscribe(Survey::PROFILES_ALL) do |sample|
445
537
  node = sample.key.split("/")[1]
446
538
  pr = ::Asterism::Profile.check(::Asterism::Codec.unpack(sample.payload))
447
539
  event("profile", node, profile: pr) if pr && node != net.node_id
448
- end
540
+ end)
449
541
  sleep 0.3
450
542
  @watch_started = true
451
543
  @err.puts "asterism: watching (Ctrl-C to stop)" unless structured?
@@ -453,6 +545,7 @@ module Asterism
453
545
  loop do
454
546
  break if deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
455
547
  break unless net.connected?
548
+ break if stopped?
456
549
  sleep 0.05
457
550
  end
458
551
  end
@@ -533,7 +626,8 @@ module Asterism
533
626
  connect do |_net, _sv|
534
627
  ms = (@opts[:timeout] * 1000).round
535
628
  @opts[:count].times do |i|
536
- sleep @opts[:interval] if i.positive?
629
+ break if stopped?
630
+ pause(@opts[:interval]) if i.positive?
537
631
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
538
632
  ok = begin
539
633
  ping_once(path, chunks, args, ms)
@@ -560,14 +654,24 @@ module Asterism
560
654
  times.empty? ? 1 : 0
561
655
  end
562
656
 
657
+ # Sleeps for seconds, or until stop: asks to end.
658
+ def pause(seconds)
659
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
660
+ loop do
661
+ left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
662
+ break if left <= 0 || stopped?
663
+ sleep [left, 0.1].min
664
+ end
665
+ end
666
+
563
667
  def ping_once(path, chunks, args, ms)
564
668
  if @opts[:call]
565
- ::Asterism[path, timeout_ms: ms].asterism_call(@opts[:call], *args)
669
+ @net[path, timeout_ms: ms].asterism_call(@opts[:call], *args)
566
670
  elsif chunks.size == 3
567
- raw = ::Asterism.meta(path, ms)
671
+ raw = @net.meta(path, ms)
568
672
  raise ::Asterism::Error, "malformed meta from #{path}" unless raw.is_a?(Hash)
569
673
  else
570
- ::Asterism.profile_async(path, false, nil, ms).raw_value
674
+ @net.profile_async(path, false, nil, ms).raw_value
571
675
  end
572
676
  end
573
677
 
@@ -583,8 +687,8 @@ module Asterism
583
687
  raise ArgumentError, "--kwargs: expected a JSON object or a Ruby Hash" unless kwargs.is_a?(Hash)
584
688
  kwargs = kwargs.transform_keys(&:to_sym)
585
689
  code = 0
586
- connect do |_net, _sv|
587
- px = ::Asterism[path, timeout: @opts[:timeout]]
690
+ connect do |net, _sv|
691
+ px = net[path, timeout: @opts[:timeout]]
588
692
  begin
589
693
  v = px.asterism_call(method, *args, **kwargs)
590
694
  structured? ? emit_line({ "value" => json_safe(v) }) : @out.puts(v.inspect)
@@ -647,11 +751,48 @@ module Asterism
647
751
  "#{paint(n['node'], :node)}#{profile_text(n['profile'])}"
648
752
  end
649
753
 
650
- # An application's status (when it has one) under "status:", indented.
754
+ # An application's status (when it has one) under "status:", and its
755
+ # topics (when it has some) under "topics:", indented.
651
756
  def status_block(app, indent)
652
- return unless app.key?("status")
653
- @out.puts "#{' ' * indent}#{paint('status:', :note)}"
654
- Text.status_lines(json_safe(app["status"]), style.width, indent + 2).each { @out.puts _1 }
757
+ if app.key?("status")
758
+ @out.puts "#{' ' * indent}#{paint('status:', :note)}"
759
+ Text.status_lines(json_safe(app["status"]), style.width, indent + 2).each { @out.puts _1 }
760
+ end
761
+ topics_block(app["topics"], indent)
762
+ end
763
+
764
+ # Topics (Survey.topic_entry) under "topics:", one a line: the name and
765
+ # what topic_about says.
766
+ def topics_block(topics, indent)
767
+ return if topics.nil? || topics.empty?
768
+ pad = " " * indent
769
+ @out.puts "#{pad}#{paint('topics:', :note)}"
770
+ topics.each do |t|
771
+ about = topic_about(t)
772
+ @out.puts "#{pad} #{paint(t['name'], :object)}#{" #{paint(about, :note)}" unless about.empty?}"
773
+ Text.wrap_text(t["desc"], style.width, first: "#{pad} ").each { @out.puts _1 } if t["desc"]
774
+ end
775
+ end
776
+
777
+ # A topic in a few words: its type, then its encoding, unit and
778
+ # "ts" (the sender's time comes along) in parentheses.
779
+ def topic_about(t)
780
+ more = [t["encoding"], t["unit"], t["ts"] ? "ts" : nil].compact
781
+ [t["type"] || "(no type)", more.empty? ? nil : "(#{more.join(', ')})"].compact.join(" ")
782
+ end
783
+
784
+ # An application's own types (Asterism::Types.check) under label:
785
+ # the name, then the fields as name type.
786
+ def types_block(types, indent, label: "types:")
787
+ return if types.nil? || types.empty?
788
+ pad = " " * indent
789
+ @out.puts "#{pad}#{paint(label, :note)}"
790
+ types.sort.each do |name, d|
791
+ @out.puts "#{pad} #{paint(name, :object)}"
792
+ Text.wrap_text(d["d"], style.width, first: "#{pad} ").each { @out.puts _1 } if d["d"]
793
+ fields = d["f"].map { |f, t| "#{f} #{paint(t.is_a?(Integer) ? (::Asterism::Types::NAMES[t - 1] || t.to_s) : t, :note)}" }
794
+ Text.wrap(fields, style.width, first: "#{pad} ", rest: "#{pad} ", sep: " ").each { @out.puts _1 } unless fields.empty?
795
+ end
655
796
  end
656
797
 
657
798
  # The methods' signatures wrapped to the width, indented.