ruby-link-checker 0.4.0 → 0.6.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.
Files changed (104) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +34 -0
  3. data/LICENSE.md +0 -0
  4. data/README.md +227 -19
  5. data/UPGRADING.md +46 -0
  6. data/lib/ruby-link-checker/async/http/checker.rb +46 -7
  7. data/lib/ruby-link-checker/async/http/config.rb +4 -0
  8. data/lib/ruby-link-checker/async/http/result.rb +5 -1
  9. data/lib/ruby-link-checker/async/http.rb +0 -0
  10. data/lib/ruby-link-checker/cache.rb +170 -0
  11. data/lib/ruby-link-checker/callbacks.rb +0 -0
  12. data/lib/ruby-link-checker/checker.rb +200 -5
  13. data/lib/ruby-link-checker/config.rb +141 -0
  14. data/lib/ruby-link-checker/errors/base_error.rb +0 -0
  15. data/lib/ruby-link-checker/errors/connection_error.rb +23 -0
  16. data/lib/ruby-link-checker/errors/redirect_limit_error.rb +15 -0
  17. data/lib/ruby-link-checker/errors/redirect_loop_error.rb +0 -0
  18. data/lib/ruby-link-checker/errors.rb +2 -0
  19. data/lib/ruby-link-checker/logger.rb +0 -0
  20. data/lib/ruby-link-checker/net/http/checker.rb +5 -3
  21. data/lib/ruby-link-checker/net/http/config.rb +0 -0
  22. data/lib/ruby-link-checker/net/http/result.rb +5 -1
  23. data/lib/ruby-link-checker/net/http.rb +0 -0
  24. data/lib/ruby-link-checker/redirect.rb +11 -0
  25. data/lib/ruby-link-checker/result.rb +120 -0
  26. data/lib/ruby-link-checker/task.rb +2 -0
  27. data/lib/ruby-link-checker/tasks.rb +53 -7
  28. data/lib/ruby-link-checker/typhoeus/hydra/checker.rb +79 -9
  29. data/lib/ruby-link-checker/typhoeus/hydra/config.rb +0 -0
  30. data/lib/ruby-link-checker/typhoeus/hydra/result.rb +5 -1
  31. data/lib/ruby-link-checker/typhoeus/hydra.rb +0 -0
  32. data/lib/ruby-link-checker/version.rb +1 -1
  33. data/lib/ruby-link-checker.rb +2 -0
  34. data/lib/ruby_link_checker.rb +0 -0
  35. metadata +26 -72
  36. data/CONTRIBUTING.md +0 -125
  37. data/Dangerfile +0 -6
  38. data/Gemfile +0 -24
  39. data/Gemfile.lock +0 -334
  40. data/RELEASING.md +0 -60
  41. data/Rakefile +0 -18
  42. data/benchmarks/check.rb +0 -38
  43. data/benchmarks/data/opensearch.org/links.txt +0 -4270
  44. data/benchmarks/data/opensearch.org/small.txt +0 -100
  45. data/coverage/assets/0.13.2/DataTables-1.10.20/images/sort_asc.png +0 -0
  46. data/coverage/assets/0.13.2/DataTables-1.10.20/images/sort_asc_disabled.png +0 -0
  47. data/coverage/assets/0.13.2/DataTables-1.10.20/images/sort_both.png +0 -0
  48. data/coverage/assets/0.13.2/DataTables-1.10.20/images/sort_desc.png +0 -0
  49. data/coverage/assets/0.13.2/DataTables-1.10.20/images/sort_desc_disabled.png +0 -0
  50. data/coverage/assets/0.13.2/application.css +0 -1
  51. data/coverage/assets/0.13.2/application.js +0 -7
  52. data/coverage/assets/0.13.2/colorbox/border.png +0 -0
  53. data/coverage/assets/0.13.2/colorbox/controls.png +0 -0
  54. data/coverage/assets/0.13.2/colorbox/loading.gif +0 -0
  55. data/coverage/assets/0.13.2/colorbox/loading_background.png +0 -0
  56. data/coverage/assets/0.13.2/favicon_green.png +0 -0
  57. data/coverage/assets/0.13.2/favicon_red.png +0 -0
  58. data/coverage/assets/0.13.2/favicon_yellow.png +0 -0
  59. data/coverage/assets/0.13.2/images/ui-bg_flat_0_aaaaaa_40x100.png +0 -0
  60. data/coverage/assets/0.13.2/images/ui-bg_flat_75_ffffff_40x100.png +0 -0
  61. data/coverage/assets/0.13.2/images/ui-bg_glass_55_fbf9ee_1x400.png +0 -0
  62. data/coverage/assets/0.13.2/images/ui-bg_glass_65_ffffff_1x400.png +0 -0
  63. data/coverage/assets/0.13.2/images/ui-bg_glass_75_dadada_1x400.png +0 -0
  64. data/coverage/assets/0.13.2/images/ui-bg_glass_75_e6e6e6_1x400.png +0 -0
  65. data/coverage/assets/0.13.2/images/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  66. data/coverage/assets/0.13.2/images/ui-bg_highlight-soft_75_cccccc_1x100.png +0 -0
  67. data/coverage/assets/0.13.2/images/ui-icons_222222_256x240.png +0 -0
  68. data/coverage/assets/0.13.2/images/ui-icons_2e83ff_256x240.png +0 -0
  69. data/coverage/assets/0.13.2/images/ui-icons_454545_256x240.png +0 -0
  70. data/coverage/assets/0.13.2/images/ui-icons_888888_256x240.png +0 -0
  71. data/coverage/assets/0.13.2/images/ui-icons_cd0a0a_256x240.png +0 -0
  72. data/coverage/assets/0.13.2/loading.gif +0 -0
  73. data/coverage/assets/0.13.2/magnify.png +0 -0
  74. data/coverage/index.html +0 -10746
  75. data/ruby-link-checker.gemspec +0 -22
  76. data/spec/fixtures/200.yml +0 -65
  77. data/spec/fixtures/301_200.yml +0 -102
  78. data/spec/fixtures/301_301.yml +0 -114
  79. data/spec/fixtures/301_400_301_200.yml +0 -185
  80. data/spec/fixtures/301_403.yml +0 -78
  81. data/spec/fixtures/308_429.yml +0 -108
  82. data/spec/fixtures/404.yml +0 -57
  83. data/spec/fixtures/404_200.yml +0 -89
  84. data/spec/fixtures/404_404.yml +0 -81
  85. data/spec/fixtures/429_200.yml +0 -135
  86. data/spec/fixtures/429_429_200.yml +0 -201
  87. data/spec/ruby-link-checker/async/http/checker_spec.rb +0 -99
  88. data/spec/ruby-link-checker/callbacks_spec.rb +0 -76
  89. data/spec/ruby-link-checker/checker_spec.rb +0 -10
  90. data/spec/ruby-link-checker/config_spec.rb +0 -39
  91. data/spec/ruby-link-checker/errors/redirect_loop_error_spec.rb +0 -18
  92. data/spec/ruby-link-checker/net/http/checker_spec.rb +0 -78
  93. data/spec/ruby-link-checker/result_error_spec.rb +0 -17
  94. data/spec/ruby-link-checker/result_spec.rb +0 -41
  95. data/spec/ruby-link-checker/task_spec.rb +0 -20
  96. data/spec/ruby-link-checker/tasks_spec.rb +0 -47
  97. data/spec/ruby-link-checker/typhoeus/hydra/checker_spec.rb +0 -93
  98. data/spec/ruby-link-checker/version_spec.rb +0 -9
  99. data/spec/spec_helper.rb +0 -19
  100. data/spec/support/config.rb +0 -8
  101. data/spec/support/link_checker.rb +0 -369
  102. data/spec/support/vcr.rb +0 -13
  103. data/spec/support/with_result.rb +0 -15
  104. data/spec/support/with_url.rb +0 -14
