wp2txt 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +16 -1
  3. data/.github/workflows/publish-image.yml +8 -4
  4. data/.gitignore +0 -1
  5. data/CHANGELOG.md +23 -0
  6. data/DEVELOPMENT.md +62 -92
  7. data/DEVELOPMENT_ja.md +60 -92
  8. data/Dockerfile +1 -1
  9. data/README.md +54 -8
  10. data/README_ja.md +54 -8
  11. data/bin/wp2txt +23 -6
  12. data/lib/wp2txt/article.rb +1 -2
  13. data/lib/wp2txt/bz2_stream.rb +63 -0
  14. data/lib/wp2txt/cli.rb +48 -26
  15. data/lib/wp2txt/config.rb +2 -11
  16. data/lib/wp2txt/constants.rb +0 -1
  17. data/lib/wp2txt/corpus.rb +1 -21
  18. data/lib/wp2txt/data/template_aliases.json +3 -0
  19. data/lib/wp2txt/data/template_patterns.json +61643 -0
  20. data/lib/wp2txt/dump_snapshot.rb +99 -0
  21. data/lib/wp2txt/extraction_run.rb +272 -0
  22. data/lib/wp2txt/extractor.rb +476 -325
  23. data/lib/wp2txt/fts_index.rb +1 -1
  24. data/lib/wp2txt/index_cache.rb +144 -55
  25. data/lib/wp2txt/index_commands.rb +22 -19
  26. data/lib/wp2txt/link_counter.rb +1 -1
  27. data/lib/wp2txt/magic_words.rb +44 -28
  28. data/lib/wp2txt/metadata_index.rb +6 -13
  29. data/lib/wp2txt/multistream.rb +890 -824
  30. data/lib/wp2txt/output_writer.rb +3 -1
  31. data/lib/wp2txt/parser_functions.rb +23 -5
  32. data/lib/wp2txt/ractor_worker.rb +6 -4
  33. data/lib/wp2txt/regex.rb +24 -4
  34. data/lib/wp2txt/site_info.rb +123 -0
  35. data/lib/wp2txt/stream_store.rb +91 -0
  36. data/lib/wp2txt/template_args.rb +111 -0
  37. data/lib/wp2txt/template_expander.rb +92 -125
  38. data/lib/wp2txt/template_patterns.rb +182 -0
  39. data/lib/wp2txt/utils.rb +160 -125
  40. data/lib/wp2txt/version.rb +1 -1
  41. data/spec/auto_download_spec.rb +9 -6
  42. data/spec/category_fetcher_spec.rb +135 -463
  43. data/spec/cli_targeted_spec.rb +60 -0
  44. data/spec/config_spec.rb +2 -15
  45. data/spec/constants_spec.rb +0 -4
  46. data/spec/dump_fetch_spec.rb +293 -0
  47. data/spec/extraction_run_spec.rb +520 -0
  48. data/spec/index_build_spec.rb +113 -0
  49. data/spec/index_commands_version_spec.rb +17 -0
  50. data/spec/multistream_reader_spec.rb +140 -0
  51. data/spec/multistream_spec.rb +8 -214
  52. data/spec/output_integrity_spec.rb +45 -2
  53. data/spec/regex_spec.rb +30 -0
  54. data/spec/spec_helper.rb +3 -3
  55. data/spec/support/dump_status.rb +34 -0
  56. data/spec/support/multistream_fixture.rb +26 -8
  57. data/spec/template_args_spec.rb +133 -0
  58. data/spec/template_expander_spec.rb +29 -111
  59. data/spec/template_passthrough_spec.rb +17 -2
  60. data/spec/template_patterns_spec.rb +253 -0
  61. data/spec/tracked_paths_spec.rb +168 -0
  62. data/spec/utils_spec.rb +7 -1
  63. metadata +30 -5
  64. data/lib/wp2txt/category_cache.rb +0 -313
  65. data/spec/category_cache_spec.rb +0 -226
@@ -7,9 +7,15 @@ require "uri"
7
7
  require "openssl"
8
8
  require "parallel"
9
9
  require "set"
10
+ require "digest"
11
+ require "securerandom"
12
+ require "time"
10
13
  require_relative "constants"
14
+ require_relative "bz2_stream"
15
+ require_relative "dump_snapshot"
16
+ require_relative "stream_store"
17
+ require_relative "site_info"
11
18
  require_relative "index_cache"
12
- require_relative "category_cache"
13
19
 
14
20
  module Wp2txt
15
21
  # Maximum number of retries for transient network errors
@@ -171,62 +177,41 @@ module Wp2txt
171
177
  def load_index
172
178
  return unless File.exist?(@index_path)
173
179
 
174
- # Handle both .bz2 and plain text index files
175
- if @index_path.end_with?(".bz2")
176
- require "open3"
177
- IO.popen(["bzcat", @index_path], "r") do |io|
178
- parse_index_stream(io)
179
- end
180
- else
181
- File.open(@index_path, "r") do |io|
182
- parse_index_stream(io)
183
- end
184
- end
185
- end
186
-
187
- def next_stream_offset_after(io, offset)
188
- io.each_line do |line|
189
- next_offset = line.split(":", 2).first.to_i
190
- return next_offset if next_offset > offset
191
- end
192
- nil
193
- end
194
-
195
- def parse_index_stream(io)
196
180
  count = 0
197
- io.each_line do |line|
198
- line = line.strip
199
- next if line.empty?
200
-
201
- parts = line.split(":", 3)
202
- next if parts.size < 3
203
-
204
- offset = parts[0].to_i
205
- page_id = parts[1].to_i
206
- title = parts[2]
207
-
208
- entry = { offset: offset, page_id: page_id, title: title }
209
- @entries_by_title[title] = entry
210
- @entries_by_id[page_id] = entry
181
+ # Offset of the stream holding the last target, once every target is found:
182
+ # the scan reads on only to learn where that stream ends
183
+ last_stream = nil
184
+ Wp2txt.each_index_line(@index_path) do |offset, page_id, title|
185
+ if last_stream
186
+ next if offset == last_stream
187
+
188
+ @stream_end_offset = offset
189
+ break
190
+ end
211
191
 
212
- if @stream_offsets.empty? || @stream_offsets.last != offset
213
- @stream_offsets << offset
192
+ @stream_offsets << offset if @stream_offsets.empty? || @stream_offsets.last != offset
193
+ # A targeted scan keeps only the targets: the full index of a large
194
+ # wiki would take gigabytes of memory
195
+ if @target_titles.nil? || @target_titles.include?(title)
196
+ entry = { offset: offset, page_id: page_id, title: title }
197
+ @entries_by_title[title] = entry
198
+ @entries_by_id[page_id] = entry
214
199
  end
215
200
 
216
- # Early termination: check if we found all target titles
217
- if @target_titles
218
- @found_targets << title if @target_titles.include?(title)
201
+ if @target_titles&.include?(title)
202
+ @found_targets << title
219
203
  if @found_targets.size == @target_titles.size
220
204
  @early_terminated = true
221
- @stream_end_offset = next_stream_offset_after(io, offset)
222
- print "\r Found all #{@target_titles.size} target articles" if @show_progress
223
- puts if @show_progress
224
- break
205
+ last_stream = offset
206
+ if @show_progress
207
+ print "\r Found all #{@target_titles.size} target articles"
208
+ puts
209
+ end
225
210
  end
226
211
  end
227
212
 
228
213
  count += 1
229
- if @show_progress && count % INDEX_PROGRESS_THRESHOLD == 0
214
+ if @show_progress && (count % INDEX_PROGRESS_THRESHOLD).zero?
230
215
  print "\r Parsed #{count / 1_000_000.0}M entries..."
231
216
  $stdout.flush
232
217
  end
@@ -240,6 +225,8 @@ module Wp2txt
240
225
  # A single multistream bz2 stream holds about 100 pages; anything this large
241
226
  # past the last known offset is several streams, not one.
242
227
  MAX_TAIL_STREAM_BYTES = 64 * 1024 * 1024
228
+ # Ranges each process reads per batch when reading in parallel
229
+ RANGES_PER_PROCESS = 8
243
230
 
244
231
  attr_reader :multistream_path, :index
245
232
 
@@ -250,6 +237,10 @@ module Wp2txt
250
237
  # @param cache_dir [String, nil] Directory for SQLite cache (only used if index_or_path is a path)
251
238
  def initialize(multistream_path, index_or_path, use_cache: true, cache_dir: nil)
252
239
  @multistream_path = multistream_path
240
+ # Opened once: if the path is later given another file (a newer version
241
+ # of the same date), this reader still reads the one it was given.
242
+ # Forked readers share the descriptor; pread leaves its position alone.
243
+ @dump_file = File.open(multistream_path, "rb") if multistream_path.is_a?(String) && File.file?(multistream_path)
253
244
 
254
245
  # Accept an existing index (or any object with the same lookup interface,
255
246
  # e.g. a lazy SQLite-backed one) or a path to create one
@@ -261,98 +252,82 @@ module Wp2txt
261
252
  end
262
253
 
263
254
  # Extract a single article by title
255
+ # @return [Hash, nil] the page, or nil when the title is not indexed or
256
+ # its range holds no page of that title
257
+ # @raise [StreamError] when the range cannot be read in full
264
258
  def extract_article(title)
265
259
  entry = @index.find_by_title(title)
266
260
  return nil unless entry
267
261
 
268
- stream_content = read_stream_at(entry[:offset])
269
- extract_page_from_xml(stream_content, title)
262
+ pages_at(entry[:offset]).find { |page| page[:title] == title }
270
263
  end
271
264
 
272
265
  # Extract multiple articles (sequential)
273
266
  def extract_articles(titles)
274
- # Group by stream offset for efficiency
275
267
  grouped = titles.group_by { |t| @index.stream_offset_for(t) }
268
+ grouped.delete(nil)
276
269
 
277
- results = {}
278
- grouped.each do |offset, titles_in_stream|
279
- next unless offset
280
-
281
- stream_content = read_stream_at(offset)
282
- titles_in_stream.each do |title|
283
- page = extract_page_from_xml(stream_content, title)
284
- results[title] = page if page
285
- end
270
+ grouped.each_with_object({}) do |(offset, titles_in_stream), results|
271
+ results.merge!(pages_by_title(offset, titles_in_stream))
286
272
  end
287
- results
288
273
  end
289
274
 
290
275
  # Extract multiple articles in parallel (by stream)
291
276
  # @param titles [Array<String>] Article titles to extract
292
277
  # @param num_processes [Integer] Number of parallel processes (default: 4)
293
- # @param progress_callback [Proc, nil] Optional callback for progress updates
294
278
  # @return [Hash] Map of title => page data
295
- def extract_articles_parallel(titles, num_processes: 4, &progress_callback)
296
- # Group titles by stream offset
279
+ # @raise [StreamError] when a range cannot be read in full
280
+ def extract_articles_parallel(titles, num_processes: 4)
297
281
  grouped = titles.group_by { |t| @index.stream_offset_for(t) }
298
282
  grouped.delete(nil) # Remove titles not found in index
299
283
 
300
- # Process streams in parallel
301
284
  stream_results = Parallel.map(grouped.keys, in_processes: num_processes) do |offset|
302
- titles_in_stream = grouped[offset]
303
- stream_content = read_stream_at(offset)
304
-
305
- stream_pages = {}
306
- titles_in_stream.each do |title|
307
- page = extract_page_from_xml(stream_content, title)
308
- stream_pages[title] = page if page
309
- end
310
-
311
- stream_pages
312
- end
313
-
314
- # Merge results from all streams
315
- results = {}
316
- stream_results.each do |stream_pages|
317
- results.merge!(stream_pages)
285
+ pages_by_title(offset, grouped[offset])
318
286
  end
