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/mrblib/asterism.rb CHANGED
@@ -1,45 +1,72 @@
1
1
  # Asterism: Ruby objects on other machines, called like local ones.
2
2
  #
3
- # Asterism.connect("tcp/192.0.2.2:7447", node: "fmruby-bbbbbb", app: "demo")
4
- # Asterism.expose("apu", apu, methods: [:play, :stop])
5
- # p = Asterism["linux/demo/apu"] # <node>/<app>/<object>
3
+ # net = Asterism.connect("tcp/192.0.2.2:7447", node: "fmruby-bbbbbb", app: "demo")
4
+ # net.expose("apu", apu, methods: [:play, :stop])
5
+ # p = net["linux/demo/apu"] # <node>/<app>/<object>
6
6
  # p.play("cde") # waits for the answer (2 s by default;
7
- # # Asterism["...", timeout: 5.0])
8
- # Asterism.poll # call regularly (answers incoming calls)
7
+ # # net["...", timeout: 5.0])
8
+ # net.poll # call regularly (answers incoming calls)
9
9
  #
10
- # Keys and payloads: protocol 1 (docs/protocol.md):
10
+ # A connection (an Asterism::Connection) is one application: its Zenoh
11
+ # session, its liveliness token, its objects, its status, topics and types,
12
+ # its own profile. A program may hold several (one per application it is),
13
+ # also as the same node:
14
+ #
15
+ # game = Asterism.connect(router, node: "host", app: "games")
16
+ # room = Asterism.connect(router, node: "host", app: "room01")
17
+ # Asterism.poll_all # or game.poll and room.poll
18
+ #
19
+ # On a board each connection costs a TLS link and a router seat
20
+ # (docs/protocol.md 1.1); one is the usual.
21
+ #
22
+ # Keys and payloads: protocol 2 (docs/protocol.md):
11
23
  # asterism/<node>/<app>/<object>/call/<caller>
12
- # get: {"method" => name, "args" => [...], "kwargs" => {...}}
24
+ # get: {"method" => name, "protocol" => 2, "args" => [...],
25
+ # "kwargs" => {...}}
13
26
  # reply {"value" => v} or
14
27
  # {"error" => {"kind" => k, "class" => c, "message" => m}}
15
28
  # asterism/<node>/<app>/<object>/meta
16
29
  # get: reply {"methods" => [{"name" => n, "arity" => a,
17
30
  # "args" => [...], "doc" => "..."}, ...], "doc" => "..."}
18
- # asterism/<node>/<app> liveliness: the application is up
31
+ # asterism/<node>/<app>/protocol/2 liveliness: the application is up, and
32
+ # the protocol it speaks
19
33
  # asterism/<node>/<app>/<object> liveliness: the object is exposed
20
34
  # asterism/<node>/@profile get: reply the node's profile (profile.rb)
21
- # asterism/<node>/<app>/@status get: reply the application's status (status.rb)
35
+ # asterism/<node>/<app>/@profile get: reply the application's own profile, its
36
+ # status, topics and types (status.rb, topic.rb)
37
+ # asterism/<node>/<app>/@status put: the application's status when it changes
38
+ # asterism/<node>/<app>/@pubs put: the application's topics when they change
39
+ # asterism/<node>/<app>/<name> put: a value of a topic (Connection#publish)
22
40
  #
23
41
  # Everything is polled: nothing runs behind the application's back. A call
24
42
  # that waits for its answer keeps polling meanwhile and answers the calls
25
- # that come in, so two machines calling each other do not lock up.
43
+ # that come in (on every connection of the program), so two machines, or
44
+ # two connections of one program, calling each other do not lock up.
26
45
  module Asterism
27
46
  ROOT = "asterism"
28
47
  # The version of the wire protocol this implementation speaks (and the
29
- # only one: protocol 0, the 0.x releases before 0.7.0, is not spoken).
30
- PROTOCOL = 1
31
- # The time limit of a call (Asterism[path] without timeout:), in seconds
32
- # and in milliseconds.
48
+ # only one: protocol 1 and protocol 0 are not spoken).
49
+ PROTOCOL = 2
50
+ # The chunk before the protocol's number in an application's token,
51
+ # asterism/<node>/<app>/protocol/<n> (docs/protocol.md 6.1).
52
+ PROTOCOL_CHUNK = "protocol"
53
+ # The time limit of a call (net[path] without timeout:), in seconds and
54
+ # in milliseconds.
33
55
  DEFAULT_TIMEOUT = 2.0
34
56
  DEFAULT_TIMEOUT_MS = 2000
35
57
  # How long Asterism.connect looks for another copy of the same
36
58
  # <node>/<app> (check_timeout:), in seconds.
37
59
  CHECK_TIMEOUT = 1.5
38
60
  # Waits that may be open inside each other (a call answered while waiting
39
- # that itself calls and waits, and so on).
61
+ # that itself calls and waits, and so on), over all the connections of
62
+ # the program: they share one stack.
40
63
  MAX_NESTING = 4
41
64
  # Pause between polls while a call waits (ms).
42
65
  WAIT_STEP_MS = 2
66
+ # The longest doc text (bytes) and the most argument names a method may
67
+ # tell in its meta (docs/protocol.md 5).
68
+ DOC_MAX = 2048
69
+ ARGS_MAX = 16
43
70
 
44
71
  # Every Asterism error is an Asterism::Error (the Zenoh bindings define
45
72
  # it; Asterism::Zenoh::Error and the ROS errors are under it too).
@@ -75,7 +102,7 @@ module Asterism
75
102
  end
76
103
  end
77
104
 
78
- # What Asterism.current_call returns while an exposed method runs for a
105
+ # What Connection#current_call returns while an exposed method runs for a
79
106
  # call: who called and what. from is the calling node's ID (a String),
80
107
  # verified how far that is checked: :claimed (the caller named itself in
81
108
  # the call's key; a router's access control is what makes the name
@@ -201,6 +228,13 @@ module Asterism
201
228
  s
202
229
  end
203
230
 
231
+ # Whether s can be a node, app or object name (check_name without raising).
232
+ # @api private
233
+ def self.valid_name?(s)
234
+ return false if s.nil? || s.empty? || s.start_with?("@")
235
+ !(s.include?("/") || s.include?("*") || s.include?("$") || s.include?("?") || s.include?("#"))
236
+ end
237
+
204
238
  # "node/app/object" -> [node, app, object]
205
239
  # @api private
206
240
  def self.split_path(path)
@@ -237,192 +271,217 @@ module Asterism
237
271
  j == parts.size
238
272
  end
239
273
 
240
- # ------------------------------------------------------------ connection
241
-
242
- # Opens the connection. locator, mode: and listen: go to
243
- # Asterism::Zenoh::Session.open (client of a router by default; mode: :peer
244
- # with or without listen: for no router), and so do config: (a Hash of
245
- # "key/path" => value or a JSON5 String, e.g. TLS certificates; the boards
246
- # take the TLS keys only) and connect_timeout: (seconds; CRuby's
247
- # asterism-zenoh only, the boards raise ArgumentError) when they are given.
248
- # credentials: a .tar from an Asterism console (Asterism::Credentials, a
249
- # path or a loaded one): its certificates go to zenoh (mutual TLS), and
250
- # locator and node: default to its router and name. node: is this
251
- # machine's ID and app: this application's name. check_timeout: how long
252
- # to look for another copy of the same <node>/<app> (seconds,
253
- # CHECK_TIMEOUT). Raises Disconnected when it cannot connect, and Error
254
- # when the same <node>/<app> is already on the network.
274
+ # ------------------------------------------------------------ connections
275
+
276
+ # Opens a connection: one application on the network, and returns it (an
277
+ # Asterism::Connection; its methods are the whole API: expose, [],
278
+ # poll, status, publish, subscribe, close, ...). locator, mode: and
279
+ # listen: go to Asterism::Zenoh::Session.open (client of a router by
280
+ # default; mode: :peer with or without listen: for no router), and so do
281
+ # config: (a Hash of "key/path" => value or a JSON5 String, e.g. TLS
282
+ # certificates; the boards take the TLS keys only) and connect_timeout:
283
+ # (seconds; CRuby's asterism-zenoh only, the boards raise ArgumentError)
284
+ # when they are given. credentials: a .tar from an Asterism console
285
+ # (Asterism::Credentials, a path or a loaded one): its certificates go to
286
+ # zenoh (mutual TLS), and locator and node: default to its router and
287
+ # name. node: is this machine's ID and app: this application's name.
288
+ # check_timeout: how long to look for another copy of the same
289
+ # <node>/<app> (seconds, CHECK_TIMEOUT). Raises Disconnected when it
290
+ # cannot connect, and Error when the same <node>/<app> is already on the
291
+ # network (or open in this program).
292
+ #
293
+ # A program may open several connections, each its own application
294
+ # (another app:, the same node: or another). Each has its own Zenoh
295
+ # session: on a board, a TLS link and a router seat each.
255
296
  def self.connect(locator = nil, node: nil, app:, mode: nil, listen: nil, config: nil, connect_timeout: nil,
256
297
  check_timeout: nil, credentials: nil)
257
- raise Error, "already connected (Asterism.close first)" if connected?
258
- if credentials
259
- locator, config, creds = Credentials.merge(credentials, locator, config)
260
- node ||= creds.name
261
- end
262
- release
263
- node = check_name("node", node)
264
- app = check_name("app", app)
265
- check_ms = time_ms("Asterism.connect check_timeout:", check_timeout, nil, nil, (CHECK_TIMEOUT * 1000).round)
266
- opts = { mode: mode, listen: listen }
267
- opts[:config] = config unless config.nil?
268
- opts[:connect_timeout] = connect_timeout unless connect_timeout.nil?
269
- begin
270
- s = Asterism::Zenoh::Session.open(locator, **opts)
271
- rescue Asterism::Zenoh::Error => e
272
- raise Disconnected, e.message
298
+ Connection.new(locator, node: node, app: app, mode: mode, listen: listen, config: config,
299
+ connect_timeout: connect_timeout, check_timeout: check_timeout,
300
+ credentials: credentials)
301
+ end
302
+
303
+ # The connections of this program that are open, or lost with their
304
+ # on_leave blocks still to be told (in the order they were opened).
305
+ def self.connections
306
+ (@connections || []).dup
307
+ end
308
+
309
+ # Polls every connection of this program (Connection#poll each). True
310
+ # while one of them is connected.
311
+ def self.poll_all
312
+ list = connections
313
+ any = false
314
+ i = 0
315
+ while i < list.size
316
+ any = true if list[i].poll
317
+ i += 1
273
318
  end
274
- begin
275
- if already_there?(s, node, app, check_ms)
276
- s.close
277
- raise Error, "#{node}/#{app} is already on the network"
319
+ any
320
+ end
321
+
322
+ # @api private
323
+ def self.register(conn)
324
+ (@connections ||= []) << conn
325
+ end
326
+
327
+ # @api private
328
+ def self.unregister(conn)
329
+ list = @connections
330
+ return unless list
331
+ i = 0
332
+ while i < list.size
333
+ if list[i].equal?(conn)
334
+ list.delete_at(i)
335
+ else
336
+ i += 1
278
337
  end