@@ -0,0 +1,170 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'fileutils'
5
+ require 'json'
6
+ require 'tempfile'
7
+ require 'uri'
8
+
9
+ module LinkChecker
10
+ class CachedResult < Result
11
+ attr_reader :code, :challenge
12
+
13
+ def initialize(data, uri)
14
+ @code = data.fetch('code')
15
+ super(URI(data.fetch('result_uri')), data.fetch('method'), URI(uri.to_s))
16
+ @redirects = data.fetch('redirects').map do |hop_uri, code, to|
17
+ Redirect.new(uri: URI(hop_uri), code: code, to: URI(to))
18
+ end.freeze
19
+ @blocked = data['blocked'] == true
20
+ @challenge = data['challenge'] if data['challenge'].is_a?(String)
21
+ @cached = true
22
+ end
23
+
24
+ def success?
25
+ !blocked?
26
+ end
27
+ end
28
+
29
+ class Cache
30
+ VERSION = 2
31
+
32
+ def initialize(options, logger:)
33
+ unless options.is_a?(Hash) && options[:file].is_a?(String) && !options[:file].strip.empty?
34
+ raise ArgumentError, 'Cache requires a file path'
35
+ end
36
+
37
+ @ttl = options[:ttl]
38
+ raise ArgumentError, 'Cache requires a positive, finite TTL in seconds' unless seconds?(@ttl)
39
+
40
+ @blocked_ttl = options[:blocked_ttl]
41
+ unless @blocked_ttl.nil? || seconds?(@blocked_ttl)
42
+ raise ArgumentError, 'Cache requires a positive, finite blocked TTL in seconds'
43
+ end
44
+
45
+ @prune = options.fetch(:prune, false)
46
+ raise ArgumentError, 'Cache prune must be true or false' unless [true, false].include?(@prune)
47
+
48
+ @file = File.expand_path(options[:file])
49
+ @logger = logger
50
+ @seen = Set.new
51
+ end
52
+
53
+ # Whether to prune entries that were not used when a run finishes.
54
+ def prune?
55
+ @prune
56
+ end
57
+
58
+ def fetch(key, uri)
59
+ @seen << key
60
+ data = read_entries[key]
61
+ return unless fresh?(data) && data['code'].is_a?(Integer)
62
+ return unless blocked?(data) ? data['code'].between?(100, 999) : data['code'].between?(200, 299)
63
+ return unless data['method'].is_a?(String) && safe_uri?(data['result_uri'])
64
+ return unless valid_redirects?(data['redirects'])
65
+
66
+ CachedResult.new(data, uri)
67
+ rescue URI::InvalidURIError
68
+ nil
69
+ end
70
+
71
+ def store(key, result)
72
+ @seen << key
73
+ return unless result.success? || (result.blocked? && @blocked_ttl)
74
+ return if URI(result.result_uri.to_s).userinfo
75
+ return if result.redirects.any? { |hop| URI(hop.uri.to_s).userinfo || URI(hop.to.to_s).userinfo }
76
+
77
+ update_entries do |entries|
78
+ entries[key] = {
79
+ 'checked_at' => Time.now.to_f,
80
+ 'method' => result.method,
81
+ 'code' => result.code,
82
+ 'result_uri' => result.result_uri.to_s,
83
+ 'redirects' => result.redirects.map { |hop| [hop.uri.to_s, hop.code, hop.to.to_s] }
84
+ }
85
+ entries[key].merge!('blocked' => true, 'challenge' => result.challenge) if result.blocked?
86
+ entries
87
+ end
88
+ rescue IOError, SystemCallError, JSON::GeneratorError
89
+ @logger.warn("Unable to write link cache #{@file}; result was not cached")
90
+ end
91
+
92
+ # Removes entries that this cache instance neither read nor wrote, and expired entries.
93
+ # Returns the number of entries removed.
94
+ def prune!
95
+ return 0 unless File.exist?(@file)
96
+
97
+ removed = 0
98
+ update_entries do |entries|
99
+ kept = entries.slice(*@seen)
100
+ removed = read_entries.size - kept.size
101
+ kept
102
+ end
103
+ @logger.info("Pruned #{removed} unused #{removed == 1 ? 'entry' : 'entries'} from link cache #{@file}")
104
+ removed
105
+ rescue IOError, SystemCallError, JSON::GeneratorError
106
+ @logger.warn("Unable to prune link cache #{@file}")
107
+ 0
108
+ end
109
+
110
+ private
111
+
112
+ # Atomically replaces the fresh entries with those returned by the block, under an exclusive lock.
113
+ def update_entries
114
+ directory = File.dirname(@file)
115
+ FileUtils.mkdir_p(directory)
116
+ File.open("#{@file}.lock", File::RDWR | File::CREAT, 0o600) do |lock|
117
+ lock.flock(File::LOCK_EX)
118
+ entries = yield(read_entries.select { |_entry_key, data| fresh?(data) })
119
+ Tempfile.create(['link-checker-', '.json'], directory) do |file|
120
+ file.write(JSON.generate('version' => VERSION, 'entries' => entries))
121
+ file.flush
122
+ File.rename(file.path, @file)
123
+ end
124
+ end
125
+ end
126
+
127
+ def seconds?(value)
128
+ value.is_a?(Numeric) && value.real? && value.finite? && value.positive?
129
+ end
130
+
131
+ def safe_uri?(value)
132
+ return false unless value.is_a?(String)
133
+
134
+ parsed = URI(value)
135
+ %w[http https].include?(parsed.scheme) && parsed.host && !parsed.userinfo
136
+ end
137
+
138
+ def valid_redirects?(redirects)
139
+ redirects.is_a?(Array) && redirects.all? do |hop|
140
+ hop.is_a?(Array) && hop.size == 3 && safe_uri?(hop[0]) && hop[1].is_a?(Integer) && safe_uri?(hop[2])
141
+ end
142
+ end
143
+
144
+ def blocked?(data)
145
+ data['blocked'] == true
146
+ end
147
+
148
+ # Successes expire after ttl and blocked results after blocked_ttl; blocked entries are stale without one.
149
+ def fresh?(data)
150
+ return false unless data.is_a?(Hash)
151
+
152
+ ttl = blocked?(data) ? @blocked_ttl : @ttl
153
+ timestamp = data['checked_at']
154
+ now = Time.now.to_f
155
+ !ttl.nil? && timestamp.is_a?(Numeric) && timestamp.finite? && timestamp <= now && now - timestamp < ttl
156
+ end
157
+
158
+ def read_entries
159
+ data = JSON.parse(File.read(@file))
160
+ return {} unless data.is_a?(Hash) && data['version'] == VERSION && data['entries'].is_a?(Hash)
161
+
162
+ data['entries']
163
+ rescue Errno::ENOENT
164
+ {}
165
+ rescue IOError, SystemCallError, JSON::ParserError
166
+ @logger.warn("Unable to read link cache #{@file}; checking links normally")
167
+ {}
168
+ end
169
+ end
170
+ end
File without changes
@@ -5,16 +5,29 @@ module LinkChecker
5
5
  include LinkChecker::Config
