bulk_import.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: bulk_imports
  5. #
  6. # id :bigint(8) not null, primary key
  7. # type :integer not null
  8. # state :integer not null
  9. # total_items :integer default(0), not null
  10. # imported_items :integer default(0), not null
  11. # processed_items :integer default(0), not null
  12. # finished_at :datetime
  13. # overwrite :boolean default(FALSE), not null
  14. # likely_mismatched :boolean default(FALSE), not null
  15. # original_filename :string default(""), not null
  16. # account_id :bigint(8) not null
  17. # created_at :datetime not null
  18. # updated_at :datetime not null
  19. #
  20. class BulkImport < ApplicationRecord
  21. self.inheritance_column = false
  22. ARCHIVE_PERIOD = 1.week
  23. CONFIRM_PERIOD = 10.minutes
  24. belongs_to :account
  25. has_many :rows, class_name: 'BulkImportRow', inverse_of: :bulk_import, dependent: :delete_all
  26. enum :type, {
  27. following: 0,
  28. blocking: 1,
  29. muting: 2,
  30. domain_blocking: 3,
  31. bookmarks: 4,
  32. lists: 5,
  33. }
  34. enum :state, {
  35. unconfirmed: 0,
  36. scheduled: 1,
  37. in_progress: 2,
  38. finished: 3,
  39. }, prefix: true
  40. validates :type, presence: true
  41. scope :archival_completed, -> { where(created_at: ..ARCHIVE_PERIOD.ago) }
  42. scope :confirmation_missed, -> { state_unconfirmed.where(created_at: ..CONFIRM_PERIOD.ago) }
  43. def self.progress!(bulk_import_id, imported: false)
  44. # Use `increment_counter` so that the incrementation is done atomically in the database
  45. BulkImport.increment_counter(:processed_items, bulk_import_id)
  46. BulkImport.increment_counter(:imported_items, bulk_import_id) if imported
  47. # Since the incrementation has been done atomically, concurrent access to `bulk_import` is now bening
  48. bulk_import = BulkImport.find(bulk_import_id)
  49. bulk_import.update!(state: :finished, finished_at: Time.now.utc) if bulk_import.processed_items == bulk_import.total_items
  50. end
  51. end