279
- @app_token = s.liveliness("#{ROOT}/#{node}/#{app}")
280
- @queryable = s.queryable("#{ROOT}/#{node}/#{app}/**", depth: 32)
281
- @watch = s.liveliness_watch("#{ROOT}/**", depth: watch_depth)
282
- @profile_queryable = s.queryable("#{ROOT}/#{node}/#{Profile::KEY}", depth: 4)
283
- rescue Asterism::Zenoh::Error => e
284
- s.close
285
- raise Disconnected, e.message
286
- end
287
- s.extend(SharedSession) # Asterism.session: the application's close does not close it
288
- @session = s
289
- @node = node
290
- @app = app
291
- @objects = {} # name => [object, {method name => arity}, token, caller keyword or nil,
292
- # {method name => meta fields}, the object's doc or nil]
293
- @alive = {} # "node/app/object" => node (from liveliness)
294
- @apps = {} # "node/app" => node (from liveliness)
295
- @proxies = {}
296
- @depth = 0
297
- @lost = nil
298
- @known = [] # the other nodes told to on_join so far
299
- @known_set = {} # the same, as node => true
300
- @known_apps = {} # "node/app" => true: the other applications told to on_app_join
301
- @node_list = [node] # what nodes returns (this node first), rebuilt on a change
302
- @nodes_changed = false # liveliness changed since tell_nodes last compared
303
- @was_reconnecting = false
304
- @status_put = nil
305
- tell_profile # for those who follow the profiles (the reply is the queryable's)
306
- tell_status(true) # a status set before connecting (status.rb)
307
- self
338
+ end
308
339
  end
309
340
 
310
- # Whether node/app is alive already (its application token or an object:
311
- # a second copy of the same application). Waits for the answer (a router answers at once), at
312
- # most check_ms. @api private
313
- def self.already_there?(s, node, app, check_ms = 1500)
314
- get_ms = check_ms > 1000 ? check_ms - 500 : check_ms
315
- g = s.liveliness_get("#{ROOT}/#{node}/#{app}/**", timeout_ms: get_ms)
316
- t0 = now_ms
317
- found = false
318
- while true
319
- s.poll
320
- ended = g.done? # before taking the replies (see Future#collect)
321
- found = true if g.each_reply.size > 0
322
- break if found || ended || now_ms - t0 > check_ms
323
- pause(WAIT_STEP_MS)
324
- end
325
- found
341
+ # The connected connection of node/app in this program, or nil.
342
+ # @api private
343
+ def self.connection_of(node, app)
344
+ list = @connections || []
345
+ i = 0
346
+ while i < list.size
347
+ c = list[i]
348
+ return c if c.node_id == node && c.app == app && c.connected?
349
+ i += 1
350
+ end
351
+ nil
326
352
  end
327
353
 
328
- def self.connected?
329
- return false if @session.nil?
330
- if @session.closed?
331
- lost("the connection was lost")
332
- return false
354
+ # Reserves node/app for a connection being opened: Error when a
355
+ # connection of this program has it, or is being opened with it.
356
+ # @api private
357
+ def self.claim(node, app)
358
+ path = "#{node}/#{app}"
359
+ claims = (@claims ||= {})
360
+ if connection_of(node, app) || claims[path]
361
+ raise Error, "#{path} is already connected in this program"
333
362
  end
334
- true
363
+ claims[path] = true
335
364
  end
336
365
 
337
- # True while the connection is lost and the Zenoh binding opens it again
338
- # by itself (a client of a router: zenoh-pico built with reconnection on
339
- # the boards, zenoh-c on CRuby). connected? stays true meanwhile, and once
340
- # the router is back everything declared before is there again: the
341
- # application token, the exposed objects, the liveliness watch, and what
342
- # the application declared on Asterism.session. Meanwhile the other nodes
343
- # leave (on_leave) and join again after it, calls raise Disconnected or
344
- # time out, and puts reach nobody.
345
- def self.reconnecting?
346
- s = @session
347
- return false if s.nil?
348
- s.respond_to?(:reconnecting?) ? s.reconnecting? : false
366
+ # @api private
367
+ def self.unclaim(node, app)
368
+ @claims.delete("#{node}/#{app}") if @claims
349
369
  end
350
370
 
351
- def self.node_id
352
- @node
371
+ # The key of the application token of node/app: it says the protocol the
372
+ # application speaks (docs/protocol.md 6.1).
373
+ # @api private
374
+ def self.app_token_key(node, app)
375
+ "#{ROOT}/#{node}/#{app}/#{PROTOCOL_CHUNK}/#{PROTOCOL}"
353
376
  end
354
377
 
355
- def self.app
356
- @app
378
+ # The protocol an application token says, from its chunks after
379
+ # "asterism/": [node, app, "protocol", "<n>"] says n; [node, app] (the
380
+ # token of protocol 1, which had no number) says 1; anything else is not
381
+ # an application token (nil).
382
+ # @api private
383
+ def self.token_protocol(parts)
384
+ return 1 if parts.size == 2
385
+ return nil unless parts.size == 4 && parts[2] == PROTOCOL_CHUNK
386
+ digits(parts[3])
357
387
  end
358
388
 
359
- # Why the connection went away (nil while connected or after close).
360
- def self.lost_reason
361
- @lost
389
+ # The non-negative Integer a chunk of decimal digits says (no sign, no
390
+ # leading zero, at most 9 digits), or nil. Without a Regexp (PicoRuby
391
+ # has none).
392
+ # @api private
393
+ def self.digits(s)
394
+ return nil if s.nil? || s.empty? || s.size > 9
395
+ return nil if s.size > 1 && s[0] == "0"
396
+ n = 0
397
+ i = 0
398
+ while i < s.size
399
+ c = s.getbyte(i)
400
+ return nil if c < 48 || c > 57
401
+ n = n * 10 + (c - 48)
402
+ i += 1
403
+ end
404
+ n
362
405
  end
363
406
 
364
- # Closes the connection (and with it every exposed object), and forgets
365
- # the on_join / on_leave blocks. Idempotent.
366
- def self.close
367
- release
368
- @known = nil
369
- @known_apps = nil
370
- @on_join = nil
371
- @on_leave = nil
372
- @on_app_join = nil
373
- @on_app_leave = nil
374
- nil
407
+ # A new run id (docs/protocol.md 9.3): 16 random bits. Kernel#rand where
408
+ # there is one (CRuby; mruby-random; PicoRuby's picoruby-rng, on the
409
+ # boards their hardware generator); otherwise the clock mixed with salt
410
+ # (a connection's object_id).
411
+ # @api private
412
+ def self.new_run_id(salt = 0)
413
+ begin
414
+ return rand(65536)
415
+ rescue NoMethodError
416
+ nil
417
+ end
418
+ (now_ms % 65536 + (salt % 65536) * 251) % 65536
375
419
  end
376
420
 
421
+ # Says msg once per key (a String) on the program's warning output.
377
422
  # @api private
378
- def self.release
379
- s = @session
380
- @session = nil
381
- @objects = {}
382
- @alive = {}
383
- @apps = {}
384
- @node_list = nil
385
- @nodes_changed = true
386
- @proxies = {}
387
- if s
388
- @releasing = s
389
- begin
390
- s.close
391
- ensure
392
- @releasing = nil
393
- end
423
+ def self.warn_text_once(key, msg)
424
+ told = (@told ||= {})
425
+ return false if told[key]
426
+ @told = told = {} if told.size >= 256
427
+ told[key] = true
428
+ if respond_to?(:warn, true)
429
+ warn(msg)
430
+ else
431
+ puts(msg)
394
432
  end
395
- @app_token = nil
396
- @queryable = nil
397
- @watch = nil
398
- @profile_queryable = nil
399
- @status_queryable = nil
400
- @status_put = nil
433
+ true
401
434
  end
402
435
 
403
- # The Zenoh session of the connection (an Asterism::Zenoh::Session), for
404
- # what the object layer does not do: put and subscribe, a ROS 2 node
405
- # (Asterism::ROS::Node.new(Asterism.session, ...)), anything of the
406
- # Zenoh API. One connection for everything: on a router that lets each
407
- # pass in once, a second session would not get in, and a ROS 2 node on
408
- # this session is part of this node (the same Zenoh ID).
409
- #
410
- # The session stays Asterism's: its close does nothing (it warns once);
411
- # Asterism.close closes it, and with it everything declared on it (the
412
- # application's subscribers, publishers, ROS 2 nodes). After a lost
413
- # connection and a new Asterism.connect, take Asterism.session again and
414
- # declare those again. Polling it (session.poll, node.poll) is fine:
415
- # Asterism.poll polls it too, each entity keeps what came for it.
416
- # Raises Disconnected when not connected (as the calls do).
417
- def self.session
418
- raise Disconnected, (@lost || "not connected") unless connected?
419
- @session
436
+ # While a call waits on one connection, the others answer their calls
437
+ # (another connection of this program may be the one called).
438
+ # @api private
439
+ def self.pump_others(conn)
440
+ list = @connections
441
+ return if list.nil? || list.size < 2
442
+ list = list.dup
443
+ i = 0
444
+ while i < list.size
445
+ c = list[i]
446
+ i += 1
447
+ c.pump unless c.equal?(conn)
448
+ end
420
449
  end
421
450
 
422
- # @api private (the name before 0.6.0; Asterism.session is the same)
423
- def self.session!
424
- raise Disconnected, (@lost || "not connected") unless @session
425
- @session
451
+ # The waits open inside each other (all connections: one stack).
452
+ # @api private
453
+ def self.depth
454
+ @depth || 0
455
+ end
456
+
457
+ # @api private
458
+ def self.enter_wait
459
+ if depth >= MAX_NESTING
460
+ # Kept, so that a method that lets it out is answered as "nesting".
461
+ @nesting_error = Error.new("calls nested too deep (max #{MAX_NESTING})")
462
+ raise @nesting_error
463
+ end
464
+ @depth = depth + 1
465
+ end
466
+
467
+ # @api private
468
+ def self.leave_wait
469
+ @depth = depth - 1
470
+ end
471
+
472
+ # @api private
473
+ def self.nesting_error?(e)
474
+ !@nesting_error.nil? && e.equal?(@nesting_error)
475
+ end
476
+
477
+ # The depth of the liveliness watch behind each / nodes. The tokens alive
478
+ # when it is declared (every node and object on the network) come in one
479
+ # burst: 64 on the boards (the ring comes from the VM's pool), the
480
+ # binding's deeper default where it has one (CRuby: 1024).
481
+ # @api private
482
+ def self.watch_depth
483
+ d = Asterism::Zenoh::DEFAULT_WATCH_DEPTH
484
+ d > 64 ? d : 64
426
485
  end
427
486
 
428
487
  # Whether Asterism itself is closing s (SharedSession#close).
@@ -431,87 +490,31 @@ module Asterism
431
490
  !@releasing.nil? && @releasing.equal?(s)
432
491
  end
433
492
 
