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
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
require "digest"
|
|
2
|
+
|
|
3
|
+
class OpenTideConstants
|
|
4
|
+
# Internal fingerprint of the source-bound, fixed historical fields.
|
|
5
|
+
module HistoricalFingerprint
|
|
6
|
+
DOMAIN = "OTC-HISTORICAL-FIXED-V1\0".b.freeze
|
|
7
|
+
ANCHORS = {
|
|
8
|
+
"noaa-2020-atlantic-table2-2513" => "b1e50c3627bc23655796779d408e5e6a64118ad067c8a1b7aaf3bac4aadcd160",
|
|
9
|
+
"noaa-2020-pacific-table2-517" => "d852f7cc264fd813be51c05fabf7d1981b2db4965a3648da94c0a2dedc5ec185"
|
|
10
|
+
}.freeze
|
|
11
|
+
TOP = %w[offset_id source source_type source_version source_record_id qc_status reference_station_id height_adjusted_type time_offset_high_min time_offset_low_min height_offset_high height_offset_low datum].freeze
|
|
12
|
+
VINTAGE = %w[publication_year source_lifecycle current_validity current_accuracy removal_events].freeze
|
|
13
|
+
PROVENANCE = %w[source_manifest_sha256 book annual_table_row printed_page pdf_page raw_row_text].freeze
|
|
14
|
+
|
|
15
|
+
def self.encode(value)
|
|
16
|
+
case value
|
|
17
|
+
when nil then "Z".b
|
|
18
|
+
when true then "T".b
|
|
19
|
+
when false then "F".b
|
|
20
|
+
when Numeric
|
|
21
|
+
number = value.to_f
|
|
22
|
+
raise ArgumentError, "nonfinite number" unless number.finite?
|
|
23
|
+
"N".b + [number.zero? ? 0.0 : number].pack("G")
|
|
24
|
+
when String
|
|
25
|
+
text = value.encode(Encoding::UTF_8)
|
|
26
|
+
raise ArgumentError, "invalid UTF-8" unless text.valid_encoding? && text.bytesize <= 0xffff_ffff
|
|
27
|
+
"S".b + [text.bytesize].pack("N") + text.b
|
|
28
|
+
when Array
|
|
29
|
+
raise ArgumentError, "array too long" if value.length > 0xffff_ffff
|
|
30
|
+
"A".b + [value.length].pack("N") + value.map { |item| encode(item) }.join.b
|
|
31
|
+
when Hash
|
|
32
|
+
raise ArgumentError, "invalid keys" unless value.length <= 0xffff_ffff && value.keys.all? { |key| key.is_a?(String) }
|
|
33
|
+
keys = value.keys.sort_by { |key| key.encode(Encoding::UTF_8).b }
|
|
34
|
+
"O".b + [keys.length].pack("N") + keys.map { |key| encode(key) + encode(value.fetch(key)) }.join.b
|
|
35
|
+
else
|
|
36
|
+
raise ArgumentError, "not JSON"
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def self.matches?(data)
|
|
41
|
+
anchor = ANCHORS[data.fetch("offset_id")]
|
|
42
|
+
return false unless anchor
|
|
43
|
+
vintage = data.fetch("vintage")
|
|
44
|
+
provenance = data.fetch("provenance")
|
|
45
|
+
projected = TOP.to_h { |key| [key, data.fetch(key)] }
|
|
46
|
+
projected["vintage"] = VINTAGE.to_h { |key| [key, vintage.fetch(key)] }
|
|
47
|
+
projected["provenance"] = PROVENANCE.to_h { |key| [key, provenance.fetch(key)] }
|
|
48
|
+
{ "id_crosswalk" => %w[legacy_id status modern_alias_verified],
|
|
49
|
+
"reference_binding" => %w[noaa_id station_id mapping_status] }.each do |key, fields|
|
|
50
|
+
projected["provenance"][key] = fields.to_h { |field| [field, provenance.fetch(key).fetch(field)] }
|
|
51
|
+
end
|
|
52
|
+
Digest::SHA256.hexdigest(DOMAIN + encode(projected)) == anchor
|
|
53
|
+
rescue KeyError, TypeError, ArgumentError, RangeError, EncodingError, NoMethodError
|
|
54
|
+
false
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
private_constant :HistoricalFingerprint
|
|
58
|
+
end
|
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
require "net/http"
|
|
2
|
+
require "openssl"
|
|
3
|
+
require "uri"
|
|
4
|
+
require "digest"
|
|
5
|
+
require "time"
|
|
6
|
+
|
|
7
|
+
class OpenTideConstants
|
|
8
|
+
# Net::HTTP with the SDK's rules: timeouts, three attempts with
|
|
9
|
+
# backoff on connection errors, 5xx and 429 (honouring Retry-After up to
|
|
10
|
+
# 60 s), never a retry on 404, proxies from the option or the environment,
|
|
11
|
+
# a custom CA, and the SDK User-Agent. No telemetry, no query parameters.
|
|
12
|
+
class HTTP
|
|
13
|
+
ATTEMPTS = 3
|
|
14
|
+
BACKOFF = [1, 2, 4].freeze
|
|
15
|
+
MAX_RETRY_AFTER = 60
|
|
16
|
+
CONNECT_TIMEOUT = 10
|
|
17
|
+
READ_TIMEOUT = 60
|
|
18
|
+
# Several compressed spans in one request: at most this many ranges and
|
|
19
|
+
# bytes per request, and at most this many single-range requests at
|
|
20
|
+
# once when a multi-range request gets no multipart/byteranges answer.
|
|
21
|
+
MULTI_RANGE_MAX = 64
|
|
22
|
+
MULTI_RANGE_MAX_BYTES = 4 << 20
|
|
23
|
+
RANGE_CONCURRENCY = 8
|
|
24
|
+
TIMEOUT_MIN = 0.001 # the range of the timeout option, in every SDK
|
|
25
|
+
TIMEOUT_MAX = 1e6
|
|
26
|
+
USER_AGENT = "opentideconstants-ruby/#{VERSION} (+https://opentideconstants.org)".freeze
|
|
27
|
+
NETWORK_ERRORS = [SocketError, SystemCallError, IOError, EOFError, Timeout::Error, OpenSSL::SSL::SSLError,
|
|
28
|
+
Net::ProtocolError, Net::OpenTimeout, Net::ReadTimeout, Net::HTTPBadResponse,
|
|
29
|
+
Net::HTTPHeaderSyntaxError, Zlib::Error].freeze
|
|
30
|
+
|
|
31
|
+
# The result of one GET: status, headers we use, and (for a 200 to a
|
|
32
|
+
# file) the size and SHA-256 of the decoded body.
|
|
33
|
+
Response = Struct.new(:status, :etag, :body, :size, :sha256, keyword_init: true)
|
|
34
|
+
|
|
35
|
+
# A local file that a body is written to cannot be written. It is not a
|
|
36
|
+
# network error: it is not retried, and the caller turns it into a
|
|
37
|
+
# cache or io error. #cause is the system error.
|
|
38
|
+
class SinkError < StandardError; end
|
|
39
|
+
|
|
40
|
+
# An absolute http or https URL, or
|
|
41
|
+
# InvalidArgumentError.
|
|
42
|
+
def self.check_url!(value, name)
|
|
43
|
+
uri = URI(value)
|
|
44
|
+
raise URI::InvalidURIError, "not absolute" unless %w[http https].include?(uri.scheme) && uri.host && !uri.host.empty?
|
|
45
|
+
uri
|
|
46
|
+
rescue URI::Error, ArgumentError => e
|
|
47
|
+
# no user or password in the message, also where the URI error quotes the value
|
|
48
|
+
shown = Redact.url(value)
|
|
49
|
+
raise InvalidArgumentError, "#{name} must be an absolute http or https URL, not #{shown.inspect} " \
|
|
50
|
+
"(#{value.is_a?(String) ? e.message.gsub(value, shown) : e.message})"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def self.validate_proxy_argument(proxy)
|
|
54
|
+
resolved = proxy && HTTP.check_url!(proxy, "proxy")
|
|
55
|
+
# Net::HTTP speaks plain HTTP to every proxy: an https:// proxy would get plaintext. Refuse it here,
|
|
56
|
+
# not at the first request. A CONNECT tunnel through an http:// proxy is still TLS end to end.
|
|
57
|
+
if resolved&.scheme == "https"
|
|
58
|
+
raise InvalidArgumentError, "proxy: Net::HTTP cannot use TLS to a proxy; use an http:// proxy, not #{proxy.inspect}"
|
|
59
|
+
end
|
|
60
|
+
resolved
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def initialize(timeout: nil, proxy: nil, ca_file: nil, user_agent: nil, logger: nil, sleeper: nil)
|
|
64
|
+
@open_timeout = timeout || CONNECT_TIMEOUT
|
|
65
|
+
@read_timeout = timeout || READ_TIMEOUT
|
|
66
|
+
@proxy = HTTP.validate_proxy_argument(proxy)
|
|
67
|
+
# A ca_file, else SSL_CERT_FILE, that does not exist or cannot be read is io, at construction:
|
|
68
|
+
# never retried, never a reason to fall back to the cache.
|
|
69
|
+
what = "ca_file"
|
|
70
|
+
if ca_file.nil? && !ENV["SSL_CERT_FILE"].to_s.empty?
|
|
71
|
+
ca_file = ENV["SSL_CERT_FILE"]
|
|
72
|
+
what = "SSL_CERT_FILE"
|
|
73
|
+
end
|
|
74
|
+
if ca_file && !(File.file?(ca_file) && File.readable?(ca_file))
|
|
75
|
+
raise FileError.new("#{what} #{ca_file} does not exist or cannot be read", path: ca_file)
|
|
76
|
+
end
|
|
77
|
+
@ca_file = ca_file
|
|
78
|
+
@user_agent = user_agent ? "#{USER_AGENT} #{user_agent}" : USER_AGENT
|
|
79
|
+
@logger = logger
|
|
80
|
+
@sleeper = sleeper || ->(s) { sleep(s) }
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# GET into memory. Returns a Response (status 200, 304 or 404); raises
|
|
84
|
+
# NetworkError for anything else after the retries.
|
|
85
|
+
def get(url, etag: nil)
|
|
86
|
+
request(url, etag: etag) do |res|
|
|
87
|
+
body = +""
|
|
88
|
+
res.read_body { |chunk| body << chunk }
|
|
89
|
+
Response.new(status: 200, etag: res["etag"], body: body, size: body.bytesize,
|
|
90
|
+
sha256: Digest::SHA256.hexdigest(body))
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# GET into a file at path (created or truncated). Returns a Response
|
|
95
|
+
# with the size and SHA-256 of the decoded bytes written.
|
|
96
|
+
def get_to_file(url, path)
|
|
97
|
+
request(url) do |res|
|
|
98
|
+
digest = Digest::SHA256.new
|
|
99
|
+
size = 0
|
|
100
|
+
# Only the file operations are local errors; a failure while the
|
|
101
|
+
# body is read stays a network error.
|
|
102
|
+
f = sink(path) { File.open(path, "wb") }
|
|
103
|
+
begin
|
|
104
|
+
res.read_body do |chunk|
|
|
105
|
+
sink(path) { f.write(chunk) }
|
|
106
|
+
digest << chunk
|
|
107
|
+
size += chunk.bytesize
|
|
108
|
+
end
|
|
109
|
+
# the close is a local file operation too: a failure there is not network
|
|
110
|
+
sink(path) do
|
|
111
|
+
f.flush
|
|
112
|
+
f.fsync
|
|
113
|
+
f.close
|
|
114
|
+
end
|
|
115
|
+
ensure
|
|
116
|
+
begin
|
|
117
|
+
f.close unless f.closed?
|
|
118
|
+
rescue SystemCallError, IOError
|
|
119
|
+
nil # the read or write already failed; that error is the one to report
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
Response.new(status: 200, etag: res["etag"], size: size, sha256: digest.hexdigest)
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# A station span is admitted from its headers before reading bytes.
|
|
127
|
+
def get_range(url, offset, length, total)
|
|
128
|
+
response = request(url, range: [offset, length, total]) do |res|
|
|
129
|
+
body = +"".b
|
|
130
|
+
res.read_body do |chunk|
|
|
131
|
+
if body.bytesize + chunk.bytesize > length
|
|
132
|
+
raise NetworkError.new("#{url}: Range body exceeds #{length} bytes", url: url, status: 206)
|
|
133
|
+
end
|
|
134
|
+
body << chunk
|
|
135
|
+
end
|
|
136
|
+
check_length!(URI(url), length, body.bytesize)
|
|
137
|
+
Response.new(status: 206, body: body, size: body.bytesize)
|
|
138
|
+
end
|
|
139
|
+
unless response.status == 206
|
|
140
|
+
raise NetworkError.new("#{url}: HTTP #{response.status} for Range", url: url, status: response.status)
|
|
141
|
+
end
|
|
142
|
+
response.body
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# Several bounded immutable compressed spans: {start => bytes} for every
|
|
146
|
+
# [start, length] asked for. Spans go in multi-range requests of at most
|
|
147
|
+
# MULTI_RANGE_MAX ranges and MULTI_RANGE_MAX_BYTES bytes. A span that a
|
|
148
|
+
# multi-range answer does not cover (the server sent 200, one part, or
|
|
149
|
+
# ignored the request) is read with its own Range request, at most
|
|
150
|
+
# RANGE_CONCURRENCY at once. Any failure is raised; nothing is partial.
|
|
151
|
+
def get_ranges(url, spans, total)
|
|
152
|
+
spans = spans.uniq.sort
|
|
153
|
+
if spans.any? { |s, n| s.negative? || n <= 0 || s + n > total } || spans.each_cons(2).any? { |a, b| a[0] + a[1] > b[0] }
|
|
154
|
+
raise InvalidArgumentError, "invalid compressed Range bounds"
|
|
155
|
+
end
|
|
156
|
+
groups = []
|
|
157
|
+
spans.each do |span|
|
|
158
|
+
groups << [] if groups.empty? || groups.last.size == MULTI_RANGE_MAX ||
|
|
159
|
+
groups.last.sum { |_, n| n } + span[1] > MULTI_RANGE_MAX_BYTES
|
|
160
|
+
groups.last << span
|
|
161
|
+
end
|
|
162
|
+
out = {}
|
|
163
|
+
missing = []
|
|
164
|
+
groups.each do |group|
|
|
165
|
+
next missing.concat(group) if group.size == 1
|
|
166
|
+
parts = multi_range(url, group, total)
|
|
167
|
+
group.each do |s, n|
|
|
168
|
+
part = parts.find { |p, data| p <= s && s + n <= p + data.bytesize }
|
|
169
|
+
part ? out[s] = part[1].byteslice(s - part[0], n) : missing << [s, n]
|
|
170
|
+
end
|
|
171
|
+
end
|
|
172
|
+
out.merge!(ranges_alone(url, missing, total))
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# [start, bytes] parts of a multipart/byteranges body; ArgumentError
|
|
176
|
+
# when it is not one.
|
|
177
|
+
def self.multipart_byteranges(body, content_type, total)
|
|
178
|
+
m = /boundary=(?:"([^"]+)"|([^;\s]+))/i.match(content_type.to_s)
|
|
179
|
+
raise ArgumentError, "no multipart boundary" unless m
|
|
180
|
+
delimiter = "--#{m[1] || m[2]}".b
|
|
181
|
+
body = body.b
|
|
182
|
+
position = body.index(delimiter) or raise ArgumentError, "no multipart delimiter"
|
|
183
|
+
parts = []
|
|
184
|
+
loop do
|
|
185
|
+
position += delimiter.bytesize
|
|
186
|
+
return parts if body.byteslice(position, 2) == "--"
|
|
187
|
+
start = body.index("\r\n", position)
|
|
188
|
+
finish = start && body.index("\r\n\r\n", start)
|
|
189
|
+
raise ArgumentError, "truncated multipart headers" unless finish
|
|
190
|
+
headers = body.byteslice(start + 2, finish - start - 2).split("\r\n").to_h do |line|
|
|
191
|
+
name, value = line.split(":", 2)
|
|
192
|
+
[name.to_s.strip.downcase, value.to_s.strip]
|
|
193
|
+
end
|
|
194
|
+
span = content_range(headers["content-range"], total) or raise ArgumentError, "a multipart part has no valid Content-Range"
|
|
195
|
+
data = body.byteslice(finish + 4, span[1]).to_s
|
|
196
|
+
position = finish + 4 + span[1]
|
|
197
|
+
unless data.bytesize == span[1] && body.byteslice(position, 2) == "\r\n" &&
|
|
198
|
+
body.byteslice(position + 2, delimiter.bytesize) == delimiter
|
|
199
|
+
raise ArgumentError, "a multipart part is truncated"
|
|
200
|
+
end
|
|
201
|
+
parts << [span[0], data]
|
|
202
|
+
position += 2
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
# [start, length] of a Content-Range "bytes a-b/total", or nil.
|
|
207
|
+
def self.content_range(value, total)
|
|
208
|
+
m = %r{\A\s*bytes\s+([0-9]+)-([0-9]+)/([0-9]+)\s*\z}.match(value.to_s)
|
|
209
|
+
return nil unless m && m[3].to_i == total && m[2].to_i >= m[1].to_i && m[2].to_i < total
|
|
210
|
+
[m[1].to_i, m[2].to_i - m[1].to_i + 1]
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
private
|
|
214
|
+
|
|
215
|
+
# The parts of one multi-range answer: [[start, bytes]], or [] when the
|
|
216
|
+
# server did not answer 206, or sent more bytes than the spans and
|
|
217
|
+
# their part headers need (a server that merged them with the bytes
|
|
218
|
+
# between): the caller then reads each span alone.
|
|
219
|
+
def multi_range(url, group, total)
|
|
220
|
+
header = "bytes=" + group.map { |s, n| "#{s}-#{s + n - 1}" }.join(",")
|
|
221
|
+
limit = group.sum { |_, n| n } + 256 * group.size + 1024
|
|
222
|
+
response = catch(:oversized) do
|
|
223
|
+
request(url, multi: header) do |res|
|
|
224
|
+
body = +"".b
|
|
225
|
+
res.read_body do |chunk|
|
|
226
|
+
throw :oversized if body.bytesize + chunk.bytesize > limit
|
|
227
|
+
body << chunk
|
|
228
|
+
end
|
|
229
|
+
check_length!(URI(url), expected_length(URI(url), res), body.bytesize)
|
|
230
|
+
[res["content-type"].to_s, res["content-range"], body]
|
|
231
|
+
end
|
|
232
|
+
end
|
|
233
|
+
return [] unless response.is_a?(Array)
|
|
234
|
+
content_type, content_range, body = response
|
|
235
|
+
unless content_type.downcase.start_with?("multipart/byteranges")
|
|
236
|
+
span = HTTP.content_range(content_range, total)
|
|
237
|
+
raise NetworkError.new("#{url}: invalid multi-range response", url: url, status: 206) unless span && span[1] == body.bytesize
|
|
238
|
+
return [[span[0], body]]
|
|
239
|
+
end
|
|
240
|
+
begin
|
|
241
|
+
HTTP.multipart_byteranges(body, content_type, total)
|
|
242
|
+
rescue ArgumentError => e
|
|
243
|
+
raise NetworkError.new("#{url}: invalid multipart/byteranges response (#{e.message})", url: url, status: 206)
|
|
244
|
+
end
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
# {start => bytes} of single-range requests, at most RANGE_CONCURRENCY
|
|
248
|
+
# at once. The first failure is raised once every request has ended.
|
|
249
|
+
def ranges_alone(url, spans, total)
|
|
250
|
+
return {} if spans.empty?
|
|
251
|
+
return { spans[0][0] => get_range(url, spans[0][0], spans[0][1], total) } if spans.size == 1
|
|
252
|
+
queue = Queue.new
|
|
253
|
+
spans.each { |span| queue << span }
|
|
254
|
+
queue.close
|
|
255
|
+
threads = Array.new([RANGE_CONCURRENCY, spans.size].min) do
|
|
256
|
+
Thread.new do
|
|
257
|
+
Thread.current.report_on_exception = false
|
|
258
|
+
got = {}
|
|
259
|
+
while (span = queue.pop)
|
|
260
|
+
got[span[0]] = get_range(url, span[0], span[1], total)
|
|
261
|
+
end
|
|
262
|
+
got
|
|
263
|
+
rescue Exception # rubocop:disable Lint/RescueException
|
|
264
|
+
queue.clear
|
|
265
|
+
raise
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
threads.each { |t| t.join rescue nil } # rubocop:disable Style/RescueModifier
|
|
269
|
+
threads.each_with_object({}) { |t, out| out.merge!(t.value) }
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
# Runs one local file operation on path; a system error becomes SinkError.
|
|
273
|
+
def sink(path)
|
|
274
|
+
yield
|
|
275
|
+
rescue SystemCallError, IOError => e
|
|
276
|
+
raise SinkError, "cannot write #{path}: #{e.message}"
|
|
277
|
+
end
|
|
278
|
+
|
|
279
|
+
# A certificate that does not verify does not get better on a retry.
|
|
280
|
+
def tls_verify_failure?(e)
|
|
281
|
+
e.is_a?(OpenSSL::SSL::SSLError) && e.message.include?("certificate verify failed")
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
REDIRECTS = [301, 302, 303, 307, 308].freeze
|
|
285
|
+
MAX_REDIRECTS = 5
|
|
286
|
+
|
|
287
|
+
# Sends the GET with the retries of, following up to 5 redirects.
|
|
288
|
+
# Each attempt is independent: no state is kept on the
|
|
289
|
+
# instance, so one HTTP can serve several threads.
|
|
290
|
+
def request(url, etag: nil, range: nil, multi: nil, &on_ok)
|
|
291
|
+
uri = URI(url)
|
|
292
|
+
# decided by the URL asked for, not the redirect hop: a CDN may send the .gz
|
|
293
|
+
# from a URL with no suffix
|
|
294
|
+
keep_gz = uri.path.end_with?(".gz")
|
|
295
|
+
attempt = 0
|
|
296
|
+
redirects = 0
|
|
297
|
+
loop do
|
|
298
|
+
attempt += 1
|
|
299
|
+
wait = nil
|
|
300
|
+
cause = nil
|
|
301
|
+
begin
|
|
302
|
+
kind, value, retry_wait = once(uri, etag, keep_gz, range, multi, &on_ok)
|
|
303
|
+
return value if kind == :ok
|
|
304
|
+
if kind == :redirect
|
|
305
|
+
redirects += 1
|
|
306
|
+
uri = follow(uri, value, url, redirects)
|
|
307
|
+
attempt = 0
|
|
308
|
+
next
|
|
309
|
+
end
|
|
310
|
+
status = value
|
|
311
|
+
return Response.new(status: status) if [304, 404].include?(status)
|
|
312
|
+
err = NetworkError.new("GET #{uri}: HTTP #{status}", url: uri.to_s, status: status)
|
|
313
|
+
raise err unless status >= 500 || status == 429
|
|
314
|
+
wait = retry_wait
|
|
315
|
+
rescue NetworkError, SinkError
|
|
316
|
+
raise
|
|
317
|
+
rescue *NETWORK_ERRORS => e
|
|
318
|
+
if tls_verify_failure?(e)
|
|
319
|
+
raise NetworkError.new("GET #{uri}: the server's TLS certificate does not verify (#{e.message}); " \
|
|
320
|
+
"check ca_file or SSL_CERT_FILE", url: uri.to_s, status: nil), cause: e
|
|
321
|
+
end
|
|
322
|
+
err = NetworkError.new("GET #{uri}: #{e.class}: #{e.message}", url: uri.to_s, status: nil)
|
|
323
|
+
cause = e
|
|
324
|
+
end
|
|
325
|
+
if attempt >= ATTEMPTS
|
|
326
|
+
raise err, cause: cause if cause
|
|
327
|
+
raise err
|
|
328
|
+
end
|
|
329
|
+
wait ||= BACKOFF[attempt - 1]
|
|
330
|
+
@logger&.warn("opentideconstants: #{err.message}; retry in #{wait} s")
|
|
331
|
+
@sleeper.call(wait)
|
|
332
|
+
end
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
# The URI a redirect goes to, or NetworkError: a 6th redirect, a
|
|
336
|
+
# missing or bad Location, a scheme other than http or https, no host,
|
|
337
|
+
# or a redirect from https to http.
|
|
338
|
+
def follow(from, location, url, count)
|
|
339
|
+
raise NetworkError.new("GET #{url}: more than #{MAX_REDIRECTS} redirects", url: url, status: nil) if count > MAX_REDIRECTS
|
|
340
|
+
if location.nil? || location.strip.empty?
|
|
341
|
+
raise NetworkError.new("GET #{from}: a redirect with no Location", url: url, status: nil)
|
|
342
|
+
end
|
|
343
|
+
to = from + location.strip
|
|
344
|
+
unless %w[http https].include?(to.scheme)
|
|
345
|
+
raise NetworkError.new("GET #{from}: a redirect to #{to} is not http or https", url: url, status: nil)
|
|
346
|
+
end
|
|
347
|
+
# a Location such as "https:" or "//:8080/x" has no host: Net::HTTP would connect to localhost.
|
|
348
|
+
# Check the Location itself too: the uri gem in Ruby 3.0 keeps the base host when it resolves "//:8080/x".
|
|
349
|
+
own = URI.parse(location.strip)
|
|
350
|
+
own_authority = own.scheme || location.strip.start_with?("//")
|
|
351
|
+
if to.host.nil? || to.host.empty? || (own_authority && (own.host.nil? || own.host.empty?))
|
|
352
|
+
raise NetworkError.new("GET #{from}: a redirect to #{location.strip.inspect} has no host", url: url, status: nil)
|
|
353
|
+
end
|
|
354
|
+
if from.scheme == "https" && to.scheme == "http"
|
|
355
|
+
raise NetworkError.new("GET #{from}: a redirect from https to http (#{to}) is not followed", url: url, status: nil)
|
|
356
|
+
end
|
|
357
|
+
to
|
|
358
|
+
rescue URI::Error => e
|
|
359
|
+
raise NetworkError.new("GET #{from}: a redirect to a bad Location #{location.inspect} (#{e.message})", url: url, status: nil)
|
|
360
|
+
end
|
|
361
|
+
|
|
362
|
+
# One request: [:ok, the block's value] for a 200, [:redirect, the
|
|
363
|
+
# Location], or [:status, the code, the Retry-After wait or nil].
|
|
364
|
+
def once(uri, etag, keep_gz, range = nil, multi = nil)
|
|
365
|
+
http = connection(uri)
|
|
366
|
+
http.start do |conn|
|
|
367
|
+
req = Net::HTTP::Get.new(uri)
|
|
368
|
+
req["User-Agent"] = @user_agent
|
|
369
|
+
req["If-None-Match"] = etag if etag
|
|
370
|
+
# A .gz file is kept as it is sent: its SHA-256 is over the gzip
|
|
371
|
+
# bytes, also when a server adds Content-Encoding: gzip.
|
|
372
|
+
req["Accept-Encoding"] = "identity" if keep_gz || range
|
|
373
|
+
req["Range"] = "bytes=#{range[0]}-#{range[0] + range[1] - 1}" if range
|
|
374
|
+
if multi
|
|
375
|
+
req["Range"] = multi
|
|
376
|
+
req["Accept-Encoding"] = "identity"
|
|
377
|
+
end
|
|
378
|
+
conn.request(req) do |res|
|
|
379
|
+
code = res.code.to_i
|
|
380
|
+
if multi && code == 206
|
|
381
|
+
unless ["", "identity"].include?(res["content-encoding"].to_s.strip.downcase)
|
|
382
|
+
raise NetworkError.new("#{uri}: invalid HTTP 206 multi-range response", url: uri.to_s, status: code)
|
|
383
|
+
end
|
|
384
|
+
return [:ok, yield(res)]
|
|
385
|
+
elsif multi && !(REDIRECTS.include?(code) || code == 429 || code >= 500)
|
|
386
|
+
# not a multi-range answer, left unread: the caller reads each span alone
|
|
387
|
+
return [:ok, nil]
|
|
388
|
+
end
|
|
389
|
+
if range && (code == 200 || code == 206)
|
|
390
|
+
offset, length, total = range
|
|
391
|
+
expected_range = "bytes #{offset}-#{offset + length - 1}/#{total}"
|
|
392
|
+
encoding = res["content-encoding"].to_s.strip.downcase
|
|
393
|
+
unless code == 206 && res["content-range"] == expected_range &&
|
|
394
|
+
[nil, length].include?(expected_length(uri, res)) && ["", "identity"].include?(encoding)
|
|
395
|
+
raise NetworkError.new("#{uri}: invalid HTTP #{code} Range response", url: uri.to_s, status: code)
|
|
396
|
+
end
|
|
397
|
+
return [:ok, yield(res)]
|
|
398
|
+
elsif code == 200
|
|
399
|
+
expected = expected_length(uri, res)
|
|
400
|
+
result = yield(res)
|
|
401
|
+
check_length!(uri, expected, result.size)
|
|
402
|
+
return [:ok, result]
|
|
403
|
+
end
|
|
404
|
+
res.read_body { |_| } if code != 304
|
|
405
|
+
return [:redirect, res["location"]] if REDIRECTS.include?(code)
|
|
406
|
+
return [:status, code, code == 429 || code >= 500 ? retry_after(res["retry-after"]) : nil]
|
|
407
|
+
end
|
|
408
|
+
end
|
|
409
|
+
end
|
|
410
|
+
|
|
411
|
+
# The Content-Length of the body as it is read, or nil: there is none,
|
|
412
|
+
# or Net::HTTP decodes a content-encoded body. Content-Length values
|
|
413
|
+
# that differ, or are not numbers, are a bad response (network).
|
|
414
|
+
def expected_length(uri, res)
|
|
415
|
+
values = Array(res.get_fields("content-length")).flat_map { |v| v.split(",") }.map(&:strip)
|
|
416
|
+
return nil if values.empty?
|
|
417
|
+
nums = values.map { |v| Integer(v, 10, exception: false) }
|
|
418
|
+
if nums.include?(nil) || nums.uniq.size > 1
|
|
419
|
+
raise Net::HTTPBadResponse, "#{uri}: Content-Length #{values.join(', ')}"
|
|
420
|
+
end
|
|
421
|
+
enc = res["content-encoding"].to_s.strip.downcase
|
|
422
|
+
return nil if res.decode_content && !(enc.empty? || enc == "identity")
|
|
423
|
+
nums.first
|
|
424
|
+
end
|
|
425
|
+
|
|
426
|
+
# Net::HTTP accepts a body that ends before its Content-Length; the
|
|
427
|
+
# SDK treats it as a network error (README suite choices).
|
|
428
|
+
def check_length!(uri, expected, got)
|
|
429
|
+
return if expected.nil? || got == expected
|
|
430
|
+
raise EOFError, "#{uri}: body ended after #{got} of #{expected} bytes"
|
|
431
|
+
end
|
|
432
|
+
|
|
433
|
+
# An HTTP date as a Time, or nil. Impossible calendar fields, hour 24,
|
|
434
|
+
# a leap second and the wrong weekday are malformed:
|
|
435
|
+
# Time.httpdate would roll them over into another date.
|
|
436
|
+
def http_date(v)
|
|
437
|
+
f = Date._httpdate(v)
|
|
438
|
+
return nil unless f && f[:year] && f[:mon] && f[:mday] && f[:hour] && f[:min] && f[:sec]
|
|
439
|
+
return nil unless Date.valid_date?(f[:year], f[:mon], f[:mday], Date::GREGORIAN)
|
|
440
|
+
return nil unless f[:hour] <= 23 && f[:min] <= 59 && f[:sec] <= 59
|
|
441
|
+
return nil if f[:wday] && f[:wday] != Date.new(f[:year], f[:mon], f[:mday], Date::GREGORIAN).wday
|
|
442
|
+
Time.httpdate(v)
|
|
443
|
+
rescue ArgumentError
|
|
444
|
+
nil
|
|
445
|
+
end
|
|
446
|
+
|
|
447
|
+
# Retry-After in seconds (a number, or an HTTP date), at most 60; nil
|
|
448
|
+
# when it is missing or malformed.
|
|
449
|
+
def retry_after(value)
|
|
450
|
+
return nil if value.nil?
|
|
451
|
+
v = value.strip
|
|
452
|
+
s = Integer(v, 10, exception: false)
|
|
453
|
+
if s.nil?
|
|
454
|
+
t = http_date(v)
|
|
455
|
+
return nil if t.nil?
|
|
456
|
+
s = [(t - Time.now).ceil, 0].max
|
|
457
|
+
end
|
|
458
|
+
s >= 0 ? [s, MAX_RETRY_AFTER].min : nil
|
|
459
|
+
end
|
|
460
|
+
|
|
461
|
+
def unescape(part)
|
|
462
|
+
part && URI::DEFAULT_PARSER.unescape(part)
|
|
463
|
+
end
|
|
464
|
+
|
|
465
|
+
def connection(uri)
|
|
466
|
+
http = if @proxy
|
|
467
|
+
# The URL's user and password are percent-encoded; the proxy wants them decoded.
|
|
468
|
+
Net::HTTP.new(uri.host, uri.port, @proxy.host, @proxy.port, unescape(@proxy.user), unescape(@proxy.password))
|
|
469
|
+
else
|
|
470
|
+
Net::HTTP.new(uri.host, uri.port) # :ENV proxy: http(s)_proxy and no_proxy
|
|
471
|
+
end
|
|
472
|
+
http.open_timeout = @open_timeout
|
|
473
|
+
http.read_timeout = @read_timeout
|
|
474
|
+
http.write_timeout = @read_timeout if http.respond_to?(:write_timeout=)
|
|
475
|
+
if uri.scheme == "https"
|
|
476
|
+
http.use_ssl = true
|
|
477
|
+
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
|
|
478
|
+
http.ca_file = @ca_file if @ca_file
|
|
479
|
+
end
|
|
480
|
+
http
|
|
481
|
+
end
|
|
482
|
+
end
|
|
483
|
+
end
|