6
6
  include LinkChecker::Callbacks
7
7
 
8
+ # Events published once per link with its final result.
9
+ OUTCOME_EVENTS = %i[error failure success blocked].freeze
10
+
11
+ # Settings that do not change the request or response, excluded from request identity.
12
+ IDENTITY_EXCLUDED_ATTRIBUTES = %i[
13
+ logger cache deduplicate blocked_status_codes detect_challenges max_concurrency_per_host min_host_interval
14
+ rate_limit_retries rate_limit_status_codes rate_limit_backoff max_rate_limit_delay
15
+ ].freeze
16
+
8
17
  attr_reader :results
9
- attr_accessor(*Config::ATTRIBUTES)
10
18
 
11
19
  def initialize(options = {})
12
20
  LinkChecker::Config::ATTRIBUTES.each do |key|
13
- send("#{key}=", options[key] || LinkChecker.config.send(key))
21
+ send("#{key}=", options.fetch(key) { LinkChecker.config.send(key) })
14
22
  end
15
23
  raise ArgumentError, "Missing methods." if methods&.none?
16
24
  @logger ||= options[:logger] || LinkChecker::Config.logger || LinkChecker::Logger.default
17
- @results = { error: [], failure: [], success: [] } unless options.key?(:results) && !options[:results]
25
+ @results = { error: [], failure: [], success: [], blocked: [] } unless options.key?(:results) && !options[:results]
26
+ @pending = {}
27
+ @successful = {}
28
+ @host_next_start = {}
29
+ @host_backoff = Hash.new(0)
30
+ @cache_store = Cache.new(cache, logger: @logger) if cache
18
31
  end