434
- # Extended onto the session of Asterism.connect: the session belongs to
435
- # Asterism, so a close from anyone else (the application, a library that
436
- # was handed Asterism.session) does nothing. Asterism.close and a lost
437
- # connection close it.
493
+ # Closes s for a connection (the one close SharedSession lets through).
494
+ # @api private
495
+ def self.close_session(s)
496
+ @releasing = s
497
+ begin
498
+ s.close
499
+ ensure
500
+ @releasing = nil
501
+ end
502
+ end
503
+
504
+ # Extended onto the session of each connection: the session belongs to
505
+ # the connection, so a close from anyone else (the application, a library
506
+ # that was handed connection.session) does nothing. Connection#close and
507
+ # a lost connection close it.
438
508
  module SharedSession
439
509
  def close
440
510
  return super if ::Asterism.releasing?(self)
441
- ::Asterism.warn_once(self, "asterism: Asterism.session belongs to Asterism; its close is ignored " \
442
- "(Asterism.close closes it)")
511
+ ::Asterism.warn_once(self, "asterism: a connection's session belongs to it; its close is ignored " \
512
+ "(Connection#close closes it)")
443
513
  nil
444
514
  end
445
515
  end
446
516
 
447
- # The connection went away: closed, but the next Asterism.poll still tells
448
- # on_leave about every node known until then.
449
- # @api private
450
- def self.lost(reason)
451
- @lost = reason
452
- release
453
- end
454
-
455
- # ------------------------------------------------------------ exposing
456
-
457
- # Makes obj callable from other machines as <node>/<app>/<name>. Only the
458
- # listed methods can be called. methods: is an Array of names, or a Hash
459
- # name => number of arguments (checked before calling; -1 for any), or
460
- # name => {args: [names], doc: "text"} (docs/protocol.md 5): the
461
- # arguments' names (their number is the number checked, unless arity:
462
- # says otherwise) and what the method does, both told in the meta for
463
- # the readers that show them (asterism mcp, the command line). doc: a
464
- # text about the object itself, also in the meta.
465
- # caller: a keyword name (caller: :from): each call passes the calling
466
- # node's ID (Asterism.current_call.from) to the method as that keyword,
467
- # and a call that brings the keyword itself is refused (an "arguments"
468
- # error), so the value is always the one Asterism took from the call.
469
- def self.expose(name, obj, methods:, caller: nil, doc: nil)
470
- s = session!
471
- name = check_name("object", name)
472
- table = {}
473
- info = {}
474
- if methods.is_a?(Hash)
475
- methods.each do |m, n|
476
- if n.is_a?(Hash)
477
- d = method_doc(m, n)
478
- table[m.to_s] = d[0]
479
- info[m.to_s] = d[1]
480
- else
481
- table[m.to_s] = n.to_i
482
- end
483
- end
484
- else
485
- methods.each { |m| table[m.to_s] = -1 }
486
- end
487
- raise ArgumentError, "no method to expose" if table.empty?
488
- unless doc.nil?
489
- raise ArgumentError, "doc: expects a String, got #{doc.class}" unless doc.is_a?(String)
490
- raise ArgumentError, "doc: at most #{DOC_MAX} bytes" if doc.bytesize > DOC_MAX
491
- end
492
- table.each_key do |m|
493
- raise ArgumentError, "#{obj.class} has no public method #{m}" unless obj.respond_to?(m)
494
- end
495
- kw = nil
496
- unless caller.nil?
497
- unless caller.is_a?(Symbol) || caller.is_a?(String)
498
- raise ArgumentError, "caller: expects a keyword name (caller: :from), got #{caller.inspect}"
499
- end
500
- kw = caller.to_s
501
- raise ArgumentError, "caller: expects a keyword name (caller: :from), got #{caller.inspect}" if kw.empty?
502
- end
503
- unexpose(name)
504
- token = s.liveliness("#{ROOT}/#{@node}/#{@app}/#{name}")
505
- @objects[name] = [obj, table, token, kw, info, doc]
506
- "#{@node}/#{@app}/#{name}"
507
- rescue Asterism::Zenoh::Error => e
508
- raise Disconnected, e.message
509
- end
510
-
511
- # The longest doc text (bytes) and the most argument names a method may
512
- # tell in its meta (docs/protocol.md 5).
513
- DOC_MAX = 2048
514
- ARGS_MAX = 16
517
+ # ------------------------------------------------------------ calls (shared)
515
518
 
516
519
  # A method's {args:, doc:, arity:} at expose: [the number of arguments
517
520
  # checked, its meta fields {"args", "doc"}].
@@ -556,643 +559,959 @@ module Asterism
556
559
  [n, out]
557
560
  end
558
561
 
559
- def self.unexpose(name)
560
- entry = @objects ? @objects.delete(name.to_s) : nil
561
- entry[2].close if entry
562
- !entry.nil?
563
- end
564
-
565
- def self.exposed
566
- @objects ? @objects.keys : []
562
+ # The request of a call: a map with the method's name, the protocol the
563
+ # caller speaks, and the arguments and keyword arguments when there are
564
+ # any (absent means none).
565
+ # @api private
566
+ def self.request(method, args, kwargs)
567
+ req = { "method" => method.to_s, "protocol" => PROTOCOL }
568
+ req["args"] = args unless args.nil? || args.empty?
569
+ req["kwargs"] = kwargs unless kwargs.nil? || kwargs.empty?
570
+ req
567
571
  end
568
572
 
569
- # ------------------------------------------------------------ polling
573
+ MALFORMED = "malformed call (expected a map {\"method\" => name, \"args\" => [...], \"kwargs\" => {...}})"
570
574
 
571
- # Call from the application's update loop. Answers the calls that came
572
- # in, follows who is alive and calls the on_join / on_leave blocks. false
573
- # once the connection is closed.
574
- #
575
- # Cheap when nothing came: each queue is looked at by its count first,
576
- # and the list of nodes (and the comparison behind on_join / on_leave)
577
- # is made again only after a liveliness change.
578
- def self.poll
579
- ok = @session ? pump : false
580
- tell_nodes
581
- ok
575
+ # [method, args, kwargs] of a decoded request, or nil when it is not one:
576
+ # a map with "method" (a non-empty str), "args" (an array, absent: none)
577
+ # and "kwargs" (a map with str keys, absent: none). Other keys are
578
+ # ignored (room for later additions).
579
+ # @api private
580
+ def self.parse_request(req)
581
+ return nil unless req.is_a?(Hash)
582
+ m = req["method"]
583
+ return nil unless m.is_a?(String) && !m.empty?
584
+ args = req.key?("args") ? req["args"] : []
585
+ return nil unless args.is_a?(Array)
586
+ kw = req.key?("kwargs") ? req["kwargs"] : {}
587
+ return nil unless kw.is_a?(Hash)
588
+ keys = kw.keys
589
+ i = 0
590
+ while i < keys.size
591
+ return nil unless keys[i].is_a?(String)
592
+ i += 1
593
+ end
594
+ [m, args, kw]
582
595
  end
583
596
 
584
- # ------------------------------------------------------------ nodes coming and going
585
-
586
- # on_join { |node| }: another node appeared (one of its applications or
587
- # objects). The nodes there already join on the first polls after
588
- # connecting. on_leave { |node| }: a node is gone (no token and no object
589
- # left); when the connection is lost, every node known until then leaves.
590
- #
591
- # The blocks run from Asterism.poll only, never from the polling inside a
592
- # waiting call. What a block raises comes out of Asterism.poll (on CRuby
593
- # with a receiving thread: to on_error). Asterism.close forgets them.
594
- def self.on_join(&blk)
595
- raise ArgumentError, "on_join needs a block" unless blk
596
- (@on_join ||= []) << blk
597
- self
597
+ # @api private
598
+ def self.invoke(obj, name, args, kw)
599
+ if kw.empty?
600
+ obj.public_send(name, *args)
601
+ else
602
+ opts = {}
603
+ kw.each { |k, v| opts[k.to_sym] = v }
604
+ obj.public_send(name, *args, **opts)
605
+ end
598
606
  end
599
607
 
600
- def self.on_leave(&blk)
601
- raise ArgumentError, "on_leave needs a block" unless blk
602
- (@on_leave ||= []) << blk
603
- self
608
+ # {"error" => {"kind", "class", "message"}}, packed.
609
+ # @api private
610
+ def self.error_reply(kind, klass, message)
611
+ ::MessagePack.pack({ "error" => { "kind" => kind, "class" => Codec.text(klass), "message" => Codec.text(message) } })
604
612
  end
605
613
 
606
- # Removes a block given to on_join / on_leave (keep the Proc to remove
607
- # it: h = proc { |n| ... }; Asterism.on_join(&h); Asterism.off_join(h)).
608
- # on_* adds a block; on_error (CRuby) is the only one that replaces.
609
- def self.off_join(blk)
610
- @on_join.delete(blk) if @on_join
611
- self
612
- end
614
+ # ------------------------------------------------------------ the connection
615
+
616
+ # One application on the network (Asterism.connect). Holds everything of
617
+ # it: the Zenoh session, the liveliness token and watch, the exposed
618
+ # objects, the calls waiting, the status, topics, types and
619
+ # subscriptions, the on_join / on_leave blocks. Its methods are the
620
+ # Asterism API; close ends it (and with it everything declared on it).
621
+ class Connection
622
+ # node_id, app: this application's names. run_id: the run id of this
623
+ # connection, 16 random bits picked when it opened, sent with each value
624
+ # of its topics (docs/protocol.md 9.3): a reader that sees another run
625
+ # id knows the sender connected again.
626
+ attr_reader :node_id, :app, :run_id
627
+
628
+ # Asterism.connect. @api private
629
+ def initialize(locator, node:, app:, mode:, listen:, config:, connect_timeout:, check_timeout:, credentials:)
630
+ if credentials
631
+ locator, config, creds = ::Asterism::Credentials.merge(credentials, locator, config)
632
+ node ||= creds.name
633
+ end
634
+ node = ::Asterism.check_name("node", node)
635
+ app = ::Asterism.check_name("app", app)
636
+ check_ms = ::Asterism.time_ms("Asterism.connect check_timeout:", check_timeout, nil, nil,
637
+ (::Asterism::CHECK_TIMEOUT * 1000).round)
638
+ opts = { mode: mode, listen: listen }
639
+ opts[:config] = config unless config.nil?
640
+ opts[:connect_timeout] = connect_timeout unless connect_timeout.nil?
641
+ # The program's own connections first (at once), then the network's
642
+ # (open_checked: on CRuby without the lock, so that the program's
643
+ # other connections go on meanwhile).
644
+ ::Asterism.claim(node, app)
645
+ begin
646
+ s = open_checked(locator, opts, node, app, check_ms)
647
+ attach(s, node, app)
648
+ ensure
649
+ ::Asterism.unclaim(node, app)
650
+ end
651
+ end
613
652
 
614
- def self.off_leave(blk)
615
- @on_leave.delete(blk) if @on_leave
616
- self
617
- end
653
+ # A session opened to locator, with no other copy of node/app on the
654
+ # network (protocol.md 6.3). Touches nothing of the program's.
655
+ # @api private
656
+ def open_checked(locator, opts, node, app, check_ms)
657
+ begin
658
+ s = ::Asterism::Zenoh::Session.open(locator, **opts)
659
+ rescue ::Asterism::Zenoh::Error => e
660
+ raise ::Asterism::Disconnected, e.message
661
+ end
662
+ begin
663
+ found = already_there?(s, node, app, check_ms)
664
+ rescue ::Asterism::Zenoh::Error => e
665
+ s.close
666
+ raise ::Asterism::Disconnected, e.message
667
+ end
668
+ if found
669
+ s.close
670
+ raise ::Asterism::Error, "#{node}/#{app} is already on the network"
671
+ end
672
+ s
673
+ end
618
674
 
