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,493 @@
1
+ require "json"
2
+ require "zlib"
3
+ require "digest"
4
+ require "stringio"
5
+ require_relative "bgzf"
6
+
7
+ class OpenTideConstants
8
+ # Reads release files from disk: .json, .json.gz, or .jsonl with its
9
+ # .meta.json sidecar.
10
+ module Reader
11
+ # OTC_<D>.<ext>, with <D> a valid datestamp (DATESTAMP_RE).
12
+ NAME_RE = /\A(OTC_([0-9]{8}(?:\.[2-9]|\.[1-9][0-9]{1,8})?))\.(jsonl\.gz|json\.gz|jsonl|json)\z/.freeze
13
+
14
+ module_function
15
+
16
+ # Splits "…/OTC_D.ext" into [prefix, datestamp, ext]; nil parts when the
17
+ # name does not follow the pattern.
18
+ def parse_name(path)
19
+ base = File.basename(path)
20
+ m = NAME_RE.match(base)
21
+ return [m[1], m[2], m[3]] if m
22
+ ext = base.end_with?(".json.gz") ? "json.gz" : File.extname(base).delete_prefix(".")
23
+ [base.delete_suffix(".#{ext}"), nil, ext]
24
+ end
25
+
26
+ # The files a load of this path reads (the data file, plus .meta.json for .jsonl).
27
+ def files_read(path)
28
+ prefix, _, ext = parse_name(path)
29
+ return [path, File.join(File.dirname(path), "#{prefix}.meta.json")] if ext == "jsonl"
30
+ [path]
31
+ end
32
+
33
+ # One sha256sum line: 64 hex digits, spaces or tabs, an optional "*",
34
+ # the name without trailing white space (the same grammar in
35
+ # every SDK). A blank line holds ASCII white space only.
36
+ SHA256_LINE = /\A(\h{64})[ \t]+\*?(.*?[^ \t\r\n\v\f])[ \t\r\n\v\f]*\z/.freeze
37
+ SHA256_BLANK = /\A[ \t\r\n\v\f]*\z/.freeze
38
+
39
+ # Parses "<sha256> <name>" lines into {name => sha256} (lower case).
40
+ # A line in any other form is invalid_release (source names the file).
41
+ # So is a file that is not UTF-8 or that names a file twice, so that
42
+ # row order never decides a check.
43
+ def parse_sha256(text, source = "the .sha256 file")
44
+ text = text.dup.force_encoding(Encoding::UTF_8)
45
+ raise InvalidReleaseError, "#{source} is not UTF-8" unless text.valid_encoding?
46
+ rows = {}
47
+ text.split("\n", -1).each.with_index(1) do |line, n|
48
+ next if line.match?(SHA256_BLANK)
49
+ m = SHA256_LINE.match(line)
50
+ raise InvalidReleaseError, "#{source} line #{n} is not \"<sha256> <name>\": #{line[0, 100].inspect}" unless m
51
+ raise InvalidReleaseError, "#{source} lists #{m[2]} twice (line #{n})" if rows.key?(m[2])
52
+ rows[m[2]] = m[1].downcase
53
+ end
54
+ rows
55
+ end
56
+
57
+ # Opens a local file given with file:.
58
+ def open_file(path, mode:, logger: nil, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback)
59
+ raise InvalidArgumentError, "file must be a String path" unless path.is_a?(String) && !path.empty?
60
+ path = File.expand_path(path)
61
+ prefix, d, ext = parse_name(path)
62
+ unless d
63
+ raise InvalidArgumentError, "file must be named OTC_<datestamp>.json, .json.gz or .jsonl, " \
64
+ "not #{File.basename(path).inspect}"
65
+ end
66
+ if ext == "jsonl.gz"
67
+ dir = File.dirname(path)
68
+ sha_path = File.join(dir, "#{prefix}.sha256")
69
+ raise ChecksumError.new("BGZF FILE requires #{prefix}.sha256", file: sha_path, expected: nil, actual: nil) unless File.file?(sha_path)
70
+ rows = parse_sha256(read_text(sha_path), File.basename(sha_path))
71
+ required = BGZF.names(d)
72
+ required.each { |name| raise FileError.new("no such file: #{name}", path: File.join(dir, name)) unless File.file?(File.join(dir, name)) }
73
+ checks = required.to_h { |name| [File.join(dir, name), rows[name]] }
74
+ files = rows.map do |name, sha|
75
+ local = File.join(dir, name)
76
+ FileInfo.new(name: name, url: nil, size: File.file?(local) ? File.size(local) : nil, sha256: sha)
77
+ end
78
+ return [BGZF.load(dir, d, rows: rows, mode: mode, files: files, checks: checks, logger: logger,
79
+ commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy), :file]
80
+ end
81
+ # A .json or .json.gz file has no lines to seek to: never load it
82
+ # eagerly in silence.
83
+ raise InvalidArgumentError, "stream mode needs .jsonl and .meta.json; choose mode: :eager for a JSON document" if mode == :stream && ext != "jsonl"
84
+ read = files_read(path)
85
+ read.each { |p| raise FileError.new("no such file: #{p}", path: p) unless File.file?(p) }
86
+ sha_path = File.join(File.dirname(path), "#{prefix}.sha256")
87
+ if File.file?(sha_path)
88
+ rows = parse_sha256(read_text(sha_path), File.basename(sha_path))
89
+ # Every release file the open reads needs a row, checked
90
+ # before any file is hashed; a
91
+ # .json.gz also needs the .json row that its decompressed
92
+ # bytes are checked against.
93
+ need_rows!(path, read, rows, File.basename(sha_path))
94
+ checks = read.to_h { |p| [p, rows[File.basename(p)]] }
95
+ files = rows.keys.sort.map do |name|
96
+ local = File.join(File.dirname(path), name)
97
+ FileInfo.new(name: name, url: nil, size: File.file?(local) ? File.size(local) : nil, sha256: rows[name])
98
+ end
99
+ json_sha256 = ext == "json.gz" ? rows["#{prefix}.json"] : nil
100
+ [load(path, mode: mode, files: files, checks: checks, verify: true, logger: logger,
101
+ commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy, json_sha256: json_sha256), :file]
102
+ else
103
+ files = read.map { |p| FileInfo.new(name: File.basename(p), url: nil, size: File.size(p), sha256: nil) }
104
+ [load(path, mode: mode, files: files, checks: {}, logger: logger, commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy),
105
+ :file_unverified]
106
+ end
107
+ end
108
+
109
+ # Raises ChecksumError "not listed" for the first release file that a
110
+ # local open of path (or verify on it) reads and that rows lacks: the
111
+ # files read, and for a .json.gz also the .json.
112
+ # The file named is the one missing.
113
+ def need_rows!(path, read, rows, sha_name)
114
+ names = read.map { |p| File.basename(p) }
115
+ names << File.basename(path).delete_suffix(".gz") if path.end_with?(".json.gz")
116
+ names.each do |name|
117
+ next if rows.key?(name)
118
+ raise ChecksumError.new("#{name} is not listed in #{sha_name}", file: File.join(File.dirname(path), name),
119
+ expected: nil, actual: nil)
120
+ end
121
+ end
122
+
123
+ # Raises ChecksumError unless the decompressed bytes of a .json.gz
124
+ # (gz_path) have the SHA-256 of its .json row.
125
+ def check_json_bytes!(gz_path, text, expected)
126
+ actual = Digest::SHA256.hexdigest(text.b)
127
+ return if actual == expected
128
+ json_path = gz_path.delete_suffix(".gz")
129
+ raise ChecksumError.new("#{File.basename(json_path)} (decompressed from #{File.basename(gz_path)}): SHA-256 mismatch",
130
+ file: json_path, expected: expected, actual: actual)
131
+ end
132
+
133
+ # Raises ChecksumError unless the SHA-256 of bytes (read from path) is expected.
134
+ def check_bytes!(path, bytes, expected)
135
+ actual = Digest::SHA256.hexdigest(bytes)
136
+ return if actual == expected
137
+ raise ChecksumError.new("#{File.basename(path)}: SHA-256 mismatch", file: path, expected: expected, actual: actual)
138
+ end
139
+
140
+ # Loads a release from a data file. With verify: true each file is
141
+ # hashed from the same bytes (or the same open file) that the load
142
+ # then reads, against checks {path => sha256}, so a file swapped
143
+ # after its hash is never used.
144
+ # logger: where a station with an unknown status is reported.
145
+ # commercial_only: the open option.
146
+ # json_sha256: for a .json.gz, the .json row that the decompressed
147
+ # bytes must match.
148
+ def load(path, mode:, files:, checks:, index: nil, index_rows: nil, zenodo_version_doi: nil, verify: false,
149
+ on_bad_index: nil, logger: nil, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback, json_sha256: nil, canonical: nil)
150
+ _, _, ext = parse_name(path)
151
+ expect = ->(p) { verify ? checks[p] : nil }
152
+ case ext
153
+ when "json"
154
+ doc = parse_json(read_text(path, expect.call(path)))
155
+ eager_from_doc(doc, files: files, checks: checks, zenodo_version_doi: zenodo_version_doi, logger: logger,
156
+ commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy)
157
+ when "json.gz"
158
+ text = gunzip(path, expect.call(path))
159
+ check_json_bytes!(path, text, json_sha256) if json_sha256
160
+ doc = parse_json(text)
161
+ eager_from_doc(doc, files: files, checks: checks, zenodo_version_doi: zenodo_version_doi, logger: logger,
162
+ commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy)
163
+ when "jsonl"
164
+ meta_path = files_read(path)[1]
165
+ meta = parse_json(read_text(meta_path, expect.call(meta_path)))
166
+ Release.check_format!(meta)
167
+ load_jsonl(path, meta, mode: mode, files: files, checks: checks, index: index, index_rows: index_rows,
168
+ zenodo_version_doi: zenodo_version_doi, expected_sha256: expect.call(path),
169
+ on_bad_index: on_bad_index, logger: logger, commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy, canonical: canonical)
170
+ else
171
+ raise InvalidArgumentError, "unknown release file type: #{path}"
172
+ end
173
+ end
174
+
175
+ def eager_from_doc(doc, files:, checks:, zenodo_version_doi: nil, logger: nil, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback)
176
+ Release.check_format!(doc)
177
+ stations = doc["stations"]
178
+ raise InvalidReleaseError, "stations missing" unless stations.is_a?(Array)
179
+ meta = doc.reject { |k, _| k == "stations" }
180
+ Release.new(meta: meta, stations: stations.map { |s| [s, nil, nil] }, mode: :eager,
181
+ files: files, checks: checks, zenodo_version_doi: zenodo_version_doi, logger: logger,
182
+ commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy)
183
+ end
184
+
185
+ # index: the entries of a fresh index-v1.json; the stations
186
+ # then come from it, and only the nonactive status lines are read. Otherwise
187
+ # every line is read, and index_rows (an Array, if given) gets the
188
+ # index entry of each line.
189
+ def load_jsonl(path, meta, mode:, files:, checks:, index: nil, index_rows: nil, zenodo_version_doi: nil,
190
+ expected_sha256: nil, on_bad_index: nil, logger: nil, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback, canonical: nil)
191
+ io = File.open(path, "rb")
192
+ if expected_sha256
193
+ digest = Digest::SHA256.new
194
+ while (chunk = io.read(1 << 16))
195
+ digest << chunk
196
+ end
197
+ io.rewind
198
+ actual = digest.hexdigest
199
+ unless actual == expected_sha256
200
+ io.close
201
+ raise ChecksumError.new("#{File.basename(path)}: SHA-256 mismatch", file: path, expected: expected_sha256,
202
+ actual: actual)
203
+ end
204
+ end
205
+ begin
206
+ index = index.call if index.respond_to?(:call)
207
+ rescue Exception
208
+ io.close
209
+ raise
210
+ end
211
+ lines = Enumerator.new do |y|
212
+ if index
213
+ profile = index_profile(index)
214
+ index.each { |e| y << [raw_from_index(e, io, profile: profile), e["offset"], e["length"], line_view(e, profile: profile)] }
215
+ else
216
+ pos = 0
217
+ io.each_line do |line|
218
+ body = line.end_with?("\n") ? line.delete_suffix("\n").delete_suffix("\r") : line
219
+ unless blank?(body)
220
+ raw = parse_json(body.force_encoding(Encoding::UTF_8))
221
+ if index_rows && raw.is_a?(Hash)
222
+ if canonical
223
+ types = OpenTideConstants.const_get(:CanonicalTypes, false)
224
+ index_rows << canonical.__send__(:project_station_index, station_source_row: raw,
225
+ source_byte_span: types::SourceByteSpan.new(offset_bytes: pos, length_bytes: body.bytesize),
226
+ projection_contract: types::ProjectionContract.new(
227
+ scalar_types: "Reader.index_entry native field types", models: "Reader.index_entry native projection",
228
+ subordinate_offsets: "complete source object", scope: "station source row", fallback: "complete source object"))
229
+ else
230
+ index_rows << index_entry(raw, pos, body.bytesize)
231
+ end
232
+ end
233
+ y << [raw, pos, body.bytesize]
234
+ end
235
+ pos += line.bytesize
236
+ end
237
+ end
238
+ end
239
+ begin
240
+ check_index_spans!(io, index) if index
241
+ rel = Release.new(meta: meta, stations: lines, mode: mode, files: files, checks: checks,
242
+ io: mode == :stream ? io : nil, zenodo_version_doi: zenodo_version_doi,
243
+ on_bad_index: index && on_bad_index, logger: logger, commercial_only: commercial_only, commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy)
244
+ ensure
245
+ io.close if mode != :stream || rel.nil?
246
+ end
247
+ rel
248
+ rescue SystemCallError, IOError => e
249
+ raise FileError.new("cannot read #{path}: #{e.message}", path: path)
250
+ end
251
+
252
+ # Check only gaps and boundaries; active source rows remain lazy.
253
+ def check_index_spans!(io, entries)
254
+ start = 0
255
+ entries.each do |entry|
256
+ offset = entry["offset"]
257
+ io.seek(offset - 1) if offset.positive?
258
+ if offset.positive? && io.read(1) != "\n"
259
+ raise InvalidReleaseError, "index-v1.json: an offset is not at a source line boundary"
260
+ end
261
+ io.seek(start)
262
+ left = offset - start
263
+ while left.positive?
264
+ bytes = io.read([left, 1 << 16].min)
265
+ raise InvalidReleaseError, "index-v1.json: a source row is missing from the index" unless bytes && blank?(bytes)
266
+ left -= bytes.bytesize
267
+ end
268
+ start = offset + entry["length"]
269
+ io.seek(start)
270
+ ending = io.read(2).to_s
271
+ unless ending.empty? || ending.start_with?("\n", "\r\n")
272
+ raise InvalidReleaseError, "index-v1.json: a length is not at a source line boundary"
273
+ end
274
+ end
275
+ io.seek(start)
276
+ while (bytes = io.read(1 << 16))
277
+ raise InvalidReleaseError, "index-v1.json: a source row is missing from the index" unless blank?(bytes)
278
+ end
279
+ io.rewind
280
+ end
281
+
282
+ SET_KEYS = %w[set_id source source_type quantity qc_status convention_id licence_id].freeze
283
+ ENTRY_STR = %w[name name_folded country type kind reference_station_id offsets_licence_id recommended_set_id].freeze
284
+
285
+ # The stream index entry of one line. "kind" is the
286
+ # station's own kind; the client sets the resolved kind.
287
+ def index_entry(raw, pos, len)
288
+ str = ->(h, k) { h.is_a?(Hash) && h[k].is_a?(String) ? h[k] : nil }
289
+ num = ->(k) { raw[k].is_a?(Numeric) ? raw[k] : nil }
290
+ off = raw["subordinate_offsets"].is_a?(Hash) ? raw["subordinate_offsets"] : {}
291
+ rec_id = str.call(raw, "recommended_set_id")
292
+ kind = nil
293
+ sets = (raw["constant_sets"].is_a?(Array) ? raw["constant_sets"] : []).map do |cs|
294
+ cs = {} unless cs.is_a?(Hash)
295
+ if !rec_id.nil? && cs["set_id"] == rec_id
296
+ kind = { "water_level" => "tide", "current" => "current" }.fetch(cs["quantity"], "other")
297
+ end
298
+ SET_KEYS.to_h { |k| [k, str.call(cs, k)] }.merge(
299
+ "fallback" => cs["fallback"], "current_bins" => Array(cs["current_bins"]).map { |b| b.is_a?(Hash) ? b["bin"] : b },
300
+ "source_record_id" => cs["source_record_id"], "source_version" => cs["source_version"], "datum" => cs["datum"],
301
+ "constituents" => Array(cs["constituents"]).filter_map { |c| c["name"] if c.is_a?(Hash) && c["name"].is_a?(String) }
302
+ )
303
+ end
304
+ name = str.call(raw, "name")
305
+ aliases = (raw["aliases"].is_a?(Hash) ? raw["aliases"] : {}).transform_values do |v|
306
+ v.is_a?(String) ? [v] : Array(v).grep(String)
307
+ end
308
+ # A line with no status is an active station to the load, so its entry says so (a nil
309
+ # status would make the index stale on every open).
310
+ status = raw["status"].is_a?(String) ? raw["status"] : "active"
311
+ { "offset" => pos, "length" => len, "station_id" => raw["station_id"], "status" => status,
312
+ "name" => name, "name_folded" => name && Fold.fold(name), "country" => str.call(raw, "country"),
313
+ "type" => str.call(raw, "type"), "lat" => num.call("lat"), "lon" => num.call("lon"), "kind" => kind,
314
+ "aliases" => aliases, "reference_station_id" => str.call(off, "reference_station_id"),
315
+ "offsets_licence_id" => str.call(off, "licence_id"), "recommended_set_id" => rec_id, "sets" => sets,
316
+ "subordinate_offsets" => raw["subordinate_offsets"], "current_offsets" => raw.fetch("current_offsets", []) }.merge(
317
+ raw.slice("subordinate_offset_alternatives", "prediction_profiles"))
318
+ end
319
+
320
+ # Every represented source field must match at the lazy read. Legacy
321
+ # optional fields retain their document-wide presence rules.
322
+ def line_view(e, profile: nil, presence: nil)
323
+ sets = e["sets"].is_a?(Array) ? e["sets"] : []
324
+ presence ||= {
325
+ "subordinate_offsets" => e.key?("subordinate_offsets"),
326
+ "current_offsets" => e.key?("current_offsets"),
327
+ "subordinate_offset_alternatives" => e.key?("subordinate_offset_alternatives"),
328
+ "prediction_profiles" => e.key?("prediction_profiles"),
329
+ "sets" => sets.map { |cs| %w[fallback current_bins source_record_id source_version datum].select { |k| cs.key?(k) } },
330
+ "base_offsets" => profile && profile["base_offsets"],
331
+ "base_current" => profile && profile["base_current"],
332
+ "base_fallback" => profile && profile["base_fallback"],
333
+ "current_profile" => profile && profile["current_profile"],
334
+ "current_keys" => Array(e["current_offsets"]).map(&:keys)
335
+ }
336
+ values = [e["station_id"], e["status"], e["name"], e["name_folded"], e["country"], e["type"], e["lat"], e["lon"], e["aliases"],
337
+ e["recommended_set_id"], e["reference_station_id"], e["offsets_licence_id"],
338
+ sets.each_with_index.map do |cs, i|
339
+ fields = SET_KEYS.map { |k| cs[k] } + [cs["constituents"]]
340
+ fields += Array(presence["sets"][i]).map { |k| cs[k] }
341
+ fields << cs["fallback"] unless presence["base_fallback"] || Array(presence["sets"][i]).include?("fallback")
342
+ fields
343
+ end]
344
+ values << e["subordinate_offsets"] unless !presence["subordinate_offsets"] && presence["base_offsets"]
345
+ if presence["current_offsets"] || !presence["base_current"]
346
+ rows = e.fetch("current_offsets", []) || []
347
+ keys = CURRENT_BASE + (presence["current_profile"] == "full" ? CURRENT_ADJUSTMENTS : [])
348
+ values << rows.each_with_index.map do |row, i|
349
+ represented = presence["current_keys"] && presence["current_keys"][i] || keys
350
+ CURRENT_BASE.to_h { |key| [key, row[key]] }.merge(row.slice(*(represented - CURRENT_BASE)))
351
+ end
352
+ end
353
+ %w[subordinate_offset_alternatives prediction_profiles].each { |key| values << e[key] if presence[key] }
354
+ Util.deep_freeze({ "presence" => presence, "kind" => e["kind"], "values" => values })
355
+ end
356
+
357
+ CURRENT_BASE = %w[bin reference_bin reference_station_id licence_id].freeze
358
+ CURRENT_ADJUSTMENTS = %w[time_adj_max_flood_min time_adj_max_ebb_min time_adj_slack_before_flood_min time_adj_slack_before_ebb_min flood_amp_ratio ebb_amp_ratio].freeze
359
+
360
+ # Presence is document-wide; the informational writer name grants no trust.
361
+ def index_profile(entries)
362
+ return nil unless entries.is_a?(Array) && entries.all? { |e| e.is_a?(Hash) && e["sets"].is_a?(Array) && e["sets"].all?(Hash) }
363
+ sets = entries.flat_map { |e| e["sets"] }
364
+ private_masks = sets.map { |cs| %w[source_record_id source_version datum].map { |k| cs.key?(k) } }.uniq
365
+ return nil unless private_masks.empty? || private_masks == [[false, false, false]] || private_masks == [[true, true, true]]
366
+ bins = sets.map { |cs| cs.key?("current_bins") }.uniq
367
+ return nil if bins.size > 1
368
+ own = entries.any? { |e| e.key?("subordinate_offsets") }
369
+ return nil if own && entries.any? { |e| !e.key?("subordinate_offsets") && (e["reference_station_id"] || e["offsets_licence_id"]) }
370
+ rows = entries.flat_map { |e| e.key?("current_offsets") && e["current_offsets"].is_a?(Array) ? e["current_offsets"] : [] }
371
+ return nil unless rows.all?(Hash)
372
+ profiles = rows.map { |row| CURRENT_ADJUSTMENTS.count { |k| row.key?(k) } }.uniq
373
+ return nil unless profiles.empty? || profiles == [0] || profiles == [CURRENT_ADJUSTMENTS.size]
374
+ { "base_offsets" => !own, "base_current" => !own && entries.none? { |e| e.key?("current_offsets") },
375
+ "base_fallback" => sets.none? { |cs| cs.key?("fallback") }, "current_profile" => profiles == [CURRENT_ADJUSTMENTS.size] ? "full" : "projected" }.freeze
376
+ end
377
+
378
+ def policy_uncached?(view, private_fields: false, offsets: true, alternatives: true)
379
+ return false unless view
380
+ p = view["presence"]
381
+ fields = private_fields ? %w[fallback current_bins source_record_id source_version datum] : %w[fallback current_bins]
382
+ (offsets && (!p["subordinate_offsets"] || (!p["current_offsets"] && p["base_current"]))) ||
383
+ (alternatives && !p["subordinate_offset_alternatives"]) ||
384
+ p["sets"].any? { |keys| fields.any? { |key| !keys.include?(key) } }
385
+ end
386
+
387
+ # v as an Integer when it is a JSON integer or a number with an
388
+ # integral value (12.0); any other value as it is.
389
+ def integral(v)
390
+ v.is_a?(Float) && v.finite? && v == v.floor ? v.to_i : v
391
+ end
392
+
393
+ # True when e has every key of an index entry with the right type.
394
+ def index_entry_ok?(e, profile: nil)
395
+ return false unless e.is_a?(Hash) && e["offset"].is_a?(Integer) && e["length"].is_a?(Integer)
396
+ return false unless e["station_id"].is_a?(String) && e["status"].is_a?(String)
397
+ return false unless ENTRY_STR.all? { |k| e.key?(k) && (e[k].nil? || e[k].is_a?(String)) }
398
+ return false unless e["name_folded"] == (e["name"] && Fold.fold(e["name"]))
399
+ return false unless %w[lat lon].all? { |k| e.key?(k) && (e[k].nil? || e[k].is_a?(Numeric)) }
400
+ return false unless e["aliases"].is_a?(Hash) && e["aliases"].values.all? { |v| v.is_a?(Array) && v.all?(String) }
401
+ return false if e.key?("subordinate_offsets") && !(e["subordinate_offsets"].nil? || e["subordinate_offsets"].is_a?(Hash))
402
+ if e.key?("current_offsets")
403
+ return false unless e["current_offsets"].is_a?(Array) && e["current_offsets"].all? do |row|
404
+ row.is_a?(Hash) && CURRENT_BASE.all? { |k| row.key?(k) } &&
405
+ %w[bin reference_bin].all? { |k| row[k].is_a?(Numeric) && row[k].finite? && row[k] == row[k].to_i && row[k].between?(1, 2**53 - 1) } &&
406
+ row["reference_station_id"].is_a?(String) && (row["licence_id"].nil? || row["licence_id"].is_a?(String)) &&
407
+ CURRENT_ADJUSTMENTS.all? { |k| !row.key?(k) || row[k].nil? || Release.real?(row[k]) }
408
+ end
409
+ end
410
+ return false unless e["sets"].is_a?(Array)
411
+ valid = e["sets"].all? do |cs|
412
+ cs.is_a?(Hash) && SET_KEYS.all? { |k| cs.key?(k) && (cs[k].nil? || cs[k].is_a?(String)) } &&
413
+ (!cs.key?("fallback") || cs["fallback"].nil? || cs["fallback"].is_a?(Hash)) &&
414
+ (!cs.key?("current_bins") || (cs["current_bins"].is_a?(Array) && cs["current_bins"].all? { |b| b.is_a?(Numeric) && b.finite? && b == b.to_i && b.between?(1, 2**53 - 1) })) &&
415
+ cs["constituents"].is_a?(Array) && cs["constituents"].all?(String)
416
+ end
417
+ return false unless valid
418
+ e["sets"].each { |cs| Release.check_set!(cs.reject { |k, _| k == "constituents" }, e["station_id"]) }
419
+ Release.check_historical_offsets!(e["subordinate_offsets"], e["station_id"])
420
+ Release.check_types!(e["subordinate_offsets"], Release::OFFSET_TYPES, e["station_id"]) if e["subordinate_offsets"]
421
+ shape = e.slice("station_id", "recommended_set_id", "subordinate_offsets", "subordinate_offset_alternatives", "prediction_profiles").merge("constant_sets" => e["sets"])
422
+ Release.check_prediction_profiles!(shape, Release.subordinate_offset_models(shape))
423
+ true
424
+ rescue InvalidReleaseError, TypeError, NoMethodError
425
+ false
426
+ end
427
+
428
+ # The station document a load needs, from an index entry. Nonactive
429
+ # rows are read to validate their status and tombstone metadata.
430
+ def raw_from_index(e, io, profile: nil)
431
+ if e["status"] != "active"
432
+ io.seek(e["offset"])
433
+ raw = parse_json(io.read(e["length"]).to_s.force_encoding(Encoding::UTF_8))
434
+ unless raw.is_a?(Hash) && raw["station_id"] == e["station_id"]
435
+ raise InvalidReleaseError, "index-v1.json: the line at #{e['offset']} is not #{e['station_id']}"
436
+ end
437
+ view = line_view(e, profile: profile)
438
+ unless line_view(index_entry(raw, e["offset"], e["length"]), presence: view["presence"]) == view
439
+ raise InvalidReleaseError, "index-v1.json: the line at #{e['offset']} does not give the entry of #{e['station_id']}"
440
+ end
441
+ return raw
442
+ end
443
+ raw = e.slice("station_id", "status", "name", "country", "type", "lat", "lon", "recommended_set_id", "aliases")
444
+ raw["constant_sets"] = e["sets"].map do |cs|
445
+ cs.reject { |k, _| k == "constituents" }.merge("constituents" => cs["constituents"].map { |n| { "name" => n } })
446
+ end
447
+ raw["subordinate_offsets"] = if e.key?("subordinate_offsets")
448
+ e["subordinate_offsets"]
449
+ elsif e["reference_station_id"] || e["offsets_licence_id"]
450
+ { "reference_station_id" => e["reference_station_id"], "licence_id" => e["offsets_licence_id"] }
451
+ end
452
+ raw["current_offsets"] = e["current_offsets"]
453
+ raw.merge!(e.slice("subordinate_offset_alternatives", "prediction_profiles"))
454
+ raw
455
+ end
456
+
457
+ # The bytes of path as UTF-8; checked against expected_sha256 when given.
458
+ def read_text(path, expected_sha256 = nil)
459
+ bytes = File.binread(path)
460
+ check_bytes!(path, bytes, expected_sha256) if expected_sha256
461
+ bytes.force_encoding(Encoding::UTF_8)
462
+ rescue SystemCallError, IOError => e
463
+ raise FileError.new("cannot read #{path}: #{e.message}", path: path)
464
+ end
465
+
466
+ # The decompressed text of a .gz file; the compressed bytes are
467
+ # checked against expected_sha256 when given.
468
+ def gunzip(path, expected_sha256 = nil)
469
+ bytes = File.binread(path)
470
+ check_bytes!(path, bytes, expected_sha256) if expected_sha256
471
+ # zcat reads every gzip member, not only the first.
472
+ Zlib::GzipReader.zcat(StringIO.new(bytes)).force_encoding(Encoding::UTF_8)
473
+ rescue Zlib::Error => e
474
+ raise InvalidReleaseError, "bad gzip file #{path}: #{e.message}"
475
+ rescue SystemCallError, IOError => e
476
+ raise FileError.new("cannot read #{path}: #{e.message}", path: path)
477
+ end
478
+
479
+ # True when a .jsonl line holds only ASCII whitespace: SP, HT, LF, VT, FF,
480
+ # CR. String#strip also drops NUL, which is not blank.
481
+ def blank?(line)
482
+ line.b.match?(/\A[ \t\n\v\f\r]*\z/n)
483
+ end
484
+
485
+ def parse_json(text)
486
+ raise InvalidReleaseError, "not valid UTF-8" unless text.valid_encoding?
487
+ Util.no_lone_surrogate!(text)
488
+ JSON.parse(text)
489
+ rescue JSON::ParserError, EncodingError => e
490
+ raise InvalidReleaseError, "not valid JSON: #{e.message[0, 200]}"
491
+ end
492
+ end
493
+ end