287
+ stream_results.reduce({}, :merge)
288
+ end
289
+
290
+ # Read the pages for index entries and report on every entry: yields
291
+ # [entry, page, error]. The page is nil when its range was read in full but
292
+ # holds no such page; error ({reason:, message:}) says why a range could not
293
+ # be read, and then applies to every entry in it. Results come range by
294
+ # range (in batches when reading in parallel), so the pages of all the
295
+ # entries are never held at once.
296
+ # @param entries [Array<Hash>] index entries with :title and :offset
297
+ # @param num_processes [Integer] parallel processes (1 = in this process)
298
+ # @param before_fork [Proc, nil] called before each batch is forked, e.g. to
299
+ # flush output the forked processes must not inherit
300
+ def each_entry_result(entries, num_processes: 1, before_fork: nil, &block)
301
+ return enum_for(:each_entry_result, entries, num_processes: num_processes, before_fork: before_fork) unless block
319
302
 
320
- results
321
- end
322
-
323
- # Iterate through articles in parallel, yielding each page
324
- # Groups articles by stream and processes streams in parallel
325
- # @param entries [Array<Hash>] Array of index entries with :title and :offset
326
- # @param num_processes [Integer] Number of parallel processes
327
- # @yield [Hash] Page data for each article
328
- def each_article_parallel(entries, num_processes: 4)
329
- return enum_for(:each_article_parallel, entries, num_processes: num_processes) unless block_given?
330
-
331
- # Group by stream offset
332
303
  grouped = entries.group_by { |e| e[:offset] }
304
+ read_range = lambda do |offset|
305
+ pages = pages_by_title(offset, grouped[offset].map { |e| e[:title] })
306
+ grouped[offset].map { |e| [e, pages[e[:title]], nil] }
307
+ rescue StreamError => e
308
+ error = { reason: e.reason, message: e.message }
309
+ grouped[offset].map { |entry| [entry, nil, error] }
310
+ end
333
311
 
334
- # Process streams in parallel, collecting all pages
335
- all_pages = Parallel.flat_map(grouped.keys, in_processes: num_processes) do |offset|
336
- entries_in_stream = grouped[offset]
337
- stream_content = read_stream_at(offset)
338
-
339
- pages = []
340
- entries_in_stream.each do |entry|
341
- page = extract_page_from_xml(stream_content, entry[:title])
342
- pages << page if page
312
+ if num_processes > 1 && grouped.size > 1
313
+ grouped.keys.each_slice(num_processes * RANGES_PER_PROCESS) do |batch|
314
+ before_fork&.call
315
+ Parallel.flat_map(batch, in_processes: num_processes, &read_range).each { |result| block.call(*result) }
343
316
  end
344
-
345
- pages
317
+ else
318
+ grouped.each_key { |offset| read_range.call(offset).each { |result| block.call(*result) } }
346
319
  end
320
+ end
347
321
 
348
- # Yield each page (sequential, as yielding must happen in main process)
349
- all_pages.each { |page| yield page }
322
+ # Close the dump file the reader keeps open
323
+ def close
324
+ @dump_file&.close
325
+ @dump_file = nil
350
326
  end
351
327
 
352
328
  # Iterate through all articles in a stream
353
329
  def each_article_in_stream(offset, &block)
354
- stream_content = read_stream_at(offset)
355
- extract_all_pages_from_xml(stream_content, &block)
330
+ pages_at(offset).each(&block)
356
331
  end
357
332
 
358
333
  # Iterate through first N streams
@@ -362,32 +337,80 @@ module Wp2txt
362
337
  end
363
338
  end
364
339
 
340
+ # The dump header (XML declaration, <mediawiki> and <siteinfo>) and the
341
+ # closing </mediawiki> sit in streams of their own, but the header may
342
+ # share a stream with the first pages, and the last index range runs to
343
+ # the end of the file, so it holds the closing tag as well.
344
+ HEADER_REGEX = %r{\A\s*(?:<\?xml[^>]*\?>\s*)?<mediawiki\b[^>]*>(?:\s*<siteinfo\b.*?</siteinfo>)?}m
345
+ FOOTER_REGEX = %r{</mediawiki>\s*\z}
346
+
347
+ # Parse the pages of one index range. Nothing is repaired: a page cut
348
+ # short is an error, not a shorter page.
349
+ # @raise [StreamError] when the pages are not well-formed XML
350
+ # @param last [Boolean] whether this is the last range of the dump
351
+ def self.parse_pages(xml, offset: nil, last: false)
352
+ require "nokogiri"
353
+
354
+ body = xml.scrub("\uFFFD").sub(HEADER_REGEX, "")
355
+ body = body.sub(FOOTER_REGEX, "") if last
356
+ doc = Nokogiri::XML("<pages>#{body}</pages>") { |config| config.strict.nonet.huge }
357
+ doc.root.xpath("page").map { |node| page_from_node(node) }
358
+ rescue Nokogiri::XML::SyntaxError => e
359
+ raise StreamError.new("malformed pages in the range at offset #{offset}: #{e.message}", offset: offset)
360
+ end
361
+
362
+ def self.page_from_node(node)
363
+ text_node = node.at_xpath("revision/text")
364
+ {
365
+ title: node.at_xpath("title")&.text,
366
+ id: node.at_xpath("id")&.text&.to_i,
367
+ ns: node.at_xpath("ns")&.text&.to_i,
368
+ revision_id: node.at_xpath("revision/id")&.text&.to_i,
369
+ redirect: node.at_xpath("redirect")&.[]("title"),
370
+ text: text_node&.text || "",
371
+ # A revision whose text was suppressed has <text deleted="deleted" />;
372
+ # an article that is really empty has a plain <text />
373
+ text_available: !text_node.nil? && text_node["deleted"].nil?
374
+ }
375
+ end
376
+
365
377
  private
366
378
 
367
- def read_stream_at(offset)
368
- # Read the bz2 stream starting at the given offset
369
- # We need to find where this stream ends (next stream start or EOF)
379
+ def pages_at(offset)
370
380
  next_offset = find_next_offset(offset)
381
+ self.class.parse_pages(read_stream_at(offset, next_offset), offset: offset, last: next_offset.nil?)
382
+ end
383
+
384
+ def pages_by_title(offset, titles)
385
+ wanted = titles.to_set
386
+ pages_at(offset).each_with_object({}) do |page, found|
387
+ found[page[:title]] = page if wanted.include?(page[:title])
388
+ end
389
+ end
371
390
 
372
- File.open(@multistream_path, "rb") do |f|
373
- f.seek(offset)
391
+ def read_stream_at(offset, next_offset)
392
+ compressed_data = if @multistream_path.respond_to?(:read_range)
393
+ @multistream_path.read_range(offset, next_offset)
394
+ else
395
+ read_file_range(offset, next_offset)
396
+ end
397
+ Wp2txt.decompress_bz2(compressed_data.to_s, offset: offset)
398
+ end
374
399
 
375
- if next_offset
376
- compressed_data = f.read(next_offset - offset)
377
- else
378
- # Last stream of the dump: the rest of the file is that one stream.
379
- # A large remainder means the end was never recorded, and reading it
380
- # in one call fails outright on some platforms (EINVAL on macOS).
381
- remaining = File.size(@multistream_path) - offset
382
- if remaining > MAX_TAIL_STREAM_BYTES
383
- raise Wp2txt::Error, "cannot locate the end of the stream at offset #{offset} " \
384
- "(#{remaining} bytes to end of file); the index may be incomplete"
385
- end
386
- compressed_data = f.read
387
- end
400
+ # Bytes of the range from offset up to the next stream start (or EOF)
401
+ def read_file_range(offset, next_offset)
402
+ file = @dump_file ||= File.open(@multistream_path, "rb")
403
+ return file.pread(next_offset - offset, offset) if next_offset
388
404
 
389
- decompress_bz2(compressed_data)
405
+ # Last stream of the dump: the rest of the file is that one stream.
406
+ # A large remainder means the end was never recorded, and reading it
407
+ # in one call fails outright on some platforms (EINVAL on macOS).
408
+ remaining = file.size - offset
409
+ if remaining > MAX_TAIL_STREAM_BYTES
410
+ raise Wp2txt::Error, "cannot locate the end of the stream at offset #{offset} " \
411
+ "(#{remaining} bytes to end of file); the index may be incomplete"
390
412
  end
413
+ remaining.positive? ? file.pread(remaining, offset) : ""
391
414
  end
392
415
 
393
416
  def find_next_offset(current_offset)
@@ -401,53 +424,16 @@ module Wp2txt
401
424
 
402
425
  @index.respond_to?(:stream_end_offset) ? @index.stream_end_offset : nil
403
426
  end
404
-
405
- def decompress_bz2(data)
406
- require "stringio"
407
- require "open3"
408
-
409
- stdout, status = Open3.capture2("bzcat", stdin_data: data)
410
- stdout
411
- end
412
-
413
- def extract_page_from_xml(xml_content, title)
414
- # Simple extraction - find the page with matching title
415
- require "nokogiri"
416
-
417
- doc = Nokogiri::XML("<root>#{xml_content}</root>")
418
- doc.xpath("//page").each do |page_node|
419
- page_title = page_node.at_xpath("title")&.text
420
- if page_title == title
421
- return {
422
- title: page_title,
423
- id: page_node.at_xpath("id")&.text&.to_i,
424
- revision_id: page_node.at_xpath("revision/id")&.text&.to_i,
425
- text: page_node.at_xpath(".//text")&.text || ""
426
- }
427
- end
428
- end
429
- nil
430
- end
431
-
432
- def extract_all_pages_from_xml(xml_content, &block)
433
- require "nokogiri"
434
-
435
- doc = Nokogiri::XML("<root>#{xml_content}</root>")
436
- doc.xpath("//page").each do |page_node|
437
- page = {
438
- title: page_node.at_xpath("title")&.text,
439
- id: page_node.at_xpath("id")&.text&.to_i,
440
- revision_id: page_node.at_xpath("revision/id")&.text&.to_i,
441
- text: page_node.at_xpath(".//text")&.text || ""
442
- }
443
- yield page if page[:title]
444
- end
445
- end
446
427
  end
447
428
 
448
429
  # Manages downloading and caching of dump files
449
430
  # Supports any Wikipedia language code (e.g., en, ja, de, fr, zh, ar, etc.)
450
431
  # Language metadata is stored in lib/wp2txt/data/language_metadata.json
432
+ #
433
+ # A manager works with one dump version (a DumpSnapshot), chosen once: the
434
+ # date asked for, else the newest finished version (checked over the network
435
+ # at most once every dump_expiry_days), else, offline, the newest one cached.
436
+ # Every file it fetches is checked against that version before it is kept.
451
437
  class DumpManager
452
438
  DUMP_BASE_URL = "https://dumps.wikimedia.org"
453
439
  DEFAULT_CACHE_DIR = File.expand_path("~/.wp2txt/cache")
@@ -455,6 +441,25 @@ module Wp2txt
455
441
  # Legacy constant for backward compatibility
456
442
  CACHE_DIR = "tmp/dump_cache"
457
443
 
444
+ # Newest dump dates looked at when searching for a finished version
445
+ MAX_DATES_TRIED = 3
446
+ # Attempts per fetch, the first one included, for transient failures only
447
+ FETCH_ATTEMPTS = 4
448
+ # Ranges fetched at the same time; the dump server answers more
449
+ # simultaneous connections from one client with 429 Too Many Requests
450
+ PARALLEL_FETCHES = 2
451
+ # Adjacent ranges are fetched together up to this many bytes per request
452
+ MAX_GROUP_BYTES = 64 * 1024 * 1024
453
+ # Files at least this large show download progress
454
+ PROGRESS_MIN_BYTES = 8 * 1024 * 1024
455
+
456
+ NETWORK_ERRORS = [Net::OpenTimeout, Net::ReadTimeout, SocketError, EOFError, IOError,
457
+ Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH,
458
+ Errno::ETIMEDOUT, OpenSSL::SSL::SSLError, Wp2txt::NetworkError].freeze
459
+
460
+ # A failure worth another attempt: a dropped connection, a short body, a 5xx
461
+ class TransientFetchError < Wp2txt::NetworkError; end
462
+
458
463
  attr_reader :lang, :cache_dir, :dump_expiry_days