619
- # on_app_join { |node, app| }: an application of another node appeared
620
- # (its token asterism/<node>/<app>); on_app_leave { |node, app| }: it is
621
- # gone. A node may run several applications: each comes and goes on its
622
- # own, and the node stays (on_join / on_leave) while one of them or an
623
- # object is there. The applications there already join on the first
624
- # polls after connecting; when the connection is lost, every application
625
- # known until then leaves. Called from Asterism.poll, as on_join;
626
- # Asterism.close forgets them.
627
- def self.on_app_join(&blk)
628
- raise ArgumentError, "on_app_join needs a block" unless blk
629
- (@on_app_join ||= []) << blk
630
- self
631
- end
675
+ # Declares this application on s and joins the program's connections.
676
+ # @api private
677
+ def attach(s, node, app)
678
+ root = ::Asterism::ROOT
679
+ begin
680
+ @app_token = s.liveliness(::Asterism.app_token_key(node, app))
681
+ @queryable = s.queryable("#{root}/#{node}/#{app}/**", depth: 32)
682
+ @watch = s.liveliness_watch("#{root}/**", depth: ::Asterism.watch_depth)
683
+ @profile_queryable = s.queryable("#{root}/#{node}/#{::Asterism::Profile::KEY}", depth: 4)
684
+ rescue ::Asterism::Zenoh::Error => e
685
+ s.close
686
+ raise ::Asterism::Disconnected, e.message
687
+ end
688
+ s.extend(::Asterism::SharedSession) # connection.session: only the connection closes it
689
+ @session = s
690
+ @node_id = node
691
+ @app = app
692
+ @objects = {} # name => [object, {method name => arity}, token, caller keyword or nil,
693
+ # {method name => meta fields}, the object's doc or nil]
694
+ @alive = {} # "node/app/object" => node (from liveliness)
695
+ @apps = {} # "node/app" => node (from liveliness)
696
+ @app_protocols = {} # "node/app" => the protocol its token says
697
+ @proxies = {}
698
+ @lost = nil
699
+ @known = [] # the other nodes told to on_join so far
700
+ @known_set = {} # the same, as node => true
701
+ @known_apps = {} # "node/app" => true: the other applications told to on_app_join
702
+ @node_list = [node] # what nodes returns (this node first), rebuilt on a change
703
+ @nodes_changed = false # liveliness changed since tell_nodes last compared
704
+ @was_reconnecting = false
705
+ @status = nil
706
+ @status_put = nil
707
+ @types = {}
708
+ @topics = {}
709
+ @seq_of = {} # a withdrawn topic's entry => its next number (publish goes on from it)
710
+ @subscriptions = []
711
+ @pubs_put = nil
712
+ @app_queryable = nil
713
+ @protocols = {} # node => the protocol its profile says (0: none said), asked
714
+ # when none of its applications' tokens is known
715
+ @run_id = ::Asterism.new_run_id(object_id)
716
+ ::Asterism.register(self)
717
+ tell_profile # for those who follow the profiles (the reply is the queryable's)
718
+ end
632
719
 
633
- def self.on_app_leave(&blk)
634
- raise ArgumentError, "on_app_leave needs a block" unless blk
635
- (@on_app_leave ||= []) << blk
636
- self
637
- end
720
+ # Whether node/app is alive already (its application token or an object:
721
+ # a second copy of the same application). Waits for the answer (a router
722
+ # answers at once), at most check_ms. @api private
723
+ def already_there?(s, node, app, check_ms = 1500)
724
+ get_ms = check_ms > 1000 ? check_ms - 500 : check_ms
725
+ g = s.liveliness_get("#{::Asterism::ROOT}/#{node}/#{app}/**", timeout_ms: get_ms)
726
+ t0 = ::Asterism.now_ms
727
+ found = false
728
+ while true
729
+ s.poll
730
+ ended = g.done? # before taking the replies (see Future#collect)
731
+ found = true if g.each_reply.size > 0
732
+ break if found || ended || ::Asterism.now_ms - t0 > check_ms
733
+ ::Asterism.pause(::Asterism::WAIT_STEP_MS)
734
+ end
735
+ found
736
+ end
638
737
 
639
- def self.off_app_join(blk)
640
- @on_app_join.delete(blk) if @on_app_join
641
- self
642
- end
738
+ def connected?
739
+ return false if @session.nil?
740
+ if @session.closed?
741
+ lost("the connection was lost")
742
+ return false
743
+ end
744
+ true
745
+ end
643
746
 
644
- def self.off_app_leave(blk)
645
- @on_app_leave.delete(blk) if @on_app_leave
646
- self
647
- end
747
+ # True while the connection is lost and the Zenoh binding opens it again
748
+ # by itself (a client of a router: zenoh-pico built with reconnection on
749
+ # the boards, zenoh-c on CRuby). connected? stays true meanwhile, and once
750
+ # the router is back everything declared before is there again: the
751
+ # application token, the exposed objects, the liveliness watch, the
752
+ # topics, and what the application declared on its session. Meanwhile
753
+ # the other nodes leave (on_leave) and join again after it, calls raise
754
+ # Disconnected or time out, and puts reach nobody.
755
+ def reconnecting?
756
+ s = @session
757
+ return false if s.nil?
758
+ s.respond_to?(:reconnecting?) ? s.reconnecting? : false
759
+ end
648
760
 
649
- # Compares the applications alive now with those told before and calls
650
- # the on_app_* blocks for the difference (this application left out).
651
- # @api private
652
- def self.tell_apps
653
- known = @known_apps
654
- return if known.nil?
655
- now = {}
656
- if @session
657
- own = "#{@node}/#{@app}"
658
- keys = @apps.keys
659
- i = 0
660
- while i < keys.size
661
- now[keys[i]] = true unless keys[i] == own
662
- i += 1
663
- end
761
+ # "<node>/<app>": this application's path.
762
+ def path
763
+ "#{@node_id}/#{@app}"
664
764
  end
665
- joined = []
666
- left = []
667
- keys = now.keys
668
- i = 0
669
- while i < keys.size
670
- joined << keys[i] unless known[keys[i]]
671
- i += 1
765
+
766
+ # Why the connection went away (nil while connected or after close).
767
+ def lost_reason
768
+ @lost
672
769
  end
673
- keys = known.keys
674
- i = 0
675
- while i < keys.size
676
- left << keys[i] unless now[keys[i]]
677
- i += 1
770
+
771
+ # Closes the connection (and with it every exposed object, topic and
772
+ # subscription), and forgets the on_join / on_leave blocks. Idempotent.
773
+ # A closed connection is not opened again: Asterism.connect makes a new
774
+ # one.
775
+ def close
776
+ release
777
+ @known = nil
778
+ @known_apps = nil
779
+ @on_join = nil
780
+ @on_leave = nil
781
+ @on_app_join = nil
782
+ @on_app_leave = nil
783
+ ::Asterism.unregister(self)
784
+ nil
678
785
  end
679
- @known_apps = @session ? now : nil
680
- tell_apps_each("on_app_join", @on_app_join, joined)
681
- tell_apps_each("on_app_leave", @on_app_leave, left)
682
- end
683
786
 
684
- # @api private
685
- def self.tell_apps_each(where, blocks, names)
686
- return if blocks.nil? || names.empty?
687
- i = 0
688
- while i < names.size
689
- cut = names[i].index("/")
690
- node = names[i][0, cut]
691
- app = names[i][cut + 1, names[i].size]
692
- j = 0
693
- while j < blocks.size
694
- tell(where, blocks[j], node, app)
695
- j += 1
696
- end
697
- i += 1
787
+ # @api private
788
+ def release
789
+ s = @session
790
+ @session = nil
791
+ @objects = {}
792
+ @alive = {}
793
+ @apps = {}
794
+ @app_protocols = {}
795
+ @node_list = nil
796
+ @nodes_changed = true
797
+ @proxies = {}
798
+ ::Asterism.close_session(s) if s
799
+ @app_token = nil
800
+ @queryable = nil
801
+ @watch = nil
802
+ @profile_queryable = nil
803
+ @app_queryable = nil
804
+ @status_put = nil
805
+ release_data
698
806
  end
699
- end
700
807
 
701
- # Compares the nodes alive now with those told before and calls the
702
- # blocks for the difference.
703
- # @api private
704
- def self.tell_nodes
705
- known = @known
706
- return if known.nil?
707
- # Nothing came on the liveliness watch since the last comparison (and
708
- # the connection is neither new nor lost): nothing can have changed.
709
- return unless @nodes_changed
710
- @nodes_changed = false
711
- tell_apps
712
- now = []
713
- now_set = {}
714
- if @session
715
- list = node_list
716
- i = 1 # list[0] is this node
717
- while i < list.size
718
- n = list[i]
719
- now << n
720
- now_set[n] = true
721
- i += 1
722
- end
808
+ # The Zenoh session of the connection (an Asterism::Zenoh::Session), for
809
+ # what the object layer does not do: put and subscribe, a ROS 2 node
810
+ # (Asterism::ROS::Node.new(net.session, ...)), anything of the Zenoh
811
+ # API. A ROS 2 node on this session is part of this application's node
812
+ # (the same Zenoh ID).
813
+ #
814
+ # The session stays the connection's: its close does nothing (it warns
815
+ # once); Connection#close closes it, and with it everything declared on
816
+ # it (the application's subscribers, publishers, ROS 2 nodes). Polling
817
+ # it (session.poll, node.poll) is fine: Connection#poll polls it too,
818
+ # each entity keeps what came for it. Raises Disconnected when not
819
+ # connected (as the calls do).
820
+ def session
821
+ raise ::Asterism::Disconnected, (@lost || "not connected") unless connected?
822
+ @session
723
823
  end
724
- known_set = @known_set || {}
725
- joined = []
726
- left = []
727
- i = 0
728
- while i < now.size
729
- joined << now[i] unless known_set[now[i]]
730
- i += 1
824
+
825
+ # @api private: the session without the check of a lost connection.
826
+ def session!
827
+ raise ::Asterism::Disconnected, (@lost || "not connected") unless @session
828
+ @session
731
829
  end
732
- i = 0
733
- while i < known.size
734
- left << known[i] unless now_set[known[i]]
735
- i += 1
830
+
831
+ # The connection went away: closed, but the next poll still tells
832
+ # on_leave about every node known until then.
833
+ # @api private
834
+ def lost(reason)
835
+ @lost = reason
836
+ release
736
837
  end
737
- # After a loss, everything has been told: nothing more to compare.
738
- if @session
739
- @known = now
740
- @known_set = now_set
741
- else
742
- @known = nil
743
- @known_set = nil
838
+
839
+ def inspect
840
+ state = if @session then ""
841
+ elsif @lost then " lost"
842
+ else " closed"
843
+ end
844
+ "#<Asterism::Connection #{@node_id}/#{@app}#{state}>"
744
845
  end
