schemic 0.1.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.
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'schemic/adapter'
4
+
5
+ # Model import and reference lookup hooks for Rails integrations.
6
+ module Schemic::Adapter::Rails
7
+ def import xml
8
+ model_attrs = parse(xml)
9
+ model = self
10
+ key = current_options[:key].to_s
11
+
12
+ return unless model_attrs[key]
13
+
14
+ if (instance = model.where(key => model_attrs[key]).first)
15
+ instance.update!(model_attrs)
16
+ else
17
+ instance = model.new(model_attrs)
18
+
19
+ instance.save!
20
+ end
21
+ end
22
+
23
+ def reference_value name, options, xml_context
24
+ context, selector = find_new_selector(name, xml_context, options)
25
+
26
+ return unless selector[:by]
27
+
28
+ value = reference_source(name, context, selector, options)
29
+ model = model_for(name, options)
30
+ relation = reference_relation(model, selector[:field] || selector[:by], value, options)
31
+ relation = fallback_relation(model, relation, value, name)
32
+ result = found_reference(relation, name, options, xml_context)
33
+
34
+ remember_reference(name, result)
35
+ end
36
+
37
+ def attributes_update name, options, xml_context
38
+ if (ref = update_reference(name, options, xml_context))
39
+ { 'id' => ref.id } if is_update_required?(name, xml_context, options, ref)
40
+ elsif (ref = reference_value(name, options, xml_context))
41
+ reference_attributes(ref)
42
+ else
43
+ {}
44
+ end
45
+ end
46
+
47
+ # Compares the existing record timestamp with the selected source timestamp.
48
+ # @param name [String] Reference declaration name.
49
+ # @param xml_context [Nokogiri::XML::Node] Source subtree.
50
+ # @param options [OpenStruct] Update field and selector declaration.
51
+ # @param object [Object] Existing model instance.
52
+ # @return [Boolean] Whether the source timestamp is newer.
53
+ def is_update_required? name, xml_context, options, object
54
+ base = object.send(options.update_field)
55
+ inx, inc = find_new_contexts(name, xml_context, options)
56
+ o, = select_value(options.update, inx, this_contexts(inc), options)
57
+
58
+ base < Time.parse(o.text)
59
+ end
60
+
61
+ # Retains the published spelling for applications extending the adapter.
62
+ alias is_update_required is_update_required?
63
+
64
+ private
65
+
66
+ # Selects the reference input; failed navigation records a field error and yields nil.
67
+ # @param name [String] Reference field name.
68
+ # @param context [Nokogiri::XML::Node] Selected source context.
69
+ # @param selector [OpenStruct] Reference selector options.
70
+ # @param options [OpenStruct] Declaration options.
71
+ # @return [Object, nil] Selected reference value.
72
+ def reference_source name, context, selector, options
73
+ value, = select_value(selector[:by], context, this_contexts(selector), options)
74
+
75
+ value
76
+ rescue NoMethodError
77
+ error(name, "field error for '#{selector[:by]}' in context: #{context.inspect}")
78
+ end
79
+
80
+ # Queries a single value or a list according to the existing reference declaration.
81
+ # @param model [Class] Target model class supplied by the integration.
82
+ # @param field [String, Symbol] Lookup field.
83
+ # @param value [Object] Selected source node or nodes.
84
+ # @param options [OpenStruct] Cardinality settings.
85
+ # @return [ActiveRecord::Relation] Matching records.
86
+ def reference_relation model, field, value, options
87
+ values = !options.single && value.respond_to?(:size) ? value.map(&:text) : value.text
88
+
89
+ model.where(field => values)
90
+ end
91
+
92
+ # Applies the integration's regexp fallback only when an ordinary lookup found no records.
93
+ # @param model [Class] Target model.
94
+ # @param relation [ActiveRecord::Relation] Ordinary lookup result.
95
+ # @param value [Object] Original selected value.
96
+ # @param name [String] Reference field name.
97
+ # @return [ActiveRecord::Relation, Array] Fallback result or original relation.
98
+ def fallback_relation model, relation, value, name
99
+ return relation unless relation.empty? && (field = inc[:re_field])
100
+
101
+ model.where("? ~* #{field}", value.text).order(code: :desc)
102
+ rescue Java::JavaLang::NoSuchMethodError
103
+ error(name, "reference is unavailable to find out via referenced field '#{field}' with data: #{value.text}")
104
+
105
+ []
106
+ end
107
+
108
+ # Resolves one or many matching records; missing plural references retain the existing nil placeholder.
109
+ # @param relation [ActiveRecord::Relation] Matching records.
110
+ # @param name [String] Reference name.
111
+ # @param options [OpenStruct] Cardinality and callback options.
112
+ # @param context [Nokogiri::XML::Node] Original subtree.
113
+ # @return [Object, Array] Final reference value.
114
+ def found_reference relation, name, options, context
115
+ return completed_reference(relation.first, name, context, options) if options.single
116
+
117
+ values = relation.empty? ? [nil] : relation
118
+
119
+ values.map {|value| completed_reference(value, name, context, options) }
120
+ end
121
+
122
+ # Runs the integration's on_found callback when present; otherwise keeps the model instance.
123
+ # @param value [Object] Found model instance.
124
+ # @param name [String] Reference field.
125
+ # @param context [Nokogiri::XML::Node] Original subtree.
126
+ # @param options [OpenStruct] Declaration options.
127
+ # @return [Object] Original instance or callback text result.
128
+ def completed_reference value, name, context, options
129
+ inc[:on_found] ? handled_value(inc[:on_found], value, name, context, options).text : value
130
+ end
131
+
132
+ # Appends the reference to the integration's relation accumulator.
133
+ # @param name [String] Reference name.
134
+ # @param value [Object] Resolved reference.
135
+ # @return [Object] Original value.
136
+ def remember_reference name, value
137
+ this['relations'] ||= {}
138
+ this['relations'][name] ||= []
139
+
140
+ this['relations'][name] << value
141
+
142
+ value
143
+ end
144
+
145
+ # Performs lookup only for configured conditional updates; absent settings yield nil.
146
+ # @param name [String] Reference field.
147
+ # @param options [OpenStruct] Update settings.
148
+ # @param context [Nokogiri::XML::Node] Original subtree.
149
+ # @return [Object, nil] Existing reference when update settings are enabled.
150
+ def update_reference name, options, context
151
+ reference_value(name, options, context) if options.update && options.update_field
152
+ end
153
+
154
+ # Converts a single reference or an array into update attribute hashes.
155
+ # @param reference [Object, Array] Model instance(s).
156
+ # @return [Hash, Array<Hash>] IDs for nested model attributes.
157
+ def reference_attributes reference
158
+ reference.is_a?(Array) ? reference.map {|value| { 'id' => value.id }} : { 'id' => reference.id }
159
+ end
160
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Application import integrations.
4
+ # Nested form establishes Schemic when this entry point is required on its own.
5
+ # rubocop:disable Style/ClassAndModuleChildren
6
+ module Schemic
7
+ # Application import integrations.
8
+ module Adapter
9
+ autoload :Rails, 'schemic/adapter/rails'
10
+ end
11
+ end
12
+ # rubocop:enable Style/ClassAndModuleChildren
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'base64'
5
+ require 'digest'
6
+ require 'fileutils'
7
+ require 'tempfile'
8
+ require 'schemic/crawler'
9
+
10
+ # One atomic, checksummed file per requested URL, containing metadata and original bytes.
11
+ class Schemic::Crawler::Cache
12
+ # Selects a local cache directory without creating files.
13
+ # @param directory [String] Cache root outside the application source tree.
14
+ # @return [Cache] Persistent raw response store.
15
+ def initialize directory
16
+ @directory = File.expand_path(directory)
17
+ end
18
+
19
+ # Reads and verifies a saved response; a missing entry returns nil.
20
+ # If its URL, bytes or checksum are invalid, raises CacheMiss; never downloads as recovery.
21
+ # @param url [String] Canonical requested URL.
22
+ # @return [Page, nil] Saved raw page.
23
+ def read url
24
+ file = path(url)
25
+
26
+ return unless File.file?(file)
27
+
28
+ entry = JSON.parse(File.binread(file))
29
+ body = Base64.strict_decode64(entry.fetch('body'))
30
+
31
+ raise(Schemic::Crawler::CacheMiss, "Invalid cached page: #{url}") unless is_entry_valid?(entry, url, body)
32
+
33
+ Schemic::Crawler::Page.new(url: entry['url'], status: entry['status'], headers: entry['headers'],
34
+ body: body, fetched_at: entry['fetched_at'])
35
+ rescue JSON::ParserError, KeyError, ArgumentError, TypeError => error
36
+ raise(Schemic::Crawler::CacheMiss, "Invalid cached page #{url}: #{error.message}")
37
+ end
38
+
39
+ # Atomically replaces one entry; interrupted writes leave its previous contents intact.
40
+ # @param url [String] Canonical requested URL, including query parameters.
41
+ # @param page [Page] Successful response to persist.
42
+ # @return [Page] Saved response.
43
+ def write url, page
44
+ FileUtils.mkdir_p(@directory)
45
+
46
+ entry = page.to_h.merge(requested_url: url, body: Base64.strict_encode64(page.body),
47
+ sha256: Digest::SHA256.hexdigest(page.body))
48
+
49
+ Tempfile.create(['page-', '.json'], @directory) do |file|
50
+ file.write(JSON.generate(entry))
51
+ file.flush
52
+ file.fsync
53
+ File.rename(file.path, path(url))
54
+ end
55
+
56
+ page
57
+ end
58
+
59
+ private
60
+
61
+ # Maps a URL to a filesystem-safe cache key without discarding its query.
62
+ # @param url [String] Canonical request URL.
63
+ # @return [String] Absolute cache entry filename.
64
+ def path url
65
+ File.join(@directory, "#{Digest::SHA256.hexdigest(url)}.json")
66
+ end
67
+
68
+ # Checks metadata and checksum together; malformed envelopes are rejected by the caller.
69
+ # @param entry [Hash] Decoded cache envelope.
70
+ # @param url [String] Expected request URL.
71
+ # @param body [String] Decoded original bytes.
72
+ # @return [Boolean] Whether this entry is a complete successful response.
73
+ def is_entry_valid? entry, url, body
74
+ entry['requested_url'] == url && entry['sha256'] == Digest::SHA256.hexdigest(body) &&
75
+ entry['headers'].is_a?(Hash) && entry['status'] == 200 && entry['url'].is_a?(String)
76
+ end
77
+ end
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require 'time'
5
+ require 'schemic/crawler'
6
+
7
+ # HTTP delivery with inherited proxy/TLS settings and bounded redirects/retries/body size.
8
+ class Schemic::Crawler::HTTP
9
+ RETRY_CODES = [429, 502, 503, 504].freeze
10
+ REDIRECT_CODES = [301, 302, 303, 307, 308].freeze
11
+
12
+ # Configures finite delivery limits without performing requests.
13
+ # @param timeout [Numeric] Positive connection/read/write timeout in seconds.
14
+ # @param retries [Integer] Additional attempts for transient HTTP or network errors.
15
+ # @param redirects [Integer] Maximum redirects per attempt.
16
+ # @param max_bytes [Integer] Maximum response body bytes.
17
+ # @return [HTTP] Callable page transport.
18
+ def initialize timeout: 15, retries: 2, redirects: 5, max_bytes: 10 * 1024 * 1024
19
+ check_delivery_limits(timeout, retries, redirects, max_bytes)
20
+
21
+ @timeout = timeout
22
+ @retries = retries
23
+ @redirects = redirects
24
+ @max_bytes = max_bytes
25
+ end
26
+
27
+ # Gets a page and validates every redirect before requesting its destination.
28
+ # If delivery fails transiently, retries within the configured bound; other responses are returned.
29
+ # @param url [String] Validated requested URL.
30
+ # @param headers [Hash] Conditional headers from cache.
31
+ # @param check [#call] URL boundary validator for seeds and redirects.
32
+ # @param before_request [#call] Rate limiter called for each HTTP attempt.
33
+ # @return [Page] Final response and exact body bytes.
34
+ def call url, headers:, check:, before_request:
35
+ attempts = 0
36
+
37
+ loop do
38
+ begin
39
+ page = redirected_page(url, headers, check, before_request)
40
+
41
+ return page unless RETRY_CODES.include?(page.status) && attempts < @retries
42
+ rescue OpenSSL::SSL::SSLError, Net::HTTPBadResponse => error
43
+ raise(Schemic::Crawler::FetchError, "Delivery failed: #{error.class}")
44
+ rescue Timeout::Error, IOError, SocketError, SystemCallError => error
45
+ raise(Schemic::Crawler::FetchError, "Delivery failed: #{error.class}") if attempts >= @retries
46
+ end
47
+
48
+ attempts += 1
49
+ end
50
+ end
51
+
52
+ private
53
+
54
+ # Follows a bounded redirect chain, checking each URL and rejecting redirects without Location.
55
+ # @param url [String] First URL.
56
+ # @param headers [Hash] Request validators.
57
+ # @param check [#call] Source boundary checker.
58
+ # @param before_request [#call] Rate limiter.
59
+ # @return [Page] Nonredirect response; loops/excess redirects raise FetchError.
60
+ def redirected_page url, headers, check, before_request
61
+ (@redirects + 1).times do |index|
62
+ checked = check.call(url)
63
+
64
+ before_request.call
65
+
66
+ page = request_page(URI(checked), headers)
67
+
68
+ return page unless REDIRECT_CODES.include?(page.status)
69
+
70
+ url = redirect_location(checked, page, index)
71
+ end
72
+ rescue URI::InvalidURIError => error
73
+ raise(Schemic::Crawler::FetchError, "Invalid redirect: #{error.message}")
74
+ end
75
+
76
+ # Streams one response using the process proxy and verified TLS configuration.
77
+ # If decompressed bytes exceed max_bytes, raises FetchError before caching.
78
+ # @param uri [URI::HTTP] Checked HTTP(S) address.
79
+ # @param headers [Hash] Additional request headers.
80
+ # @return [Page] Raw bytes, lowercase response headers and UTC fetch time.
81
+ def request_page uri, headers
82
+ client = client_for(uri)
83
+ request = Net::HTTP::Get.new(uri.request_uri,
84
+ { 'User-Agent' => 'Schemic/0.1', 'Accept-Encoding' => 'identity' }.merge(headers))
85
+ page = nil
86
+
87
+ client.request(request) {|response| page = response_page(uri, response) }
88
+
89
+ page
90
+ end
91
+
92
+ # Rejects nonfinite timeouts and negative or noninteger delivery limits before requests.
93
+ # @param timeout [Numeric] Positive finite timeout.
94
+ # @param retries [Integer] Retry bound.
95
+ # @param redirects [Integer] Redirect bound.
96
+ # @param max_bytes [Integer] Positive body limit.
97
+ # @return [nil] No result after successful validation.
98
+ def check_delivery_limits timeout, retries, redirects, max_bytes
99
+ valid = is_timeout_valid?(timeout) && [retries, redirects].all? {|value| is_retry_limit_valid?(value) }
100
+ valid &&= max_bytes.is_a?(Integer) && max_bytes.positive?
101
+
102
+ raise(ArgumentError, 'Invalid HTTP delivery limits') unless valid
103
+ end
104
+
105
+ # Resolves a redirect location; a missing header or exhausted limit raises FetchError.
106
+ # @param url [String] Current request URL.
107
+ # @param page [Page] Redirect response.
108
+ # @param index [Integer] Current redirect index.
109
+ # @return [String] Absolute next URL, checked by the following request iteration.
110
+ def redirect_location url, page, index
111
+ raise(Schemic::Crawler::FetchError, 'Redirect limit exceeded') if index == @redirects
112
+ raise(Schemic::Crawler::FetchError, 'Redirect has no Location') unless page.headers['location']
113
+
114
+ URI.join(url, page.headers.fetch('location')).to_s
115
+ end
116
+
117
+ # Creates the HTTP client with inherited proxy settings and verified TLS for HTTPS.
118
+ # @param uri [URI::HTTP] Destination URL.
119
+ # @return [Net::HTTP] Client with finite timeouts and no implicit retries.
120
+ def client_for uri
121
+ Net::HTTP.new(uri.host, uri.port).tap do |client|
122
+ client.use_ssl = uri.scheme == 'https'
123
+ client.open_timeout = @timeout
124
+ client.read_timeout = @timeout
125
+ client.write_timeout = @timeout
126
+ client.max_retries = 0
127
+ end
128
+ end
129
+
130
+ # Reads response bytes and assembles metadata; oversized chunks are rejected before retention.
131
+ # @param uri [URI::HTTP] Final URL.
132
+ # @param response [Net::HTTPResponse] Delivered response.
133
+ # @return [Page] Original body and response headers.
134
+ def response_page uri, response
135
+ body = ''.b
136
+
137
+ response.read_body do |chunk|
138
+ if body.bytesize + chunk.bytesize > @max_bytes
139
+ raise(Schemic::Crawler::FetchError,
140
+ 'Response body limit exceeded')
141
+ end
142
+
143
+ body << chunk
144
+ end
145
+
146
+ Schemic::Crawler::Page.new(url: uri.to_s, status: response.code.to_i,
147
+ headers: response.each_header.to_h, body: body, fetched_at: Time.now.utc.iso8601)
148
+ end
149
+
150
+ # Recognizes finite positive timeout values.
151
+ # @param value [Object] Timeout candidate.
152
+ # @return [Boolean] Whether HTTP can use the timeout.
153
+ def is_timeout_valid? value
154
+ value.is_a?(Numeric) && value.real? && value.finite? && value.positive?
155
+ end
156
+
157
+ # Recognizes nonnegative integer attempt bounds.
158
+ # @param value [Object] Retry or redirect limit.
159
+ # @return [Boolean] Whether the limit is valid.
160
+ def is_retry_limit_valid? value
161
+ value.is_a?(Integer) && value >= 0
162
+ end
163
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ # URL boundaries, collection validation and selected link discovery.
4
+ module Schemic::Crawler::Navigation
5
+ private
6
+
7
+ # Validates the scheme and excludes embedded credentials before canonicalizing fragments.
8
+ # @param value [String] Absolute HTTP(S) URL.
9
+ # @return [URI::HTTP] Normalized URI; invalid inputs raise Schemic::Crawler::ScopeError.
10
+ def checked_url value
11
+ uri = URI.parse(value)
12
+
13
+ unless uri.is_a?(URI::HTTP) && uri.host && !uri.userinfo
14
+ raise(Schemic::Crawler::ScopeError, 'Expected an absolute HTTP(S) URL without credentials')
15
+ end
16
+
17
+ uri.fragment = nil
18
+
19
+ uri.path = '/' if uri.path.empty?
20
+
21
+ URI.join(uri.to_s, '').normalize
22
+ rescue URI::InvalidURIError, TypeError
23
+ raise(Schemic::Crawler::ScopeError, 'Invalid URL')
24
+ end
25
+
26
+ # Extracts the network origin, retaining explicit nondefault ports.
27
+ # @param uri [URI::HTTP] Parsed URL.
28
+ # @return [Array] Scheme, lowercased host and port.
29
+ def origin uri
30
+ [uri.scheme, uri.host.downcase, uri.port]
31
+ end
32
+
33
+ # Checks seeds and every redirect against the same source boundary.
34
+ # If either origin or path is outside it, raises Schemic::Crawler::ScopeError before delivery.
35
+ # @param value [String] Candidate URL.
36
+ # @return [String] Canonical in-scope URL.
37
+ def scoped_url value
38
+ uri = checked_url(value)
39
+ path = URI::DEFAULT_PARSER.unescape(uri.path)
40
+ inside = path == @path_prefix || path.start_with?("#{@path_prefix}/")
41
+
42
+ unless @origins.include?(origin(uri)) && inside && !path.split('/').include?('..')
43
+ raise(Schemic::Crawler::ScopeError, "URL outside source boundary: #{uri}")
44
+ end
45
+
46
+ uri.to_s
47
+ end
48
+
49
+ # Resolves selected hrefs against the final response URL; external links are ignored.
50
+ # @param page [Page] HTML response with its effective URL.
51
+ # @param selectors [String, Hash] Link selectors and optional attributes, e.g. frame=>src.
52
+ # @return [Array<String>] Canonical in-scope links.
53
+ def discovered_links page, selectors
54
+ document = Nokogiri::HTML(page.body)
55
+ location = link_base(document, page.url)
56
+ rules = selectors.is_a?(String) ? { selectors => 'href' } : selectors
57
+
58
+ rules.flat_map do |selector, attribute|
59
+ document.css(selector).filter_map {|node| resolved_link(location, node[attribute]) }
60
+ end
61
+ rescue URI::InvalidURIError, Nokogiri::CSS::SyntaxError => error
62
+ raise(Schemic::Crawler::FetchError, "Invalid source links: #{error.message}")
63
+ end
64
+
65
+ # Resolves one selected reference; absent, invalid or out-of-scope links are ignored.
66
+ # @param location [String] Effective document/base URL.
67
+ # @param reference [String, nil] Selected href or src.
68
+ # @return [String, nil] In-scope URL, or nil when ignored.
69
+ def resolved_link location, reference
70
+ scoped_url(URI.join(location, reference).to_s) if reference
71
+ rescue Schemic::Crawler::ScopeError, URI::InvalidURIError
72
+ nil
73
+ end
74
+
75
+ # Checks constructor limits before storing any configuration; invalid values raise ArgumentError.
76
+ # @param origins [Array<String>] Allowed origins.
77
+ # @param prefix [String] Absolute path boundary.
78
+ # @param limit [Integer] Maximum pages.
79
+ # @param delay [Numeric] Finite pause in seconds.
80
+ # @return [nil] No result after successful validation.
81
+ def check_collection_limits origins, prefix, limit, delay
82
+ valid = origins.is_a?(Array) && !origins.empty? && is_page_limit_valid?(limit)
83
+ valid &&= prefix.is_a?(String) && prefix.start_with?('/') && is_delay_valid?(delay)
84
+
85
+ return if valid
86
+
87
+ raise(ArgumentError,
88
+ 'Expected origins, absolute path prefix, positive page limit and nonnegative delay')
89
+ end
90
+
91
+ # Checks collection input types; invalid seed containers or selectors raise ArgumentError.
92
+ # @param urls [Array<String>] Seed list.
93
+ # @param links [String, Hash, nil] Link declaration.
94
+ # @return [nil] No result after successful validation.
95
+ def check_collection_input urls, links
96
+ raise(ArgumentError, 'Expected a list of seed URLs') unless urls.is_a?(Array)
97
+ return if links.nil? || links.is_a?(String) || links.is_a?(Hash)
98
+
99
+ raise(ArgumentError, 'Expected a CSS selector or selector/attribute mapping')
100
+ end
101
+
102
+ # Resolves an HTML base declaration when present, otherwise keeps the effective response URL.
103
+ # @param document [Nokogiri::HTML::Document] Source DOM.
104
+ # @param url [String] Effective page URL.
105
+ # @return [String] Base URL for relative references.
106
+ def link_base document, url
107
+ base = document.at_css('base[href]')&.[]('href')
108
+
109
+ base ? URI.join(url, base).to_s : url
110
+ end
111
+
112
+ # Recognizes a positive integer page bound.
113
+ # @param value [Object] Page limit candidate.
114
+ # @return [Boolean] Whether the limit is valid.
115
+ def is_page_limit_valid? value
116
+ value.is_a?(Integer) && value.positive?
117
+ end
118
+
119
+ # Recognizes a finite nonnegative pause.
120
+ # @param value [Object] Delay candidate.
121
+ # @return [Boolean] Whether the delay is valid.
122
+ def is_delay_valid? value
123
+ value.is_a?(Numeric) && value.real? && value.finite? && value >= 0
124
+ end
125
+ end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require 'tempfile'
5
+ require 'fileutils'
6
+ require 'schemic/crawler'
7
+
8
+ # Conversion of a complete collection through the existing Parser into import YAML.
9
+ class Schemic::Crawler::Pipeline
10
+ # Per-page diagnostics for an unpublished collection.
11
+ class ExtractionError < Schemic::Crawler::Error
12
+ attr_reader :errors
13
+
14
+ # Keeps per-page extraction failures for a caller's report.
15
+ # @param errors [Hash] Page URLs mapped to parser diagnostics.
16
+ # @return [ExtractionError] Failure that does not publish partial output.
17
+ def initialize errors
18
+ @errors = errors
19
+
20
+ super("Extraction failed for #{errors.size} page(s)")
21
+ end
22
+ end
23
+
24
+ # Uses an existing schema/parser and optional extracted collection key.
25
+ # @param parser [Schemic::Parser] Existing DSL or YAML parser.
26
+ # @param format [Symbol] :html or :xml.
27
+ # @param collection [String, nil] Top-level array key, or nil for one record per page.
28
+ # @return [Pipeline] Reusable page-to-YAML converter.
29
+ def initialize parser:, format: :html, collection: nil
30
+ raise(ArgumentError, 'Expected html/xml format and optional collection key') unless
31
+ %i[html xml].include?(format) && (collection.nil? || collection.is_a?(String))
32
+
33
+ @parser = parser
34
+ @format = format
35
+ @collection = collection
36
+
37
+ return if parser.root_scheme&.has
38
+
39
+ raise(Schemic::Parser::InvalidSchemeError, 'Expected a root extraction schema with fields')
40
+ end
41
+
42
+ # Extracts all pages before returning any import bundle.
43
+ # If any page has parser errors or an invalid collection, raises ExtractionError.
44
+ # @param pages [Enumerable<Page>] Saved or freshly collected pages.
45
+ # @return [Array<Hash>] Complete records; an invalid page never yields a partial import.
46
+ def records pages
47
+ errors = {}
48
+ records = pages.flat_map {|page| page_records(page, errors) }
49
+
50
+ errors['collection'] = ['No records collected'] if records.empty? && errors.empty?
51
+
52
+ raise(ExtractionError, errors) unless errors.empty?
53
+
54
+ records
55
+ end
56
+
57
+ # Writes YAML only after full extraction; failures preserve existing output.
58
+ # @param pages [Enumerable<Page>] Input collection.
59
+ # @param output [String] Destination YAML path.
60
+ # @return [Array<Hash>] Records written atomically to output.
61
+ def write pages, output:
62
+ data = records(pages)
63
+ directory = File.dirname(File.expand_path(output))
64
+
65
+ FileUtils.mkdir_p(directory)
66
+
67
+ Tempfile.create(['bundle-', '.yaml'], directory) do |file|
68
+ file.write(YAML.dump(data))
69
+ file.flush
70
+ file.fsync
71
+ File.rename(file.path, output)
72
+ end
73
+
74
+ data
75
+ end
76
+
77
+ private
78
+
79
+ # Honors an HTTP charset while retaining the original cached bytes.
80
+ # If HTML has no HTTP charset, preserves valid UTF-8 or lets Nokogiri detect its meta declaration.
81
+ # @param page [Page] Raw response with lowercase headers.
82
+ # @return [String, Nokogiri::HTML::Document] Parser input with the proper encoding.
83
+ def document_for page
84
+ return page.body unless @format == :html
85
+
86
+ charset = page.headers.fetch('content-type', '')[/charset\s*=\s*["']?([^\s;"']+)/i, 1]
87
+ body = page.body.dup.force_encoding('UTF-8')
88
+
89
+ body = page.body unless body.valid_encoding?
90
+
91
+ Nokogiri::HTML::Document.parse(body, page.url, charset, &:nonet)
92
+ end
93
+
94
+ # Extracts one page; parser or collection errors are retained without returning partial records.
95
+ # @param page [Page] Source response.
96
+ # @param errors [Hash] Collection diagnostic accumulator.
97
+ # @return [Array<Hash>] Valid records, or an empty array after recording a failure.
98
+ def page_records page, errors
99
+ tree = @parser.parse(document_for(page), format: @format)
100
+ values = @collection ? tree[@collection] : [tree]
101
+
102
+ return values if @parser.errors.empty? && is_collection_valid?(values)
103
+
104
+ errors[page.url] = page_errors
105
+
106
+ []
107
+ end
108
+
109
+ # Checks that extraction produced at least one nonempty record.
110
+ # @param values [Object] Extracted collection candidate.
111
+ # @return [Boolean] Whether all records can be published.
112
+ def is_collection_valid? values
113
+ values.is_a?(Array) && !values.empty? && values.all? {|value| value.is_a?(Hash) && !value.empty? }
114
+ end
115
+
116
+ # Copies parser diagnostics when present, otherwise describes the invalid collection.
117
+ # @return [Hash] Independent errors that survive the parser's next invocation.
118
+ def page_errors
119
+ return { collection: ['Expected a nonempty list of records'] } if @parser.errors.empty?
120
+
121
+ Marshal.load(Marshal.dump(@parser.errors))
122
+ end
123
+ end