relaton 3.1.7 → 3.1.9

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f9a1dcc62dca48c6e2c80ad43a9e404d13ac3692be82282545271322681ca3d7
4
- data.tar.gz: 3997131f34e955e52439d88b8c943a63984ca3df5f77a5a379eff5a8b7cf7afb
3
+ metadata.gz: 8ea394ab28844cd3cd3a8bf4fb5050801ca09e7470f12f41ac4e3c2de5819c5b
4
+ data.tar.gz: b68f5acb575773b322524d63a4c3957f07b97b96f5f38fcfa0e17303cb1c1a8e
5
5
  SHA512:
6
- metadata.gz: 99c5dbe4bfa6197a209df83a9fc07bf9516f9915aa98158adf64da1168b65d2f8811f7e9e87db9cccf17880aa0e8910c94e49cb1d53d532143d8324b1620936a
7
- data.tar.gz: 6fc0ef51ff656c6776efa46f33306789569bfa72743caebf594b3ff2ec441fc0b3838521d6edd6bb37c40b83c7ff28158a49fa4a6cad18e6add449a4bec4b831
6
+ metadata.gz: e502491df55e172406e8cf02c7e0fd51557ec9d1d9a897f903846151cf782a2fef6bc56f52dbd155e8944af0a0c0f27a48d6e4193fb2b0c8ef14f6de2f2dcd61
7
+ data.tar.gz: d0ed43395a6bde95476b75856c57b57913823d204eabdc94c752ff3dee4e1bc82972c93a3dcd8eda21dc83966e66c7d13818a2657b53bafa6c3bc999485bd6ec
@@ -378,9 +378,19 @@ module Relaton
378
378
  end
379
379
  end
380
380
 
381
- # Rows dropped by `indexed_rows` — reported so the loss is never silent.
381
+ # Documents no row could identify: `add` leaves id_hash nil when
382
+ # neither a pubid parse nor a committed-index row covers the file.
383
+ # (A derived alias pruned by `indexed_rows` because another document
384
+ # owns its spelling is NOT a skip — its id_hash is present and the
385
+ # primary row serves the file.)
382
386
  def skipped_count
383
- count - indexed_rows.size
387
+ @rows.count { |row| row.id_hash.nil? }
388
+ end
389
+
390
+ # The files behind `skipped_count`.
391
+ def skipped_files
392
+ @rows.select { |row| row.id_hash.nil? }
393
+ .map(&:file).uniq.sort
384
394
  end
385
395
 
386
396
  # Rows bucketed by shard, in deterministic (key, rendered) order;
@@ -767,9 +777,13 @@ module Relaton
767
777
  ),
768
778
  )
769
779
  if machine.skipped_count.positive?
770
- Util.warn "Machine index: skipped #{machine.skipped_count} of " \
771
- "#{machine.count} document(s) whose id could not be parsed " \
772
- "(a structured index cannot carry them)."
780
+ raise Relaton::IndexBuildError,
781
+ "Machine index build: #{machine.skipped_count} of " \
782
+ "#{machine.count} document(s) could not be indexed — neither " \
783
+ "a pubid parse of the printed docid nor a committed-index row " \
784
+ "covers them, so no fetch could ever find them: " \
785
+ "#{machine.skipped_files.join(', ')}. Fix the records' " \
786
+ "docidentifier or the flavor grammar, then rebuild."
773
787
  end
774
788
  machine.shard_count
775
789
  end
@@ -49,6 +49,13 @@ module Relaton
49
49
  end
50
50
  end
51
51
 
52
+ # `relaton index` could not build machine-index rows for some documents:
53
+ # neither a pubid parse of the printed docid nor a committed-index row
54
+ # covers them, so those documents would be invisible to every fetch. The
55
+ # build fails (the 2026-11-23 adobe drop: 11 records lost from a published
56
+ # index with only a log warning) instead of publishing a partial index.
57
+ class IndexBuildError < Error; end
58
+
52
59
  module Core