745
- tell_each("on_join", @on_join, joined)
746
- tell_each("on_leave", @on_leave, left)
747
- end
748
846
 
749
- # While loops, not each with a block: the blocks are the application's,
750
- # and nothing else stands between them and the update loop on the stack.
751
- # @api private
752
- def self.tell_each(where, blocks, names)
753
- return if blocks.nil? || names.empty?
754
- i = 0
755
- while i < names.size
756
- j = 0
757
- while j < blocks.size
758
- tell(where, blocks[j], names[i])
759
- j += 1
847
+ def to_s
848
+ inspect
849
+ end
850
+
851
+ # ---------------------------------------------------------- exposing
852
+
853
+ # Makes obj callable from other machines as <node>/<app>/<name>. Only the
854
+ # listed methods can be called. methods: is an Array of names, or a Hash
855
+ # name => number of arguments (checked before calling; -1 for any), or
856
+ # name => {args: [names], doc: "text"} (docs/protocol.md 5): the
857
+ # arguments' names (their number is the number checked, unless arity:
858
+ # says otherwise) and what the method does, both told in the meta for
859
+ # the readers that show them (asterism mcp, the command line). doc: a
860
+ # text about the object itself, also in the meta.
861
+ # caller: a keyword name (caller: :from): each call passes the calling
862
+ # node's ID (current_call.from) to the method as that keyword, and a
863
+ # call that brings the keyword itself is refused (an "arguments"
864
+ # error), so the value is always the one Asterism took from the call.
865
+ def expose(name, obj, methods:, caller: nil, doc: nil)
866
+ s = session!
867
+ name = ::Asterism.check_name("object", name)
868
+ table = {}
869
+ info = {}
870
+ if methods.is_a?(Hash)
871
+ methods.each do |m, n|
872
+ if n.is_a?(Hash)
873
+ d = ::Asterism.method_doc(m, n)
874
+ table[m.to_s] = d[0]
875
+ info[m.to_s] = d[1]
876
+ else
877
+ table[m.to_s] = n.to_i
878
+ end
879
+ end
880
+ else
881
+ methods.each { |m| table[m.to_s] = -1 }
760
882
  end
761
- i += 1
883
+ raise ArgumentError, "no method to expose" if table.empty?
884
+ unless doc.nil?
885
+ raise ArgumentError, "doc: expects a String, got #{doc.class}" unless doc.is_a?(String)
886
+ raise ArgumentError, "doc: at most #{::Asterism::DOC_MAX} bytes" if doc.bytesize > ::Asterism::DOC_MAX
887
+ end
888
+ table.each_key do |m|
889
+ raise ArgumentError, "#{obj.class} has no public method #{m}" unless obj.respond_to?(m)
890
+ end
891
+ kw = nil
892
+ unless caller.nil?
893
+ unless caller.is_a?(Symbol) || caller.is_a?(String)
894
+ raise ArgumentError, "caller: expects a keyword name (caller: :from), got #{caller.inspect}"
895
+ end
896
+ kw = caller.to_s
897
+ raise ArgumentError, "caller: expects a keyword name (caller: :from), got #{caller.inspect}" if kw.empty?
898
+ end
899
+ unexpose(name)
900
+ token = s.liveliness("#{::Asterism::ROOT}/#{@node_id}/#{@app}/#{name}")
901
+ @objects[name] = [obj, table, token, kw, info, doc]
902
+ "#{@node_id}/#{@app}/#{name}"
903
+ rescue ::Asterism::Zenoh::Error => e
904
+ raise ::Asterism::Disconnected, e.message
762
905
  end
763
- end
764
906
 
765
- # One block for one node, or one application (CRuby routes what it
766
- # raises to on_error).
767
- # @api private
768
- def self.tell(_where, blk, node, app = nil)
769
- if app.nil?
770
- blk.call(node)
771
- else
772
- blk.call(node, app)
907
+ def unexpose(name)
908
+ entry = @objects ? @objects.delete(name.to_s) : nil
909
+ entry[2].close if entry
910
+ !entry.nil?
773
911
  end
774
- end
775
912
 
776
- # @api private
777
- def self.pump
778
- s = @session
779
- return false unless s
780
- unless s.poll
781
- lost("the connection was lost")
782
- return false
783
- end
784
- back_again(s)
785
- answer_calls
786
- answer_profile
787
- answer_status
788
- follow_liveliness
789
- !@session.nil?
790
- rescue Asterism::Zenoh::Error => e
791
- lost_if_closed(e.message)
792
- !@session.nil?
793
- end
913
+ def exposed
914
+ @objects ? @objects.keys : []
915
+ end
794
916
 
795
- # After the binding opened a lost connection again: tell the profile and
796
- # the status again (a put made while the router was away reached nobody).
797
- # @api private
798
- def self.back_again(s)
799
- now = s.respond_to?(:reconnecting?) && s.reconnecting?
800
- was = @was_reconnecting
801
- @was_reconnecting = now
802
- return unless was && !now
803
- tell_profile
804
- tell_status(true)
805
- end
917
+ # ---------------------------------------------------------- polling
918
+
919
+ # Call from the application's update loop. Answers the calls that came
920
+ # in, follows who is alive, calls the on_join / on_leave blocks and hands
921
+ # the values that came to the subscriptions' blocks (subscribe).
922
+ # false once the connection is closed. (Asterism.poll_all polls every
923
+ # connection of the program.)
924
+ #
925
+ # Cheap when nothing came: each queue is looked at by its count first,
926
+ # and the list of nodes (and the comparison behind on_join / on_leave)
927
+ # is made again only after a liveliness change.
928
+ def poll
929
+ ok = @session ? pump : false
930
+ tell_nodes
931
+ deliver_samples if @session
932
+ # A lost connection leaves the program once on_leave told everything.
933
+ ::Asterism.unregister(self) if @session.nil? && @known.nil?
934
+ ok
935
+ end
806
936
 
807
- # A Zenoh error during a call or a poll: the connection is gone only when
808
- # the session says it is closed. While the binding reconnects, the
809
- # session (and everything declared on it) stays.
810
- # @api private
811
- def self.lost_if_closed(reason)
812
- s = @session
813
- lost(reason) if s.nil? || s.closed?
814
- end
937
+ # ---------------------------------------------------------- nodes coming and going
938
+
939
+ # on_join { |node| }: another node appeared (one of its applications or
940
+ # objects). The nodes there already join on the first polls after
941
+ # connecting. on_leave { |node| }: a node is gone (no token and no object
942
+ # left); when the connection is lost, every node known until then leaves.
943
+ #
944
+ # The blocks run from poll only, never from the polling inside a
945
+ # waiting call. What a block raises comes out of poll (on CRuby with a
946
+ # receiving thread: to on_error). close forgets them.
947
+ def on_join(&blk)
948
+ raise ArgumentError, "on_join needs a block" unless blk
949
+ (@on_join ||= []) << blk
950
+ self
951
+ end
815
952
 
816
- # Polls until the block is true. Answers incoming calls meanwhile.
817
- # @api private
818
- def self.wait_until
819
- if (@depth || 0) >= MAX_NESTING
820
- # Kept, so that a method that lets it out is answered as "nesting".
821
- @nesting_error = Error.new("calls nested too deep (max #{MAX_NESTING})")
822
- raise @nesting_error
953
+ def on_leave(&blk)
954
+ raise ArgumentError, "on_leave needs a block" unless blk
955
+ (@on_leave ||= []) << blk
956
+ self
823
957
  end
824
- @depth = (@depth || 0) + 1
825
- begin
826
- until yield
827
- break unless pump
828
- break if yield
829
- pause(WAIT_STEP_MS)
830
- end
831
- ensure
832
- @depth -= 1
958
+
959
+ # Removes a block given to on_join / on_leave (keep the Proc to remove
960
+ # it: h = proc { |n| ... }; net.on_join(&h); net.off_join(h)).
961
+ # on_* adds a block; on_error (CRuby) is the only one that replaces.
962
+ def off_join(blk)
963
+ @on_join.delete(blk) if @on_join
964
+ self
833
965
  end
834
- end
835
966
 
836
- # @api private
837
- def self.depth
838
- (@depth || 0)
839
- end
967
+ def off_leave(blk)
968
+ @on_leave.delete(blk) if @on_leave
969
+ self
970
+ end
840
971
 
841
- # The depth of the liveliness watch behind each / nodes. The tokens alive
842
- # when it is declared (every node and object on the network) come in one
843
- # burst: 64 on the boards (the ring comes from the VM's pool), the
844
- # binding's deeper default where it has one (CRuby: 1024).
845
- # @api private
846
- def self.watch_depth
847
- d = Asterism::Zenoh::DEFAULT_WATCH_DEPTH
848
- d > 64 ? d : 64
849
- end
972
+ # on_app_join { |node, app| }: an application of another node appeared
973
+ # (its token asterism/<node>/<app>); on_app_leave { |node, app| }: it is
974
+ # gone. A node may run several applications (and one program may be
975
+ # several of them): each comes and goes on its own, and the node stays
976
+ # (on_join / on_leave) while one of them or an object is there. The
977
+ # applications there already join on the first polls after connecting;
978
+ # when the connection is lost, every application known until then
979
+ # leaves. Called from poll, as on_join; close forgets them.
980
+ def on_app_join(&blk)
981
+ raise ArgumentError, "on_app_join needs a block" unless blk
982
+ (@on_app_join ||= []) << blk
983
+ self
984
+ end
850
985
 
851
- # @api private
852
- def self.follow_liveliness
853
- w = @watch
854
- return unless w && w.pending > 0
855
- # Array forms instead of blocks called from C (see Future#collect).
856
- events = w.each_pending
857
- @nodes_changed = true if events.size > 0
858
- if events.size > 0 && w.dropped > 0
859
- warn_once(w, "asterism: #{w.dropped} liveliness changes dropped (more than #{watch_depth} at once); " \
860
- "Asterism.each and Asterism.nodes may miss some objects")
986
+ def on_app_leave(&blk)
987
+ raise ArgumentError, "on_app_leave needs a block" unless blk
988
+ (@on_app_leave ||= []) << blk
989
+ self
861
990
  end
862
- i = 0
863
- while i < events.size
864
- key = events[i][0]
865
- alive = events[i][1]
866
- i += 1
867
- rest = key[ROOT.length + 1, key.length].to_s
868
- parts = rest.split("/")
869
- if parts.size == 2 # an application: asterism/<node>/<app>
870
- if alive
871
- @apps[rest] = parts[0]
872
- else
873
- @apps.delete(rest)
874
- end
875
- elsif parts.size == 3 # an object: asterism/<node>/<app>/<object>
876
- if alive
877
- @alive[rest] = parts[0]
878
- else
879
- @alive.delete(rest)
880
- end
881
- end
991
+
992
+ def off_app_join(blk)
993
+ @on_app_join.delete(blk) if @on_app_join
994
+ self
882
995
  end
883
- @node_list = nil
884
- end
885
996
 
886
- # The node IDs alive now, this one first.
887
- def self.nodes
888
- return [] unless @session
889
- node_list.dup
890
- end
997
+ def off_app_leave(blk)
998
+ @on_app_leave.delete(blk) if @on_app_leave
999
+ self
1000
+ end
891
1001
 
