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.

79 lines
2.3 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. db_config = ActiveRecord::Base.configurations[Rails.env].dup
  23. db_config['pool'] = options[:concurrency] + 1
  24. ActiveRecord::Base.establish_connection(db_config)
  25. progress = create_progress_bar(scope.count)
  26. pool = Concurrent::FixedThreadPool.new(options[:concurrency])
  27. total = Concurrent::AtomicFixnum.new(0)
  28. aggregate = Concurrent::AtomicFixnum.new(0)
  29. scope.reorder(nil).find_in_batches do |items|
  30. futures = []
  31. items.each do |item|
  32. futures << Concurrent::Future.execute(executor: pool) do
  33. begin
  34. if !progress.total.nil? && progress.progress + 1 > progress.total
  35. # The number of items has changed between start and now,
  36. # since there is no good way to predict the final count from
  37. # here, just change the progress bar to an indeterminate one
  38. progress.total = nil
  39. end
  40. progress.log("Processing #{item.id}") if options[:verbose]
  41. result = ActiveRecord::Base.connection_pool.with_connection do
  42. yield(item)
  43. end
  44. aggregate.increment(result) if result.is_a?(Integer)
  45. rescue => e
  46. progress.log pastel.red("Error processing #{item.id}: #{e}")
  47. ensure
  48. progress.increment
  49. end
  50. end
  51. end
  52. total.increment(items.size)
  53. futures.map(&:value)
  54. end
  55. progress.stop
  56. [total.value, aggregate.value]
  57. end
  58. def pastel
  59. @pastel ||= Pastel.new
  60. end
  61. end
  62. end