asterism 0.12.0 → 0.13.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: da843ff3a157644e6b93edbcb6d8e7be7f9964af7599bb033d0d5a0b4a3c7757
4
- data.tar.gz: 4d4a45ca03b5615decdef1f9f683550ec670c7a7347b36e9a7411788762935c6
3
+ metadata.gz: 695c668eb3f8c5f24247a577350e62593d3258c1ccba88a2addc5741768ba304
4
+ data.tar.gz: dbbb782677ae81639aba09ae984e370f3749ccdd24ae941deb391a5cb8647f2b
5
5
  SHA512:
6
- metadata.gz: 945450cf13d5343477e9994295e09e0f449d5012a6e4893628b9775b7100261fe60fa6e8e378a67c122c4f2192f8f409e65d650341216f7cd4e9a36c59ed2236
7
- data.tar.gz: dbec4a48913f223c5742068259f78d7bdfe4b92c222e2290379c80a8252741023ce7c1b7598bdff48914e3d39552a3cb7a6ba46a1768a0085f43f00c6e12a73e
6
+ metadata.gz: ad45f8c308b32cd1f079651e7a049624646c8c3369fcd1042821285cbf20967bba2c9750c7eb11b0de1418bea7fb281dc07f95f3ca704e04f0065394e1262f92
7
+ data.tar.gz: 917539dea244fa7a2312da0b0a16b3a1082290f386f46a8d03d99156fd245f20078a099e33d02ead8c17d1888dc0cafc6b0c7a5c546a37276cbb406c5460955c
data/CHANGELOG.md CHANGED
@@ -6,6 +6,12 @@ the earlier ones are only in this repository. From 0.4.0 the two Zenoh
6
6
  bindings (asterism-zenoh, picoruby-asterism-zenoh) carry the same minor
7
7
  version (a patch release of one may come without the other).
8
8
 
9
+ ## 0.13.0
10
+
11
+ - The command line runs inside another program, on that program's connection (README "Inside another program"): `Asterism::CLI.new(net:, stop:, permit:)`. `net:` an `Asterism::Net` already connected (neither started nor closed; what a command subscribes to or hooks onto it is released when it ends), `stop:` ends a streaming command as Ctrl-C does, `permit:` is asked with an `Asterism::CLI::Plan` (the command, `:read` / `:call` / `:local`, the object and method of a call) and may refuse with a reason (`CLI#refused`). Such a command line takes no connection options, runs neither `mcp` nor `completion`, takes long options only in full, prints `--help` to its `out`, and its `__complete` keeps no cache and never exits the process.
12
+ - `lib/asterism/cli/commands.rb`: the command table (`NOUNS`, `COMMANDS`, `ALIASES`, `VALUE_OPTIONS`, `CONNECTION_OPTIONS`, `LOCAL`), `CLI.kind(key, call:)` (what a command does on the network: only `call` and `ping --call` call a method) and `CLI::Plan`, loadable without the Zenoh binding.
13
+ - The command line closes what a command subscribed to (and takes off its `on_join` / `on_leave` blocks) when the command ends, before the connection closes. The output is the same.
14
+
9
15
  ## 0.12.0
10
16
 
11
17
  - `Asterism::Transfer` (`data/transfer/`, `require "asterism/transfer"` on CRuby): a file carried in pieces over calls, resent from the receiver's position after lost, repeated or reordered pieces, a dropped connection or a receiver started again, checked whole by SHA-256. Plain Ruby loaded at run time on the boards (not part of the mrbgem). `rake test:transfer`.
