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,559 @@
1
+ require "fileutils"
2
+ require "json"
3
+ require "securerandom"
4
+ require "socket"
5
+ require "time"
6
+ require_relative "cache_json"
7
+
8
+ class OpenTideConstants
9
+ # The on-disk cache shared by every SDK on one machine:
10
+ #
11
+ # <root>/v1/pointer/OTC_latest-f1.json (+ .etag), OTC_index.json (+ .etag)
12
+ # <root>/v1/releases/<D>/OTC_<D>.sha256, data files, .verified, .lock/
13
+ #
14
+ # Every write is a temporary file in the same directory, fsynced and then
15
+ # renamed into place. A release directory is trusted only when .verified
16
+ # is valid. The lock directory stops duplicate work and guards deletion.
17
+ class Cache
18
+ LOCK_POLL_S = 0.5
19
+ LOCK_STALE_S = 120
20
+ # How old the lock itself must be to be stale.
21
+ LOCK_STALE_AGE_S = 120
22
+ STARTED_AT_RE = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|\+00:00)\z/
23
+
24
+ # A stale lock that cannot be removed this many times is a cache error.
25
+ LOCK_REMOVE_ATTEMPTS = 3
26
+
27
+ # Windows: a release blocked by a waiter reading owner.json tries again
28
+ # this many times (an open file cannot be deleted there).
29
+ RELEASE_ATTEMPTS = 20
30
+ RELEASE_RETRY_S = 0.05
31
+
32
+ attr_reader :root
33
+
34
+ def self.encode_cache_json(cache_document)
35
+ CacheJSON.encode(cache_document).encode(Encoding::UTF_8)
36
+ end
37
+
38
+ def self.default_root
39
+ if (dir = ENV["OPENTIDECONSTANTS_CACHE_DIR"]) && !dir.empty?
40
+ return dir
41
+ end
42
+ if Gem.win_platform?
43
+ base = ENV["LOCALAPPDATA"]
44
+ base = File.join(home, "AppData", "Local") if base.nil? || base.empty?
45
+ File.join(base, "opentideconstants", "Cache")
46
+ elsif RUBY_PLATFORM.include?("darwin")
47
+ File.join(home, "Library", "Caches", "opentideconstants")
48
+ else
49
+ base = ENV["XDG_CACHE_HOME"]
50
+ base = File.join(home, ".cache") if base.nil? || base.empty?
51
+ File.join(base, "opentideconstants")
52
+ end
53
+ end
54
+
55
+ # The home directory for the default cache root, or CacheError when
56
+ # there is none that can be used.
57
+ def self.home
58
+ dir = Dir.home
59
+ raise ArgumentError, "it is #{dir.inspect}" unless dir.is_a?(String) && !dir.empty? && File.absolute_path?(dir)
60
+ dir
61
+ rescue ArgumentError => e
62
+ raise CacheError, "cannot find the home directory for the default cache (#{e.message}); " \
63
+ "pass cache_dir or set OPENTIDECONSTANTS_CACHE_DIR"
64
+ end
65
+
66
+ def self.datestamp_key(d)
67
+ date, counter = d.split(".", 2)
68
+ [date.to_i, (counter || "1").to_i]
69
+ end
70
+
71
+ # logger: where lock and cleanup problems that are not raised are
72
+ # logged. lock_stale_s, lock_stale_age_s and lock_poll_s are the
73
+ # lock times.
74
+ def initialize(root, logger: nil, lock_stale_s: LOCK_STALE_S, lock_poll_s: LOCK_POLL_S,
75
+ lock_stale_age_s: LOCK_STALE_AGE_S)
76
+ @root = File.expand_path(root)
77
+ @base = File.join(@root, CACHE_LAYOUT_VERSION)
78
+ @logger = logger
79
+ @lock_stale_s = lock_stale_s
80
+ @lock_poll_s = lock_poll_s
81
+ @lock_stale_age_s = lock_stale_age_s
82
+ end
83
+
84
+ def pointer_dir
85
+ File.join(@base, "pointer")
86
+ end
87
+
88
+ def releases_dir
89
+ File.join(@base, "releases")
90
+ end
91
+
92
+ def release_dir(datestamp)
93
+ File.join(releases_dir, datestamp)
94
+ end
95
+
96
+ # Creates a directory, or raises CacheError.
97
+ def ensure_dir(dir)
98
+ FileUtils.mkdir_p(dir)
99
+ dir
100
+ rescue SystemCallError, IOError => e
101
+ raise CacheError, "cannot create the cache directory #{dir}: #{e.message}"
102
+ end
103
+
104
+ # A temporary file name in dir.
105
+ def self.tmp_path(dir)
106
+ File.join(dir, ".tmp-#{Process.pid}-#{SecureRandom.hex(6)}")
107
+ end
108
+
109
+ # Writes bytes to path atomically.
110
+ def write_atomic(path, bytes)
111
+ dir = ensure_dir(File.dirname(path))
112
+ tmp = Cache.tmp_path(dir)
113
+ File.open(tmp, "wb") do |f|
114
+ f.write(bytes)
115
+ f.flush
116
+ f.fsync
117
+ end
118
+ File.rename(tmp, path)
119
+ rescue SystemCallError, IOError => e
120
+ FileUtils.rm_f(tmp) if tmp
121
+ raise CacheError, "cannot write #{path}: #{e.message}"
122
+ end
123
+
124
+ def rename_into_place(tmp, path)
125
+ File.rename(tmp, path)
126
+ rescue SystemCallError => e
127
+ FileUtils.rm_f(tmp)
128
+ raise CacheError, "cannot rename into #{path}: #{e.message}"
129
+ end
130
+
131
+ # ---- pointer files
132
+
133
+ # [body, etag] of a cached pointer or index file, or nil when it is not
134
+ # cached. A file that exists but cannot be read is cache, never absent
135
+ def read_pointer(name)
136
+ path = File.join(pointer_dir, name)
137
+ body = read_file(path)
138
+ return nil unless body
139
+ etag = read_file("#{path}.etag")
140
+ [body.force_encoding(Encoding::UTF_8), etag&.strip]
141
+ end
142
+
143
+ # The bytes of a cache file, nil when it is not there, CacheError when
144
+ # it cannot be read (cache, never absent).
145
+ def read_file(path)
146
+ File.binread(path)
147
+ rescue Errno::ENOENT, Errno::ENOTDIR
148
+ nil
149
+ rescue SystemCallError, IOError => e
150
+ raise CacheError, "cannot read #{path}: #{e.message}"
151
+ end
152
+
153
+ # Writes a pointer or index file and its ETag as a pair, under
154
+ # pointer/.lock. The old ETag goes first, so a reader
155
+ # between the steps sees a body with no ETag (and asks without one),
156
+ # never a body with another body's ETag.
157
+ def write_pointer(name, body, etag)
158
+ path = File.join(pointer_dir, name)
159
+ with_lock(pointer_dir) do
160
+ remove_file("#{path}.etag")
161
+ write_atomic(path, body)
162
+ write_atomic("#{path}.etag", etag) if etag
163
+ end
164
+ end
165
+
166
+ # Deletes a file if it is there; CacheError if it cannot.
167
+ def remove_file(path)
168
+ File.delete(path)
169
+ rescue Errno::ENOENT
170
+ nil
171
+ rescue SystemCallError => e
172
+ raise CacheError, "cannot remove #{path}: #{e.message}"
173
+ end
174
+
175
+ # ---- releases
176
+
177
+ # The parsed .verified of a release, or nil when the directory is not
178
+ # trusted: no .verified, or one that is not a JSON object whose files
179
+ # rows are objects with a 64-hex or null sha256, a string or null url and an integer
180
+ # size; a null or absent size makes it malformed.
181
+ # A size written as 1024.0 is the integer
182
+ # 1024. A .verified that cannot be read is cache.
183
+ def verified(datestamp)
184
+ text = read_file(File.join(release_dir(datestamp), ".verified"))
185
+ return nil unless text
186
+ doc = Reader.parse_json(text.force_encoding(Encoding::UTF_8))
187
+ return nil unless verified_json_value?(doc)
188
+ return nil unless doc.is_a?(Hash) && doc["files"].is_a?(Hash)
189
+ return nil unless doc["datestamp"].nil? || doc["datestamp"] == datestamp
190
+ return nil unless %w[format_version min_reader_version].all? do |key|
191
+ doc[key].nil? || (doc[key].is_a?(String) && doc[key].match?(/\A(0|[1-9]\d*)\.(0|[1-9]\d*)\z/))
192
+ end
193
+ return nil unless %w[zenodo_version_doi verified_at by].all? { |key| doc[key].nil? || doc[key].is_a?(String) }
194
+ doc["files"].each_value { |row| return nil unless verified_row?(row) }
195
+ doc["files"].each_value { |row| row["size"] = Reader.integral(row["size"]) }
196
+ doc
197
+ rescue InvalidReleaseError
198
+ nil
199
+ end
200
+
201
+ # The strict-JSON rules apply to unknown receipt extensions too.
202
+ # Count containers, including the root, and keep finite untyped integers.
203
+ def verified_json_value?(value, depth = 0)
204
+ return value.to_f.finite? if value.is_a?(Numeric)
205
+ children = value.is_a?(Hash) ? value.values : value.is_a?(Array) ? value : nil
206
+ return true unless children
207
+ return false if depth >= 64
208
+ children.all? { |child| verified_json_value?(child, depth + 1) }
209
+ end
210
+
211
+ def verified_row?(row)
212
+ return false unless row.is_a?(Hash)
213
+ size = Reader.integral(row["size"])
214
+ (row["sha256"].nil? || (row["sha256"].is_a?(String) && row["sha256"].match?(/\A[0-9a-fA-F]{64}\z/))) &&
215
+ (row["url"].nil? || row["url"].is_a?(String)) && size.is_a?(Integer) && size.between?(0, 2**53 - 1)
216
+ end
217
+
218
+ # True when name is in the release directory, listed in .verified and
219
+ # of the size .verified gives.
220
+ def file_ok?(datestamp, name, ver = verified(datestamp))
221
+ return false unless ver
222
+ row = ver["files"][name]
223
+ path = File.join(release_dir(datestamp), name)
224
+ return false unless row.is_a?(Hash) && row["sha256"].is_a?(String) && File.file?(path)
225
+ row["size"].nil? || File.size(path) == row["size"]
226
+ end
227
+
228
+ # The release-level values .verified keeps next to the files: what the
229
+ # pointer or index entry said (format_version, min_reader_version,
230
+ # zenodo_version_doi). A key that info leaves out keeps its old value.
231
+ # .verified also has the datestamp.
232
+ VERIFIED_INFO = %w[format_version min_reader_version zenodo_version_doi].freeze
233
+
234
+ # files: the rows of the files this open stored and verified. A row of
235
+ # the old .verified stays only while its file is in the release
236
+ # directory, and a row for OTC_<D>.sha256 never does;
237
+ # every SHA-256 is written in lowercase.
238
+ def write_verified(datestamp, files, info = {})
239
+ dir = release_dir(datestamp)
240
+ path = File.join(dir, ".verified")
241
+ prev = verified(datestamp)
242
+ sums = "OTC_#{datestamp}.sha256"
243
+ merged = (prev ? prev["files"] : {}).select do |name, row|
244
+ name != sums && row["sha256"].is_a?(String) && File.file?(File.join(dir, name))
245
+ end
246
+ merged = merged.transform_values do |row|
247
+ { "sha256" => row["sha256"].downcase, "size" => row["size"], "url" => row["url"] }
248
+ end
249
+ files.each do |name, row|
250
+ old = merged[name] || {}
251
+ merged[name] = { "sha256" => (row["sha256"] || old["sha256"])&.downcase, "size" => row["size"] || old["size"],
252
+ "url" => row["url"] || old["url"] }
253
+ end
254
+ doc = { "datestamp" => datestamp, "files" => merged.sort.to_h, "verified_at" => Time.now.utc.iso8601,
255
+ "by" => "opentideconstants-ruby/#{VERSION}" }
256
+ VERIFIED_INFO.each do |k|
257
+ doc[k] = info.key?(k) ? info[k] : prev&.dig(k)
258
+ end
259
+ write_atomic(path, Cache.encode_cache_json(doc))
260
+ end
261
+
262
+ # Stores the version DOI of a pointer or index entry in the .verified
263
+ # of a cached release, when it differs. Best effort. The
264
+ # read-modify-write runs under the release lock, taken without waiting
265
+ # while another process holds a young lock (a
266
+ # download writes .verified), the note is skipped.
267
+ def note_version_doi(datestamp, doi)
268
+ same = ->(v) { v.nil? || (v.key?("zenodo_version_doi") && v["zenodo_version_doi"] == doi) }
269
+ return if same.call(verified(datestamp))
270
+ dir = release_dir(datestamp)
271
+ taken = try_lock(dir) do
272
+ ver = verified(datestamp) # again, now under the lock
273
+ next if same.call(ver)
274
+ ver["zenodo_version_doi"] = doi
275
+ write_atomic(File.join(dir, ".verified"), Cache.encode_cache_json(ver))
276
+ end
277
+ log(:debug, "#{dir} is locked by another process; its version DOI is noted later") unless taken
278
+ rescue CacheError, FileError => e
279
+ log(:warn, "cannot note the version DOI of #{datestamp}: #{e.message}")
280
+ end
281
+
282
+ # Datestamps of trusted release directories, newest first.
283
+ def cached_releases
284
+ return [] unless File.directory?(releases_dir)
285
+ Dir.children(releases_dir)
286
+ .select { |d| d.match?(DATESTAMP_RE) && verified(d) }
287
+ .sort_by { |d| Cache.datestamp_key(d) }.reverse
288
+ rescue Errno::ENOENT, Errno::ENOTDIR
289
+ []
290
+ rescue SystemCallError => e
291
+ # an unreadable cache is not an empty one
292
+ raise CacheError, "cannot list #{releases_dir}: #{e.message}"
293
+ end
294
+
295
+ # Datestamp directories with no valid .verified: a download that failed
296
+ # or is still running. These never count toward prune's keep budget.
297
+ def partial_releases
298
+ return [] unless File.directory?(releases_dir)
299
+ Dir.children(releases_dir)
300
+ .select { |d| d.match?(DATESTAMP_RE) && File.directory?(release_dir(d)) && !verified(d) }
301
+ rescue Errno::ENOENT, Errno::ENOTDIR
302
+ []
303
+ rescue SystemCallError => e
304
+ raise CacheError, "cannot list #{releases_dir}: #{e.message}"
305
+ end
306
+
307
+ # Removes a release directory. It takes the release
308
+ # lock without waiting, so a release that another process is
309
+ # downloading into is left alone: then it returns false. .verified
310
+ # goes first, so a directory that cannot be removed in full is no
311
+ # longer trusted, and any failure is a CacheError. True when removed.
312
+ # Partial releases are judged under the lock after a marker re-read;
313
+ # their age uses the pre-take mtime, which taking the lock changes.
314
+ def remove_release(datestamp, partial: false)
315
+ dir = release_dir(datestamp)
316
+ return true unless File.directory?(dir)
317
+ if partial
318
+ candidate = File.lstat(dir)
319
+ return false unless candidate.directory?
320
+ mtime = candidate.mtime
321
+ same_directory = lambda do
322
+ current = File.lstat(dir)
323
+ current.directory? && current.dev == candidate.dev && current.ino == candidate.ino
324
+ end
325
+ end
326
+ return false if partial && Time.now - mtime <= 120
327
+ removed = false
328
+ return false if partial && !same_directory.call
329
+ taken = try_lock(dir) do
330
+ if partial
331
+ next unless same_directory.call
332
+ if verified(datestamp)
333
+ log(:info, "prune: #{datestamp} became verified; kept")
334
+ next
335
+ end
336
+ next unless Time.now - mtime > 120
337
+ end
338
+ next if partial && !same_directory.call
339
+ remove_file(File.join(dir, ".verified"))
340
+ Dir.children(dir).each do |name|
341
+ next if name == ".lock"
342
+ FileUtils.rm_r(File.join(dir, name))
343
+ end
344
+ removed = true
345
+ end
346
+ return false unless taken && removed
347
+ begin
348
+ Dir.rmdir(dir)
349
+ rescue Errno::ENOENT, Errno::ENOTEMPTY, Errno::EEXIST
350
+ nil # another process started a download into it after the lock was released
351
+ end
352
+ true
353
+ rescue SystemCallError => e
354
+ raise CacheError, "cannot remove #{dir}: #{e.message}"
355
+ end
356
+
357
+ # ---- the lock directory
358
+
359
+ # Runs the block while holding <dir>/.lock. Returns early (without the
360
+ # block) with :done when done.call becomes true while waiting. A lock
361
+ # is stale when this waiter has waited the stale time and the lock
362
+ # itself is at least lock_stale_age_s old; a stale lock is
363
+ # removed and taken, and the wait starts again. A stale lock that
364
+ # cannot be removed 3 times is a CacheError.
365
+ def with_lock(dir, done: -> { false })
366
+ ensure_dir(dir)
367
+ lock = File.join(dir, ".lock")
368
+ waited = 0.0
369
+ failures = 0
370
+ loop do
371
+ begin
372
+ Dir.mkdir(lock)
373
+ break
374
+ rescue Errno::EEXIST
375
+ return :done if done.call
376
+ if waited >= @lock_stale_s && lock_stale?(lock) # the age is read just before the removal
377
+ if remove_stale_lock(lock)
378
+ waited = 0.0
379
+ next
380
+ end
381
+ failures += 1
382
+ raise CacheError, "cannot remove the stale lock #{lock} after #{failures} attempts" if failures >= LOCK_REMOVE_ATTEMPTS
383
+ end
384
+ sleep(@lock_poll_s)
385
+ waited += @lock_poll_s
386
+ rescue SystemCallError => e
387
+ raise CacheError, "cannot take the lock #{lock}: #{e.message}"
388
+ end
389
+ end
390
+ hold(lock) { yield }
391
+ end
392
+
393
+ # Takes <dir>/.lock without waiting, runs the block and returns true;
394
+ # returns false (without the block) when another process holds a lock
395
+ # younger than lock_stale_age_s. An older lock is stale: it is removed
396
+ # and taken. A stale lock that
397
+ # cannot be removed is a CacheError.
398
+ def try_lock(dir)
399
+ lock = File.join(dir, ".lock")
400
+ attempt = 0
401
+ begin
402
+ Dir.mkdir(lock)
403
+ rescue Errno::EEXIST
404
+ return false if attempt.positive? || !lock_stale?(lock)
405
+ raise CacheError, "cannot remove the stale lock #{lock}" unless remove_stale_lock(lock)
406
+ attempt += 1
407
+ retry # once: a process that takes it now holds a young lock
408
+ rescue SystemCallError => e
409
+ raise CacheError, "cannot take the lock #{lock}: #{e.message}"
410
+ end
411
+ hold(lock) { yield }
412
+ true
413
+ end
414
+
415
+ # Seconds since the lock was taken: from
416
+ # owner.json started_at, or from the mtime of the lock directory when
417
+ # owner.json is missing or cannot be read. nil when the lock is gone
418
+ # or its age cannot be read: such a lock is never stale.
419
+ def lock_age(lock)
420
+ started = begin
421
+ owner = JSON.parse(File.read(File.join(lock, "owner.json")))
422
+ at = owner.is_a?(Hash) ? owner["started_at"] : nil
423
+ at.is_a?(String) && at.match?(STARTED_AT_RE) ? Time.iso8601(at) : nil
424
+ rescue JSON::ParserError, SystemCallError, IOError, ArgumentError, EncodingError
425
+ nil
426
+ end
427
+ Time.now - (started || File.mtime(lock))
428
+ rescue SystemCallError
429
+ nil
430
+ end
431
+
432
+ def lock_stale?(lock)
433
+ age = lock_age(lock)
434
+ !age.nil? && age >= @lock_stale_age_s
435
+ end
436
+
437
+ private
438
+
439
+ # Writes owner.json with a fresh token, runs the block, and releases
440
+ # the lock only while the token is still ours.
441
+ def hold(lock)
442
+ token = SecureRandom.hex(16)
443
+ owner_path = File.join(lock, "owner.json")
444
+ begin
445
+ owner = { "pid" => Process.pid, "host" => Socket.gethostname, "sdk" => "opentideconstants-ruby/#{VERSION}",
446
+ "started_at" => Time.now.utc.iso8601, "token" => token }
447
+ File.write(owner_path, JSON.generate(owner))
448
+ rescue SystemCallError, IOError => e
449
+ release_lock(lock, owner_path, nil)
450
+ raise CacheError, "cannot write #{owner_path}: #{e.message}"
451
+ end
452
+ mutex = Mutex.new
453
+ wake = ConditionVariable.new
454
+ stopped = false
455
+ heartbeat = nil
456
+ identity = nil
457
+ owned = lambda do
458
+ current = JSON.parse(File.read(owner_path))
459
+ stat = File.stat(lock)
460
+ current if current.is_a?(Hash) && current["token"] == token && stat.dev == identity.dev && stat.ino == identity.ino
461
+ end
462
+ begin
463
+ identity = File.stat(lock)
464
+ heartbeat = Thread.new do
465
+ loop do
466
+ break if mutex.synchronize { wake.wait(mutex, 30) unless stopped; stopped }
467
+ tmp = nil
468
+ begin
469
+ current = owned.call
470
+ unless current
471
+ log(:warn, "the lock #{lock} is no longer ours; stopping its heartbeat")
472
+ break
473
+ end
474
+ tmp = Cache.tmp_path(lock)
475
+ File.open(tmp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
476
+ file.write(JSON.generate(current.merge("started_at" => Time.now.utc.iso8601)))
477
+ file.flush
478
+ file.fsync
479
+ end
480
+ unless owned.call
481
+ log(:warn, "the lock #{lock} is no longer ours; stopping its heartbeat")
482
+ break
483
+ end
484
+ File.rename(tmp, owner_path)
485
+ unless owned.call
486
+ log(:warn, "the lock #{lock} is no longer ours; stopping its heartbeat")
487
+ break
488
+ end
489
+ now = Time.now
490
+ File.utime(now, now, lock)
491
+ rescue Errno::ENOENT, Errno::ENOTDIR
492
+ log(:warn, "the lock #{lock} is gone; stopping its heartbeat")
493
+ break
494
+ rescue JSON::ParserError, SystemCallError, IOError => e
495
+ log(:warn, "cannot refresh the lock #{lock}: #{e.message}")
496
+ ensure
497
+ FileUtils.rm_f(tmp) if tmp
498
+ end
499
+ end
500
+ end
501
+ yield
502
+ ensure
503
+ mutex.synchronize { stopped = true; wake.signal }
504
+ heartbeat&.join
505
+ release_lock(lock, owner_path, token)
506
+ end
507
+ end
508
+
509
+ # Deletes owner.json and the lock directory, unless another process
510
+ # has taken the lock as stale (its token differs). A failure is logged:
511
+ # the work is done, and a leftover lock only delays others.
512
+ def release_lock(lock, owner_path, token)
513
+ if token
514
+ current = begin
515
+ JSON.parse(File.read(owner_path))["token"]
516
+ rescue JSON::ParserError, SystemCallError, IOError, TypeError, NoMethodError
517
+ nil
518
+ end
519
+ if current != token
520
+ log(:warn, "the lock #{lock} is now held by another process; leaving it")
521
+ return
522
+ end
523
+ end
524
+ attempt = 0
525
+ begin
526
+ begin
527
+ File.delete(owner_path)
528
+ rescue Errno::ENOENT
529
+ nil
530
+ end
531
+ Dir.rmdir(lock)
532
+ rescue Errno::EACCES
533
+ # On Windows a waiter reading owner.json blocks the delete: try again, bounded.
534
+ attempt += 1
535
+ raise if !Gem.win_platform? || attempt >= RELEASE_ATTEMPTS
536
+ sleep(RELEASE_RETRY_S)
537
+ retry
538
+ end
539
+ rescue SystemCallError => e
540
+ log(:warn, "cannot release the lock #{lock}: #{e.message}")
541
+ end
542
+
543
+ # Removes a stale lock directory; false when it is still there.
544
+ def remove_stale_lock(lock)
545
+ log(:warn, "taking the stale lock #{lock}")
546
+ FileUtils.rm_r(lock)
547
+ true
548
+ rescue Errno::ENOENT
549
+ true
550
+ rescue SystemCallError => e
551
+ log(:warn, "cannot remove the stale lock #{lock}: #{e.message}")
552
+ !File.exist?(lock)
553
+ end
554
+
555
+ def log(level, msg)
556
+ @logger&.public_send(level, "opentideconstants: #{msg}")
557
+ end
558
+ end
559
+ end
@@ -0,0 +1,67 @@
1
+ class OpenTideConstants
2
+ # Encoding for generated cache documents only; downloaded bytes stay original.
3
+ module CacheJSON
4
+ def self.encode(value)
5
+ case value
6
+ when Hash
7
+ raise ArgumentError, "non-string cache JSON key" unless value.keys.all? { |key| key.is_a?(String) }
8
+ keys = value.keys.map { |key| [key, utf8(key)] }.sort_by { |_, key| key.codepoints }
9
+ "{" + keys.map { |original, key| encode(key) + ":" + encode(value.fetch(original)) }.join(",") + "}"
10
+ when Array
11
+ "[" + value.map { |item| encode(item) }.join(",") + "]"
12
+ when String
13
+ '"' + utf8(value).codepoints.map do |scalar|
14
+ if scalar < 32
15
+ "\\u#{scalar.to_s(16).rjust(4, '0')}"
16
+ elsif scalar == 34
17
+ '\\"'
18
+ elsif scalar == 92
19
+ '\\\\'
20
+ else
21
+ scalar.chr(Encoding::UTF_8)
22
+ end
23
+ end.join + '"'
24
+ when Integer then value.to_s
25
+ when Float then number(value)
26
+ when true then "true"
27
+ when false then "false"
28
+ when nil then "null"
29
+ else raise ArgumentError, "unsupported cache JSON value #{value.class}"
30
+ end
31
+ end
32
+
33
+ def self.utf8(value)
34
+ text = value.encode(Encoding::UTF_8)
35
+ raise ArgumentError, "invalid UTF8 or surrogate in cache JSON" unless text.valid_encoding?
36
+ text
37
+ end
38
+
39
+ def self.number(value)
40
+ raise ArgumentError, "nonfinite cache JSON number" unless value.finite?
41
+ return "0" if value.zero?
42
+ # Ruby's Float#to_s supplies the closest shortest roundtrip decimal.
43
+ # Change only notation and redundant zeroes, without rounding again.
44
+ mantissa, exponent = value.abs.to_s.split("e", 2)
45
+ whole, fraction = mantissa.split(".", 2)
46
+ digits = (whole + (fraction || "")).sub(/\A0+/, "")
47
+ scale = (exponent || "0").to_i - (fraction || "").length
48
+ while digits.end_with?("0")
49
+ digits = digits.chop
50
+ scale += 1
51
+ end
52
+ point = digits.length + scale
53
+ text = if value.abs >= 1e-6 && value.abs < 1e21
54
+ if point <= 0
55
+ "0." + "0" * -point + digits
56
+ elsif point >= digits.length
57
+ digits + "0" * (point - digits.length)
58
+ else
59
+ digits[0, point] + "." + digits[point..]
60
+ end
61
+ else
62
+ digits[0] + (digits.length > 1 ? "." + digits[1..] : "") + "e#{point - 1}"
63
+ end
64
+ value.negative? ? "-#{text}" : text
65
+ end
66
+ end
67
+ end