Repository navigation
Expand file tree
/
Copy patherror_classifier.rb
More file actions
359 lines (309 loc) · 12.8 KB
/
Copy patherror_classifier.rb
File metadata and controls
359 lines (309 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# frozen_string_literal: true
require 'timeout'
require 'net/http'
module Html2rss
module Web
##
# Classifies exception chains into immutable HTTP error decisions and telemetry diagnostics.
#
# Acts as the single source of truth for error-to-HTTP mapping across both
# XML feed and JSON API endpoints.
module ErrorClassifier # rubocop:disable Metrics/ModuleLength
##
# Immutable HTTP decision for a classified error.
Decision = Data.define(
:status, :code, :message, :kind, :cacheable, :retryable, :next_action, :retry_action
)
##
# Gem strategy attempts plus expanded transport telemetry for feed Observability / headers.
Diagnostics = Data.define(
:strategy_attempts, :request_id, :strategy_used, :render_ms, :error_category, :timeout_phase
) do
class << self
# @return [Html2rss::Web::ErrorClassifier::Diagnostics]
def empty
EMPTY_DIAGNOSTICS
end
# Digs strategy attempts from the exception cause chain.
# Prefer +timeout_phase+ from transport_meta; else from +RequestTimedOut+ in the chain.
#
# @param error [Exception, nil]
# @return [Html2rss::Web::ErrorClassifier::Diagnostics]
def from_error(error)
chain = ErrorClassifier.error_chain(error)
with_attempts = chain.find { it.respond_to?(:attempts) }
list = with_attempts ? Array(with_attempts.attempts) : []
fields = transport_fields(list)
fields[:timeout_phase] ||= timeout_phase_from_chain(chain)
return EMPTY_DIAGNOSTICS if list.empty? && fields.values.all?(&:nil?)
new(strategy_attempts: list, **fields)
end
# Expands attempt hashes into transport fields (single dig algorithm).
#
# @param attempts [Array<Hash>, nil]
# @return [Html2rss::Web::ErrorClassifier::Diagnostics]
def from_attempts(attempts)
list = Array(attempts)
return EMPTY_DIAGNOSTICS if list.empty?
new(strategy_attempts: list, **transport_fields(list))
end
private
# @param attempts [Array<Hash>]
# @return [Hash{Symbol=>Object}]
def transport_fields(attempts)
meta = attempts.filter_map { it[:transport_meta] || it['transport_meta'] }.last
{
request_id: dig_meta(meta, :request_id),
strategy_used: dig_meta(meta, :strategy_used),
render_ms: dig_meta(meta, :render_ms),
error_category: dig_meta(meta, :error_category),
timeout_phase: dig_meta(meta, :timeout_phase)
}
end
# @param chain [Array<Exception>]
# @return [Object, nil]
def timeout_phase_from_chain(chain)
return unless defined?(::Html2rss::RequestService::RequestTimedOut)
timed_out = chain.find { it.is_a?(::Html2rss::RequestService::RequestTimedOut) }
return unless timed_out
return unless timed_out.respond_to?(:timeout_phase)
timed_out.timeout_phase
end
# @param meta [Hash, nil]
# @param key [Symbol]
# @return [Object, nil]
def dig_meta(meta, key)
return unless meta
meta[key] || meta[key.to_s]
end
end
# Sparse hash for Observability emit (omits blank fields).
#
# @return [Hash{Symbol=>Object}]
def to_h
details = strategy_attempts.empty? ? {} : { strategy_attempts: strategy_attempts }
%i[request_id strategy_used render_ms error_category timeout_phase].each do |key|
val = public_send(key)
details[key] = val if val
end
details
end
end
EMPTY_DIAGNOSTICS = Diagnostics.new(
strategy_attempts: [].freeze,
request_id: nil,
strategy_used: nil,
render_ms: nil,
error_category: nil,
timeout_phase: nil
).freeze
##
# Carries an already-computed {Decision} through raise → {ErrorResponder}.
class DecidedError < StandardError
# @return [Html2rss::Web::ErrorClassifier::Decision]
attr_reader :decision
# @param decision [Html2rss::Web::ErrorClassifier::Decision]
def initialize(decision)
@decision = decision
super(decision.message)
end
end
NETWORK_ERRORS = Set[
Timeout::Error, Net::OpenTimeout, Net::ReadTimeout, SocketError,
EOFError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ETIMEDOUT
].freeze
AUTH_META = { kind: 'auth', retryable: false, next_action: 'enter_token', retry_action: 'none' }.freeze
INPUT_META = { kind: 'input', retryable: false, next_action: 'correct_input', retry_action: 'none' }.freeze
SERVER_META = { kind: 'server', retryable: false, next_action: 'none', retry_action: 'none' }.freeze
RETRY_META = { retryable: true, next_action: 'retry', retry_action: 'primary' }.freeze
EXTRACTION_EMPTY_CODE = 'EXTRACTION_EMPTY'
EXTRACTION_EMPTY_MESSAGE = 'We could not extract feed items from this page yet. ' \
'Try a more specific listing URL or explicit selectors.'
EXTRACTION_EMPTY = Decision.new(
status: 422,
code: EXTRACTION_EMPTY_CODE,
message: EXTRACTION_EMPTY_MESSAGE,
kind: 'input',
cacheable: true,
retryable: false,
next_action: 'correct_input',
retry_action: 'none'
).freeze
BLOCKED_SURFACE_CODE = 'BLOCKED_SURFACE'
BLOCKED_SURFACE_MESSAGE = 'This site blocked automated access. Try another URL or site.'
BLOCKED_SURFACE = Decision.new(
status: 422,
code: BLOCKED_SURFACE_CODE,
message: BLOCKED_SURFACE_MESSAGE,
kind: 'input',
cacheable: true,
retryable: false,
next_action: 'correct_input',
retry_action: 'none'
).freeze
SCRAPER_UNAVAILABLE_CODE = 'SCRAPER_UNAVAILABLE'
SCRAPER_UNAVAILABLE_MESSAGE = 'Feed fetching is temporarily unavailable.'
SCRAPER_UNAVAILABLE = Decision.new(
status: 503,
code: SCRAPER_UNAVAILABLE_CODE,
message: SCRAPER_UNAVAILABLE_MESSAGE,
kind: 'server',
cacheable: false,
retryable: true,
next_action: 'retry',
retry_action: 'primary'
).freeze
SERVICE_UNAVAILABLE = Decision.new(
status: 503,
code: 'SERVICE_UNAVAILABLE',
message: 'The server is too busy or the request timed out.',
kind: 'server',
cacheable: false,
retryable: true,
next_action: 'retry',
retry_action: 'primary'
).freeze
GATEWAY_TIMEOUT = Decision.new(
status: 504,
code: 'GATEWAY_TIMEOUT',
message: 'The target website took too long to respond.',
kind: 'network',
cacheable: false,
retryable: true,
next_action: 'retry',
retry_action: 'primary'
).freeze
INTERNAL_SERVER_ERROR = Decision.new(
status: 500,
code: 'INTERNAL_SERVER_ERROR',
message: 'Internal Server Error',
kind: 'server',
cacheable: false,
retryable: true,
next_action: 'retry',
retry_action: 'primary'
).freeze
PRIVATE_NETWORK_DENIED = Decision.new(
status: 403,
code: 'FORBIDDEN',
message: 'Requests to private or loopback networks are forbidden.',
kind: 'input',
cacheable: true,
retryable: false,
next_action: 'correct_input',
retry_action: 'none'
).freeze
INTERNAL_NETWORK_ERROR = Decision.new(
status: 500,
code: 'INTERNAL_SERVER_ERROR',
message: 'Internal Server Error',
kind: 'network',
cacheable: false,
retryable: true,
next_action: 'retry',
retry_action: 'primary'
).freeze
SPECIAL_DECISIONS = [
[lambda { |c, _|
defined?(::Html2rss::NoFeedItemsExtracted) && c.any?(::Html2rss::NoFeedItemsExtracted)
}, EXTRACTION_EMPTY],
[lambda { |c, _|
defined?(::Html2rss::RequestService::BlockedSurfaceDetected) &&
c.any?(::Html2rss::RequestService::BlockedSurfaceDetected)
}, BLOCKED_SURFACE],
[lambda { |c, _|
defined?(::Html2rss::RequestService::BotasaurusConnectionFailed) &&
c.any?(::Html2rss::RequestService::BotasaurusConnectionFailed)
}, SCRAPER_UNAVAILABLE],
[lambda { |c, _|
defined?(::Html2rss::RequestService::PrivateNetworkDenied) &&
c.any?(::Html2rss::RequestService::PrivateNetworkDenied)
}, PRIVATE_NETWORK_DENIED],
[lambda { |c, _|
# queue/boot = our capacity or Chromium — not the target site.
return false unless defined?(::Html2rss::RequestService::RequestTimedOut)
timed_out = c.find { it.is_a?(::Html2rss::RequestService::RequestTimedOut) }
return false unless timed_out
phase = timed_out.respond_to?(:timeout_phase) ? timed_out.timeout_phase : nil
%w[queue boot].include?(phase)
}, SERVICE_UNAVAILABLE],
[lambda { |c, _|
# Gem wall-clock timeout (Botasaurus 504 / HTTPX timeout) — not Timeout::Error.
# work / nil (transport hop) → site-shaped 504.
defined?(::Html2rss::RequestService::RequestTimedOut) &&
c.any?(::Html2rss::RequestService::RequestTimedOut)
}, GATEWAY_TIMEOUT],
[lambda { |c, err|
err.is_a?(Timeout::Error) || err.is_a?(Errno::ETIMEDOUT) ||
(defined?(::Async::TimeoutError) && (err.is_a?(::Async::TimeoutError) || c.any?(::Async::TimeoutError))) ||
(defined?(::HTTPX::TimeoutError) && (err.is_a?(::HTTPX::TimeoutError) || c.any?(::HTTPX::TimeoutError)))
}, GATEWAY_TIMEOUT]
].freeze
class << self
# Returns an immutable HTTP decision for any error.
#
# @param error [Exception]
# @return [Html2rss::Web::ErrorClassifier::Decision]
def classify(error)
return error.decision if error.is_a?(DecidedError)
classify_special_error(error) || classify_http_error(error) || classify_unhandled_error(error)
end
# Walks +Exception#cause+ without following identity cycles.
#
# @param error [Exception, nil]
# @return [Array<Exception>]
def error_chain(error)
chain = []
seen = {}.compare_by_identity
current = error
while current && !seen[current]
chain << current
seen[current] = true
current = current.respond_to?(:cause) ? current.cause : nil
end
chain
end
private
def classify_http_error(error)
case error
when TooManyRequestsError
decision_for_http_error(error, RETRY_META.merge(kind: 'client'),
default_message: 'Too many requests. Wait before retrying.')
when UnauthorizedError then decision_for_http_error(error, AUTH_META)
when BadRequestError, ForbiddenError then decision_for_http_error(error, INPUT_META)
when HealthCheckFailedError then decision_for_http_error(error, SERVER_META)
when HttpError then decision_for_http_error(error, RETRY_META.merge(kind: error_kind_for(error)))
end
end
def classify_special_error(error)
chain = error_chain(error)
SPECIAL_DECISIONS.find { |match, _| match.call(chain, error) }&.last
end
def error_kind_for(error)
return 'client' if error.status == 429
network_error?(error) ? 'network' : 'server'
end
def classify_unhandled_error(error)
network_error?(error) ? INTERNAL_NETWORK_ERROR : INTERNAL_SERVER_ERROR
end
def decision_for_http_error(error, meta, default_message: nil)
message = if error.message != error.class.name && !error.message.to_s.empty?
error.message
else
default_message || error.class::DEFAULT_MESSAGE
end
Decision.new(status: error.status, code: error.code, message:, cacheable: false, **meta)
end
def network_error?(error)
error_chain(error).any? { |err| network_error_class?(err) }
end
def network_error_class?(err)
return true if NETWORK_ERRORS.include?(err.class)
return true if defined?(::Async::TimeoutError) && err.is_a?(::Async::TimeoutError)
return false unless defined?(::HTTPX::Error)
err.is_a?(::HTTPX::ConnectionError) || err.is_a?(::HTTPX::TLSError) || err.is_a?(::HTTPX::TimeoutError)
end
end
end
end
end