53
60
  RequestError = Relaton::RequestError
54
61
  end
@@ -13,7 +13,8 @@ module Relaton
13
13
  relaton/oasis relaton/doi relaton/jis relaton/xsf
14
14
  relaton/ccsds relaton/etsi relaton/isbn relaton/plateau
15
15
  relaton/oiml relaton/jcgm relaton/easc relaton/gost relaton/adobe
16
- relaton/iala relaton/evs relaton/sae relaton/arxiv
16
+ relaton/iala relaton/evs relaton/sae relaton/eu relaton/arxiv
17
+ relaton/wmo
17
18
  ].freeze
18
19
 
19
20
  include Singleton
@@ -0,0 +1,103 @@
1
+ require "net/http"
2
+
3
+ module Relaton
4
+ module Eu
5
+ module Bibliography
6
+ # Transport failures of the document fetch. They become
7
+ # `Relaton::RequestError`, the one class `Relaton::Db#net_retry` retries.
8
+ NET_ERRORS = [
9
+ SocketError, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED,
10
+ Errno::ETIMEDOUT, EOFError, Net::HTTPBadResponse,
11
+ Net::HTTPHeaderSyntaxError, Net::ProtocolError, Net::OpenTimeout,
12
+ Net::ReadTimeout, OpenSSL::SSL::SSLError
13
+ ].freeze
14
+
15
+ class << self
16
+ #
17
+ # Fetch an EU legal act.
18
+ #
19
+ # @param ref [String, Pubid::Eu::Identifier] `EU Regulation 1227/2011`
20
+ # @param year [String, nil] the act's year; a reference always states
21
+ # it, so a year that differs finds nothing
22
+ # @param _opts [Hash]
23
+ # @return [Relaton::Bib::ItemData, nil]
24
+ #
25
+ def get(ref, year = nil, _opts = {})
26
+ Util.info "Fetching from Relaton repository ...", key: ref.to_s
27
+ pubid = parse_ref ref
28
+ return not_found(ref) unless pubid && (year.nil? || year.to_s == pubid.year.to_s)
29
+
30
+ row = select_row index.search(pubid), pubid
31
+ item = row && fetch_doc(row[:file])
32
+ return not_found(ref) unless item
33
+
34
+ Util.info "Found: `#{item.docidentifier.first.content}`", key: ref.to_s
35
+ item
36
+ end
37
+
38
+ private
39
+
40
+ #
41
+ # Before 2015 a decision had two number series, so two acts can share
42
+ # a number and a year: Council Decision No 252/2013/EU and Commission
43
+ # Implementing Decision 2013/252/EU. `===` ignores the print order,
44
+ # so both rows match; the row printed in the query's order wins.
45
+ # `number_first?` is the order pubid prints: the stored flag is nil
46
+ # for the default order, and a caller can set the default explicitly.
47
+ # With no such row (a query in the other order), the first file.
48
+ #
49
+ def select_row(rows, pubid)
50
+ rows.find { |r| r[:id].number_first? == pubid.number_first? } ||
51
+ rows.min_by { |r| r[:file] }
52
+ end
53
+
54
+ def not_found(ref)
55
+ Util.info "Not found.", key: ref.to_s
56
+ nil
57
+ end
58
+
59
+ #
60
+ # The query as a `Pubid::Eu::Identifier`. A parsed pubid comes from
61
+ # `Relaton::Db` (relaton#205). A reference pubid cannot read answers
62
+ # nil, so `get` answers not-found with a log line (relaton#235).
63
+ #
64
+ # @return [Pubid::Eu::Identifier, nil]
65
+ #
66
+ def parse_ref(ref)
67
+ return ref if ref.is_a?(::Pubid::Eu::Identifier)
68
+
69
+ ::Pubid::Eu::Identifier.parse ref.to_s.strip
70
+ rescue ::Pubid::Errors::Error, ArgumentError => e
71
+ Util.info "Not an EU act identifier pubid reads: #{e.message}", key: ref.to_s
72
+ nil
73
+ end
74
+
75
+ # @param file [String] the row's path in the data repo
76
+ # @return [Relaton::Bib::ItemData, nil] nil when the file is missing
77
+ def fetch_doc(file)
78
+ uri = URI("#{ENDPOINT}#{file}")
79
+ resp = Net::HTTP.get_response uri
80
+ return if resp.code == "404"
81
+ unless resp.code == "200"
82
+ raise Relaton::RequestError, "Could not access #{uri}: HTTP #{resp.code}"
83
+ end
84
+
85
+ Bib::Item.from_yaml(resp.body).tap { |i| i.fetched = Date.today.to_s }
86
+ rescue *NET_ERRORS => e
87
+ raise Relaton::RequestError, "Could not access #{uri}: #{e.message}"
88
+ end
89
+
90
+ #
91
+ # `Index::Type#search` with a pubid narrows to the `number` bucket and
92
+ # selects with pubid's subset match `query === row`: the type and the
93
+ # year must agree, and the legal family is a wildcard.
94
+ #
95
+ def index
96
+ Relaton::Index.find_or_create(
97
+ :eu, pages_url: PAGES_URL, pubid_class: ::Pubid::Eu::Identifier
98
+ )
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,259 @@
1
+ require "net/http"
2
+ require_relative "../core"
3
+ require_relative "../json"
4
+
5
+ module Relaton
6
+ module Eu
7
+ #
8
+ # The EU Publications Office CELLAR SPARQL endpoint, for the crawler.
9
+ #
10
+ # A page holds sector-3 regulations, directives and decisions (CELEX
11
+ # types R, L and D) of one scope, one row a work, ordered by CELEX: one
12
+ # year (`#each_row`), or the works CELLAR changed since a time
13
+ # (`#each_modified_row`, by `cmr:lastModificationDate`). A field with
14
+ # many values (entry-into-force dates, authors, repealed and amended
15
+ # acts) is one `GROUP_CONCAT` string.
16
+ #
17
+ # A property name with a hyphen is written as a full IRI. The endpoint
18
+ # (Virtuoso) misreads `cdm:resource_legal_date_entry-into-force` as a
19
+ # prefixed name: it answers, but with values from no such property.
20
+ #
21
+ class Cellar
22
+ URL = "https://publications.europa.eu/webapi/rdf/sparql".freeze
23
+ # Rows a request. A year has at most about 5,200 works (1988), and a
24
+ # page of 1,000 answers in 4 s to more than 100 s (docs/eu.md).
25
+ ROWS = 1000
26
+ # One request at a time, one a second: the endpoint is public.
27
+ GAP = 1
28
+ ATTEMPTS = 5
29
+ # The wait before retry n (0-based) doubles from this: 15, 30, 60,
30
+ # 120 s. CELLAR can answer 502/504 for a minute or more.
31
+ FIRST_WAIT = 15
32
+ RETRY_CODES = %w[429 500 502 503 504].freeze
33
+ NET_ERRORS = [
34
+ SocketError, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED,
35
+ Errno::ETIMEDOUT, EOFError, Net::HTTPBadResponse,
36
+ Net::HTTPHeaderSyntaxError, Net::ProtocolError, Net::OpenTimeout,
37
+ Net::ReadTimeout, OpenSSL::SSL::SSLError
38
+ ].freeze
39
+
40
+ # The scope of a query: a triple pattern on `?w` that ends with ` ;`,
41
+ # and a FILTER (or nothing).
42
+ Scope = Struct.new(:pattern, :filter, :what, :works)
43
+
44
+ # Joins the `<language>|<title>` pairs of `?titles` (one per language
45
+ # expression, the language as CELLAR's authority code: `ENG`, `BUL`, …).
46
+ # It must be ASCII: Virtuoso turns a non-ASCII character of the query
47
+ # text into `?` (the titles it returns are UTF-8 as stored).
48
+ TITLE_SEP = "~|~".freeze
49
+
50
+ # `%<scope>s`, `%<filter>s`, `%<limit>d` and `%<offset>d` are filled per
51
+ # page.
52
+ QUERY = <<~SPARQL.freeze
53
+ PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>
54
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
55
+ PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
56
+ SELECT ?celex
57
+ (SAMPLE(?eli_) AS ?eli)
58
+ (SAMPLE(?date_) AS ?date)
59
+ (GROUP_CONCAT(DISTINCT STR(?force_); separator=" ") AS ?force)
60
+ (SAMPLE(?inforce_) AS ?inforce)
61
+ (GROUP_CONCAT(DISTINCT CONCAT(STRAFTER(STR(?tlang_), "language/"), "|", STR(?title_)); separator="#{TITLE_SEP}") AS ?titles)
62
+ (GROUP_CONCAT(DISTINCT CONCAT(STR(?author_), "|", COALESCE(STR(?alabel), "")); separator="\\n") AS ?authors)
63
+ (GROUP_CONCAT(DISTINCT ?repeals_; separator=" ") AS ?repeals)
64
+ (GROUP_CONCAT(DISTINCT ?amends_; separator=" ") AS ?amends)
65
+ WHERE {
66
+ ?w cdm:resource_legal_id_sector "3"^^xsd:string ;
67
+ %<scope>s
68
+ cdm:resource_legal_type ?t ;
69
+ cdm:resource_legal_id_celex ?celex .
70
+ FILTER(?t IN ("R"^^xsd:string, "L"^^xsd:string, "D"^^xsd:string))
71
+ %<filter>s
72
+ OPTIONAL { ?w cdm:resource_legal_eli ?eli_ }
73
+ OPTIONAL { ?w cdm:work_date_document ?date_ }
74
+ OPTIONAL { ?w <http://publications.europa.eu/ontology/cdm#resource_legal_date_entry-into-force> ?force_ }
75
+ OPTIONAL { ?w <http://publications.europa.eu/ontology/cdm#resource_legal_in-force> ?inforce_ }
76
+ OPTIONAL { ?w cdm:work_created_by_agent ?author_ .
77
+ OPTIONAL { ?author_ skos:prefLabel ?alabel FILTER(LANG(?alabel) = "en") } }
78
+ OPTIONAL { ?w cdm:resource_legal_repeals_resource_legal/cdm:resource_legal_id_celex ?repeals_ }
79
+ OPTIONAL { ?w cdm:resource_legal_amends_resource_legal/cdm:resource_legal_id_celex ?amends_ }
80
+ OPTIONAL { ?e cdm:expression_belongs_to_work ?w ;
81
+ cdm:expression_uses_language ?tlang_ ;
82
+ cdm:expression_title ?title_ }
83
+ }
84
+ GROUP BY ?celex
85
+ ORDER BY ?celex
86
+ LIMIT %<limit>d OFFSET %<offset>d
87
+ SPARQL
88
+
89
+ # The works of one scope, for #each_scoped to check that it read them
90
+ # all.
91
+ COUNT_QUERY = <<~SPARQL.freeze
92
+ PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>
93
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
94
+ SELECT (COUNT(DISTINCT ?celex) AS ?n) WHERE {
95
+ ?w cdm:resource_legal_id_sector "3"^^xsd:string ;
96
+ %<scope>s
97
+ cdm:resource_legal_type ?t ;
98
+ cdm:resource_legal_id_celex ?celex .
99
+ FILTER(?t IN ("R"^^xsd:string, "L"^^xsd:string, "D"^^xsd:string))
100
+ %<filter>s
101
+ }
102
+ SPARQL
103
+
104
+ # The CELLAR time a work last changed. The name is written as a full
105
+ # IRI, as every name outside the `cdm:` prefix is here.
106
+ MODIFIED = "<http://publications.europa.eu/ontology/cdm/cmr#lastModificationDate>".freeze
107
+
108
+ #
109
+ # Each row of one year, page by page (see #each_scoped).
110
+ #
111
+ # @param year [Integer]
112
+ # @yieldparam binding [Hash{String=>Hash}] one SPARQL result row
113
+ #
114
+ def each_row(year, &block)
115
+ each_scoped year_scope(year), &block
116
+ end
117
+
118
+ #
119
+ # Each row of a work CELLAR changed at or after a time, page by page
120
+ # (see #each_scoped).
121
+ #
122
+ # @param since [Time]
123
+ # @yieldparam binding [Hash{String=>Hash}] one SPARQL result row
124
+ #
125
+ def each_modified_row(since, &block)
126
+ each_scoped modified_scope(since), &block
127
+ end
128
+
129
+ #
130
+ # Each row of one scope, page by page.
131
+ #
132
+ # A page shorter than ROWS ends the scope. Virtuoso can answer a page
133
+ # short with HTTP 200 (a query timeout, a server row cap), so the scope
134
+ # is checked against a COUNT of its works first: a scope that read
135
+ # fewer rows raises `Relaton::RequestError` instead of publishing an
136
+ # index without them.
137
+ #
138
+ # @param scope [Scope]
139
+ # @yieldparam binding [Hash{String=>Hash}] one SPARQL result row
140
+ #
141
+ def each_scoped(scope, &block)
142
+ expected = count(scope)
143
+ read = 0
144
+ offset = 0
145
+ loop do
146
+ rows = page(scope, offset)
147
+ rows.each(&block)
148
+ read += rows.size
149
+ break if rows.size < ROWS
150
+
151
+ offset += ROWS
152
+ end
153
+ return if read == expected
154
+
155
+ raise Relaton::RequestError,
156
+ "CELLAR gave #{read} of #{expected} works #{scope.works}"
157
+ end
158
+
159
+ # @param scope [Scope]
160
+ # @return [Integer] the works of one scope
161
+ def count(scope)
162
+ rows = request fill(COUNT_QUERY, scope), "#{scope.what} count"
163
+ rows.dig(0, "n", "value").to_i
164
+ end
165
+
166
+ # @param scope [Scope]
167
+ # @return [Array<Hash>] the result bindings of one page
168
+ def page(scope, offset)
169
+ query = fill(QUERY, scope, limit: ROWS, offset: offset)
170
+ request query, "#{scope.what} offset #{offset}"
171
+ end
172
+
173
+ # @return [Scope] the works of one year
174
+ def year_scope(year)
175
+ Scope.new(%(cdm:resource_legal_year "#{Integer(year)}"^^xsd:gYear ;), "",
176
+ "year #{year}", "for year #{year}")
177
+ end
178
+
179
+ # @param since [Time]
180
+ # @return [Scope] the works changed at or after `since`
181
+ def modified_scope(since)
182
+ stamp = since.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
183
+ Scope.new("#{MODIFIED} ?modified ;",
184
+ %(FILTER(?modified >= "#{stamp}"^^xsd:dateTime)),
185
+ "changes since #{stamp}", "changed since #{stamp}")
186
+ end
187
+
188
+ #
189
+ # One request. A throttle, a server error or a transport error is
190
+ # retried with a growing wait; any other answer, an answer Virtuoso
191
+ # marks incomplete, or a request that keeps failing, raises
192
+ # `Relaton::RequestError`: a partial crawl would publish a partial
193
+ # index.
194
+ #
195
+ # @return [Array<Hash>] the result bindings
196
+ #
197
+ def request(query, what) # rubocop:disable Metrics/MethodLength
198
+ uri = query_uri(query)
199
+ ATTEMPTS.times do |n|
200
+ pacer.wait
201
+ resp, failure = attempt uri
202
+ return bindings(resp, what) if resp&.code == "200"
203
+ if resp && !RETRY_CODES.include?(resp.code)
204
+ raise Relaton::RequestError, "CELLAR HTTP #{resp.code} for #{what}"
205
+ end
206
+
207
+ break if n == ATTEMPTS - 1
208
+
209
+ Util.warn "CELLAR #{failure || "HTTP #{resp.code}"}, " \
210
+ "retry #{n + 1} of #{ATTEMPTS - 1}"
211
+ sleep FIRST_WAIT * (2**n)
212
+ end
213
+ raise Relaton::RequestError,
214
+ "CELLAR keeps failing for #{what} after #{ATTEMPTS} attempts"
215
+ end
216
+
217
+ private
218
+
219
+ def fill(query, scope, **page)
220
+ format(query, scope: scope.pattern, filter: scope.filter, **page)
221
+ end
222
+
223
+ # Virtuoso sends `X-SQL-State` with a 200 when it cut the answer
224
+ # short (an anytime query that hit its timeout).
225
+ def bindings(resp, what)
226
+ if resp["x-sql-state"]
227
+ raise Relaton::RequestError,
228
+ "CELLAR answer incomplete for #{what}: " \
229
+ "#{resp['x-sql-state']} #{resp['x-sql-message']}".strip
230
+ end
231
+
232
+ Relaton::Json.parse_external(resp.body).dig("results", "bindings") || []
233
+ end
234
+
235
+ def attempt(uri)
236
+ [http_get(uri), nil]
237
+ rescue *NET_ERRORS => e
238
+ [nil, "#{e.class}: #{e.message}"]
239
+ end
240
+
241
+ def query_uri(query)
242
+ uri = URI URL
243
+ uri.query = URI.encode_www_form(query: query)
244
+ uri
245
+ end
246
+
247
+ def http_get(uri)
248
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true,
249
+ open_timeout: 30, read_timeout: 180) do |http|
250
+ http.get uri.request_uri, "Accept" => "application/sparql-results+json"
251
+ end
252
+ end
253
+
254
+ def pacer
255
+ @pacer ||= Core::Pacer.new(gap: GAP)
256
+ end
257
+ end
258
+ end
259
+ end
@@ -0,0 +1,138 @@
1
+ require "time"
2
+ require_relative "../core"
3
+ require_relative "../eu"
4
+
5
+ module Relaton
6
+ module Eu
7
+ #
8
+ # Crawl every EU regulation, directive and decision from CELLAR into a
9
+ # data repo: one document a act and the pubid `index-v2`.
10
+ #
11
+ # Two sources:
12
+ #
13
+ # - `eu-cellar`, the full crawl: CELLAR is read one year at a time
14
+ # (`Cellar#each_row`), from the first year of the Official Journal to
15
+ # this year, into an empty index. Run it with `prune: true`, so an act
16
+ # CELLAR dropped loses its file.
17
+ # - `eu-cellar-updates`: only the works CELLAR changed since the last
18
+ # run (`Cellar#each_modified_row`), written over the existing data and
19
+ # added to the existing index. It cannot see a work CELLAR deleted, nor
20
+ # a change that does not touch the work (an author's new label), so the
21
+ # full crawl still runs from time to time. It refuses `prune: true`.
22
+ #
23
+ # Both write the start time of the run to SINCE_FILE; the next update
24
+ # run reads from one day before it. A page that keeps failing raises
25
+ # before the index and SINCE_FILE are written, so a failed run
26
+ # publishes nothing and the next one reads the same changes again.
27
+ #
28
+ class DataFetcher < Core::DataFetcher
29
+ FULL = "eu-cellar".freeze
30
+ UPDATES = "eu-cellar-updates".freeze
31
+ SOURCES = [FULL, UPDATES].freeze
32
+ # The first year of the Official Journal (of the ECSC).
33
+ FIRST_YEAR = 1952
34
+ # The start time of the last run that finished, in UTC (ISO 8601).
35
+ SINCE_FILE = "cellar-since.txt".freeze
36
+ # An update run reads from this long before the last run started:
37
+ # CELLAR's clock and the crawler's need not agree, and a work can be
38
+ # changed while a run reads its year.
39
+ OVERLAP = 24 * 60 * 60
40
+
41
+ def fetch(source = nil)
42
+ unless SOURCES.include? source
43
+ raise ArgumentError,
44
+ "Unknown source `#{source}`, expected one of #{SOURCES}"
45
+ end
46
+
47
+ started = Time.now.utc
48
+ @keys = {}
49
+ source == FULL ? fetch_all : fetch_updates
50
+ index.save
51
+ File.write SINCE_FILE, "#{started.strftime('%Y-%m-%dT%H:%M:%SZ')}\n"
52
+ report_errors
53
+ end
54
+
55
+ def index
56
+ # `pubid_class:` on the producer too: FileIO#save calls `to_hash` only
57
+ # for instances of it.
58
+ @index ||= Relaton::Index.find_or_create(
59
+ :eu, file: "#{INDEXFILE}.yaml", pubid_class: ::Pubid::Eu::Identifier
60
+ )
61
+ end
62
+
63
+ def log_error(msg)
64
+ Util.error msg
65
+ end
66
+
67
+ private
68
+
69
+ def cellar
70
+ @cellar ||= Cellar.new
71
+ end
72
+
73
+ def fetch_all
74
+ # Every full run writes the whole corpus, so the index starts empty:
75
+ # a row an earlier run wrote for an act that is now skipped would
76
+ # outlive its pruned file.
77
+ index.remove_all
78
+ (FIRST_YEAR..Date.today.year).each do |year|
79
+ cellar.each_row(year) { |row| parse_row row }
80
+ end
81
+ end
82
+
83
+ def fetch_updates
84
+ if prune
85
+ raise ArgumentError, "#{UPDATES} writes only the changed acts; " \
86
+ "prune would delete every other act. Prune " \
87
+ "with #{FULL}."
88
+ end
89
+
90
+ cellar.each_modified_row(last_run - OVERLAP) { |row| parse_row row }
91
+ end
92
+
93
+ # @return [Time] the start time of the last run, from SINCE_FILE
94
+ def last_run
95
+ unless File.exist? SINCE_FILE
96
+ raise ArgumentError, "#{UPDATES} needs #{SINCE_FILE}, which a " \
97
+ "finished #{FULL} run writes; run #{FULL} first"
98
+ end
99
+
100
+ Time.iso8601 File.read(SINCE_FILE, encoding: "UTF-8").strip
101
+ end
102
+
103
+ #
104
+ # Write one work and index it. A work the flavor does not cover (a
105
+ # corrigendum, a work with no ELI of a regulation, directive or
106
+ # decision) gives no item and is skipped. An ELI of a covered act that
107
+ # pubid cannot read is recorded in `@errors`, which `report_errors`
108
+ # sends to the crawl's GitHub issue.
109
+ #
110
+ # Two works of one act keep the first; the second is logged. The act is
111
+ # its ELI, not its printed id: the print order (`number_first`) is not
112
+ # part of the act's identity.
113
+ #
114
+ def parse_row(row)
115
+ parser = Parser.new(row)
116
+ item = parser.parse
117
+ @errors["ELI #{row.dig('eli', 'value')}"] = parser.error if parser.error
118
+ return unless item
119
+
120
+ name = parser.pubid.to_s
121
+ act = parser.pubid.to_eli
122
+ celex = row.dig("celex", "value")
123
+ if @keys[act]
124
+ return Util.warn "Skipped CELEX #{celex}: CELEX #{@keys[act]} " \
125
+ "is the same act", key: name
126
+ end
127
+
128
+ @keys[act] = celex
129
+ file = write_unique name, serialize(item)
130
+ index.add_or_update parser.pubid, file
131
+ end
132
+
133
+ def to_yaml(bib) = bib.to_yaml
134
+ def to_xml(bib) = bib.to_xml(bibdata: true)
135
+ def to_bibxml(bib) = bib.to_rfcxml
136
+ end
137
+ end
138
+ end