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,1531 @@
1
+ require "json"
2
+ require "zlib"
3
+ require "digest"
4
+ require "set"
5
+ require_relative "historical_fingerprint"
6
+
7
+ class OpenTideConstants
8
+ # One loaded OTC_{DATESTAMP} release. Immutable: an
9
+ # update of the client swaps in a new Release and leaves this one as it is.
10
+ #
11
+ # In eager mode every station is built at load. In stream mode the release
12
+ # keeps a small index (one entry per station, with the byte offset of its
13
+ # line in the .jsonl file) and builds a Station when a query needs it.
14
+ class Release
15
+ EARTH_RADIUS_KM = 6371.0088
16
+ FILTER_KEYS = %i[country type kind source source_type include_flagged include_fallback].freeze
17
+ # The qc_status values of a set with constants.
18
+ USABLE_QC = %i[ok flagged].freeze
19
+ # The reference links a walk follows.
20
+ MAX_LINKS = 16
21
+
22
+ # A small per-station summary, used by the filters and the indexes.
23
+ # eff_*: the recommended set the Stations give (the effective one under
24
+ # commercial_only); offsets_ref_licence_id: the
25
+ # licence of the station's first set in file order from the offsets'
26
+ # source (noaa), water_level, ok or flagged (the reference set of the
27
+ # one-link offsets path), or nil.
28
+ Entry = Struct.new(:station_id, :name, :folded, :lat, :lon, :type, :country, :kind, :sources,
29
+ :rec_source_type, :rec_licence_id, :offsets_licence_id, :reference_id,
30
+ :eff_id, :eff_source_type, :eff_licence_id, :offsets_ref_licence_id,
31
+ :aliases, :pos, :len, :station, :view, :sets, :offsets, :current_offsets,
32
+ :subordinate_offset_alternatives, :prediction_profiles, keyword_init: true)
33
+ # The source of every subordinate_offsets in format 1.0.
34
+ OFFSETS_SOURCE = "noaa"
35
+
36
+ # The metadata: readable after close too. Every other
37
+ # method is a query, and after close it is io "the release is
38
+ # closed".
39
+ attr_reader :datestamp, :created, :format_version, :concept_doi, :source_versions,
40
+ :build_commit, :changelog_url, :files
41
+
42
+ def zenodo_version_doi
43
+ @state.fetch(:zenodo_version_doi, @zenodo_version_doi)
44
+ end
45
+
46
+ def note_version_doi(doi)
47
+ @state[:zenodo_version_doi] = doi
48
+ end
49
+ private :note_version_doi
50
+
51
+ # meta: the release document without its stations. stations: an
52
+ # enumerator of [raw_station, pos, len, view]; view (Reader.line_view)
53
+ # when the station came from index-v1.json, else nil. files: [FileInfo]. checks:
54
+ # {path => expected sha256} for #verify. io: the open .jsonl file in
55
+ # stream mode (or nil). zenodo_version_doi: from the pointer or index
56
+ # entry of this datestamp (the release document does not hold it).
57
+ # on_bad_index: called (with the message) when a line read through the
58
+ # stream index is not the station its entry names.
59
+ # logger: where a station with an unknown status is reported, once at
60
+ # load.
61
+ # commercial_only: the open option.
62
+ def initialize(meta:, stations:, mode:, files:, checks:, io: nil, zenodo_version_doi: nil, on_bad_index: nil,
63
+ logger: nil, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback)
64
+ prepare_release_fields(meta: meta, mode: mode, files: files, checks: checks, io: io,
65
+ zenodo_version_doi: zenodo_version_doi, on_bad_index: on_bad_index, logger: logger,
66
+ commercial_only: commercial_only, commercial_basis: commercial_basis,
67
+ historical_offsets_policy: historical_offsets_policy)
68
+ load_stations(stations)
69
+ freeze
70
+ end
71
+
72
+ def prepare_release_fields(meta:, mode:, files:, checks:, io: nil, zenodo_version_doi: nil, on_bad_index: nil,
73
+ logger: nil, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback)
74
+ @station_origin = Object.new.freeze
75
+ @mode = mode
76
+ @commercial_only = commercial_only
77
+ @commercial_basis = commercial_basis.to_s
78
+ @historical_offsets_policy = historical_offsets_policy.to_s
79
+ @meta = meta
80
+ @logger = logger
81
+ @io = io
82
+ @on_bad_index = on_bad_index
83
+ @io_lock = Mutex.new
84
+ @station_cache = {}
85
+ @station_cache_lock = Mutex.new
86
+ @state = { closed: false } # not frozen with the Release: close sets it
87
+ @files = files.sort_by(&:name).freeze
88
+ @checks = checks.freeze
89
+ Util.deep_freeze(meta)
90
+ Release.check_format!(meta)
91
+ rel = meta["release"]
92
+ raise InvalidReleaseError, "release object missing" unless rel.is_a?(Hash) && rel["datestamp"].is_a?(String)
93
+ @datestamp = rel["datestamp"]
94
+ @created = Util.time(rel["created"])
95
+ sv = rel["source_versions"]
96
+ unless sv.nil? || (sv.is_a?(Hash) && sv.values.all?(String))
97
+ raise InvalidReleaseError, "release.source_versions is not an object of strings"
98
+ end
99
+ %w[conventions licences].each do |k|
100
+ list = meta[k]
101
+ next if list.nil?
102
+ id = k == "conventions" ? "convention_id" : "licence_id"
103
+ unless list.is_a?(Array) && list.all? { |x| x.is_a?(Hash) && x[id].is_a?(String) }
104
+ raise InvalidReleaseError, "#{k} must be a list of objects with a #{id}"
105
+ end
106
+ end
107
+ # The attribution text prints both; a null
108
+ # provider is allowed.
109
+ Array(meta["licences"]).each do |l|
110
+ Licence.check!(l)
111
+ next if l["attribution"].is_a?(String) && (l["provider"].nil? || l["provider"].is_a?(String))
112
+ raise InvalidReleaseError,
113
+ "licence #{l['licence_id']}: attribution must be a string and provider a string or null"
114
+ end
115
+ @format_version = meta["format_version"]
116
+ @concept_doi = rel["concept_doi"]
117
+ @zenodo_version_doi = zenodo_version_doi
118
+ @source_versions = (rel["source_versions"] || {}).freeze
119
+ @build_commit = rel["build_commit"]
120
+ @changelog_url = rel["changelog_url"]
121
+ @conventions = Array(meta["conventions"]).map { |c| Convention.new(c) }.freeze
122
+ @licences = Array(meta["licences"]).map { |l| Licence.new(l) }.freeze
123
+ Release.no_repeats!(@conventions.map(&:convention_id), "convention_id")
124
+ Release.no_repeats!(@licences.map(&:licence_id), "licence_id")
125
+ @convention_by_id = @conventions.to_h { |c| [c.convention_id, c] }.freeze
126
+ @licence_by_id = @licences.to_h { |l| [l.licence_id, l] }.freeze
127
+ end
128
+ private :prepare_release_fields
129
+
130
+ # Raises unsupported_format unless the format major is supported, and
131
+ # reader_too_old when release.min_reader_version is newer than
132
+ # SUPPORTED_FORMAT_VERSION.
133
+ def self.check_format!(meta)
134
+ raise InvalidReleaseError, "not a release document" unless meta.is_a?(Hash)
135
+ fv = meta["format_version"]
136
+ raise InvalidReleaseError, "format_version missing" unless Release.version_key(fv)
137
+ unless Release.supported_major?(fv)
138
+ raise UnsupportedFormatError, "format_version #{fv} is not supported (supported majors: #{SUPPORTED_FORMAT_MAJORS.join(', ')})"
139
+ end
140
+ rel = meta["release"]
141
+ mrv = rel.is_a?(Hash) ? rel["min_reader_version"] : nil
142
+ return if mrv.nil?
143
+ raise InvalidReleaseError, "bad release.min_reader_version #{mrv.inspect}" unless Release.version_key(mrv)
144
+ return if Release.readable_version?(mrv)
145
+ d = rel["datestamp"]
146
+ raise ReaderTooOldError, "release #{d} needs a reader for format #{mrv}; this SDK reads format #{SUPPORTED_FORMAT_VERSION}"
147
+ end
148
+
149
+ # invalid_release when a value appears twice.
150
+ def self.no_repeats!(values, what)
151
+ seen = Set.new
152
+ values.each do |v|
153
+ raise InvalidReleaseError, "#{what} #{v.inspect} appears twice" unless seen.add?(v)
154
+ end
155
+ end
156
+
157
+ # [major, minor] of a "MAJOR.MINOR" format version, or nil.
158
+ def self.version_key(v)
159
+ m = /\A(\d+)\.(\d+)\z/.match(v.to_s) if v.is_a?(String)
160
+ m && [m[1].to_i, m[2].to_i]
161
+ end
162
+
163
+ def self.supported_major?(format_version)
164
+ key = version_key(format_version)
165
+ !key.nil? && SUPPORTED_FORMAT_MAJORS.include?(key[0])
166
+ end
167
+
168
+ # True when this SDK reads a release whose min_reader_version is v.
169
+ def self.readable_version?(v)
170
+ key = version_key(v)
171
+ !key.nil? && (key <=> version_key(SUPPORTED_FORMAT_VERSION)) <= 0
172
+ end
173
+
174
+ # ---- release-level values
175
+
176
+ def historical_offsets_policy
177
+ check_open!
178
+ @historical_offsets_policy.to_sym
179
+ end
180
+
181
+ def conventions
182
+ check_open!
183
+ @conventions
184
+ end
185
+
186
+ def licences
187
+ check_open!
188
+ @licences
189
+ end
190
+
191
+ def constituent_names
192
+ check_open!
193
+ @constituent_names
194
+ end
195
+
196
+ def convention(convention_id)
197
+ check_open!
198
+ @convention_by_id[convention_id]
199
+ end
200
+
201
+ def licence(licence_id)
202
+ check_open!
203
+ @licence_by_id[licence_id]
204
+ end
205
+
206
+ def station_count
207
+ check_open!
208
+ @entries.size
209
+ end
210
+
211
+ def tombstone_count
212
+ check_open!
213
+ @tombstones.size
214
+ end
215
+
216
+ def stats
217
+ check_open!
218
+ count = ->(values) { values.compact.tally.sort_by { |k, _| k.to_s }.to_h.freeze }
219
+ Stats.new(type: count.call(@entries.map(&:type)), kind: count.call(@entries.map(&:kind)),
220
+ country: count.call(@entries.map(&:country)), source: count.call(@set_sources),
221
+ qc_status: count.call(@set_qc))
222
+ end
223
+
224
+ # The dataset citation; the year is the first four digits
225
+ # of the datestamp. It links the concept DOI, and adds the version DOI
226
+ # when the release has its own Zenodo version.
227
+ def citation
228
+ link = @concept_doi ? "https://doi.org/#{@concept_doi}" : default_url
229
+ doi = zenodo_version_doi
230
+ version = doi && doi != "" ? " (version DOI: https://doi.org/#{doi})" : ""
231
+ "OpenTideConstants contributors (#{@datestamp[0, 4]}). OpenTideConstants, release #{@datestamp} [Data set]. #{link}#{version}"
232
+ end
233
+
234
+ # The attribution text for what an app shows: "Tidal constants:
235
+ # OpenTideConstants {D}, {ident}.", then the per-set licences
236
+ # (Sources) and the non-commercial notice. The header states no
237
+ # licence for the data. With
238
+ # no stations, or an empty list, every licence in the release. A
239
+ # Station that is not one of this release's is invalid_argument, never
240
+ # skipped. A licence with no provider prints its attribution
241
+ # alone and is never merged with another.
242
+ def attribution(stations = nil)
243
+ check_open!
244
+ raise InvalidArgumentError, "stations must be an Array of Station" unless stations.nil? || stations.is_a?(Array)
245
+ co = @commercial_only
246
+ ids = if stations.nil? || stations.empty?
247
+ # with commercial_only, only the commercial licences
248
+ @licences.select { |l| !co || l.commercial_use == true }.map(&:licence_id)
249
+ else
250
+ out = Set.new
251
+ stations.each do |st|
252
+ e = validate_attribution_station_owner(st)
253
+ e = policy_entry(e)
254
+ Array(e.subordinate_offset_alternatives).each do |wrapper|
255
+ out.merge(tide_source_licences(e, offsets: wrapper["offsets"]))
256
+ end
257
+ if co # the licences of the station's tide source
258
+ out.merge(tide_source_licences(e))
259
+ next
260
+ end
261
+ out << e.rec_licence_id if e.rec_licence_id
262
+ out.merge(chain_licences(e))
263
+ end
264
+ out.to_a
265
+ end
266
+ seen = Set.new
267
+ parts = []
268
+ ids.uniq.sort.each do |lid|
269
+ lic = @licence_by_id[lid]
270
+ next if lic.nil?
271
+ if lic.provider.nil?
272
+ parts << lic.attribution.to_s
273
+ next
274
+ end
275
+ next if seen.include?(lic.provider)
276
+ seen << lic.provider
277
+ parts << "#{lic.provider}: #{lic.attribution}"
278
+ end
279
+ ident = @concept_doi ? "doi:#{@concept_doi}" : default_url
280
+ head = "Tidal constants: OpenTideConstants #{@datestamp}, #{ident}."
281
+ # An empty scope: the dataset header alone.
282
+ return head if ids.empty?
283
+ text = "#{head} Sources: " + parts.join("; ")
284
+ # The non-commercial notice: once, then one
285
+ # entry per non-commercial licence in scope, by licence_id; a nil
286
+ # provider gives the licence_id.
287
+ nc = ids.uniq.sort.map { |lid| @licence_by_id[lid] }.reject { |l| l.nil? || l.commercial_use == true }
288
+ unless nc.empty?
289
+ text += ". Non-commercial use only: " +
290
+ nc.map { |l| "#{l.provider.nil? ? l.licence_id : l.provider} (#{l.spdx}, #{l.terms_url})" }.join("; ")
291
+ end
292
+ text
293
+ end
294
+
295
+ # The licences of a station's tide source under commercial_only: its effective recommended set; else the one-link
296
+ # offsets path (the reference station's first set from the offsets'
297
+ # source), usable only when the offsets' licence and that set's licence
298
+ # allow commercial use; else none (no usable tides). Retained alternatives
299
+ # use prediction's effective recommendation, then set_id order.
300
+ def tide_source_licences(e, offsets: nil)
301
+ return [e.eff_licence_id] if offsets.nil? && e.eff_id
302
+ reference_id = offsets ? offsets["reference_station_id"] : e.reference_id
303
+ licence_id = offsets ? offsets["licence_id"] : e.offsets_licence_id
304
+ return [] if reference_id.nil? && licence_id.nil?
305
+ ref = @by_id[reference_id]
306
+ return [] if ref.nil?
307
+ reference_licence = if @commercial_only && @commercial_basis == "strict"
308
+ ref = policy_entry(ref, offsets: false, alternatives: false)
309
+ ref.sets.select { |set| offsets_reference_set?(set) && commercial_set?(set) }
310
+ .min_by { |set| [set["set_id"] == ref.eff_id ? 0 : 1, set["set_id"]] }&.fetch("licence_id")
311
+ elsif offsets
312
+ retained_reference_set(ref)&.fetch("licence_id")
313
+ else
314
+ ref.offsets_ref_licence_id
315
+ end
316
+ return [] if reference_licence.nil?
317
+ out = [reference_licence]
318
+ out << licence_id if licence_id
319
+ !@commercial_only || out.all? { |lid| @licence_by_id[lid].commercial_use == true } ? out : []
320
+ end
321
+ private :tide_source_licences
322
+
323
+ # Original pure argument phases; query/discovery bodies stay on Release.
324
+ module QueryArguments
325
+ private
326
+
327
+ def validate_alias_arguments(system, alias_id)
328
+ unless (system.is_a?(String) || system.is_a?(Symbol)) && alias_id.is_a?(String)
329
+ raise InvalidArgumentError, "system must be a String or Symbol and alias_id a String"
330
+ end
331
+ end
332
+
333
+ def validate_search_arguments(name, limit, match)
334
+ raise InvalidArgumentError, "name must be a String" unless name.is_a?(String)
335
+ check_limit!(limit)
336
+ unless match.nil? || match.to_s == "exact"
337
+ raise InvalidArgumentError, "match must be nil or :exact"
338
+ end
339
+ q = Fold.fold(utf8_query(name))
340
+ raise InvalidArgumentError, "the query is empty" if q.empty?
341
+ q
342
+ end
343
+
344
+ def validate_bbox_arguments(south, west, north, east, limit)
345
+ check_point!(south, west)
346
+ check_point!(north, east)
347
+ raise InvalidArgumentError, "south must not exceed north" if south > north
348
+ check_limit!(limit)
349
+ end
350
+
351
+ def validate_near_arguments(lat, lon, radius_km, limit)
352
+ check_point!(lat, lon)
353
+ unless real?(radius_km) && radius_km >= 0
354
+ raise InvalidArgumentError, "radius_km must be a number >= 0"
355
+ end
356
+ check_limit!(limit)
357
+ end
358
+
359
+ def validate_nearest_arguments(lat, lon, max_km)
360
+ check_point!(lat, lon)
361
+ unless max_km.nil? || (real?(max_km) && max_km >= 0)
362
+ raise InvalidArgumentError, "max_km must be nil or a number >= 0"
363
+ end
364
+ end
365
+
366
+ def validate_filter_arguments(filters)
367
+ unknown = filters.keys - FILTER_KEYS
368
+ raise InvalidArgumentError, "unknown filter #{unknown.first}" unless unknown.empty?
369
+ f = {}
370
+ filters.each do |k, v|
371
+ if %i[include_flagged include_fallback].include?(k)
372
+ raise InvalidArgumentError, "#{k} must be true or false" unless v == true || v == false
373
+ f[k] = v
374
+ next
375
+ end
376
+ next if v.nil?
377
+ raise InvalidArgumentError, "filter #{k} must be a String or Symbol" unless v.is_a?(String) || v.is_a?(Symbol)
378
+ f[k] = v.to_s
379
+ end
380
+
381
+ f
382
+ end
383
+
384
+ def check_id!(id)
385
+ raise InvalidArgumentError, "station_id must be a String" unless id.is_a?(String)
386
+ end
387
+
388
+ def check_limit!(limit)
389
+ return if limit.nil?
390
+ raise InvalidArgumentError, "limit must be nil or an Integer >= 1" unless limit.is_a?(Integer) && limit >= 1
391
+ end
392
+
393
+ def real?(v)
394
+ Release.real?(v)
395
+ end
396
+
397
+ def check_point!(lat, lon)
398
+ raise InvalidArgumentError, "lat must be a number in [-90, 90]" unless real?(lat) && lat >= -90 && lat <= 90
399
+ raise InvalidArgumentError, "lon must be a number in [-180, 180]" unless real?(lon) && lon >= -180 && lon <= 180
400
+ end
401
+
402
+ def utf8_query(name)
403
+ q = name.encoding == Encoding::UTF_8 ? name : name.encode(Encoding::UTF_8)
404
+ raise InvalidArgumentError, "name is not valid UTF-8" unless q.valid_encoding?
405
+ q
406
+ rescue EncodingError
407
+ raise InvalidArgumentError, "name cannot be converted to UTF-8"
408
+ end
409
+
410
+ end
411
+ include QueryArguments
412
+ private_constant :QueryArguments
413
+
414
+ # ---- station queries
415
+
416
+ def station(station_id)
417
+ check_open!
418
+ check_id!(station_id)
419
+ e = @by_id[station_id]
420
+ e && materialize(e)
421
+ end
422
+
423
+ def require_station(station_id)
424
+ check_open!
425
+ check_id!(station_id)
426
+ e = @by_id[station_id]
427
+ return materialize(e) if e
428
+ t = @tomb_by_id[station_id]
429
+ raise StationRemovedError.new("station #{station_id} was removed in #{t.removed_in}", tombstone: t) if t
430
+ raise StationNotFoundError, "no station #{station_id}"
431
+ end
432
+
433
+ def tombstone(station_id)
434
+ check_open!
435
+ check_id!(station_id)
436
+ @tomb_by_id[station_id]
437
+ end
438
+
439
+ def station_by_alias(system, alias_id)
440
+ check_open!
441
+ validate_alias_arguments(system, alias_id)
442
+ sid = @aliases.dig(system.to_s, alias_id)
443
+ sid && station(sid)
444
+ end
445
+
446
+ def stations(**filters)
447
+ check_open!
448
+ filter(filters).map { |e| materialize(e) }.freeze
449
+ end
450
+
451
+ # Each step checks that the release is not closed, also for an
452
+ # enumerator made before close.
453
+ def iter_stations(**filters)
454
+ check_open!
455
+ list = filter(filters, lazy: true)
456
+ return enum_for(:iter_stations, **filters) unless block_given?
457
+ list.each do |e|
458
+ check_open!
459
+ yield materialize(e)
460
+ end
461
+ check_open!
462
+ self
463
+ end
464
+ alias each_station iter_stations
465
+
466
+ def search(name: nil, limit: nil, match: nil, **filters)
467
+ check_open!
468
+ q = validate_search_arguments(name, limit, match)
469
+ exact = !match.nil?
470
+ matches = matcher(filters)
471
+ ranked = []
472
+ @entries.each do |e|
473
+ n = e.folded
474
+ rank = if n == q then 0
475
+ elsif exact then nil
476
+ elsif n.start_with?(q) then 1
477
+ elsif word_start?(n, q) then 2
478
+ elsif n.include?(q) then 3
479
+ end
480
+ ranked << [rank, n, e.station_id, e] if rank
481
+ end
482
+ ranked.sort_by! { |r| r[0, 3] }
483
+ ordered = ranked.map { |r| r[3] }
484
+ hinted(ordered, limit, filters, matches) do |keep|
485
+ first_matching(limit, ordered, keep).map { |e| materialize(e) }.freeze
486
+ end
487
+ end
488
+
489
+ def bbox(south: nil, west: nil, north: nil, east: nil, limit: nil, **filters)
490
+ check_open!
491
+ validate_bbox_arguments(south, west, north, east, limit)
492
+ matches = matcher(filters)
493
+ inside = @entries.lazy.select do |e|
494
+ e.lat >= south && e.lat <= north &&
495
+ (west <= east ? e.lon >= west && e.lon <= east : e.lon >= west || e.lon <= east)
496
+ end
497
+ inside = inside.to_a
498
+ hinted(inside, limit, filters, matches) do |keep|
499
+ first_matching(limit, inside, keep).map { |e| materialize(e) }.freeze
500
+ end
501
+ end
502
+
503
+ def near(lat: nil, lon: nil, radius_km: nil, limit: nil, **filters)
504
+ check_open!
505
+ validate_near_arguments(lat, lon, radius_km, limit)
506
+ distances(lat, lon, radius_km, filters, limit) do |hits|
507
+ hits.map { |d, e| Nearby.new(materialize(e), d) }.freeze
508
+ end
509
+ end
510
+
511
+ def nearest(lat: nil, lon: nil, max_km: nil, **filters)
512
+ check_open!
513
+ validate_nearest_arguments(lat, lon, max_km)
514
+ distances(lat, lon, max_km, filters, 1) do |hits|
515
+ d, e = hits.first
516
+ e && Nearby.new(materialize(e), d)
517
+ end
518
+ end
519
+
520
+ def reference_station(station)
521
+ check_open!
522
+ own_station!(station, "reference_station")
523
+ off = station.subordinate_offsets
524
+ off && off.reference_station_id && station(off.reference_station_id)
525
+ end
526
+
527
+ def subordinates_of(station)
528
+ check_open!
529
+ own_station!(station, "subordinates_of")
530
+ (@subordinates[station.station_id] || []).map { |e| materialize(e) }.freeze
531
+ end
532
+
533
+ def inspect
534
+ "#<OpenTideConstants::Release #{@datestamp} format #{@format_version} #{@entries.size} stations (#{@mode})>"
535
+ end
536
+
537
+ def self.sha256_file(path)
538
+ Digest::SHA256.file(path).hexdigest
539
+ rescue SystemCallError => e
540
+ raise FileError.new("cannot read #{path}: #{e.message}", path: path)
541
+ end
542
+
543
+ private
544
+
545
+ # Used by OpenTideConstants#verify and #close (not public on Release:
546
+ # the API manifest has them on the client only).
547
+ # Hashes the release files again and compares them with rows, the
548
+ # {name => sha256} of OTC_{D}.sha256 that the client reads again
549
+ # A file with no row is checksum_mismatch.
550
+ def verify(rows)
551
+ raise ChecksumError.new("release #{@datestamp}: no files to verify", file: nil, expected: nil, actual: nil) if @checks.empty?
552
+ @checks.each_key do |path|
553
+ expected = rows[File.basename(path)]
554
+ actual = Release.sha256_file(path)
555
+ next if actual == expected
556
+ what = expected ? "SHA-256 mismatch" : "not listed in OTC_#{@datestamp}.sha256"
557
+ raise ChecksumError.new("#{File.basename(path)}: #{what}", file: path, expected: expected, actual: actual)
558
+ end
559
+ # A .json.gz: its decompressed bytes against the .json row, as at
560
+ # open.
561
+ @checks.each_key do |path|
562
+ next unless File.basename(path) == "OTC_#{@datestamp}.json.gz"
563
+ Reader.need_rows!(path, [path], rows, "OTC_#{@datestamp}.sha256")
564
+ Reader.check_json_bytes!(path, Reader.gunzip(path), rows[File.basename(path).delete_suffix(".gz")])
565
+ end
566
+ true
567
+ end
568
+
569
+ # The paths of the data files this release was opened from.
570
+ def opened_paths
571
+ @checks.keys
572
+ end
573
+
574
+ def close
575
+ @io_lock.synchronize do
576
+ @state[:closed] = true
577
+ @io.close if @io && !@io.closed?
578
+ end
579
+ @station_cache_lock.synchronize { @station_cache.clear }
580
+ nil
581
+ end
582
+
583
+ def check_open!
584
+ raise FileError.new("the release is closed", path: @io&.path) if @state[:closed]
585
+ end
586
+
587
+ # The resolved kind of each active station, {station_id => "tide" | "current" | "other" | nil},
588
+ # for the stream index. Used by the client.
589
+ def index_kinds
590
+ @entries.to_h { |e| [e.station_id, e.kind&.to_s] }
591
+ end
592
+
593
+ def default_url
594
+ "https://data.opentideconstants.org/OTC_#{@datestamp}.json"
595
+ end
596
+
597
+ # A Station that is an active station of this release, as attribution
598
+ # checks it; nil, an unknown station or another release's
599
+ # Station is invalid_argument.
600
+ def own_station!(station, what)
601
+ raise InvalidArgumentError, "#{what}: station must be a Station" unless station.is_a?(Station)
602
+ return if @by_id.key?(station.station_id) && station.instance_variable_get(:@origin).equal?(@station_origin)
603
+ raise InvalidArgumentError, "#{what}: station #{station.station_id} is not a station of release #{@datestamp}"
604
+ end
605
+
606
+ def validate_attribution_station_owner(station)
607
+ raise InvalidArgumentError, "stations must be an Array of Station" unless station.is_a?(Station)
608
+ entry = @by_id[station.station_id]
609
+ unless entry && station.instance_variable_get(:@origin).equal?(@station_origin)
610
+ raise InvalidArgumentError, "station #{station.station_id} is not a station of release #{@datestamp}"
611
+ end
612
+ entry
613
+ end
614
+
615
+ def station_origin
616
+ @station_origin
617
+ end
618
+
619
+
620
+ # limit: nil for no limit, else an Integer of 1 or more.
621
+
622
+ # A finite real number (not a Complex, NaN or infinity).
623
+
624
+ # A real number that is finite as a double: an Integer too large for a
625
+ # double (400 digits) is not.
626
+ def self.real?(v)
627
+ v.is_a?(Numeric) && v.real? && v.to_f.finite?
628
+ end
629
+
630
+
631
+ # The query as a valid UTF-8 String; invalid_argument when it is not one.
632
+
633
+ def word_start?(n, q)
634
+ i = n.index(q)
635
+ while i
636
+ return true if i.positive? && n[i - 1] == " "
637
+ i = n.index(q, i + 1)
638
+ end
639
+ false
640
+ end
641
+
642
+ # The [distance, entry] pairs within max_km (any distance when nil),
643
+ # nearest first, that match filters; at most limit of them. They are
644
+ # yielded while the source has the candidates as its hint.
645
+ def distances(lat, lon, max_km, filters, limit = nil)
646
+ matches = matcher(filters)
647
+ hits = @entries.map { |e| [haversine(lat, lon, e.lat, e.lon), e] }
648
+ hits.select! { |d, _| d <= max_km } if max_km
649
+ hits.sort_by! { |d, e| [d, e.station_id] }
650
+ hinted(hits.map(&:last), limit, filters, matches) do |keep|
651
+ yield first_matching(limit, hits, ->((_, e)) { keep.call(e) })
652
+ end
653
+ end
654
+
655
+ # Yields the keep test for entries (matches, counting the stations it
656
+ # finds). A BGZF source is told, for this thread's query, the records
657
+ # of the entries that pass the index-only filters, each subordinate's
658
+ # reference station after it, so the records the query reads come in
659
+ # few requests. A batch is at most what the query can still use: limit
660
+ # minus the stations it has found. The hint is cleared after the block.
661
+ def hinted(entries, limit, filters, matches)
662
+ return yield(matches) unless @io.respond_to?(:hint)
663
+ f = validate_filter_arguments(filters)
664
+ same = ->(value, want) { !value.nil? && value.to_s == want }
665
+ offsets = entries.select do |e|
666
+ (!f.key?(:country) || same.call(e.country, f[:country])) &&
667
+ (!f.key?(:type) || same.call(e.type, f[:type])) && (!f.key?(:kind) || same.call(e.kind, f[:kind]))
668
+ end.flat_map do |e|
669
+ ref = e.reference_id && @by_id[e.reference_id]
670
+ ref ? [e.pos, ref.pos] : [e.pos]
671
+ end
672
+ window = ->(found) { limit.nil? ? BGZF::BATCH_RECORDS : (limit - found).clamp(1, BGZF::BATCH_RECORDS) }
673
+ hint = @io_lock.synchronize { @io.hint(offsets, window.call(0)) }
674
+ found = 0
675
+ keep = lambda do |e|
676
+ accepted = matches.call(e)
677
+ hint.window = window.call(found += 1) if accepted && hint
678
+ accepted
679
+ end
680
+ begin
681
+ yield keep
682
+ ensure
683
+ @io_lock.synchronize { @io.hint([]) unless @io.closed? }
684
+ end
685
+ end
686
+
687
+ # The first limit items (all when limit is nil) that keep accepts, in
688
+ # order; keep is not called after that.
689
+ def first_matching(limit, items, keep)
690
+ out = []
691
+ items.each do |item|
692
+ break if limit && out.size == limit
693
+ out << item if keep.call(item)
694
+ end
695
+ out
696
+ end
697
+
698
+ def haversine(lat1, lon1, lat2, lon2)
699
+ rad = Math::PI / 180
700
+ p1 = lat1 * rad
701
+ p2 = lat2 * rad
702
+ dp = p2 - p1
703
+ dl = (lon2 - lon1) * rad
704
+ a = Math.sin(dp / 2)**2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2)**2
705
+ 2 * EARTH_RADIUS_KM * Math.asin([1.0, Math.sqrt(a)].min)
706
+ end
707
+
708
+ def filter(filters, lazy: false)
709
+ matches = matcher(filters)
710
+ (lazy ? @entries.lazy : @entries).select { |e| matches.call(e) }
711
+ end
712
+
713
+ # The filter test for one entry. Eligibility can read the station's
714
+ # record to fill policy fields the index does not carry, so queries
715
+ # apply their cheap index tests (bounds, distance, name) first and call
716
+ # this only for the entries that pass them.
717
+ def matcher(filters)
718
+ f = validate_filter_arguments(filters)
719
+
720
+ # A field that is null matches no filter value, also not "".
721
+ same = ->(value, want) { !value.nil? && value.to_s == want }
722
+ lambda do |e|
723
+ (!f.key?(:country) || same.call(e.country, f[:country])) &&
724
+ (!f.key?(:type) || same.call(e.type, f[:type])) &&
725
+ (!f.key?(:kind) || same.call(e.kind, f[:kind])) &&
726
+ eligible_paths(e, f.fetch(:include_flagged, false), f.fetch(:include_fallback, false), lazy: true).any? do |cs|
727
+ (!f.key?(:source) || same.call(cs["source"], f[:source])) &&
728
+ (!f.key?(:source_type) || same.call(Util.enum(cs["source_type"], ENUMS[:source_type]), f[:source_type]))
729
+ end
730
+ end
731
+ end
732
+
733
+ def materialize(e, canonical: nil, reader_version: nil)
734
+ check_open!
735
+ return e.station if e.station
736
+ cached = @station_cache_lock.synchronize do
737
+ station = @station_cache.delete(e.station_id)
738
+ @station_cache[e.station_id] = station if station
739
+ station
740
+ end
741
+ return cached if cached
742
+ raw = read_station_source(e, canonical: canonical, reader_version: reader_version)
743
+ effective = e.eff_id
744
+ if @commercial_only && Reader.policy_uncached?(e.view, offsets: false, alternatives: false)
745
+ sets = raw["constant_sets"] || []
746
+ effective = effective_set(sets.find { |cs| cs["set_id"] == raw["recommended_set_id"] }, sets)&.fetch("set_id")
747
+ end
748
+ station = build_station(raw, e.kind, effective)
749
+ @io_lock.synchronize do
750
+ check_open!
751
+ @station_cache_lock.synchronize do
752
+ @station_cache[e.station_id] = station
753
+ @station_cache.shift while @station_cache.size > 256
754
+ end
755
+ end
756
+ station
757
+ end
758
+
759
+ # Policy hydration uses the same validated source row transiently,
760
+ # without populating the Station LRU with rejected complete fits.
761
+ def read_station_source(e, canonical: nil, reader_version: nil)
762
+ line = @io_lock.synchronize do
763
+ raise FileError.new("the release is closed", path: @io&.path) if @io.nil? || @io.closed?
764
+ @io.seek(e.pos)
765
+ @io.read(e.len)
766
+ end
767
+ raw, why = line && line.bytesize == e.len ? parse_station(line, canonical: canonical, reader_version: reader_version) : nil
768
+ unless raw.is_a?(Hash) && raw["station_id"] == e.station_id
769
+ bad_line!(e, raw.is_a?(Hash) ? "is #{raw['station_id'].inspect}" : ["is not a station line", why].compact.join(": "))
770
+ end
771
+ if e.view
772
+ if canonical
773
+ canonical.__send__(:compare_station_source, index_entry: e, station_source_row: raw, index_presence: self)
774
+ else
775
+ check_line!(raw, e)
776
+ end
777
+ end
778
+ raw
779
+ rescue SystemCallError, IOError => err
780
+ raise FileError.new("cannot read station #{e.station_id}: #{err.message}", path: @io&.path)
781
+ end
782
+
783
+ # A line that is not the station its entry names: invalid_release. When
784
+ # the entry came from index-v1.json, the client deletes that index so
785
+ # the next open rebuilds it.
786
+ def bad_line!(e, what)
787
+ source = @on_bad_index ? "index-v1.json" : "the .jsonl"
788
+ msg = "#{source}: the line at byte #{e.pos} for #{e.station_id} #{what}"
789
+ @on_bad_index&.call(msg)
790
+ raise InvalidReleaseError, msg
791
+ end
792
+
793
+ # A line read through the stream index gets the checks of the full
794
+ # pass, and every represented source field must match the entry
795
+ # otherwise bad_line!.
796
+ def check_line!(raw, e)
797
+ begin
798
+ Release.check_station!(raw)
799
+ aliases = raw["aliases"]
800
+ unless aliases.nil? || (aliases.is_a?(Hash) && aliases.values.all? { |v| v.is_a?(String) || (v.is_a?(Array) && v.all?(String)) })
801
+ raise InvalidReleaseError, "station #{e.station_id}: aliases must map a system to a String id or a list of them"
802
+ end
803
+ rescue InvalidReleaseError => err
804
+ bad_line!(e, "fails a check: #{err.message}")
805
+ end
806
+ summary = Reader.index_entry(raw, e.pos, e.len)
807
+ if summary["kind"].nil? && e.kind && raw["type"] == "subordinate" && e.reference_id
808
+ summary["kind"] = @by_id.fetch(e.reference_id).kind&.to_s
809
+ end
810
+ return if Reader.line_view(summary, presence: e.view["presence"]) == e.view
811
+ bad_line!(e, "does not give the represented source fields of its entry")
812
+ end
813
+
814
+ # Returns [the parsed line, nil], or [nil, why it does not parse]. The
815
+ # reason goes into the invalid_release message.
816
+ def parse_station(line, canonical: nil, reader_version: nil)
817
+ return [canonical.__send__(:decode_release_document, source_bytes: line, reader_version: reader_version, document_kind: "station_row"), nil] if canonical
818
+ line = line.force_encoding(Encoding::UTF_8)
819
+ Util.no_lone_surrogate!(line)
820
+ [JSON.parse(line), nil]
821
+ rescue JSON::ParserError, EncodingError, InvalidReleaseError => err
822
+ [nil, err.message[0, 200]]
823
+ end
824
+
825
+ # rec_id: the set the Station gives as recommended (the effective one
826
+ # under commercial_only).
827
+ def build_station(raw, kind, rec_id)
828
+ all_validation = Array(raw["validation"]).map { |v| Validation.new(v) }
829
+ raw_sets = Array(raw["constant_sets"])
830
+ metadata_id = rec_id
831
+ if @commercial_only && @commercial_basis == "strict"
832
+ published_id = raw["recommended_set_id"]
833
+ published = raw_sets.find { |cs| cs["set_id"] == published_id }
834
+ metadata_id = effective_set(published, raw_sets, eligible: method(:commercial_licence?))&.fetch("set_id")
835
+ end
836
+ sets = raw_sets.map do |cs|
837
+ set_validation = all_validation.each_with_index.select { |v, _| v.set_id == cs["set_id"] }
838
+ .sort_by { |v, i| [v.window.to_s, i] }.map(&:first)
839
+ ConstantSet.__send__(:with_recommendations, cs, convention: @convention_by_id.fetch(cs["convention_id"]),
840
+ licence: @licence_by_id.fetch(cs["licence_id"]), validation: set_validation,
841
+ recommended: !metadata_id.nil? && cs["set_id"] == metadata_id,
842
+ effective: !rec_id.nil? && cs["set_id"] == rec_id)
843
+ end
844
+ Station.new(raw, sets: sets, kind: kind, validation: all_validation, origin: self, licences: @licence_by_id)
845
+ end
846
+
847
+ # Checks every station and builds the indexes. In stream mode no
848
+ # Station is kept.
849
+ def bind_eager_station_owners(entries, raws)
850
+ if @mode == :eager
851
+ entries.each { |e| e.station = build_station(raws[e.station_id], e.kind, e.eff_id) }
852
+ end
853
+ entries.each(&:freeze)
854
+ end
855
+
856
+ def bind_prepared_release_fields(prepared)
857
+ @station_origin = Object.new.freeze
858
+ @mode = prepared.mode
859
+ @commercial_only = prepared.commercial_only
860
+ @commercial_basis = prepared.commercial_basis
861
+ @historical_offsets_policy = prepared.historical_offsets_policy
862
+ @meta = prepared.meta
863
+ @logger = prepared.logger
864
+ @io = prepared.io
865
+ @on_bad_index = prepared.on_bad_index
866
+ @io_lock = prepared.io_lock
867
+ @station_cache = prepared.station_cache
868
+ @station_cache_lock = prepared.station_cache_lock
869
+ @state = prepared.state
870
+ @files = prepared.files
871
+ @checks = prepared.checks
872
+ @datestamp = prepared.datestamp
873
+ @created = prepared.created
874
+ @format_version = prepared.format_version
875
+ @concept_doi = prepared.concept_doi
876
+ @zenodo_version_doi = prepared.zenodo_version_doi
877
+ @source_versions = prepared.source_versions
878
+ @build_commit = prepared.build_commit
879
+ @changelog_url = prepared.changelog_url
880
+ @conventions = prepared.conventions
881
+ @licences = prepared.licences
882
+ @convention_by_id = prepared.convention_by_id
883
+ @licence_by_id = prepared.licence_by_id
884
+ @set_ids = prepared.set_ids
885
+ @set_sources = prepared.set_sources
886
+ @set_qc = prepared.set_qc
887
+ @aliases = prepared.aliases
888
+ @by_id = prepared.by_id
889
+ @entries = prepared.entries
890
+ @tombstones = prepared.tombstones
891
+ @tomb_pos = prepared.tomb_pos
892
+ @tomb_by_id = prepared.tomb_by_id
893
+ @constituent_names = prepared.constituent_names
894
+ @subordinates = prepared.subordinates
895
+ end
896
+
897
+ def load_stations(stations)
898
+ entries = []
899
+ tombs = []
900
+ tomb_pos = []
901
+ raws = {}
902
+ names = Set.new
903
+ ids = Set.new
904
+ @set_ids = Set.new
905
+ @set_sources = []
906
+ @set_qc = []
907
+ stations.each do |raw, pos, len, view|
908
+ raise InvalidReleaseError, "a station is not an object" unless raw.is_a?(Hash)
909
+ sid = raw["station_id"]
910
+ raise InvalidReleaseError, "a station has no station_id" unless sid.is_a?(String)
911
+ # One id across the active stations and the tombstones together.
912
+ raise InvalidReleaseError, "station_id #{sid} appears twice" unless ids.add?(sid)
913
+ # A line with no status (or null) is an active station, as in the stream index.
914
+ status = raw["status"].nil? ? "active" : raw["status"]
915
+ # A status that is there but not a String is malformed (schema type string).
916
+ raise InvalidReleaseError, "station #{sid}: status is not a string: #{status.inspect[0, 100]}" unless status.is_a?(String)
917
+ if status == "removed"
918
+ Release.check_tombstone!(raw)
919
+ tombs << Tombstone.new(raw)
920
+ tomb_pos << [tombs.last, pos, len]
921
+ next
922
+ end
923
+ unless status == "active"
924
+ # A status this SDK does not know (a newer minor's value): not a
925
+ # station, not a tombstone, in no query and no count; said once,
926
+ # at load.
927
+ @logger&.warn("opentideconstants: station #{sid} has the status #{status.inspect}, which this SDK " \
928
+ "does not know: it is left out of every query")
929
+ next
930
+ end
931
+ Release.check_station!(raw)
932
+ entries << entry_for(raw, pos, len, names)
933
+ entries.last.view = view
934
+ raws[sid] = raw if @mode == :eager
935
+ end
936
+ entries.sort_by!(&:station_id)
937
+ @by_id = entries.to_h { |e| [e.station_id, e] }
938
+ entries.each do |e|
939
+ refs = [e.reference_id] + Array(e.subordinate_offset_alternatives).map { |wrapper| wrapper["offsets"]["reference_station_id"] }
940
+ refs.each do |ref|
941
+ next if ref.nil? || (ref.is_a?(String) && @by_id.key?(ref))
942
+ raise InvalidReleaseError, "station #{e.station_id}: reference_station_id #{ref.inspect} names no active station"
943
+ end
944
+ end
945
+ @set_ids = nil
946
+ kinds = entries.to_h { |e| [e.station_id, kind_of(e, [])] }
947
+ entries.each { |e| e.kind = kinds.fetch(e.station_id) }
948
+ entries.each do |e|
949
+ next unless e.view && e.view["kind"] != e.kind&.to_s
950
+ raise InvalidReleaseError, "index-v1.json: station #{e.station_id} has the wrong derived kind"
951
+ end
952
+ bind_eager_station_owners(entries, raws)
953
+ @entries = entries.freeze
954
+ @by_id.freeze
955
+ @tombstones = tombs.sort_by(&:station_id).freeze
956
+ @tomb_pos = tomb_pos.freeze
957
+ @tomb_by_id = @tombstones.to_h { |t| [t.station_id, t] }.freeze
958
+ @constituent_names = names.to_a.sort.freeze
959
+ @set_sources.freeze
960
+ @set_qc.freeze
961
+ subs = Hash.new { |h, k| h[k] = [] }
962
+ entries.each { |e| subs[e.reference_id] << e if e.type == :subordinate && e.reference_id }
963
+ @subordinates = subs.transform_values(&:freeze).freeze
964
+ @aliases = (@aliases || {}).to_a.to_h { |k, v| [k, v.freeze] }.freeze
965
+ end
966
+
967
+ def entry_for(raw, pos, len, names)
968
+ sid = raw["station_id"]
969
+ %w[name lat lon type].each do |k|
970
+ raise InvalidReleaseError, "station #{sid}: #{k} missing" if raw[k].nil?
971
+ end
972
+ rec_id = raw["recommended_set_id"]
973
+ sets = raw["constant_sets"] || []
974
+ raise InvalidReleaseError, "station #{sid}: constant_sets is not an array" unless sets.is_a?(Array)
975
+ rec = nil
976
+ sources = Set.new
977
+ sets.each do |cs|
978
+ raise InvalidReleaseError, "station #{sid}: a set is not an object" unless cs.is_a?(Hash)
979
+ raise InvalidReleaseError, "set_id #{cs['set_id'].inspect} appears twice" unless @set_ids.add?(cs["set_id"])
980
+ unless @convention_by_id.key?(cs["convention_id"])
981
+ raise InvalidReleaseError, "set #{cs['set_id']}: convention #{cs['convention_id'].inspect} does not resolve"
982
+ end
983
+ unless @licence_by_id.key?(cs["licence_id"])
984
+ raise InvalidReleaseError, "set #{cs['set_id']}: licence #{cs['licence_id'].inspect} does not resolve"
985
+ end
986
+ rec = cs if !rec_id.nil? && cs["set_id"] == rec_id
987
+ qc = Util.enum(cs["qc_status"], ENUMS[:qc_status])
988
+ # Only a set with constants (ok or flagged) is a usable source.
989
+ if USABLE_QC.include?(qc)
990
+ sources << cs["source"]
991
+ @set_sources << cs["source"]
992
+ end
993
+ @set_qc << qc
994
+ Array(cs["constituents"]).each { |c| names << c["name"] if c.is_a?(Hash) && c["name"] }
995
+ end
996
+ raise InvalidReleaseError, "station #{sid}: recommended set #{rec_id} does not exist" if rec_id && rec.nil?
997
+ off = raw["subordinate_offsets"]
998
+ off = nil unless off.is_a?(Hash)
999
+ self.class.subordinate_offset_models(raw).each_value do |offsets|
1000
+ if offsets["licence_id"] && !@licence_by_id.key?(offsets["licence_id"])
1001
+ raise InvalidReleaseError, "station #{sid}: offsets licence #{offsets['licence_id'].inspect} does not resolve"
1002
+ end
1003
+ end
1004
+ index_aliases(sid, raw["aliases"])
1005
+ Array(raw["source_records"]).each { |r| SourceRecord.new(r, licences: @licence_by_id) }
1006
+ eff = @commercial_only ? effective_set(rec, sets) : rec
1007
+ # Keep the reader's discovery fields, not the full fits. The names
1008
+ # were collected above; materialize reads the complete line on demand.
1009
+ summaries = Reader.index_entry(raw, pos, len).fetch("sets")
1010
+ summaries.each { |cs| cs.delete("constituents") }
1011
+ Entry.new(station_id: sid, name: raw["name"], folded: Fold.fold(raw["name"].to_s), lat: raw["lat"],
1012
+ lon: raw["lon"], type: Util.enum(raw["type"], ENUMS[:station_type]), country: raw["country"],
1013
+ kind: rec && quantity_kind(rec["quantity"]), sources: sources.freeze,
1014
+ rec_source_type: rec && Util.enum(rec["source_type"], ENUMS[:source_type]),
1015
+ rec_licence_id: rec && rec["licence_id"], offsets_licence_id: off && off["licence_id"],
1016
+ reference_id: off && off["reference_station_id"],
1017
+ eff_id: eff && eff["set_id"], eff_licence_id: eff && eff["licence_id"],
1018
+ eff_source_type: eff && Util.enum(eff["source_type"], ENUMS[:source_type]),
1019
+ offsets_ref_licence_id: sets.find { |cs| offsets_reference_set?(cs) }&.fetch("licence_id"),
1020
+ aliases: (raw["aliases"].is_a?(Hash) ? raw["aliases"].transform_values { |v| Array(v) } : {}),
1021
+ sets: summaries, offsets: off, current_offsets: raw["current_offsets"] || [],
1022
+ subordinate_offset_alternatives: raw["subordinate_offset_alternatives"], prediction_profiles: raw["prediction_profiles"],
1023
+ pos: pos, len: len, station: nil)
1024
+ end
1025
+
1026
+ # The effective recommended set under commercial_only:
1027
+ # the release's recommended set when its licence allows
1028
+ # commercial use; otherwise the first set in file order of the same
1029
+ # typed quantity, qc_status ok, with a commercial licence; then the same
1030
+ # with flagged; otherwise nil. A set with no quantity never matches.
1031
+ def commercial_set?(cs)
1032
+ return false if @commercial_basis == "strict" && cs.dig("fallback", "reason") == "licence_reading"
1033
+ commercial_licence?(cs)
1034
+ end
1035
+
1036
+ def commercial_licence?(cs)
1037
+ @licence_by_id[cs["licence_id"]]&.commercial_use == true
1038
+ end
1039
+
1040
+ def set_eligible?(cs, flagged, fallback, offsets_licence = nil)
1041
+ return false unless cs && %w[ok flagged].include?(cs["qc_status"])
1042
+ if cs["fallback"]
1043
+ return false unless fallback
1044
+ else
1045
+ return false if cs["qc_status"] != "ok" && !flagged
1046
+ end
1047
+ return false if offsets_licence && !@licence_by_id.key?(offsets_licence)
1048
+ return true unless @commercial_only
1049
+ return false if @commercial_basis == "strict" && cs.dig("fallback", "reason") == "licence_reading"
1050
+ [cs["licence_id"], offsets_licence].compact.all? { |lid| @licence_by_id[lid]&.commercial_use == true }
1051
+ end
1052
+
1053
+ # Hydrate only missing policy fields demanded by this path. Reuse the
1054
+ # checked compact summary without retaining its full station fit.
1055
+ def policy_entry(e, private_fields: false, offsets: true, alternatives: true)
1056
+ return e unless e
1057
+ cached = @station_cache_lock.synchronize { @state[:policy_entries]&.[](e.station_id) }
1058
+ return cached if cached
1059
+ return e unless Reader.policy_uncached?(e.view, private_fields: private_fields, offsets: offsets, alternatives: alternatives)
1060
+ station = e.station || @station_cache_lock.synchronize { @station_cache[e.station_id] }
1061
+ raw = station ? station.raw : read_station_source(e)
1062
+ Array(raw["source_records"]).each { |record| SourceRecord.new(record, licences: @licence_by_id) }
1063
+ summary = Reader.index_entry(raw, e.pos, e.len)
1064
+ Array(summary["subordinate_offset_alternatives"]).each do |wrapper|
1065
+ off = wrapper["offsets"]
1066
+ if off["licence_id"] && !@licence_by_id.key?(off["licence_id"])
1067
+ raise InvalidReleaseError, "station #{e.station_id}: offsets licence does not resolve"
1068
+ end
1069
+ unless @by_id.key?(off["reference_station_id"])
1070
+ raise InvalidReleaseError, "station #{e.station_id}: alternative reference_station_id names no active station"
1071
+ end
1072
+ end
1073
+ summary["sets"].each { |cs| cs.delete("constituents") }
1074
+ Util.deep_freeze(summary)
1075
+ candidate = e.dup
1076
+ candidate.sets = summary["sets"]
1077
+ candidate.offsets = summary["subordinate_offsets"]
1078
+ candidate.current_offsets = summary["current_offsets"] || []
1079
+ candidate.subordinate_offset_alternatives = summary["subordinate_offset_alternatives"]
1080
+ sets = raw["constant_sets"] || []
1081
+ rec = sets.find { |cs| cs["set_id"] == raw["recommended_set_id"] }
1082
+ effective = @commercial_only ? effective_set(rec, sets) : rec
1083
+ candidate.eff_id = effective&.fetch("set_id")
1084
+ candidate.eff_licence_id = effective&.fetch("licence_id")
1085
+ candidate.freeze
1086
+ @station_cache_lock.synchronize { (@state[:policy_entries] ||= {})[e.station_id] ||= candidate }
1087
+ end
1088
+
1089
+ def eligible_paths(e, flagged, fallback, historical: true, lazy: false)
1090
+ return enum_for(:eligible_paths, e, flagged, fallback, historical: historical) if lazy
1091
+ return enum_for(:eligible_paths, e, flagged, fallback, historical: historical).to_a unless block_given?
1092
+ e = policy_entry(e, offsets: false, alternatives: false)
1093
+ e.sets.each { |cs| yield cs if set_eligible?(cs, flagged, fallback) }
1094
+ e = policy_entry(e)
1095
+ ref = policy_entry(@by_id[e.reference_id], offsets: false, alternatives: false)
1096
+ off = e.offsets || {}
1097
+ if off["offset_id"]
1098
+ yield off if historical && historical_discovery?(e)
1099
+ elsif ref
1100
+ cs = ref.sets.find { |v| offsets_reference_set?(v) }
1101
+ yield cs if set_eligible?(cs, flagged, fallback, e.offsets_licence_id)
1102
+ end
1103
+ Array(e.subordinate_offset_alternatives).each do |wrapper|
1104
+ offsets = wrapper["offsets"]
1105
+ next unless set_eligible?({ "qc_status" => "ok" }.merge(offsets), flagged, fallback)
1106
+ parent = policy_entry(@by_id[offsets["reference_station_id"]], offsets: false, alternatives: false)
1107
+ next unless parent
1108
+ cs = retained_reference_set(parent)
1109
+ if set_eligible?(cs, flagged, fallback, offsets["licence_id"])
1110
+ yield cs.merge("source" => offsets["source"] || cs["source"], "source_type" => offsets["source_type"] || cs["source_type"])
1111
+ end
1112
+ end
1113
+ e.current_offsets.each do |co|
1114
+ parent = policy_entry(@by_id[co["reference_station_id"]], offsets: false, alternatives: false)
1115
+ n = co["reference_bin"]
1116
+ own = co["bin"]
1117
+ next unless parent && [n, own].all? { |i| i.is_a?(Numeric) && i == i.to_i && i.between?(1, 2**53 - 1) }
1118
+ cs = parent.sets.find { |v| v["quantity"] == "current" && %w[ok flagged].include?(v["qc_status"]) && Array(v["current_bins"]).any? { |b| (b.is_a?(Hash) ? b["bin"] : b) == n } }
1119
+ yield cs if set_eligible?(cs, flagged, fallback, co["licence_id"])
1120
+ end
1121
+ nil
1122
+ end
1123
+
1124
+ def historical_discovery?(e)
1125
+ return false if @historical_offsets_policy == "exclude"
1126
+ return false if e.sets.any? { |cs| cs["set_id"] == e.eff_id && %w[ok flagged].include?(cs["qc_status"]) }
1127
+ return false unless eligible_paths(e, false, false, historical: false).empty?
1128
+ off = e.offsets
1129
+ ref = policy_entry(@by_id[off["reference_station_id"]], private_fields: true, offsets: false, alternatives: false)
1130
+ return false unless ref
1131
+ cs = ref.sets.find { |v| offsets_reference_set?(v) }
1132
+ binding = off.dig("provenance", "reference_binding")
1133
+ return false unless cs && cs["qc_status"] == "ok" && cs["fallback"].nil? && cs["source_record_id"] == binding["noaa_id"]
1134
+ return false if @commercial_only && (!commercial_set?(cs) || @licence_by_id[off["licence_id"]]&.commercial_use != true)
1135
+ conv = @convention_by_id[cs["convention_id"]]
1136
+ return false unless conv && conv.v0_model == "schureman_tcd" && conv.nodal_handling == :f_u_at_prediction
1137
+ datum = cs["datum"] || {}
1138
+ return false unless datum["chart_datum"] == "mllw" && datum["msl_offset_m"] && datum.dig("named", "mllw") == 0.0 && datum.dig("basis", "mllw", "kind") == "published"
1139
+ constants = materialize(ref).constant_set(cs["set_id"])
1140
+ begin
1141
+ table = Predict.table_for(self, constants)
1142
+ Array(constants.raw["constituents"]).each { |row| table.send(:row_for, row["name"]) }
1143
+ rescue NoAstroTableError, UnsupportedConventionError, UnsupportedConstituentError, InvalidArgumentError
1144
+ return false
1145
+ end
1146
+ true
1147
+ end
1148
+
1149
+ def effective_set(rec, sets, eligible: method(:commercial_set?))
1150
+ return rec if rec.nil? || eligible.call(rec)
1151
+ q = Util.enum(rec["quantity"], ENUMS[:quantity])
1152
+ return nil if q.nil?
1153
+ %i[ok flagged].each do |status|
1154
+ found = sets.find do |cs|
1155
+ Util.enum(cs["qc_status"], ENUMS[:qc_status]) == status && Util.enum(cs["quantity"], ENUMS[:quantity]) == q &&
1156
+ eligible.call(cs)
1157
+ end
1158
+ return found if found
1159
+ end
1160
+ nil
1161
+ end
1162
+
1163
+ # A set that the one-link offsets path takes as its reference set
1164
+ # from the offsets' source, water_level, ok or
1165
+ # flagged.
1166
+ def offsets_reference_set?(cs)
1167
+ cs["source"] == OFFSETS_SOURCE && Util.enum(cs["quantity"], ENUMS[:quantity]) == :water_level &&
1168
+ USABLE_QC.include?(Util.enum(cs["qc_status"], ENUMS[:qc_status]))
1169
+ end
1170
+
1171
+ # Match prediction's recommended-first, then set_id ordering using
1172
+ # compact policy summaries instead of materializing reference fits.
1173
+ def retained_reference_set(reference)
1174
+ reference = policy_entry(reference, offsets: false, alternatives: false)
1175
+ reference.sets.select { |cs| offsets_reference_set?(cs) }
1176
+ .min_by { |cs| [cs["set_id"] == reference.eff_id ? 0 : 1, cs["set_id"]] }
1177
+ end
1178
+
1179
+ # The JSON type of each known field that the SDK reads (# tolerant is not lax). Absent or null is always allowed
1180
+ # here; required fields are checked where they are used. :t a String,
1181
+ # :n a finite number, :i a finite number with an integral value, :o an
1182
+ # object, :l a list of objects, :s a list of Strings, :a a list. The
1183
+ # same table is in the Python, TypeScript and C SDKs.
1184
+ STATION_TYPES = { "name" => :t, "country" => :t, "timezone" => :t, "type" => :t, "recommended_set_id" => :t,
1185
+ "status" => :t, "constant_sets" => :l, "validation" => :l, "subordinate_offsets" => :o,
1186
+ "current_offsets" => :a, "source_records" => :l, "recommended_is_fallback" => :b }.freeze
1187
+ OFFSET_TYPES = { "reference_station_id" => :t, "licence_id" => :t, "height_adjusted_type" => :t,
1188
+ "time_offset_high_min" => :n, "time_offset_low_min" => :n, "height_offset_high" => :n,
1189
+ "height_offset_low" => :n, "offset_id" => :t, "source" => :t, "source_type" => :t,
1190
+ "source_version" => :t, "source_record_id" => :t, "qc_status" => :t, "qc_flags" => :l,
1191
+ "fallback" => :o, "vintage" => :o, "provenance" => :o }.freeze
1192
+ VALIDATION_TYPES = { "set_id" => :t, "reference_source" => :t, "reference_station" => :t, "window" => :t,
1193
+ "reference_distance_km" => :n, "time_mae_min" => :n, "time_p95_min" => :n,
1194
+ "time_bias_min" => :n, "height_mae_m" => :n, "range_error_m" => :n,
1195
+ "missed_events" => :i, "extra_events" => :i, "previous_release" => :o }.freeze
1196
+ SET_TYPES = { "set_id" => :t, "source" => :t, "source_type" => :t, "quantity" => :t, "source_record_id" => :t,
1197
+ "source_version" => :t, "convention_id" => :t, "licence_id" => :t, "qc_status" => :t,
1198
+ "constituents" => :l, "dropped_constituents" => :l, "qc_flags" => :l, "record_span" => :o,
1199
+ "datum" => :o, "time_base" => :o, "provenance" => :o, "current_bins" => :a, "fallback" => :o }.freeze
1200
+ SPAN_TYPES = { "good_samples" => :i }.freeze
1201
+ DATUM_TYPES = { "msl_offset_m" => :n, "named" => :o }.freeze
1202
+ CONSTITUENT_TYPES = { "name" => :t, "source_name" => :t, "doodson" => :t, "kept_reason" => :t,
1203
+ "speed_deg_per_hour" => :n, "amplitude_m" => :n, "phase_deg" => :n,
1204
+ "amp_uncertainty_m" => :n, "phase_uncertainty_deg" => :n }.freeze
1205
+ QC_FLAG_TYPES = { "flag" => :t, "reason" => :t, "values" => :o }.freeze
1206
+ DROPPED_TYPES = { "name" => :t, "dropped_reason" => :t, "detail" => :t }.freeze
1207
+ TIME_BASE_TYPES = { "code" => :t, "reason" => :t, "declared" => :t, "published" => :t, "decided_in" => :t,
1208
+ "decided_build_commit" => :t, "correction" => :o, "months_dropped" => :s,
1209
+ "evidence" => :l }.freeze
1210
+ CORRECTION_TYPES = { "from" => :t, "to" => :t }.freeze
1211
+ EVIDENCE_TYPES = { "comparator_kind" => :t, "comparator_id" => :t, "detail" => :t, "distance_km" => :n,
1212
+ "lag_min" => :n }.freeze
1213
+ PROVENANCE_TYPES = { "adapter_version" => :t, "carried_from_release" => :t, "selection_reason" => :t,
1214
+ "input_sha256" => :s, "decision" => :o }.freeze
1215
+
1216
+ # The shape checks of a tombstone line: its fields are strings or null.
1217
+ def self.check_tombstone!(raw)
1218
+ %w[name removed_in removed_reason merged_into detail].each do |k|
1219
+ next if raw[k].nil? || raw[k].is_a?(String)
1220
+ raise InvalidReleaseError, "tombstone #{raw['station_id']}: #{k} is not a string"
1221
+ end
1222
+ end
1223
+
1224
+ def self.type_ok?(v, type)
1225
+ return true if v.nil?
1226
+ case type
1227
+ when :b then v == true || v == false
1228
+ when :t then v.is_a?(String)
1229
+ when :n then real?(v)
1230
+ when :i then real?(v) && v == v.to_i
1231
+ when :o then v.is_a?(Hash)
1232
+ when :l then v.is_a?(Array) && v.all?(Hash)
1233
+ when :s then v.is_a?(Array) && v.all?(String)
1234
+ else v.is_a?(Array)
1235
+ end
1236
+ end
1237
+
1238
+ def self.check_types!(obj, table, what)
1239
+ table.each do |k, type|
1240
+ raise InvalidReleaseError, "#{what}: #{k} has the wrong type" unless type_ok?(obj[k], type)
1241
+ end
1242
+ end
1243
+
1244
+ # The shape checks of an active station line: every
1245
+ # field that the SDK reads has the type of the format, also the nested
1246
+ # ones, so a malformed station fails the load with invalid_release in
1247
+ # eager and stream mode alike, never a raw error at the first query.
1248
+ def self.check_historical_offsets!(off, what)
1249
+ return unless off
1250
+ raise InvalidReleaseError, "#{what}: subordinate_offsets must be an object" unless off.is_a?(Hash)
1251
+ check_types!(off, OFFSET_TYPES, "#{what}: subordinate_offsets")
1252
+ historical = off.key?("offset_id") || off.dig("fallback", "reason") == "historical_offsets" || Array(off["qc_flags"]).any? { |f| f.is_a?(Hash) && f["flag"] == "fallback:historical_offsets" }
1253
+ return unless historical
1254
+ fail_field = ->(key) { raise InvalidReleaseError, "#{what}: invalid or missing historical #{key}" }
1255
+ fail_field.call("profile") unless HistoricalFingerprint.matches?(off)
1256
+ text = ->(value) { value.is_a?(String) && !value.strip.empty? }
1257
+ digest = ->(value) { value.is_a?(String) && value.match?(/\A[a-f0-9]{64}\z/) }
1258
+ hashes = ->(values) { values.is_a?(Array) && !values.empty? && values.uniq.size == values.size && values.all? { |v| digest.call(v) } }
1259
+ fail_field.call("licence_id") unless text.call(off["licence_id"])
1260
+ flags = off["qc_flags"]
1261
+ fail_field.call("qc_flags") unless flags.is_a?(Array) && flags.size == 1 && flags[0].is_a?(Hash) && flags[0]["flag"] == "fallback:historical_offsets" && (!flags[0].key?("reason") || text.call(flags[0]["reason"]))
1262
+ fallback = off["fallback"]
1263
+ fail_field.call("fallback") unless fallback.is_a?(Hash) && fallback["reason"] == "historical_offsets" && %w[basis otc_finding].all? { |k| !fallback.key?(k) || text.call(fallback[k]) } && !fallback.key?("preferred_set_id")
1264
+ vintage = off["vintage"]
1265
+ fail_field.call("vintage") unless vintage.is_a?(Hash)
1266
+ equivalence = vintage["reference_2020_equivalence"]
1267
+ fail_field.call("reference_2020_equivalence") unless %w[not_checked matched_at_publisher_precision disagrees].include?(equivalence)
1268
+ if equivalence == "not_checked"
1269
+ fail_field.call("reference_2020_equivalence_sha256") if vintage.key?("reference_2020_equivalence_sha256")
1270
+ else
1271
+ fail_field.call("reference_2020_equivalence_sha256") unless digest.call(vintage["reference_2020_equivalence_sha256"])
1272
+ end
1273
+ prov = off["provenance"]
1274
+ fail_field.call("provenance") unless prov.is_a?(Hash)
1275
+ fail_field.call("provenance hashes") unless hashes.call(prov["input_sha256"]) && (!prov.key?("acceptance_report_sha256") || digest.call(prov["acceptance_report_sha256"]))
1276
+ %w[id_crosswalk reference_binding].each do |key|
1277
+ nested = prov[key]
1278
+ fail_field.call(key) unless nested.is_a?(Hash) && hashes.call(nested["evidence_sha256"])
1279
+ end
1280
+ begin
1281
+ fail_field.call("raw_values_json") unless text.call(prov["raw_values_json"]) && JSON.parse(prov["raw_values_json"]).is_a?(Hash)
1282
+ rescue JSON::ParserError
1283
+ fail_field.call("raw_values_json")
1284
+ end
1285
+ end
1286
+
1287
+ def self.check_source_records!(raw, what)
1288
+ return unless raw.key?("source_records")
1289
+ records = raw["source_records"]
1290
+ raise InvalidReleaseError, "#{what}: source_records must be a nonempty array" unless records.is_a?(Array) && !records.empty?
1291
+ records.each do |r|
1292
+ raise InvalidReleaseError, "#{what}: source record is not an object" unless r.is_a?(Hash)
1293
+ check_types!(r, {"source"=>:t,"source_version"=>:t,"source_record_id"=>:t,"role"=>:t,"disposition"=>:t,"detail"=>:t,"licence_id"=>:t,"upstream_licence_id"=>:t,"published_set_ids"=>:s,"provenance"=>:o,"original_metadata"=>:o,"original_harmonics"=>:o}, what)
1294
+ %w[source source_version source_record_id role disposition].each do |k|
1295
+ raise InvalidReleaseError, "#{what}: source record #{k} must be nonempty" unless r[k].is_a?(String) && !r[k].empty?
1296
+ end
1297
+ if r.key?("detail") && (!r["detail"].is_a?(String) || r["detail"].empty?)
1298
+ raise InvalidReleaseError, "#{what}: source record detail must be nonempty"
1299
+ end
1300
+ unless r.key?("licence_id") && r["published_set_ids"].is_a?(Array) && r["provenance"].is_a?(Hash)
1301
+ raise InvalidReleaseError, "#{what}: source record missing licence/published_set_ids/provenance"
1302
+ end
1303
+ check_types!(r["provenance"], {"input_sha256"=>:s,"inventory_sha256"=>:t}, what)
1304
+ unless r["provenance"]["input_sha256"].is_a?(Array) && r["provenance"]["inventory_sha256"].is_a?(String)
1305
+ raise InvalidReleaseError, "#{what}: source record provenance missing input_sha256/inventory_sha256"
1306
+ end
1307
+ if r.key?("original_metadata") && !r["original_metadata"].is_a?(Hash)
1308
+ raise InvalidReleaseError, "#{what}: original_metadata must be an object"
1309
+ end
1310
+ h=r["original_harmonics"]
1311
+ next unless h
1312
+ check_types!(h, {"format"=>:t,"columns"=>:s,"rows"=>:a,"annotations"=>:l,"amplitude_unit"=>:t,"amplitude_unit_basis"=>:t,"phase_unit"=>:t,"phase_convention"=>:t,"amplitude_uncertainty_unit"=>:t,"amplitude_uncertainty_unit_basis"=>:t}, what)
1313
+ if h.key?("rows") && !(h["rows"].is_a?(Array) && h["rows"].all? { |row| row.is_a?(Array) && row.all?(String) })
1314
+ raise InvalidReleaseError, "#{what}: original_harmonics rows must contain arrays of strings"
1315
+ end
1316
+ Array(h["annotations"]).each { |a| check_types!(a, {"row"=>:i,"reason"=>:t,"detail"=>:t}, what) }
1317
+ end
1318
+ end
1319
+
1320
+ def self.check_station!(raw)
1321
+ sid = raw["station_id"]
1322
+ what = "station #{sid}"
1323
+ raise InvalidReleaseError, "#{what}: name is not a string" unless raw["name"].is_a?(String)
1324
+ check_types!(raw, STATION_TYPES, what)
1325
+ check_source_records!(raw, what)
1326
+ check_historical_offsets!(raw["subordinate_offsets"], what)
1327
+ check_prediction_profiles!(raw, subordinate_offset_models(raw))
1328
+ unless real?(raw["lat"]) && raw["lat"].between?(-90, 90)
1329
+ raise InvalidReleaseError, "#{what}: lat is not a number in [-90, 90]"
1330
+ end
1331
+ unless real?(raw["lon"]) && raw["lon"].between?(-180, 180)
1332
+ raise InvalidReleaseError, "#{what}: lon is not a number in [-180, 180]"
1333
+ end
1334
+ if raw["subordinate_offsets"]
1335
+ check_offset_metadata!(raw["subordinate_offsets"], "#{what}: subordinate_offsets")
1336
+ end
1337
+ Array(raw["validation"]).each { |v| check_types!(v, VALIDATION_TYPES, "#{what}: validation") }
1338
+ Array(raw["constant_sets"]).each { |cs| check_set!(cs, what) }
1339
+ end
1340
+
1341
+ def self.subordinate_offset_models(raw)
1342
+ sid = raw["station_id"]
1343
+ models = {}
1344
+ original = raw["subordinate_offsets"]
1345
+ if original
1346
+ check_historical_offsets!(original, sid)
1347
+ identity = SubordinateOffsets.routing_id(sid, original)
1348
+ models[identity] = original if identity
1349
+ end
1350
+ return models unless raw.key?("subordinate_offset_alternatives")
1351
+ alternatives = raw["subordinate_offset_alternatives"]
1352
+ unless alternatives.is_a?(Array) && !alternatives.empty?
1353
+ raise InvalidReleaseError, "#{sid}: subordinate_offset_alternatives must be a nonempty array"
1354
+ end
1355
+ set_ids = Array(raw["constant_sets"]).map { |cs| cs["set_id"] }
1356
+ alternatives.each do |wrapper|
1357
+ unless wrapper.is_a?(Hash) && wrapper.keys.sort == %w[offset_id offsets]
1358
+ raise InvalidReleaseError, "#{sid}: offset alternative requires exactly offset_id and offsets"
1359
+ end
1360
+ identity, offsets = wrapper.values_at("offset_id", "offsets")
1361
+ unless identity.is_a?(String) && !identity.empty? && !models.key?(identity) && !set_ids.include?(identity)
1362
+ raise InvalidReleaseError, "#{sid}: offset alternative identity is empty or duplicated"
1363
+ end
1364
+ check_historical_offsets!(offsets, sid)
1365
+ unless offsets.is_a?(Hash) && offsets["reference_station_id"].is_a?(String) && !offsets["reference_station_id"].empty? &&
1366
+ %w[R A].include?(offsets["height_adjusted_type"]) && (offsets.keys - OFFSET_TYPES.keys - ["datum"]).empty?
1367
+ raise InvalidReleaseError, "#{sid}: invalid offset alternative body"
1368
+ end
1369
+ check_offset_metadata!(offsets, "#{sid}: offset alternative #{identity}")
1370
+ models[identity] = offsets
1371
+ end
1372
+ models
1373
+ end
1374
+
1375
+ def self.check_prediction_profiles!(raw, models)
1376
+ return unless raw.key?("prediction_profiles")
1377
+ profiles = raw["prediction_profiles"]
1378
+ unless profiles.is_a?(Hash) && profiles.keys.sort == %w[observed-best official]
1379
+ raise InvalidReleaseError, "#{raw['station_id']}: invalid prediction_profiles"
1380
+ end
1381
+ set_ids = Array(raw["constant_sets"]).map { |cs| cs["set_id"] }
1382
+ profiles.each do |name, binding|
1383
+ unless binding.is_a?(Hash) && [%w[offset_id selection_status], %w[selection_status set_id]].include?((binding.keys - ["selection_evidence"]).sort)
1384
+ raise InvalidReleaseError, "#{name}: profile requires exactly one set_id or offset_id"
1385
+ end
1386
+ key = binding.key?("offset_id") ? "offset_id" : "set_id"
1387
+ identity = binding[key]
1388
+ unless identity.is_a?(String) && !identity.empty? && (key == "offset_id" ? models.key?(identity) : set_ids.include?(identity))
1389
+ raise InvalidReleaseError, "#{name}: #{key} does not resolve"
1390
+ end
1391
+ evidence = binding["selection_evidence"]
1392
+ if binding["selection_status"] == "measured"
1393
+ raise InvalidReleaseError, "#{name}: measured profile requires selection_evidence" if binding.key?("selection_evidence") && (!evidence.is_a?(String) || evidence.empty?)
1394
+ elsif binding["selection_status"] != "unmeasured" || !evidence.nil?
1395
+ raise InvalidReleaseError, "#{name}: invalid selection status or evidence"
1396
+ end
1397
+ if name == "observed-best" && key == "set_id" && identity != raw["recommended_set_id"]
1398
+ raise InvalidReleaseError, "observed-best set_id differs from recommended_set_id"
1399
+ end
1400
+ end
1401
+ end
1402
+
1403
+ def self.check_offset_metadata!(off, what)
1404
+ check_types!(off, OFFSET_TYPES.merge("datum" => :o), what)
1405
+ if off["datum"]
1406
+ datum = off["datum"]
1407
+ check_types!(datum, DATUM_TYPES.merge("basis" => :o, "zero" => :t, "zero_name" => :t, "chart_datum" => :t), what)
1408
+ raise InvalidReleaseError, "#{what}: datum.named has a value that is not a number" unless (datum["named"] || {}).values.all? { |value| real?(value) }
1409
+ (datum["basis"] || {}).each_value do |basis|
1410
+ raise InvalidReleaseError, "#{what}: datum.basis has a value that is not an object" unless type_ok?(basis, :o)
1411
+ check_types!(basis, { "kind" => :t, "method" => :t, "uncertainty_m" => :n, "flags" => :s }, what) if basis
1412
+ end
1413
+ end
1414
+ Array(off["qc_flags"]).each { |flag| check_qc_flag!(flag, what) }
1415
+ check_types!(off["fallback"], { "reason" => :t, "basis" => :t, "otc_finding" => :t, "preferred_set_id" => :t }, what) if off["fallback"]
1416
+ end
1417
+
1418
+ def self.check_qc_flag!(flag, what)
1419
+ check_types!(flag, QC_FLAG_TYPES, what)
1420
+ unless (flag["values"] || {}).values.all? { |value| value.nil? || real?(value) }
1421
+ raise InvalidReleaseError, "#{what}: a qc_flags value is not a number or null"
1422
+ end
1423
+ end
1424
+ private_class_method :check_qc_flag!
1425
+
1426
+ def self.check_set!(cs, station)
1427
+ raise InvalidReleaseError, "#{station}: a set has no set_id" unless cs["set_id"].is_a?(String)
1428
+ what = "#{station}: set #{cs['set_id']}"
1429
+ check_types!(cs, SET_TYPES, what)
1430
+ check_types!(cs["fallback"], {"reason" => :t, "basis" => :t, "otc_finding" => :t, "preferred_set_id" => :t}, what) if cs["fallback"]
1431
+ { "record_span" => SPAN_TYPES, "datum" => DATUM_TYPES, "time_base" => TIME_BASE_TYPES,
1432
+ "provenance" => PROVENANCE_TYPES }.each do |k, table|
1433
+ check_types!(cs[k], table, "#{what}: #{k}") if cs[k]
1434
+ end
1435
+ build = cs.dig("provenance", "build")
1436
+ if build.is_a?(Hash)
1437
+ check_types!(build, { "build_commit" => :t, "run_id" => :t, "tool_versions" => :o }, "#{what}: provenance.build")
1438
+ tools = build["tool_versions"]
1439
+ unless tools.nil? || tools.values.all?(String)
1440
+ raise InvalidReleaseError, "#{what}: provenance.build.tool_versions has a value that is not a string"
1441
+ end
1442
+ end
1443
+ names = Set.new
1444
+ Array(cs["constituents"]).each do |c|
1445
+ raise InvalidReleaseError, "#{what}: a constituent has no name" unless c["name"].is_a?(String)
1446
+ check_types!(c, CONSTITUENT_TYPES, "#{what}: constituents")
1447
+ # a name once per set
1448
+ raise InvalidReleaseError, "#{what}: constituent #{c['name']} appears twice" unless names.add?(c["name"])
1449
+ end
1450
+ Array(cs["dropped_constituents"]).each { |x| check_types!(x, DROPPED_TYPES, "#{what}: dropped_constituents") }
1451
+ Array(cs["qc_flags"]).each do |f|
1452
+ check_qc_flag!(f, "#{what}: qc_flags")
1453
+ end
1454
+ span = cs["record_span"]
1455
+ if span
1456
+ Util.time(span["start"])
1457
+ Util.time(span["end"])
1458
+ end
1459
+ named = (cs["datum"] || {})["named"] || {}
1460
+ raise InvalidReleaseError, "#{what}: datum.named has a value that is not a number" unless named.values.all? { |x| real?(x) }
1461
+ tb = cs["time_base"] || {}
1462
+ check_types!(tb["correction"], CORRECTION_TYPES, "#{what}: time_base.correction") if tb["correction"]
1463
+ Array(tb["evidence"]).each { |e| check_types!(e, EVIDENCE_TYPES, "#{what}: time_base.evidence") }
1464
+ end
1465
+
1466
+ def quantity_kind(q)
1467
+ case q
1468
+ when "water_level" then :tide
1469
+ when "current" then :current
1470
+ else :other
1471
+ end
1472
+ end
1473
+
1474
+ # The licences of a station's reference chain.
1475
+ # The walk follows reference_station_id through at most 16 links
1476
+ # (the kind rule). It takes the offsets licence of each
1477
+ # station on the path, and the licence of the first recommended set
1478
+ # it reaches, where it stops. A loop or a missing station ends the
1479
+ # walk: the load has checked the links.
1480
+ def chain_licences(e)
1481
+ out = []
1482
+ seen = Set[e.station_id]
1483
+ links = 0
1484
+ while e.type == :subordinate && (e.reference_id || e.offsets_licence_id)
1485
+ out << e.offsets_licence_id if e.offsets_licence_id
1486
+ break if links == MAX_LINKS
1487
+ ref = @by_id[e.reference_id]
1488
+ break if ref.nil? || seen.include?(ref.station_id)
1489
+ links += 1
1490
+ seen << ref.station_id
1491
+ if ref.rec_licence_id
1492
+ out << ref.rec_licence_id
1493
+ break
1494
+ end
1495
+ e = ref
1496
+ end
1497
+ out
1498
+ end
1499
+
1500
+ # A station's kind comes from its recommended set, or from its
1501
+ # reference station if it is subordinate with offsets only.
1502
+ def kind_of(e, seen)
1503
+ return e.kind if e.kind
1504
+ return nil if seen.size >= MAX_LINKS
1505
+ return nil unless e.type == :subordinate && e.reference_id
1506
+ ref = @by_id[e.reference_id]
1507
+ return nil if ref.nil? || seen.include?(ref.station_id)
1508
+ kind_of(ref, seen + [e.station_id])
1509
+ end
1510
+
1511
+ # Indexes a station's aliases. They map a system to a String id or an
1512
+ # Array of String ids, and a (system, id) pair names one station only
1513
+ # anything else is invalid_release.
1514
+ def index_aliases(sid, aliases)
1515
+ @aliases ||= Hash.new { |h, k| h[k] = {} }
1516
+ return if aliases.nil?
1517
+ raise InvalidReleaseError, "station #{sid}: aliases is not an object" unless aliases.is_a?(Hash)
1518
+ aliases.each do |system, ids|
1519
+ list = ids.is_a?(Array) ? ids : [ids]
1520
+ unless list.all?(String)
1521
+ raise InvalidReleaseError, "station #{sid}: alias #{system} must be a String id or a list of them"
1522
+ end
1523
+ list.each do |id|
1524
+ other = @aliases[system.to_s][id]
1525
+ raise InvalidReleaseError, "alias #{system} #{id} appears twice (#{other} and #{sid})" if other
1526
+ @aliases[system.to_s][id] = sid
1527
+ end
1528
+ end
1529
+ end
1530
+ end
1531
+ end