19
32
 
20
33
  def task_klass
@@ -25,6 +38,133 @@ module LinkChecker
25
38
  end
26
39
 
27
40
  def check(uri, options = {})
41
+ return execute_check(uri, options) unless deduplicate || @cache_store
42
+
43
+ key = request_key(uri)
44
+ return execute_check(uri, options) unless key
45
+
46
+ subscriber = [uri.to_s.dup, options]
47
+ if deduplicate && (entry = @pending[key])
48
+ entry[:subscribers] << subscriber
49
+ entry[:events].each { |event, result| publish(event, copy_result(result, subscriber)) }
50
+ return
51
+ end
52
+
53
+ cached_result = @successful[key] if deduplicate
54
+ cached_result ||= @cache_store&.fetch(key, uri)
55
+ if cached_result&.success?
56
+ @successful[key] ||= cached_result if deduplicate
57
+ return publish_cached(:success, cached_result, subscriber)
58
+ end
59
+ return publish_cached(:blocked, cached_result, subscriber) if blocked_result?(cached_result)
60
+
61
+ entry = { subscribers: [subscriber], events: [] }
62
+ @pending[key] = entry if deduplicate
63
+ execute_check(uri, options) { |event, result| handle_shared_result(key, entry, uri, event, result) }
64
+ end
65
+
66
+ # Finishes a run. Checkers that queue requests run them first; Net::HTTP checks links as they are submitted.
67
+ def run
68
+ _finish_run
69
+ end
70
+
71
+ # Removes cache entries that this checker did not use, returning the number of entries removed.
72
+ def prune_cache!
73
+ @cache_store ? @cache_store.prune! : 0
74
+ end
75
+
76
+ # Whether a final, non-successful HTTP result should be reported as blocked rather than failed.
77
+ def blocked_result?(result)
78
+ return false if result.nil? || result.error? || result.success? || result.redirect?
79
+ return true if blocked_status_codes.include?(result.code)
80
+
81
+ detect_challenges && result.challenge?
82
+ end
83
+
84
+ # Request headers for uri: the user-agent, then global headers, then every matching host_headers entry.
85
+ # Later values replace earlier ones with the same case-insensitive name.
86
+ def request_headers_for(uri)
87
+ host = _host_key(uri)
88
+ sources = [{ 'User-Agent' => user_agent }, headers]
89
+ sources += host_headers.filter_map { |pattern, values| values if host && _host_match?(pattern, host) }
90
+ sources.each_with_object({}) do |values, merged|
91
+ values.each do |name, value|
92
+ merged.delete_if { |existing, _value| existing.casecmp?(name.to_s) }
93
+ merged[name.to_s] = value
94
+ end
95
+ end
96
+ end
97
+
98
+ # The host that per-host limits apply to, or nil when the URI has none.
99
+ def _host_key(uri)
100
+ URI(uri.to_s).host&.downcase
101
+ rescue URI::InvalidURIError
102
+ nil
103
+ end
104
+
105
+ # Seconds to wait before the next request to host may start, without reserving it.
106
+ def _host_wait(host)
107
+ return 0 unless host && @host_next_start[host]
108
+
109
+ [@host_next_start[host] - _monotonic_time, 0].max
110
+ end
111
+
112
+ # Reserves the next start for host, spaced by min_host_interval, and returns the seconds to wait for it.
113
+ def _reserve_host_slot(host)
114
+ return 0 unless host
115
+
116
+ wait = _host_wait(host)
117
+ @host_next_start[host] = _monotonic_time + wait + min_host_interval if min_host_interval.positive?
118
+ wait
119
+ end
120
+
121
+ # Whether a response should be retried with per-host rate limit backoff.
122
+ def rate_limited?(result)
123
+ rate_limit_retries.positive? && !result.error? && rate_limit_status_codes.include?(result.code)
124
+ end
125
+
126
+ # Pauses every request to host after a rate limited result and returns the pause in seconds.
127
+ # The pause doubles with each rate limited response from host, starting at rate_limit_backoff,
128
+ # but rate limited responses that arrive while host is already paused don't escalate it.
129
+ # Retry-After is honored as a minimum, and every pause is capped at max_rate_limit_delay.
130
+ def _rate_limit!(host, result)
131
+ return 0 unless host
132
+
133
+ @host_backoff[host] += 1 unless _host_wait(host).positive? && @host_backoff[host].positive?
134
+ delay = rate_limit_backoff * (2**(@host_backoff[host] - 1))
135
+ delay = [delay, result.retry_after_delay].max
136
+ delay = [delay, max_rate_limit_delay].min
137
+ @host_next_start[host] = [@host_next_start[host] || 0, _monotonic_time + delay].max
138
+ logger.info "Rate limited by #{host}, pausing requests for #{delay.round(2)}s"
139
+ delay
140
+ end
141
+
142
+ # Resets the backoff of host after a response that isn't rate limited.
143
+ def _rate_limit_reset!(host)
144
+ @host_backoff.delete(host) if host
145
+ end
146
+
147
+ private
148
+
149
+ def _finish_run
150
+ prune_cache! if @cache_store&.prune?
151
+ end
152
+
153
+ def _host_headers_identity
154
+ host_headers.map do |pattern, values|
155
+ [pattern.is_a?(Regexp) ? pattern.inspect : pattern, values.sort_by { |key, _value| key.to_s }]
156
+ end
157
+ end
158
+
159
+ def _host_match?(pattern, host)
160
+ pattern.is_a?(Regexp) ? pattern.match?(host) : pattern == host
161
+ end
162
+
163
+ def _monotonic_time
164
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
165
+ end
166
+
167
+ def execute_check(uri, options, &handler)
28
168
  tasks = Tasks.new(
29
169
  self,
30
170
  task_klass,
@@ -33,10 +173,65 @@ module LinkChecker
33
173
  options
34
174
  )
