Class: WCC::Contentful::SyncEngine::Job

Inherits:
ActiveJob::Base
  • Object
show all
Defined in:
lib/wcc/contentful/sync_engine.rb

Overview

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

Instance Method Summary collapse

Instance Method Details

#configurationObject



145
146
147
# File 'lib/wcc/contentful/sync_engine.rb', line 145

def configuration
  @configuration ||= WCC::Contentful.configuration
end

#perform(event = nil) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/wcc/contentful/sync_engine.rb', line 153

def perform(event = nil)
  return unless services.sync_engine&.should_sync?

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

#servicesObject



149
150
151
# File 'lib/wcc/contentful/sync_engine.rb', line 149

def services
  @services ||= WCC::Contentful::Services.instance
end

#sync!(up_to_id: nil, retry_count: 0) ⇒ 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.



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/wcc/contentful/sync_engine.rb', line 173

def sync!(up_to_id: nil, retry_count: 0)
  id_found, count = services.sync_engine.next(up_to_id: up_to_id)

  next_sync_token = services.sync_engine.state['token']

  logger.info "Synced #{count} entries.  Next sync token:\n  #{next_sync_token}"
  unless id_found
    if retry_count >= configuration.sync_retry_limit
      logger.error "Unable to find item with id '#{up_to_id}' on the Sync API.  " \
                   "Abandoning after #{retry_count} retries."
    else
      wait = (2**retry_count) * configuration.sync_retry_wait.seconds
      logger.info "Unable to find item with id '#{up_to_id}' on the Sync API.  " \
                  "Retrying after #{wait.inspect} " \
                  "(#{configuration.sync_retry_limit - retry_count} retries remaining)"

      self.class.set(wait: wait)
        .perform_later(up_to_id: up_to_id, retry_count: retry_count + 1)
    end
  end
  next_sync_token
end

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

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



198
199
200
201
# File 'lib/wcc/contentful/sync_engine.rb', line 198

def sync_later!(up_to_id: nil, wait: 10.seconds)
  self.class.set(wait: wait)
    .perform_later(up_to_id: up_to_id)
end