459
464
 
460
465
  class << self
@@ -464,10 +469,14 @@ module Wp2txt
464
469
  end
465
470
  end
466
471
 
467
- def initialize(lang, cache_dir: nil, dump_expiry_days: nil)
472
+ # @param dump_date [String, nil] use this dump version (YYYYMMDD) instead of the newest
473
+ # @param update [Boolean] check for the newest version now, even within dump_expiry_days
474
+ def initialize(lang, cache_dir: nil, dump_expiry_days: nil, dump_date: nil, update: false)
468
475
  @lang = lang.to_sym
469
476
  @cache_dir = cache_dir || DEFAULT_CACHE_DIR
470
477
  @dump_expiry_days = dump_expiry_days || Wp2txt::DEFAULT_DUMP_EXPIRY_DAYS
478
+ @dump_date = dump_date&.to_s
479
+ @update = update
471
480
  FileUtils.mkdir_p(@cache_dir)
472
481
  end
473
482
 
@@ -476,374 +485,122 @@ module Wp2txt
476
485
  Wp2txt.format_file_size(bytes)
477
486
  end
478
487
 
479
- # Get the latest dump date for a language
480
- def latest_dump_date
481
- @latest_dump_date ||= fetch_latest_dump_date
488
+ # The dump version this manager works with, fixed for its lifetime
489
+ # @return [DumpSnapshot]
490
+ def snapshot
491
+ @snapshot ||= select_snapshot
482
492
  end
483
493
 
484
- # Download multistream index file
485
- def download_index(force: false)
486
- index_path = cached_index_path
487
- if File.exist?(index_path) && !force
488
- puts "Index already cached: #{File.basename(index_path)}"
489
- $stdout.flush
490
- return index_path
491
- end
492
-
493
- url = index_url
494
- puts "Downloading index: #{url}"
495
- $stdout.flush
496
- download_file(url, index_path)
497
- index_path
498
- end
499
-
500
- # Download multistream dump file
501
- # @param force [Boolean] Force re-download even if cached
502
- # @param max_streams [Integer, nil] If set, only download first N streams (partial download)
503
- def download_multistream(force: false, max_streams: nil)
504
- # For partial downloads, first check if full dump exists (most efficient)
505
- if max_streams && !force
506
- full_path = cached_multistream_path
507
- if File.exist?(full_path)
508
- puts "Using cached full dump: #{File.basename(full_path)}"
509
- $stdout.flush
510
- return full_path
511
- end
512
-
513
- # Check if a larger partial download exists
514
- existing_partial = find_suitable_partial_cache(max_streams)
515
- if existing_partial
516
- puts "Using cached partial: #{File.basename(existing_partial)}"
517
- $stdout.flush
518
- return existing_partial
519
- end
520
- end
521
-
522
- dump_path = max_streams ? cached_partial_multistream_path(max_streams) : cached_multistream_path
523
- if File.exist?(dump_path) && !force
524
- puts "Multistream already cached: #{File.basename(dump_path)}"
525
- $stdout.flush
526
- return dump_path
527
- end
528
-
529
- url = multistream_url
530
-
531
- if max_streams
532
- # Partial download: need index first to know byte range
533
- index_path = download_index
534
- index = MultistreamIndex.new(index_path, cache_dir: @cache_dir)
494
+ # Date of the dump version in use
495
+ def latest_dump_date
496
+ snapshot.date
497
+ end
535
498
 
536
- if index.stream_offsets.size >= max_streams
537
- # Get byte range for first N streams
538
- end_offset = index.stream_offsets[max_streams]
539
- puts "Downloading first #{max_streams} streams (#{format_size(end_offset)}): #{url}"
540
- $stdout.flush
541
- download_file_range(url, dump_path, 0, end_offset - 1)
542
- else
543
- puts "Only #{index.stream_offsets.size} streams available, downloading all"
544
- $stdout.flush
545
- download_file(url, dump_path)
546
- end
547
- else
548
- puts "Downloading multistream: #{url}"
549
- $stdout.flush
550
- download_file(url, dump_path)
551
- end
499
+ # How the version in use was chosen, for messages: :requested, :recent, :checked, :offline
500
+ attr_reader :snapshot_origin
552
501
 
553
- dump_path
502
+ # Download multistream index file (or use the cached one once it checks out)
503
+ # @return [String] the version's pinned path of the index
504
+ def download_index(force: false)
505
+ ensure_file(snapshot.index_file, cached_index_path, index_url, force: force, label: "index")
554
506
  end
555
507
 
556
- # Find a suitable cached partial download (same or larger than needed)
557
- # @param min_streams [Integer] Minimum number of streams needed
558
- # @return [String, nil] Path to suitable cached file, or nil
559
- def find_suitable_partial_cache(min_streams)
560
- pattern = File.join(@cache_dir, "#{@lang}wiki-#{latest_dump_date}-multistream-*streams.xml.bz2")
561
- Dir.glob(pattern).each do |path|
562
- if path =~ /multistream-(\d+)streams\.xml\.bz2$/
563
- stream_count = $1.to_i
564
- return path if stream_count >= min_streams
565
- end
566
- end
567
- nil
508
+ # Download the whole multistream dump file (or use the cached one once it checks out)
509
+ # @return [String] the version's pinned path of the dump file
510
+ def download_multistream(force: false)
511
+ ensure_file(snapshot.dump_file, cached_multistream_path, multistream_url, force: force, label: "dump")
568
512
  end
569
513
 
570
- # Find any existing partial dump (any date)
571
- # @return [Hash, nil] Info about existing partial dump, or nil
572
- def find_any_partial_cache
573
- pattern = File.join(@cache_dir, "#{@lang}wiki-*-multistream-*streams.xml.bz2")
574
- partials = []
575
-
576
- Dir.glob(pattern).each do |path|
577
- if path =~ /#{@lang}wiki-(\d{8})-multistream-(\d+)streams\.xml\.bz2$/
578
- dump_date = $1
579
- stream_count = $2.to_i
580
- partials << {
581
- path: path,
582
- dump_date: dump_date,
583
- stream_count: stream_count,
584
- size: File.size(path),
585
- mtime: File.mtime(path)
586
- }
587
- end
588
- end
514
+ # Names of the cached index and dump files that are not this version's.
515
+ # A shared name passes only when it names the file pinned for the version
516
+ # (a file not yet pinned is checked, and pinned when it matches).
517
+ # @return [Array<String>]
518
+ def mismatched_cached_files
519
+ [[snapshot.index_file, cached_index_path], [snapshot.dump_file, cached_multistream_path]].reject do |info, path|
520
+ next false unless File.exist?(path)
521
+ next pinned_file?(info, path) if usable_pin?(info)
589
522
 
590
- # Return the largest partial (by stream count)
591
- partials.max_by { |p| p[:stream_count] }
523
+ check_and_pin(info, path)
524
+ end.map { |_, path| File.basename(path) }
592
525
  end
593
526
 
594
- # Check if incremental download is possible from existing partial
595
- # @param partial_info [Hash] Info from find_any_partial_cache
596
- # @return [Hash] Result with :possible, :reason, and details
597
- def can_resume_from_partial?(partial_info)
598
- return { possible: false, reason: :no_partial } unless partial_info
599
-
600
- current_date = latest_dump_date
527
+ # Give the cache's shared names (used by --build-index and MCP) to the
528
+ # files pinned for this version, replacing names that held another
529
+ # version's files. Each name changes by one rename.
530
+ def align_cached_names!
531
+ [[snapshot.index_file, cached_index_path], [snapshot.dump_file, cached_multistream_path]].each do |info, path|
532
+ next unless usable_pin?(info)
533
+ next if pinned_file?(info, path)
601
534
 
602
- # Check if dump dates match
603
- if partial_info[:dump_date] != current_date
604
- return {
605
- possible: false,
606
- reason: :date_mismatch,
607
- partial_date: partial_info[:dump_date],
608
- latest_date: current_date
609
- }
535
+ link_atomically(pinned_path(info), path)
610
536
  end
611
-
612
- # Validate the partial file with Bz2Validator
613
- require_relative "bz2_validator"
614
- validation = Bz2Validator.validate_quick(partial_info[:path])
615
- unless validation.valid?
616
- return {
617
- possible: false,
618
- reason: :invalid_partial,
619
- error: validation.message
620
- }
621
- end
622
-
623
- # Verify file size matches expected offset
624
- index_path = download_index
625
- index = MultistreamIndex.new(index_path, cache_dir: @cache_dir)
626
-
627
- expected_size = if partial_info[:stream_count] < index.stream_offsets.size
628
- index.stream_offsets[partial_info[:stream_count]]
629
- else
630
- # Partial has all streams - no need to resume
631
- return { possible: false, reason: :already_complete }
632
- end
633
-
634
- actual_size = partial_info[:size]
635
- if actual_size != expected_size
636
- return {
637
- possible: false,
638
- reason: :size_mismatch,
639
- expected: expected_size,
640
- actual: actual_size
641
- }
642
- end
643
-
644
- {
645
- possible: true,
646
- partial_info: partial_info,
647
- current_streams: partial_info[:stream_count],
648
- total_streams: index.stream_offsets.size,
649
- current_size: actual_size
650
- }
651
537
  end
652
538
 
653
- # Download full dump with incremental support
654
- # @param force [Boolean] Force re-download
655
- # @param interactive [Boolean] Prompt user for choices (default: true)
656
- # @return [String] Path to downloaded file
657
- def download_multistream_full(force: false, interactive: true)
658
- full_path = cached_multistream_path
659
-
660
- # If full dump exists, use it
661
- if File.exist?(full_path) && !force
662
- puts "Using cached full dump: #{File.basename(full_path)}"
663
- $stdout.flush
664
- return full_path
665
- end
666
-
667
- # Check for existing partial dump
668
- partial = find_any_partial_cache
669
- if partial && interactive
670
- resume_info = can_resume_from_partial?(partial)
671
-
672
- if resume_info[:possible]
673
- # Same date - can resume
674
- return handle_resumable_partial(partial, resume_info, force)
675
- elsif resume_info[:reason] == :date_mismatch
676
- # Different date - ask user
677
- return handle_outdated_partial(partial, resume_info, force)
678
- elsif resume_info[:reason] == :size_mismatch || resume_info[:reason] == :invalid_partial
679
- # Corrupted partial - inform and re-download
680
- puts "Warning: Existing partial dump appears corrupted."
681
- puts " Reason: #{resume_info[:reason]}"
682
- puts " Will download fresh copy."
683
- FileUtils.rm_f(partial[:path])
684
- end
685
- end
686
-
687
- # Standard full download
688
- download_multistream(force: force, max_streams: nil)
539
+ # The cached whole dump, when it is known to be this version's complete
540
+ # file. Checking an unrecorded one would mean hashing gigabytes, which
541
+ # costs more than fetching the few ranges a targeted extraction needs.
542
+ def verified_full_dump
543
+ usable_pin?(snapshot.dump_file) ? pinned_path(snapshot.dump_file) : nil
689
544
  end
690
545
 
