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,400 @@
1
+ require "fileutils"
2
+ require "digest"
3
+ require "zlib"
4
+ require "securerandom"
5
+
6
+ class OpenTideConstants
7
+ # Fetching and checking release files and
8
+ # OpenTideConstants#download. Internal.
9
+ class Downloader
10
+ # The start of one valid sha256sum row, on the raw bytes.
11
+ SHA256_ROW = /\A\s*\h{64}[ \t]+\*?\S/n.freeze
12
+
13
+ # GETs OTC_{D}.sha256 and checks it against the pointer entry, if any.
14
+ # Returns [{name => sha256}, bytes].
15
+ def self.fetch_sha256(client, d, entry, pointer_url)
16
+ name = "OTC_#{d}.sha256"
17
+ pf = entry && Array(entry["files"]).find { |f| f["name"] == name }
18
+ url = pf && pf["url"] ? client.send(:resolve, pointer_url, pf["url"]) : client.send(:base_url) + name
19
+ res = client.send(:http).get(url)
20
+ raise ReleaseNotFoundError, "release #{d} not found (#{url}: HTTP 404)" if res.status == 404
21
+ raise NetworkError.new("#{url}: HTTP #{res.status}", url: url, status: res.status) unless res.status == 200
22
+ bytes = res.body
23
+ # A 200 body with no "<sha256> <name>" row (a captive portal or a
24
+ # proxy page) is a network error, checked first.
25
+ unless bytes.each_line.any? { |l| l.b.match?(SHA256_ROW) }
26
+ raise NetworkError.new("#{url}: HTTP 200 with no \"<sha256> <name>\" row", url: url, status: 200)
27
+ end
28
+ # The file itself is checked against the pointer before it is parsed.
29
+ if pf && pf["sha256"] && pf["sha256"].downcase != res.sha256
30
+ raise ChecksumError.new("#{name} does not match the pointer", file: name, expected: pf["sha256"], actual: res.sha256)
31
+ end
32
+ rows = Reader.parse_sha256(bytes.dup.force_encoding(Encoding::UTF_8), name)
33
+ check_agreement(entry, name, rows) if entry
34
+ [rows, bytes]
35
+ end
36
+
37
+ # The pointer (or index) entry and OTC_{D}.sha256 must give the same
38
+ # SHA-256 for every file (compared without regard to case), and the
39
+ # same files.
40
+ def self.check_agreement(entry, sha_name, rows)
41
+ listed = Array(entry["files"]).reject { |f| f["name"] == sha_name }
42
+ listed.each do |f|
43
+ next if f["sha256"].nil?
44
+ got = rows[f["name"]]
45
+ next if got == f["sha256"].downcase
46
+ raise ChecksumError.new("the pointer and #{sha_name} disagree on #{f['name']}", file: f["name"],
47
+ expected: f["sha256"].downcase, actual: got)
48
+ end
49
+ return if listed.none? { |f| f["sha256"] }
50
+ extra = rows.keys - listed.map { |f| f["name"] }
51
+ return if extra.empty?
52
+ raise ChecksumError.new("#{sha_name} lists #{extra.first}, which the pointer does not", file: extra.first,
53
+ expected: nil, actual: rows[extra.first])
54
+ end
55
+
56
+ # Downloads url to a temporary file in dir and checks its size and
57
+ # SHA-256; then renames it to final (or leaves it at keep_tmp).
58
+ # Returns the size. A bad file is deleted.
59
+ # error_class: CacheError for the cache, FileError for the caller's
60
+ # folder: what a local write failure is.
61
+ def self.fetch_checked(client, url, dir, final, name, expected_sha, expected_size, keep_tmp: nil,
62
+ error_class: CacheError)
63
+ tmp = keep_tmp || Cache.tmp_path(dir)
64
+ begin
65
+ res = client.send(:http).get_to_file(url, tmp)
66
+ if res.status == 404
67
+ # The release exists (its .sha256 lists the file): a server inconsistency.
68
+ raise NetworkError.new("#{url}: HTTP 404 for a file that OTC_#{name[/\AOTC_([^.]+(?:\.[0-9]+)?)\./, 1]}.sha256 " \
69
+ "lists; it is missing on the server", url: url, status: 404)
70
+ elsif res.status != 200
71
+ raise NetworkError.new("#{url}: HTTP #{res.status}", url: url, status: res.status)
72
+ end
73
+ # Each failure says which check failed.
74
+ why = if expected_sha.nil?
75
+ "no expected SHA-256 (the .sha256 file has no row for it)"
76
+ elsif expected_size && res.size != expected_size
77
+ "size #{res.size}, expected #{expected_size}"
78
+ elsif res.sha256 != expected_sha
79
+ "SHA-256 #{res.sha256}, expected #{expected_sha}"
80
+ end
81
+ raise ChecksumError.new("#{name}: #{why}", file: final || File.join(dir, name), expected: expected_sha,
82
+ actual: res.sha256) if why
83
+ File.rename(tmp, final) if final
84
+ res.size
85
+ rescue Exception # rubocop:disable Lint/RescueException
86
+ FileUtils.rm_f(tmp)
87
+ raise
88
+ end
89
+ rescue SystemCallError, HTTP::SinkError => e
90
+ raise local_error(error_class, "cannot write #{final || tmp}: #{e.message}", final || tmp)
91
+ end
92
+
93
+ def self.local_error(error_class, msg, path)
94
+ error_class == FileError ? FileError.new(msg, path: path) : error_class.new(msg)
95
+ end
96
+
97
+ # Decompresses gz into a temporary file in dir, checks the SHA-256 of
98
+ # the result and renames it to final. Returns its size.
99
+ def self.gunzip_checked(gz, dir, final, name, expected_sha, error_class: CacheError)
100
+ tmp = Cache.tmp_path(dir)
101
+ digest = Digest::SHA256.new
102
+ size = 0
103
+ begin
104
+ File.open(tmp, "wb") do |out|
105
+ File.open(gz, "rb") do |zin|
106
+ # zcat reads every gzip member, not only the first.
107
+ Zlib::GzipReader.zcat(zin) do |chunk|
108
+ out.write(chunk)
109
+ digest << chunk
110
+ size += chunk.bytesize
111
+ end
112
+ end
113
+ out.flush
114
+ out.fsync
115
+ end
116
+ actual = digest.hexdigest
117
+ if expected_sha.nil? || actual != expected_sha
118
+ raise ChecksumError.new("#{name}: SHA-256 mismatch after decompression", file: final,
119
+ expected: expected_sha, actual: actual)
120
+ end
121
+ File.rename(tmp, final)
122
+ size
123
+ rescue Zlib::Error => e
124
+ FileUtils.rm_f(tmp)
125
+ raise ChecksumError.new("#{name}: bad gzip data (#{e.message})", file: gz, expected: expected_sha, actual: nil)
126
+ rescue SystemCallError, IOError => e
127
+ FileUtils.rm_f(tmp)
128
+ raise local_error(error_class, "cannot decompress #{gz} into #{final}: #{e.message}", final)
129
+ rescue Exception # rubocop:disable Lint/RescueException
130
+ FileUtils.rm_f(tmp)
131
+ raise
132
+ end
133
+ end
134
+
135
+ def initialize(client, release, to, formats, overwrite)
136
+ @client = client
137
+ @release = release
138
+ @to = to
139
+ @formats = formats
140
+ @overwrite = overwrite
141
+ end
142
+
143
+ def run
144
+ d, entry, pointer_url = resolve_release
145
+ cache = @client.send(:cache)
146
+ ver = cache.verified(d)
147
+ rows, sha_bytes = sha_rows(d, ver, entry, pointer_url)
148
+ names = []
149
+ names << "OTC_#{d}.json" if @formats.include?("json")
150
+ names << "OTC_#{d}.json.gz" if @formats.include?("json.gz")
151
+ if @formats.include?("jsonl")
152
+ names.concat(BGZF.declared?(rows, d) ? BGZF.names(d) : ["OTC_#{d}.jsonl"])
153
+ end
154
+ # OTC_{D}.meta.json is always written, whatever the formats.
155
+ names << "OTC_#{d}.meta.json"
156
+ names.uniq!
157
+ sha_name = "OTC_#{d}.sha256"
158
+ sha_digest = Digest::SHA256.hexdigest(sha_bytes)
159
+ names.each do |n|
160
+ next if rows[n]
161
+ # The eager data file is always published, so a .sha256 without its row is a bad list, as for an
162
+ # eager open.
163
+ raise ChecksumError.new("#{n} is not listed in #{sha_name}", file: n, expected: nil, actual: nil) if n == "OTC_#{d}.json"
164
+ # A format that the release does not publish.
165
+ raise ReleaseNotFoundError, "release #{d} does not publish #{n} (#{sha_name} does not list it)"
166
+ end
167
+
168
+ # Check every existing file before writing any file.
169
+ begin
170
+ FileUtils.mkdir_p(@to)
171
+ rescue SystemCallError => e
172
+ raise FileError.new("cannot create #{@to}: #{e.message}", path: @to)
173
+ end
174
+ todo = []
175
+ (names + [sha_name]).each do |n|
176
+ path = File.join(@to, n)
177
+ want = n == sha_name ? sha_digest : rows[n]
178
+ if File.exist?(path)
179
+ have = Release.sha256_file(path)
180
+ next if have == want
181
+ raise FileExistsError.new("#{path} exists with other content", path: path) unless @overwrite
182
+ end
183
+ todo << n
184
+ end
185
+
186
+ pointer_files = entry ? Array(entry["files"]).to_h { |f| [f["name"], f] } : {}
187
+ # Every file is made and checked as a temporary file in to first;
188
+ # only when all of them are there are they renamed into place, all
189
+ # or nothing, so a failure (offline, a network error, a
190
+ # bad checksum, a failed rename) leaves to as it was.
191
+ staged = [] # [temporary file, final path], in the order of todo
192
+ begin
193
+ todo.each do |n|
194
+ tmp = Cache.tmp_path(@to)
195
+ staged << [tmp, File.join(@to, n)]
196
+ fetch = lambda do
197
+ raise OfflineError, "offline and #{n} is not cached" if @client.send(:offline)
198
+ pf = pointer_files[n]
199
+ url = pf && pf["url"] ? @client.send(:resolve, pointer_url, pf["url"]) : @client.send(:base_url) + n
200
+ Downloader.fetch_checked(@client, url, @to, tmp, n, rows[n], pf && pf["size"], error_class: FileError)
201
+ end
202
+ if n == sha_name
203
+ write_bytes(tmp, sha_bytes)
204
+ elsif ver && cache.file_ok?(d, n, ver) && cached_sha_ok?(cache, d, n, rows[n])
205
+ from_cache(cache, File.join(cache.release_dir(d), n), fetch) { |src| copy_checked(src, tmp, n, rows[n]) }
206
+ elsif n.end_with?(".json") && !n.end_with?(".meta.json") && ver && cache.file_ok?(d, "#{n}.gz", ver)
207
+ from_cache(cache, File.join(cache.release_dir(d), "#{n}.gz"), fetch) { |src| gunzip_into(src, tmp, n, rows[n]) }
208
+ else
209
+ fetch.call
210
+ end
211
+ end
212
+ # OTC_{D}.sha256 is last in todo, so it goes into place last.
213
+ rename_all_in(staged)
214
+ ensure
215
+ staged.each { |tmp, _| FileUtils.rm_f(tmp) }
216
+ end
217
+ staged.map(&:last)
218
+ end
219
+
220
+ private
221
+
222
+ # Renames each [temporary file, final path] into place, all or nothing
223
+ # Each original that a new file replaces is
224
+ # first renamed aside to a .tmp-bak- name in to. If any rename fails,
225
+ # every original is restored and the new files renamed in are removed,
226
+ # so to is as it was: FileError. If a restore fails too, the error
227
+ # lists the paths that changed.
228
+ def rename_all_in(staged)
229
+ aside = {} # final path => its original, renamed aside
230
+ placed = [] # final paths a new file was renamed into
231
+ final = nil
232
+ begin
233
+ staged.each do |_, f|
234
+ final = f
235
+ next unless File.symlink?(f) || (File.exist?(f) && !File.directory?(f))
236
+ bak = File.join(File.dirname(f), ".tmp-bak-#{Process.pid}-#{SecureRandom.hex(6)}")
237
+ File.rename(f, bak)
238
+ aside[f] = bak
239
+ end
240
+ staged.each do |tmp, f|
241
+ final = f
242
+ File.rename(tmp, f)
243
+ placed << f
244
+ end
245
+ rescue SystemCallError => e
246
+ changed = restore(placed, aside)
247
+ msg = "cannot rename into #{final}: #{e.message}"
248
+ unless changed.empty?
249
+ msg += "; these paths changed and could not be restored: #{changed.join(', ')} " \
250
+ "(an original that is not back is in a .tmp-bak- file next to it)"
251
+ end
252
+ raise FileError.new(msg, path: final)
253
+ end
254
+ aside.each do |f, bak|
255
+ File.delete(bak)
256
+ rescue SystemCallError => e # the new file is in place; only the old copy is left over
257
+ @client.send(:log, :warn, "download: cannot remove #{bak} (the replaced #{f}): #{e.message}")
258
+ end
259
+ end
260
+
261
+ # Undoes rename_all_in after a failure. Returns the paths that could
262
+ # not be restored.
263
+ def restore(placed, aside)
264
+ changed = []
265
+ placed.reverse_each do |f|
266
+ if aside.key?(f)
267
+ File.rename(aside.delete(f), f)
268
+ else
269
+ File.delete(f)
270
+ end
271
+ rescue SystemCallError => e
272
+ @client.send(:log, :warn, "download: cannot restore #{f}: #{e.message}")
273
+ changed << f
274
+ end
275
+ aside.each do |f, bak|
276
+ next if changed.include?(f)
277
+ File.rename(bak, f)
278
+ rescue SystemCallError => e
279
+ @client.send(:log, :warn, "download: cannot restore #{f} from #{bak}: #{e.message}")
280
+ changed << f
281
+ end
282
+ changed
283
+ end
284
+
285
+ def resolve_release
286
+ if @release == :latest
287
+ if @client.send(:offline)
288
+ d = @client.send(:newest_cached, usable: false)
289
+ raise OfflineError, "offline and no readable release is cached" unless d
290
+ return [d, nil, nil]
291
+ end
292
+ # The newest release this SDK reads, as for opening latest.
293
+ begin
294
+ entry, url = @client.send(:resolve_latest)
295
+ rescue NetworkError => e
296
+ # on_network_error as when a client opens latest: use_cache writes the newest cached
297
+ # readable release; raise, or nothing usable cached,
298
+ # raises the network error.
299
+ d = @client.send(:on_network_error) == :use_cache ? @client.send(:newest_cached, usable: false) : nil
300
+ raise unless d
301
+ @client.send(:log, :warn, "#{e.message}; writing the cached release #{d}")
302
+ return [d, nil, nil]
303
+ end
304
+ d = entry["datestamp"]
305
+ raise InvalidReleaseError, "bad datestamp #{d.inspect} in the pointer" unless d.is_a?(String) && d.match?(DATESTAMP_RE)
306
+ return [d, entry, url]
307
+ end
308
+ [@release, nil, nil]
309
+ end
310
+
311
+ # The rows and bytes of OTC_{D}.sha256: the cached copy of a verified
312
+ # release when it can be trusted, else fetched.
313
+ def sha_rows(d, ver, entry, pointer_url)
314
+ path = File.join(@client.send(:cache).release_dir(d), "OTC_#{d}.sha256")
315
+ present = ver && File.file?(path)
316
+ rows = present ? cached_sha_rows(path, entry) : nil
317
+ return rows if rows
318
+ if @client.send(:offline)
319
+ why = present ? " with a usable #{File.basename(path)}" : ""
320
+ raise OfflineError, "offline and release #{d} is not cached#{why}"
321
+ end
322
+ Downloader.fetch_sha256(@client, d, entry, pointer_url)
323
+ end
324
+
325
+ # [rows, bytes] of a cached OTC_{D}.sha256, or nil when it cannot be
326
+ # trusted: it cannot be read, it does not parse or lists no file, the
327
+ # pointer lists the .sha256 with another digest, or its rows disagree
328
+ # with the pointer. The caller fetches it again.
329
+ def cached_sha_rows(path, entry)
330
+ name = File.basename(path)
331
+ bytes = File.binread(path)
332
+ rows = Reader.parse_sha256(bytes.dup.force_encoding(Encoding::UTF_8), name)
333
+ raise InvalidReleaseError, "#{name} lists no files" if rows.empty?
334
+ if entry
335
+ pf = Array(entry["files"]).find { |f| f["name"] == name }
336
+ if pf && pf["sha256"] && pf["sha256"].downcase != Digest::SHA256.hexdigest(bytes)
337
+ raise ChecksumError.new("#{name} does not match the pointer", file: name, expected: pf["sha256"], actual: nil)
338
+ end
339
+ Downloader.check_agreement(entry, name, rows)
340
+ end
341
+ [rows, bytes]
342
+ rescue SystemCallError, IOError, InvalidReleaseError, ChecksumError => e
343
+ @client.send(:log, :warn, "the cached #{name} cannot be used (#{e.message}); fetching it again")
344
+ nil
345
+ end
346
+
347
+ # Copies a file from the cache with the block. A cached copy that fails
348
+ # its check is deleted from the cache and
349
+ # the file is downloaded instead (fetch).
350
+ def from_cache(cache, src, fetch)
351
+ yield src
352
+ rescue ChecksumError => e
353
+ @client.send(:log, :warn, "#{e.message}; deleting the cached #{File.basename(src)} and downloading it again")
354
+ begin
355
+ cache.remove_file(src)
356
+ rescue CacheError => ce
357
+ # the download does not need the cached copy gone; it goes on
358
+ @client.send(:log, :warn, "#{ce.message}; downloading #{File.basename(src)} anyway")
359
+ end
360
+ fetch.call
361
+ end
362
+
363
+ def cached_sha_ok?(cache, d, n, sha)
364
+ row = cache.verified(d)&.dig("files", n)
365
+ row.is_a?(Hash) && row["sha256"] == sha
366
+ end
367
+
368
+ def write_bytes(path, bytes)
369
+ tmp = Cache.tmp_path(@to)
370
+ File.open(tmp, "wb") do |f|
371
+ f.write(bytes)
372
+ f.flush
373
+ f.fsync
374
+ end
375
+ File.rename(tmp, path)
376
+ rescue SystemCallError, IOError => e
377
+ FileUtils.rm_f(tmp)
378
+ raise FileError.new("cannot write #{path}: #{e.message}", path: path)
379
+ end
380
+
381
+ def copy_checked(src, dest, name, sha)
382
+ tmp = Cache.tmp_path(@to)
383
+ begin
384
+ FileUtils.cp(src, tmp)
385
+ File.open(tmp, "r+b", &:fsync) # Windows: fsync needs a handle open for writing
386
+ actual = Release.sha256_file(tmp)
387
+ raise ChecksumError.new("#{name}: SHA-256 mismatch", file: dest, expected: sha, actual: actual) if actual != sha
388
+ File.rename(tmp, dest)
389
+ rescue SystemCallError, IOError => e
390
+ raise FileError.new("cannot write #{dest}: #{e.message}", path: dest)
391
+ ensure
392
+ FileUtils.rm_f(tmp)
393
+ end
394
+ end
395
+
396
+ def gunzip_into(gz, dest, name, sha)
397
+ Downloader.gunzip_checked(gz, @to, dest, name, sha, error_class: FileError)
398
+ end
399
+ end
400
+ end
@@ -0,0 +1,210 @@
1
+ class OpenTideConstants
2
+ # The user and password of a URL never go into an error message or a log
3
+ # line: they are replaced by "***".
4
+ module Redact
5
+ # "scheme://" and then the authority up to its last "@". The authority
6
+ # ends at "/", "?", "#", white space or a quote.
7
+ USERINFO = %r{([A-Za-z][A-Za-z0-9+.\-]*://)[^/?#\s'"<>]*@}.freeze
8
+
9
+ module_function
10
+
11
+ # text with the userinfo of every URL in it redacted.
12
+ def text(text)
13
+ text.gsub(USERINFO, '\1***@')
14
+ end
15
+
16
+ # One URL (a proxy may have no scheme) with its userinfo redacted.
17
+ def url(url)
18
+ s = url.to_s
19
+ return text(s) if s.include?("://")
20
+
21
+ head, at, tail = s.rpartition("@")
22
+ at.empty? || head.include?("/") ? s : "***@#{tail}"
23
+ end
24
+ end
25
+ private_constant :Redact
26
+
27
+ # The base class of every SDK error. Every error has a stable
28
+ # string #code; every error class is a direct subclass of this one. A URL
29
+ # in the message never carries its user and password.
30
+ class Error < StandardError
31
+ CODE = "error".freeze
32
+
33
+ def initialize(message = nil)
34
+ super(message.is_a?(String) ? Redact.text(message) : message)
35
+ end
36
+
37
+ def code
38
+ self.class::CODE
39
+ end
40
+ end
41
+
42
+ class NetworkError < Error
43
+ CODE = "network".freeze
44
+ attr_reader :url, :status
45
+
46
+ def initialize(message = "network error", url: nil, status: nil)
47
+ super(message)
48
+ # Callers print the url too: it never carries the user and password.
49
+ @url = url.is_a?(String) ? Redact.url(url) : url
50
+ @status = status
51
+ end
52
+ end
53
+
54
+ class ReleaseNotFoundError < Error
55
+ CODE = "release_not_found".freeze
56
+ end
57
+
58
+ class OfflineError < Error
59
+ CODE = "offline_unavailable".freeze
60
+ end
61
+
62
+ class ChecksumError < Error
63
+ CODE = "checksum_mismatch".freeze
64
+ attr_reader :file, :expected, :actual
65
+
66
+ def initialize(message = "checksum mismatch", file: nil, expected: nil, actual: nil)
67
+ super(message)
68
+ @file = file
69
+ @expected = expected
70
+ @actual = actual
71
+ end
72
+ end
73
+
74
+ class UnsupportedFormatError < Error
75
+ CODE = "unsupported_format".freeze
76
+ end
77
+
78
+ # The release's release.min_reader_version is newer than SUPPORTED_FORMAT_VERSION.
79
+ class ReaderTooOldError < Error
80
+ CODE = "reader_too_old".freeze
81
+ end
82
+
83
+ class InvalidReleaseError < Error
84
+ CODE = "invalid_release".freeze
85
+ end
86
+
87
+ class StationNotFoundError < Error
88
+ CODE = "station_not_found".freeze
89
+ end
90
+
91
+ class StationRemovedError < Error
92
+ CODE = "station_removed".freeze
93
+ attr_reader :tombstone
94
+
95
+ def initialize(message = "station removed", tombstone: nil)
96
+ super(message)
97
+ @tombstone = tombstone
98
+ end
99
+ end
100
+
101
+ class PinnedReleaseError < Error
102
+ CODE = "pinned_release".freeze
103
+ end
104
+
105
+ # The cache cannot be written. #removed lists the datestamps that prune
106
+ # removed before the failure, newest first; it is empty for every other
107
+ # operation.
108
+ class CacheError < Error
109
+ CODE = "cache".freeze
110
+ attr_reader :removed
111
+
112
+ def initialize(message = "cache error", removed: [])
113
+ super(message)
114
+ @removed = removed.dup.freeze
115
+ end
116
+ end
117
+
118
+ class FileExistsError < Error
119
+ CODE = "file_exists".freeze
120
+ attr_reader :path
121
+
122
+ def initialize(message = "file exists", path: nil)
123
+ super(message)
124
+ @path = path
125
+ end
126
+ end
127
+
128
+ # A local file cannot be opened or read. The system error is #cause.
129
+ class FileError < Error
130
+ CODE = "io".freeze
131
+ attr_reader :path
132
+
133
+ def initialize(message = "file error", path: nil)
134
+ super(message)
135
+ @path = path
136
+ end
137
+ end
138
+
139
+ class UnsupportedError < Error
140
+ CODE = "unsupported".freeze
141
+ end
142
+ class InvalidArgumentError < Error
143
+ CODE = "invalid_argument".freeze
144
+ end
145
+ class NoConstantsError < Error
146
+ CODE = "no_constants".freeze
147
+ end
148
+ class QuantityMismatchError < Error
149
+ CODE = "quantity_mismatch".freeze
150
+ end
151
+ class UnsupportedConventionError < Error
152
+ CODE = "unsupported_convention".freeze
153
+ end
154
+ class NoAstroTableError < Error
155
+ CODE = "no_astro_table".freeze
156
+ end
157
+ class UnsupportedConstituentError < Error
158
+ CODE = "unsupported_constituent".freeze
159
+ attr_reader :constituent
160
+ def initialize(message = nil, constituent: nil)
161
+ super(message)
162
+ @constituent = constituent
163
+ end
164
+ end
165
+ class TimeOutOfRangeError < Error
166
+ CODE = "time_out_of_range".freeze
167
+ attr_reader :first_year, :last_year
168
+ def initialize(message = nil, first_year: nil, last_year: nil)
169
+ super(message)
170
+ @first_year = first_year
171
+ @last_year = last_year
172
+ end
173
+ end
174
+ class DatumUnavailableError < Error
175
+ CODE = "datum_unavailable".freeze
176
+ attr_reader :missing
177
+ def initialize(message = nil, missing: nil)
178
+ super(message)
179
+ @missing = missing
180
+ end
181
+ end
182
+ class BinNotFoundError < Error
183
+ CODE = "bin_not_found".freeze
184
+ end
185
+ class ExtremesOnlyError < Error
186
+ CODE = "extremes_only".freeze
187
+ end
188
+ class LocalTimeUnavailableError < Error
189
+ CODE = "local_time_unavailable".freeze
190
+ end
191
+ class UnknownTimeZoneError < Error
192
+ CODE = "unknown_time_zone".freeze
193
+ attr_reader :zone
194
+ def initialize(message = nil, zone: nil)
195
+ super(message)
196
+ @zone = zone
197
+ end
198
+ end
199
+ class ReferenceUnavailableError < Error
200
+ CODE = "reference_unavailable".freeze
201
+ attr_reader :reference_station_id
202
+ def initialize(message = nil, reference_station_id: nil)
203
+ super(message)
204
+ @reference_station_id = reference_station_id
205
+ end
206
+ end
207
+ class HistoricalOffsetsExcludedError < Error
208
+ CODE = "historical_offsets_excluded".freeze
209
+ end
210
+ end
@@ -0,0 +1,24 @@
1
+ require "json"
2
+
3
+ class OpenTideConstants
4
+ # Name normalisation for search. It uses the shared fold table
5
+ # (a copy of tests/name_fold.json embedded in the gem), not Ruby's own
6
+ # Unicode functions.
7
+ module Fold
8
+ TABLE_PATH = File.expand_path("name_fold.json", __dir__)
9
+ MAP = JSON.parse(File.read(TABLE_PATH, encoding: "UTF-8"))["map"]
10
+ .to_h { |k, v| [k.to_i(16), v.freeze] }.freeze
11
+
12
+ module_function
13
+
14
+ # Step 1, the table; step 2, each run of white space (U+0020 and the
15
+ # ASCII tab, line feed, vertical tab, form feed and carriage return
16
+ # that the table leaves) becomes one space, then only U+0020 is
17
+ # trimmed: a NUL, for one, stays.
18
+ def fold(name)
19
+ out = +""
20
+ name.each_char { |ch| out << (MAP[ch.ord] || ch) }
21
+ out.gsub(/[ \t\n\v\f\r]+/, " ").gsub(/\A +| +\z/, "")
22
+ end
23
+ end
24
+ end