892
- # The list behind nodes, made again only after a liveliness change (the
893
- # caller must not change it). @api private
894
- def self.node_list
895
- list = @node_list
896
- return list if list
897
- list = [@node]
898
- seen = { @node => true }
899
- names = @apps.values
900
- i = 0
901
- while i < names.size
902
- n = names[i]
903
- unless seen[n]
904
- seen[n] = true
905
- list << n
1002
+ # Compares the applications alive now with those told before and calls
1003
+ # the on_app_* blocks for the difference (this application left out).
1004
+ # @api private
1005
+ def tell_apps
1006
+ known = @known_apps
1007
+ return if known.nil?
1008
+ now = {}
1009
+ if @session
1010
+ own = "#{@node_id}/#{@app}"
1011
+ keys = @apps.keys
1012
+ i = 0
1013
+ while i < keys.size
1014
+ now[keys[i]] = true unless keys[i] == own
1015
+ i += 1
1016
+ end
906
1017
  end
907
- i += 1
908
- end
909
- owners = @alive.values
910
- i = 0
911
- while i < owners.size
912
- n = owners[i]
913
- unless seen[n]
914
- seen[n] = true
915
- list << n
1018
+ joined = []
1019
+ left = []
1020
+ keys = now.keys
1021
+ i = 0
1022
+ while i < keys.size
1023
+ joined << keys[i] unless known[keys[i]]
1024
+ i += 1
916
1025
  end
917
- i += 1
1026
+ keys = known.keys
1027
+ i = 0
1028
+ while i < keys.size
1029
+ left << keys[i] unless now[keys[i]]
1030
+ i += 1
1031
+ end
1032
+ @known_apps = @session ? now : nil
1033
+ tell_apps_each("on_app_join", @on_app_join, joined)
1034
+ tell_apps_each("on_app_leave", @on_app_leave, left)
918
1035
  end
919
- @node_list = list
920
- end
921
1036
 
922
- # The exposed objects alive now whose <node>/<app>/<object> matches the
923
- # pattern (* is one chunk, ** any number), this application's own
924
- # included. With a block, yields a proxy for each and returns their
925
- # number (1.0 will return the proxies instead, as Ruby's each returns
926
- # its receiver; use the Array form for the count); else returns them.
927
- def self.each(pattern = "**")
928
- paths = []
929
- if @session
930
- seen = {}
931
- @objects.each_key do |name|
932
- path = "#{@node}/#{@app}/#{name}"
933
- if glob?(pattern, path)
934
- paths << path
935
- seen[path] = true
1037
+ # @api private
1038
+ def tell_apps_each(where, blocks, names)
1039
+ return if blocks.nil? || names.empty?
1040
+ i = 0
1041
+ while i < names.size
1042
+ cut = names[i].index("/")
1043
+ node = names[i][0, cut]
1044
+ app = names[i][cut + 1, names[i].size]
1045
+ j = 0
1046
+ while j < blocks.size
1047
+ tell(where, blocks[j], node, app)
1048
+ j += 1
936
1049
  end
1050
+ i += 1
937
1051
  end
938
- @alive.each_key { |path| paths << path if !seen[path] && glob?(pattern, path) }
939
1052
  end
940
- proxies = paths.map { |path| self[path] }
941
- return proxies unless block_given?
942
- proxies.each { |px| yield px }
943
- proxies.size
944
- end
945
1053
 
946
- # A proxy for <node>/<app>/<object>. Nothing is sent until a method is
947
- # called on it. timeout: the time limit of its calls in seconds (2.0), or
948
- # timeout_ms:. (Asterism[path, ms], the time as a positional argument, is
949
- # deprecated.)
950
- def self.[](path, *args, timeout: nil, timeout_ms: nil)
951
- raise ArgumentError, "Asterism[]: wrong number of arguments (given #{args.size + 1}, expected 1)" if args.size > 1
952
- timeout_ms = time_ms("Asterism[]", timeout, timeout_ms, args[0], DEFAULT_TIMEOUT_MS)
953
- split_path(path)
954
- @proxies ||= {}
955
- key = "#{path}|#{timeout_ms}"
956
- @proxies[key] ||= Proxy.new(path.to_s, timeout_ms)
957
- end
1054
+ # Compares the nodes alive now with those told before and calls the
1055
+ # blocks for the difference.
1056
+ # @api private
1057
+ def tell_nodes
1058
+ known = @known
1059
+ return if known.nil?
1060
+ # Nothing came on the liveliness watch since the last comparison (and
1061
+ # the connection is neither new nor lost): nothing can have changed.
1062
+ return unless @nodes_changed
1063
+ @nodes_changed = false
1064
+ tell_apps
1065
+ now = []
1066
+ now_set = {}
1067
+ if @session
1068
+ list = node_list
1069
+ i = 1 # list[0] is this node
1070
+ while i < list.size
1071
+ n = list[i]
1072
+ now << n
1073
+ now_set[n] = true
1074
+ i += 1
1075
+ end
1076
+ end
1077
+ known_set = @known_set || {}
1078
+ joined = []
1079
+ left = []
1080
+ i = 0
1081
+ while i < now.size
1082
+ joined << now[i] unless known_set[now[i]]
1083
+ i += 1
1084
+ end
1085
+ i = 0
1086
+ while i < known.size
1087
+ left << known[i] unless now_set[known[i]]
1088
+ i += 1
1089
+ end
1090
+ # After a loss, everything has been told: nothing more to compare.
1091
+ if @session
1092
+ @known = now
1093
+ @known_set = now_set
1094
+ else
1095
+ @known = nil
1096
+ @known_set = nil
1097
+ end
1098
+ i = 0
1099
+ while i < left.size
1100
+ @protocols.delete(left[i]) if @protocols
1101
+ i += 1
1102
+ end
1103
+ tell_each("on_join", @on_join, joined)
1104
+ tell_each("on_leave", @on_leave, left)
1105
+ end
958
1106
 
959
- # ------------------------------------------------------------ calling
1107
+ # While loops, not each with a block: the blocks are the application's,
1108
+ # and nothing else stands between them and the update loop on the stack.
1109
+ # @api private
1110
+ def tell_each(where, blocks, names)
1111
+ return if blocks.nil? || names.empty?
1112
+ i = 0
1113
+ while i < names.size
1114
+ j = 0
1115
+ while j < blocks.size
1116
+ tell(where, blocks[j], names[i])
1117
+ j += 1
1118
+ end
1119
+ i += 1
1120
+ end
1121
+ end
960
1122
 
961
- # Starts a call; returns a Future. Raises EncodeError (before sending)
962
- # and Disconnected.
963
- # @api private
964
- def self.call_async(path, method, args, kwargs, timeout_ms)
965
- parts = split_path(path)
966
- payload = Codec.pack(request(method, args, kwargs))
967
- if parts[0] == @node && parts[1] == @app && @session
968
- # This application's own object: no network (a session does not see
969
- # its own queryable), same encoding and checks as a remote call.
970
- return Future.answered(path, method, dispatch(parts[2], payload, @node, :local))
1123
+ # One block for one node, or one application (CRuby routes what it
1124
+ # raises to on_error).
1125
+ # @api private
1126
+ def tell(_where, blk, node, app = nil)
1127
+ if app.nil?
1128
+ blk.call(node)
1129
+ else
1130
+ blk.call(node, app)
1131
+ end
971
1132
  end
972
- begin
973
- s = session!
974
- # The caller's node ID is the key's last chunk (docs/protocol.md 4.1).
975
- g = s.get("#{ROOT}/#{path}/call/#{@node}", timeout_ms: timeout_ms, payload: payload)
976
- rescue Asterism::Zenoh::Error => e
1133
+
1134
+ # Answers what came (calls, profiles) and follows liveliness; false
1135
+ # once the connection is gone. @api private
1136
+ def pump
1137
+ s = @session
1138
+ return false unless s
1139
+ unless s.poll
1140
+ lost("the connection was lost")
1141
+ return false
1142
+ end
1143
+ back_again(s)
1144
+ answer_calls
1145
+ answer_profile
1146
+ answer_app_profile
1147
+ follow_liveliness
1148
+ follow_pubs
1149
+ !@session.nil?
1150
+ rescue ::Asterism::Zenoh::Error => e
977
1151
  lost_if_closed(e.message)
978
- raise Disconnected, e.message
1152
+ !@session.nil?
979
1153
  end
980
- Future.new(path, method, g, now_ms + timeout_ms, timeout_ms)
981
- end
982
1154
 
983
- # The request of a call: a map with the method's name, and the arguments
984
- # and keyword arguments when there are any (absent means none).
985
- # @api private
986
- def self.request(method, args, kwargs)
987
- req = { "method" => method.to_s }
988
- req["args"] = args unless args.nil? || args.empty?
989
- req["kwargs"] = kwargs unless kwargs.nil? || kwargs.empty?
990
- req
991
- end
992
-
993
- # @api private
994
- def self.call(path, method, args, kwargs, timeout_ms)
995
- call_async(path, method, args, kwargs, timeout_ms).value
996
- end
1155
+ # After the binding opened a lost connection again: tell the profile, the
1156
+ # status and the topics again (a put made while the router was away
1157
+ # reached nobody).
1158
+ # @api private
1159
+ def back_again(s)
1160
+ now = s.respond_to?(:reconnecting?) && s.reconnecting?
1161
+ was = @was_reconnecting
1162
+ @was_reconnecting = now
1163
+ return unless was && !now
1164
+ tell_profile
1165
+ tell_status(true)
1166
+ tell_pubs(true)
1167
+ end
997
1168
 
998
- # The meta reply of path: {"methods" => [{"name" => n, "arity" => a}, ...]}.
999
- # @api private
1000
- def self.meta(path, timeout_ms = DEFAULT_TIMEOUT_MS)
1001
- parts = split_path(path)
1002
- if parts[0] == @node && parts[1] == @app && @session
1003
- m = meta_of(parts[2])
1004
- raise RemoteError.new("NameError", "no object #{parts[2]} exposed by #{@node}/#{@app}", "no_object") unless m
1005
- return m
1169
+ # A Zenoh error during a call or a poll: the connection is gone only when
1170
+ # the session says it is closed. While the binding reconnects, the
1171
+ # session (and everything declared on it) stays.
1172
+ # @api private
1173
+ def lost_if_closed(reason)
1174
+ s = @session
1175
+ lost(reason) if s.nil? || s.closed?
1006
1176
  end
1007
- begin
1008
- g = session!.get("#{ROOT}/#{path}/meta", timeout_ms: timeout_ms)
1009
- rescue Asterism::Zenoh::Error => e
1010
- lost_if_closed(e.message)
1011
- raise Disconnected, e.message
1177
+
1178
+ # Polls until the block is true. Answers incoming calls meanwhile, on
1179
+ # this connection and on the program's others.
1180
+ # @api private
1181
+ def wait_until
1182
+ ::Asterism.enter_wait
1183
+ begin
1184
+ until yield
1185
+ break unless pump
1186
+ ::Asterism.pump_others(self)
1187
+ break if yield
1188
+ ::Asterism.pause(::Asterism::WAIT_STEP_MS)
1189
+ end
1190
+ ensure
1191
+ ::Asterism.leave_wait
1192
+ end
1012
1193
  end