691
- private
692
-
693
- def handle_resumable_partial(partial, resume_info, force)
694
- current = resume_info[:current_streams]
695
- total = resume_info[:total_streams]
696
- current_size = resume_info[:current_size]
697
-
698
- # Calculate remaining download size
699
- index_path = cached_index_path
700
- index = MultistreamIndex.new(index_path, cache_dir: @cache_dir)
701
-
702
- # Get total file size from HTTP HEAD request
703
- url = multistream_url
704
- total_size = get_remote_file_size(url)
705
- remaining_size = total_size - current_size
706
-
707
- puts
708
- puts "Found existing partial dump (same date):"
709
- puts " Current: #{current} streams (#{format_size(current_size)})"
710
- puts " Total: #{total} streams (#{format_size(total_size)})"
711
- puts " Remaining: #{format_size(remaining_size)}"
712
- puts
713
-
714
- print "Download remaining data? [Y/n/f(ull fresh download)]: "
715
- $stdout.flush
716
- response = $stdin.gets&.strip&.downcase || "y"
717
-
718
- case response
719
- when "n", "no"
720
- puts "Using existing partial dump."
721
- partial[:path]
722
- when "f", "full", "fresh"
723
- puts "Downloading fresh full dump..."
724
- FileUtils.rm_f(partial[:path])
725
- download_multistream(force: true, max_streams: nil)
726
- else
727
- # Resume download
728
- puts "Resuming download..."
729
- download_incremental(partial[:path], current_size, total_size)
730
- end
546
+ # Ranges of this version's dump kept on disk
547
+ def stream_store
548
+ StreamStore.new(File.join(snapshot.dir(@cache_dir), "streams"), total_size: snapshot.dump_file.size)
731
549
  end
732
550
 
733
- def handle_outdated_partial(partial, resume_info, force)
734
- puts
735
- puts "Found existing partial dump with different date:"
736
- puts " Partial dump: #{partial[:dump_date]} (#{partial[:stream_count]} streams, #{format_size(partial[:size])})"
737
- puts " Latest dump: #{resume_info[:latest_date]}"
738
- puts
739
- puts "Options:"
740
- puts " [D] Delete old partial and download latest full dump (recommended)"
741
- puts " [K] Keep old partial, download latest full dump separately"
742
- puts " [U] Use old partial as-is (may have outdated content)"
743
- puts
551
+ # Fetch index ranges that are not stored yet. A range that cannot be
552
+ # fetched is left out; reading it raises StreamUnavailableError.
553
+ # @param ranges [Array<Array(Integer, Integer)>] [offset, end_offset (exclusive)]
554
+ # @return [StreamStore]
555
+ def fetch_streams(ranges)
556
+ store = stream_store
557
+ missing = ranges.uniq.sort.reject { |s, e| store.have?(s, e) }
558
+ return store if missing.empty?
744
559
 
745
- print "Choice [D/k/u]: "
560
+ total = missing.sum { |s, e| e - s }
561
+ puts "Fetching #{missing.size} range(s) (#{format_size(total)}): #{multistream_url}"
746
562
  $stdout.flush
747
- response = $stdin.gets&.strip&.downcase || "d"
748
-
749
- case response
750
- when "k", "keep"
751
- puts "Keeping old partial, downloading latest full dump..."
752
- download_multistream(force: true, max_streams: nil)
753
- when "u", "use"
754
- puts "Using old partial dump (content may be outdated)."
755
- partial[:path]
756
- else
757
- puts "Deleting old partial and downloading latest..."
758
- FileUtils.rm_f(partial[:path])
759
- download_multistream(force: true, max_streams: nil)
760
- end
761
- end
762
-
763
- def download_incremental(partial_path, start_byte, total_size)
764
- url = multistream_url
765
- full_path = cached_multistream_path
766
-
767
- uri = URI(url)
768
- http = Net::HTTP.new(uri.host, uri.port)
769
- http.use_ssl = (uri.scheme == "https")
770
- http.open_timeout = DEFAULT_HTTP_TIMEOUT
771
- http.read_timeout = DEFAULT_HTTP_TIMEOUT
772
- if http.use_ssl?
773
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
774
- end
775
-
776
- request = Net::HTTP::Get.new(uri)
777
- request["Range"] = "bytes=#{start_byte}-"
778
-
779
- # Copy partial to full path first, then append
780
- FileUtils.cp(partial_path, full_path)
781
-
782
- File.open(full_path, "ab") do |file|
783
- http.request(request) do |response|
784
- if response.code == "206"
785
- remaining = total_size - start_byte
786
- downloaded = 0
787
-
788
- response.read_body do |chunk|
789
- file.write(chunk)
790
- downloaded += chunk.size
791
- total_downloaded = start_byte + downloaded
792
- percent = (total_downloaded * 100.0 / total_size).round(1)
793
- print "\r Progress: #{percent}% (#{format_size(total_downloaded)} / #{format_size(total_size)})"
794
- $stdout.flush
795
- end
796
- puts
797
- elsif response.code == "200"
798
- # Server doesn't support Range - need full download
799
- puts "\nServer doesn't support resume. Downloading full file..."
800
- file.close
801
- FileUtils.rm_f(full_path)
802
- return download_multistream(force: true, max_streams: nil)
803
- else
804
- raise "Download failed: #{response.code} #{response.message}"
563
+ failures = Queue.new
564
+ queue = Queue.new
565
+ range_groups(missing).each { |group| queue << group }
566
+ workers = Array.new([PARALLEL_FETCHES, queue.size].min) do
567
+ Thread.new do
568
+ while (group = begin
569
+ queue.pop(true)
570
+ rescue ThreadError
571
+ nil
572
+ end)
573
+ fetch_group(store, group, failures)
805
574
  end
806
575
  end
807
576
  end
808
-
809
- # Validate the combined file
810
- require_relative "bz2_validator"
811
- validation = Bz2Validator.validate_quick(full_path)
812
- unless validation.valid?
813
- puts "Warning: Combined file validation failed. Re-downloading..."
814
- FileUtils.rm_f(full_path)
815
- return download_multistream(force: true, max_streams: nil)
577
+ workers.each(&:join)
578
+ until failures.empty?
579
+ offset, message = failures.pop
580
+ warn " Could not fetch the range at offset #{offset}: #{message}"
816
581
  end
817
-
818
- puts "Successfully resumed download!"
819
-
820
- # Optionally remove the partial file
821
- FileUtils.rm_f(partial_path) if partial_path != full_path
822
-
823
- full_path
824
- end
825
-
826
- def get_remote_file_size(url)
827
- uri = URI(url)
828
- http = Net::HTTP.new(uri.host, uri.port)
829
- http.use_ssl = (uri.scheme == "https")
830
- http.open_timeout = DEFAULT_HTTP_TIMEOUT
831
- http.read_timeout = DEFAULT_HTTP_TIMEOUT
832
- if http.use_ssl?
833
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
582
+ store
583
+ end
584
+
585
+ # The dump's <siteinfo> (namespaces and their case rules), kept with the
586
+ # version once read from the dump's first stream
587
+ # @param header_end [Integer] where the stream holding the siteinfo ends
588
+ # @return [SiteInfo]
589
+ def site_info(header_end)
590
+ path = File.join(snapshot.dir(@cache_dir), "siteinfo.xml")
591
+ FileUtils.rm_f(path) if File.exist?(path) && !SiteInfo.parse(File.read(path)).valid?
592
+ unless File.exist?(path)
593
+ full = verified_full_dump
594
+ data = full ? File.binread(full, header_end) : fetch_streams([[0, header_end]]).read_range(0, header_end)
595
+ xml = Wp2txt.decompress_bz2(data, offset: 0)[%r{<siteinfo\b.*?</siteinfo>}m]
596
+ raise SnapshotError, "#{@lang}wiki #{snapshot.date}: no siteinfo at the start of the dump" unless xml
597
+
598
+ write_atomically(path, xml)
834
599
  end
600
+ site = SiteInfo.parse(File.read(path))
601
+ raise SnapshotError, "#{@lang}wiki #{snapshot.date}: the siteinfo at the start of the dump is incomplete" unless site.valid?
835
602
 
836
- request = Net::HTTP::Head.new(uri)
837
- response = http.request(request)
838
-
839
- response["Content-Length"]&.to_i || 0
840
- end
841
-
842
- public
843
-
844
- # Path for partial multistream cache
845
- def cached_partial_multistream_path(stream_count)
846
- File.join(@cache_dir, "#{@lang}wiki-#{latest_dump_date}-multistream-#{stream_count}streams.xml.bz2")
603
+ site
847
604
  end
848
605
 
849
606
  # Get paths for cached files
@@ -950,10 +707,15 @@ module Wp2txt
950
707
  }
951
708
  end
952
709
 
710
+ # Everything cached for this language: dumps, indexes built from them,
711
+ # fetched ranges, and files set aside after failing a check
712
+ def cache_entries
713
+ self.class.lang_cache_entries(@cache_dir, @lang)
714
+ end
715
+
953
716
  # Clear cache for this language
954
717
  def clear_cache!
955
- lang_dir = File.join(@cache_dir, "#{@lang}wiki")
956
- FileUtils.rm_rf(lang_dir) if File.exist?(lang_dir)
718
+ cache_entries.each { |path| FileUtils.rm_rf(path) }
957
719
  end
958
720
 
959
721
  # Clear all cache
@@ -961,46 +723,414 @@ module Wp2txt
961
723
  FileUtils.rm_rf(cache_dir) if File.exist?(cache_dir)
962
724
  end
963
725
 
964
- # Get status for all cached languages
726
+ def self.lang_cache_entries(cache_dir, lang)
727
+ Dir.glob(File.join(cache_dir, "#{lang}wiki-*"))
728
+ end
729
+
730
+ # Status for every cached language, read from the cache alone
731
+ # @return [Hash{Symbol => Hash}]
965
732
  def self.all_cache_status(cache_dir = DEFAULT_CACHE_DIR)
966
733
  return {} unless File.exist?(cache_dir)
967
734
 
