ruby-link-checker 0.5.1 → 0.6.1

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 (68) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +23 -0
  3. data/README.md +150 -19
  4. data/UPGRADING.md +46 -0
  5. data/lib/ruby-link-checker/async/http/checker.rb +19 -6
  6. data/lib/ruby-link-checker/async/http/result.rb +1 -1
  7. data/lib/ruby-link-checker/cache.rb +90 -21
  8. data/lib/ruby-link-checker/checker.rb +141 -14
  9. data/lib/ruby-link-checker/config.rb +79 -0
  10. data/lib/ruby-link-checker/net/http/checker.rb +3 -2
  11. data/lib/ruby-link-checker/net/http/result.rb +1 -1
  12. data/lib/ruby-link-checker/redirect.rb +11 -0
  13. data/lib/ruby-link-checker/result.rb +96 -1
  14. data/lib/ruby-link-checker/tasks.rb +24 -12
  15. data/lib/ruby-link-checker/typhoeus/hydra/checker.rb +59 -11
  16. data/lib/ruby-link-checker/typhoeus/hydra/result.rb +1 -1
  17. data/lib/ruby-link-checker/version.rb +1 -1
  18. data/lib/ruby-link-checker.rb +1 -0
  19. metadata +18 -51
  20. data/.github/workflows/coverage.yml +0 -24
  21. data/.github/workflows/danger-comment.yml +0 -17
  22. data/.github/workflows/danger.yml +0 -12
  23. data/.github/workflows/lint.yml +0 -20
  24. data/.github/workflows/release.yml +0 -14
  25. data/.github/workflows/test.yml +0 -25
  26. data/.gitignore +0 -6
  27. data/.rspec +0 -2
  28. data/.rubocop.yml +0 -26
  29. data/.rubocop_todo.yml +0 -332
  30. data/AGENTS.md +0 -23
  31. data/CONTRIBUTING.md +0 -129
  32. data/Dangerfile +0 -6
  33. data/Gemfile +0 -27
  34. data/RELEASING.md +0 -37
  35. data/Rakefile +0 -26
  36. data/benchmarks/check.rb +0 -38
  37. data/benchmarks/data/opensearch.org/links.txt +0 -4270
  38. data/benchmarks/data/opensearch.org/small.txt +0 -100
  39. data/ruby-link-checker.gemspec +0 -22
  40. data/spec/fixtures/200.yml +0 -65
  41. data/spec/fixtures/301_200.yml +0 -102
  42. data/spec/fixtures/301_301.yml +0 -114
  43. data/spec/fixtures/301_400_301_200.yml +0 -185
  44. data/spec/fixtures/301_403.yml +0 -78
  45. data/spec/fixtures/308_429.yml +0 -108
  46. data/spec/fixtures/404.yml +0 -57
  47. data/spec/fixtures/404_200.yml +0 -89
  48. data/spec/fixtures/404_404.yml +0 -81
  49. data/spec/fixtures/429_200.yml +0 -135
  50. data/spec/fixtures/429_429_200.yml +0 -201
  51. data/spec/ruby-link-checker/async/http/checker_spec.rb +0 -184
  52. data/spec/ruby-link-checker/callbacks_spec.rb +0 -76
  53. data/spec/ruby-link-checker/checker_spec.rb +0 -97
  54. data/spec/ruby-link-checker/config_spec.rb +0 -45
  55. data/spec/ruby-link-checker/errors/redirect_loop_error_spec.rb +0 -18
  56. data/spec/ruby-link-checker/net/http/checker_spec.rb +0 -93
  57. data/spec/ruby-link-checker/result_error_spec.rb +0 -34
  58. data/spec/ruby-link-checker/result_spec.rb +0 -41
  59. data/spec/ruby-link-checker/task_spec.rb +0 -20
  60. data/spec/ruby-link-checker/tasks_spec.rb +0 -91
  61. data/spec/ruby-link-checker/typhoeus/hydra/checker_spec.rb +0 -180
  62. data/spec/ruby-link-checker/version_spec.rb +0 -9
  63. data/spec/spec_helper.rb +0 -19
  64. data/spec/support/config.rb +0 -8
  65. data/spec/support/link_checker.rb +0 -609
  66. data/spec/support/vcr.rb +0 -13
  67. data/spec/support/with_result.rb +0 -15
  68. data/spec/support/with_url.rb +0 -14
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 54db300e7891f1cf05b6f0cee2ad9ed00694a7057e8e4cdbd8cdf73ebe430da6
4
- data.tar.gz: 5cbf0243b4032cd7feb1624a56c192e7439574c46ea6932df8ddcf5b3e1ccf18
3
+ metadata.gz: d39534bd64245b18ca425097d7ee4dbe9946cbddc32e25bfe8928c8210b50735
4
+ data.tar.gz: e3732fd4400612e1b67458e20772fcf67ce1c4b3134fd555a63aebcefb458ac8
5
5
  SHA512:
