You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.2 KiB

  1. # frozen_string_literal: true
  2. dev_null = Logger.new('/dev/null')
  3. Rails.logger = dev_null
  4. ActiveRecord::Base.logger = dev_null
  5. ActiveJob::Base.logger = dev_null
  6. HttpLog.configuration.logger = dev_null
  7. Paperclip.options[:log] = false
  8. Chewy.logger = dev_null
  9. module Mastodon
  10. module CLIHelper
  11. def dry_run?
  12. options[:dry_run]
  13. end
  14. def create_progress_bar(total = nil)
  15. ProgressBar.create(total: total, format: '%c/%u |%b%i| %e')
  16. end
  17. def parallelize_with_progress(scope)
  18. if options[:concurrency] < 1
  19. say('Cannot run with this concurrency setting, must be at least 1', :red)
  20. exit(1)
  21. end
  22. ActiveRecord::Base.configurations[Rails.env]['pool'] = options[:concurrency] + 1
  23. progress = create_progress_bar(scope.count)
  24. pool = Concurrent::FixedThreadPool.new(options[:concurrency])
  25. total = Concurrent::AtomicFixnum.new(0)
  26. aggregate = Concurrent::AtomicFixnum.new(0)
  27. scope.reorder(nil).find_in_batches do |items|
  28. futures = []
  29. items.each do |item|
  30. futures << Concurrent::Future.execute(executor: pool) do
  31. begin
  32. if !progress.total.nil? && progress.progress + 1 > progress.total
  33. # The number of items has changed between start and now,
  34. # since there is no good way to predict the final count from
  35. # here, just change the progress bar to an indeterminate one
  36. progress.total = nil
  37. end
  38. progress.log("Processing #{item.id}") if options[:verbose]
  39. result = ActiveRecord::Base.connection_pool.with_connection do
  40. yield(item)
  41. end
  42. aggregate.increment(result) if result.is_a?(Integer)
  43. rescue => e
  44. progress.log pastel.red("Error processing #{item.id}: #{e}")
  45. ensure
  46. progress.increment
  47. end
  48. end
  49. end
  50. total.increment(items.size)
  51. futures.map(&:value)
  52. end
  53. progress.stop
  54. [total.value, aggregate.value]
  55. end
  56. def pastel
  57. @pastel ||= Pastel.new
  58. end
  59. end
  60. end