968
- status = {}
969
- Dir.glob(File.join(cache_dir, "*wiki")).each do |lang_dir|
970
- lang = File.basename(lang_dir).sub(/wiki$/, "").to_sym
971
- manager = new(lang, cache_dir: cache_dir)
972
- status[lang] = manager.cache_status
973
- rescue IOError, Errno::ENOENT, Errno::EACCES, JSON::ParserError => e
974
- status[lang] = { error: e.message }
975
- end
976
- status
735
+ langs = Dir.glob(File.join(cache_dir, "*wiki-*")).filter_map { |p| File.basename(p)[/\A([a-z][a-z_-]*)wiki-/, 1] }.uniq
736
+ langs.sort.to_h { |lang| [lang.to_sym, cached_files_status(cache_dir, lang)] }
737
+ end
738
+
739
+ def self.cached_files_status(cache_dir, lang)
740
+ entries = lang_cache_entries(cache_dir, lang)
741
+ names = entries.map { |p| File.basename(p) }
742
+ dates = names.filter_map { |n| n[/\A#{Regexp.escape(lang)}wiki-(\d{8})-/, 1] }.uniq.sort
743
+ date = dates.last
744
+ flat = ->(suffix) { File.join(cache_dir, "#{lang}wiki-#{date}-#{suffix}") }
745
+ size_of = ->(path) { File.file?(path) ? File.size(path) : 0 }
746
+ stream_dirs = entries.select { |p| File.directory?(p) && File.basename(p).match?(/-\d{8}-\h{12}\z/) }
747
+ {
748
+ dump_date: date,
749
+ dates: dates,
750
+ index_size: date ? size_of.(flat.("multistream-index.txt.bz2")) : 0,
751
+ multistream_size: date ? size_of.(flat.("multistream.xml.bz2")) : 0,
752
+ streams_size: stream_dirs.sum { |d| Dir.glob(File.join(d, "streams", "*.bz2")).sum { |f| File.size(f) } },
753
+ legacy_partials: entries.select { |p| p.match?(/-multistream-\d+streams\.xml\.bz2\z/) },
754
+ set_aside: entries.select { |p| p.include?(".bad-") },
755
+ fresh: date ? Wp2txt.file_fresh?(flat.("multistream-index.txt.bz2"), DEFAULT_DUMP_EXPIRY_DAYS) : false
756
+ }
977
757
  end
978
758
 
979
759
  private
980
760
 
981
- def fetch_latest_dump_date
982
- # Try to find the latest available dump
983
- wiki = "#{@lang}wiki"
984
- uri = URI("#{DUMP_BASE_URL}/#{wiki}/")
761
+ # --- choosing the version -------------------------------------------
985
762
 
763
+ def select_snapshot
764
+ if @dump_date
765
+ @snapshot_origin = :requested
766
+ return snapshot_for_date(@dump_date)
767
+ end
768
+ unless @update
769
+ recent = recently_checked_snapshot
770
+ if recent
771
+ @snapshot_origin = :recent
772
+ return recent
773
+ end
774
+ end
775
+ begin
776
+ snap = newest_finished_snapshot
777
+ record_check(snap)
778
+ @snapshot_origin = :checked
779
+ snap
780
+ rescue *NETWORK_ERRORS => e
781
+ raise Wp2txt::NetworkError, "cannot reach #{DUMP_BASE_URL} (#{e.message})" if @update
782
+
783
+ fallback = cached_snapshots.max_by(&:date)
784
+ raise Wp2txt::NetworkError, "cannot reach #{DUMP_BASE_URL} and no dump version is cached for #{@lang} (#{e.message})" unless fallback
785
+
786
+ warn "Cannot reach #{DUMP_BASE_URL} (#{e.message}); using the cached dump of #{fallback.date}"
787
+ @snapshot_origin = :offline
788
+ fallback
789
+ end
790
+ end
791
+
792
+ # The version of a given date: the cached one when it is there (newest
793
+ # check first), otherwise its status fetched now
794
+ def snapshot_for_date(date)
795
+ raise ArgumentError, "dump date must be YYYYMMDD: #{date}" unless date.match?(/\A\d{8}\z/)
796
+
797
+ cached = cached_snapshots(date)
798
+ unless cached.empty?
799
+ record = read_check_record
800
+ return cached.find { |s| s.id == record&.dig("snapshot") } || cached.max_by { |s| File.mtime(status_path(s)) }
801
+ end
802
+
803
+ snap = DumpSnapshot.parse(@lang, date, fetch_status(date))
804
+ save_snapshot(snap)
805
+ end
806
+
807
+ def recently_checked_snapshot
808
+ record = read_check_record
809
+ return nil unless record
810
+
811
+ checked_at = Time.parse(record["checked_at"].to_s)
812
+ return nil if Time.now - checked_at > Wp2txt.days_to_seconds(@dump_expiry_days)
813
+
814
+ cached_snapshots(record["date"].to_s).find { |s| s.id == record["snapshot"] }
815
+ rescue ArgumentError
816
+ nil
817
+ end
818
+
819
+ def newest_finished_snapshot
820
+ reasons = []
821
+ list_dump_dates.first(MAX_DATES_TRIED).each do |date|
822
+ snap = DumpSnapshot.parse(@lang, date, fetch_status(date))
823
+ return save_snapshot(snap)
824
+ rescue SnapshotError => e
825
+ reasons << e.message
826
+ end
827
+ raise SnapshotError, "no finished multistream dump among the newest #{MAX_DATES_TRIED} for #{@lang}wiki: #{reasons.join('; ')}"
828
+ end
829
+
830
+ # Versions cached for this language (optionally of one date), each read
831
+ # back from its saved status
832
+ def cached_snapshots(date = "*")
833
+ Dir.glob(File.join(@cache_dir, "#{@lang}wiki-#{date}-*", "dumpstatus.json")).filter_map do |path|
834
+ snap_date = File.basename(File.dirname(path))[/-(\d{8})-\h{12}\z/, 1]
835
+ next unless snap_date
836
+
837
+ snap = DumpSnapshot.parse(@lang, snap_date, File.read(path))
838
+ snap if File.dirname(path) == snap.dir(@cache_dir)
839
+ rescue SnapshotError
840
+ nil
841
+ end
842
+ end
843
+
844
+ def status_path(snap)
845
+ File.join(snap.dir(@cache_dir), "dumpstatus.json")
846
+ end
847
+
848
+ def save_snapshot(snap)
849
+ path = status_path(snap)
850
+ write_atomically(path, snap.status_json) unless File.exist?(path)
851
+ snap
852
+ end
853
+
854
+ def check_record_path
855
+ File.join(@cache_dir, "#{@lang}wiki-checked.json")
856
+ end
857
+
858
+ def read_check_record
859
+ JSON.parse(File.read(check_record_path))
860
+ rescue Errno::ENOENT, JSON::ParserError
861
+ nil
862
+ end
863
+
864
+ def record_check(snap)
865
+ write_atomically(check_record_path, JSON.generate(
866
+ "checked_at" => Time.now.utc.iso8601, "date" => snap.date, "snapshot" => snap.id
867
+ ))
868
+ end
869
+
870
+ def fetch_status(date)
871
+ uri = URI("#{DUMP_BASE_URL}/#{@lang}wiki/#{date}/dumpstatus.json")
872
+ response = Wp2txt.ssl_safe_get(uri)
873
+ return response.body if response.is_a?(Net::HTTPSuccess)
874
+ raise SnapshotError, "#{@lang}wiki #{date}: no dump status (#{response.code})" if response.is_a?(Net::HTTPNotFound)
875
+
876
+ raise Wp2txt::NetworkError, "#{uri}: #{response.code} #{response.message}"
877
+ end
878
+
879
+ # Dump dates listed on the server, newest first
880
+ def list_dump_dates
881
+ uri = URI("#{DUMP_BASE_URL}/#{@lang}wiki/")
986
882
  response = Wp2txt.ssl_safe_get(uri)
987
- raise("Failed to fetch dump list for #{wiki}") unless response.is_a?(Net::HTTPSuccess)
883
+ raise Wp2txt::NetworkError, "Failed to fetch dump list for #{@lang}wiki (#{response.code})" unless response.is_a?(Net::HTTPSuccess)
988
884
 
989
- # Find dates in format YYYYMMDD
990
- dates = response.body.scan(/href="(\d{8})\/"/).flatten
991
- dates.sort.last || raise("No dumps found for #{wiki}")
885
+ dates = response.body.scan(%r{href="(\d{8})/"}).flatten.uniq.sort.reverse
886
+ raise SnapshotError, "No dumps found for #{@lang}wiki" if dates.empty?
887
+
888
+ dates
992
889
  end
993
890
 
994
891
  def index_url
995
- wiki = "#{@lang}wiki"
996
- date = latest_dump_date
997
- "#{DUMP_BASE_URL}/#{wiki}/#{date}/#{wiki}-#{date}-pages-articles-multistream-index.txt.bz2"
892
+ file_url(snapshot.index_file)
998
893
  end
999
894
 
1000
895
  def multistream_url
1001
- wiki = "#{@lang}wiki"
1002
- date = latest_dump_date
1003
- "#{DUMP_BASE_URL}/#{wiki}/#{date}/#{wiki}-#{date}-pages-articles-multistream.xml.bz2"
896
+ file_url(snapshot.dump_file)
897
+ end
898
+
899
+ def file_url(info)
900
+ "#{DUMP_BASE_URL}/#{@lang}wiki/#{snapshot.date}/#{info.name}"
901
+ end
902
+
903
+ # --- checking cached files ------------------------------------------
904
+
905
+ # The version's own name for one of its files: a hard link, in the
906
+ # version's directory, to the very file that was checked against the
907
+ # version. Readers use it, so whatever later happens to the cache's shared
908
+ # name for the file (another version of the same date put there), they
909
+ # keep reading what was checked. It exists only once the file has passed.
910
+ def pinned_path(info)
911
+ File.join(snapshot.dir(@cache_dir), info.name)
912
+ end
913
+
914
+ # Use a cached file once it matches the version, else fetch it. A cached
915
+ # file that does not match is set aside, never overwritten, so a process
916
+ # still reading it is not affected.
917
+ # @return [String] the pinned path of the file
918
+ def ensure_file(info, path, url, force:, label:)
919
+ pinned = pinned_path(info)
920
+ if !force && usable_pin?(info)
921
+ puts "Using cached #{label}: #{File.basename(path)}"
922
+ $stdout.flush
923
+ return pinned
924
+ end
925
+
926
+ if File.exist?(path) && !force
927
+ if File.exist?(download_meta_path(path))
928
+ puts "Resuming the #{label} download: #{File.basename(path)}"
929
+ elsif (checked = check_and_pin(info, path))
930
+ puts "Using cached #{label}: #{File.basename(path)}"
931
+ $stdout.flush
932
+ return checked
933
+ else
934
+ set_aside(path)
935
+ end
936
+ end
937
+
938
+ puts "Downloading #{label}: #{url}"
939
+ $stdout.flush
940
+ download_file(url, path, expected_size: info.size, sha1: info.sha1, pin_to: pinned)
941
+ pinned
942
+ end
943
+
944
+ # Whether the version's pinned file is there and still of the version's
945
+ # size; one that is not is set aside, to be checked or fetched again
946
+ def usable_pin?(info)
947
+ pinned = pinned_path(info)
948
+ return false unless File.exist?(pinned) || File.symlink?(pinned)
949
+ return true if File.file?(pinned) && !File.symlink?(pinned) && File.size(pinned) == info.size
950
+
951
+ set_aside(pinned)
952
+ false
953
+ end
954
+
955
+ # Whether path names the very file pinned for the version
956
+ def pinned_file?(info, path)
957
+ pinned = pinned_path(info)
958
+ return false unless File.exist?(path) && File.exist?(pinned)
959
+
960
+ a = File.stat(path)
961
+ b = File.stat(pinned)
962
+ a.ino == b.ino && a.dev == b.dev
963
+ end
964
+
965
+ # Make target another name of source, replacing whatever target named
966
+ def link_atomically(source, target)
967
+ tmp = "#{target}.#{Process.pid}.#{SecureRandom.hex(4)}.link"
968
+ File.link(source, tmp)
969
+ File.rename(tmp, target)
970
+ rescue Errno::EPERM, Errno::EXDEV, Errno::ENOTSUP, Errno::EMLINK => e
971
+ raise SnapshotError, "cannot keep #{File.basename(source)} for dump version #{snapshot.date}: the cache directory " \
972
+ "must allow hard links (#{e.message})"
973
+ ensure
974
+ FileUtils.rm_f(tmp) if tmp && File.exist?(tmp)
975
+ end
976
+
977
+ # Check the file at path against the version through one open
978
+ # descriptor, and pin what was checked
979
+ # @return [String, nil] the pinned path, or nil when the file does not match
980
+ def check_and_pin(info, path)
981
+ File.open(path, "rb") do |io|
982
+ return nil unless io.stat.size == info.size
983
+
984
+ puts "Checking #{File.basename(path)} (#{format_size(info.size)})..." if info.size >= PROGRESS_MIN_BYTES
985
+ digest = Digest::SHA1.new
986
+ while (chunk = io.read(4 * 1024 * 1024))
987
+ digest << chunk
988
+ end
989
+ return nil unless digest.hexdigest == info.sha1
990
+
991
+ pin(info, path, io.stat)
992
+ end
993
+ end
994
+
995
+ # Link the version's name to the file at path, provided path still names
996
+ # the file that was checked (stat taken from the checked descriptor)
997
+ def pin(info, path, checked_stat)
998
+ pinned = pinned_path(info)
999
+ FileUtils.mkdir_p(File.dirname(pinned))
1000
+ tmp = "#{pinned}.#{Process.pid}.#{SecureRandom.hex(4)}.link"
1001
+ begin
1002
+ File.link(path, tmp)
1003
+ rescue Errno::EPERM, Errno::EXDEV, Errno::ENOTSUP, Errno::EMLINK => e
1004
+ raise SnapshotError, "cannot keep #{File.basename(path)} for dump version #{snapshot.date}: the cache directory " \
1005
+ "must allow hard links (#{e.message})"
1006
+ end
1007
+ linked = File.stat(tmp)
1008
+ unless linked.ino == checked_stat.ino && linked.dev == checked_stat.dev
1009
+ raise SnapshotError, "#{File.basename(path)} changed while it was being checked"
1010
+ end
1011
+
1012
+ File.rename(tmp, pinned)
1013
+ pinned
1014
+ ensure
1015
+ FileUtils.rm_f(tmp) if tmp && File.exist?(tmp)
1016
+ end
1017
+
1018
+ def set_aside(path)
1019
+ target = "#{path}.bad-#{Time.now.utc.strftime('%Y%m%dT%H%M%SZ')}"
1020
+ File.rename(path, target)
1021
+ warn "#{File.basename(path)} does not match dump version #{snapshot.date}; set aside as #{File.basename(target)}"
1022
+ end
1023
+
1024
+ # --- fetching ---------------------------------------------------------
1025
+
1026
+ # Contiguous ranges, merged into groups no larger than MAX_GROUP_BYTES
1027
+ def range_groups(ranges)
1028
+ ranges.each_with_object([]) do |(s, e), groups|
1029
+ last = groups.last
1030
+ if last && last.last[1] == s && e - last.first[0] <= MAX_GROUP_BYTES
1031
+ last << [s, e]
1032
+ else
1033
+ groups << [[s, e]]
1034
+ end
1035
+ end
1036
+ end
1037
+
1038
+ def fetch_group(store, group, failures)
1039
+ start = group.first[0]
1040
+ finish = group.last[1]
1041
+ data = with_attempts { fetch_bytes(multistream_url, start, finish - 1) }
1042
+ group.each do |s, e|
1043
+ store.store(s, e, data.byteslice(s - start, e - s))
1044
+ rescue StreamError => e
1045
+ failures << [s, e.message]
1046
+ end
1047
+ rescue Wp2txt::NetworkError, *NETWORK_ERRORS => e
1048
+ group.each { |s, _| failures << [s, e.message] }
1049
+ end
1050
+
1051
+ def with_attempts
1052
+ attempts = 0
1053
+ begin
1054
+ attempts += 1
1055
+ yield
1056
+ rescue TransientFetchError, *(NETWORK_ERRORS - [Wp2txt::NetworkError]) => e
1057
+ raise TransientFetchError, e.message if attempts >= FETCH_ATTEMPTS
1058
+
1059
+ delay = 2**attempts
1060
+ warn " Network error (attempt #{attempts}/#{FETCH_ATTEMPTS}): #{e.message}. Retrying in #{delay}s..."
1061
+ sleep delay
1062
+ retry
1063
+ end
1064
+ end
1065
+
1066
+ def http_for(uri)
1067
+ http = Net::HTTP.new(uri.host, uri.port)
1068
+ http.use_ssl = (uri.scheme == "https")
1069
+ http.open_timeout = DEFAULT_HTTP_TIMEOUT
1070
+ http.read_timeout = DEFAULT_HTTP_TIMEOUT
1071
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER if http.use_ssl?
1072
+ http
1073
+ end
1074
+
1075
+ # Bytes first..last (inclusive) of a file of this version, checked against
1076
+ # the response's Content-Range and the size the version records
1077
+ def fetch_bytes(url, first, last)
1078
+ uri = URI(url)
1079
+ request = Net::HTTP::Get.new(uri)
1080
+ request["Range"] = "bytes=#{first}-#{last}"
1081
+ expected = last - first + 1
1082
+ data = +"".b
1083
+ http_for(uri).request(request) do |response|
1084
+ check_partial_response(response, first, last, snapshot.dump_file.size)
1085
+ check_validators(response)
1086
+ response.read_body do |chunk|
1087
+ data << chunk
1088
+ raise Wp2txt::NetworkError, "#{url}: more data than the #{expected} bytes asked for" if data.bytesize > expected
1089
+ end
1090
+ end
1091
+ raise TransientFetchError, "#{url}: #{data.bytesize} of #{expected} bytes received" if data.bytesize < expected
1092
+
1093
+ data
1094
+ end
1095
+
1096
+ def check_partial_response(response, first, last, total)
1097
+ code = response.code.to_i
1098
+ raise TransientFetchError, "#{response.code} #{response.message}" if code >= 500 || code == 429
1099
+ unless code == 206
1100
+ raise Wp2txt::NetworkError, "the server answered a range request with #{response.code}, not 206"
1101
+ end
1102
+
1103
+ range = response["Content-Range"].to_s.match(%r{\Abytes (\d+)-(\d+)/(\d+|\*)\z})
1104
+ unless range && range[1].to_i == first && range[2].to_i == last && range[3] == total.to_s
1105
+ raise Wp2txt::NetworkError, "unexpected Content-Range #{response['Content-Range'].inspect} " \
1106
+ "for bytes #{first}-#{last} of #{total}"
1107
+ end
1108
+ end
1109
+
1110
+ # The ETag and Last-Modified of the dump file are recorded with the version
1111
+ # at its first range and must match on every later one: ranges of a file
1112
+ # replaced on the server would decompress fine and still not belong together
1113
+ def check_validators(response)
1114
+ seen = { "etag" => response["ETag"], "last_modified" => response["Last-Modified"] }.compact
1115
+ return if seen.empty?
1116
+
1117
+ FileUtils.mkdir_p(snapshot.dir(@cache_dir))
1118
+ File.open(File.join(snapshot.dir(@cache_dir), "validators.lock"), File::RDWR | File::CREAT, 0o644) do |lock|
1119
+ # One lock for threads and processes alike: each opens its own descriptor
1120
+ lock.flock(File::LOCK_EX)
1121
+ path = File.join(snapshot.dir(@cache_dir), "validators.json")
1122
+ recorded = begin
1123
+ JSON.parse(File.read(path))
1124
+ rescue Errno::ENOENT, JSON::ParserError
1125
+ {}
1126
+ end
1127
+ changed = seen.select { |key, value| recorded.key?(key) && recorded[key] != value }
1128
+ unless changed.empty?
1129
+ raise Wp2txt::NetworkError, "the dump file on the server is not the one fetched before " \
1130
+ "(#{changed.keys.join(', ')} changed); check for a newer version with --update-cache"
1131
+ end
1132
+ write_atomically(path, JSON.pretty_generate(recorded.merge(seen))) if (seen.keys - recorded.keys).any?
1133
+ end
1004
1134
  end
1005
1135
 
1006
1136
  # Download metadata file path for tracking resumable downloads
@@ -1008,20 +1138,15 @@ module Wp2txt
1008
1138
  "#{path}.wp2txt_download"
1009
1139
  end
1010
1140
 
1141
+ def part_path(path)
1142
+ "#{path}.part"
1143
+ end
1144
+
1011
1145
  # Get remote file info via HEAD request
1012
1146
  # @return [Hash] { size:, etag:, last_modified: }
1013
1147
  def get_remote_file_info(url)
1014
1148
  uri = URI(url)
1015
- http = Net::HTTP.new(uri.host, uri.port)
1016
- http.use_ssl = (uri.scheme == "https")
1017
- http.open_timeout = DEFAULT_HTTP_TIMEOUT
1018
- http.read_timeout = DEFAULT_HTTP_TIMEOUT
1019
- if http.use_ssl?
1020
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
1021
- end
1022
-
1023
- request = Net::HTTP::Head.new(uri)
1024
- response = http.request(request)
1149
+ response = http_for(uri).request(Net::HTTP::Head.new(uri))
1025
1150
 
1026
1151
  {
1027
1152
  size: response["Content-Length"]&.to_i || 0,
@@ -1061,30 +1186,26 @@ module Wp2txt
1061
1186
 
1062
1187
  # Check if resume is safe (server file hasn't changed)
1063
1188
  def can_resume_download?(path, url)
1064
- return false unless File.exist?(path)
1189
+ return false unless File.exist?(part_path(path))
1065
1190
 
1066
1191
  meta = load_download_meta(path)
1067
- return false unless meta
1192
+ return false unless meta && meta[:url] == url
1068
1193
 
1069
1194
  # Check if metadata is not too old (max 7 days)
1070
1195
  if meta[:started_at]
1071
1196
  started = Time.parse(meta[:started_at]) rescue nil
1072
- if started && (Time.now - started) > days_to_seconds(RESUME_METADATA_MAX_AGE_DAYS)
1197
+ if started && (Time.now - started) > Wp2txt.days_to_seconds(RESUME_METADATA_MAX_AGE_DAYS)
1073
1198
  puts " Partial download is too old (>#{RESUME_METADATA_MAX_AGE_DAYS} days). Starting fresh."
1074
1199
  return false
1075
1200
  end
1076
1201
  end
1077
1202
 
1078
- # Get current remote file info
1079
1203
  remote_info = get_remote_file_info(url)
1080
-
1081
- # Check if ETag matches (most reliable)
1082
1204
  if meta[:etag] && remote_info[:etag]
1083
1205
  if meta[:etag] != remote_info[:etag]
1084
1206
  puts " Server file has changed (ETag mismatch). Starting fresh."
1085
1207
  return false
1086
1208
  end
1087
- # Fallback: check Last-Modified
1088
1209
  elsif meta[:last_modified] && remote_info[:last_modified]
1089
1210
  if meta[:last_modified] != remote_info[:last_modified]
1090
1211
  puts " Server file has changed (Last-Modified mismatch). Starting fresh."
@@ -1092,7 +1213,6 @@ module Wp2txt
1092
1213
  end
1093
1214
  end
1094
1215
 
1095
- # Check if server supports Range requests
1096
1216
  unless remote_info[:accept_ranges]
1097
1217
  puts " Server doesn't support resume. Starting fresh."
1098
1218
  return false
@@ -1101,324 +1221,277 @@ module Wp2txt
1101
1221
  true
1102
1222
  end
1103
1223
 
1104
- def download_file(url, path)
1105
- uri = URI(url)
1224
+ # Download a whole file into <path>.part, resuming an interrupted
1225
+ # download of the same file, and put it in place only once it is complete
1226
+ # (and, when known, of the expected size and SHA-1). One process at a
1227
+ # time downloads a given file; the lock goes with the process.
1228
+ # @param pin_to [String, nil] also link the finished file under this name
1229
+ def download_file(url, path, expected_size: nil, sha1: nil, pin_to: nil)
1106
1230
  FileUtils.mkdir_p(File.dirname(path))
1231
+ File.open("#{path}.lock", File::RDWR | File::CREAT, 0o644) do |lock|
1232
+ unless lock.flock(File::LOCK_EX | File::LOCK_NB)
1233
+ raise Wp2txt::NetworkError, "another process is downloading #{File.basename(path)}"
1234
+ end
1107
1235
 
1108
- # Check for resumable download
1109
- partial_size = File.exist?(path) ? File.size(path) : 0
1110
- resume_mode = false
1111
-
1112
- if partial_size > 0 && can_resume_download?(path, url)
1113
- meta = load_download_meta(path)
1114
- total_size = meta[:size]
1115
- if partial_size < total_size
1116
- resume_mode = true
1117
- puts " Resuming download from #{format_size(partial_size)} / #{format_size(total_size)} (#{(partial_size * 100.0 / total_size).round(1)}%)"
1118
- elsif partial_size == total_size
1119
- puts " Download already complete."
1236
+ adopt_legacy_partial(path)
1237
+ with_attempts { download_to_part(url, path, expected_size) }
1238
+ part = part_path(path)
1239
+ actual = File.size(part)
1240
+ raise Wp2txt::NetworkError, "#{File.basename(path)}: #{actual} bytes, expected #{expected_size}" \
1241
+ if expected_size && actual != expected_size
1242
+ if sha1 && Digest::SHA1.file(part).hexdigest != sha1
1243
+ FileUtils.rm_f(part)
1120
1244
  cleanup_download_meta(path)
1121
- return path
1122
- else
1123
- # Partial is larger than expected - corrupted, start fresh
1124
- puts " Partial file corrupted (size mismatch). Starting fresh."
1125
- FileUtils.rm_f(path)
1126
- partial_size = 0
1245
+ raise Wp2txt::NetworkError, "#{File.basename(path)} does not match the SHA-1 the dump status records"
1127
1246
  end
1128
- elsif partial_size > 0
1129
- # Can't resume - remove partial and start fresh
1130
- FileUtils.rm_f(path)
1247
+
1248
+ if pin_to
1249
+ FileUtils.mkdir_p(File.dirname(pin_to))
1250
+ link_atomically(part, pin_to)
1251
+ end
1252
+ File.rename(part, path)
1131
1253
  cleanup_download_meta(path)
1132
- partial_size = 0
1133
1254
  end
1255
+ path
1256
+ end
1134
1257
 
1135
- http = Net::HTTP.new(uri.host, uri.port)
1136
- http.use_ssl = (uri.scheme == "https")
1137
- http.open_timeout = DEFAULT_HTTP_TIMEOUT
1138
- http.read_timeout = DEFAULT_HTTP_TIMEOUT
1139
- if http.use_ssl?
1140
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
1141
- end
1258
+ # Downloads interrupted before this version wrote straight to the final
1259
+ # path with a .wp2txt_download record; continue them as a part file
1260
+ def adopt_legacy_partial(path)
1261
+ return unless File.exist?(path) && File.exist?(download_meta_path(path)) && !File.exist?(part_path(path))
1142
1262
 
1143
- request = Net::HTTP::Get.new(uri)
1263
+ File.rename(path, part_path(path))
1264
+ end
1144
1265
 
1145
- if resume_mode
1146
- request["Range"] = "bytes=#{partial_size}-"
1147
- file_mode = "ab" # Append mode
1148
- else
1149
- file_mode = "wb" # Write mode (overwrite)
1150
- # Save metadata for potential future resume
1266
+ def download_to_part(url, path, expected_size)
1267
+ uri = URI(url)
1268
+ part = part_path(path)
1269
+ offset = File.exist?(part) ? File.size(part) : 0
1270
+ resume = offset.positive? && can_resume_download?(path, url)
1271
+ # A part file longer than the whole file cannot be continued
1272
+ resume = false if resume && expected_size && offset > expected_size
1273
+ unless resume
1274
+ FileUtils.rm_f(part)
1275
+ offset = 0
1151
1276
  remote_info = get_remote_file_info(url)
1152
- save_download_meta(path, url, remote_info) if remote_info[:size] > 0
1277
+ save_download_meta(path, url, remote_info) if remote_info[:size].positive?
1153
1278
  end
1279
+ total = expected_size || load_download_meta(path)&.dig(:size)
1280
+ return if resume && total && offset == total
1154
1281
 
1155
- File.open(path, file_mode) do |file|
1156
- http.request(request) do |response|
1157
- if response.code == "200" || response.code == "206"
1158
- total = if resume_mode
1159
- load_download_meta(path)[:size]
1160
- else
1161
- response["Content-Length"]&.to_i
1162
- end
1163
- downloaded = partial_size
1164
-
1165
- response.read_body do |chunk|
1166
- file.write(chunk)
1167
- downloaded += chunk.size
1168
- if total && total > 0
1169
- percent = (downloaded * 100.0 / total).round(1)
1170
- print "\r Progress: #{percent}% (#{format_size(downloaded)} / #{format_size(total)})"
1171
- $stdout.flush
1172
- end
1173
- end
1174
- puts
1175
- elsif response.code == "416"
1176
- # Range Not Satisfiable - file might be complete or corrupted
1177
- puts "\n Range error. Verifying file..."
1178
- remote_info = get_remote_file_info(url)
1179
- if File.size(path) == remote_info[:size]
1180
- puts " File is already complete."
1181
- else
1182
- puts " File corrupted. Re-downloading..."
1183
- file.close
1184
- FileUtils.rm_f(path)
1185
- cleanup_download_meta(path)
1186
- return download_file(url, path)
1187
- end
1282
+ request = Net::HTTP::Get.new(uri)
1283
+ request["Range"] = "bytes=#{offset}-" if resume
1284
+ puts " Resuming from #{format_size(offset)}" if resume
1285
+ File.open(part, resume ? "ab" : "wb") do |file|
1286
+ http_for(uri).request(request) do |response|
1287
+ if resume
1288
+ check_partial_response(response, offset, total - 1, total) if total
1188
1289
  else
1189
- raise "Download failed: #{response.code} #{response.message}"
1290
+ code = response.code.to_i
1291
+ raise TransientFetchError, "#{response.code} #{response.message}" if code >= 500 || code == 429
1292
+ raise Wp2txt::NetworkError, "Download failed: #{response.code} #{response.message}" unless code == 200
1190
1293
  end
1294
+ total ||= response["Content-Length"]&.to_i
1295
+ downloaded = offset
1296
+ response.read_body do |chunk|
1297
+ file.write(chunk)
1298
+ downloaded += chunk.bytesize
1299
+ raise Wp2txt::NetworkError, "#{url}: more data than the #{total} bytes expected" if total && downloaded > total
1300
+
1301
+ show_progress(downloaded, total)
1302
+ end
1303
+ puts if total && total >= PROGRESS_MIN_BYTES
1191
1304
  end
1192
1305
  end
1306
+ written = File.size(part)
1307
+ raise TransientFetchError, "#{url}: #{written} of #{total} bytes received" if total && written < total
1308
+ end
1193
1309
 
1194
- # Clean up metadata on successful completion
1195
- cleanup_download_meta(path)
1310
+ def show_progress(done, total)
1311
+ return unless total && total >= PROGRESS_MIN_BYTES
1196
1312
 
1197
- path
1313
+ print "\r Progress: #{(done * 100.0 / total).round(1)}% (#{format_size(done)} / #{format_size(total)})"
1314
+ $stdout.flush
1198
1315
  end
1199
1316
 
1200
- # Download a range of bytes from a URL using HTTP Range header
1201
- def download_file_range(url, path, start_byte, end_byte)
1202
- uri = URI(url)
1203
-
1317
+ def write_atomically(path, content)
1204
1318
  FileUtils.mkdir_p(File.dirname(path))
1205
-
1206
- http = Net::HTTP.new(uri.host, uri.port)
1207
- http.use_ssl = (uri.scheme == "https")
1208
- http.open_timeout = DEFAULT_HTTP_TIMEOUT
1209
- http.read_timeout = DEFAULT_HTTP_TIMEOUT
1210
- if http.use_ssl?
1211
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
1212
- end
1213
-
1214
- request = Net::HTTP::Get.new(uri)
1215
- request["Range"] = "bytes=#{start_byte}-#{end_byte}"
1216
-
1217
- File.open(path, "wb") do |file|
1218
- http.request(request) do |response|
1219
- if response.code == "206" || response.code == "200"
1220
- total = end_byte - start_byte + 1
1221
- downloaded = 0
1222
-
1223
- response.read_body do |chunk|
1224
- file.write(chunk)
1225
- downloaded += chunk.size
1226
- percent = (downloaded * 100.0 / total).round(1)
1227
- print "\r Progress: #{percent}% (#{format_size(downloaded)} / #{format_size(total)})"
1228
- $stdout.flush
1229
- end
1230
- puts
1231
- else
1232
- raise "Download failed: #{response.code} #{response.message}"
1233
- end
1234
- end
1235
- end
1236
-
1237
- path
1319
+ tmp = "#{path}.#{Process.pid}.#{SecureRandom.hex(4)}.part"
1320
+ File.write(tmp, content)
1321
+ File.rename(tmp, path)
1322
+ ensure
1323
+ FileUtils.rm_f(tmp) if tmp && File.exist?(tmp)
1238
1324
  end
1239
1325
  end
1240
1326
 
1241
- # Fetches category members from Wikipedia API
1242
- # Uses SQLite-based CategoryCache for efficient repeated access
1327
+ # Lists the articles of a Wikipedia category (and of its subcategories down
1328
+ # to max_depth) through the MediaWiki API, as it is now, not as of a dump.
1329
+ #
1330
+ # Subcategories are followed by page ID, breadth first, each from the
1331
+ # shallowest depth it is reached at, so the result does not depend on the
1332
+ # order the API lists them in. A listing that cannot be read in full raises
1333
+ # IncompleteListing, which carries what was read; it is never passed off as
1334
+ # the whole category.
1243
1335
  class CategoryFetcher
1244
1336
  API_ENDPOINT = "https://%s.wikipedia.org/w/api.php"
1245
1337
  MAX_LIMIT = 500
1246
1338
  RATE_LIMIT_DELAY = 0.1
1247
1339
 
1248
- attr_reader :lang, :category, :max_depth, :cache_expiry_days
1340
+ # A category listing and how far it got
1341
+ # articles: title => page ID; categories: [{name:, id:, depth:, article_count:}]
1342
+ Listing = Struct.new(:articles, :categories, :complete, :error, :started_at, :finished_at, keyword_init: true)
1343
+
1344
+ # Raised when the API cannot list a category in full
1345
+ class ListingError < Wp2txt::NetworkError; end
1249
1346
 
1250
- def initialize(lang, category, max_depth: 0, cache_expiry_days: nil, cache_dir: nil)
1347
+ # Raised when a listing stops part way; #listing holds what was read
1348
+ class IncompleteListing < Wp2txt::NetworkError
1349
+ attr_reader :listing
1350
+
1351
+ def initialize(message, listing)
1352
+ super(message)
1353
+ @listing = listing
1354
+ end
1355
+ end
1356
+
1357
+ # Raised when the category does not exist on the wiki
1358
+ class CategoryNotFound < Wp2txt::Error; end
1359
+
1360
+ attr_reader :lang, :category, :max_depth
1361
+
1362
+ def initialize(lang, category, max_depth: 0)
1251
1363
  @lang = lang.to_s
1364
+ @requested = category.to_s.strip
1252
1365
  @category = normalize_category_name(category)
1253
1366
  @max_depth = max_depth
1254
- @cache_expiry_days = cache_expiry_days || Wp2txt::DEFAULT_CATEGORY_CACHE_EXPIRY_DAYS
1255
- @cache_dir = cache_dir
1256
- @cache = nil
1257
- @visited_categories = Set.new
1258
1367
  end
1259
1368
 
1260
- # Enable caching of category member lists
1261
- # @param cache_dir [String] Directory for cache files
1262
- def enable_cache(cache_dir)
1263
- @cache_dir = cache_dir
1264
- @cache = CategoryCache.new(@lang, cache_dir: cache_dir, expiry_days: @cache_expiry_days)
1265
- end
1266
-
1267
- # Get the category cache instance
1268
- # Creates one if caching is enabled but cache not yet initialized
1269
- def cache
1270
- return @cache if @cache
1271
- return nil unless @cache_dir
1369
+ # The listing, read once and kept for later calls
1370
+ # @return [Listing]
1371
+ # @raise [IncompleteListing, CategoryNotFound]
1372
+ def fetch_listing
1373
+ @listing ||= read_listing
1374
+ raise IncompleteListing.new("the listing of #{@category} could not be read in full: #{@listing.error}", @listing) \
1375
+ unless @listing.complete
1272
1376
 
1273
- @cache = CategoryCache.new(@lang, cache_dir: @cache_dir, expiry_days: @cache_expiry_days)
1377
+ @listing
1274
1378
  end
1275
1379
 
1276
1380
  # Preview mode - returns statistics without full article list
1277
1381
  def fetch_preview
1278
- @visited_categories = Set.new
1279
- subcategories = []
1280
- total_articles = 0
1281
-
1282
- fetch_category_stats(@category, 0, subcategories)
1283
-
1284
- total_articles = subcategories.sum { |s| s[:article_count] }
1382
+ preview_of(fetch_listing)
1383
+ end
1285
1384
 
1385
+ def preview_of(listing)
1286
1386
  {
1287
1387
  category: @category,
1288
1388
  depth: @max_depth,
1289
- subcategories: subcategories,
1290
- total_subcategories: subcategories.size - 1,
1291
- total_articles: total_articles
1389
+ subcategories: listing.categories.map { |c| { name: c[:name], article_count: c[:article_count] } },
1390
+ total_subcategories: [listing.categories.size - 1, 0].max,
1391
+ total_articles: listing.articles.size
1292
1392
  }
1293
1393
  end
1294
1394
 
1295
1395
  # Fetch all article titles in the category (and subcategories if depth > 0)
1296
1396
  def fetch_articles
1297
- @visited_categories = Set.new
1298
- @articles = []
1299
- fetch_category_members(@category, 0)
1300
- @articles.uniq
1397
+ fetch_listing.articles.keys
1301
1398
  end
1302
1399
 
1303
1400
  private
1304
1401
 
1305
1402
  def normalize_category_name(name)
1306
- name.to_s.sub(/^[Cc]ategory:/, "").strip
1307
- end
1308
-
1309
- def fetch_category_stats(category_name, current_depth, results)
1310
- return if @visited_categories.include?(category_name)
1311
- @visited_categories << category_name
1312
-
1313
- cached = load_from_cache(category_name)
1314
- if cached
1315
- results << { name: category_name, article_count: (cached[:pages] || []).size }
1316
- if current_depth < @max_depth
1317
- (cached[:subcats] || []).each do |subcat|
1318
- fetch_category_stats(subcat, current_depth + 1, results)
1403
+ name.to_s.strip.sub(/\A[Cc]ategory:/, "").strip
1404
+ end
1405
+
1406
+ def read_listing
1407
+ started_at = Time.now.utc
1408
+ articles = {}
1409
+ categories = []
1410
+ current = nil
1411
+ root = resolve_root
1412
+ raise CategoryNotFound, "category not found on #{@lang}.wikipedia.org: #{@requested}" unless root
1413
+
1414
+ visited = Set[root[:id]]
1415
+ level = [root]
1416
+ depth = 0
1417
+ until level.empty?
1418
+ next_level = []
1419
+ level.each do |cat|
1420
+ current = cat
1421
+ count = 0
1422
+ list_members(cat[:id]) do |member|
1423
+ case member["ns"]
1424
+ when 0
1425
+ articles[member["title"]] ||= member["pageid"]
1426
+ count += 1
1427
+ when 14
1428
+ next_level << { id: member["pageid"], title: member["title"] } if depth < @max_depth && visited.add?(member["pageid"])
1429
+ end
1319
1430
  end
1431
+ categories << { name: display_name(cat[:title]), id: cat[:id], depth: depth, article_count: count }
1320
1432
  end
1321
- return
1433
+ level = next_level
1434
+ depth += 1
1322
1435
  end
1323
-
1324
- pages = []
1325
- subcats = []
1326
- continue_token = nil
1327
-
1328
- loop do
1329
- response = api_request(category_name, continue_token)
1330
- break unless response
1331
-
1332
- categorymembers = response.dig("query", "categorymembers") || []
1333
- categorymembers.each do |member|
1334
- case member["ns"]
1335
- when 0
1336
- pages << member["title"]
1337
- when 14
1338
- subcats << member["title"].sub(/^Category:/, "")
1339
- end
1340
- end
1341
-
1342
- continue_token = response.dig("continue", "cmcontinue")
1343
- break unless continue_token
1344
-
1345
- sleep(RATE_LIMIT_DELAY)
1346
- end
1347
-
1348
- save_to_cache(category_name, { pages: pages, subcats: subcats })
1349
-
1350
- results << { name: category_name, article_count: pages.size }
1351
-
1352
- if current_depth < @max_depth
1353
- subcats.each do |subcat|
1354
- fetch_category_stats(subcat, current_depth + 1, results)
1355
- end
1436
+ Listing.new(articles: articles, categories: categories, complete: true,
1437
+ started_at: started_at, finished_at: Time.now.utc)
1438
+ rescue ListingError, *DumpManager::NETWORK_ERRORS => e
1439
+ raise if e.is_a?(IncompleteListing)
1440
+
1441
+ where = current ? display_name(current[:title]) : @category
1442
+ @listing = Listing.new(articles: articles, categories: categories, complete: false,
1443
+ error: "#{where}: #{e.message}", started_at: started_at, finished_at: Time.now.utc)
1444
+ raise IncompleteListing.new("the listing of #{where} could not be read in full: #{e.message}", @listing)
1445
+ end
1446
+
1447
+ # The category as the wiki names it, with its page ID. A name given with
1448
+ # a namespace prefix (in any language) is tried as written first.
1449
+ def resolve_root
1450
+ candidates = []
1451
+ candidates << @requested if @requested.include?(":")
1452
+ candidates << "Category:#{@category}"
1453
+ candidates.uniq.each do |title|
1454
+ query = api_get(action: "query", titles: title)["query"]
1455
+ pages = query.is_a?(Hash) ? query["pages"] : nil
1456
+ raise ListingError, "unexpected response for #{title}" unless pages.is_a?(Array)
1457
+
1458
+ page = pages.first
1459
+ return { id: page["pageid"], title: page["title"] } if page && page["ns"] == 14 && page["pageid"].is_a?(Integer)
1356
1460
  end
1461
+ nil
1357
1462
  end
1358
1463
 
1359
- def fetch_category_members(category_name, current_depth)
1360
- return if @visited_categories.include?(category_name)
1361
- @visited_categories << category_name
1362
-
1363
- cached = load_from_cache(category_name)
1364
- if cached
1365
- @articles.concat(cached[:pages] || [])
1366
- if current_depth < @max_depth
1367
- (cached[:subcats] || []).each do |subcat|
1368
- fetch_category_members(subcat, current_depth + 1)
1369
- end
1370
- end
1371
- return
1372
- end
1373
-
1374
- pages = []
1375
- subcats = []
1376
- continue_token = nil
1377
-
1464
+ # Yield every member of a category, page by page through all continuation
1465
+ def list_members(page_id)
1466
+ continuation = {}
1467
+ seen = Set.new
1378
1468
  loop do
1379
- response = api_request(category_name, continue_token)
1380
- break unless response
1381
-
1382
- categorymembers = response.dig("query", "categorymembers") || []
1383
- categorymembers.each do |member|
1384
- case member["ns"]
1385
- when 0
1386
- pages << member["title"]
1387
- when 14
1388
- subcats << member["title"].sub(/^Category:/, "")
1389
- end
1469
+ response = api_get(action: "query", list: "categorymembers", cmpageid: page_id, cmtype: "page|subcat",
1470
+ cmprop: "ids|title", cmlimit: MAX_LIMIT, **continuation)
1471
+ query = response["query"]
1472
+ list = query.is_a?(Hash) ? query["categorymembers"] : nil
1473
+ raise ListingError, "unexpected response for category #{page_id}" unless list.is_a?(Array)
1474
+ unless list.all? { |m| m.is_a?(Hash) && m["pageid"].is_a?(Integer) && m["ns"].is_a?(Integer) && m["title"].is_a?(String) }
1475
+ raise ListingError, "malformed members of category #{page_id}"
1390
1476
  end
1391
1477
 
1392
- continue_token = response.dig("continue", "cmcontinue")
1393
- break unless continue_token
1478
+ list.each { |member| yield member }
1479
+ following = response["continue"]
1480
+ break if following.nil?
1481
+ unless following.is_a?(Hash) && following.any? && following.all? { |k, v| k.is_a?(String) && v.is_a?(String) }
1482
+ raise ListingError, "malformed continuation for category #{page_id}"
1483
+ end
1484
+ raise ListingError, "the listing of category #{page_id} does not advance" unless seen.add?(following.to_a.sort)
1394
1485
 
1486
+ continuation = following.transform_keys(&:to_sym)
1395
1487
  sleep(RATE_LIMIT_DELAY)
1396
1488
  end
1397
-
1398
- save_to_cache(category_name, { pages: pages, subcats: subcats })
1399
-
1400
- @articles.concat(pages)
1401
-
1402
- if current_depth < @max_depth
1403
- subcats.each do |subcat|
1404
- fetch_category_members(subcat, current_depth + 1)
1405
- end
1406
- end
1407
1489
  end
1408
1490
 
1409
- def api_request(category_name, continue_token = nil)
1491
+ # GET the API; a failure is an error, never an empty result
1492
+ def api_get(params)
1410
1493
  uri = URI(format(API_ENDPOINT, @lang))
1411
- params = {
1412
- action: "query",
1413
- list: "categorymembers",
1414
- cmtitle: "Category:#{category_name}",
1415
- cmtype: "page|subcat",
1416
- cmlimit: MAX_LIMIT,
1417
- format: "json"
1418
- }
1419
- params[:cmcontinue] = continue_token if continue_token
1420
- uri.query = URI.encode_www_form(params)
1421
-
1494
+ uri.query = URI.encode_www_form(params.merge(format: "json", formatversion: 2))
1422
1495
  attempts = 0
1423
1496
  begin
1424
1497
  attempts += 1
@@ -1427,13 +1500,17 @@ module Wp2txt
1427
1500
  http.open_timeout = DEFAULT_HTTP_TIMEOUT
1428
1501
  http.read_timeout = DEFAULT_HTTP_TIMEOUT
1429
1502
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
1503
+ response = http.request(Net::HTTP::Get.new(uri))
1504
+ code = response.code.to_i
1505
+ raise DumpManager::TransientFetchError, "#{response.code} #{response.message}" if code >= 500 || code == 429
1506
+ raise ListingError, "#{response.code} #{response.message}" unless response.is_a?(Net::HTTPSuccess)
1430
1507
 
1431
- request = Net::HTTP::Get.new(uri)
1432
- response = http.request(request)
1433
- return nil unless response.is_a?(Net::HTTPSuccess)
1508
+ body = JSON.parse(response.body)
1509
+ raise ListingError, "unexpected response" unless body.is_a?(Hash)
1510
+ raise ListingError, body["error"].is_a?(Hash) ? body["error"]["info"].to_s : body["error"].to_s if body.key?("error")
1434
1511
 
1435
- JSON.parse(response.body)
1436
- rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, Errno::ECONNRESET,
1512
+ body
1513
+ rescue DumpManager::TransientFetchError, Net::OpenTimeout, Net::ReadTimeout, SocketError, Errno::ECONNRESET,
1437
1514
  Errno::ECONNREFUSED, Errno::EHOSTUNREACH, OpenSSL::SSL::SSLError => e
1438
1515
  if attempts <= MAX_HTTP_RETRIES
1439
1516
  delay = 2**attempts
@@ -1441,26 +1518,15 @@ module Wp2txt
1441
1518
  sleep delay
1442
1519
  retry
1443
1520
  end
1444
- warn " API request failed after #{attempts} attempts for category '#{category_name}': #{e.message}"
1445
- nil
1521
+ raise ListingError, e.message
1446
1522
  rescue JSON::ParserError => e
1447
- warn " Invalid JSON response for category '#{category_name}': #{e.message}"
1448
- nil
1523
+ raise ListingError, "invalid JSON: #{e.message}"
1449
1524
  end
1450
1525
  end
1451
1526
 
1452
- def load_from_cache(category_name)
1453
- return nil unless cache
1454
-
1455
- cache.get(category_name)
1456
- end
1457
-
1458
- def save_to_cache(category_name, members)
1459
- return unless cache
1460
-
1461
- pages = members[:pages] || members["pages"] || []
1462
- subcats = members[:subcats] || members["subcats"] || []
1463
- cache.save(category_name, pages, subcats)
1527
+ # A category title without its namespace prefix, for display
1528
+ def display_name(title)
1529
+ title.to_s.split(":", 2).last
1464
1530
  end
1465
1531
  end
1466
1532
  end