crawlscope 0.10.2 → 0.11.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.
@@ -0,0 +1,240 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module LinkMap
5
+ class Audit
6
+ REDIRECT_STATUSES = [301, 302, 303, 307, 308].freeze
7
+ BATCH_SIZE = 32
8
+ MAX_PAGE_BYTES = 5 * 1024 * 1024
9
+
10
+ def initialize(base_url:, sitemap_path: nil, roots: nil, inventory: [], manifest: {}, paths: ["/"], exclude_paths: [],
11
+ max_pages: 10_000, max_edges: 100_000, follow_limit: 0, follow_depth: 3,
12
+ concurrency: Configuration::DEFAULT_CONCURRENCY, fetch_executor: Configuration::DEFAULT_FETCH_EXECUTOR,
13
+ timeout_seconds: Configuration::DEFAULT_TIMEOUT_SECONDS)
14
+ @scope = Scope.new(base_url, paths: paths, exclude_paths: exclude_paths)
15
+ @sitemap_path = sitemap_path
16
+ @roots = roots.nil? ? ["#{@scope.origin}/"] : Array(roots)
17
+ @inventory = inventory
18
+ @manifest = manifest
19
+ @max_pages = limit(max_pages, "max_pages", 1)
20
+ @max_edges = limit(max_edges, "max_edges", 1)
21
+ @follow_limit = limit(follow_limit, "follow_limit", 0)
22
+ @follow_depth = limit(follow_depth, "follow_depth", 1)
23
+ @fetch_executor = fetch_executor
24
+ @concurrency = concurrency
25
+ @timeout_seconds = timeout_seconds
26
+ end
27
+
28
+ def call
29
+ roots = prepare_graph
30
+ manifest = Manifest.new(@manifest, scope: @scope)
31
+ inventory = scoped_urls(@inventory, "inventory")
32
+ @executor = FetchExecutor.build(name: @fetch_executor, concurrency: @concurrency)
33
+ @http = Http.new(base_url: @scope.origin, timeout_seconds: @timeout_seconds, adapter: http_adapter, follow_redirects: false)
34
+ sitemap = SitemapUrls.new(source: @sitemap_path, http: @http, scope: @scope, exclusions: @exclusions).call
35
+ @robots = RobotsPolicy.new(@http.fetch("#{@scope.origin}/robots.txt", max_body_bytes: RobotsPolicy::MAX_BYTES, parse_html: false))
36
+ fetch(roots | sitemap)
37
+ remaining = @follow_limit
38
+ depths = reachability(roots) do |frontier, depth|
39
+ if @follow_limit.positive? && depth <= @follow_depth
40
+ remaining -= fetch(frontier, limit: remaining)
41
+ end
42
+ end
43
+ assign_exclusions(@edges.filter_map { |edge| edge[:target_url] }.uniq | inventory | manifest.pages.keys |
44
+ manifest.edges.flat_map { |edge| edge.values_at(:source_url, :target_url) })
45
+
46
+ graph(sitemap: sitemap, roots: roots, depths: depths, robots: @robots.state, manifest: manifest, inventory: inventory)
47
+ ensure
48
+ @http&.close
49
+ end
50
+
51
+ def from_pages(urls:, pages:)
52
+ roots = prepare_graph
53
+ sitemap = scoped_urls(urls, "sitemap")
54
+ pages.each do |page|
55
+ url, reason = @scope.resolve(page.url)
56
+ if reason
57
+ @exclusions["page:#{reason}"] += 1
58
+ next
59
+ end
60
+
61
+ final, reason = @scope.resolve(page.final_url || page.url)
62
+ if reason
63
+ @responses[url] = {coverage: reason}
64
+ next
65
+ end
66
+
67
+ # Validation exposes the final response after redirects.
68
+ status = (page.status if url == final)
69
+ record(url, status, page, final, nil)
70
+ end
71
+ graph(sitemap: sitemap, roots: roots, depths: reachability(roots), robots: nil)
72
+ end
73
+
74
+ private
75
+
76
+ def prepare_graph
77
+ @exclusions = Hash.new(0)
78
+ @responses = {}
79
+ @edges = []
80
+ @outgoing = Hash.new { |hash, url| hash[url] = [] }
81
+ @extracted = Set.new
82
+ @truncated = Set.new
83
+ @attempted = 0
84
+ @extractor = Extractor.new(scope: @scope, exclusions: @exclusions)
85
+ roots = scoped_urls(@roots, "root")
86
+ raise ConfigurationError, "Link map requires at least one entry root in scope" if roots.empty?
87
+
88
+ roots
89
+ end
90
+
91
+ def http_adapter
92
+ return unless FetchExecutor.normalize(@fetch_executor) == :async
93
+
94
+ require "async/http/faraday"
95
+ :async_http
96
+ end
97
+
98
+ def graph(sitemap:, roots:, depths:, robots:, manifest: Manifest.new({}, scope: @scope), inventory: [])
99
+ Graph.new(
100
+ responses: @responses, occurrences: @edges, depths: depths, sitemap: sitemap, inventory: inventory,
101
+ manifest: manifest, roots: roots, exclusions: @exclusions, robots: robots, truncated: @truncated
102
+ ).report
103
+ end
104
+
105
+ def limit(value, name, minimum)
106
+ limit = value.is_a?(Integer) ? value : Integer(value, 10)
107
+ return limit if limit >= minimum
108
+
109
+ raise ArgumentError
110
+ rescue ArgumentError, TypeError
111
+ raise ConfigurationError, "Link map #{name} must be an integer >= #{minimum}"
112
+ end
113
+
114
+ def scoped_urls(values, origin)
115
+ Array(values).filter_map do |value|
116
+ url, reason = @scope.resolve(value)
117
+ @exclusions["#{origin}:#{reason}"] += 1 if reason
118
+ url
119
+ end.uniq.sort
120
+ end
121
+
122
+ def fetch(urls, limit: @max_pages)
123
+ allowed = assign_exclusions(urls)
124
+ count = [@max_pages - @attempted, limit].min
125
+ selected = allowed.take(count)
126
+ allowed.drop(count).each { |url| @responses[url] = {coverage: "page_limit"} }
127
+ @attempted += selected.size
128
+ selected.each_slice(BATCH_SIZE) do |batch|
129
+ @executor.call(batch) { |url| [url, visit(url)] }.each do |url, (status, last, final_url, redirect_exclusion)|
130
+ record(url, status, last, final_url, redirect_exclusion)
131
+ end
132
+ end
133
+ selected.size
134
+ end
135
+
136
+ def assign_exclusions(urls)
137
+ urls.reject { |url| @responses.key?(url) }.filter_map do |url|
138
+ reason = @robots.exclusion(url)
139
+ next url unless reason
140
+
141
+ @responses[url] = {coverage: reason}
142
+ nil
143
+ end
144
+ end
145
+
146
+ def visit(url)
147
+ last = @http.fetch(url, max_body_bytes: MAX_PAGE_BYTES)
148
+ status = last.status
149
+ final = url
150
+ visited = Set.new([url])
151
+ while REDIRECT_STATUSES.include?(last.status)
152
+ target, reason = @scope.resolve(last.header("location"), base: final)
153
+ reason ||= @robots.exclusion(target)
154
+ return [status, last, final, reason] if reason
155
+ return [status, last, final, "redirect_limit"] if visited.size > Http::MAX_REDIRECTS || !visited.add?(target)
156
+
157
+ final = target
158
+ last = @http.fetch(final, max_body_bytes: MAX_PAGE_BYTES)
159
+ end
160
+
161
+ [status, last, final, nil]
162
+ end
163
+
164
+ def record(url, status, last, final, redirect_exclusion)
165
+ observed = page_record(last, final)
166
+ redirect = final != url || REDIRECT_STATUSES.include?(status)
167
+ if final != url
168
+ @responses[final] = observed unless @responses[final]&.key?(:status)
169
+ end
170
+ @responses[url] = observed.merge(
171
+ status: status, resolved_url: final, redirect: redirect,
172
+ redirect_exclusion: redirect_exclusion,
173
+ indexable: redirect ? false : observed[:indexable]
174
+ )
175
+ return unless observed[:html] && @extracted.add?(final)
176
+
177
+ @extractor.each(last, final) do |edge|
178
+ if @edges.size == @max_edges
179
+ @exclusions["link:edge_limit"] += 1
180
+ @truncated << final
181
+ break
182
+ end
183
+
184
+ @edges << edge
185
+ @outgoing[final] << edge
186
+ end
187
+ end
188
+
189
+ def page_record(page, url)
190
+ type = page.header("content-type").to_s.downcase
191
+ html = !page.error && page.status == 200 && page.html? && (type.empty? || type.include?("text/html"))
192
+ doc = (page.doc if html)
193
+ base = @scope.document_base(doc, url)
194
+ canonical = Documents::Canonical.new(doc: doc, base_url: base)
195
+ canonical_url, canonical_exclusion = @scope.resolve(canonical.href, base: base) if canonical.present?
196
+ noindex = Documents::Robots.noindex_header?(page.headers) || Documents::Robots.noindex_meta?(doc)
197
+ noncanonical = canonical.present? && canonical_url != url
198
+
199
+ {
200
+ status: page.status, resolved_status: page.status, resolved_url: url, html: html,
201
+ coverage: page.error ? "fetch_failed" : "fetched",
202
+ canonical_url: canonical_url, canonical_exclusion: canonical_exclusion,
203
+ noncanonical: noncanonical, indexable: page.status.nil? ? nil : html && !noindex && !noncanonical,
204
+ redirect: REDIRECT_STATUSES.include?(page.status)
205
+ }
206
+ end
207
+
208
+ def reachability(roots)
209
+ frontier = roots
210
+ seen = Set.new
211
+ expanded = Set.new
212
+ depths = {}
213
+ depth = 0
214
+ until frontier.empty?
215
+ seen.merge(frontier)
216
+ yield(frontier, depth) if block_given?
217
+
218
+ next_frontier = []
219
+ frontier.each do |url|
220
+ response = @responses[url]
221
+ next unless response && response[:html]
222
+
223
+ final = response.fetch(:resolved_url)
224
+ depths[url] ||= depth
225
+ depths[final] ||= depth
226
+ next unless expanded.add?(final)
227
+
228
+ @outgoing.fetch(final, []).each do |edge|
229
+ target = edge[:target_url]
230
+ next_frontier << target if target && !edge[:nofollow] && !seen.include?(target)
231
+ end
232
+ end
233
+ frontier = next_frontier.uniq.sort
234
+ depth += 1
235
+ end
236
+ depths
237
+ end
238
+ end
239
+ end
240
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module LinkMap
5
+ class Extractor
6
+ MAX_TEXT = 300
7
+ POSITIONS = {
8
+ "nav" => "nav", "navigation" => "nav", "footer" => "footer",
9
+ "contentinfo" => "footer", "aside" => "sidebar", "complementary" => "sidebar",
10
+ "main" => "main", "article" => "main"
11
+ }.freeze
12
+
13
+ def initialize(scope:, exclusions:)
14
+ @scope = scope
15
+ @exclusions = exclusions
16
+ end
17
+
18
+ def each(page, source)
19
+ base = @scope.document_base(page.doc, source)
20
+ page_nofollow = nofollow?(Documents::Robots.header_value(page.headers, "x-robots-tag")) ||
21
+ page.doc.css(Documents::Robots::ROBOTS_META_SELECTOR).any? { |node| nofollow?(node["content"].to_s) }
22
+
23
+ page.doc.css(Rules::Links::LINK_SELECTORS).each do |node|
24
+ href = node["href"].strip
25
+ next if href.empty? || href.start_with?("#")
26
+
27
+ target, reason = @scope.resolve(href, base: base)
28
+ @exclusions["link:#{reason}"] += 1 if reason
29
+ next unless target || reason == "query"
30
+
31
+ position = position(node)
32
+ rel = node["rel"].to_s.downcase.split.uniq.sort & %w[alternate author bookmark external help license next nofollow noopener noreferrer prev search sponsored tag ugc]
33
+ yield({
34
+ source_url: source, raw_href: href.split(/[?#]/, 2).first, target_url: target,
35
+ anchor_text: text(node.text), image_alt: text(node.css("img[alt]").map { |image| image["alt"] }.join(" ")),
36
+ rel: rel, position: position, contextual: position == "main", exclusion: reason,
37
+ nofollow: page_nofollow || rel.include?("nofollow")
38
+ })
39
+ end
40
+ end
41
+
42
+ private
43
+
44
+ def nofollow?(value)
45
+ Documents::Robots.new(value).nofollow?
46
+ end
47
+
48
+ def position(node)
49
+ nearest = node.ancestors.filter_map { |parent| POSITIONS[parent["role"]] || POSITIONS[parent.name] }
50
+ nearest.find { |value| value != "main" } || nearest.first || "unknown"
51
+ end
52
+
53
+ def text(value)
54
+ value.gsub(/[^\s]*[?#][^\s]+/) { |word| word.split(/[?#]/, 2).first }
55
+ .gsub(/\s+/, " ").strip[0, MAX_TEXT]
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module LinkMap
5
+ class Graph
6
+ def initialize(responses:, occurrences:, depths:, sitemap:, inventory:, manifest:, roots:, exclusions:, robots:, truncated:)
7
+ @responses = responses
8
+ @occurrences = occurrences
9
+ @depths = depths
10
+ @sitemap = sitemap.to_set
11
+ @inventory = inventory.to_set
12
+ @manifest = manifest
13
+ @roots = roots
14
+ @exclusions = exclusions
15
+ @robots = robots
16
+ @truncated = truncated
17
+ @issues = IssueCollection.new
18
+ end
19
+
20
+ def report
21
+ occurrences = @occurrences.map { |edge| annotate(edge) }
22
+ .sort_by { |edge| edge.values.map(&:to_s) }
23
+ by_pair = occurrences.reject { |edge| edge[:target_url].nil? }
24
+ .group_by { |edge| edge.values_at(:source_url, :target_url) }
25
+ pairs = by_pair.sort.map do |(source, target), edges|
26
+ {
27
+ source_url: source, target_url: target, occurrences: edges.size,
28
+ contextual_occurrences: edges.count { |edge| edge[:contextual] },
29
+ followable_occurrences: edges.count { |edge| !edge[:nofollow] }
30
+ }
31
+ end
32
+ inbound = pairs.group_by { |edge| edge[:target_url] }
33
+ nodes = build_nodes(inbound)
34
+ clusters = unreachable_clusters(nodes, pairs)
35
+ clusters.each do |members|
36
+ issue(:unreachable_cluster, members.first, "Review how users can enter this cluster from an entry root.", urls: members)
37
+ end
38
+ expected = check_manifest(by_pair)
39
+
40
+ Report.new(
41
+ roots: @roots, robots: @robots, exclusions: @exclusions.sort.to_h,
42
+ nodes: nodes, occurrences: occurrences, pairs: pairs, expected_edges: expected,
43
+ unreachable_clusters: clusters, issues: @issues.map(&:to_h)
44
+ )
45
+ end
46
+
47
+ private
48
+
49
+ def annotate(edge)
50
+ target = @responses.fetch(edge[:target_url], {})
51
+ edge.merge(
52
+ resolved_url: target[:resolved_url], canonical_url: target[:canonical_url],
53
+ status: target[:status], resolved_status: target[:resolved_status], indexable: target[:indexable],
54
+ coverage: edge[:exclusion] || target.fetch(:coverage, "unobserved")
55
+ )
56
+ end
57
+
58
+ def build_nodes(inbound)
59
+ urls = @sitemap | @inventory | @responses.keys | @manifest.pages.keys | @roots | inbound.keys
60
+ @manifest.edges.each { |edge| urls.merge(edge.values_at(:source_url, :target_url)) }
61
+ urls.sort.map do |url|
62
+ response = @responses.fetch(url, {})
63
+ pairs = inbound.fetch(url, []).reject { |pair| pair[:source_url] == url }
64
+ node = {
65
+ url: url, sitemap: @sitemap.include?(url), inventory: @inventory.include?(url), entry_root: @roots.include?(url),
66
+ coverage: "unobserved", click_depth: @depths[url],
67
+ outgoing_complete: (response[:html] && !response[:redirect]) ? !@truncated.include?(url) : nil,
68
+ sitemap_reached: @sitemap.include?(url) ? @depths.key?(url) : nil,
69
+ inventory_reached: @inventory.include?(url) ? @depths.key?(url) : nil,
70
+ inbound_sources: pairs.size, contextual_inbound_sources: pairs.count { |pair| pair[:contextual_occurrences].positive? },
71
+ sitemap_only: @sitemap.include?(url) && !@depths.key?(url) && pairs.empty?
72
+ }.merge(response).merge(@manifest.pages.fetch(url, {}))
73
+ diagnose_node(node, pairs)
74
+ node
75
+ end
76
+ end
77
+
78
+ def diagnose_node(node, pairs)
79
+ url = node.fetch(:url)
80
+ sources = pairs.map { |pair| pair[:source_url] }
81
+ if node[:html]
82
+ if node[:sitemap_only]
83
+ issue(:sitemap_only, url, "Review whether an entry-root path should link to this sitemap URL.")
84
+ end
85
+ if node[:contextual_inbound_sources].zero?
86
+ issue(:no_contextual_inlinks, url, "Review relevant pages that could link here in their main content.", source_urls: sources) unless node[:entry_root]
87
+ end
88
+ end
89
+ if node[:priority] && node[:click_depth].nil?
90
+ issue(:priority_unreached, url, "Check coverage, then review a relevant path from an entry root.")
91
+ end
92
+ if node[:coverage] == "fetch_failed"
93
+ issue(:link_map_fetch_failed, url, "Retry this URL and review crawl coverage.", source_urls: sources)
94
+ elsif node[:resolved_status].to_i >= 400
95
+ issue(:broken_target, url, "Review the URLs linking here and update broken links.", source_urls: sources, status: node[:resolved_status])
96
+ end
97
+ if node[:redirect]
98
+ issue(:redirect_target, url, "Review direct links to this redirect and update them when appropriate.", source_urls: sources,
99
+ resolved_url: node[:resolved_url], exclusion: node[:redirect_exclusion])
100
+ end
101
+ if node[:noncanonical]
102
+ issue(:noncanonical_target, url, "Review direct links and the declared canonical URL.", source_urls: sources,
103
+ canonical_url: node[:canonical_url], exclusion: node[:canonical_exclusion])
104
+ end
105
+ end
106
+
107
+ def check_manifest(by_pair)
108
+ @manifest.edges.map do |edge|
109
+ source, target = edge.values_at(:source_url, :target_url)
110
+ matches = by_pair.fetch([source, target], []).any? { |link| !edge[:position] || link[:position] == edge[:position] }
111
+ state = if matches
112
+ "observed"
113
+ elsif edge[:approved_exception]
114
+ "excepted"
115
+ elsif !@responses.dig(source, :html) || @responses.dig(source, :redirect) || @truncated.include?(source)
116
+ "unknown"
117
+ else
118
+ "missing"
119
+ end
120
+ if state == "missing" || state == "unknown"
121
+ action = if state == "missing"
122
+ "Review whether a relevant link from this source should point to the expected target."
123
+ else
124
+ "Verify the source page and retry with sufficient coverage."
125
+ end
126
+ code = (state == "missing") ? :missing_expected_edge : :unknown_expected_edge
127
+ issue(code, source, action, **edge)
128
+ end
129
+ edge.merge(state: state)
130
+ end
131
+ end
132
+
133
+ def unreachable_clusters(nodes, pairs)
134
+ neighbors = nodes.select { |node| node[:html] && node[:click_depth].nil? && !node[:redirect] }
135
+ .to_h { |node| [node[:url], []] }
136
+ pairs.each do |pair|
137
+ source, target = pair.values_at(:source_url, :target_url)
138
+ next if pair[:followable_occurrences].zero? || !neighbors.key?(source) || !neighbors.key?(target)
139
+
140
+ neighbors[source] << target
141
+ neighbors[target] << source
142
+ end
143
+
144
+ clusters = []
145
+ until neighbors.empty?
146
+ pending = [neighbors.first.first]
147
+ members = []
148
+ pending.each do |url|
149
+ links = neighbors.delete(url)
150
+ next unless links
151
+
152
+ members << url
153
+ pending.concat(links)
154
+ end
155
+ clusters << members.sort if members.size > 1
156
+ end
157
+ clusters
158
+ end
159
+
160
+ def issue(code, url, message, **details)
161
+ @issues.add(code: code, severity: :notice, category: :link_map, url: url, message: message, details: details)
162
+ end
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Crawlscope
4
+ module LinkMap
5
+ class Manifest
6
+ attr_reader :pages, :edges
7
+
8
+ def initialize(manifest, scope:)
9
+ @scope = scope
10
+ input = object(manifest)
11
+ @pages = object(input.fetch("pages", {})).to_h do |url, metadata|
12
+ data = object(metadata)
13
+ [scoped(url), {priority: data["priority"] == true, page_type: label(data["page_type"]), cluster: label(data["cluster"])}]
14
+ end
15
+ records = input.fetch("edges", [])
16
+ raise ConfigurationError, "Link map manifest edges must be an array" unless records.is_a?(Array)
17
+
18
+ @edges = records.map do |record|
19
+ edge = object(record)
20
+ type = label(edge["type"])
21
+ reason = clean(edge["reason"])
22
+ raise ConfigurationError, "Manifest edges require a type and reason" if type.nil? || reason.nil?
23
+
24
+ position = edge["position"]
25
+ if position && !%w[main nav footer sidebar unknown].include?(position)
26
+ raise ConfigurationError, "Invalid manifest edge position"
27
+ end
28
+
29
+ exception = clean(edge["approved_exception"])
30
+ if edge.key?("approved_exception") && exception.nil?
31
+ raise ConfigurationError, "Approved exceptions require a reason"
32
+ end
33
+
34
+ {
35
+ source_url: scoped(edge["source"]), target_url: scoped(edge["target"]),
36
+ type: type, reason: reason, position: position, approved_exception: exception
37
+ }
38
+ end.uniq.sort_by { |edge| edge.values.map(&:to_s) }
39
+ end
40
+
41
+ private
42
+
43
+ def scoped(url)
44
+ @scope.resolve(url).first || raise(ConfigurationError, "Manifest URL is outside link map scope")
45
+ end
46
+
47
+ def object(value)
48
+ raise ConfigurationError, "Link map manifest requires JSON objects" unless value.is_a?(Hash)
49
+
50
+ value.transform_keys(&:to_s)
51
+ end
52
+
53
+ def label(value)
54
+ return if value.nil?
55
+ return value if value.is_a?(String) && value.match?(/\A[a-z0-9][a-z0-9 _-]{0,79}\z/i)
56
+
57
+ raise ConfigurationError, "Manifest labels must be short names"
58
+ end
59
+
60
+ def clean(value)
61
+ return unless value.is_a?(String)
62
+
63
+ value = value.gsub(/[^\s]*[?#][^\s]+/) { |word| word.split(/[?#]/, 2).first }.strip[0, 300]
64
+ value unless value.empty?
65
+ end
66
+ end
67
+ end
68
+ end