data/README.md CHANGED
@@ -605,6 +605,41 @@ network named on the line (`--router`, `--credentials`, `--peer`) or in
605
605
  - as one more node for a moment (a `cli-` node, or the certificate's name),
606
606
  so `asterism watch` shows it come and go.
607
607
 
608
+ ### Inside another program
609
+
610
+ A program that is connected already (a console's bridge, which shows the
611
+ commands on a page) runs the same commands on its own connection:
612
+
613
+ ```ruby
614
+ require "asterism/cli"
615
+ cli = Asterism::CLI.new(out: io, err: io, env: {}, net: Asterism.net,
616
+ stop: -> { asked_to_stop }, permit: ->(plan) { nil })
617
+ cli.run(%w[node list]) # the exit code; the text went to io
618
+ ```
619
+
620
+ - `net:` the `Asterism::Net` to run on. It is neither started nor closed:
621
+ what a command subscribes to or hooks onto it (watch, echo, hz, get) is
622
+ released when the command ends. Its own application is left out of the
623
+ listings, as the command line's own is.
624
+ - `stop:` asked while a command streams or waits; `true` ends it as
625
+ Ctrl-C does.
626
+ - `permit:` asked once the words are read, with an `Asterism::CLI::Plan`:
627
+ `key` ("node list", "call", ...), `kind` (`:read`; `:call` for `call`
628
+ and `ping --call`, with `path` and `method`; `:local` for `mcp` and
629
+ `completion`), `args`, `options`. It returns nil to go on, or the reason
630
+ the command may not run (printed; `CLI#refused` keeps it).
631
+ - Such a command line takes no `--router`, `--credentials`, `--peer`,
632
+ `--node` or `--app`, never runs `mcp` or `completion`, takes long
633
+ options only as written in full (`--cal` is not `--call`), and prints
634
+ `--help` to `out` (OptionParser's own `--help` / `--version` would print
635
+ to `$stdout` and exit the process). `__complete` asks the connection on
636
+ each Tab and keeps nothing.
637
+ - Colours and width: `out` that answers `tty?` true (and `winsize`) gets
638
+ them, as a terminal does.
639
+ - `require "asterism/cli/commands"` loads the command table alone (the
640
+ nouns, verbs, commands, `CLI.kind`, `CLI::Plan`), without the Zenoh
641
+ binding, for a program that only checks a command line.
642
+
608
643
  ### MCP: Asterism as tools of an AI assistant
609
644
 
610
645
  `asterism mcp` is an MCP server on stdio (it needs the `mcp` gem, which
@@ -0,0 +1,91 @@
1
+ # The command table of the command line (lib/asterism/cli.rb): the nouns
2
+ # and their verbs, the commands without a noun, the older names, and what
3
+ # each command does on the network (it reads, or it calls a method).
4
+ #
5
+ # Plain Ruby with nothing required, so a program that does not load the
6
+ # Zenoh binding (a web server in front of a process that does) can read the
7
+ # table: `require "asterism/cli/commands"`.
8
+ module Asterism
9
+ class CLI
10
+ # The nouns and their verbs: verb => [its arguments, what it does].
11
+ NOUNS = {
12
+ "node" => {
13
+ "list" => ["", "the nodes, a name a line"],
14
+ "info" => ["NODE", "one node: its profile, applications (with their statuses) and objects"]
15
+ },
16
+ "app" => {
17
+ "list" => ["", "the applications, node/app a line"],
18
+ "info" => ["NODE/APP", "one application: its status and its objects"]
19
+ },
20
+ "object" => {
21
+ "list" => ["[PATTERN]", "the objects, node/app/object a line (PATTERN: * and ** for whole parts)"],
22
+ "info" => ["PATH", "one object (node/app/object): its description and its methods"],
23
+ "find" => ["METHOD", "the objects that have the method (* as a wildcard)"],
24
+ "get" => ["PATH [KEY]", "the next value the application puts on PATH/KEY (its own keys; KEY: ** " \
25
+ "by default; --timeout 5.0)"],
26
+ "echo" => ["PATH [KEY]", "the values it puts there as they come (the text: what changed; --once: " \
27
+ "the first; --raw: each whole)"]
28
+ },
29
+ "status" => {
30
+ "get" => ["NODE/APP", "an application's status, now"],
31
+ "echo" => ["NODE/APP", "its status, then each change as it comes (--once: now, once)"],
32
+ "hz" => ["NODE/APP", "how often it changes: the rate, the intervals' min / max / std dev"]
33
+ }
34
+ }.freeze
35
+
36
+ # The commands without a noun: name => [its arguments, what it does].
37
+ COMMANDS = {
38
+ "call" => ["PATH METHOD [ARG...]", "calls a method; each ARG is JSON, else a Ruby literal, else text"],
39
+ "ping" => ["PATH", "round trips: PATH node/app/object (its meta) or node (its profile); " \
40
+ "--call METHOD [ARG...] times a call instead"],
41
+ "watch" => ["", "nodes, applications and objects coming and going, and status changes"],
42
+ "tree" => ["", "nodes > applications (with their status) > objects (--methods: their methods)"],
43
+ "mcp" => ["", "an MCP server on stdio (needs the mcp gem): the listings as tools, and the methods " \
44
+ "--allow names"],
45
+ "completion" => ["bash|zsh", "the shell's Tab completion: source <(asterism completion bash)"],
46
+ "version" => ["", "the gem's version"]
47
+ }.freeze
48
+
49
+ # The older names, kept with their output.
50
+ ALIASES = {
51
+ "nodes" => "the nodes, their applications (with their statuses) and profiles, in one listing",
52
+ "objects" => "[PATTERN] the objects with their descriptions and methods (object info of each)",
53
+ "echo" => "ping"
54
+ }.freeze
55
+
56
+ # The options that take a value (what __complete skips over).
57
+ VALUE_OPTIONS = %w[--router --credentials --peer --node --app -o --output --timeout --settle --duration --count
58
+ --interval --call --kwargs --allow --period --window].freeze
59
+
60
+ # The options that say where the network is and who this command line
61
+ # is on it. A command line given a connection (CLI.new(net:)) has none.
62
+ CONNECTION_OPTIONS = %w[--router --credentials --peer --node --app].freeze
63
+
64
+ # The commands that act here rather than on the network: an MCP server
65
+ # on stdio, a script for the shell. A command line given a connection
66
+ # does not run them.
67
+ LOCAL = %w[mcp completion].freeze
68
+
69
+ # What a command does on the network. Every command only reads (the
70
+ # tokens, metas, profiles, statuses, the values the applications put),
71
+ # except call, and ping with --call: those run a method of an object.
72
+ #
73
+ # :call path:, method: say which
74
+ # :read it only reads
75
+ # :local it acts here (LOCAL)
76
+ #
77
+ # key: "node list", "call", "ping", ...; call: ping's --call METHOD.
78
+ def self.kind(key, call: nil)
79
+ return :local if LOCAL.include?(key)
80
+ return :call if key == "call"
81
+ return :call if %w[ping echo].include?(key) && call
82
+ :read
83
+ end
84
+
85
+ # What a command line is about to do, once its words are read (before
86
+ # it connects): the command, its kind (CLI.kind), the object and the
87
+ # method it calls (kind :call), its positional arguments and options.
88
+ # What CLI.new(permit:) is asked about.
89
+ Plan = Struct.new(:key, :kind, :path, :method, :args, :options, keyword_init: true)
90
+ end
91
+ end
@@ -126,8 +126,8 @@ module Asterism
126
126
  code = 0
127
127
  connect do |net, _sv|
128
128
  q = Queue.new
129
- net.session.subscribe(Values.key_expr(pattern), depth: 16) { |s| q << [s.key, s.payload, Time.now] }
130
- got = q.pop(timeout: wait)
129
+ hold net.session.subscribe(Values.key_expr(pattern), depth: 16) { |s| q << [s.key, s.payload, Time.now] }
130
+ got = pop_until(q, wait)
131
131
  if got.nil?
132
132
  @err.puts nothing_came(pattern, wait)
133
133
  code = 1
@@ -151,7 +151,7 @@ module Asterism
151
151
  code = 0
152
152
  connect do |net, _sv|
153
153
  q = Queue.new
154
- net.session.subscribe(Values.key_expr(pattern), depth: 256) { |s| q << [s.key, s.payload, Time.now] }
154
+ hold net.session.subscribe(Values.key_expr(pattern), depth: 256) { |s| q << [s.key, s.payload, Time.now] }
155
155
  seen = 0
156
156
  last = {}
157
157
  until_stopped(net) do |left|
@@ -283,7 +283,8 @@ module Asterism
283
283
  @out.flush
284
284
  # A connection still trying past the budget is left behind: the
285
285
  # process ends without waiting for it.
286
- Process.exit!(0) if @complete_abandoned
286
+ # (Not when it runs on a connection given to it: the program goes on.)
287
+ Process.exit!(0) if @complete_abandoned && !embedded?
287
288
  0
288
289
  end
289
290
 
@@ -315,7 +316,10 @@ module Asterism
315
316
 
316
317
  private
317
318
 
319
+ # On a connection given to the command line: asked every time (its
320
+ # program keeps what it needs; nothing is written here).
318
321
  def cached(entry, &blk)
322
+ return blk.call if @cli.embedded?
319
323
  net = @cli.complete_network(@words)
320
324
  return nil if net.none?
321
325
  dir = Complete::Cache.dir(@cli.env)
@@ -439,10 +443,10 @@ module Asterism
439
443
 
440
444
  # The status's puts of one application, cleaned (Status.parse).
441
445
  def subscribe_status(net, path)
442
- net.session.subscribe("asterism/#{path}/@status") do |sample|
446
+ hold(net.session.subscribe("asterism/#{path}/@status") do |sample|
443
447
  got = ::Asterism::Status.parse(sample.key, sample.payload)
444
448
  yield got[2] if got
445
- end
449
+ end)
446
450
  end
447
451
 
448
452
  # Yields until Ctrl-C, --duration or a lost connection (the seconds
@@ -453,10 +457,23 @@ module Asterism
453
457
  left = deadline && (deadline - now)
454
458
  break if left && left <= 0
455
459
  break unless net.connected?
460
+ break if stopped?
456
461
  yield left
457
462
  end
458
463
  end
459
464
 
465
+ # The next item of the queue within seconds (nil: none came, or stop:
466
+ # asked to end first).
467
+ def pop_until(queue, seconds)
468
+ deadline = now + seconds
469
+ loop do
470
+ left = deadline - now
471
+ return nil if left <= 0 || stopped?
472
+ got = queue.pop(timeout: [left, 0.2].min)
473
+ return got if got
474
+ end
475
+ end
476
+
460
477
  def now
461
478
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
462
479
  end
data/lib/asterism/cli.rb CHANGED
@@ -21,10 +21,29 @@
21
21
  # and reads what docs/protocol.md lets anyone read. It calls a method only
22
22
  # with `call` (and the MCP bridge only the methods --allow names). What it
23
23
  # can see is what the router lets it see: with a console's .tar, its role.
24
+ #
25
+ # Inside another program (a console's bridge) it runs on that program's
26
+ # connection instead of opening one:
27
+ #
28
+ # cli = Asterism::CLI.new(out: io, err: io, env: {}, net: Asterism.net,
29
+ # stop: -> { asked_to_stop }, permit: ->(plan) { nil })
30
+ # cli.run(%w[node list])
31
+ #
32
+ # net: the Asterism::Net to use (it is neither started nor closed here; what
33
+ # a command subscribes to or hooks onto it is released when the command
34
+ # ends); stop: asked often while a command streams (watch, echo, hz, get,
35
+ # ping), true ends it as Ctrl-C does; permit: asked once the words are read
36
+ # (an Asterism::CLI::Plan: the command, whether it reads or calls, the
37
+ # object and method it calls), returns nil to go on or the reason it may
38
+ # not (printed; CLI#refused keeps it). Such a command line takes no
39
+ # --router / --credentials / --peer / --node / --app, runs neither mcp nor
40
+ # completion, takes long options only as written in full, and prints
41
+ # --help to its out.
24
42
  require "asterism"
25
43
  require "optparse"
26
44
  require "json"
27
45
  require "securerandom"
46
+ require_relative "cli/commands"
28
47
  require_relative "cli/literal"
29
48
  require_relative "cli/survey"
30
49
  require_relative "cli/allow"
@@ -35,56 +54,6 @@ require_relative "cli/values"
35
54
 
36
55
  module Asterism
37
56
  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
57
  def self.usage
89
58
  col = 30
90
59
  line = lambda do |name, args, what|
@@ -130,20 +99,38 @@ module Asterism
130
99
  new(out: out, err: err, env: env).run(argv.dup)
131
100
  end
132
101
 
133
- def initialize(out: $stdout, err: $stderr, env: ENV)
102
+ # The reason permit: gave for not running the command (nil: it ran).
103
+ attr_reader :refused
104
+
105
+ def initialize(out: $stdout, err: $stderr, env: ENV, net: nil, stop: nil, permit: nil)
134
106
  @out = out
135
107
  @err = err
136
108
  @env = env
109
+ @given_net = net
110
+ @stop = stop
111
+ @permit = permit
112
+ @held = []
137
113
  @lock = Mutex.new
138
114
  @last_status = {}
139
115
  @opts = { timeout: 2.0, settle: 1.5, format: nil, count: 5, interval: 0.2, allow: [], period: 1.0,
140
116
  window: 1000 }
141
117
  end
142
118
 
119
+ # Whether this command line runs on a connection it was given (net:).
120
+ def embedded?
121
+ !@given_net.nil?
122
+ end
123
+
124
+ # Whether stop: asks the command to end.
125
+ def stopped?
126
+ @stop ? @stop.call : false
127
+ end
128
+
143
129
  def run(argv)
144
130
  cmd = argv.shift
145
131
  case cmd
146
132
  when nil, "help", "-h", "--help"
133
+ return 2 unless permitted?(Plan.new(key: "help", kind: :read, args: argv.dup, options: {}))
147
134
  if cmd == "help" && NOUNS.key?(argv.first)
148
135
  @out.puts CLI.noun_usage(argv.first)
149
136
  return 0
@@ -151,9 +138,11 @@ module Asterism
151
138
  @out.puts USAGE
152
139
  return cmd.nil? ? 2 : 0
153
140
  when "version", "--version", "-v"
141
+ return 2 unless permitted?(Plan.new(key: "version", kind: :read, args: [], options: {}))
154
142
  @out.puts "asterism #{::Asterism::VERSION}"
155
143
  return 0
156
144
  when "__complete"
145
+ return 2 unless permitted?(Plan.new(key: "__complete", kind: :read, args: argv.dup, options: {}))
157
146
  return cmd_complete(argv)
158
147
  end
159
148
  key = cmd
@@ -173,8 +162,10 @@ module Asterism
173
162
  @err.puts "asterism: unknown command #{cmd.inspect}\n\n#{USAGE}"
174
163
  return 2
175
164
  end
165
+ return embedded_run(key, argv) if embedded?
176
166
  rest = parser(key).parse(argv)
177
- send("cmd_#{key == 'echo' ? 'ping' : key.tr(' ', '_')}", rest)
167
+ return 2 unless permitted?(plan(key, rest))
168
+ run_command(key, rest)
178
169
  rescue OptionParser::ParseError, ArgumentError => e
179
170
  @err.puts "asterism: #{e.message}"
180
171
  2
@@ -188,17 +179,70 @@ module Asterism
188
179
  0
189
180
  end
190
181
 
182
+ def run_command(key, rest)
183
+ send("cmd_#{key == 'echo' ? 'ping' : key.tr(' ', '_')}", rest)
184
+ end
185
+
186
+ # A command on the connection given (net:): no connection options, no
187
+ # mcp or completion, --help printed to out (see the top of this file).
188
+ def embedded_run(key, argv)
189
+ if LOCAL.include?(key)
190
+ return 2 unless permitted?(Plan.new(key: key, kind: :local, args: argv.dup, options: {}))
191
+ raise ArgumentError, "#{key} runs only as a program of its own (asterism #{key})"
192
+ end
193
+ words = argv.take_while { _1 != "--" }
194
+ given = words.find { CONNECTION_OPTIONS.include?(_1.split("=", 2)[0]) }
195
+ raise ArgumentError, "#{given.split('=', 2)[0]}: this command line runs on the connection it was given" if given
196
+ if words.any? { %w[-h --help].include?(_1) }
197
+ @out.puts parser(key).help
198
+ return 0
199
+ end
200
+ rest = parser(key).parse(argv)
201
+ return 2 unless permitted?(plan(key, rest))
202
+ run_command(key, rest)
203
+ end
204
+
205
+ # The Plan of a command whose words were read (rest: its positional
206
+ # arguments).
207
+ def plan(key, rest)
208
+ kind = CLI.kind(key, call: @opts[:call])
209
+ path = rest[0]
210
+ method = kind == :call ? (key == "call" ? rest[1] : @opts[:call]) : nil
211
+ Plan.new(key: key, kind: kind, path: path, method: method, args: rest.dup,
212
+ options: @opts.reject { |k, _| k == :allow }.merge(allow: @opts[:allow].dup))
213
+ end
214
+
215
+ # Asks permit: (when given) about the plan; prints the reason it gives.
216
+ def permitted?(plan)
217
+ return true unless @permit
218
+ why = @permit.call(plan)
219
+ return true if why.nil?
220
+ @refused = why.to_s
221
+ @err.puts "asterism: #{@refused}"
222
+ false
223
+ end
224
+
191
225
  # The options of a command (key: "tree", "node info", ...).
192
226
  def parser(key)
193
227
  OptionParser.new do |o|
194
228
  args = (NOUNS.dig(*key.split(" ")) || COMMANDS[key] || [""])[0]
195
229
  o.banner = "Usage: asterism #{key} #{args} [options]".squeeze(" ")
230
+ if embedded?
231
+ # Long options only as written in full (no --cal for --call), and
232
+ # none of OptionParser's own (--help, --version, the completion
233
+ # scripts): they print to $stdout and exit the process.
234
+ o.require_exact = true
235
+ o.base.long.clear
236
+ o.base.short.clear
237
+ end
196
238
  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 }
239
+ unless embedded?
240
+ o.on("--router LOCATOR", "a router (tcp/HOST:7447)") { @opts[:router] = _1 }
241
+ o.on("--credentials TAR", "a console's .tar") { @opts[:credentials] = _1 }
242
+ o.on("--peer LOCATOR", "a direct peer link to a node listening there (no router)") { @opts[:peer] = _1 }
243
+ o.on("--node NAME", "this node's ID (default: the certificate's name, or cli-<6 hex>)") { @opts[:node] = _1 }
244
+ o.on("--app NAME", "this application's name (default: cli-<4 hex>)") { @opts[:app] = _1 }
245
+ end
202
246
  unless key == "mcp"
203
247
  o.on("-o", "--output FORMAT", %w[json yaml], "json or yaml instead of text (the same content)") do
204
248
  @opts[:format] = _1.to_sym
@@ -297,7 +341,8 @@ module Asterism
297
341
 
298
342
  # Connects, starts the receiving thread, waits for the tokens and yields
299
343
  # the Net and a Survey.
300
- def connect(app_prefix: "cli")
344
+ def connect(app_prefix: "cli", &blk)
345
+ return connect_given(&blk) if embedded?
301
346
  router, creds, peer = network
302
347
  if router.nil? && creds.nil? && peer.nil?
303
348
  raise ArgumentError, "where is the network? --router tcp/HOST:7447 or --credentials FILE.tar " \
@@ -319,7 +364,42 @@ module Asterism
319
364
  net.start
320
365
  survey = Survey.new(timeout: @opts[:timeout])
321
366
  survey.settle(@opts[:settle])
322
- yield net, survey
367
+ begin
368
+ yield net, survey
369
+ ensure
370
+ release_held
371
+ end
372
+ end
373
+ end
374
+
375
+ # The connection given (net:): yields it and a Survey; nothing is
376
+ # started, waited for or closed (its tokens are known already). What
377
+ # the command subscribed to or hooked onto it is released at the end.
378
+ def connect_given
379
+ raise ::Asterism::Disconnected, "the connection is not there" unless @given_net.connected?
380
+ yield @given_net, Survey.new(timeout: @opts[:timeout])
381
+ ensure
382
+ release_held
383
+ end
384
+
385
+ # Something a command keeps until it ends (released when it does): a
386
+ # subscription or liveliness watch (closed), or [:join / :leave, block]
387
+ # given to on_join / on_leave (taken off). Returns it.
388
+ def hold(thing)
389
+ @lock.synchronize { @held << thing }
390
+ thing
391
+ end
392
+
393
+ def release_held
394
+ held = @lock.synchronize { @held.slice!(0..) }
395
+ held.reverse_each do |h|
396
+ case h
397
+ in [:join, blk] then (@given_net || ::Asterism).off_join(blk)
398
+ in [:leave, blk] then (@given_net || ::Asterism).off_leave(blk)
399
+ else h.close
400
+ end
401
+ rescue StandardError
402
+ nil
323
403
  end
324
404
  end
325
405
 
@@ -427,25 +507,25 @@ module Asterism
427
507
  connect do |net, sv|
428
508
  own = "#{net.node_id}/#{net.app}"
429
509
  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|
510
+ net.on_join(&hold([:join, proc { |n| event("join", n, what: "node") }])[1])
511
+ net.on_leave(&hold([:leave, proc { |n| event("leave", n, what: "node") }])[1])
512
+ hold(net.session.liveliness_watch("asterism/**") do |key, alive|
433
513
  # The tokens alive at the start come first, in one burst: not news.
434
514
  next unless @watch_started
435
515
  path = key.delete_prefix("asterism/")
436
516
  next if path == own || path.start_with?("#{own}/")
437
517
  what = { 2 => "app", 3 => "object" }[path.count("/") + 1]
438
518
  event(alive ? "join" : "leave", path, what: what) if what
439
- end
440
- net.session.subscribe(Survey::STATUS_ALL) do |sample|
519
+ end)
520
+ hold(net.session.subscribe(Survey::STATUS_ALL) do |sample|
441
521
  got = ::Asterism::Status.parse(sample.key, sample.payload)
442
522
  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|
523
+ end)
524
+ hold(net.session.subscribe(Survey::PROFILES_ALL) do |sample|
445
525
  node = sample.key.split("/")[1]
446
526
  pr = ::Asterism::Profile.check(::Asterism::Codec.unpack(sample.payload))
447
527
  event("profile", node, profile: pr) if pr && node != net.node_id
448
- end
528
+ end)
449
529
  sleep 0.3
450
530
  @watch_started = true
451
531
  @err.puts "asterism: watching (Ctrl-C to stop)" unless structured?
@@ -453,6 +533,7 @@ module Asterism
453
533
  loop do
454
534
  break if deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
455
535
  break unless net.connected?
536
+ break if stopped?
456
537
  sleep 0.05
457
538
  end
458
539
  end
@@ -533,7 +614,8 @@ module Asterism
533
614
  connect do |_net, _sv|
534
615
  ms = (@opts[:timeout] * 1000).round
535
616
  @opts[:count].times do |i|
536
- sleep @opts[:interval] if i.positive?
617
+ break if stopped?
618
+ pause(@opts[:interval]) if i.positive?
537
619
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
538
620
  ok = begin
539
621
  ping_once(path, chunks, args, ms)
@@ -560,6 +642,16 @@ module Asterism
560
642
  times.empty? ? 1 : 0
561
643
  end
562
644
 
645
+ # Sleeps for seconds, or until stop: asks to end.
646
+ def pause(seconds)
647
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
648
+ loop do
649
+ left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
650
+ break if left <= 0 || stopped?
651
+ sleep [left, 0.1].min
652
+ end
653
+ end
654
+
563
655
  def ping_once(path, chunks, args, ms)
564
656
  if @opts[:call]
565
657
  ::Asterism[path, timeout_ms: ms].asterism_call(@opts[:call], *args)
@@ -3,5 +3,5 @@ module Asterism
3
3
  # is in asterism.gemspec (asterism-zenoh ~> 0.4.0 for 0.5.0 to 0.7.0:
4
4
  # the bindings did not change; see CHANGELOG.md). 0.7.0 speaks wire
5
5
  # protocol 1 only (Asterism::PROTOCOL, docs/protocol.md).
6
- VERSION = "0.12.0"
6
+ VERSION = "0.13.0"
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: asterism
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.12.0
4
+ version: 0.13.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Katsuhiko Kageyama
@@ -149,6 +149,7 @@ files:
149
149
  - lib/asterism.rb
150
150
  - lib/asterism/cli.rb
151
151
  - lib/asterism/cli/allow.rb
152
+ - lib/asterism/cli/commands.rb
152
153
  - lib/asterism/cli/complete.rb
153
154
  - lib/asterism/cli/hz.rb
154
155
  - lib/asterism/cli/literal.rb