2024-11-15 13:49:37 -05:00
|
|
|
module Syncable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
has_many :syncs, as: :syncable, dependent: :destroy
|
|
|
|
end
|
|
|
|
|
|
|
|
def syncing?
|
2025-06-10 18:20:06 -04:00
|
|
|
syncs.visible.any?
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-19 16:39:31 -04:00
|
|
|
# Schedules a sync for syncable. If there is an existing sync pending/syncing for this syncable,
|
|
|
|
# we do not create a new sync, and attempt to expand the sync window if needed.
|
2025-05-15 10:19:56 -04:00
|
|
|
def sync_later(parent_sync: nil, window_start_date: nil, window_end_date: nil)
|
2025-05-17 18:28:21 -04:00
|
|
|
Sync.transaction do
|
2025-05-19 16:39:31 -04:00
|
|
|
with_lock do
|
|
|
|
sync = self.syncs.incomplete.first
|
2025-05-17 18:28:21 -04:00
|
|
|
|
2025-05-19 16:39:31 -04:00
|
|
|
if sync
|
|
|
|
Rails.logger.info("There is an existing sync, expanding window if needed (#{sync.id})")
|
|
|
|
sync.expand_window_if_needed(window_start_date, window_end_date)
|
|
|
|
else
|
|
|
|
sync = self.syncs.create!(
|
|
|
|
parent: parent_sync,
|
|
|
|
window_start_date: window_start_date,
|
|
|
|
window_end_date: window_end_date
|
|
|
|
)
|
2025-05-17 18:28:21 -04:00
|
|
|
|
2025-05-19 16:39:31 -04:00
|
|
|
SyncJob.perform_later(sync)
|
|
|
|
end
|
2025-05-18 10:19:15 -04:00
|
|
|
|
2025-05-19 16:39:31 -04:00
|
|
|
sync
|
|
|
|
end
|
2025-05-17 18:28:21 -04:00
|
|
|
end
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
def perform_sync(sync)
|
|
|
|
syncer.perform_sync(sync)
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
def perform_post_sync
|
|
|
|
syncer.perform_post_sync
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
def broadcast_sync_complete
|
|
|
|
sync_broadcaster.broadcast
|
2024-11-20 11:01:52 -05:00
|
|
|
end
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
def sync_error
|
2025-05-09 14:56:49 -04:00
|
|
|
latest_sync&.error
|
|
|
|
end
|
|
|
|
|
|
|
|
def last_synced_at
|
2025-05-15 10:19:56 -04:00
|
|
|
latest_sync&.completed_at
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
|
2025-05-13 16:14:29 -04:00
|
|
|
def last_sync_created_at
|
|
|
|
latest_sync&.created_at
|
|
|
|
end
|
|
|
|
|
2024-11-15 13:49:37 -05:00
|
|
|
private
|
|
|
|
def latest_sync
|
2025-05-15 10:19:56 -04:00
|
|
|
syncs.ordered.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def syncer
|
|
|
|
self.class::Syncer.new(self)
|
|
|
|
end
|
|
|
|
|
|
|
|
def sync_broadcaster
|
|
|
|
self.class::SyncCompleteEvent.new(self)
|
2024-11-15 13:49:37 -05:00
|
|
|
end
|
|
|
|
end
|