1013
- f = Future.new(path, "meta", g, now_ms + timeout_ms, timeout_ms)
1014
- f.raw_value
1015
- end
1016
1194
 
1017
- # ------------------------------------------------------------ answering
1195
+ # @api private
1196
+ def follow_liveliness
1197
+ w = @watch
1198
+ return unless w && w.pending > 0
1199
+ # Array forms instead of blocks called from C (see Future#collect).
1200
+ events = w.each_pending
1201
+ @nodes_changed = true if events.size > 0
1202
+ if events.size > 0 && w.dropped > 0
1203
+ ::Asterism.warn_once(w, "asterism: #{w.dropped} liveliness changes dropped (more than " \
1204
+ "#{::Asterism.watch_depth} at once); each and nodes may miss some objects")
1205
+ end
1206
+ cut = ::Asterism::ROOT.length + 1
1207
+ i = 0
1208
+ while i < events.size
1209
+ key = events[i][0]
1210
+ alive = events[i][1]
1211
+ i += 1
1212
+ rest = key[cut, key.length].to_s
1213
+ parts = rest.split("/")
1214
+ if parts.size == 3 # an object: asterism/<node>/<app>/<object>
1215
+ if alive
1216
+ @alive[rest] = parts[0]
1217
+ else
1218
+ @alive.delete(rest)
1219
+ end
1220
+ next
1221
+ end
1222
+ # An application: asterism/<node>/<app>/protocol/<n> (or protocol
1223
+ # 1's asterism/<node>/<app>).
1224
+ pr = ::Asterism.token_protocol(parts)
1225
+ next if pr.nil?
1226
+ name = "#{parts[0]}/#{parts[1]}"
1227
+ if alive
1228
+ @apps[name] = parts[0]
1229
+ @app_protocols[name] = pr
1230
+ app_protocol_seen(name, pr)
1231
+ else
1232
+ @apps.delete(name)
1233
+ @app_protocols.delete(name)
1234
+ # What the readers keep of it goes with it (protocol.md 8.5, 9.4).
1235
+ forget_app(name)
1236
+ end
1237
+ end
1238
+ @node_list = nil
1239
+ end
1018
1240
 
1019
- # The call being answered now (an Asterism::CurrentCall: who called,
1020
- # which object and method), while an exposed method runs for a call; nil
1021
- # outside one. Calls answered while that method waits for its own call
1022
- # are on top of it until they end.
1023
- def self.current_call
1024
- stack = call_stack
1025
- stack.empty? ? nil : stack[stack.size - 1]
1026
- end
1241
+ # The node IDs alive now, this one first.
1242
+ def nodes
1243
+ return [] unless @session
1244
+ node_list.dup
1245
+ end
1027
1246
 
1028
- # The calls being answered, innermost last (CRuby: per thread).
1029
- # @api private
1030
- def self.call_stack
1031
- @call_stack ||= []
1032
- end
1247
+ # The list behind nodes, made again only after a liveliness change (the
1248
+ # caller must not change it). @api private
1249
+ def node_list
1250
+ list = @node_list
1251
+ return list if list
1252
+ list = [@node_id]
1253
+ seen = { @node_id => true }
1254
+ names = @apps.values
1255
+ i = 0
1256
+ while i < names.size
1257
+ n = names[i]
1258
+ unless seen[n]
1259
+ seen[n] = true
1260
+ list << n
1261
+ end
1262
+ i += 1
1263
+ end
1264
+ owners = @alive.values
1265
+ i = 0
1266
+ while i < owners.size
1267
+ n = owners[i]
1268
+ unless seen[n]
1269
+ seen[n] = true
1270
+ list << n
1271
+ end
1272
+ i += 1
1273
+ end
1274
+ @node_list = list
1275
+ end
1033
1276
 
1034
- # @api private
1035
- def self.answer_calls
1036
- qa = @queryable
1037
- return unless qa && qa.pending > 0
1038
- # Without a block, so that a handler that waits (and so polls) does not
1039
- # re-enter the queryable's iteration.
1040
- queries = qa.each_pending
1041
- i = 0
1042
- while i < queries.size
1043
- q = queries[i]
1044
- i += 1
1045
- begin
1046
- answer(q)
1047
- ensure
1048
- begin
1049
- q.finish
1050
- rescue Asterism::Zenoh::Error
1051
- # the session went away meanwhile
1277
+ # The exposed objects alive now whose <node>/<app>/<object> matches the
1278
+ # pattern (* is one chunk, ** any number), this application's own
1279
+ # included. With a block, yields a proxy for each and returns their
1280
+ # number (1.0 will return the connection instead, as Ruby's each
1281
+ # returns its receiver; use the Array form for the count); else returns
1282
+ # them (an Array).
1283
+ def each(pattern = "**")
1284
+ paths = []
1285
+ if @session
1286
+ seen = {}
1287
+ @objects.each_key do |name|
1288
+ path = "#{@node_id}/#{@app}/#{name}"
1289
+ if ::Asterism.glob?(pattern, path)
1290
+ paths << path
1291
+ seen[path] = true
1292
+ end
1052
1293
  end
1294
+ @alive.each_key { |path| paths << path if !seen[path] && ::Asterism.glob?(pattern, path) }
1053
1295
  end
1296
+ proxies = paths.map { |path| self[path] }
1297
+ return proxies unless block_given?
1298
+ proxies.each { |px| yield px }
1299
+ proxies.size
1054
1300
  end
1055
- end
1056
1301
 
1057
- # asterism/<node>/<app>/<object>/call/<caller> and
1058
- # asterism/<node>/<app>/<object>/meta; the node and app may come as
1059
- # wildcards (the query matched this application's queryable).
1060
- # @api private
1061
- def self.answer(q)
1062
- parts = q.key.split("/")
1063
- n = parts.size
1064
- return unless n == 5 || n == 6
1065
- obj = parts[3]
1066
- kind = parts[4]
1067
- prefix = "#{ROOT}/#{@node}/#{@app}/"
1068
- if kind == "meta"
1069
- return unless n == 5
1070
- names = obj == "*" ? @objects.keys : [obj]
1071
- names.each do |nm|
1072
- m = meta_of(nm)
1073
- q.reply("#{prefix}#{nm}/meta", Codec.pack(m)) if m
1302
+ # A proxy for <node>/<app>/<object> (calls go out on this connection).
1303
+ # Nothing is sent until a method is called on it. timeout: the time
1304
+ # limit of its calls in seconds (2.0), or timeout_ms:. (net[path, ms],
1305
+ # the time as a positional argument, is deprecated.)
1306
+ def [](path, *args, timeout: nil, timeout_ms: nil)
1307
+ if args.size > 1
1308
+ raise ArgumentError, "Connection#[]: wrong number of arguments (given #{args.size + 1}, expected 1)"
1074
1309
  end
1075
- elsif kind == "call" && valid_name?(obj)
1076
- if n == 5
1077
- # A protocol 0 call (no caller chunk): refused, so that its sender
1078
- # learns why at once instead of waiting.
1079
- q.reply("#{prefix}#{obj}/call",
1080
- error_reply("protocol", "Asterism::Error",
1081
- "#{@node}/#{@app} speaks Asterism protocol #{PROTOCOL}: call " \
1082
- "asterism/<node>/<app>/<object>/call/<caller> with a map " \
1083
- "{\"method\", \"args\", \"kwargs\"} (asterism 0.7.0 and later)"))
1084
- elsif valid_name?(parts[5])
1085
- q.reply("#{prefix}#{obj}/call/#{parts[5]}", dispatch(obj, q.payload, parts[5], :claimed))
1310
+ timeout_ms = ::Asterism.time_ms("Connection#[]", timeout, timeout_ms, args[0], ::Asterism::DEFAULT_TIMEOUT_MS)
1311
+ ::Asterism.split_path(path)
1312
+ @proxies ||= {}
1313
+ key = "#{path}|#{timeout_ms}"
1314
+ @proxies[key] ||= ::Asterism::Proxy.new(self, path.to_s, timeout_ms)
1315
+ end
1316
+
1317
+ # ---------------------------------------------------------- calling
1318
+
1319
+ # Starts a call; returns a Future. Raises EncodeError (before sending)
1320
+ # and Disconnected.
1321
+ # @api private
1322
+ def call_async(path, method, args, kwargs, timeout_ms)
1323
+ parts = ::Asterism.split_path(path)
1324
+ payload = ::Asterism::Codec.pack(::Asterism.request(method, args, kwargs))
1325
+ if parts[0] == @node_id && parts[1] == @app && @session
1326
+ # This application's own object: no network (a session does not see
1327
+ # its own queryable), same encoding and checks as a remote call.
1328
+ return ::Asterism::Future.answered(path, method, dispatch(parts[2], payload, @node_id, :local))
1329
+ end
1330
+ begin
1331
+ s = session!
1332
+ # The caller's node ID is the key's last chunk (docs/protocol.md 4.1).
1333
+ g = s.get("#{::Asterism::ROOT}/#{path}/call/#{@node_id}", timeout_ms: timeout_ms, payload: payload)
1334
+ rescue ::Asterism::Zenoh::Error => e
1335
+ lost_if_closed(e.message)
1336
+ raise ::Asterism::Disconnected, e.message
1086
1337
  end
1338
+ ::Asterism::Future.new(self, path, method, g, ::Asterism.now_ms + timeout_ms, timeout_ms)
1087
1339
  end
1088
- end
1089
1340
 
1090
- # Whether s can be a node, app or object name (check_name without raising).
1091
- # @api private
1092
- def self.valid_name?(s)
1093
- return false if s.nil? || s.empty? || s.start_with?("@")
1094
- !(s.include?("/") || s.include?("*") || s.include?("$") || s.include?("?") || s.include?("#"))
1095
- end
1341
+ # @api private
1342
+ def call(path, method, args, kwargs, timeout_ms)
1343
+ call_async(path, method, args, kwargs, timeout_ms).value
1344
+ end
1096
1345
 
1097
- # @api private
1098
- def self.meta_of(name)
1099
- entry = @objects[name]
1100
- return nil unless entry
1101
- list = []
1102
- info = entry[4] || {}
1103
- entry[1].each do |m, n|
1104
- e = { "name" => m, "arity" => n }
1105
- extra = info[m]
1106
- extra.each { |k, v| e[k] = v } if extra
1107
- list << e
1108
- end
1109
- out = { "methods" => list }
1110
- out["doc"] = entry[5] if entry[5]
1111
- out
1112
- end
1346
+ # The meta reply of path: {"methods" => [{"name" => n, "arity" => a}, ...]}.
1347
+ # @api private
1348
+ def meta(path, timeout_ms = ::Asterism::DEFAULT_TIMEOUT_MS)
1349
+ parts = ::Asterism.split_path(path)
1350
+ if parts[0] == @node_id && parts[1] == @app && @session
1351
+ m = meta_of(parts[2])
1352
+ unless m
1353
+ raise ::Asterism::RemoteError.new("NameError", "no object #{parts[2]} exposed by #{@node_id}/#{@app}",
1354
+ "no_object")
1355
+ end
1356
+ return m
1357
+ end
1358
+ begin
1359
+ g = session!.get("#{::Asterism::ROOT}/#{path}/meta", timeout_ms: timeout_ms)
1360
+ rescue ::Asterism::Zenoh::Error => e
1361
+ lost_if_closed(e.message)
1362
+ raise ::Asterism::Disconnected, e.message
1363
+ end
1364
+ f = ::Asterism::Future.new(self, path, "meta", g, ::Asterism.now_ms + timeout_ms, timeout_ms)
1365
+ f.raw_value
1366
+ end
1113
1367
 
