asterism 0.10.0 → 0.12.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.
@@ -0,0 +1,1027 @@
1
+ # Asterism::Transfer: a file carried between two machines in pieces, over
2
+ # calls to an exposed object, that comes through lost, repeated and
3
+ # reordered pieces, a connection that drops for a while and a receiver
4
+ # that is stopped and started again -- and arrives whole or not at all.
5
+ #
6
+ # One source for every machine: the boards load it at run time (it is not
7
+ # compiled into the mrbgem, so an mruby VM that does not carry files pays
8
+ # nothing for it: require "/usr/share/asterism/transfer/transfer" on Family
9
+ # mruby), CRuby loads it through lib/asterism/transfer.rb.
10
+ #
11
+ # The receiver is an Inbox exposed with caller: :from; the machine's own
12
+ # application decides what a file may be (a kind), who may send it, where
13
+ # it goes once whole, by overriding the hooks below. The sender is a
14
+ # Sender, stepped from the application's update loop: one call on its way
15
+ # at a time (or a few, window:), never waiting in one go.
16
+ #
17
+ # The calls (docs: the receiver's position is the truth):
18
+ #
19
+ # begin(kind, meta) meta {"name", "size", "sha256" (hex, of the whole
20
+ # file), ...the kind's own}. -> {"id", "piece" (the
21
+ # largest piece this receiver takes), "window" (how
22
+ # many pieces may be on their way at once), "pos" (the
23
+ # bytes it already holds of this very file: 0, or
24
+ # where it stopped)}. The receiver chooses piece and
25
+ # window (the room a call has, its own memory, the
26
+ # kind); the sender keeps within both (a receiver that
27
+ # names no window is sent one piece at a time). The same sender beginning the same file
28
+ # (name, size and sha256 alike) again goes on where it
29
+ # stopped -- after a lost answer, a dropped connection,
30
+ # or this receiver's application started again (the
31
+ # piece file and a note of the file stay where they
32
+ # were written). Refused (Refused) for a kind or a sender
33
+ # the hooks do not take, or a file that does not fit;
34
+ # Busy while another node's file is coming in. The
35
+ # meta may carry what the kind wants besides (the
36
+ # kind "file" of Family mruby: "overwrite").
37
+ # chunk(id, pos, bytes) -> the position the receiver holds now. Taken at
38
+ # that position only: a piece before it (already here)
39
+ # is read past, a piece after it (one went missing) is
40
+ # not taken; either way the answer says where to go on
41
+ # from, so a piece may arrive any number of times.
42
+ # commit(id) all bytes are here: the whole is checked against the
43
+ # sha256 of begin, then handed to the kind (received).
44
+ # -> the kind's answer; {"status" => "refused",
45
+ # "reason"} when the sha256 does not match (nothing is
46
+ # placed); {"status" => "more", "pos"} when bytes are
47
+ # still missing. Asked again for the same id, the same
48
+ # answer.
49
+ # cancel(id) drops it (and its files); the sender's Sender#cancel.
50
+ #
51
+ # Unknown raised by chunk / commit for an id this receiver
52
+ # does not have (any more): the sender begins again.
53
+ #
54
+ # A file that stops coming: after STALE_MS another node may begin (and the
55
+ # held one is dropped); after keep_ms (KEEP_MS) its files are deleted.
56
+ # Only one file at a time.
57
+ module Asterism
58
+ module Transfer
59
+ # The receiver will not take it: the sender gives up (the message says why).
60
+ class Refused < StandardError; end
61
+ # Another node's file is coming in: the sender may try again later.
62
+ class Busy < StandardError; end
63
+ # The receiver has no such file (any more): the sender begins again.
64
+ class Unknown < StandardError; end
65
+
66
+ # A call carries 4 KB in all on zenoh-pico (Z_FRAG_MAX_SIZE), its key
67
+ # and the arguments' framing included; a larger one is dropped without
68
+ # an error (the caller waits until its time is out).
69
+ CALL_BYTES = 4096
70
+ # What a chunk call needs besides its key and the piece (the request's
71
+ # map, the id and the position: under 40 bytes), with a margin.
72
+ CALL_SPARE = 160
73
+ # The piece a sender sends when the receiver names none (an older
74
+ # receiver), and the largest a receiver names.
75
+ PIECE = 3072
76
+ PIECE_MAX = 3840
77
+ # The pieces on their way at once that a receiver names when its
78
+ # application does not say (Inbox#window), and the most a sender keeps
79
+ # on their way whatever the receiver says (a node's calls wait in a
80
+ # queue of 32 on zenoh-pico).
81
+ WINDOW = 4
82
+ WINDOW_MAX = 16
83
+ # The key length a receiver that does not know its own path assumes.
84
+ KEY_GUESS = 128
85
+ # Where this file and sha256.rb are on the boards.
86
+ DIR = "/usr/share/asterism/transfer"
87
+
88
+ def self.now_ms
89
+ ::Asterism.now_ms
90
+ end
91
+
92
+ # The largest piece a chunk call on a key of key_bytes carries: the 4 KB
93
+ # of a call less the key and CALL_SPARE, in steps of 256, 512 to
94
+ # PIECE_MAX.
95
+ def self.piece_for_key(key_bytes)
96
+ n = ((CALL_BYTES - CALL_SPARE - key_bytes) / 256) * 256
97
+ return PIECE_MAX if n > PIECE_MAX
98
+ n < 512 ? 512 : n
99
+ end
100
+
101
+ # A String of hex digits, n of them.
102
+ def self.hex?(s, n)
103
+ return false unless s.is_a?(String) && s.bytesize == n
104
+ i = 0
105
+ while i < n
106
+ c = s.getbyte(i)
107
+ return false unless (c >= 48 && c <= 57) || (c >= 97 && c <= 102)
108
+ i += 1
109
+ end
110
+ true
111
+ end
112
+
113
+ # A name with no way out of the receiver's directory: letters, digits,
114
+ # _ and -, up to 40 bytes.
115
+ def self.plain_name?(name)
116
+ return false unless name.is_a?(String)
117
+ return false if name.empty? || name.bytesize > 40
118
+ i = 0
119
+ while i < name.bytesize
120
+ c = name.getbyte(i)
121
+ ok = (c >= 97 && c <= 122) || (c >= 65 && c <= 90) || (c >= 48 && c <= 57) || c == 95 || c == 45
122
+ return false unless ok
123
+ i += 1
124
+ end
125
+ true
126
+ end
127
+
128
+ # A file name another machine may give (a receiver's kind that places
129
+ # files under a directory of its own, the kind "file"): no way out of
130
+ # that directory (no "/", "\\" or ".."), not hidden (no "." first),
131
+ # no control characters, 1 to 48 bytes (UTF-8 is fine). The piece file
132
+ # beside it ("<name>.<kind>.part") keeps within 63 bytes.
133
+ def self.file_name?(name)
134
+ return false unless name.is_a?(String)
135
+ n = name.bytesize
136
+ return false if n == 0 || n > 48
137
+ return false if name.getbyte(0) == 46
138
+ i = 0
139
+ while i < n
140
+ c = name.getbyte(i)
141
+ return false if c < 32 || c == 127 || c == 47 || c == 92
142
+ return false if c == 46 && i + 1 < n && name.getbyte(i + 1) == 46
143
+ i += 1
144
+ end
145
+ true
146
+ end
147
+
148
+ # name with " (k)" put before its extension: "foo.txt" -> "foo(1).txt",
149
+ # "foo" -> "foo(1)" (the receiver keeps the file there and places the
150
+ # new one beside it).
151
+ def self.numbered(name, k)
152
+ dot = nil
153
+ i = name.bytesize - 1
154
+ while i > 0
155
+ if name.getbyte(i) == 46
156
+ dot = i
157
+ break
158
+ end
159
+ i -= 1
160
+ end
161
+ return "#{name}(#{k})" if dot.nil?
162
+ "#{name.byteslice(0, dot)}(#{k})#{name.byteslice(dot, name.bytesize - dot)}"
163
+ end
164
+
165
+ # The name to place under dir (it ends in "/"): name itself when there is
166
+ # no such file there, else the first of name(1), name(2), ... that is free.
167
+ def self.free_name(dir, name)
168
+ return name unless ::File.exist?("#{dir}#{name}")
169
+ k = 1
170
+ while k < 10000
171
+ n = numbered(name, k)
172
+ return n unless ::File.exist?("#{dir}#{n}")
173
+ k += 1
174
+ end
175
+ nil
176
+ end
177
+
178
+ def self.to_hex(bin)
179
+ out = ""
180
+ i = 0
181
+ while i < bin.bytesize
182
+ out << format("%02x", bin.getbyte(i))
183
+ i += 1
184
+ end
185
+ out
186
+ end
187
+
188
+ # SHA-256 in pieces: update(bytes), hexdigest. CRuby's Digest, mbedTLS
189
+ # where the build has it (MbedTLS::Digest), else the plain Ruby one
190
+ # (sha256.rb; slow, for builds with neither).
191
+ class SHA256
192
+ def self.engine
193
+ if Object.const_defined?(:Digest) && ::Digest.const_defined?(:SHA256)
194
+ :digest
195
+ elsif Object.const_defined?(:MbedTLS) && ::MbedTLS.const_defined?(:Digest)
196
+ :mbedtls
197
+ else
198
+ :ruby
199
+ end
200
+ end
201
+
202
+ # The digest of a file, read a block at a time.
203
+ def self.file(path, block = 4096)
204
+ d = new
205
+ ::File.open(path, "r") do |f|
206
+ while (b = f.read(block))
207
+ break if b.empty?
208
+ d.update(b)
209
+ end
210
+ end
211
+ d.hexdigest
212
+ end
213
+
214
+ def initialize(engine = nil)
215
+ @engine = engine || SHA256.engine
216
+ if @engine == :digest
217
+ @d = ::Digest::SHA256.new
218
+ elsif @engine == :mbedtls
219
+ @d = ::MbedTLS::Digest.new(:sha256)
220
+ else
221
+ require "#{::Asterism::Transfer::DIR}/sha256" unless ::Asterism::Transfer.const_defined?(:PlainSHA256)
222
+ @d = ::Asterism::Transfer::PlainSHA256.new
223
+ end
224
+ end
225
+
226
+ attr_reader :engine
227
+
228
+ def update(bytes)
229
+ @d.update(bytes)
230
+ self
231
+ end
232
+
233
+ def hexdigest
234
+ return @d.hexdigest if @engine == :digest
235
+ return ::Asterism::Transfer.to_hex(@d.finish) if @engine == :mbedtls
236
+ @d.hexdigest
237
+ end
238
+ end
239
+
240
+ # ------------------------------------------------------------- receiver
241
+
242
+ # The receiving side. Expose it (or a subclass) with caller: :from:
243
+ #
244
+ # Asterism.expose("inbox", inbox, methods: Asterism::Transfer::Inbox::METHODS, caller: :from)
245
+ #
246
+ # and call tick from the update loop. The hooks to override:
247
+ #
248
+ # refused(kind, from, meta) why this is not taken (nil: taken)
249
+ # name_ok?(kind, name) whether the name is one this kind takes
250
+ # (plain_name?: letters, digits, _ and -)
251
+ # room(kind, meta) bytes free where this file goes (nil: not
252
+ # known; it is then refused where it stops
253
+ # being written)
254
+ # part_path(kind, name, meta) where the piece file is written (default
255
+ # "<dir><name>.<kind>.part"; a kind may write
256
+ # it beside the place it goes -- which the
257
+ # meta may choose -- so that the commit has
258
+ # only to rename it). The note
259
+ # of the file ("<dir><name>.<kind>.xfer")
260
+ # stays in dir
261
+ # window(kind, meta) how many pieces may be on their way at once
262
+ # (default the window: given to new)
263
+ # received(t) the file is whole at t["part"]: put it where
264
+ # it belongs -> the answer to commit (a Hash)
265
+ #
266
+ # The piece named to a sender is the largest a call to this inbox carries
267
+ # (path=, "<node>/<app>/<object>": the key is known; else KEY_GUESS), at
268
+ # most the piece: given to new.
269
+ class Inbox
270
+ METHODS = { "begin" => 2, "chunk" => 3, "commit" => 1, "cancel" => 1 }
271
+ # Without a piece for this long, another node may begin.
272
+ STALE_MS = 10000
273
+ # Without a piece for this long, the held file is deleted.
274
+ KEEP_MS = 60000
275
+
276
+ attr_accessor :logger, :path
277
+ attr_reader :dir, :keep_ms
278
+
279
+ # dir: where the files are written (it ends in "/"). piece: the largest
280
+ # piece taken. window: the pieces on their way at once a sender is
281
+ # told (the window hook's default). keep_ms: how long a file that
282
+ # stopped coming is kept.
283
+ def initialize(dir, piece: PIECE_MAX, window: WINDOW, keep_ms: KEEP_MS, stale_ms: STALE_MS)
284
+ @dir = dir
285
+ @piece = piece
286
+ @window = window
287
+ @keep_ms = keep_ms
288
+ @stale_ms = stale_ms
289
+ @t = nil
290
+ @done = nil
291
+ @last_id = ::Asterism::Transfer.now_ms
292
+ @logger = Object.const_defined?(:Log) ? ::Log : nil
293
+ @last_call = -100000
294
+ end
295
+
296
+ # ---- hooks ----
297
+
298
+ def refused(kind, from, meta)
299
+ nil
300
+ end
301
+
302
+ def name_ok?(kind, name)
303
+ ::Asterism::Transfer.plain_name?(name)
304
+ end
305
+
306
+ def room(kind, meta)
307
+ nil
308
+ end
309
+
310
+ def part_path(kind, name, meta)
311
+ "#{@dir}#{name}.#{kind}.part"
312
+ end
313
+
314
+ def window(kind, meta)
315
+ @window
316
+ end
317
+
318
+ def received(t)
319
+ { "status" => "received" }
320
+ end
321
+
322
+ # ---- the calls ----
323
+
324
+ def begin(kind, meta, from: nil)
325
+ @last_call = now_ms
326
+ k = kind.to_s
327
+ m = meta.is_a?(Hash) ? meta : {}
328
+ why = refused(k, from, m)
329
+ raise Refused, why if why
330
+ name = m["name"]
331
+ size = m["size"]
332
+ sha = m["sha256"]
333
+ raise Refused, "not a name for a file: #{name}" unless name_ok?(k, name)
334
+ raise Refused, "size #{size} is not a size" unless size.is_a?(Integer) && size > 0
335
+ raise Refused, "sha256 is not 64 hex digits" unless ::Asterism::Transfer.hex?(sha, 64)
336
+ t = @t
337
+ part = part_path(k, name, m)
338
+ if t && t["from"] == from && t["kind"] == k && t["name"] == name && t["size"] == size && t["sha256"] == sha &&
339
+ t["part"] == part
340
+ open_part(t)
341
+ t["at"] = now_ms
342
+ t["meta"] = m
343
+ info("transfer: #{from} goes on with #{k} #{name} at #{t['got']} of #{size} bytes")
344
+ return { "id" => t["id"], "piece" => piece_for(from), "window" => window_for(k, m), "pos" => t["got"] }
345
+ end
346
+ if t
347
+ if t["from"] != from && now_ms - t["at"] <= @stale_ms
348
+ raise Busy, "busy: a file from #{t['from']} is coming in"
349
+ end
350
+ drop("#{from} begins another")
351
+ end
352
+ left = room(k, m)
353
+ if left && size > left
354
+ raise Refused, "#{size} bytes do not fit (#{left} bytes free)"
355
+ end
356
+ @done = nil if @done && @done["from"] == from
357
+ t = { "id" => new_id, "from" => from, "kind" => k, "name" => name, "size" => size, "sha256" => sha,
358
+ "meta" => m, "got" => 0, "part" => part, "note" => "#{@dir}#{name}.#{k}.xfer",
359
+ "file" => nil, "digest" => nil, "at" => now_ms, "gaps" => 0, "again" => 0 }
360
+ remove(t["part"])
361
+ write_note(t)
362
+ @t = t
363
+ open_part(t)
364
+ piece = piece_for(from)
365
+ win = window_for(k, m)
366
+ info("transfer: #{from} sends #{k} #{name} (#{size} bytes) to #{t['part']}, pieces of #{piece} bytes, " \
367
+ "#{win} at a time")
368
+ { "id" => t["id"], "piece" => piece, "window" => win, "pos" => 0 }
369
+ end
370
+
371
+ def chunk(id, pos, data, from: nil)
372
+ t = current(id, from)
373
+ bytes = data.to_s
374
+ got = t["got"]
375
+ n = bytes.bytesize
376
+ p = pos.is_a?(Integer) ? pos : -1
377
+ raise Refused, "not a position: #{pos}" if p < 0
378
+ t["at"] = now_ms
379
+ if p > got
380
+ t["gaps"] += 1
381
+ return got
382
+ end
383
+ if p + n <= got
384
+ t["again"] += 1
385
+ return got
386
+ end
387
+ bytes = bytes.byteslice(got - p, n - (got - p)).to_s if p < got
388
+ if got + bytes.bytesize > t["size"]
389
+ drop("a piece past #{t['size']} bytes")
390
+ raise Refused, "the piece goes past #{t['size']} bytes"
391
+ end
392
+ open_part(t)
393
+ begin
394
+ t["file"].write(bytes)
395
+ rescue => e
396
+ drop("cannot write: #{e.message}")
397
+ raise Refused, "cannot write at #{got} (#{e.message})"
398
+ end
399
+ t["digest"].update(bytes)
400
+ t["got"] = got + bytes.bytesize
401
+ end
402
+
403
+ def commit(id, from: nil)
404
+ @last_call = now_ms
405
+ d = @done
406
+ return d["answer"] if d && d["id"] == id && d["from"] == from
407
+ t = current(id, from)
408
+ return { "status" => "more", "pos" => t["got"] } if t["got"] < t["size"]
409
+ close_part(t)
410
+ sha = t["digest"].hexdigest
411
+ @t = nil
412
+ remove(t["note"])
413
+ if sha != t["sha256"]
414
+ remove(t["part"])
415
+ warn("transfer: #{t['kind']} #{t['name']} from #{from}: sha256 #{sha[0, 12]}..., " \
416
+ "#{t['sha256'][0, 12]}... was sent; not placed")
417
+ answer = { "status" => "refused",
418
+ "reason" => "the sha256 of the #{t['size']} bytes that came does not match (#{sha[0, 12]}...)" }
419
+ else
420
+ info("transfer: #{t['kind']} #{t['name']} from #{from} is whole (#{t['size']} bytes, sha256 matches; " \
421
+ "#{t['gaps']} gap(s), #{t['again']} piece(s) again)")
422
+ answer = received(t)
423
+ end
424
+ @done = { "id" => id, "from" => from, "answer" => answer, "t" => t }
425
+ answer
426
+ end
427
+
428
+ def cancel(id, from: nil)
429
+ @last_call = now_ms
430
+ t = @t
431
+ if t && t["id"] == id && t["from"] == from
432
+ drop("cancelled by #{from}")
433
+ return true
434
+ end
435
+ false
436
+ end
437
+
438
+ # ---- the application's side ----
439
+
440
+ # Call from the update loop: a file that stopped coming is deleted
441
+ # once keep_ms has gone by.
442
+ def tick
443
+ t = @t
444
+ drop("no piece for #{@keep_ms} ms") if t && now_ms - t["at"] > @keep_ms
445
+ nil
446
+ end
447
+
448
+ # A call came in a moment ago (the application may poll more often).
449
+ def busy?(ms = 2000)
450
+ now_ms - @last_call < ms
451
+ end
452
+
453
+ # The file coming in (a Hash), nil when none.
454
+ def current_file
455
+ @t
456
+ end
457
+
458
+ # The last committed one: {"id", "from", "answer", "t"}.
459
+ def last_done
460
+ @done
461
+ end
462
+
463
+ # The application ends: the files stay, for a start again to go on.
464
+ def close
465
+ t = @t
466
+ close_part(t) if t
467
+ nil
468
+ end
469
+
470
+ # The application starts: a file held when it last ended is taken up
471
+ # again (counted from now for keep_ms), the others are deleted.
472
+ def resume_held
473
+ names = held_notes
474
+ i = 0
475
+ while i < names.size
476
+ path = "#{@dir}#{names[i]}"
477
+ t = read_note(path)
478
+ if t && @t.nil?
479
+ got = ::File.exist?(t["part"]) ? ::File.size(t["part"]) : 0
480
+ got = t["size"] if got > t["size"]
481
+ t["got"] = got
482
+ t["at"] = now_ms
483
+ @t = t
484
+ info("transfer: held #{t['kind']} #{t['name']} from #{t['from']} (#{got} of #{t['size']} bytes)")
485
+ else
486
+ remove(path)
487
+ remove(t ? t["part"] : "#{path.byteslice(0, path.bytesize - 5)}.part")
488
+ end
489
+ i += 1
490
+ end
491
+ nil
492
+ end
493
+
494
+ # ---- inside ----
495
+
496
+ def now_ms
497
+ ::Asterism::Transfer.now_ms
498
+ end
499
+
500
+ def info(msg)
501
+ @logger.info(msg) if @logger
502
+ end
503
+
504
+ def warn(msg)
505
+ @logger.warn(msg) if @logger
506
+ end
507
+
508
+ # The largest piece a call from this sender carries here.
509
+ def piece_for(from)
510
+ key = @path ? "asterism/#{@path}/call/#{from}".bytesize : KEY_GUESS
511
+ n = ::Asterism::Transfer.piece_for_key(key)
512
+ n < @piece ? n : @piece
513
+ end
514
+
515
+ def window_for(kind, meta)
516
+ w = window(kind, meta)
517
+ w = 1 unless w.is_a?(Integer) && w >= 1
518
+ w > WINDOW_MAX ? WINDOW_MAX : w
519
+ end
520
+
521
+ def new_id
522
+ id = now_ms
523
+ id = @last_id + 1 if id <= @last_id
524
+ @last_id = id
525
+ id
526
+ end
527
+
528
+ def current(id, from)
529
+ @last_call = now_ms
530
+ t = @t
531
+ raise Unknown, "no file #{id} is coming in from #{from}" unless t && t["id"] == id && t["from"] == from
532
+ t
533
+ end
534
+
535
+ # The piece file open for appending, and the digest of what it holds.
536
+ def open_part(t)
537
+ return if t["file"]
538
+ d = SHA256.new
539
+ got = 0
540
+ if t["got"] > 0 && ::File.exist?(t["part"])
541
+ ::File.open(t["part"], "r") do |f|
542
+ while got < t["got"]
543
+ b = f.read(t["got"] - got > 4096 ? 4096 : t["got"] - got)
544
+ break if b.nil? || b.empty?
545
+ d.update(b)
546
+ got += b.bytesize
547
+ end
548
+ end
549
+ end
550
+ if got != t["got"]
551
+ # shorter than noted: start over
552
+ remove(t["part"])
553
+ d = SHA256.new
554
+ got = 0
555
+ end
556
+ t["got"] = got
557
+ t["digest"] = d
558
+ t["file"] = ::File.open(t["part"], got > 0 ? "a" : "w")
559
+ end
560
+
561
+ def close_part(t)
562
+ f = t["file"]
563
+ return unless f
564
+ t["file"] = nil
565
+ f.close
566
+ rescue => e
567
+ warn("transfer: close: #{e.message}")
568
+ end
569
+
570
+ def drop(why)
571
+ t = @t
572
+ return nil unless t
573
+ @t = nil
574
+ warn("transfer: #{t['kind']} #{t['name']} from #{t['from']} dropped at #{t['got']} of #{t['size']} bytes: #{why}")
575
+ close_part(t)
576
+ remove(t["part"])
577
+ remove(t["note"])
578
+ nil
579
+ end
580
+
581
+ def remove(path)
582
+ ::File.delete(path) if ::File.exist?(path)
583
+ rescue => e
584
+ warn("transfer: delete #{path}: #{e.message}")
585
+ end
586
+
587
+ # The note beside the piece file: who sends what (JSON, one line).
588
+ def write_note(t)
589
+ h = { "from" => t["from"], "kind" => t["kind"], "name" => t["name"], "size" => t["size"],
590
+ "sha256" => t["sha256"], "meta" => t["meta"] }
591
+ ::File.open(t["note"], "w") { |f| f.write(::JSON.generate(h)) }
592
+ end
593
+
594
+ def read_note(path)
595
+ text = ::File.open(path, "r") { |f| f.read }
596
+ h = ::JSON.parse(text.to_s)
597
+ return nil unless h.is_a?(Hash) && h["size"].is_a?(Integer)
598
+ k = h["kind"].to_s
599
+ return nil unless name_ok?(k, h["name"])
600
+ { "id" => new_id, "from" => h["from"], "kind" => k, "name" => h["name"], "size" => h["size"],
601
+ "sha256" => h["sha256"], "meta" => h["meta"].is_a?(Hash) ? h["meta"] : {}, "got" => 0,
602
+ "part" => part_path(k, h["name"], h["meta"].is_a?(Hash) ? h["meta"] : {}), "note" => path, "file" => nil, "digest" => nil, "at" => now_ms,
603
+ "gaps" => 0, "again" => 0 }
604
+ rescue => e
605
+ warn("transfer: #{path}: #{e.message}")
606
+ nil
607
+ end
608
+
609
+ def held_notes
610
+ out = []
611
+ names = ::Dir.entries(@dir.byteslice(0, @dir.bytesize - 1))
612
+ i = 0
613
+ while i < names.size
614
+ n = names[i].to_s
615
+ out << n if n.bytesize > 5 && n.byteslice(n.bytesize - 5, 5) == ".xfer"
616
+ i += 1
617
+ end
618
+ out
619
+ rescue => e
620
+ warn("transfer: #{@dir}: #{e.message}")
621
+ []
622
+ end
623
+ end
624
+
625
+ # --------------------------------------------------------------- sender
626
+
627
+ # The sending side of one file. Made with the receiver's path
628
+ # ("<node>/<app>/<object>"), the kind, the local file and the meta the
629
+ # kind wants; call step from the update loop until done?. Then ok? and
630
+ # answer (commit's answer: the kind's), or reason.
631
+ #
632
+ # The receiver's position is the truth: every answer says where it
633
+ # stands and the next piece goes from there. A call that fails (no
634
+ # answer in time, the connection gone, the receiver busy or started
635
+ # again) is tried again after a wait that doubles (RETRY_MS up to
636
+ # RETRY_MAX_MS), by beginning again -- the receiver answers where it
637
+ # stopped. tries failures in a row without a byte of progress end it.
638
+ #
639
+ # The receiver names the piece size and how many pieces may be on their
640
+ # way at once (begin's answer); piece: and window: are only the most
641
+ # this sender goes to (a receiver that names no window gets one piece
642
+ # at a time, as before).
643
+ class Sender
644
+ RETRY_MS = 200
645
+ RETRY_MAX_MS = 4000
646
+ TRIES = 8
647
+ CALL_TIMEOUT_MS = 10000
648
+
649
+ attr_accessor :logger
650
+ attr_reader :path, :size, :sha256, :answer, :reason, :stats, :pos, :id, :kind, :piece, :window
651
+
652
+ def initialize(to, kind, path, meta: {}, name: nil, piece: PIECE_MAX, window: WINDOW_MAX,
653
+ timeout_ms: CALL_TIMEOUT_MS, tries: TRIES, sha256: nil)
654
+ @to = to
655
+ @kind = kind
656
+ @path = path
657
+ @piece_max = piece
658
+ @window_max = window < 1 ? 1 : window
659
+ @window = 1
660
+ @timeout_ms = timeout_ms
661
+ @tries_max = tries
662
+ @logger = Object.const_defined?(:Log) ? ::Log : nil
663
+ @size = ::File.size(path)
664
+ @sha256 = sha256 || SHA256.file(path)
665
+ @meta = {}
666
+ meta.each { |k, v| @meta[k] = v }
667
+ @meta["name"] = name if name
668
+ @meta["size"] = @size
669
+ @meta["sha256"] = @sha256
670
+ @state = :begin
671
+ @id = nil
672
+ @piece = piece
673
+ @pos = 0 # what the receiver holds, as last told
674
+ @next = 0 # the next byte to send
675
+ @inflight = [] # [future, pos, length] in the order sent
676
+ @fut = nil # begin / commit on its way
677
+ @retry_at = nil
678
+ @tries = 0
679
+ @answer = nil
680
+ @reason = nil
681
+ @file = nil
682
+ @file_pos = 0
683
+ @cache = [] # [pos, bytes] of the last pieces read
684
+ @stats = { "calls" => 0, "pieces" => 0, "again" => 0, "retries" => 0, "begins" => 0, "resumed_at" => [] }
685
+ @t0 = now_ms
686
+ end
687
+
688
+ def done?
689
+ @state == :done || @state == :failed
690
+ end
691
+
692
+ def ok?
693
+ @state == :done
694
+ end
695
+
696
+ # commit was asked at least once: the receiver may have the whole
697
+ # file (and have acted on it) even when the answer never came.
698
+ def committing?
699
+ @committing == true
700
+ end
701
+
702
+ def took_ms
703
+ now_ms - @t0
704
+ end
705
+
706
+ # One step: issues the calls there is room for, takes the answers in.
707
+ # Never waits.
708
+ def step
709
+ return if done?
710
+ if @retry_at
711
+ return if now_ms < @retry_at
712
+ @retry_at = nil
713
+ @state = :begin
714
+ end
715
+ if @state == :begin
716
+ return call_begin if @fut.nil?
717
+ return unless @fut.done?
718
+ v = take(@fut)
719
+ @fut = nil
720
+ return if v.nil?
721
+ begun(v)
722
+ elsif @state == :chunk
723
+ pump
724
+ elsif @state == :commit
725
+ return call_commit if @fut.nil?
726
+ return unless @fut.done?
727
+ v = take(@fut)
728
+ @fut = nil
729
+ return if v.nil?
730
+ committed(v)
731
+ end
732
+ nil
733
+ end
734
+
735
+ # Gives up on purpose: the receiver is asked to drop what it holds of
736
+ # this file (its piece file and note; nothing is placed), without
737
+ # waiting for its answer. -> false when already done.
738
+ def cancel
739
+ return false if done?
740
+ id = @id
741
+ if id
742
+ begin
743
+ call("cancel", id)
744
+ rescue ::Asterism::Error
745
+ nil
746
+ end
747
+ end
748
+ finish_failed("cancelled")
749
+ @cancelled = true
750
+ true
751
+ end
752
+
753
+ def cancelled?
754
+ @cancelled == true
755
+ end
756
+
757
+ # Stops (the application ends, or gives up): the file is closed.
758
+ def close
759
+ close_file
760
+ @state = :failed if !done?
761
+ @reason ||= "stopped"
762
+ end
763
+
764
+ # ---- the test's hook ----
765
+
766
+ # What happens to the piece at pos (length n) on its way: nil (sent),
767
+ # :drop (not sent; the next one is), :twice (sent two times), :swap
768
+ # (the next piece is sent before it). For the fault tests.
769
+ def fault(pos, n)
770
+ nil
771
+ end
772
+
773
+ # ---- inside ----
774
+
775
+ def now_ms
776
+ ::Asterism::Transfer.now_ms
777
+ end
778
+
779
+ def info(msg)
780
+ @logger.info(msg) if @logger
781
+ end
782
+
783
+ def proxy
784
+ ::Asterism[@to, timeout_ms: @timeout_ms].async
785
+ end
786
+
787
+ def call(method, *args)
788
+ @stats["calls"] += 1
789
+ proxy.asterism_call(method, *args)
790
+ end
791
+
792
+ def call_begin
793
+ @stats["begins"] += 1
794
+ @inflight = []
795
+ @fut = call("begin", @kind, @meta)
796
+ rescue ::Asterism::Error => e
797
+ failed_call(e)
798
+ end
799
+
800
+ def call_commit
801
+ @committing = true
802
+ @fut = call("commit", @id)
803
+ rescue ::Asterism::Error => e
804
+ failed_call(e)
805
+ end
806
+
807
+ # The answer of a future, or nil after dealing with its failure.
808
+ def take(f)
809
+ f.value
810
+ rescue ::Asterism::RemoteError => e
811
+ cls = e.remote_class.to_s
812
+ if ends_with?(cls, "Refused")
813
+ finish_failed(e.remote_message)
814
+ elsif ends_with?(cls, "Unknown")
815
+ info("transfer: #{@to} has no file #{@id} (any more); beginning again")
816
+ @state = :begin
817
+ @inflight = []
818
+ else
819
+ failed_call(e)
820
+ end
821
+ nil
822
+ rescue ::Asterism::Error => e
823
+ failed_call(e)
824
+ nil
825
+ end
826
+
827
+ def int(v)
828
+ v.is_a?(Integer) ? v : 0
829
+ end
830
+
831
+ def ends_with?(s, tail)
832
+ s.bytesize >= tail.bytesize && s.byteslice(s.bytesize - tail.bytesize, tail.bytesize) == tail
833
+ end
834
+
835
+ # A call failed: wait, then begin again (asking where the receiver is).
836
+ def failed_call(e)
837
+ @fut = nil
838
+ @inflight = []
839
+ @tries += 1
840
+ msg = e.respond_to?(:remote_message) ? e.remote_message.to_s : e.message.to_s
841
+ if @tries > @tries_max
842
+ return finish_failed("#{@to}: gave up after #{@tries - 1} tries (#{msg})")
843
+ end
844
+ wait = RETRY_MS
845
+ i = 1
846
+ while i < @tries && wait < RETRY_MAX_MS
847
+ wait *= 2
848
+ i += 1
849
+ end
850
+ wait = RETRY_MAX_MS if wait > RETRY_MAX_MS
851
+ @stats["retries"] += 1
852
+ info("transfer: #{@to}: #{msg}; asking again in #{wait} ms (try #{@tries})")
853
+ @retry_at = now_ms + wait
854
+ nil
855
+ end
856
+
857
+ def begun(v)
858
+ r = v.is_a?(Hash) ? v : {}
859
+ @id = r["id"]
860
+ p = int(r["piece"])
861
+ @piece = p > 0 && p < @piece_max ? p : @piece_max
862
+ w = int(r["window"])
863
+ w = 1 if w < 1
864
+ @window = w < @window_max ? w : @window_max
865
+ if @stats["begins"] == 1
866
+ info("transfer: #{@to} takes pieces of #{@piece} bytes, #{@window} at a time")
867
+ end
868
+ pos = int(r["pos"])
869
+ pos = 0 if pos < 0 || pos > @size
870
+ if @stats["begins"] > 1 || pos > 0
871
+ @stats["resumed_at"] << pos
872
+ info("transfer: #{@to} holds #{pos} of #{@size} bytes; going on from there")
873
+ end
874
+ progress(pos)
875
+ @next = pos
876
+ @state = pos >= @size ? :commit : :chunk
877
+ pump if @state == :chunk
878
+ end
879
+
880
+ def progress(pos)
881
+ @tries = 0 if pos > @pos
882
+ @pos = pos
883
+ end
884
+
885
+ # Keeps up to window pieces on their way; takes their answers in order.
886
+ def pump
887
+ while !@inflight.empty?
888
+ f = @inflight[0][0]
889
+ break unless f.done?
890
+ ent = @inflight.shift
891
+ v = take(f)
892
+ return if v.nil?
893
+ held = int(v)
894
+ progress(held) if held > @pos
895
+ if held < ent[1] + ent[2] && held < @size
896
+ # the receiver stands before the end of this piece: go on from
897
+ # where it is (the pieces still on their way are read past or
898
+ # not taken there)
899
+ @stats["again"] += 1
900
+ @next = held
901
+ @inflight = []
902
+ break
903
+ end
904
+ end
905
+ if @pos >= @size && @inflight.empty?
906
+ @state = :commit
907
+ close_file
908
+ return call_commit
909
+ end
910
+ while @inflight.size < @window && @next < @size
911
+ send_from(@next)
912
+ end
913
+ end
914
+
915
+ def send_from(pos)
916
+ n = @size - pos
917
+ n = @piece if n > @piece
918
+ what = fault(pos, n)
919
+ if what == :drop
920
+ @next = pos + n
921
+ return if @next >= @size
922
+ pos = @next
923
+ n = @size - pos
924
+ n = @piece if n > @piece
925
+ what = nil
926
+ end
927
+ if what == :swap && pos + n < @size
928
+ m = @size - (pos + n)
929
+ m = @piece if m > @piece
930
+ send_piece(pos + n, m)
931
+ send_piece(pos, n)
932
+ @next = pos + n + m
933
+ return
934
+ end
935
+ send_piece(pos, n)
936
+ send_piece(pos, n) if what == :twice
937
+ @next = pos + n
938
+ end
939
+
940
+ def send_piece(pos, n)
941
+ data = read_at(pos, n)
942
+ return finish_failed("cannot read #{@path} at #{pos}") if data.nil?
943
+ @stats["pieces"] += 1
944
+ @inflight << [call("chunk", @id, pos, data), pos, n]
945
+ rescue ::Asterism::Error => e
946
+ failed_call(e)
947
+ end
948
+
949
+ def committed(v)
950
+ r = v.is_a?(Hash) ? v : {}
951
+ if r["status"].to_s == "more"
952
+ @next = int(r["pos"])
953
+ @pos = @next
954
+ @state = :chunk
955
+ return pump
956
+ end
957
+ @answer = r
958
+ @state = :done
959
+ close_file
960
+ nil
961
+ end
962
+
963
+ def finish_failed(why)
964
+ @reason = why.to_s
965
+ @state = :failed
966
+ @fut = nil
967
+ @inflight = []
968
+ close_file
969
+ nil
970
+ end
971
+
972
+ # The bytes at pos: from the last pieces read, else from the file (read
973
+ # on from where it is, or opened again and read up to pos: the boards'
974
+ # files have no seek).
975
+ def read_at(pos, n)
976
+ i = 0
977
+ while i < @cache.size
978
+ c = @cache[i]
979
+ return c[1] if c[0] == pos && c[1].bytesize == n
980
+ i += 1
981
+ end
982
+ if @file && @file_pos != pos && seek_to(pos)
983
+ @file_pos = pos
984
+ end
985
+ if @file.nil? || @file_pos > pos
986
+ close_file
987
+ @file = ::File.open(@path, "r")
988
+ @file_pos = 0
989
+ @file_pos = pos if pos > 0 && seek_to(pos)
990
+ end
991
+ while @file_pos < pos
992
+ k = pos - @file_pos
993
+ k = 4096 if k > 4096
994
+ b = @file.read(k)
995
+ return nil if b.nil? || b.empty?
996
+ @file_pos += b.bytesize
997
+ end
998
+ data = @file.read(n)
999
+ return nil if data.nil? || data.bytesize != n
1000
+ @file_pos += n
1001
+ data = data.b if data.respond_to?(:b)
1002
+ @cache << [pos, data]
1003
+ @cache.shift while @cache.size > @window + 2
1004
+ data
1005
+ end
1006
+
1007
+ # Moves the file to pos where the File has seek (CRuby, and the boards'
1008
+ # that have it); false where it has none (then it is read up to pos).
1009
+ def seek_to(pos)
1010
+ return false unless @file.respond_to?(:seek)
1011
+ @file.seek(pos)
1012
+ true
1013
+ rescue ScriptError, StandardError
1014
+ false
1015
+ end
1016
+
1017
+ def close_file
1018
+ f = @file
1019
+ @file = nil
1020
+ @file_pos = 0
1021
+ f.close if f
1022
+ rescue
1023
+ nil
1024
+ end
1025
+ end
1026
+ end
1027
+ end