35
175
  tasks.on do |event, *args|
36
- results[event] << args.first if @results && %i[error failure success].include?(event)
37
- callback event, *args
176
+ handler ? handler.call(event, *args) : publish(event, args.first)
38
177
  end
39
178
  tasks.execute!
40
179
  end
180
+
181
+ def publish_cached(event, cached_result, subscriber)
182
+ result = copy_result(cached_result, subscriber)
183
+ result.cached = true
184
+ result.blocked = event == :blocked
185
+ publish(:result, result)
186
+ publish(event, result)
187
+ end
188
+
189
+ def publish(event, result)
190
+ result.checker = self
191
+ outcome = OUTCOME_EVENTS.include?(event)
192
+ results[event] << result if @results && outcome
193
+ callback(event, result)
194
+ callback(:complete, result) if outcome
195
+ end
196
+
197
+ def handle_shared_result(key, entry, uri, event, result)
198
+ entry[:events] << [event, result]
199
+ subscribers = entry[:subscribers].dup
200
+ if OUTCOME_EVENTS.include?(event)
201
+ @pending.delete(key) if @pending[key].equal?(entry)
202
+ if %i[success blocked].include?(event) && request_key(uri) == key
203
+ @successful[key] = result if deduplicate && event == :success
204
+ @cache_store&.store(key, result)
205
+ end
206
+ end
207
+ subscribers.each { |subscriber| publish(event, copy_result(result, subscriber)) }
208
+ end
209
+
210
+ def copy_result(result, subscriber)
211
+ result.dup.tap do |copy|
212
+ copy.uri = URI(subscriber.first)
213
+ # Without redirects, the final URL is the submitted one, including its own fragment.
214
+ copy.result_uri = result.redirects.empty? ? URI(subscriber.first) : result.result_uri.dup
215
+ copy.options = subscriber.last
216
+ end
217
+ end
218
+
219
+ def request_key(uri)
220
+ parsed = URI(uri.to_s)
221
+ return unless %w[http https].include?(parsed.scheme) && parsed.host && !parsed.userinfo
222
+
223
+ # Fragments are never sent over HTTP, so links that differ only by #fragment share a check.
224
+ parsed.fragment = nil
225
+
226
+ attributes = Config::ATTRIBUTES - IDENTITY_EXCLUDED_ATTRIBUTES
227
+ attributes += %i[timeout connecttimeout read_timeout open_timeout protocol].select { |key| respond_to?(key) }
228
+ settings = attributes.to_h { |key| [key, send(key)] }
229
+ settings[:headers] = headers.sort_by { |key, _value| key.to_s }
230
+ settings.delete(:host_headers)
231
+ settings[:host_headers] = _host_headers_identity if host_headers.any?
232
+ Digest::SHA256.hexdigest(JSON.generate([task_klass.name, parsed.to_s, settings]))
233
+ rescue URI::InvalidURIError, JSON::GeneratorError, TypeError
234
+ nil
235
+ end
41
236
  end
