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.
@@ -1,30 +1,55 @@
1
- # The values the applications put on their own keys
2
- # (asterism/<node>/<app>/<object>/<more>, docs/protocol.md 2.2: a game
3
- # table's state, a log), for `asterism object get / echo` and the MCP
1
+ # The values the applications put on their own keys (their topics,
2
+ # asterism/<node>/<app>/<name>, docs/protocol.md 9: a game table's state, a
3
+ # log, a camera's pictures), for `asterism object get / echo` and the MCP
4
4
  # bridge's asterism_values. A put is not kept anywhere and a get has no
5
5
  # answer for it (an application's queryable answers only the key shapes of
6
6
  # 4.3), so the latest value is only what a subscriber received and kept:
7
7
  # Values::Store keeps it, a key at a time, within limits.
8
+ #
9
+ # Each value is read with what came along (9.2, 9.3): its encoding (none:
10
+ # MessagePack; else the bytes as they are, image/jpeg) and the attachment
11
+ # [seq, run id] or [seq, run id, sender's ms], from which Values::Seq counts
12
+ # the values lost between two of a key (Asterism::Sequences: a new run id
13
+ # is a sender that connected again). This reads the Zenoh samples itself rather
14
+ # than through Connection#subscribe: it shows what is on the wire, the
15
+ # payload's size and a value that is not MessagePack too (as text or its
16
+ # size), where Connection#subscribe leaves those out.
17
+ #
18
+ # The shared places (docs/protocol.md 17: asterism/<node>/@shared/<name>
19
+ # and asterism/@shared/<name>) are read too: a key there has no owner
20
+ # application, several applications may put on it, and each value names
21
+ # its sender ("<node>/<app>", the attachment's fourth element). A shared
22
+ # value is shown with its sender ("from"), its numbers are counted per
23
+ # key and sender, and Store keeps the latest value of each sender. As in
24
+ # Zenoh, * and ** never match a part that starts with @: a pattern names
25
+ # @shared itself (games/@shared/**, */@shared/spectate/**, @shared/**).
8
26
  require "json"
9
27
 
10
28
  module Asterism
11
29
  class CLI
12
30
  module Values
13
31
  PREFIX = "asterism/"
32
+ # The part of a shared place's keys (docs/protocol.md 17).
33
+ SHARED = "@shared"
14
34
  # Characters a part of a key cannot have (2.1); * and ** are whole
15
35
  # parts.
