Class: WCC::Contentful::DelayedSyncJob

Inherits:
ActiveJob::Base
  • Object
show all
Includes:
ServiceAccessors
Defined in:
app/jobs/wcc/contentful/delayed_sync_job.rb

Overview

This job uses the Contentful Sync API to update the configured store with the latest data from Contentful.

Constant Summary

Constants included from ServiceAccessors

ServiceAccessors::SERVICES

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.mutexObject



14
15
16
# File 'app/jobs/wcc/contentful/delayed_sync_job.rb', line 14

def self.mutex
  @mutex ||= Mutex.new
end

Instance Method Details

#perform(event = nil) ⇒ Object



18
19
20
21
22
# File 'app/jobs/wcc/contentful/delayed_sync_job.rb', line 18

def perform(event = nil)
  up_to_id = nil
  up_to_id = event[:up_to_id] || event.dig('sys', 'id') if event
  sync!(up_to_id: up_to_id)
end

#sync!(up_to_id: nil) ⇒ Object

Calls the Contentful Sync API and updates the configured store with the returned data.

Parameters:

  • up_to_id (String) (defaults to: nil)

    An ID that we know has changed and should come back from the sync. If we don’t find this ID in the sync data, then drop a job to try the sync again after a few minutes.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'app/jobs/wcc/contentful/delayed_sync_job.rb', line 32

def sync!(up_to_id: nil)
  return unless store.respond_to?(:index)

  self.class.mutex.synchronize do
    next_sync_token = store.find('sync:token')&.fetch('token')
    sync_resp = client.sync(sync_token: next_sync_token)

    id_found = up_to_id.nil?

    count = 0
    sync_resp.items.each do |item|
      id = item.dig('sys', 'id')
      id_found ||= id == up_to_id
      store.index(item)
      count += 1
    end
    store.set('sync:token', token: sync_resp.next_sync_token)

    logger.info "Synced #{count} entries.  Next sync token:\n  #{sync_resp.next_sync_token}"
    sync_later!(up_to_id: up_to_id) unless id_found
    sync_resp.next_sync_token
  end
end

#sync_later!(up_to_id: nil, wait: 10.minutes) ⇒ Object

Drops an ActiveJob job to invoke WCC::Contentful.sync! after a given amount of time.



58
59
60
61
# File 'app/jobs/wcc/contentful/delayed_sync_job.rb', line 58

def sync_later!(up_to_id: nil, wait: 10.minutes)
  WCC::Contentful::DelayedSyncJob.set(wait: wait)
    .perform_later(up_to_id: up_to_id)
end