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.

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