opentideconstants 0.0.0 → 0.1.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,1135 @@
1
+ require "fileutils"
2
+ require "monitor"
3
+ require "json"
4
+ require "uri"
5
+ require "zlib"
6
+ require "digest"
7
+
8
+ class OpenTideConstants
9
+ FORMATS = %w[json json.gz jsonl].freeze
10
+ MODES = %w[eager stream].freeze
11
+ ON_NETWORK_ERROR = %w[use_cache raise].freeze
12
+
13
+ # The current release, with an interval check when automatic updates apply.
14
+ # After close the stored release metadata stays readable without an update.
15
+ def release
16
+ maybe_auto_update
17
+ @release
18
+ end
19
+ # Where the release came from: :download, :cache, :cache_after_error, :file or :file_unverified.
20
+ attr_reader :loaded_from
21
+ # The error behind loaded_from :cache_after_error, or the error of the
22
+ # last automatic update that failed; nil after any check
23
+ # (manual or automatic) reaches the latest pointer, or when there is none.
24
+ #
25
+ attr_reader :last_error
26
+ # The format major of a release on the server that this SDK cannot read
27
+ # (newer than every supported major), as check_for_update last saw it; or nil.
28
+ attr_reader :newer_format_major
29
+
30
+ # The original constructor validation/default phase, before acquisition.
31
+ module ConstructorArguments
32
+ ResolvedOptions = Struct.new(:requested, :mode, :on_network_error, :offline, :auto_update, :verify_on_open, :commercial_only, :commercial_basis, :historical_offsets_policy, :update_interval, :base_url, :cache_dir, :logger, keyword_init: true)
33
+ private
34
+
35
+ def constructor_options(release: :latest, file: nil, cache_dir: nil, offline: false, mode: :stream, base_url: nil, timeout: nil, proxy: nil, ca_file: nil, user_agent: nil, on_network_error: :use_cache, auto_update: false, update_interval: 86_400, logger: nil, verify_on_open: false, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback, environment: ENV)
36
+ # A file client reads no pointer and opens no socket, so these options
37
+ # would be silently ignored. The variable
38
+ # OPENTIDECONSTANTS_OFFLINE is not an option and does not conflict.
39
+ if file && (release != :latest || offline != false || on_network_error != :use_cache)
40
+ raise InvalidArgumentError, "file cannot be combined with release, offline or on_network_error"
41
+ end
42
+ requested = check_release_arg(release)
43
+ mode = check_enum(mode, MODES, "mode").to_sym
44
+ on_network_error = check_enum(on_network_error, ON_NETWORK_ERROR, "on_network_error").to_sym
45
+ # The variable turns offline on with 1, true, yes or on, and then wins over offline: false.
46
+ offline = check_bool(offline, "offline") || %w[1 true yes on].include?(environment["OPENTIDECONSTANTS_OFFLINE"].to_s.strip.downcase)
47
+ auto_update = check_bool(auto_update, "auto_update")
48
+ verify_on_open = check_bool(verify_on_open, "verify_on_open")
49
+ # Select only sets whose licence allows commercial use, in every
50
+ # release this client loads.
51
+ commercial_only = check_bool(commercial_only, "commercial_only")
52
+ commercial_basis = check_enum(commercial_basis, %w[strict as_published_upstream], "commercial_basis").to_sym
53
+ historical_offsets_policy = check_enum(historical_offsets_policy, %w[fallback exclude], "historical_offsets_policy").to_sym
54
+ unless update_interval.is_a?(Numeric) && update_interval.positive?
55
+ raise InvalidArgumentError, "update_interval must be a number of seconds > 0"
56
+ end
57
+ update_interval = update_interval
58
+ # 0.001 to 1e6 s in every SDK; a Float NaN fails the range check too
59
+ unless timeout.nil? || (timeout.is_a?(Numeric) && timeout.real? && timeout >= HTTP::TIMEOUT_MIN && timeout <= HTTP::TIMEOUT_MAX)
60
+ raise InvalidArgumentError, "timeout must be nil or a number of seconds from #{HTTP::TIMEOUT_MIN} to #{HTTP::TIMEOUT_MAX.to_i}"
61
+ end
62
+ %i[proxy ca_file user_agent].zip([proxy, ca_file, user_agent]).each do |name, v|
63
+ raise InvalidArgumentError, "#{name} must be a String" unless v.nil? || v.is_a?(String)
64
+ end
65
+ # user_agent goes into a header: no control character
66
+ if user_agent && (!user_agent.valid_encoding? || user_agent.match?(/[[:cntrl:]]/))
67
+ raise InvalidArgumentError, "user_agent must have no control characters: #{user_agent.inspect}"
68
+ end
69
+ raise InvalidArgumentError, "base_url must be nil or a String" unless base_url.nil? || base_url.is_a?(String)
70
+ base_url ||= environment["OPENTIDECONSTANTS_BASE_URL"]
71
+ base_url = DEFAULT_BASE_URL if base_url.nil? || base_url.empty?
72
+ HTTP.check_url!(base_url, "base_url")
73
+ base_url = base_url.end_with?("/") ? base_url : "#{base_url}/"
74
+ raise InvalidArgumentError, "cache_dir must be a String" unless cache_dir.nil? || cache_dir.is_a?(String)
75
+ cache_dir = cache_dir
76
+ logger = logger
77
+ ResolvedOptions.new(requested: requested, mode: mode, on_network_error: on_network_error, offline: offline, auto_update: auto_update, verify_on_open: verify_on_open, commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy, update_interval: update_interval, base_url: base_url, cache_dir: cache_dir, logger: logger).freeze
78
+ end
79
+
80
+ def bind_client_option_fields(options)
81
+ @requested = options.requested
82
+ @mode = options.mode
83
+ @on_network_error = options.on_network_error
84
+ @offline = options.offline
85
+ @auto_update = options.auto_update
86
+ @verify_on_open = options.verify_on_open
87
+ @commercial_only = options.commercial_only
88
+ @commercial_basis = options.commercial_basis
89
+ @historical_offsets_policy = options.historical_offsets_policy
90
+ @update_interval = options.update_interval
91
+ @base_url = options.base_url
92
+ @cache_dir = options.cache_dir
93
+ @logger = options.logger
94
+ end
95
+
96
+ def bind_prepared_client_fields(prepared)
97
+ bind_client_option_fields(prepared)
98
+ @http = prepared.http
99
+ @lock = prepared.lock
100
+ @closed = prepared.closed
101
+ @last_error = prepared.last_error
102
+ @newer_format_major = prepared.newer_format_major
103
+ @file = prepared.file
104
+ @loaded = prepared.loaded
105
+ @release = prepared.release
106
+ @loaded_from = prepared.loaded_from
107
+ @last_check = prepared.last_check
108
+ @cache = prepared.cache
109
+ end
110
+
111
+ def check_release_arg(release)
112
+ return :latest if release == :latest || release == "latest"
113
+ unless release.is_a?(String) && release.match?(DATESTAMP_RE)
114
+ raise InvalidArgumentError, "release must be :latest or a datestamp like 20261008 or 20261008.2, not #{release.inspect}"
115
+ end
116
+ release
117
+ end
118
+
119
+ def check_enum(value, allowed, name)
120
+ v = value.is_a?(Symbol) ? value.to_s : value
121
+ raise InvalidArgumentError, "#{name} must be one of #{allowed.join(', ')}, not #{value.inspect}" unless allowed.include?(v)
122
+ v
123
+ end
124
+
125
+ def check_bool(value, name)
126
+ raise InvalidArgumentError, "#{name} must be true or false" unless value == true || value == false
127
+ value
128
+ end
129
+
130
+ end
131
+ include ConstructorArguments
132
+ private_constant :ConstructorArguments
133
+
134
+ # Opens a client and yields it, closing it afterwards. Without a block it
135
+ # is the same as new.
136
+ def self.open(**options)
137
+ client = new(**options)
138
+ return client unless block_given?
139
+ begin
140
+ yield client
141
+ ensure
142
+ client.close
143
+ end
144
+ end
145
+
146
+ # Opens the latest release (the default), a pinned release
147
+ # (release: "20261008") or a local file (file: "…/OTC_20261008.jsonl").
148
+ # See for the options.
149
+ def initialize(release: :latest, file: nil, cache_dir: nil, offline: false, mode: :stream, base_url: nil,
150
+ timeout: nil, proxy: nil, ca_file: nil, user_agent: nil, on_network_error: :use_cache,
151
+ auto_update: false, update_interval: 86_400, logger: nil, verify_on_open: false,
152
+ commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback)
153
+ options = constructor_options(release: release, file: file, cache_dir: cache_dir, offline: offline, mode: mode, base_url: base_url, timeout: timeout, proxy: proxy, ca_file: ca_file, user_agent: user_agent, on_network_error: on_network_error, auto_update: auto_update, update_interval: update_interval, logger: logger, verify_on_open: verify_on_open, commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy)
154
+ bind_client_option_fields(options)
155
+ @http = HTTP.new(timeout: timeout, proxy: proxy, ca_file: ca_file, user_agent: user_agent, logger: logger)
156
+ @lock = Monitor.new
157
+ @closed = false
158
+ @last_error = nil
159
+ @newer_format_major = nil
160
+ @file = file
161
+ @loaded = ObjectSpace::WeakMap.new # every Release this client loaded, while a caller holds it
162
+ if file
163
+ @release, @loaded_from = Reader.open_file(file, mode: @mode, logger: @logger, commercial_only: @commercial_only, commercial_basis: @commercial_basis, historical_offsets_policy: @historical_offsets_policy)
164
+ elsif @requested == :latest
165
+ open_latest
166
+ else
167
+ open_pinned(@requested)
168
+ end
169
+ @last_check = monotonic
170
+ @loaded[@release] = true
171
+ log(:info, "loaded #{@release.datestamp} (#{@loaded_from})")
172
+ end
173
+
174
+ # ---- release management
175
+
176
+ # Every release, newest first, from OTC_index.json.
177
+ def releases
178
+ check_open!
179
+ list = index_entries(fetch_pointer_doc("OTC_index.json", missing: :offline))
180
+ list.each { |e| note_version_doi(e) }
181
+ list.map { |e| release_info(e, @base_url + "OTC_index.json") }
182
+ .sort_by { |i| Cache.datestamp_key(i.datestamp) }.reverse.freeze
183
+ end
184
+
185
+ # The newest release this gem reads: the latest pointer (a conditional
186
+ # GET), and OTC_index.json too when the pointer's release is not readable
187
+ # It does not switch to it.
188
+ def latest
189
+ check_open!
190
+ raise OfflineError, "offline: the latest pointer is not available" if @offline
191
+ entry, url = resolve_latest
192
+ release_info(entry, url)
193
+ end
194
+
195
+ # A release newer than the loaded one, with a supported format major and
196
+ # a readable min_reader_version, or nil. It also
197
+ # sets newer_format_major when the server has a release of a newer major,
198
+ # also when it then raises because only such releases exist.
199
+ def check_for_update
200
+ check_open!
201
+ raise OfflineError, "offline: the latest pointer is not available" if @offline
202
+ begin
203
+ entry, url = resolve_latest
204
+ rescue UnsupportedFormatError, ReaderTooOldError
205
+ check_newer_major
206
+ raise
207
+ end
208
+ check_newer_major
209
+ info = release_info(entry, url)
210
+ newer?(info.datestamp, @release.datestamp) ? info : nil
211
+ end
212
+
213
+ # Downloads and checks the latest release and swaps it in atomically. A
214
+ # Release held from before stays valid.
215
+ def update!
216
+ check_open!
217
+ raise PinnedReleaseError, "the client was opened on a file" if @file
218
+ raise PinnedReleaseError, "the client was opened on release #{@requested}" unless @requested == :latest
219
+ # update is defined against the pointer, so offline it cannot run, and
220
+ # it does not switch to a newer cached release either.
221
+ raise OfflineError, "offline: update needs the latest pointer" if @offline
222
+ @lock.synchronize do
223
+ # Again under the lock: a close that ran since the check above
224
+ # wins, so no release is swapped in after close that nothing
225
+ # would close.
226
+ check_open!
227
+ from = @release.datestamp
228
+ entry, url = resolve_latest
229
+ unless newer?(entry["datestamp"], from)
230
+ @last_check = monotonic
231
+ return UpdateResult.new(false, from, from)
232
+ end
233
+ rel, how = load_from_entry(entry, url)
234
+ @loaded[rel] = true
235
+ @release = rel
236
+ @loaded_from = how
237
+ @last_error = nil
238
+ @last_check = monotonic
239
+ log(:info, "updated from #{from} to #{rel.datestamp}")
240
+ UpdateResult.new(true, from, rel.datestamp)
241
+ end
242
+ end
243
+
244
+ # Writes a release into a folder the caller chooses: the
245
+ # data files of formats, and always OTC_{D}.meta.json and OTC_{D}.sha256,
246
+ # whatever the formats; all of them or none. Returns the paths written, in that
247
+ # order with the .sha256 last; a file already there with the same content
248
+ # is left alone and is not in the list.
249
+ def download(release = :latest, to:, formats: [:jsonl], overwrite: false)
250
+ check_open!
251
+ want = check_release_arg(release)
252
+ raise InvalidArgumentError, "to must be a String path" unless to.is_a?(String) && !to.empty?
253
+ raise InvalidArgumentError, "formats must be an Array" unless formats.is_a?(Array) && !formats.empty?
254
+ formats = formats.map { |f| check_enum(f, FORMATS, "format") }.uniq
255
+ check_bool(overwrite, "overwrite")
256
+ Downloader.new(self, want, File.expand_path(to), formats, overwrite).run
257
+ end
258
+
259
+ # Hashes the loaded files again and compares them with OTC_{D}.sha256.
260
+ # A client on a file with no .sha256 next to it has nothing to compare
261
+ # with: checksum_mismatch.
262
+ def verify
263
+ check_open!
264
+ verify_release_integrity
265
+ end
266
+
267
+ def verify_release_integrity(canonical: nil, trusted_cached_pointer: nil)
268
+ if @loaded_from == :file_unverified
269
+ raise ChecksumError.new("no OTC_#{@release.datestamp}.sha256 next to the file", file: @file, expected: nil, actual: nil)
270
+ end
271
+ # Compare with OTC_{D}.sha256, read again: next to the file, or in
272
+ # the cache directory of a cached release. A missing one is
273
+ # checksum_mismatch, never verified.
274
+ d = @release.datestamp
275
+ sha_name = "OTC_#{d}.sha256"
276
+ first = @release.send(:opened_paths).first
277
+ dir = @file ? File.dirname(first || @file) : cache.release_dir(d)
278
+ sha_path = File.join(dir, sha_name)
279
+ raise ChecksumError.new("no #{sha_name} next to #{first}", file: first, expected: nil, actual: nil) unless File.file?(sha_path)
280
+ text = Reader.read_text(sha_path)
281
+ # A cached release: the cached OTC_{D}.sha256 must have the SHA-256
282
+ # that a cached pointer lists for it, when one lists it. verify
283
+ # fetches nothing, so a mismatch is checksum_mismatch and the file
284
+ # stays.
285
+ if !@file || trusted_cached_pointer
286
+ actual = Digest::SHA256.hexdigest(text)
287
+ digests = @file ? [] : cached_pointer_sha256(d)
288
+ supplied = trusted_cached_pointer&.digests&.fetch(sha_name, nil)
289
+ digests = digests + [supplied.downcase] if supplied
290
+ digests.each do |expected|
291
+ next if expected == actual
292
+ raise ChecksumError.new("#{sha_name}: SHA-256 #{actual}, but the cached pointer lists #{expected}",
293
+ file: sha_path, expected: expected, actual: actual)
294
+ end
295
+ end
296
+ rows = if canonical
297
+ bytes = OpenTideConstants.const_get(:CanonicalTypes, false)::ChecksumBytes.new(text, source: sha_name)
298
+ canonical.__send__(:bind_checksum_manifest, checksum_bytes: bytes, pointer_digests: {}, required_files: [])
299
+ else
300
+ Reader.parse_sha256(text, sha_name)
301
+ end
302
+ @release.send(:verify, rows)
303
+ end
304
+ private :verify_release_integrity
305
+
306
+ # Datestamps in the cache, newest first.
307
+ def cached_releases
308
+ check_open!
309
+ cache.cached_releases
310
+ end
311
+
312
+ # Removes all but the newest keep releases from the cache. It never
313
+ # removes the current loaded release or a release locked by another
314
+ # process. Earlier held releases can keep reading on POSIX after their
315
+ # directories are removed. It also removes incomplete
316
+ # release directories that no one holds. Returns the
317
+ # datestamps removed, newest first; CacheError when one cannot be removed.
318
+ def prune(keep: 3)
319
+ check_open!
320
+ raise InvalidArgumentError, "keep must be an Integer >= 0" unless keep.is_a?(Integer) && keep >= 0
321
+ protect = @file ? [] : [@release.datestamp]
322
+ removed = []
323
+ begin
324
+ cache.cached_releases.drop(keep).reject { |d| protect.include?(d) }.each do |d|
325
+ if cache.remove_release(d)
326
+ removed << d
327
+ else
328
+ log(:info, "prune: #{d} is locked by another process; kept")
329
+ end
330
+ end
331
+ cache.partial_releases.each do |d|
332
+ next if protect.include?(d)
333
+ begin
334
+ if cache.remove_release(d, partial: true)
335
+ log(:info, "prune: removed the incomplete release directory #{d}")
336
+ else
337
+ log(:info, "prune: incomplete release directory #{d} was kept")
338
+ end
339
+ rescue CacheError => e
340
+ log(:warn, "prune: cannot remove the incomplete release directory #{d}: #{e.message}")
341
+ end
342
+ end
343
+ rescue CacheError => e
344
+ # Stop at the first failure and report the releases removed
345
+ # before it.
346
+ raise CacheError.new(e.message, removed: removed)
347
+ end
348
+ removed
349
+ end
350
+
351
+ # Closes the client and every Release it loaded (stream mode holds a file
352
+ # handle per release). After close every query and call is io "the
353
+ # release is closed". A second close does nothing.
354
+ # Every release is closed even when one close fails; the first failure is
355
+ # raised after, as an SDK error (FileError, io, with the system error as
356
+ # its cause).
357
+ def close
358
+ failure = nil
359
+ @lock.synchronize do
360
+ return nil if @closed
361
+ @closed = true
362
+ ([@release] + @loaded.keys).compact.uniq.each do |r|
363
+ r.send(:close)
364
+ rescue StandardError => e
365
+ failure ||= [e, r]
366
+ end
367
+ end
368
+ return nil unless failure
369
+ e, r = failure
370
+ raise e if e.is_a?(Error)
371
+ raise FileError.new("cannot close release #{r.datestamp}: #{e.message}"), cause: e
372
+ end
373
+
374
+ # ---- queries, forwarded to the current release
375
+
376
+ %i[station require_station tombstone station_by_alias stations iter_stations each_station search bbox near nearest
377
+ reference_station subordinates_of attribution].each do |name|
378
+ define_method(name) do |*args, **kw, &blk|
379
+ check_open!
380
+ maybe_auto_update
381
+ @release.public_send(name, *args, **kw, &blk)
382
+ end
383
+ end
384
+
385
+ def inspect
386
+ "#<OpenTideConstants #{@release&.datestamp} (#{@loaded_from})>"
387
+ end
388
+
389
+ # ---- internals shared with Downloader (private: Downloader calls them with send)
390
+
391
+ attr_reader :http, :base_url, :offline, :on_network_error
392
+
393
+ def cache
394
+ @cache ||= Cache.new(@cache_dir || Cache.default_root, logger: @logger)
395
+ end
396
+
397
+ # The SHA-256 values (lower case) that the cached pointers
398
+ # (OTC_latest-f{MAJOR}.json, OTC_latest.json) give for OTC_{D}.sha256.
399
+ # A cached pointer that is not there, cannot be read or does not parse,
400
+ # names another release or does not list the .sha256 gives none.
401
+ #
402
+ def cached_pointer_sha256(d)
403
+ names = SUPPORTED_FORMAT_MAJORS.sort.reverse.map { |m| "OTC_latest-f#{m}.json" } + ["OTC_latest.json"]
404
+ names.flat_map do |name|
405
+ begin
406
+ body, = cache.read_pointer(name)
407
+ doc = body && JSON.parse(body)
408
+ rescue CacheError, JSON::ParserError, EncodingError => e
409
+ log(:debug, "verify: the cached #{name} cannot be used (#{e.message})")
410
+ next []
411
+ end
412
+ next [] unless doc.is_a?(Hash) && doc["files"].is_a?(Array)
413
+ doc["files"].filter_map do |f|
414
+ f["sha256"].downcase if f.is_a?(Hash) && f["name"] == "OTC_#{d}.sha256" && f["sha256"].is_a?(String)
415
+ end
416
+ end
417
+ end
418
+
419
+ # The latest pointer: [entry, url]. OTC_latest-f1.json, then
420
+ # OTC_latest.json on a 404 only.
421
+ def fetch_latest_pointer
422
+ names = SUPPORTED_FORMAT_MAJORS.sort.reverse.map { |m| "OTC_latest-f#{m}.json" } + ["OTC_latest.json"]
423
+ names.each do |name|
424
+ doc = fetch_pointer_doc(name, missing: :nil)
425
+ next if doc.nil?
426
+ return [check_entry!(doc, name), @base_url + name]
427
+ end
428
+ raise ReleaseNotFoundError, "no latest pointer at #{@base_url}"
429
+ end
430
+
431
+ # The newest release this SDK reads: [entry, url]. The pointer's release when it is readable; otherwise one GET
432
+ # of OTC_index.json and its newest readable entry. None: reader_too_old
433
+ # when a release of a supported major exists, else unsupported_format.
434
+ def resolve_latest
435
+ entry, url = fetch_latest_pointer
436
+ note_version_doi(entry)
437
+ # A check that reaches the pointer clears last_error; loaded_from does
438
+ # not change.
439
+ @last_error = nil
440
+ return [entry, url] if readable_entry?(entry)
441
+ index_url = @base_url + "OTC_index.json"
442
+ doc = fetch_pointer_doc("OTC_index.json", missing: :nil)
443
+ list = doc ? index_entries(doc) : []
444
+ list.each { |e| note_version_doi(e) }
445
+ pick = list.select { |e| readable_entry?(e) }.max_by { |e| Cache.datestamp_key(e["datestamp"]) }
446
+ return [pick, index_url] if pick
447
+ too_new = ([entry] + list).find { |e| Release.supported_major?(e["format_version"]) }
448
+ if too_new
449
+ raise ReaderTooOldError, "release #{too_new['datestamp']} needs a reader for format " \
450
+ "#{too_new['min_reader_version']}; this SDK reads format #{SUPPORTED_FORMAT_VERSION}"
451
+ end
452
+ raise UnsupportedFormatError, "the latest release has format #{entry['format_version']}, not supported by this " \
453
+ "SDK (supported majors: #{SUPPORTED_FORMAT_MAJORS.join(', ')})"
454
+ end
455
+
456
+ # The newest cached release this SDK reads, or nil. With usable: true,
457
+ # only one this client's mode can load.
458
+ def newest_cached(usable: true)
459
+ index = cached_index
460
+ cache.cached_releases.find do |d|
461
+ cached_readable?(d, cache.verified(d), index[d]) && (!usable || usable_cached?(d))
462
+ end
463
+ end
464
+
465
+ def release_info(entry, pointer_url)
466
+ files = Array(entry["files"]).map do |f|
467
+ FileInfo.new(name: f["name"], url: f["url"] && resolve(pointer_url, f["url"]), size: f["size"], sha256: f["sha256"])
468
+ end.sort_by(&:name)
469
+ ReleaseInfo.new(entry, files)
470
+ end
471
+
472
+ # The absolute URL of a files[] url. A url that is not a
473
+ # URL is invalid_release.
474
+ def resolve(base, ref)
475
+ URI.join(base, ref).to_s
476
+ rescue URI::Error, TypeError => e
477
+ raise InvalidReleaseError, "bad url #{ref.inspect} in a release entry: #{e.message}"
478
+ end
479
+
480
+ def log(level, msg)
481
+ @logger&.public_send(level, "opentideconstants: #{Redact.text(msg)}") # no URL user or password
482
+ end
483
+
484
+ private :http, :base_url, :offline, :on_network_error, :cache, :fetch_latest_pointer, :resolve_latest, :newest_cached, :release_info,
485
+ :resolve, :log, :cached_pointer_sha256
486
+
487
+ private
488
+
489
+ def monotonic
490
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
491
+ end
492
+
493
+ # The datestamps prune must keep: the loaded release and every release
494
+ # this client loaded that is still reachable (a caller may hold it,
495
+ # update). A client on a file keeps no cached release.
496
+ def held_datestamps
497
+ return [] if @file
498
+ ([@release] + @loaded.keys).compact.map(&:datestamp).uniq
499
+ end
500
+
501
+ def check_open!
502
+ raise FileError.new("the release is closed", path: @file) if @closed
503
+ end
504
+
505
+ # The automatic update: at most once per update_interval, in
506
+ # the first query after it. A failure keeps the current release, is
507
+ # logged and is kept in last_error; it never breaks the query.
508
+ def maybe_auto_update
509
+ return unless @auto_update && @requested == :latest && @file.nil? && !@offline && !@closed
510
+ return if monotonic - @last_check < @update_interval
511
+ @lock.synchronize do
512
+ # Again under the lock: queries that passed the check above at
513
+ # the same time run one update, not one each.
514
+ return if @closed || monotonic - @last_check < @update_interval
515
+ begin
516
+ update!
517
+ rescue StandardError => e
518
+ @last_check = monotonic
519
+ @last_error = auto_update_error(e)
520
+ log(:warn, "automatic update failed: #{@last_error.message}\n#{Array(e.backtrace).join("\n")}")
521
+ end
522
+ end
523
+ end
524
+
525
+ # Transport failures that a non-SDK exception in the automatic update can
526
+ # be (the HTTP layer wraps them; this is the safety net).
527
+ TRANSPORT_ERRORS = [SocketError, Timeout::Error, EOFError, Errno::ECONNREFUSED, Errno::ECONNRESET,
528
+ Errno::ECONNABORTED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ETIMEDOUT, Errno::EPIPE,
529
+ OpenSSL::SSL::SSLError, Net::ProtocolError, Net::HTTPBadResponse].freeze
530
+ private_constant :TRANSPORT_ERRORS
531
+
532
+ # The last_error of an automatic update that failed:
533
+ # an SDK error as it is; any other failure as an SDK error whose
534
+ # cause is the original: network for a transport failure, else io.
535
+ def auto_update_error(e)
536
+ return e if e.is_a?(Error)
537
+ msg = "automatic update failed: #{e.class}: #{e.message}"
538
+ begin
539
+ # raised here, inside the rescue of e, so Ruby sets its #cause to e
540
+ raise(TRANSPORT_ERRORS.any? { |k| e.is_a?(k) } ? NetworkError.new(msg) : FileError.new(msg))
541
+ rescue Error => wrapped
542
+ wrapped
543
+ end
544
+ end
545
+
546
+
547
+
548
+ # True when this SDK reads the release of a pointer or index entry.
549
+ def readable_entry?(entry)
550
+ return false unless entry.is_a?(Hash) && Release.supported_major?(entry["format_version"])
551
+ mrv = entry["min_reader_version"]
552
+ mrv.nil? || Release.readable_version?(mrv)
553
+ end
554
+
555
+ # The checked entries of OTC_index.json; invalid_release when releases
556
+ # is missing or an entry is malformed.
557
+ def index_entries(doc)
558
+ raise InvalidReleaseError, "OTC_index.json has no releases list" unless doc.is_a?(Hash) && doc["releases"].is_a?(Array)
559
+ doc["releases"].map { |e| check_entry!(e, "OTC_index.json") }
560
+ end
561
+
562
+ # Checks a pointer or index entry from the server: an
563
+ # object with a valid datestamp, and files (if any) whose elements are
564
+ # objects with a String name, a String sha256, an Integer size of 0 or
565
+ # more and, if given, a String url. Returns the entry.
566
+ def check_entry!(entry, source)
567
+ raise InvalidReleaseError, "#{source}: an entry is not an object" unless entry.is_a?(Hash)
568
+ d = entry["datestamp"]
569
+ raise InvalidReleaseError, "#{source}: bad datestamp #{d.inspect}" unless d.is_a?(String) && d.match?(DATESTAMP_RE)
570
+ files = entry["files"]
571
+ return entry if files.nil?
572
+ raise InvalidReleaseError, "#{source}: files of #{d} is not a list" unless files.is_a?(Array)
573
+ files.each do |f|
574
+ next if f.is_a?(Hash) && f["name"].is_a?(String) && (f["url"].nil? || f["url"].is_a?(String)) &&
575
+ f["sha256"].is_a?(String) && f["size"].is_a?(Integer) && f["size"] >= 0
576
+ raise InvalidReleaseError, "#{source}: a files entry of #{d} is malformed: #{f.inspect[0, 120]}"
577
+ end
578
+ entry
579
+ end
580
+
581
+ # The entries of the cached OTC_index.json by datestamp ({} if none).
582
+ def cached_index
583
+ cached = cached_pointer("OTC_index.json")
584
+ return {} unless cached
585
+ index_entries(cached[0]).to_h { |e| [e["datestamp"], e] }
586
+ rescue InvalidReleaseError
587
+ {}
588
+ end
589
+
590
+ # Whether a cached release is readable, by its .verified, else the cached
591
+ # index entry, else its .meta.json. Unknown counts as readable (the load
592
+ # then checks it).
593
+ def cached_readable?(d, ver, index_entry)
594
+ fv = ver&.dig("format_version") || index_entry&.dig("format_version")
595
+ mrv = ver&.dig("min_reader_version") || index_entry&.dig("min_reader_version")
596
+ if fv.nil? || mrv.nil?
597
+ meta = cached_meta(d)
598
+ fv ||= meta["format_version"]
599
+ mrv ||= meta["release"].is_a?(Hash) ? meta["release"]["min_reader_version"] : nil
600
+ end
601
+ (fv.nil? || Release.supported_major?(fv)) && (mrv.nil? || Release.readable_version?(mrv))
602
+ end
603
+
604
+ # The format_version and release of a .json release file, as a Hash
605
+ # ({} when it cannot be read; the load then checks it).
606
+ def release_versions(path)
607
+ doc = JSON.parse(File.read(path, mode: "rb").force_encoding(Encoding::UTF_8))
608
+ doc.is_a?(Hash) ? doc.slice("format_version", "release") : {}
609
+ rescue JSON::ParserError, EncodingError, SystemCallError, IOError
610
+ {}
611
+ end
612
+
613
+ # The cached .meta.json of release d ({} when it is not there or not a
614
+ # JSON object; CacheError when it cannot be read).
615
+ def cached_meta(d)
616
+ text = cache.read_file(File.join(cache.release_dir(d), "OTC_#{d}.meta.json"))
617
+ doc = text ? JSON.parse(text.force_encoding(Encoding::UTF_8)) : {}
618
+ doc.is_a?(Hash) ? doc : {}
619
+ rescue JSON::ParserError, EncodingError
620
+ {}
621
+ end
622
+
623
+ # check_for_update: a conditional GET of OTC_latest.json; a release there
624
+ # with a major newer than every supported one sets newer_format_major,
625
+ # else it is nil. When the check fails (a network error, a
626
+ # malformed entry, an unreadable cached copy), the value from before
627
+ # stays.
628
+ def check_newer_major
629
+ entry = fetch_pointer_doc("OTC_latest.json", missing: :nil)
630
+ if entry.nil?
631
+ @newer_format_major = nil
632
+ return
633
+ end
634
+ key = entry.is_a?(Hash) ? Release.version_key(entry["format_version"]) : nil
635
+ raise InvalidReleaseError, "OTC_latest.json: bad format_version #{entry.is_a?(Hash) ? entry['format_version'].inspect : nil}" unless key
636
+ if key[0] > SUPPORTED_FORMAT_MAJORS.max
637
+ @newer_format_major = key[0]
638
+ log(:warn, "a newer format (#{key[0]}) exists; upgrade opentideconstants to read it")
639
+ else
640
+ @newer_format_major = nil
641
+ end
642
+ rescue Error => e
643
+ # any failure (network, a malformed entry, a cached copy that cannot be read) keeps the value from
644
+ # before, and never replaces the error or the result of the check that called this
645
+ log(:warn, "cannot check OTC_latest.json for a newer format: #{e.message}")
646
+ end
647
+
648
+ # Keeps the version DOI of an entry in the .verified of its cached release.
649
+ # An entry whose DOI is null never erases a known one.
650
+ def note_version_doi(entry)
651
+ d = entry["datestamp"]
652
+ return unless d.is_a?(String) && d.match?(DATESTAMP_RE) && !entry["zenodo_version_doi"].nil?
653
+ cache.note_version_doi(d, entry["zenodo_version_doi"])
654
+ @lock.synchronize do
655
+ next if @file || @closed || !@release || @release.datestamp != d || @release.zenodo_version_doi == entry["zenodo_version_doi"]
656
+ @release.__send__(:note_version_doi, entry["zenodo_version_doi"])
657
+ end
658
+ end
659
+
660
+ def newer?(a, b)
661
+ (Cache.datestamp_key(a) <=> Cache.datestamp_key(b)) == 1
662
+ end
663
+
664
+ # GETs a pointer or index file with If-None-Match and returns it parsed
665
+ # A 200 is parsed before it is cached: a body that is
666
+ # not JSON (a captive portal or a proxy error page) is a network error
667
+ # and leaves the cached copy alone. A failure to cache it is
668
+ # logged, not raised. A 304 with no usable cached copy is asked again
669
+ # without the ETag. Offline it uses the cached copy, or raises
670
+ # OfflineError. missing: :nil returns nil on a 404 (the latest pointers
671
+ # and the index lookup; a network error is raised, and the
672
+ # caller's open falls back to a cached release). missing: :offline is for
673
+ # releases: a 404 is release_not_found, and after a network error with
674
+ # on_network_error :use_cache it uses the cached copy.
675
+ def fetch_pointer_doc(name, missing:)
676
+ url = @base_url + name
677
+ cached = cached_pointer(name)
678
+ if @offline
679
+ return cached[0] if cached
680
+ raise OfflineError, "offline and #{name} is not cached"
681
+ end
682
+ res = @http.get(url, etag: cached && cached[1])
683
+ res = @http.get(url) if res.status == 304 && cached.nil?
684
+ case res.status
685
+ when 304
686
+ raise NetworkError.new("#{url}: HTTP 304 to a request without If-None-Match", url: url, status: 304) unless cached
687
+ log(:debug, "#{name}: 304, the cached copy is current")
688
+ cached[0]
689
+ when 200
690
+ doc = parse_pointer_body(name, url, res.body)
691
+ store_pointer(name, res.body, res.etag)
692
+ log(:debug, "#{name}: 200")
693
+ doc
694
+ when 404
695
+ return nil if missing == :nil
696
+ raise ReleaseNotFoundError, "#{url}: HTTP 404"
697
+ else
698
+ raise NetworkError.new("#{url}: HTTP #{res.status}", url: url, status: res.status)
699
+ end
700
+ rescue NetworkError => e
701
+ raise unless missing == :offline && @on_network_error == :use_cache && cached
702
+ log(:warn, "#{e.message}; using the cached #{name}")
703
+ cached[0]
704
+ end
705
+
706
+ # The cached copy of a pointer or index file as [doc, etag], or nil. A
707
+ # copy that is not JSON of the right shape counts as none, so its ETag is
708
+ # not sent.
709
+ def cached_pointer(name)
710
+ cached = cache.read_pointer(name)
711
+ return nil unless cached
712
+ doc = JSON.parse(cached[0])
713
+ return [doc, cached[1]] if pointer_shape?(name, doc)
714
+ log(:warn, "the cached #{name} is not JSON of the right shape; ignoring it")
715
+ nil
716
+ rescue JSON::ParserError, EncodingError
717
+ log(:warn, "the cached #{name} is not JSON; ignoring it")
718
+ nil
719
+ end
720
+
721
+ # The shape of a pointer (an object with a datestamp and a files list) or
722
+ # of the index (an object with a releases list). A wrong value inside a
723
+ # body of the right shape is invalid_release later.
724
+ def pointer_shape?(name, doc)
725
+ return false unless doc.is_a?(Hash)
726
+ return doc["releases"].is_a?(Array) if name == "OTC_index.json"
727
+ doc.key?("datestamp") && doc["files"].is_a?(Array)
728
+ end
729
+
730
+ # A 200 pointer or index body that is not JSON, or is JSON of the
731
+ # wrong shape, is a network error. It is checked before the
732
+ # body is cached, so it never replaces the cached copy.
733
+ def parse_pointer_body(name, url, body)
734
+ doc = JSON.parse(body.dup.force_encoding(Encoding::UTF_8))
735
+ return doc if pointer_shape?(name, doc)
736
+ raise NetworkError.new("#{url}: HTTP 200 with JSON of the wrong shape for #{name}", url: url, status: 200)
737
+ rescue JSON::ParserError, EncodingError => e
738
+ raise NetworkError.new("#{url}: HTTP 200 with a body that is not JSON (#{e.message[0, 100]})", url: url, status: 200)
739
+ end
740
+
741
+ # Stores a pointer or index file and its ETag. The cached copy only saves
742
+ # work, so a failure is logged, not raised.
743
+ def store_pointer(name, body, etag)
744
+ cache.write_pointer(name, body, etag)
745
+ rescue CacheError => e
746
+ log(:warn, "cannot cache #{name}: #{e.message}")
747
+ end
748
+
749
+ def open_latest
750
+ if @offline
751
+ @release = load_newest_cached or raise OfflineError, "offline and no release is cached in #{cache.root}"
752
+ @loaded_from = :cache
753
+ return
754
+ end
755
+ cache.ensure_dir(cache.releases_dir)
756
+ begin
757
+ entry, url = resolve_latest
758
+ @release, @loaded_from = load_from_entry(entry, url)
759
+ rescue NetworkError => e
760
+ rel = @on_network_error == :use_cache ? load_newest_cached : nil
761
+ raise e unless rel
762
+ log(:warn, "#{e.message}; using the cached release #{rel.datestamp}")
763
+ @release = rel
764
+ @loaded_from = :cache_after_error
765
+ @last_error = e
766
+ end
767
+ end
768
+
769
+ def open_pinned(d)
770
+ if (rel = load_cached_unless_corrupt(d))
771
+ @release = rel
772
+ @loaded_from = :cache
773
+ return
774
+ end
775
+ raise OfflineError, "offline and release #{d} is not cached" if @offline
776
+ cache.ensure_dir(cache.releases_dir)
777
+ @release = fetch_release(d, nil, nil)
778
+ @loaded_from = :download
779
+ end
780
+
781
+ # [release, loaded_from] for a pointer entry: the cache when it has it.
782
+ def load_from_entry(entry, url)
783
+ d = entry["datestamp"]
784
+ raise InvalidReleaseError, "bad datestamp #{d.inspect} in the pointer" unless d.is_a?(String) && d.match?(DATESTAMP_RE)
785
+ # The entry's version DOI is the newest one read for d: the session has it even when .verified does not yet
786
+ # (a pinned writer cached d with none, or the note below is skipped under a busy lock).
787
+ if (rel = load_cached_unless_corrupt(d, doi: entry["zenodo_version_doi"]))
788
+ note_version_doi(entry)
789
+ return [rel, :cache]
790
+ end
791
+ [fetch_release(d, entry, url), :download]
792
+ end
793
+
794
+ # The cached release d when it is usable, else nil. A cached release that
795
+ # fails its size or SHA-256 check or does not parse is healed, and then,
796
+ # when online, nil, so the caller downloads it again. Offline, the error is raised.
797
+ def load_cached_unless_corrupt(d, doi: nil)
798
+ return nil unless present_cached?(d)
799
+ load_cached(d, doi: doi)
800
+ rescue ChecksumError, InvalidReleaseError => e
801
+ heal(d, e)
802
+ raise if @offline
803
+ log(:warn, "downloading #{d} again")
804
+ nil
805
+ end
806
+
807
+ # The newest cached release this SDK reads, loaded. A candidate that fails its size or SHA-256 check or does not
808
+ # parse is healed and the next older one is tried; one whose format this
809
+ # SDK cannot read is skipped. nil when none loads: the caller raises its
810
+ # original error.
811
+ def load_newest_cached
812
+ index = cached_index
813
+ cache.cached_releases.each do |d|
814
+ next unless cached_readable?(d, cache.verified(d), index[d]) && present_cached?(d)
815
+ begin
816
+ rel = load_cached(d)
817
+ return rel if rel
818
+ rescue UnsupportedFormatError, ReaderTooOldError => e
819
+ log(:info, "the cached release #{d} is not readable: #{e.message}")
820
+ rescue ChecksumError, InvalidReleaseError => e
821
+ heal(d, e)
822
+ end
823
+ end
824
+ nil
825
+ end
826
+
827
+ # Removes a cached release that failed its check or does not parse: .verified first, so it is no longer trusted, then the bad
828
+ # file (the one the error names, or the data files of this mode). A
829
+ # failure to delete is logged; it never hides the original error.
830
+ def heal(d, err)
831
+ log(:warn, "the cached release #{d} is corrupt (#{err.message}); removing it from the cache")
832
+ dir = cache.release_dir(d)
833
+ bad = if err.respond_to?(:file) && err.file
834
+ [File.join(dir, File.basename(err.file.to_s))] # only ever a file of this release's directory
835
+ else
836
+ (wanted_files(d).find { |ns| ns.all? { |n| File.file?(File.join(dir, n)) } } || []).map { |n| File.join(dir, n) }
837
+ end
838
+ [File.join(dir, ".verified"), *bad].each do |path|
839
+ cache.remove_file(path)
840
+ rescue CacheError => e
841
+ log(:warn, e.message)
842
+ end
843
+ end
844
+
845
+ # The data files a load in this mode reads, in order of preference.
846
+ def wanted_files(d)
847
+ json = ["OTC_#{d}.json"]
848
+ jsonl = ["OTC_#{d}.jsonl", "OTC_#{d}.meta.json"]
849
+ bootstrap = BGZF.names(d).drop(1)
850
+ @mode == :stream ? [bootstrap, jsonl] : [json, bootstrap, jsonl]
851
+ end
852
+
853
+ def usable_cached?(d)
854
+ ver = cache.verified(d)
855
+ return false unless ver
856
+ wanted_files(d).any? { |names| names.all? { |n| cache.file_ok?(d, n, ver) } }
857
+ end
858
+
859
+ # A verified release whose data files for this mode are there and listed
860
+ # in .verified, whatever their size (load_cached checks the size).
861
+ def present_cached?(d)
862
+ ver = cache.verified(d)
863
+ return false unless ver
864
+ return true if BGZF.declared?(ver["files"], d)
865
+ wanted_files(d).any? { |names| names.all? { |n| ver["files"][n].is_a?(Hash) && ver["files"][n]["sha256"].is_a?(String) && File.file?(File.join(cache.release_dir(d), n)) } }
866
+ end
867
+
868
+ # Loads cached release d, or nil when it is no longer usable (another
869
+ # process removed it after the caller checked it). doi: a version DOI
870
+ # newer than .verified's (a pointer entry); anything but a String keeps .verified's.
871
+ def load_cached(d, doi: nil, files: nil, bgzf_bootstrap: nil)
872
+ ver = cache.verified(d)
873
+ return load_cached_bgzf(d, ver, doi: doi, files: files, bgzf_bootstrap: bgzf_bootstrap) if ver && BGZF.declared?(ver["files"], d)
874
+ dir = cache.release_dir(d)
875
+ names = ver && wanted_files(d).find { |ns| ns.all? { |n| ver["files"][n].is_a?(Hash) && ver["files"][n]["sha256"].is_a?(String) && File.file?(File.join(dir, n)) } }
876
+ return nil unless names
877
+ paths = names.map { |n| File.join(dir, n) }
878
+ # the size is compared with .verified on every open
879
+ names.zip(paths).each do |n, p|
880
+ next if cache.file_ok?(d, n, ver)
881
+ raise ChecksumError.new("#{n}: the size does not match .verified", file: p, expected: ver["files"][n]["sha256"], actual: nil)
882
+ end
883
+ checks = paths.to_h { |p| [p, ver["files"][File.basename(p)]["sha256"]&.downcase] }
884
+ files ||= ver["files"].map do |name, row|
885
+ FileInfo.new(name: name, url: row["url"], size: row["size"], sha256: row["sha256"]&.downcase)
886
+ end
887
+ # With verify_on_open the load hashes each file from the bytes it reads.
888
+ opts = { mode: @mode, files: files, checks: checks, zenodo_version_doi: doi.is_a?(String) ? doi : ver["zenodo_version_doi"], verify: @verify_on_open || @mode == :stream,
889
+ logger: @logger, commercial_only: @commercial_only, commercial_basis: @commercial_basis, historical_offsets_policy: @historical_offsets_policy }
890
+ return Reader.load(paths.first, **opts) unless @mode == :stream
891
+ load_cached_stream(d, ver, paths.first, opts)
892
+ end
893
+
894
+ def load_cached_bgzf(d, ver, doi: nil, files: nil, supplied_index: nil, index_presence: nil, on_index: nil, canonical: nil, bgzf_bootstrap: nil)
895
+ dir = cache.release_dir(d)
896
+ sha_name = "OTC_#{d}.sha256"
897
+ sha_path = File.join(dir, sha_name)
898
+ unless File.file?(sha_path)
899
+ raise ChecksumError.new("no #{sha_name} in the BGZF cache", file: sha_path, expected: nil, actual: nil)
900
+ end
901
+ text = Reader.read_text(sha_path)
902
+ digest = Digest::SHA256.hexdigest(text)
903
+ cached_pointer_sha256(d).each do |expected|
904
+ next if expected == digest
905
+ raise ChecksumError.new("#{sha_name} differs from cached pointer", file: sha_path, expected: expected, actual: digest)
906
+ end
907
+ rows = Reader.parse_sha256(text, sha_name)
908
+ names = BGZF.names(d)
909
+ names.drop(1).each do |name|
910
+ next if cache.file_ok?(d, name, ver)
911
+ raise ChecksumError.new("#{name}: missing or wrong size in BGZF cache", file: File.join(dir, name), expected: rows[name], actual: nil)
912
+ end
913
+ complete = names.drop(1)
914
+ complete = [names.first, *complete] if cache.file_ok?(d, names.first, ver)
915
+ checks = complete.to_h { |name| [File.join(dir, name), rows[name]] }
916
+ files ||= ver["files"].map { |name, row| FileInfo.new(name: name, url: row["url"], size: row["size"], sha256: row["sha256"]) }
917
+ archive_url = bgzf_archive_url(d, names.first)
918
+ BGZF.load(dir, d, rows: rows, mode: @mode, files: files, checks: checks, verified: ver, cache: cache, http: @http,
919
+ url: archive_url, offline: @offline, zenodo_version_doi: doi.is_a?(String) ? doi : ver["zenodo_version_doi"],
920
+ logger: @logger, commercial_only: @commercial_only, commercial_basis: @commercial_basis,
921
+ historical_offsets_policy: @historical_offsets_policy, supplied_index: supplied_index,
922
+ index_presence: index_presence, on_index: on_index, canonical: canonical, bootstrap: bgzf_bootstrap)
923
+ end
924
+
925
+ def bgzf_archive_url(d, archive)
926
+ pointer_names = SUPPORTED_FORMAT_MAJORS.sort.reverse.map { |major| "OTC_latest-f#{major}.json" } + ["OTC_latest.json", "OTC_index.json"]
927
+ pointer_names.each do |pointer|
928
+ cached = cached_pointer(pointer)
929
+ next unless cached
930
+ entries = pointer == "OTC_index.json" ? index_entries(cached[0]) : [cached[0]]
931
+ entry = entries.find { |candidate| candidate["datestamp"] == d }
932
+ next unless entry
933
+ file = release_info(entry, @base_url + pointer).files.find { |candidate| candidate.name == archive }
934
+ return file.url if file&.url
935
+ end
936
+ @base_url + archive
937
+ end
938
+
939
+ # Authenticate the opened source before the index admission callback.
940
+ # Its complete source pass and one index-derived retry stay in this phase.
941
+ def load_cached_stream(d, ver, jsonl_path, opts, canonical: nil, supplied_index: nil, index_presence: nil, on_index: nil)
942
+ selected = nil
943
+ rows = []
944
+ admission = lambda do
945
+ selected = fresh_stream_index(d, ver, jsonl_path, supplied_index: supplied_index, index_presence: index_presence, on_index: on_index)
946
+ drop_stream_index(d, "the stream index is stale") if !selected && File.file?(File.join(cache.release_dir(d), "index-v1.json"))
947
+ selected
948
+ end
949
+ begin
950
+ rel = Reader.load(jsonl_path, index: admission, index_rows: rows, canonical: canonical,
951
+ on_bad_index: ->(msg) { drop_stream_index(d, msg) }, **opts)
952
+ rescue InvalidReleaseError => error
953
+ raise unless selected
954
+ log(:warn, "the stream index for #{d} cannot be used (#{error.message}); rebuilding it")
955
+ drop_stream_index(d, "the stream index is stale") if File.file?(File.join(cache.release_dir(d), "index-v1.json"))
956
+ rows = []
957
+ rel = Reader.load(jsonl_path, index_rows: rows, canonical: canonical, **opts)
958
+ selected = nil
959
+ end
960
+ write_stream_index(d, rel, rows, ver, jsonl_path, on_index: on_index) unless selected
961
+ rel
962
+ end
963
+
964
+ # The entries of index-v1.json when it is fresh for release d, else nil.
965
+ def fresh_stream_index(d, ver, jsonl_path, supplied_index: nil, index_presence: nil, on_index: nil)
966
+ path = File.join(cache.release_dir(d), "index-v1.json")
967
+ return nil unless File.file?(path)
968
+ idx = JSON.parse(File.read(path, mode: "rb").force_encoding(Encoding::UTF_8))
969
+ if index_presence
970
+ unless supplied_index == idx && index_presence.all? { |key, present| idx.is_a?(Hash) && idx.key?(key) == present }
971
+ raise OpenTideConstants.const_get(:Canonical, false)::Unimplemented.new("authenticate_station_index mismatched authenticated index source or presence")
972
+ end
973
+ end
974
+ jsonl = "OTC_#{d}.jsonl"
975
+ return nil unless idx.is_a?(Hash)
976
+ # An integer key may be written as a number with an integral value, 12.0.
977
+ %w[index_version jsonl_size].each { |k| idx[k] = Reader.integral(idx[k]) if idx.key?(k) }
978
+ if idx["stations"].is_a?(Array)
979
+ idx["stations"].each do |e|
980
+ %w[offset length].each { |k| e[k] = Reader.integral(e[k]) if e.is_a?(Hash) && e.key?(k) }
981
+ end
982
+ end
983
+ return nil unless idx["index_version"].is_a?(Integer) && idx["index_version"] == 1
984
+ return nil if idx.key?("discovery_index_version") && Reader.integral(idx["discovery_index_version"]) != 1
985
+ return nil unless idx["datestamp"] == d && idx["jsonl"] == jsonl
986
+ return nil unless idx["jsonl_sha256"].is_a?(String) && idx["jsonl_sha256"] == ver["files"].dig(jsonl, "sha256")
987
+ return nil unless idx["jsonl_size"].is_a?(Integer) && idx["jsonl_size"] == File.size(jsonl_path)
988
+ return nil unless idx["stations"].is_a?(Array)
989
+ profile = Reader.index_profile(idx["stations"])
990
+ return nil unless profile && idx["stations"].all? { |e| Reader.index_entry_ok?(e, profile: profile) }
991
+ return nil unless index_in_bounds?(idx["stations"], idx["jsonl_size"])
992
+ on_index&.call(idx)
993
+ idx["stations"]
994
+ rescue JSON::ParserError, EncodingError, SystemCallError, IOError
995
+ nil
996
+ end
997
+
998
+ # The bounds check of a fresh index: each length > 0,
999
+ # offset + length <= the .jsonl size, and each offset at least the
1000
+ # previous offset + the previous length + 1, so that no two entries
1001
+ # overlap.
1002
+ def index_in_bounds?(entries, size)
1003
+ start = 0
1004
+ entries.all? do |e|
1005
+ ok = e["length"].positive? && e["offset"] >= start && e["offset"] + e["length"] <= size
1006
+ start = e["offset"] + e["length"] + 1
1007
+ ok
1008
+ end
1009
+ end
1010
+
1011
+ # Deletes the stream index of release d after a line did not match its
1012
+ # entry; the next open rebuilds it.
1013
+ def drop_stream_index(d, msg)
1014
+ log(:warn, "#{msg}; deleting index-v1.json of #{d}")
1015
+ cache.remove_file(File.join(cache.release_dir(d), "index-v1.json"))
1016
+ rescue CacheError => e
1017
+ log(:warn, e.message)
1018
+ end
1019
+
1020
+ # Writes index-v1.json: rows are the entries of every line,
1021
+ # from the pass that loaded rel. A failure to write it is logged, not
1022
+ # raised: the index only saves work.
1023
+ def write_stream_index(d, rel, rows, ver, jsonl_path, on_index: nil)
1024
+ jsonl = "OTC_#{d}.jsonl"
1025
+ sha = ver["files"].dig(jsonl, "sha256")
1026
+ return unless sha.is_a?(String)
1027
+ kinds = rel.send(:index_kinds)
1028
+ rows.each do |r|
1029
+ r["kind"] = kinds[r["station_id"]] if r["status"] == "active" && kinds.key?(r["station_id"])
1030
+ r["sets"] = r["sets"].map { |cs| cs.reject { |k, _| %w[source_record_id source_version datum].include?(k) } }
1031
+ r["current_offsets"] = r["current_offsets"].map { |off| Reader::CURRENT_BASE.to_h { |key| [key, off[key]] } }
1032
+ end
1033
+ doc = { "index_version" => 1, "discovery_index_version" => 1, "datestamp" => d, "jsonl" => jsonl, "jsonl_sha256" => sha,
1034
+ "jsonl_size" => File.size(jsonl_path), "by" => "opentideconstants-ruby/#{VERSION}", "stations" => rows }
1035
+ on_index&.call(doc)
1036
+ cache.write_atomic(File.join(cache.release_dir(d), "index-v1.json"), Cache.encode_cache_json(doc))
1037
+ rescue CacheError, SystemCallError, IOError => e
1038
+ log(:warn, "cannot write the stream index for #{d}: #{e.message}")
1039
+ end
1040
+
1041
+ # Downloads, checks and caches release d, then loads it.
1042
+ def fetch_release(d, entry, pointer_url)
1043
+ dir = cache.ensure_dir(cache.release_dir(d))
1044
+ result = cache.with_lock(dir, done: -> { usable_cached?(d) }) do
1045
+ next if usable_cached?(d)
1046
+ download_into_cache(d, entry, pointer_url)
1047
+ end
1048
+ # release.files: the pointer entry for a download of latest, else the .verified rows
1049
+ files = entry && release_info(entry, pointer_url).files
1050
+ load_cached(d, files: files, bgzf_bootstrap: result.is_a?(Array) ? result : nil) or raise CacheError, "release #{d} left the cache while it was opened"
1051
+ end
1052
+
1053
+ def download_into_cache(d, entry, pointer_url)
1054
+ dir = cache.release_dir(d)
1055
+ rows, sha_bytes = Downloader.fetch_sha256(self, d, entry, pointer_url)
1056
+ return download_bgzf_bootstrap(d, rows, sha_bytes, entry, pointer_url) if BGZF.declared?(rows, d)
1057
+ pointer_files = entry ? Array(entry["files"]).to_h { |f| [f["name"], f] } : {}
1058
+ # Eager mode reads the .json, from .json.gz when the release has one.
1059
+ gz = "OTC_#{d}.json.gz"
1060
+ json = "OTC_#{d}.json"
1061
+ need = @mode == :stream ? %W[OTC_#{d}.jsonl OTC_#{d}.meta.json] : [rows[gz] ? gz : json, json]
1062
+ need.uniq.each do |name|
1063
+ # Check the list before any download (a file it does not list cannot be checked).
1064
+ raise ChecksumError.new("#{name} is not listed in OTC_#{d}.sha256", file: name, expected: nil, actual: nil) unless rows[name]
1065
+ end
1066
+ url_of = lambda do |name|
1067
+ f = pointer_files[name]
1068
+ f && f["url"] ? resolve(pointer_url, f["url"]) : @base_url + name
1069
+ end
1070
+ sha_name = "OTC_#{d}.sha256"
1071
+ # .verified gets a row only for each file stored and verified here, with
1072
+ # its real size; release.files of a download of
1073
+ # latest is the pointer entry (fetch_release).
1074
+ verified = {}
1075
+ row = ->(name, size) { verified[name] = { "sha256" => rows[name], "size" => size, "url" => url_of.call(name) } }
1076
+ cache.write_atomic(File.join(dir, sha_name), sha_bytes)
1077
+ # Only the keys the entry has: a missing or null zenodo_version_doi keeps the stored one.
1078
+ info = entry ? entry.slice(*Cache::VERIFIED_INFO) : {}
1079
+ info.delete("zenodo_version_doi") if info["zenodo_version_doi"].nil?
1080
+ if @mode == :stream
1081
+ %W[OTC_#{d}.jsonl OTC_#{d}.meta.json].each do |name|
1082
+ size = Downloader.fetch_checked(self, url_of.call(name), dir, File.join(dir, name), name, rows[name],
1083
+ pointer_files.dig(name, "size"))
1084
+ row.call(name, size)
1085
+ end
1086
+ elsif !rows[gz]
1087
+ size = Downloader.fetch_checked(self, url_of.call(json), dir, File.join(dir, json), json, rows[json],
1088
+ pointer_files.dig(json, "size"))
1089
+ row.call(json, size)
1090
+ else
1091
+ tmp_gz = Cache.tmp_path(dir)
1092
+ begin
1093
+ Downloader.fetch_checked(self, url_of.call(gz), dir, nil, gz, rows[gz], pointer_files.dig(gz, "size"),
1094
+ keep_tmp: tmp_gz)
1095
+ size = Downloader.gunzip_checked(tmp_gz, dir, File.join(dir, json), json, rows[json])
1096
+ row.call(json, size)
1097
+ ensure
1098
+ FileUtils.rm_f(tmp_gz)
1099
+ end
1100
+ end
1101
+ # The receipt keeps the versions of the checked source, including
1102
+ # readable higher minors, rather than the pointer's advertised values.
1103
+ meta = @mode == :stream ? cached_meta(d) : release_versions(File.join(dir, "OTC_#{d}.json"))
1104
+ info["format_version"] = meta["format_version"]
1105
+ info["min_reader_version"] = meta["release"].is_a?(Hash) ? meta["release"]["min_reader_version"] : nil
1106
+ cache.write_verified(d, verified, info)
1107
+ end
1108
+
1109
+ def download_bgzf_bootstrap(d, rows, sha_bytes, entry, pointer_url)
1110
+ dir = cache.release_dir(d)
1111
+ pointer_files = entry ? Array(entry["files"]).to_h { |file| [file["name"], file] } : {}
1112
+ BGZF.names(d).each do |name|
1113
+ unless rows[name]
1114
+ raise ChecksumError.new("#{name} is not listed in OTC_#{d}.sha256", file: name, expected: nil, actual: nil)
1115
+ end
1116
+ end
1117
+ verified = {}
1118
+ BGZF.names(d).drop(1).each do |name|
1119
+ advertised = pointer_files[name]
1120
+ url = advertised && advertised["url"] ? resolve(pointer_url, advertised["url"]) : @base_url + name
1121
+ size = Downloader.fetch_checked(self, url, dir, File.join(dir, name), name, rows[name], advertised && advertised["size"])
1122
+ verified[name] = { "sha256" => rows[name], "size" => size, "url" => url }
1123
+ end
1124
+ # Authenticate every binding before admitting the sparse release.
1125
+ bootstrap = BGZF.read_bootstrap(dir, d, rows, cache: cache)
1126
+ meta = bootstrap[2]
1127
+ cache.write_atomic(File.join(dir, "OTC_#{d}.sha256"), sha_bytes)
1128
+ info = entry ? entry.slice(*Cache::VERIFIED_INFO) : {}
1129
+ info.delete("zenodo_version_doi") if info["zenodo_version_doi"].nil?
1130
+ info["format_version"] = meta["format_version"]
1131
+ info["min_reader_version"] = meta.dig("release", "min_reader_version")
1132
+ cache.write_verified(d, verified, info)
1133
+ bootstrap << rows.freeze
1134
+ end
1135
+ end