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.
- checksums.yaml +4 -4
- data/README.md +132 -3
- data/lib/opentideconstants/bgzf.rb +436 -0
- data/lib/opentideconstants/cache.rb +559 -0
- data/lib/opentideconstants/cache_json.rb +67 -0
- data/lib/opentideconstants/canonical.rb +756 -0
- data/lib/opentideconstants/canonical_types.rb +2537 -0
- data/lib/opentideconstants/client.rb +1135 -0
- data/lib/opentideconstants/downloader.rb +400 -0
- data/lib/opentideconstants/errors.rb +210 -0
- data/lib/opentideconstants/fold.rb +24 -0
- data/lib/opentideconstants/historical_fingerprint.rb +58 -0
- data/lib/opentideconstants/http.rb +483 -0
- data/lib/opentideconstants/models.rb +635 -0
- data/lib/opentideconstants/name_fold.json +949 -0
- data/lib/opentideconstants/predict/astro.rb +85 -0
- data/lib/opentideconstants/predict/daily-facts.json +1 -0
- data/lib/opentideconstants/predict/daily.rb +62 -0
- data/lib/opentideconstants/predict/engine.rb +506 -0
- data/lib/opentideconstants/predict/harmonic.rb +228 -0
- data/lib/opentideconstants/predict/local.rb +49 -0
- data/lib/opentideconstants/predict/results.rb +357 -0
- data/lib/opentideconstants/predict/retained.rb +487 -0
- data/lib/opentideconstants/predict.rb +192 -0
- data/lib/opentideconstants/reader.rb +493 -0
- data/lib/opentideconstants/release.rb +1531 -0
- data/lib/opentideconstants/version.rb +15 -0
- data/lib/opentideconstants.rb +24 -3
- data/supported-formats.json +5 -0
- metadata +37 -5
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: d6b1febdadfc05f7046e41dbd8a03b1928a112c93629e634e83565a8c31aeb3b
|
|
4
|
+
data.tar.gz: e38231591a543c5cf44ade706bdb0ae85557201ca01fe3f1e6cd9747f1c46d32
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 76a98ca2b403452f23cfe3a073ba459d10eab55707b342c9fdd576318be64ddfc2062974cbed2e00cd59eb1782f9725fad0133e5283a3d7b15b2c1cee485f6b4
|
|
7
|
+
data.tar.gz: 6f8c1a720d48f468225d9611bbe98114fc7e6718801d05b7703888e888b9570f920d7192f790d83f43ee5ce568f39b562a1f21d5c539b7a12f6a1a09b0bd2866
|
data/README.md
CHANGED
|
@@ -1,5 +1,134 @@
|
|
|
1
|
-
# opentideconstants
|
|
1
|
+
# opentideconstants (Ruby)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Ruby SDK for [OpenTideConstants](https://opentideconstants.org), an open dataset of tidal harmonic constants. It downloads a release, checks its SHA-256, caches it, and gives you the stations and their constants. Pure Ruby, standard library only, Ruby 3.3 or later.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
```
|
|
6
|
+
gem install opentideconstants
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Or add it to a Gemfile with `bundle add opentideconstants`. 0.1.0 is the first release. The earlier `0.0.0` gem only reserved the name.
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
require "opentideconstants"
|
|
13
|
+
|
|
14
|
+
otc = OpenTideConstants.new # the latest release, cached
|
|
15
|
+
st = otc.station_by_alias(:noaa, "9414290") # nil when no station has this id
|
|
16
|
+
m2 = st&.recommended_set&.constituent("M2") # a station can have no recommended set
|
|
17
|
+
puts "#{st.name}: M2 #{m2.amplitude_m} m, #{m2.phase_deg}°" if m2
|
|
18
|
+
puts otc.attribution([st]) if st # the attribution text for this station
|
|
19
|
+
otc.close
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Pin a release in production, and bump the pin in a reviewed change:
|
|
23
|
+
|
|
24
|
+
```ruby
|
|
25
|
+
otc = OpenTideConstants.new(release: "20261130")
|
|
26
|
+
otc.close
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Other ways to open:
|
|
30
|
+
|
|
31
|
+
| Option | Use |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `file: "OTC_20261130.jsonl.gz"` | a local BGZF `.jsonl.gz` bundle, or a legacy `.json`, `.json.gz` or `.jsonl` (+ `.meta.json`). Keep all bundle companions together. With a matching `OTC_{D}.sha256` manifest, `loaded_from` is `:file`. Legacy files without a manifest open as `:file_unverified`. Then `verify` fails with `checksum_mismatch`. |
|
|
34
|
+
| `offline: true` | never open a socket. Opening the latest release (the default) loads the newest cached release; `latest`, `check_for_update` and `update!` fail with `offline_unavailable` |
|
|
35
|
+
| `mode: :stream` | low memory: stations are read from the `.jsonl` file when a query needs them |
|
|
36
|
+
|
|
37
|
+
The other options:
|
|
38
|
+
|
|
39
|
+
| Option | Default | Use |
|
|
40
|
+
|---|---|---|
|
|
41
|
+
| `cache_dir:` | `OPENTIDECONSTANTS_CACHE_DIR`, else the user cache folder (`~/Library/Caches/opentideconstants`, `$XDG_CACHE_HOME/opentideconstants` or `~/.cache/opentideconstants`, `%LOCALAPPDATA%\opentideconstants\Cache`) | where downloaded releases are kept |
|
|
42
|
+
| `base_url:` | `OPENTIDECONSTANTS_BASE_URL`, else `https://data.opentideconstants.org/` | where releases are downloaded from (`http` or `https`) |
|
|
43
|
+
| `timeout:` | `nil`: 10 s to connect, 60 s to read | seconds for both, from 0.001 to 1000000 |
|
|
44
|
+
| `proxy:` | `nil`: the `http_proxy`/`https_proxy` and `no_proxy` variables | an `http://` proxy URL (Net::HTTP cannot use TLS to a proxy); a user and password in it are sent to the proxy |
|
|
45
|
+
| `ca_file:` | `nil`: `SSL_CERT_FILE`, else the system roots | a PEM file of the certificates to trust |
|
|
46
|
+
| `user_agent:` | `nil` | text added after the gem's own User-Agent |
|
|
47
|
+
| `on_network_error:` | `:use_cache` | when the network fails while the latest release is opened: `:use_cache` loads the newest cached release (`loaded_from` is `:cache_after_error`, `last_error` has the error); `:raise` raises it. `download` of the latest release and `releases` follow it too |
|
|
48
|
+
| `auto_update:` | `false` | `true` (a client on the latest release only): a query checks for a newer release when `update_interval` has passed, and switches to it; a failure goes to `last_error`, the query still answers |
|
|
49
|
+
| `update_interval:` | `86400` | seconds between the automatic checks |
|
|
50
|
+
| `logger:` | `nil` | any object with `debug`, `info`, `warn` and `error` (a `Logger`) |
|
|
51
|
+
| `verify_on_open:` | `false` | `true`: a cached release is hashed again, from the bytes that are read, and compared with its `.sha256` when it is loaded |
|
|
52
|
+
| `commercial_only:` | `false` | `true`: only the constant sets whose licence allows commercial use |
|
|
53
|
+
|
|
54
|
+
Environment variables: `OPENTIDECONSTANTS_CACHE_DIR` and `OPENTIDECONSTANTS_BASE_URL` are the defaults of `cache_dir` and `base_url` (an option wins over them). `OPENTIDECONSTANTS_OFFLINE` set to `1`, `true`, `yes` or `on` makes every client offline, also one opened with `offline: false`; if a client fails with `offline_unavailable` when you did not ask for offline, check this variable.
|
|
55
|
+
|
|
56
|
+
Queries: `station`, `require_station`, `tombstone`, `station_by_alias`, `stations(**filters)`, `each_station`, `search(name:)`, `bbox(south:, west:, north:, east:)`, `near(lat:, lon:, radius_km:)`, `nearest(lat:, lon:)`, `reference_station`, `subordinates_of`, `attribution`. Release management: `release`, `loaded_from`, `releases`, `latest`, `check_for_update`, `update!`, `download(to:)`, `verify`, `cached_releases`, `prune(keep:)`.
|
|
57
|
+
|
|
58
|
+
Use `bbox` on the client or a held release to find stations inside inclusive latitude and longitude bounds. Results use station-ID order and the usual discovery filters. `limit: nil` returns all matches; a positive integer limits the filtered results before station loading. When west exceeds east, the box crosses the date line.
|
|
59
|
+
|
|
60
|
+
Over the network, `bbox` and `near` read the station records they need in a few batched requests, and cache them:
|
|
61
|
+
|
|
62
|
+
```ruby
|
|
63
|
+
OpenTideConstants.open(release: "20261130") do |otc|
|
|
64
|
+
boston = otc.bbox(south: 42.2, west: -71.2, north: 42.5, east: -70.7, limit: 3)
|
|
65
|
+
pacific = otc.release.bbox(south: -25, west: 170, north: -10, east: -170)
|
|
66
|
+
end
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Every error that the SDK raises is a subclass of `OpenTideConstants::Error` and has a stable `code`. A lookup that finds nothing (`station`, `station_by_alias`, `tombstone`, `constituent`) returns `nil`; `require_station` raises instead. Ruby's own errors, such as an `ArgumentError` for an unknown keyword, are not SDK errors.
|
|
70
|
+
|
|
71
|
+
The gem reads format 1.0 (`OpenTideConstants::SUPPORTED_FORMAT_VERSION`). A pinned release or a file whose `min_reader_version` is newer fails with `reader_too_old`. The latest release skips such a release: opening it, `latest`, `check_for_update` and `update!` all use the newest release that the gem reads. `station.constant_sets` leaves out `no_constants` sets unless you pass `include_no_constants: true`. `release.citation` and `otc.attribution` give the exact text to cite.
|
|
72
|
+
|
|
73
|
+
Bundle a BGZF release with your app:
|
|
74
|
+
|
|
75
|
+
```ruby
|
|
76
|
+
OpenTideConstants.open(release: "20261130", mode: :stream) do |otc|
|
|
77
|
+
otc.download("20261130", to: "vendor/tides", formats: [:jsonl])
|
|
78
|
+
end
|
|
79
|
+
bundle = Dir.glob("vendor/tides/OTC_20261130.jsonl{,.gz}").first
|
|
80
|
+
otc = OpenTideConstants.new(file: bundle)
|
|
81
|
+
otc.close
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The `jsonl` selector requests the logical format. The release determines its physical files.
|
|
85
|
+
Keep the complete bundle together: `.jsonl.gz`, `.jsonl.gz.gzi`, `.index-v1.json.gz`,
|
|
86
|
+
`.station-index.json.gz`, `.meta.json` and `.sha256`, all with the same `OTC_20261130` prefix.
|
|
87
|
+
For a legacy JSONL release, open `vendor/tides/OTC_20261130.jsonl` with its matching `.meta.json` and `.sha256`.
|
|
88
|
+
The manifest lets the SDK check the bundle (`loaded_from` is `:file`).
|
|
89
|
+
`20261130` is the current release at the time of writing. Select a release available from your data endpoint.
|
|
90
|
+
|
|
91
|
+
`download` writes the complete bundle or none of it. It returns the paths it writes, except unchanged files already in the destination.
|
|
92
|
+
|
|
93
|
+
Run the public tests with `ruby -Iruby/lib ruby/test/test_unit.rb` from the repository root.
|
|
94
|
+
|
|
95
|
+
Native prediction uses `otc-predict-1`. Pass Ruby `Time` values. The SDK floors each instant to a whole UTC second.
|
|
96
|
+
|
|
97
|
+
```ruby
|
|
98
|
+
require "opentideconstants"
|
|
99
|
+
OpenTideConstants.open do |otc|
|
|
100
|
+
start = Time.utc(otc.release.datestamp[0, 4].to_i, 10, 11)
|
|
101
|
+
station = otc.station_by_alias(:noaa, "9414290")
|
|
102
|
+
heights = otc.heights(station, start: start, stop: start + 86400, step_s: 600)
|
|
103
|
+
events = otc.extremes(station, start: start, stop: start + 86400)
|
|
104
|
+
datums = otc.datums(station)
|
|
105
|
+
end
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`heights_at` preserves input order and repeated instants. `currents` returns velocities, speed and direction for the selected `bin_number`. `current_events` returns signed peaks and slack events. Results and their items are immutable.
|
|
109
|
+
|
|
110
|
+
Pass `units: "feet"` to `heights`, `heights_at` or `extremes` to read the selected value as `item.height`; the default is `"meters"`. Pass `units: "knots"` to `currents` or `current_events`; the default is `"m/s"`. Current points expose `velocity_major`, `velocity_minor` and `speed`, and current events expose `velocity`. Every prediction result and item exposes its `units` label, including after `to_local`.
|
|
111
|
+
|
|
112
|
+
Existing `height_m`, `velocity_major_ms`, `velocity_minor_ms`, `speed_ms`, `velocity_ms` and datum uncertainty fields always retain SI values. Conversion happens after prediction and datum/offset adjustments: feet divide the final metres by `0.3048`; knots divide the final metres per second by `(1852.0 / 3600.0)`. Other selector strings raise `InvalidArgumentError`.
|
|
113
|
+
|
|
114
|
+
If high and low offsets differ, the station provides extrema only. Curve calls raise `ExtremesOnlyError`. Subordinate current stations also provide events only.
|
|
115
|
+
|
|
116
|
+
For eligible NOAA subordinate stations, default `extremes` calls use the current NOAA offsets instead of the flagged FES fallback. Explicit `set_id`, `offset_id` and `profile` choices take precedence. Existing profile bindings also take precedence. Continuous height calls keep their selected harmonic model.
|
|
117
|
+
|
|
118
|
+
Use `otc.datum_sources(station, set_id: nil)` to inspect original source datum declarations and alternative prediction paths. The immutable `DatumSources` result contains `prediction_binding`, `declarations` and `alternative_paths`. Its `to_h` method returns their JSON projection. Each declaration preserves its original value, units, frame, epoch, restrictions and provenance. Station declarations remain separate when `set_id` filters set declarations.
|
|
119
|
+
|
|
120
|
+
A source chart declaration does not bind an unbound model zero or authorize prediction. Existing `datums` and `ranges` calls retain their behavior.
|
|
121
|
+
|
|
122
|
+
The default `historical_offsets_policy: :fallback` permits eligible NOAA2020 historical profiles when no better contemporary path exists. These results retain the retired source label, unestablished current validity and unverified current accuracy. Select an exact profile with `offset_id:`. Use `historical_offsets_policy: :exclude` to disable historical prediction and discovery. Query flags cannot override that policy.
|
|
123
|
+
|
|
124
|
+
Discovery excludes flagged and fallback sets by default. Use `include_flagged: true` or `include_fallback: true` for their respective sets. Lookup retains all station metadata. `station.source_records` preserves original source values and provenance in frozen `raw` objects. Original-source licences remain separate from published-set licences. `commercial_basis: :strict` is the default; `:as_published_upstream` selects the approved upstream interpretation.
|
|
125
|
+
|
|
126
|
+
Install `tzinfo` to use `result.to_local("America/New_York")`. Core prediction does not require it. Local conversion preserves the UTC instant and exposes `local_time`, `utc_offset_s` and `local_time_object`. Without the optional module, conversion raises `LocalTimeUnavailableError`.
|
|
127
|
+
|
|
128
|
+
Fixture unit tests run through `ruby -Iruby/lib ruby/test/test_unit.rb`. External-source tests run separately through `test_core_native.rb` and `test_noaa_historical.rb`. They require the source artifact paths in their environment. The full source dataset is not bundled in the gem.
|
|
129
|
+
|
|
130
|
+
## Data licences
|
|
131
|
+
|
|
132
|
+
The MIT licence covers the SDK code only. It does not cover the data. Each constant set carries its own licence, taken from the terms of its source. Read it from `set.licence`. Some sets are for non-commercial use only, for example CHS IWLS sets, many GESLA sets, UHSLC sets and sets fitted to Bureau of Meteorology prediction tables. Some sets are labelled licence-reading fallbacks, for example TICON-4 constants used "as published". Their licences say `commercial_use: true` but carry a restriction, and they do not meet the strict commercial criterion.
|
|
133
|
+
|
|
134
|
+
For commercial use, open the client with `commercial_only: true`. With the default `commercial_basis: :strict`, this excludes the non-commercial sets and the fallbacks; `:as_published_upstream` accepts the fallbacks. If you inspect licences yourself, check both `commercial_use` and `restriction`: a licence with `commercial_use: true` can still carry a restriction, as the TICON-4 "as published" sets do, and strict mode excludes them. Do not infer commercial use from the licence ID. The SDK does not grant new permissions. Show the text of `attribution` wherever you show the data. For each source's licence and the full policy, see https://opentideconstants.org/about/#licence.
|
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require "zlib"
|
|
3
|
+
require "digest"
|
|
4
|
+
require "stringio"
|
|
5
|
+
|
|
6
|
+
class OpenTideConstants
|
|
7
|
+
# Private logical JSONL source. Only complete bootstrap files and exact
|
|
8
|
+
# authenticated records enter the shared cache; a Range is never a file receipt.
|
|
9
|
+
module BGZF
|
|
10
|
+
HEX = /\A[0-9a-f]{64}\z/.freeze
|
|
11
|
+
# A record read over the network brings at most this many uncached
|
|
12
|
+
# records that the running query reads next (Source#hint), in
|
|
13
|
+
# multi-range requests; compressed spans closer than MERGE_GAP bytes
|
|
14
|
+
# are read as one range.
|
|
15
|
+
BATCH_RECORDS = 64
|
|
16
|
+
MERGE_GAP = 16 << 10
|
|
17
|
+
module_function
|
|
18
|
+
|
|
19
|
+
def names(d)
|
|
20
|
+
prefix = "OTC_#{d}"
|
|
21
|
+
["#{prefix}.jsonl.gz", "#{prefix}.jsonl.gz.gzi", "#{prefix}.station-index.json.gz",
|
|
22
|
+
"#{prefix}.index-v1.json.gz", "#{prefix}.meta.json"]
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def declared?(rows, d)
|
|
26
|
+
rows.key?("OTC_#{d}.station-index.json.gz") || rows.key?("OTC_#{d}.jsonl.gz.gzi")
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def parse_gzi(bytes, physical_size, logical_size)
|
|
30
|
+
raise InvalidReleaseError, "bad BGZF GZI byte count" unless bytes.bytesize >= 8
|
|
31
|
+
count = bytes.unpack1("Q<")
|
|
32
|
+
raise InvalidReleaseError, "bad BGZF GZI byte count" unless bytes.bytesize == 8 + count * 16
|
|
33
|
+
starts = [[0, 0]]
|
|
34
|
+
bytes.unpack("Q<*").drop(1).each_slice(2) do |physical, logical|
|
|
35
|
+
unless physical > starts.last[0] && logical > starts.last[1] && physical < physical_size && logical < logical_size
|
|
36
|
+
raise InvalidReleaseError, "BGZF GZI offsets are not increasing within the source"
|
|
37
|
+
end
|
|
38
|
+
starts << [physical, logical]
|
|
39
|
+
end
|
|
40
|
+
starts
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Discovery is immutable. Intern its repeated strings rather than
|
|
44
|
+
# retaining independent copies of each constituent and enum value.
|
|
45
|
+
def parse_bootstrap_json(text)
|
|
46
|
+
raise InvalidReleaseError, "not valid UTF-8" unless text.valid_encoding?
|
|
47
|
+
Util.no_lone_surrogate!(text)
|
|
48
|
+
JSON.parse(text, freeze: true)
|
|
49
|
+
rescue JSON::ParserError, EncodingError => error
|
|
50
|
+
raise InvalidReleaseError, "invalid BGZF bootstrap JSON: #{error.message[0, 200]}"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def inflate_span(bytes, row)
|
|
54
|
+
position = 0
|
|
55
|
+
count = 0
|
|
56
|
+
skip = row.fetch("bgzf_virtual_offset").to_i % 65_536
|
|
57
|
+
record = +"".b
|
|
58
|
+
while position < bytes.bytesize
|
|
59
|
+
header = bytes.byteslice(position, 12)
|
|
60
|
+
unless header && header.bytesize == 12 && header.byteslice(0, 4) == "\x1f\x8b\x08\x04".b
|
|
61
|
+
raise InvalidReleaseError, "invalid BGZF member header"
|
|
62
|
+
end
|
|
63
|
+
extra_size = header.byteslice(10, 2).unpack1("v")
|
|
64
|
+
extra = bytes.byteslice(position + 12, extra_size)
|
|
65
|
+
raise InvalidReleaseError, "truncated BGZF extra header" unless extra && extra.bytesize == extra_size
|
|
66
|
+
cursor = 0
|
|
67
|
+
member_size = nil
|
|
68
|
+
while cursor + 4 <= extra_size
|
|
69
|
+
tag = extra.byteslice(cursor, 2)
|
|
70
|
+
length = extra.byteslice(cursor + 2, 2).unpack1("v")
|
|
71
|
+
raise InvalidReleaseError, "bad BGZF extra field" if cursor + 4 + length > extra_size
|
|
72
|
+
if tag == "BC"
|
|
73
|
+
raise InvalidReleaseError, "duplicate or invalid BGZF BC field" if member_size || length != 2
|
|
74
|
+
member_size = extra.byteslice(cursor + 4, 2).unpack1("v") + 1
|
|
75
|
+
end
|
|
76
|
+
cursor += 4 + length
|
|
77
|
+
end
|
|
78
|
+
unless cursor == extra_size && member_size && member_size >= 12 + extra_size + 8 && member_size <= 65_536
|
|
79
|
+
raise InvalidReleaseError, "missing or invalid BGZF block size"
|
|
80
|
+
end
|
|
81
|
+
member = bytes.byteslice(position, member_size)
|
|
82
|
+
raise InvalidReleaseError, "truncated BGZF member" unless member && member.bytesize == member_size
|
|
83
|
+
gzip = Zlib::GzipReader.new(StringIO.new(member))
|
|
84
|
+
begin
|
|
85
|
+
decoded = gzip.read(65_537)
|
|
86
|
+
raise InvalidReleaseError, "BGZF member exceeds 65536 decoded bytes" if decoded.bytesize > 65_536
|
|
87
|
+
raise InvalidReleaseError, "BGZF member has trailing bytes" unless gzip.eof? && gzip.unused.to_s.empty?
|
|
88
|
+
ensure
|
|
89
|
+
gzip.close
|
|
90
|
+
end
|
|
91
|
+
if count.zero?
|
|
92
|
+
raise InvalidReleaseError, "BGZF virtual offset exceeds its block" if skip >= decoded.bytesize
|
|
93
|
+
decoded = decoded.byteslice(skip..)
|
|
94
|
+
end
|
|
95
|
+
remaining = row.fetch("length") - record.bytesize
|
|
96
|
+
record << decoded.byteslice(0, remaining) if remaining.positive?
|
|
97
|
+
count += 1
|
|
98
|
+
position += member_size
|
|
99
|
+
end
|
|
100
|
+
unless count == row.fetch("block_count") && record.bytesize == row.fetch("length")
|
|
101
|
+
raise InvalidReleaseError, "BGZF record span does not match the directory"
|
|
102
|
+
end
|
|
103
|
+
Reader.check_bytes!("BGZF station record", record, row.fetch("sha256"))
|
|
104
|
+
record
|
|
105
|
+
rescue Zlib::Error => error
|
|
106
|
+
raise ChecksumError.new("invalid BGZF member: #{error.message}", file: "BGZF station record", expected: row["sha256"], actual: nil)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def read_bootstrap(dir, d, rows, verified: nil, cache: nil, supplied_index: nil, index_presence: nil, on_index: nil)
|
|
110
|
+
archive, gzi_name, directory_name, discovery_name, meta_name = names(d)
|
|
111
|
+
names(d).each do |name|
|
|
112
|
+
unless rows[name].is_a?(String) && rows[name].match?(HEX)
|
|
113
|
+
raise ChecksumError.new("#{name} is not listed in OTC_#{d}.sha256", file: name, expected: nil, actual: nil)
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
names(d).drop(1).each do |name|
|
|
117
|
+
if verified && verified.dig("files", name, "sha256") != rows[name]
|
|
118
|
+
raise ChecksumError.new("#{name}: manifest differs from .verified", file: File.join(dir, name), expected: verified.dig("files", name, "sha256"), actual: rows[name])
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
directory = parse_bootstrap_json(Reader.gunzip(File.join(dir, directory_name), rows[directory_name]))
|
|
122
|
+
bgzf = directory.fetch("bgzf")
|
|
123
|
+
provenance = directory.fetch("provenance")
|
|
124
|
+
unless directory["index_version"] == 1 && directory["datestamp"] == d && directory["jsonl"] == "OTC_#{d}.jsonl" &&
|
|
125
|
+
directory["jsonl_sha256"].is_a?(String) && directory["jsonl_sha256"].match?(HEX) &&
|
|
126
|
+
directory["jsonl_size"].is_a?(Integer) && directory["jsonl_size"].positive? &&
|
|
127
|
+
bgzf["filename"] == archive && bgzf["gzi_filename"] == gzi_name &&
|
|
128
|
+
bgzf["sha256"] == rows[archive] && bgzf["gzi_sha256"] == rows[gzi_name] &&
|
|
129
|
+
bgzf["bytes"].is_a?(Integer) && bgzf["bytes"].positive? && provenance["metadata_sha256"] == rows[meta_name] &&
|
|
130
|
+
provenance["existing_index_sha256"].is_a?(String) && provenance["existing_index_sha256"].match?(HEX)
|
|
131
|
+
raise InvalidReleaseError, "BGZF directory identity does not match the release"
|
|
132
|
+
end
|
|
133
|
+
decoded = Reader.gunzip(File.join(dir, discovery_name), rows[discovery_name])
|
|
134
|
+
Reader.check_bytes!(File.join(dir, discovery_name), decoded, provenance["existing_index_sha256"])
|
|
135
|
+
index = parse_bootstrap_json(decoded)
|
|
136
|
+
if supplied_index && (supplied_index != index || index_presence && index_presence.any? { |key, present| index.key?(key) != present })
|
|
137
|
+
raise OpenTideConstants.const_get(:Canonical, false)::Unimplemented.new("authenticate_station_index mismatched authenticated BGZF index")
|
|
138
|
+
end
|
|
139
|
+
index_path = File.join(dir, "index-v1.json")
|
|
140
|
+
cache.write_atomic(index_path, decoded) if cache && (!File.file?(index_path) || Digest::SHA256.file(index_path).hexdigest != provenance["existing_index_sha256"])
|
|
141
|
+
decoded = nil
|
|
142
|
+
GC.start
|
|
143
|
+
meta = parse_bootstrap_json(Reader.read_text(File.join(dir, meta_name), rows[meta_name]))
|
|
144
|
+
Release.check_format!(meta)
|
|
145
|
+
raise InvalidReleaseError, "BGZF metadata datestamp differs" unless meta.dig("release", "datestamp") == d
|
|
146
|
+
gzi_bytes = File.binread(File.join(dir, gzi_name))
|
|
147
|
+
Reader.check_bytes!(gzi_name, gzi_bytes, rows[gzi_name])
|
|
148
|
+
starts = parse_gzi(gzi_bytes, bgzf["bytes"], directory["jsonl_size"])
|
|
149
|
+
validate_index!(index, directory, starts)
|
|
150
|
+
on_index&.call(index)
|
|
151
|
+
[directory, index, meta]
|
|
152
|
+
rescue KeyError, TypeError, NoMethodError => error
|
|
153
|
+
raise InvalidReleaseError, "invalid BGZF bootstrap: #{error.message}"
|
|
154
|
+
rescue SystemCallError, IOError => error
|
|
155
|
+
raise FileError.new("cannot read BGZF bootstrap: #{error.message}", path: dir)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def validate_index!(index, directory, starts)
|
|
159
|
+
unless %w[index_version datestamp jsonl jsonl_sha256 jsonl_size].all? { |key| index[key] == directory[key] } &&
|
|
160
|
+
(!index.key?("discovery_index_version") || index["discovery_index_version"] == 1) && index["stations"].is_a?(Array)
|
|
161
|
+
raise InvalidReleaseError, "BGZF discovery identity differs from directory"
|
|
162
|
+
end
|
|
163
|
+
profile = Reader.index_profile(index["stations"])
|
|
164
|
+
unless profile && index["stations"].all? { |entry| Reader.index_entry_ok?(entry, profile: profile) }
|
|
165
|
+
raise InvalidReleaseError, "invalid BGZF discovery entry"
|
|
166
|
+
end
|
|
167
|
+
entries = directory["stations"]
|
|
168
|
+
unless entries.is_a?(Array) && entries.length == index["stations"].length
|
|
169
|
+
raise InvalidReleaseError, "BGZF directory coverage differs from discovery"
|
|
170
|
+
end
|
|
171
|
+
by_id = {}
|
|
172
|
+
previous_end = -1
|
|
173
|
+
index["stations"].each do |entry|
|
|
174
|
+
offset, length = entry.values_at("offset", "length")
|
|
175
|
+
unless offset.is_a?(Integer) && length.is_a?(Integer) && length.positive? && offset > previous_end && offset + length <= directory["jsonl_size"] && !by_id.key?(entry["station_id"])
|
|
176
|
+
raise InvalidReleaseError, "invalid BGZF logical index span"
|
|
177
|
+
end
|
|
178
|
+
previous_end = offset + length
|
|
179
|
+
by_id[entry["station_id"]] = entry
|
|
180
|
+
end
|
|
181
|
+
seen = {}
|
|
182
|
+
entries.each do |row|
|
|
183
|
+
entry = row.is_a?(Hash) && by_id[row["station_id"]]
|
|
184
|
+
unless entry && !seen[row["station_id"]] && %w[offset length].all? { |key| row[key] == entry[key] } && row["sha256"].is_a?(String) && row["sha256"].match?(HEX) &&
|
|
185
|
+
%w[compressed_offset compressed_length block_count].all? { |key| row[key].is_a?(Integer) } && row["compressed_length"].positive? && row["block_count"].positive? &&
|
|
186
|
+
row["bgzf_virtual_offset"].is_a?(String) && row["bgzf_virtual_offset"].match?(/\A(?:0|[1-9][0-9]*)\z/)
|
|
187
|
+
raise InvalidReleaseError, "invalid BGZF station directory row"
|
|
188
|
+
end
|
|
189
|
+
first = starts.bsearch_index { |pair| pair[1] > row["offset"] }
|
|
190
|
+
first = first ? first - 1 : starts.length - 1
|
|
191
|
+
last = starts.bsearch_index { |pair| pair[1] >= row["offset"] + row["length"] } || starts.length
|
|
192
|
+
# GZI omits the terminal EOF member. The authenticated final
|
|
193
|
+
# row ends at the last data member, before that EOF marker.
|
|
194
|
+
finish = last < starts.length ? starts[last][0] : row["compressed_offset"] + row["compressed_length"]
|
|
195
|
+
virtual = starts[first][0] * 65_536 + row["offset"] - starts[first][1]
|
|
196
|
+
unless row["compressed_offset"] == starts[first][0] && row["compressed_length"] == finish - starts[first][0] &&
|
|
197
|
+
finish <= directory["bgzf"]["bytes"] && row["block_count"] == last - first &&
|
|
198
|
+
row["bgzf_virtual_offset"].to_i == virtual && virtual <= (2**64 - 1)
|
|
199
|
+
raise InvalidReleaseError, "BGZF station span disagrees with GZI"
|
|
200
|
+
end
|
|
201
|
+
seen[row["station_id"]] = true
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def load(dir, d, rows:, mode:, files:, checks:, cache: nil, http: nil, url: nil, offline: true, verified: nil,
|
|
206
|
+
zenodo_version_doi: nil, logger: nil, commercial_only: false, commercial_basis: :strict, historical_offsets_policy: :fallback,
|
|
207
|
+
supplied_index: nil, index_presence: nil, on_index: nil, canonical: nil, bootstrap: nil)
|
|
208
|
+
if bootstrap
|
|
209
|
+
# One acquisition hands off exactly its authenticated documents.
|
|
210
|
+
# Clear the caller's handoff so consumed index rows can be freed.
|
|
211
|
+
directory, index, meta, admitted_rows = bootstrap
|
|
212
|
+
bootstrap.clear
|
|
213
|
+
unless admitted_rows == rows && names(d).drop(1).all? { |name| verified&.dig("files", name, "sha256") == rows[name] }
|
|
214
|
+
raise InvalidReleaseError, "BGZF acquisition handoff differs from current receipt"
|
|
215
|
+
end
|
|
216
|
+
else
|
|
217
|
+
directory, index, meta = read_bootstrap(dir, d, rows, verified: verified, cache: cache,
|
|
218
|
+
supplied_index: supplied_index, index_presence: index_presence, on_index: on_index)
|
|
219
|
+
end
|
|
220
|
+
source = Source.new(dir, directory, index, rows, cache: cache, http: http, url: url, offline: offline, verified: verified)
|
|
221
|
+
profile = Reader.index_profile(index["stations"])
|
|
222
|
+
entries = index["stations"].dup
|
|
223
|
+
# The source and Release share comparison views. Retaining the
|
|
224
|
+
# decoded index hashes as well would keep a second discovery graph.
|
|
225
|
+
index = directory = nil
|
|
226
|
+
stations = Enumerator.new do |yielded|
|
|
227
|
+
entries.each_index do |position|
|
|
228
|
+
entry = entries[position]
|
|
229
|
+
entries[position] = nil
|
|
230
|
+
view = source.bind_entry(entry)
|
|
231
|
+
raw = if mode == :eager
|
|
232
|
+
source.seek(entry["offset"])
|
|
233
|
+
Reader.parse_json(source.read(entry["length"]).force_encoding(Encoding::UTF_8))
|
|
234
|
+
else
|
|
235
|
+
Reader.raw_from_index(entry, source, profile: profile)
|
|
236
|
+
end
|
|
237
|
+
yielded << [raw, entry["offset"], entry["length"], view]
|
|
238
|
+
GC.start if (position + 1) % 1024 == 0
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
release = Release.new(meta: meta, stations: stations, mode: mode, files: files, checks: checks, io: mode == :stream ? source : nil,
|
|
242
|
+
zenodo_version_doi: zenodo_version_doi, logger: logger, commercial_only: commercial_only,
|
|
243
|
+
commercial_basis: commercial_basis, historical_offsets_policy: historical_offsets_policy)
|
|
244
|
+
release
|
|
245
|
+
ensure
|
|
246
|
+
source&.close if mode != :stream || release.nil?
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
class Source
|
|
250
|
+
attr_reader :path
|
|
251
|
+
|
|
252
|
+
def initialize(dir, directory, index, rows, cache:, http:, url:, offline:, verified:)
|
|
253
|
+
@dir, @cache, @http, @url, @offline = dir, cache, http, url, offline
|
|
254
|
+
@path = File.join(dir, directory["bgzf"]["filename"])
|
|
255
|
+
@total = directory["bgzf"]["bytes"]
|
|
256
|
+
@rows = directory["stations"].to_h { |row| [row["offset"], row] }
|
|
257
|
+
@views = {}
|
|
258
|
+
@profile = Reader.index_profile(index["stations"])
|
|
259
|
+
@closed = false
|
|
260
|
+
@position = 0
|
|
261
|
+
@hint_key = :"opentideconstants_hint_#{object_id}"
|
|
262
|
+
archive_name = File.basename(@path)
|
|
263
|
+
if File.file?(@path) && (!verified || verified.dig("files", archive_name, "sha256") == rows[archive_name])
|
|
264
|
+
@file = File.open(@path, "rb")
|
|
265
|
+
digest = Digest::SHA256.new
|
|
266
|
+
while (chunk = @file.read(1 << 16))
|
|
267
|
+
digest << chunk
|
|
268
|
+
end
|
|
269
|
+
unless @file.size == @total && digest.hexdigest == rows[archive_name]
|
|
270
|
+
raise ChecksumError.new("BGZF archive SHA-256 mismatch", file: @path, expected: rows[archive_name], actual: digest.hexdigest)
|
|
271
|
+
end
|
|
272
|
+
@file.rewind
|
|
273
|
+
end
|
|
274
|
+
rescue Exception
|
|
275
|
+
@file&.close
|
|
276
|
+
raise
|
|
277
|
+
end
|
|
278
|
+
|
|
279
|
+
def seek(position)
|
|
280
|
+
@position = position
|
|
281
|
+
0
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
# One query's hint: the record offsets it reads, in order, and how
|
|
285
|
+
# many records one batch may hold.
|
|
286
|
+
Hint = Struct.new(:offsets, :at, :window, :cursor)
|
|
287
|
+
|
|
288
|
+
# The record offsets that the calling thread's query reads, in
|
|
289
|
+
# order; [] when it is done. A network read of one of them also
|
|
290
|
+
# reads up to window - 1 uncached ones after it, so a discovery
|
|
291
|
+
# query needs few requests. Returns the hint, whose window the
|
|
292
|
+
# query narrows as it finds stations, or nil.
|
|
293
|
+
def hint(offsets, window = BATCH_RECORDS)
|
|
294
|
+
offsets = offsets.select { |o| @rows.key?(o) }
|
|
295
|
+
at = {}
|
|
296
|
+
offsets.each_with_index { |o, i| at[o] ||= i }
|
|
297
|
+
Thread.current[@hint_key] = offsets.empty? ? nil : Hint.new(offsets, at, window, 0)
|
|
298
|
+
end
|
|
299
|
+
|
|
300
|
+
def bind_entry(entry)
|
|
301
|
+
@views[entry["offset"]] = Reader.line_view(entry, profile: @profile)
|
|
302
|
+
end
|
|
303
|
+
|
|
304
|
+
def fileno
|
|
305
|
+
@file&.fileno
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
def closed?
|
|
309
|
+
@closed
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
def close
|
|
313
|
+
@closed = true
|
|
314
|
+
@file&.close unless @file&.closed?
|
|
315
|
+
end
|
|
316
|
+
|
|
317
|
+
def read(length)
|
|
318
|
+
raise FileError.new("the release is closed", path: @path) if @closed
|
|
319
|
+
row = @rows[@position]
|
|
320
|
+
raise InvalidReleaseError, "BGZF read is not an indexed record" unless row && row["length"] == length
|
|
321
|
+
record_path = record_path(row)
|
|
322
|
+
cached = cached_record(record_path, row)
|
|
323
|
+
return cached if cached
|
|
324
|
+
if @cache
|
|
325
|
+
result = nil
|
|
326
|
+
@cache.with_lock(@dir) do
|
|
327
|
+
result = cached_record(record_path, row) || acquire_record(row)
|
|
328
|
+
@cache.write_atomic(record_path, result) unless File.file?(record_path)
|
|
329
|
+
end
|
|
330
|
+
result
|
|
331
|
+
else
|
|
332
|
+
acquire_record(row)
|
|
333
|
+
end
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
def cached_record(path, row)
|
|
337
|
+
return nil unless File.file?(path)
|
|
338
|
+
record = File.binread(path)
|
|
339
|
+
validate_record(record, row)
|
|
340
|
+
rescue ChecksumError
|
|
341
|
+
raise if @offline
|
|
342
|
+
@cache ? @cache.remove_file(path) : File.delete(path)
|
|
343
|
+
nil
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
def acquire_record(row)
|
|
347
|
+
bytes = if @file
|
|
348
|
+
@file.seek(row["compressed_offset"])
|
|
349
|
+
@file.read(row["compressed_length"])
|
|
350
|
+
else
|
|
351
|
+
raise OfflineError, "offline and station #{row['station_id']} is not cached" if @offline || !@http
|
|
352
|
+
fetch(row)
|
|
353
|
+
end
|
|
354
|
+
validate_record(BGZF.inflate_span(bytes, row), row)
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
def record_path(row)
|
|
358
|
+
File.join(@dir, "station-records", "#{row['sha256']}.json")
|
|
359
|
+
end
|
|
360
|
+
|
|
361
|
+
# The uncached hinted rows after row (or after the last hinted
|
|
362
|
+
# read), at most window - 1 of them.
|
|
363
|
+
def following(row)
|
|
364
|
+
hint = Thread.current[@hint_key]
|
|
365
|
+
return [] unless hint
|
|
366
|
+
at = hint.at[row["offset"]]
|
|
367
|
+
at ? hint.cursor = at : at = hint.cursor
|
|
368
|
+
out = []
|
|
369
|
+
seen = { row["offset"] => true }
|
|
370
|
+
hint.offsets.drop(at).each do |offset|
|
|
371
|
+
break if out.size + 1 >= hint.window
|
|
372
|
+
next if seen[offset]
|
|
373
|
+
seen[offset] = true
|
|
374
|
+
other = @rows[offset]
|
|
375
|
+
out << other unless File.file?(record_path(other))
|
|
376
|
+
end
|
|
377
|
+
out
|
|
378
|
+
end
|
|
379
|
+
|
|
380
|
+
# The compressed span of row. The uncached hinted records after it
|
|
381
|
+
# come in the same requests; each is checked as a single read is
|
|
382
|
+
# and cached. One that fails its check is not cached: the read
|
|
383
|
+
# that needs it fetches it again and raises.
|
|
384
|
+
def fetch(row)
|
|
385
|
+
batch = @cache ? [row] + following(row) : [row]
|
|
386
|
+
return @http.get_range(@url, row["compressed_offset"], row["compressed_length"], @total) if batch.size == 1
|
|
387
|
+
merged = []
|
|
388
|
+
batch.sort_by { |r| r["compressed_offset"] }.each do |r|
|
|
389
|
+
start = r["compressed_offset"]
|
|
390
|
+
finish = start + r["compressed_length"]
|
|
391
|
+
if merged.any? && start <= merged.last[1] + MERGE_GAP
|
|
392
|
+
merged.last[1] = [merged.last[1], finish].max
|
|
393
|
+
else
|
|
394
|
+
merged << [start, finish]
|
|
395
|
+
end
|
|
396
|
+
end
|
|
397
|
+
got = @http.get_ranges(@url, merged.map { |a, b| [a, b - a] }, @total)
|
|
398
|
+
span = lambda do |r|
|
|
399
|
+
a = merged.reverse_each.find { |m| m[0] <= r["compressed_offset"] }[0]
|
|
400
|
+
got.fetch(a).byteslice(r["compressed_offset"] - a, r["compressed_length"])
|
|
401
|
+
end
|
|
402
|
+
batch.drop(1).each do |other|
|
|
403
|
+
record = begin
|
|
404
|
+
validate_record(BGZF.inflate_span(span.call(other), other), other)
|
|
405
|
+
rescue ChecksumError, InvalidReleaseError
|
|
406
|
+
next
|
|
407
|
+
end
|
|
408
|
+
path = record_path(other)
|
|
409
|
+
@cache.write_atomic(path, record) unless File.file?(path)
|
|
410
|
+
end
|
|
411
|
+
span.call(row)
|
|
412
|
+
end
|
|
413
|
+
|
|
414
|
+
def validate_record(record, row)
|
|
415
|
+
unless record.bytesize == row["length"]
|
|
416
|
+
raise ChecksumError.new("BGZF station record length differs", file: row["station_id"], expected: row["sha256"], actual: Digest::SHA256.hexdigest(record))
|
|
417
|
+
end
|
|
418
|
+
Reader.check_bytes!(row["station_id"], record, row["sha256"])
|
|
419
|
+
raw = Reader.parse_json(record.dup.force_encoding(Encoding::UTF_8))
|
|
420
|
+
view = @views.fetch(row["offset"])
|
|
421
|
+
summary = raw.is_a?(Hash) && Reader.index_entry(raw, row["offset"], row["length"])
|
|
422
|
+
if summary && summary["kind"].nil? && raw["type"] == "subordinate" && summary["reference_station_id"]
|
|
423
|
+
# Release validates the reference-derived kind at admission
|
|
424
|
+
# and resolves it again when comparing the complete line.
|
|
425
|
+
summary["kind"] = view["kind"]
|
|
426
|
+
end
|
|
427
|
+
unless summary && raw["station_id"] == row["station_id"] &&
|
|
428
|
+
Reader.line_view(summary, presence: view["presence"]) == view
|
|
429
|
+
raise InvalidReleaseError, "BGZF source record differs from discovery index"
|
|
430
|
+
end
|
|
431
|
+
record
|
|
432
|
+
end
|
|
433
|
+
end
|
|
434
|
+
end
|
|
435
|
+
private_constant :BGZF
|
|
436
|
+
end
|