2024-11-15 13:49:37 -05:00
|
|
|
class Sync < ApplicationRecord
|
2025-04-18 09:46:49 -04:00
|
|
|
Error = Class.new(StandardError)
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
belongs_to :syncable, polymorphic: true
|
|
|
|
|
2025-04-11 12:13:46 -04:00
|
|
|
belongs_to :parent, class_name: "Sync", optional: true
|
|
|
|
has_many :children, class_name: "Sync", foreign_key: :parent_id, dependent: :destroy
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
enum :status, { pending: "pending", syncing: "syncing", completed: "completed", failed: "failed" }
|
|
|
|
|
|
|
|
scope :ordered, -> { order(created_at: :desc) }
|
|
|
|
|
2025-04-11 12:13:46 -04:00
|
|
|
def child?
|
|
|
|
parent_id.present?
|
|
|
|
end
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
def perform
|
2025-03-05 15:38:31 -05:00
|
|
|
Rails.logger.tagged("Sync", id, syncable_type, syncable_id) do
|
|
|
|
start!
|
|
|
|
|
|
|
|
begin
|
2025-05-08 12:52:40 -04:00
|
|
|
syncable.sync_data(self, start_date: start_date)
|
2025-04-11 12:13:46 -04:00
|
|
|
|
2025-05-12 15:41:14 -04:00
|
|
|
complete!
|
|
|
|
Rails.logger.info("Sync completed, starting post-sync")
|
|
|
|
syncable.post_sync(self)
|
|
|
|
Rails.logger.info("Post-sync completed")
|
2025-04-18 11:39:58 -04:00
|
|
|
rescue StandardError => error
|
2025-05-09 14:56:49 -04:00
|
|
|
fail! error, report_error: true
|
2025-04-11 12:13:46 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
private
|
|
|
|
def start!
|
2025-03-05 15:38:31 -05:00
|
|
|
Rails.logger.info("Starting sync")
|
2024-11-15 13:49:37 -05:00
|
|
|
update! status: :syncing
|
|
|
|
end
|
|
|
|
|
|
|
|
def complete!
|
2025-03-05 15:38:31 -05:00
|
|
|
Rails.logger.info("Sync completed")
|
2024-11-15 13:49:37 -05:00
|
|
|
update! status: :completed, last_ran_at: Time.current
|
|
|
|
end
|
|
|
|
|
2025-05-09 14:56:49 -04:00
|
|
|
def fail!(error, report_error: false)
|
2025-03-05 15:38:31 -05:00
|
|
|
Rails.logger.error("Sync failed: #{error.message}")
|
|
|
|
|
2025-05-09 14:56:49 -04:00
|
|
|
if report_error
|
|
|
|
Sentry.capture_exception(error) do |scope|
|
|
|
|
scope.set_context("sync", { id: id, syncable_type: syncable_type, syncable_id: syncable_id })
|
|
|
|
scope.set_tags(sync_id: id)
|
|
|
|
end
|
2024-12-02 12:04:54 -05:00
|
|
|
end
|
|
|
|
|
2024-12-30 16:04:05 +01:00
|
|
|
update!(
|
|
|
|
status: :failed,
|
|
|
|
error: error.message,
|
|
|
|
last_ran_at: Time.current
|
|
|
|
)
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
end
|