42
237
  end
@@ -8,8 +8,26 @@ module LinkChecker
8
8
  methods
9
9
  user_agent
10
10
  headers
11
+ host_headers
11
12
  logger
12
13
  retries
14
+ max_redirects
15
+ retry_status_codes
16
+ blocked_status_codes
17
+ detect_challenges
18
+ retry_after
19
+ retry_backoff
20
+ retry_jitter
21
+ max_retry_delay
22
+ respect_retry_after
23
+ deduplicate
24
+ cache
25
+ max_concurrency_per_host
26
+ min_host_interval
27
+ rate_limit_retries
28
+ rate_limit_status_codes
29
+ rate_limit_backoff
30
+ max_rate_limit_delay
13
31
  ].freeze
14
32
 
15
33
  attr_accessor(*Config::ATTRIBUTES)
@@ -18,8 +36,36 @@ module LinkChecker
18
36
  self.methods = %w[HEAD GET]
19
37
  self.user_agent = "Ruby Link Checker/#{LinkChecker::VERSION}"
20
38
  self.headers = {}
39
+ self.host_headers = {}
21
40
  self.logger = nil
22
41
  self.retries = 0
42
+ self.max_redirects = 20
43
+ self.retry_status_codes = [408, 425, 429, 500, 502, 503, 504]
44
+ self.blocked_status_codes = [401, 403, 429, 999]
45
+ self.detect_challenges = true
46
+ self.retry_after = 0
47
+ self.retry_backoff = 1
48
+ self.retry_jitter = 0
49
+ self.max_retry_delay = 60
50
+ self.respect_retry_after = false
51
+ self.deduplicate = false
52
+ self.cache = nil
53
+ self.max_concurrency_per_host = nil
54
+ self.min_host_interval = 0
55
+ self.rate_limit_retries = 2
56
+ self.rate_limit_status_codes = [429]
57
+ self.rate_limit_backoff = 1
58
+ self.max_rate_limit_delay = 30
59
+ end
60
+
61
+ def host_headers=(value)
62
+ value ||= {}
63
+ valid = value.is_a?(Hash) && value.all? do |host, host_values|
64
+ (host.is_a?(String) || host.is_a?(Regexp)) && host_values.is_a?(Hash)
65
+ end
66
+ raise ArgumentError, "Invalid host headers: #{value}" unless valid
67
+
68
+ @host_headers = value.transform_keys { |host| host.is_a?(String) ? host.downcase : host }
23
69
  end