16
36
  BAD = /[*$?#]/
17
37
 
18
38
  module_function
19
39
 
20
- # The pattern (node/app/object/more, * and ** as whole parts) checked;
40
+ # The pattern (node/app/object/more, * and ** as whole parts; or a
41
+ # shared place's node/@shared/name..., @shared/name...) checked;
21
42
  # ArgumentError otherwise.
22
43
  def check_pattern!(pattern)
23
44
  parts = pattern.to_s.split("/", -1)
24
- bad = parts.empty? || parts.any? do |p|
45
+ bad = parts.empty? || parts.each_with_index.any? do |p, i|
46
+ next false if p == SHARED && (i.zero? || (i == 1 && parts[0] != SHARED))
25
47
  p.empty? || p.start_with?("@") || (p.match?(BAD) && !%w[* **].include?(p))
26
48
  end
27
- raise ArgumentError, "#{pattern.inspect}: a key's parts are names, * (one part) or ** (any parts)" if bad
49
+ if bad
50
+ raise ArgumentError, "#{pattern.inspect}: a key's parts are names, * (one part) or ** (any parts); " \
51
+ "a shared place's keys are node/@shared/... or @shared/..."
52
+ end
28
53
  pattern
29
54
  end
30
55
 
@@ -33,15 +58,89 @@ module Asterism
33
58
  "#{PREFIX}#{pattern}"
34
59
  end
35
60
 
61
+ # Whether key (without asterism/) matches pattern: * one part, ** any
62
+ # parts, neither a part that starts with @ (verbatim, as Zenoh's).
36
63
  def match?(pattern, key)
37
- ::Asterism.glob?(pattern, key)
64
+ glob_parts?(pattern.split("/"), 0, key.split("/"), 0)
65
+ end
66
+
67
+ def glob_parts?(pat, i, parts, j)
68
+ while i < pat.size
69
+ if pat[i] == "**"
70
+ k = j
71
+ while k <= parts.size
72
+ return true if glob_parts?(pat, i + 1, parts, k)
73
+ break if k < parts.size && parts[k].start_with?("@")
74
+ k += 1
75
+ end
76
+ return false
77
+ end
78
+ return false if j >= parts.size
79
+ ok = pat[i] == parts[j] || (pat[i] == "*" && !parts[j].start_with?("@"))
80
+ return false unless ok
81
+ i += 1
82
+ j += 1
83
+ end
84
+ j == parts.size
85
+ end
86
+
87
+ # Whether a key (without asterism/) is in a shared place: @shared its
88
+ # first part (the network's) or its second (a node's).
89
+ def shared?(key)
90
+ parts = key.split("/", 3)
91
+ parts[0] == SHARED || parts[1] == SHARED
92
+ end
93
+
94
+ # The sender "<node>/<app>" of a value on key, from its attachment
95
+ # (the fourth element, docs/protocol.md 17.3); nil when key is not a
96
+ # shared one (an application's own keys do not read it), or there is
97
+ # no such sender (on a node's place, one of another node is none).
98
+ def sender(key, att)
99
+ got = read(key, att)
100
+ got ? got[3] : nil
38
101
  end
39
102
 
40
- # [value, format] of a payload: MessagePack (Asterism's own, 3.1);
41
- # else JSON text; else UTF-8 text; else "(n bytes)". The value is
42
- # what JSON can hold (bytes inside as "(n bytes)").
43
- def decode(payload)
103
+ # [seq, run id, ms, sender] of an attachment on key
104
+ # (Asterism.read_attachment), or nil when it has no sequence number.
105
+ def read(key, att)
106
+ return nil if att.nil? || att.empty?
107
+ parts = key.delete_prefix(PREFIX).split("/", 3)
108
+ place = if parts[0] == SHARED then :global
109
+ elsif parts[1] == SHARED then :node
110
+ end
111
+ ::Asterism.read_attachment(att.to_s.b, place, place == :node ? parts[0] : nil)
112
+ end
113
+
114
+ # Where a value's numbers are counted and its latest value kept: the
115
+ # key, and for a shared one with a sender the key and the sender.
116
+ def lane(key, from)
117
+ from ? "#{key}\n#{from}" : key
118
+ end
119
+
120
+ # Zenoh's default encoding: what a MessagePack value goes with (it is
121
+ # sent with none).
122
+ DEFAULT_ENCODING = "zenoh/bytes"
123
+ # The encodings whose bytes are JSON text, and those that are text.
124
+ JSON_ENCODINGS = %w[application/json text/json application/json-seq application/json-patch+json
125
+ text/json5].freeze
126
+ TEXT_ENCODINGS = %w[application/yaml application/xml application/sql application/jsonpath
127
+ application/jwt].freeze
128
+ # The encodings an MCP client takes as an image (MCP's image content).
129
+ IMAGE_ENCODINGS = %w[image/png image/jpeg image/gif image/webp].freeze
130
+
131
+ # [value, format] of a payload. No encoding (or Zenoh's default):
132
+ # MessagePack (Asterism's own, 3.1), format "msgpack"; else, for a
133
+ # sender that does not follow the protocol, JSON text ("json"), UTF-8
134
+ # text ("text"), else "(n bytes)" ("bytes"). With an encoding (9.2):
135
+ # format is the encoding without its schema ("image/jpeg"), and the
136
+ # value JSON for the JSON ones, the text for text ones, else
137
+ # "(n bytes)". The value is what JSON can hold (bytes inside as
138
+ # "(n bytes)").
139
+ def decode(payload, encoding = nil)
44
140
  bytes = payload.to_s.b
141
+ enc = encoding.to_s
142
+ enc = "" if enc == DEFAULT_ENCODING || enc.start_with?("#{DEFAULT_ENCODING};")
143
+ return decode_encoded(bytes, enc) unless enc.empty?
45
144
  return [nil, "empty"] if bytes.empty?
46
145
  begin
47
146
  return [json_safe(::MessagePack.unpack(bytes)), "msgpack"]
@@ -57,6 +156,23 @@ module Asterism
57
156
  end
58
157
  end
59
158
 
159
+ # [value, format] of the bytes of a value with an encoding (enc, not
160
+ # Zenoh's default).
161
+ def decode_encoded(bytes, enc)
162
+ name = enc.split(";", 2)[0]
163
+ text = bytes.dup.force_encoding(Encoding::UTF_8)
164
+ texty = name.start_with?("text/") || JSON_ENCODINGS.include?(name) || TEXT_ENCODINGS.include?(name)
165
+ return ["(#{bytes.bytesize} bytes)", name] unless texty && text.valid_encoding?
166
+ if JSON_ENCODINGS.include?(name)
167
+ begin
168
+ return [json_safe(JSON.parse(text)), name]
169
+ rescue JSON::ParserError
170
+ nil
171
+ end
172
+ end
173
+ [text, name]
174
+ end
175
+
60
176
  def json_safe(v)
61
177
  case v
62
178
  when Hash then v.to_h { |k, x| [k.is_a?(String) ? k : k.to_s, json_safe(x)] }
@@ -74,15 +190,64 @@ module Asterism
74
190
  end
75
191
 
76
192
  # One put as the command line and the MCP tool show it: {"key"
77
- # (without asterism/), "t", "bytes", "format", "value"}.
78
- def entry(key, payload, t = Time.now)
79
- value, format = decode(payload)
80
- { "key" => key.delete_prefix(PREFIX), "t" => time(t), "bytes" => payload.to_s.bytesize,
81
- "format" => format, "value" => value }
193
+ # (without asterism/), "t", "bytes", "format", "value"} and, from the
194
+ # attachment, "from" (a shared value's sender), "seq", "run_id",
195
+ # "sent" (the sender's time) and, when seq (a Values::Seq) is given, "lost" (when
196
+ # some were) and "restarted" (the sender started its numbers again),
197
+ # counted per sender on a shared key.
198
+ def entry(key, payload, t = Time.now, encoding: nil, attachment: nil, seq: nil)
199
+ value, format = decode(payload, encoding)
200
+ e = { "key" => key.delete_prefix(PREFIX), "t" => time(t), "bytes" => payload.to_s.bytesize,
201
+ "format" => format, "value" => value }
202
+ e.merge!(numbers(e["key"], attachment, seq))
203
+ end
204
+
205
+ # {"from", "seq", "run_id", "sent", "lost", "restarted"} of an
206
+ # attachment, each when there is one.
207
+ def numbers(key, attachment, seq = nil)
208
+ got = Values.read(key, attachment)
209
+ out = {}
210
+ return out if got.nil?
211
+ n, run, ms, from = got
212
+ out["from"] = from if from
213
+ out["seq"] = n
214
+ out["run_id"] = run if run
215
+ out["sent"] = time(Time.at(ms / 1000, ms % 1000, :millisecond)) if ms
216
+ if seq
217
+ app = from || (shared?(key) ? nil : key.split("/", 3)[0, 2].join("/"))
218
+ lost, restarted = seq.see(Values.lane(key, from), run, n, app)
219
+ out["lost"] = lost if lost.positive?
220
+ out["restarted"] = true if restarted
221
+ end
222
+ out
223
+ end
224
+
225
+ # The sequence numbers seen, key by key (a shared key's sender by
226
+ # sender, Values.lane): how many values were lost before each
227
+ # (docs/protocol.md 9.4: Asterism::Sequences, as a subscription reads
228
+ # them). Thread safe.
229
+ class Seq
230
+ def initialize(max = nil)
231
+ @seqs = ::Asterism::Sequences.new(max)
232
+ @lock = Mutex.new
233
+ end
234
+
235
+ # [lost, restarted] of number n of run id run (nil: none) on lane,
236
+ # from app ("<node>/<app>" or nil).
237
+ def see(lane, run, n, app = nil)
238
+ @lock.synchronize { @seqs.see(lane, run, n, app) }
239
+ end
240
+
241
+ # The application app left: its numbers are forgotten (its next
242
+ # value is a first one).
243
+ def forget(app)
244
+ @lock.synchronize { @seqs.forget(app) }
245
+ end
82
246
  end
83
247
 
84
- # The latest put of each key, as received since it was made: at most
85
- # max_keys keys and max_total payload bytes (the key received
248
+ # The latest put of each key (of each sender on a shared key), as
249
+ # received since it was made: at most max_keys keys and max_total
250
+ # payload bytes (the key received
86
251
  # longest ago is forgotten first); a payload over max_bytes is kept
87
252
  # as its size only. Thread safe; wait blocks until a key matches.
88
253
  class Store
@@ -95,6 +260,8 @@ module Asterism
95
260
  MAX_ANSWER = 100
96
261
  # The longest wait an answer may ask for (seconds).
97
262
  MAX_WAIT = 30
263
+ # The most images an answer hands over (answer_images).
264
+ MAX_IMAGES = 4
98
265
 
99
266
  attr_reader :since, :forgotten
100
267
 
@@ -112,26 +279,38 @@ module Asterism
112
279
  @keys = {} # key => record, the oldest received first
113
280
  @total = 0
114
281
  @forgotten = 0
282
+ @seq = Seq.new
283
+ @lost = {} # key => the values lost on it since the start
115
284
  @lock = Mutex.new
116
285
  @cond = ConditionVariable.new
117
286
  end
118
287
 
119
- # A put received (key with or without asterism/).
120
- def put(key, payload)
288
+ # A put received (key with or without asterism/), with its encoding
289
+ # and attachment when it had them. An image (IMAGE_ENCODINGS) kept
290
+ # keeps its bytes too, for answer_images.
291
+ def put(key, payload, encoding: nil, attachment: nil)
121
292
  key = key.delete_prefix(PREFIX)
122
293
  payload = payload.to_s
123
294
  size = payload.bytesize
124
295
  rec = if size > @max_bytes
125
296
  { "value" => "(#{size} bytes: too large to keep)", "format" => "dropped", "kept" => false }
126
297
  else
127
- v, f = Values.decode(payload)
128
- { "value" => v, "format" => f }
298
+ v, f = Values.decode(payload, encoding)
299
+ r = { "value" => v, "format" => f }
300
+ r["raw"] = payload.b if IMAGE_ENCODINGS.include?(f)
301
+ r
129
302
  end
130
303
  rec.merge!("key" => key, "bytes" => size, "t" => @now.call, "mono" => @clock.call, "left" => false)
304
+ num = Values.numbers(key, attachment, @seq)
305
+ %w[from seq run_id sent].each { |k| rec[k] = num[k] if num[k] }
306
+ lane = Values.lane(key, num["from"])
131
307
  @lock.synchronize do
132
- old = @keys.delete(key)
308
+ lost = (@lost[lane] || 0) + num["lost"].to_i
309
+ @lost[lane] = lost
310
+ rec["lost"] = lost if lost.positive?
311
+ old = @keys.delete(lane)
133
312
  @total -= old["kept"] == false ? 0 : old["bytes"] if old
134
- @keys[key] = rec
313
+ @keys[lane] = rec
135
314
  @total += size unless rec["kept"] == false
136
315
  while @keys.size > @max_keys || (@total > @max_total && @keys.size > 1)
137
316
  _, gone = @keys.shift
@@ -144,19 +323,31 @@ module Asterism
144
323
  end
145
324
 
146
325
  # The application "<node>/<app>" left the network: its values are
147
- # from before (kept, marked).
326
+ # from before (kept, marked), those on its own keys and those it
327
+ # sent to a shared place.
148
328
  def left(app)
149
329
  prefix = "#{app}/"
150
- @lock.synchronize { @keys.each_value { |r| r["left"] = true if r["key"].start_with?(prefix) } }
330
+ @seq.forget(app)
331
+ @lock.synchronize do
332
+ @keys.each_value { |r| r["left"] = true if Store.app_of(r) == app || (r["from"].nil? && r["key"].start_with?(prefix)) }
333
+ end
151
334
  self
152
335
  end
153
336
 
337
+ # The application a record is of: its sender on a shared key (nil
338
+ # when it named none), else its key's "<node>/<app>".
339
+ def self.app_of(rec)
340
+ return rec["from"] if rec["from"] || Values.shared?(rec["key"])
341
+ rec["key"].split("/")[0, 2].join("/")
342
+ end
343
+
154
344
  def size
155
345
  @lock.synchronize { @keys.size }
156
346
  end
157
347
 
348
+ # The keys kept (a shared key once for each of its senders).
158
349
  def keys
159
- @lock.synchronize { @keys.keys }
350
+ @lock.synchronize { @keys.values.map { _1["key"] } }
160
351
  end
161
352
 
162
353
  # The records whose keys match (sorted by key); with wait (seconds),
@@ -166,7 +357,7 @@ module Asterism
166
357
  @lock.synchronize do
167
358
  loop do
168
359
  got = @keys.values.select { Values.match?(pattern, _1["key"]) }
169
- return got.sort_by { _1["key"] } unless got.empty?
360
+ return got.sort_by { [_1["key"], _1["from"].to_s] } unless got.empty?
170
361
  left = deadline - @clock.call
171
362
  return [] if left <= 0
172
363
  @cond.wait(@lock, left)
@@ -175,22 +366,45 @@ module Asterism
175
366
  end
176
367
 
177
368
  # What asterism_values answers: {"since", "values" => [{"key", "t",
178
- # "age_s", "app", "bytes", "format", "value"(, "truncated")}]}, with
369
+ # "age_s", "app", "bytes", "format", "value"(, "from", "seq",
370
+ # "run_id", "sent", "lost", "truncated")}]} (from the sender of a
371
+ # shared key's value, one entry for each sender; seq, run_id and
372
+ # sent from the attachment of
373
+ # the latest value, lost the values missed on the key, or of that
374
+ # sender, since the start; app of the sender, left out for a shared
375
+ # value that named none), with
179
376
  # "more" when more keys matched than an answer lists, "forgotten"
180
377
  # when the limits made it forget keys, and "note" when nothing came.
181
378
  def answer(pattern = "**", wait: 0)
379
+ answer_images(pattern, wait: wait, images: 0)[0]
380
+ end
381
+
382
+ # [answer, images]: the answer, and the bytes of at most images
383
+ # values that are images (IMAGE_ENCODINGS) among those it lists,
384
+ # [[format, bytes], ...]; each such value's entry says "image" =>
385
+ # its place in that list (0 first).
386
+ def answer_images(pattern = "**", wait: 0, images: MAX_IMAGES)
182
387
  Values.check_pattern!(pattern)
183
388
  wait = wait.to_f.clamp(0, MAX_WAIT)
184
389
  recs = match(pattern, wait: wait)
390
+ pics = []
185
391
  now = @clock.call
186
392
  alive = {}
187
393
  out = { "since" => Values.time(@since) }
188
394
  out["values"] = recs.first(MAX_ANSWER).map do |r|
189
- app = r["key"].split("/")[0, 2].join("/")
190
- here = alive.key?(app) ? alive[app] : (alive[app] = @alive.call(app) ? true : false)
191
- h = { "key" => r["key"], "t" => Values.time(r["t"]), "age_s" => (now - r["mono"]).round(1),
192
- "app" => here ? (r["left"] ? "restarted" : "alive") : "gone", "bytes" => r["bytes"],
193
- "format" => r["format"] }
395
+ app = Store.app_of(r)
396
+ h = { "key" => r["key"], "t" => Values.time(r["t"]), "age_s" => (now - r["mono"]).round(1) }
397
+ if app
398
+ here = alive.key?(app) ? alive[app] : (alive[app] = @alive.call(app) ? true : false)
399
+ h["app"] = here ? (r["left"] ? "restarted" : "alive") : "gone"
400
+ end
401
+ h["bytes"] = r["bytes"]
402
+ h["format"] = r["format"]
403
+ %w[from seq run_id sent lost].each { |k| h[k] = r[k] if r.key?(k) }
404
+ if r["raw"] && pics.size < images
405
+ h["image"] = pics.size
406
+ pics << [r["format"], r["raw"]]
407
+ end
194
408
  text = JSON.generate(r["value"])
195
409
  if text.bytesize > VALUE_CUT
196
410
  h["value"] = "#{text.byteslice(0, VALUE_CUT).scrub('')}…"
@@ -208,7 +422,7 @@ module Asterism
208
422
  "it has not been put since this server started (puts come only when a value " \
209
423
  "changes), or the router does not let this server read it"
210
424
  end
211
- out
425
+ [out, pics]
212
426
  end
213
427
  end
214
428
  end