6
- metadata.gz: 9823f6b88d45a45a9ed566a307aa5dd4b10c8299c7952b906ec96c17489128361566ebfec4e97fe577588408d6ac9aa5cab35aa99630351d53c51a8e2b5919f6
7
- data.tar.gz: cd91f12a7ce839f698be56f7d740d3f1a02d6b92ea3f2ce9fc3f5dff06955a6f33d412b1604afd5d6ce51e9f1fb34d5af9159bf9db02c866d1bdaa3acd7f6893
6
+ metadata.gz: '09b1ba24a8340d78c998503acc0fb7c9e54309b070a42a87ec03b4f7a8889f5a34777562896dead599728acf2a669a376c56c774c3d89f01cd648d973ac0b2b5'
7
+ data.tar.gz: cd7a8b47ed981eee09db624f2f25647a70634f617942db0a841973fa87200223e32d6b7f2f971e66aed13c59a6c288e554c89d71dde87d16b541f8a137c73f4b
data/CHANGELOG.md CHANGED
@@ -1,3 +1,26 @@
1
+ ### 0.6.1 (2026/11/23)
2
+
3
+ * [#56](https://github.com/dblock/ruby-link-checker/pull/56): Fixed `host_headers` invalidating cached results for every URL; only URLs whose headers changed are rechecked - [@dblock](https://github.com/dblock).
4
+
5
+ ### 0.6.0 (2026/11/22)
6
+
7
+ * [#31](https://github.com/dblock/ruby-link-checker/pull/31): Updated ruby-gem-release to 0.5.0 - [@dblock](https://github.com/dblock), [@Copilot](https://github.com/Copilot).
8
+ * [#38](https://github.com/dblock/ruby-link-checker/pull/38): Added `blocked_status_codes` (default `[401, 403, 429, 999]`) and `detect_challenges` (enabled by default, recognizes Cloudflare's `cf-mitigated: challenge`) to report links blocked by bot walls as `:blocked` instead of `:failure`; set `blocked_status_codes: []` and `detect_challenges: false` to restore the previous behavior - [@dblock](https://github.com/dblock).
9
+ * [#39](https://github.com/dblock/ruby-link-checker/pull/39): Added a `:complete` event published once per link with its final result and documented which events fire per attempt and which fire once per link - [@dblock](https://github.com/dblock).
10
+ * [#40](https://github.com/dblock/ruby-link-checker/pull/40): Added `max_concurrency_per_host` and `min_host_interval` to limit concurrent and back-to-back requests to the same host - [@dblock](https://github.com/dblock).
11
+ * [#42](https://github.com/dblock/ruby-link-checker/pull/42): Added `host_headers` to send headers to specific hosts, chosen per redirect hop so that credentials are not forwarded to other hosts - [@dblock](https://github.com/dblock).
12
+ * [#43](https://github.com/dblock/ruby-link-checker/pull/43): Added `result.redirects` and `result.permanent_redirect?` with the redirect hops that led to a final result, persisted in the cache - [@dblock](https://github.com/dblock).
13
+ * [#44](https://github.com/dblock/ruby-link-checker/pull/44): Added an optional `blocked_ttl` cache setting to reuse blocked results for a shorter period than successes - [@dblock](https://github.com/dblock).
14
+ * [#46](https://github.com/dblock/ruby-link-checker/pull/46): Added per-host exponential backoff for rate-limited (429) responses with `rate_limit_retries` (default `2`, `0` disables), `rate_limit_backoff`, `max_rate_limit_delay`, and `rate_limit_status_codes`, honoring `Retry-After` - [@dblock](https://github.com/dblock).
15
+ * [#47](https://github.com/dblock/ruby-link-checker/pull/47): Added a logo and wordmark, excluded from the gem package - [@dblock](https://github.com/dblock).
16
+ * [#48](https://github.com/dblock/ruby-link-checker/pull/48): Updated ruby-gem-release to 0.9.0, added Commonmarker for Markdown changelogs, and added a release dry run - [@dblock](https://github.com/dblock).
17
+ * [#49](https://github.com/dblock/ruby-link-checker/pull/49): Fixed loading the gem on Ruby 4.0 by declaring the `logger` dependency, and added a `Package` workflow that installs the built gem in a clean environment - [@dblock](https://github.com/dblock).
18
+ * [#50](https://github.com/dblock/ruby-link-checker/pull/50): Ignored URL fragments in deduplication and cache identity, so links that differ only by `#fragment` share one check - [@dblock](https://github.com/dblock).
19
+ * [#51](https://github.com/dblock/ruby-link-checker/pull/51): Added `result.outcome`, a stable `result.reason`, and a serializable `result.to_h` - [@dblock](https://github.com/dblock).
20
+ * [#52](https://github.com/dblock/ruby-link-checker/pull/52): Added cache pruning with `cache: { prune: true }` and `checker.prune_cache!` to remove entries for links that are no longer checked - [@dblock](https://github.com/dblock).
21
+ * [#53](https://github.com/dblock/ruby-link-checker/pull/53): Packaged only the library and its documentation, disabled the local Bundler `rake release` tasks, pinned the release workflow to a commit, updated `actions/checkout`, and removed the `git` pin now that Danger supports git 6 - [@dblock](https://github.com/dblock).
22
+ * [#54](https://github.com/dblock/ruby-link-checker/pull/54): Added UPGRADING.md with instructions for upgrading to 0.6.0 - [@dblock](https://github.com/dblock).
23
+
1
24
  ### 0.5.1 (2026/11/08)
2
25
 
3
26
  * [#30](https://github.com/dblock/ruby-link-checker/pull/30): Updated ruby-gem-release to 0.3.1 - [@dblock](https://github.com/dblock), [@Copilot](https://github.com/Copilot).
data/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ <img alt="ruby-link-checker" src="assets/logo.svg" width="128">
2
+
1
3
  Fast Ruby Link Checker
2
4
  ======================
3
5
 
@@ -22,6 +24,9 @@ A fast Ruby link checker with support for multiple HTTP libraries. Does not pars
22
24
  - [Redirects](#redirects)
23
25
  - [Retry After](#retry-after)
24
26
  - [Retry Policy](#retry-policy)
27
+ - [Rate Limits](#rate-limits)
28
+ - [Blocked Results](#blocked-results)
29
+ - [Per-Host Limits](#per-host-limits)
25
30
  - [Results](#results)
26
31
  - [Methods](#methods)
27
32
  - [Deduplication](#deduplication)
@@ -192,7 +197,7 @@ checker = LinkChecker::Async::HTTP::Checker.new(max_concurrency: 25)
192
197
 
193
198
  #### [LinkChecker::Net::HTTP](lib/ruby-link-checker/net/http/checker.rb)
194
199
 
195
- Slow, sequential checker.
200
+ Slow, sequential checker. It checks each link when it's submitted; call `checker.run` afterwards to finish the run, for example to [prune the cache](#caching).
196
201
 
197
202
  ```ruby
198
203
  require 'net/http'
@@ -228,7 +233,7 @@ end
228
233
 
229
234
  #### Retries
230
235
 
231
- By default link checkers do not retry. Set `retries` to enable retries for transient connection errors/timeouts and HTTP statuses 408, 425, 429, 500, 502, 503, and 504. Permanent HTTP failures and invalid URLs are not retried. HEAD-to-GET fallback still applies independently of the retry policy. The retry budget is shared across methods: with `retries: 2`, repeated transient failures produce `HEAD`, `HEAD`, `HEAD`, then `GET`.
236
+ By default link checkers only retry [rate-limited responses](#rate-limits). Set `retries` to enable retries for transient connection errors/timeouts and HTTP statuses 408, 425, 429, 500, 502, 503, and 504. Permanent HTTP failures and invalid URLs are not retried. HEAD-to-GET fallback still applies independently of the retry policy. The retry budget is shared across methods: with `retries: 2`, repeated transient failures produce `HEAD`, `HEAD`, `HEAD`, then `GET`.
232
237
 
233
238
  ```ruby
234
239
  checker = LinkChecker::Net::HTTP::Checker.new(retries: 1)
@@ -242,6 +247,14 @@ Checkers follow up to 20 redirects per attempt and detect redirect loops. Relati
242
247
  checker = LinkChecker::Typhoeus::Hydra::Checker.new(max_redirects: 10)
243
248
  ```
244
249
 
250
+ Final results expose the redirect hops that led to them as `result.redirects`, oldest first, each a `LinkChecker::Redirect` with the responding `uri`, its status `code`, the resolved target `to`, and `permanent?` for 301 and 308. Use `result.permanent_redirect?` to suggest updating links that moved permanently. Only the hops of the final attempt are included: when `HEAD` fails after redirects and `GET` is tried, `redirects` lists the `GET` hops. Redirect loop and limit errors include the hops that led to them.
251
+
252
+ ```ruby
253
+ checker.on :success do |result|
254
+ puts "#{result.uri} moved permanently to #{result.result_uri}" if result.permanent_redirect?
255
+ end
256
+ ```
257
+
245
258
  #### Retry After
246
259
 
247
260
  Set `retry_after` to a minimum delay in seconds (default `0`). Optional `retry_backoff` multiplies that delay on successive retries (default `1`), and `retry_jitter` adds a random fraction between `0` and the configured value (default `0`, maximum `1`). All delays are capped by `max_retry_delay` (default `60` seconds).
@@ -267,16 +280,68 @@ Customize `retry_status_codes` to choose retryable HTTP statuses. Set it to `nil
267
280
  checker = LinkChecker::Net::HTTP::Checker.new(retries: 1, retry_status_codes: [429, 503])
268
281
  ```
269
282
 
283
+ #### Rate Limits
284
+
285
+ Rate-limited responses (429 Too Many Requests) are retried with exponential backoff per host, on their own budget, independently of `retries`. A rate-limited response pauses every later request to the same host, not just the retried one, for `rate_limit_backoff` seconds (default `1`), doubling with each further rate-limited response from that host (1s, 2s, 4s, ...). A `Retry-After` header that asks for longer is honored, and every pause is capped at `max_rate_limit_delay` seconds (default `30`). Rate-limited responses that arrive while the host is already paused, such as the rest of a burst, don't increase the backoff, and any response from the host that isn't rate limited resets it.
286
+
287
+ Each link is retried up to `rate_limit_retries` times (default `2`) when rate limited. After that, the general [retry policy](#retry-policy) applies, and a link that's still rate limited is reported as [blocked](#blocked-results) (or failed if 429 isn't in `blocked_status_codes`). Set `rate_limit_retries: 0` to disable rate limit backoff entirely.
288
+
289
+ ```ruby
290
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(
291
+ rate_limit_retries: 3,
292
+ rate_limit_backoff: 2,
293
+ max_rate_limit_delay: 60,
294
+ rate_limit_status_codes: [429, 503]
295
+ )
296
+ ```
297
+
298
+ Use `rate_limit_status_codes` (default `[429]`) to treat other statuses, such as 503, as rate limits. Pauses use the same per-host scheduling as [per-host limits](#per-host-limits): Hydra holds back requests to a paused host until the active batch drains, but can't recall requests it already started, so combine rate limit backoff with `max_concurrency_per_host` to keep bursts small. Rate limit retries publish `:retry` like other retries.
299
+
300
+ #### Blocked Results
301
+
302
+ Bot protection often answers automated requests with 401, 403, 429, or a non-standard status, such as LinkedIn's 999, even though the page exists. By default, checkers report links with those final status codes as blocked (unverified) instead of failed. Customize `blocked_status_codes` (default `[401, 403, 429, 999]`) to choose the statuses, or set it to `[]` to report them as failures, as versions before 0.6.0 did.
303
+
304
+ ```ruby
305
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(
306
+ blocked_status_codes: [403, 999]
307
+ )
308
+
309
+ checker.on :blocked do |result|
310
+ puts "UNVERIFIED: #{result}" # result.blocked? == true, result.failure? == false
311
+ end
312
+ ```
313
+
314
+ A link is blocked when its final result, after retries, redirects, and the `HEAD` to `GET` fallback, has one of those status codes. Blocked results publish `:blocked` instead of `:failure` and are collected in `results[:blocked]`. Retries still apply first, so a 429 that is in `retry_status_codes` is retried before being reported as blocked. Errors, such as timeouts, are never blocked. Blocked results are only cached with a [`blocked_ttl`](#caching).
315
+
316
+ By default, `detect_challenges` also reports non-successful responses that carry a known bot challenge as blocked, whatever their status code. Combined with a narrower `blocked_status_codes`, such as `[]`, this lets an ordinary 403 remain a failure while a challenged one is blocked. Challenge detection currently recognizes Cloudflare's [`cf-mitigated: challenge`](https://developers.cloudflare.com/cloudflare-challenges/challenge-types/challenge-pages/detect-response/) response header. Set `detect_challenges: false` to report challenged responses as failures.
317
+
318
+ ```ruby
319
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(detect_challenges: false)
320
+ ```
321
+
322
+ #### Per-Host Limits
323
+
324
+ Many links to the same host arrive as one burst, which bot protection and rate limits react to. Set `max_concurrency_per_host` to bound the requests in flight to one host (default `nil`, unlimited), and `min_host_interval` to the minimum number of seconds between the starts of consecutive requests to one host (default `0`). Hosts are compared case-insensitively, ignoring scheme and port, and the limits apply to every request, including redirects and retries.
325
+
326
+ ```ruby
327
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(
328
+ max_concurrency_per_host: 2,
329
+ min_host_interval: 0.5
330
+ )
331
+ ```
332
+
333
+ Limits per host apply in addition to the global `max_concurrency` of `LinkChecker::Async::HTTP` and Hydra's `max_concurrency`. Hydra holds requests per host and hands them to Hydra as slots free up; requests that must wait for `min_host_interval` are handed over once the active batch drains, like delayed retries, so actual intervals can exceed the minimum. `LinkChecker::Net::HTTP` is sequential, so only `min_host_interval` changes its behavior. Neither setting affects [deduplication](#deduplication) or [caching](#caching) identity.
334
+
270
335
  #### Results
271
336
 
272
337
  By default checkers collect results.
273
338
 
274
339
  ```ruby
275
- checker = LinkChecker::Net::HTTP::Checker.new(results: false)
340
+ checker = LinkChecker::Net::HTTP::Checker.new
276
341
  ...
277
342
  checker.run
278
343
 
279
- checker.results # => { error: [...], failure: [...], success: [...] }
344
+ checker.results # => { error: [...], failure: [...], success: [...], blocked: [...] }
280
345
  ```
281
346
 
282
347
  You can disable this with `results: false`.
@@ -310,11 +375,20 @@ checker.check('https://www.example.org', location: 'two.html')
310
375
  checker.run # one check, two sets of result events
311
376
  ```
312
377
 
313
- Identity includes the complete URL (including query values and fragment), transport, methods, headers, user-agent, and request-related settings. Changing those settings prevents reuse. URLs containing user-info credentials bypass deduplication and caching.
378
+ Identity includes the URL with its query values, but not its `#fragment`, which is never sent to the server, so links that differ only by fragment share one check. Each submission's results still report its own URL, fragment included. Identity also includes the transport, methods, headers, host headers, user-agent, and request-related settings. Changing those settings prevents reuse. URLs containing user-info credentials bypass deduplication and caching.
314
379
 
315
380
  #### Caching
316
381
 
317
- Persistent success caching is disabled by default. Enable it with an explicit file path and positive TTL in seconds. Recent successful checks can then be reused across checker instances; failures and errors are never stored. Cache writes are atomic and locked, and unreadable or malformed files fall back to normal checking.
382
+ Persistent success caching is disabled by default. Enable it with an explicit file path and positive TTL in seconds. Recent successful checks can then be reused across checker instances; failures and errors are never stored.
383
+
384
+ Add an optional `blocked_ttl` in seconds to also reuse [blocked results](#blocked-results) for a shorter period, so that bot-walled hosts aren't requested on every run but are still rechecked regularly. Blocked results are not cached without it. A cached blocked result is reused only while the checker's `blocked_status_codes` or `detect_challenges` still classify it as blocked; otherwise the link is checked again. Cache hits for blocked results emit `:result`, `:blocked`, and `:complete` with `cached? == true`.
385
+
386
+ ```ruby
387
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(
388
+ blocked_status_codes: [401, 403, 429, 999],
389
+ cache: { file: 'tmp/link-checker/cache.json', ttl: 7 * 24 * 3600, blocked_ttl: 24 * 3600 }
390
+ )
391
+ ``` Cache writes are atomic and locked, and unreadable or malformed files fall back to normal checking.
318
392
 
319
393
  ```ruby
320
394
  checker = LinkChecker::Typhoeus::Hydra::Checker.new(
@@ -323,7 +397,15 @@ checker = LinkChecker::Typhoeus::Hydra::Checker.new(
323
397
  )
324
398
  ```
325
399
 
326
- Each cache hit emits `:result` and `:success` with the new submission's metadata and `cached? == true`. Persistent hits return `LinkChecker::CachedResult` with the HTTP method, status, original/final URIs, and metadata; native request/response objects and headers are not persisted. Redirect targets containing user-info credentials are not written. Add the cache directory to your ignore rules.
400
+ Each cache hit emits `:result` and `:success` with the new submission's metadata and `cached? == true`. Persistent hits return `LinkChecker::CachedResult` with the HTTP method, status, original/final URIs, redirect hops, and metadata; native request/response objects and headers are not persisted. Results whose final URL or any redirect hop contains user-info credentials are not written. Cache files written by versions before 0.6.0 are ignored and rewritten. Add the cache directory to your ignore rules.
401
+
402
+ Entries for links that are no longer checked stay in the cache file until they expire. Set `prune: true` to remove every entry that the checker didn't use when `checker.run` finishes, or call `checker.prune_cache!`, which returns the number of entries removed. Pruning is off by default: enable it only when each run checks every link that should stay cached, not for partial runs, such as incremental builds, and not with a cache file shared by checkers that check different links.
403
+
404
+ ```ruby
405
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(
406
+ cache: { file: 'tmp/link-checker/cache.json', ttl: 7 * 24 * 3600, prune: true }
407
+ )
408
+ ```
327
409
 
328
410
  Caching alone does not coalesce in-flight checks. With deduplication enabled, successful results remain reusable within that checker even after the persistent TTL expires. Cached successes do not replay historical redirect/retry events.
329
411
 
@@ -357,6 +439,20 @@ checker = LinkChecker::Net::HTTP::Checker.new(
357
439
  )
358
440
  ```
359
441
 
442
+ Set `host_headers` to add or replace headers for specific hosts, on top of the global `headers`. Keys are an exact host name (case-insensitive) or a `Regexp` matched against the lower-cased host. Every matching entry applies, in order, and replaces earlier values with the same case-insensitive name, including `User-Agent`.
443
+
444
+ ```ruby
445
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(
446
+ host_headers: {
447
+ 'www.npmjs.com' => { 'Accept' => 'text/html' },
448
+ 'api.github.com' => { 'Authorization' => "Bearer #{ENV.fetch('GITHUB_TOKEN')}" },
449
+ /(\A|\.)medium\.com\z/ => { 'Cookie' => 'consent=1' }
450
+ }
451
+ )
452
+ ```
453
+
454
+ Host headers are chosen for each request from that request's own host, including every redirect hop, so a token configured for one host is never sent to a different host that it redirects to. Global `headers` are sent to every host, including redirect targets. The headers sent for a URL, global headers merged with its matching host headers, are part of its [deduplication](#deduplication) and [caching](#caching) identity: the cache file stores a hash of them, not the values themselves. Changing the host headers of one host only invalidates cached results for the URLs on the hosts it matches.
455
+
360
456
  ### Global Configuration
361
457
 
362
458
  All options can also be configured globally.
@@ -375,8 +471,8 @@ end
375
471
  Events enable processing of results as they become available.
376
472
 
377
473
  ```ruby
378
- checker.on :result do |result|
379
- puts result # any result
474
+ checker.on :complete do |result|
475
+ puts result # the final result of each link
380
476
  end
381
477
 
382
478
  checker.on :error, :failure do |result|
@@ -384,15 +480,33 @@ checker.on :error, :failure do |result|
384
480
  end
385
481
  ```
386
482
 
387
- Checkers support the following events.
388
-
389
- | Event | Description |
390
- |----------|----------------------------------------------------------------|
391
- | :retry | A request is being retried on failure or error. |
392
- | :result | A new result, any of success, failure, or error. |
393
- | :success | A valid URL, usually a 2xx response from the server. |
394
- | :failure | A failed URL, usually a 4xx or a 5xx response from the server. |
395
- | :error | An error, such as an invalid URL or a network timeout. |
483
+ Some events fire once per attempt, others fire once per link with its final result. Subscribe to `:complete`, or to the outcome events, to report links: `:result` also fires for each redirect hop and for a failed `HEAD` that is followed by a `GET`, so treating every `:result` that isn't a success as a broken link reports redirects and fallbacks as broken.
484
+
485
+ | Event | Fires | Description |
486
+ |-----------|------------------------|--------------------------------------------------------------------------|
487
+ | :result | Once per attempt | A new response or error, including redirects and attempts that are retried or followed by another method. |
488
+ | :redirect | Once per redirect hop | A redirect response that is being followed. |
489
+ | :retry | Once per retry | A request is being retried on failure or error. |
490
+ | :success | Once per link (final) | A valid URL, usually a 2xx response from the server. |
491
+ | :failure | Once per link (final) | A failed URL, usually a 4xx or a 5xx response from the server. |
492
+ | :blocked | Once per link (final) | A URL blocked by bot protection, see [Blocked Results](#blocked-results). |
493
+ | :error | Once per link (final) | An error, such as an invalid URL or a network timeout. |
494
+ | :complete | Once per link (final) | The final result, after the outcome event, whatever the outcome. |
495
+
496
+ Exactly one of `:success`, `:failure`, `:blocked`, or `:error` fires for each checked link, followed by `:complete` with the same result. For example, checking a URL that redirects once to a page that answers `HEAD` with 405 and `GET` with 200 publishes the following events, in order.
497
+
498
+ | Event | Method | Code |
499
+ |-----------|--------|------|
500
+ | :result | HEAD | 301 |
501
+ | :redirect | HEAD | 301 |
502
+ | :result | HEAD | 405 |
503
+ | :result | GET | 301 |
504
+ | :redirect | GET | 301 |
505
+ | :result | GET | 200 |
506
+ | :success | GET | 200 |
507
+ | :complete | GET | 200 |
508
+
509
+ Cache hits publish `:result`, `:success`, and `:complete`. With [deduplication](#deduplication), every submission of a URL receives its own copy of each event.
396
510
 
397
511
  Events are called with results, which contain the following properties.
398
512
 
@@ -408,6 +522,23 @@ Events are called with results, which contain the following properties.
408
522
  | :error_type | `:timeout`, `:connection`, or `:other` for errors; otherwise `nil`. |
409
523
  | :response_headers | Response headers, accessible using `[]`. |
410
524
  | :cached? | Whether this result was reused from a successful check. |
525
+ | :blocked? | Whether this final result was reported as blocked. |
526
+ | :redirects | The redirect hops that led to this result, see [Redirects](#redirects). |
527
+ | :permanent_redirect? | Whether any of those hops was a permanent redirect (301 or 308). |
528
+
529
+ | :outcome | `:success`, `:failure`, `:blocked`, or `:error` for a final result, `:redirect` for a redirect hop. |
530
+ | :reason | A stable explanation of the outcome, see below. |
531
+ | :to_h | A serializable summary of the result, see below. |
532
+
533
+ `result.reason` is one of `HTTP <status>` (such as `HTTP 404` or `HTTP 403`), `<name> challenge (HTTP <status>)` for an unsuccessful response that carries a known bot challenge (such as `Cloudflare challenge (HTTP 403)`), `Timeout`, `Connection error`, `Redirect loop`, `Too many redirects`, `Invalid URL`, or `Error (<class name>)` for other errors.
534
+
535
+ `result.to_h` returns a hash with the `url`, `result_url`, `method`, `code` (an integer, or `nil` for errors), `outcome`, `reason`, `redirects` (each with `url`, `code`, and `to`), `permanent_redirect`, `blocked`, `challenge` (the name of a detected bot challenge, such as `Cloudflare`, or `nil`), `cached`, `error` (the error message), `error_type`, and the `options` passed to `check`. It's suitable for JSON reports when those options are.
536
+
537
+ ```ruby
538
+ checker.on :complete do |result|
539
+ puts JSON.generate(result.to_h) unless result.success?
540
+ end
541
+ ```
411
542
 
412
543
  See [result.rb](lib/ruby-link-checker/result.rb) for more details.
413
544
 
@@ -423,7 +554,7 @@ Anecdotal results show `LinkChecker::Async::HTTP` using significantly less CPU t
423
554
 
424
555
  ## Contributing
425
556
 
426
- You're encouraged to contribute to ruby-link-checker. See [CONTRIBUTING](CONTRIBUTING.md) for details.
557
+ You're encouraged to contribute to ruby-link-checker. See [CONTRIBUTING](CONTRIBUTING.md) for details, [CHANGELOG](CHANGELOG.md) for changes, [UPGRADING](UPGRADING.md) for upgrade instructions, and [RELEASING](RELEASING.md) for how releases are made.
427
558
 
428
559
  ## Copyright and License
429
560
 
data/UPGRADING.md ADDED
@@ -0,0 +1,46 @@
1
+ # Upgrading ruby-link-checker
2
+
3
+ ## Upgrading to 0.6.0
4
+
5
+ ### Blocked Results
6
+
7
+ Links whose final response is 401, 403, 429, or 999, or carries a known bot challenge, such as Cloudflare's `cf-mitigated: challenge`, are now reported as blocked instead of failed. They publish `:blocked` instead of `:failure`, have `blocked? == true` and `failure? == false`, and are collected in `results[:blocked]`, a new key in the results hash.
8
+
9
+ If you fail a build on `:failure` or `results[:failure]`, decide whether blocked links should fail it too, and handle `:blocked` or subscribe to `:complete`, which fires once per link with any outcome. To restore the previous behavior, report blocked links as failures:
10
+
11
+ ```ruby
12
+ LinkChecker.configure do |config|
13
+ config.blocked_status_codes = []
14
+ config.detect_challenges = false
15
+ end
16
+ ```
17
+
18
+ See [Blocked Results](README.md#blocked-results) for details.
19
+
20
+ ### Rate Limits
21
+
22
+ Rate-limited responses (429) are now retried up to twice by default, with exponential backoff per host that honors `Retry-After`, even when `retries` is `0`. A rate-limited link can take about 3 more seconds to report, and other links to the same host wait during the backoff. To restore the previous behavior, disable it:
23
+
24
+ ```ruby
25
+ LinkChecker.configure do |config|
26
+ config.rate_limit_retries = 0
27
+ end
28
+ ```
29
+
30
+ See [Rate Limits](README.md#rate-limits) for details.
31
+
32
+ ### Events
33
+
34
+ A new `:complete` event fires once per link with its final result. `:result` still fires for every attempt, including redirect hops and a failed `HEAD` before a `GET`. If you report links from `:result`, switch to `:complete` or the outcome events. See [Callbacks and Events](README.md#callbacks-and-events).
35
+
36
+ ### Caching
37
+
38
+ The cache file format changed to store redirect hops and blocked results. Caches written by earlier versions are ignored and rewritten, so the first run after upgrading checks every link again. Links that differ only by `#fragment` now share one cache entry and one check.
39
+
40
+ ### LinkChecker::Net::HTTP
41
+
42
+ `LinkChecker::Net::HTTP::Checker` now responds to `run`, which finishes a run, for example to [prune the cache](README.md#caching). Links are still checked as they are submitted, so calling `run` is optional unless you prune the cache automatically.
43
+
44
+ ### Ruby 4.0
45
+
46
+ The gem now declares its `logger` dependency, which Ruby 4.0 no longer includes by default. Earlier versions failed to load on Ruby 4.0 unless another gem in the bundle depended on `logger`.
@@ -3,7 +3,7 @@ module LinkChecker
3
3
  module HTTP
4
4
  class Task < ::LinkChecker::Task
5
5
  def run!
6
- checker._queue(delay: delay) { _run! }
6
+ checker._queue(delay: delay, host: checker._host_key(uri)) { _run! }
7
7
  end
8
8
 
9
9
  private
@@ -11,7 +11,7 @@ module LinkChecker
11
11
  def _run!
12
12
  client = checker._client_for(uri)
13
13
  headers = ::Protocol::HTTP::Headers[
14
- [['user-agent', checker.user_agent]] + checker.headers.map { |key, value| [key, value] }
14
+ checker.request_headers_for(uri).map { |key, value| [key.downcase, value] }
15
15
  ]
16
16
  request = ::Protocol::HTTP::Request[method, uri.request_uri, headers]
17
17
  response = _call(client, request)
@@ -42,6 +42,7 @@ module LinkChecker
42
42
  end
43
43
  @queue = []
44
44
  @clients = {}
45
+ @host_semaphores = {}
45
46
  if max_concurrency && (!max_concurrency.is_a?(Integer) || max_concurrency < 1)
46
47
  raise ArgumentError, "Invalid concurrency limit: #{max_concurrency}"
47
48
  end
@@ -58,20 +59,26 @@ module LinkChecker
58
59
  @semaphore = ::Async::Semaphore.new(max_concurrency) if max_concurrency
59
60
  _flush!
60
61
  end
62
+ _finish_run
61
63
  ensure
62
64
  @barrier = nil
63
65
  @semaphore = nil
66
+ @host_semaphores = {}
64
67
  _close_clients!
65
68
  end
66
69
 
67
- def _queue(delay: 0, &block)
70
+ def _queue(delay: 0, host: nil, &block)
68
71
  if @barrier
69
72
  @barrier.async do
70
73
  sleep(delay) if delay.positive?
71
- @semaphore ? @semaphore.acquire(&block) : block.call
74
+ _with_host_limit(host) do
75
+ host_wait = _reserve_host_slot(host)
76
+ sleep(host_wait) if host_wait.positive?
77
+ @semaphore ? @semaphore.acquire(&block) : block.call
78
+ end
72
79
  end
73
80
  else
74
- @queue << [delay, block]
81
+ @queue << [delay, host, block]
75
82
  end
76
83
  end
77
84
 
@@ -105,7 +112,13 @@ module LinkChecker
105
112
  def _flush!
106
113
  queue = @queue
107
114
  @queue = []
108
- queue.each { |delay, block| _queue(delay: delay, &block) }
115
+ queue.each { |delay, host, block| _queue(delay: delay, host: host, &block) }
116
+ end
117
+
118
+ def _with_host_limit(host, &)
119
+ return yield unless host && max_concurrency_per_host
120
+
121
+ (@host_semaphores[host] ||= ::Async::Semaphore.new(max_concurrency_per_host)).acquire(&)
109
122
  end
110
123
 
111
124
  def _close_clients!
@@ -43,7 +43,7 @@ module LinkChecker
43
43
  end
44
44
 
45
45
  def failure?
46
- !success? && !redirect?
46
+ !success? && !redirect? && !blocked?
47
47
  end
48
48
 
49
49
  def code
@@ -8,21 +8,26 @@ require 'uri'
8
8
 
9
9
  module LinkChecker
10
10
  class CachedResult < Result
11
- attr_reader :code
11
+ attr_reader :code, :challenge
12
12
 
13
13
  def initialize(data, uri)
14
14
  @code = data.fetch('code')
15
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)
16
21
  @cached = true
17
22
  end
18
23
 
19
24
  def success?
20
- true
25
+ !blocked?
21
26
  end
22
27
  end
23
28
 
24
29
  class Cache
25
- VERSION = 1
30
+ VERSION = 2
26
31
 
27
32
  def initialize(options, logger:)
28
33
  unless options.is_a?(Hash) && options[:file].is_a?(String) && !options[:file].strip.empty?
@@ -30,21 +35,33 @@ module LinkChecker
30
35
  end
31
36
 
32
37
  @ttl = options[:ttl]
33
- unless @ttl.is_a?(Numeric) && @ttl.real? && @ttl.finite? && @ttl.positive?
34
- raise ArgumentError, 'Cache requires a positive, finite TTL in seconds'
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'
35
43
  end
36
44
 
45
+ @prune = options.fetch(:prune, false)
46
+ raise ArgumentError, 'Cache prune must be true or false' unless [true, false].include?(@prune)
47
+
37
48
  @file = File.expand_path(options[:file])
38
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
39
56
  end
40
57
 
41
58
  def fetch(key, uri)
59
+ @seen << key
42
60
  data = read_entries[key]
43
- return unless fresh?(data) && data['code'].is_a?(Integer) && data['code'].between?(200, 299)
44
- return unless data['method'].is_a?(String) && data['result_uri'].is_a?(String)
45
-
46
- parsed = URI(data['result_uri'])
47
- return unless %w[http https].include?(parsed.scheme) && parsed.host && !parsed.userinfo
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'])
48
65
 
49
66
  CachedResult.new(data, uri)
50
67
  rescue URI::InvalidURIError
@@ -52,38 +69,90 @@ module LinkChecker
52
69
  end
53
70
 
54
71
  def store(key, result)
55
- return unless result.success?
72
+ @seen << key
73
+ return unless result.success? || (result.blocked? && @blocked_ttl)
56
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 }
57
76
 
58
- directory = File.dirname(@file)
59
- FileUtils.mkdir_p(directory)
60
- File.open("#{@file}.lock", File::RDWR | File::CREAT, 0o600) do |lock|
61
- lock.flock(File::LOCK_EX)
62
- entries = read_entries.select { |_entry_key, data| fresh?(data) }
77
+ update_entries do |entries|
63
78
  entries[key] = {
64
79
  'checked_at' => Time.now.to_f,
65
80
  'method' => result.method,
66
81
  'code' => result.code,
67
- 'result_uri' => result.result_uri.to_s
82
+ 'result_uri' => result.result_uri.to_s,
83
+ 'redirects' => result.redirects.map { |hop| [hop.uri.to_s, hop.code, hop.to.to_s] }
68
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) })
69
119
  Tempfile.create(['link-checker-', '.json'], directory) do |file|
70
120
  file.write(JSON.generate('version' => VERSION, 'entries' => entries))
71
121
  file.flush
72
122
  File.rename(file.path, @file)
73
123
  end
74
124
  end
75
- rescue IOError, SystemCallError, JSON::GeneratorError
76
- @logger.warn("Unable to write link cache #{@file}; result was not cached")
77
125
  end
78
126
 
79
- private
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
80
147
 
148
+ # Successes expire after ttl and blocked results after blocked_ttl; blocked entries are stale without one.
81
149
  def fresh?(data)
82
150
  return false unless data.is_a?(Hash)
83
151
 
152
+ ttl = blocked?(data) ? @blocked_ttl : @ttl
84
153
  timestamp = data['checked_at']
85
154
  now = Time.now.to_f
86
- timestamp.is_a?(Numeric) && timestamp.finite? && timestamp <= now && now - timestamp < @ttl
155
+ !ttl.nil? && timestamp.is_a?(Numeric) && timestamp.finite? && timestamp <= now && now - timestamp < ttl
87
156
  end
88
157
 
89
158
  def read_entries