24
70
 
25
71
  def retries=(value)
@@ -27,6 +73,101 @@ module LinkChecker
27
73
 
28
74
  @retries = value
29
75
  end
76
+
77
+ def max_redirects=(value)
78
+ raise ArgumentError, "Invalid redirect limit: #{value}" unless value.is_a?(Integer) && value >= 0
79
+
80
+ @max_redirects = value
81
+ end
82
+
83
+ def retry_status_codes=(value)
84
+ unless value.nil? || (value.is_a?(Array) && value.all? { |code| code.is_a?(Integer) && code.between?(100, 599) })
85
+ raise ArgumentError, "Invalid retry status codes: #{value}"
86
+ end
87
+
88
+ @retry_status_codes = value&.dup
89
+ end
90
+
91
+ def blocked_status_codes=(value)
92
+ unless value.nil? || (value.is_a?(Array) && value.all? { |code| code.is_a?(Integer) && code.between?(100, 999) })
93
+ raise ArgumentError, "Invalid blocked status codes: #{value}"
94
+ end
95
+
96
+ @blocked_status_codes = value&.dup || []
97
+ end
98
+
99
+ def detect_challenges=(value)
100
+ raise ArgumentError, "Invalid detect_challenges: #{value}" unless [true, false].include?(value)
101
+
102
+ @detect_challenges = value
103
+ end
104
+
105
+ def retry_after=(value)
106
+ validate_number!(:retry_after, value, 0)
107
+ @retry_after = value
108
+ end
109
+
110
+ def retry_backoff=(value)
111
+ validate_number!(:retry_backoff, value, 1)
112
+ @retry_backoff = value
113
+ end
114
+
115
+ def retry_jitter=(value)
116
+ validate_number!(:retry_jitter, value, 0)
117
+ raise ArgumentError, "Invalid retry_jitter: #{value}" if value > 1
118
+
119
+ @retry_jitter = value
120
+ end
121
+
122
+ def max_concurrency_per_host=(value)
123
+ unless value.nil? || (value.is_a?(Integer) && value.positive?)
124
+ raise ArgumentError, "Invalid concurrency limit per host: #{value}"
125
+ end
126
+
127
+ @max_concurrency_per_host = value
128
+ end
129
+
130
+ def min_host_interval=(value)
131
+ validate_number!(:min_host_interval, value, 0)
132
+ @min_host_interval = value
133
+ end
134
+
135
+ def rate_limit_retries=(value)
136
+ raise ArgumentError, "Invalid number of rate limit retries: #{value}" unless value.is_a?(Integer) && value >= 0
137
+
138
+ @rate_limit_retries = value
139
+ end
140
+
141
+ def rate_limit_status_codes=(value)
142
+ unless value.nil? || (value.is_a?(Array) && value.all? { |code| code.is_a?(Integer) && code.between?(100, 999) })
143
+ raise ArgumentError, "Invalid rate limit status codes: #{value}"
144
+ end
145
+
146
+ @rate_limit_status_codes = value&.dup || []
147
+ end
148
+
149
+ def rate_limit_backoff=(value)
150
+ validate_number!(:rate_limit_backoff, value, 0)
151
+ @rate_limit_backoff = value
152
+ end
153
+
154
+ def max_rate_limit_delay=(value)
155
+ validate_number!(:max_rate_limit_delay, value, 0)
156
+ @max_rate_limit_delay = value
157
+ end
158
+
159
+ def max_retry_delay=(value)
160
+ validate_number!(:max_retry_delay, value, 0)
161
+ @max_retry_delay = value
162
+ end
163
+
164
+ private
165
+
166
+ def validate_number!(name, value, minimum)
167
+ return if value.is_a?(Numeric) && value.real? && value.finite? && value >= minimum
168
+
169
+ raise ArgumentError, "Invalid #{name}: #{value}"
170
+ end
30
171
  end