1114
- MALFORMED = "malformed call (expected a map {\"method\" => name, \"args\" => [...], \"kwargs\" => {...}})"
1368
+ # ---------------------------------------------------------- answering
1115
1369
 
1116
- # Runs a call on an exposed object; returns the packed reply. from is
1117
- # the caller's node ID, verified how it is known (CurrentCall).
1118
- # @api private
1119
- def self.dispatch(obj_name, payload, from, verified)
1120
- req = parse_request(Codec.unpack(payload))
1121
- return error_reply("malformed", "ArgumentError", MALFORMED) unless req
1122
- entry = @objects[obj_name]
1123
- return error_reply("no_object", "NameError", "no object #{obj_name} exposed by #{@node}/#{@app}") unless entry
1124
- name = req[0]
1125
- args = req[1]
1126
- kw = req[2]
1127
- arity = entry[1][name]
1128
- if arity.nil?
1129
- return error_reply("not_exposed", "NoMethodError",
1130
- "undefined method '#{name}' for #{@node}/#{@app}/#{obj_name} (not exposed)")
1131
- end
1132
- if arity >= 0 && args.size != arity
1133
- return error_reply("arguments", "ArgumentError", "wrong number of arguments (given #{args.size}, expected #{arity})")
1134
- end
1135
- ckw = entry[3]
1136
- if ckw
1137
- if kw.key?(ckw)
1138
- return error_reply("arguments", "ArgumentError",
1139
- "#{ckw}: is given by Asterism, not by the caller " \
1140
- "(#{@node}/#{@app}/#{obj_name} is exposed with caller: :#{ckw})")
1141
- end
1142
- kw[ckw] = from
1370
+ # The call being answered now on this connection (an
1371
+ # Asterism::CurrentCall: who called, which object and method), while an
1372
+ # exposed method runs for a call; nil outside one. Calls answered while
1373
+ # that method waits for its own call are on top of it until they end.
1374
+ def current_call
1375
+ stack = call_stack
1376
+ stack.empty? ? nil : stack[stack.size - 1]
1143
1377
  end
1144
- stack = call_stack
1145
- stack << CurrentCall.new(from, verified, obj_name, name)
1146
- begin
1147
- value = invoke(entry[0], name, args, kw)
1148
- rescue => e
1149
- return error_reply(e.equal?(@nesting_error) ? "nesting" : "raised", e.class.to_s, e.message)
1150
- ensure
1151
- stack.pop
1378
+
1379
+ # The calls being answered, innermost last (CRuby: per thread).
1380
+ # @api private
1381
+ def call_stack
1382
+ @call_stack ||= []
1152
1383
  end
1153
- begin
1154
- Codec.pack({ "value" => value })
1155
- rescue EncodeError => e
1156
- error_reply("unsendable", "Asterism::EncodeError", "the return value: #{e.message}")
1384
+
1385
+ # @api private
1386
+ def answer_calls
1387
+ qa = @queryable
1388
+ return unless qa && qa.pending > 0
1389
+ # Without a block, so that a handler that waits (and so polls) does not
1390
+ # re-enter the queryable's iteration.
1391
+ queries = qa.each_pending
1392
+ i = 0
1393
+ while i < queries.size
1394
+ q = queries[i]
1395
+ i += 1
1396
+ begin
1397
+ answer(q)
1398
+ ensure
1399
+ begin
1400
+ q.finish
1401
+ rescue ::Asterism::Zenoh::Error
1402
+ # the session went away meanwhile
1403
+ end
1404
+ end
1405
+ end
1157
1406
  end
1158
- end
1159
1407
 
1160
- # [method, args, kwargs] of a decoded request, or nil when it is not one:
1161
- # a map with "method" (a non-empty str), "args" (an array, absent: none)
1162
- # and "kwargs" (a map with str keys, absent: none). Other keys are
1163
- # ignored (room for later additions).
1164
- # @api private
1165
- def self.parse_request(req)
1166
- return nil unless req.is_a?(Hash)
1167
- m = req["method"]
1168
- return nil unless m.is_a?(String) && !m.empty?
1169
- args = req.key?("args") ? req["args"] : []
1170
- return nil unless args.is_a?(Array)
1171
- kw = req.key?("kwargs") ? req["kwargs"] : {}
1172
- return nil unless kw.is_a?(Hash)
1173
- keys = kw.keys
1174
- i = 0
1175
- while i < keys.size
1176
- return nil unless keys[i].is_a?(String)
1177
- i += 1
1408
+ # asterism/<node>/<app>/<object>/call/<caller> and
1409
+ # asterism/<node>/<app>/<object>/meta; the node and app may come as
1410
+ # wildcards (the query matched this application's queryable).
1411
+ # @api private
1412
+ def answer(q)
1413
+ parts = q.key.split("/")
1414
+ n = parts.size
1415
+ return unless n == 5 || n == 6
1416
+ obj = parts[3]
1417
+ kind = parts[4]
1418
+ prefix = "#{::Asterism::ROOT}/#{@node_id}/#{@app}/"
1419
+ if kind == "meta"
1420
+ return unless n == 5
1421
+ names = obj == "*" ? @objects.keys : [obj]
1422
+ names.each do |nm|
1423
+ m = meta_of(nm)
1424
+ q.reply("#{prefix}#{nm}/meta", ::Asterism::Codec.pack(m)) if m
1425
+ end
1426
+ elsif kind == "call" && ::Asterism.valid_name?(obj)
1427
+ if n == 5
1428
+ # A protocol 0 call (no caller chunk): refused, so that its sender
1429
+ # learns why at once instead of waiting.
1430
+ q.reply("#{prefix}#{obj}/call",
1431
+ ::Asterism.error_reply("protocol", "Asterism::Error",
1432
+ "#{@node_id}/#{@app} speaks Asterism protocol #{::Asterism::PROTOCOL}: call " \
1433
+ "asterism/<node>/<app>/<object>/call/<caller> with a map " \
1434
+ "{\"method\", \"args\", \"kwargs\"} (asterism 0.7.0 and later)"))
1435
+ elsif ::Asterism.valid_name?(parts[5])
1436
+ q.reply("#{prefix}#{obj}/call/#{parts[5]}", dispatch(obj, q.payload, parts[5], :claimed))
1437
+ end
1438
+ end
1178
1439
  end
1179
- [m, args, kw]
1180
- end
1181
1440
 
1182
- # @api private
1183
- def self.invoke(obj, name, args, kw)
1184
- if kw.empty?
1185
- obj.public_send(name, *args)
1186
- else
1187
- opts = {}
1188
- kw.each { |k, v| opts[k.to_sym] = v }
1189
- obj.public_send(name, *args, **opts)
1441
+ # @api private
1442
+ def meta_of(name)
1443
+ entry = @objects[name]
1444
+ return nil unless entry
1445
+ list = []
1446
+ info = entry[4] || {}
1447
+ entry[1].each do |m, n|
1448
+ e = { "name" => m, "arity" => n }
1449
+ extra = info[m]
1450
+ extra.each { |k, v| e[k] = v } if extra
1451
+ list << e
1452
+ end
1453
+ out = { "methods" => list }
1454
+ out["doc"] = entry[5] if entry[5]
1455
+ out
1190
1456
  end
1191
- end
1192
1457
 
1193
- # {"error" => {"kind", "class", "message"}}, packed.
1194
- # @api private
1195
- def self.error_reply(kind, klass, message)
1196
- ::MessagePack.pack({ "error" => { "kind" => kind, "class" => Codec.text(klass), "message" => Codec.text(message) } })
1458
+ # Runs a call on an exposed object; returns the packed reply. from is
1459
+ # the caller's node ID, verified how it is known (CurrentCall).
1460
+ # @api private
1461
+ def dispatch(obj_name, payload, from, verified)
1462
+ raw = ::Asterism::Codec.unpack(payload)
1463
+ if raw.is_a?(Hash)
1464
+ # The protocol first: a caller of another protocol may send another
1465
+ # shape of request (docs/protocol.md 4.3 step 3).
1466
+ pr = raw["protocol"]
1467
+ unless pr.is_a?(Integer) && pr == ::Asterism::PROTOCOL
1468
+ said = pr.is_a?(Integer) ? "protocol #{pr}" : "no protocol (protocol 1 or older)"
1469
+ return ::Asterism.error_reply("protocol", "Asterism::Error",
1470
+ "#{@node_id}/#{@app} speaks Asterism protocol #{::Asterism::PROTOCOL}, " \
1471
+ "the call says #{said}")
1472
+ end
1473
+ end
1474
+ req = ::Asterism.parse_request(raw)
1475
+ return ::Asterism.error_reply("malformed", "ArgumentError", ::Asterism::MALFORMED) unless req
1476
+ entry = @objects[obj_name]
1477
+ unless entry
1478
+ return ::Asterism.error_reply("no_object", "NameError", "no object #{obj_name} exposed by #{@node_id}/#{@app}")
1479
+ end
1480
+ name = req[0]
1481
+ args = req[1]
1482
+ kw = req[2]
1483
+ arity = entry[1][name]
1484
+ if arity.nil?
1485
+ return ::Asterism.error_reply("not_exposed", "NoMethodError",
1486
+ "undefined method '#{name}' for #{@node_id}/#{@app}/#{obj_name} (not exposed)")
1487
+ end
1488
+ if arity >= 0 && args.size != arity
1489
+ return ::Asterism.error_reply("arguments", "ArgumentError",
1490
+ "wrong number of arguments (given #{args.size}, expected #{arity})")
1491
+ end
1492
+ ckw = entry[3]
1493
+ if ckw
1494
+ if kw.key?(ckw)
1495
+ return ::Asterism.error_reply("arguments", "ArgumentError",
1496
+ "#{ckw}: is given by Asterism, not by the caller " \
1497
+ "(#{@node_id}/#{@app}/#{obj_name} is exposed with caller: :#{ckw})")
1498
+ end
1499
+ kw[ckw] = from
1500
+ end
1501
+ stack = call_stack
1502
+ stack << ::Asterism::CurrentCall.new(from, verified, obj_name, name)
1503
+ begin
1504
+ value = ::Asterism.invoke(entry[0], name, args, kw)
1505
+ rescue => e
1506
+ return ::Asterism.error_reply(::Asterism.nesting_error?(e) ? "nesting" : "raised", e.class.to_s, e.message)
1507
+ ensure
1508
+ stack.pop
1509
+ end
1510
+ begin
1511
+ ::Asterism::Codec.pack({ "value" => value })
1512
+ rescue ::Asterism::EncodeError => e
1513
+ ::Asterism.error_reply("unsendable", "Asterism::EncodeError", "the return value: #{e.message}")
1514
+ end
1515
+ end
1197
1516
  end
1198
1517
  end