31
172
 
32
173
  class << self
File without changes
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LinkChecker
4
+ module Errors
5
+ class ConnectionError < BaseError
6
+ TRANSIENT_CODES = %i[
7
+ couldnt_resolve_proxy couldnt_resolve_host couldnt_connect
8
+ partial_file got_nothing send_error recv_error http2 http2_stream
9
+ ].freeze
10
+
11
+ attr_reader :return_code
12
+
13
+ def initialize(return_code, message)
14
+ @return_code = return_code
15
+ super(message)
16
+ end
17
+
18
+ def error_type
19
+ TRANSIENT_CODES.include?(return_code) ? :connection : :other
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LinkChecker
4
+ module Errors
5
+ class RedirectLimitError < BaseError
6
+ attr_reader :limit, :urls
7
+
8
+ def initialize(limit, urls)
9
+ @limit = limit
10
+ @urls = urls
11
+ super("Redirect limit of #{limit} exceeded: #{urls.join(' -> ')}.")
12
+ end
13
+ end
14
+ end
15
+ end
File without changes
@@ -1,2 +1,4 @@
1
1
  require_relative 'errors/base_error'
2
2
  require_relative 'errors/redirect_loop_error'
3
+ require_relative 'errors/redirect_limit_error'
4
+ require_relative 'errors/connection_error'
File without changes
@@ -3,12 +3,14 @@ module LinkChecker
3
3
  module HTTP
4
4
  class Task < ::LinkChecker::Task
5
5
  def run!
6
- ::Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
6
+ sleep(delay) if delay.positive?
7
+ host_wait = checker._reserve_host_slot(checker._host_key(uri))
8
+ sleep(host_wait) if host_wait.positive?
9
+ ::Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
7
10
  http.read_timeout = checker.read_timeout if checker.read_timeout
8
11
  http.open_timeout = checker.open_timeout if checker.open_timeout
9
12
  request = ::Net::HTTPGenericRequest.new(method, false, true, uri)
10
- request['User-Agent'] = checker.user_agent
11
- checker.headers.each { |key, value| request[key] = value }
13
+ checker.request_headers_for(uri).each { |key, value| request[key] = value }
12
14
  response = http.request(request)
13
15
  result! Result.new(uri, method, original_uri, request, response, options)
14
16
  end
File without changes
@@ -15,7 +15,7 @@ module LinkChecker
15
15
  end
16
16
 
17
17
  def failure?
18
- !success? && !redirect?
18
+ !success? && !redirect? && !blocked?
19
19
  end
20
20
 
21
21
  def code
@@ -30,6 +30,10 @@ module LinkChecker
30
30
  request
31
31
  end
32
32
 
33
+ def response_headers
34
+ response || {}
35
+ end
36
+
33
37
  def redirect_to
34
38
  return nil unless response
35
39
 
File without changes
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LinkChecker
4
+ # A redirect hop: uri responded with code and redirected to the resolved target uri, to.
5
+ Redirect = Data.define(:uri, :code, :to) do
6
+ # Whether the hop was a permanent redirect (301 or 308).
7
+ def permanent?
8
+ [301, 308].include?(code)
9
+ end
10
+ end
11
+ end