Sha256: 7f852c26c5fefbd6e5430b000983c28486088ac93922fbf91b675365af0391b5

Contents?: true

Size: 1.42 KB

Versions: 9

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

module Prefab
  module PeriodicSync
    LOG = Prefab::InternalLogger.new(self)

    def sync
      return if @data.size.zero?

      LOG.debug "Syncing #{@data.size} items"

      start_at_was = @start_at
      @start_at = Prefab::TimeHelpers.now_in_ms

      flush(prepare_data, start_at_was)
    end

    def prepare_data
      to_ship = @data.dup
      @data.clear

      on_prepare_data

      to_ship
    end

    def on_prepare_data
      # noop -- override as you wish
    end

    def post(url, data)
      @client.post(url, data)
    end

    def instance_hash
      @client.instance_hash
    end

    def start_periodic_sync(sync_interval)
      @start_at = Prefab::TimeHelpers.now_in_ms

      @sync_interval = calculate_sync_interval(sync_interval)

      Thread.new do
        LOG.debug "Initialized #{@name} instance_hash=#{@client.instance_hash}"

        loop do
          sleep @sync_interval.call
          sync
        end
      end
    end

    def pool
      @pool ||= Concurrent::ThreadPoolExecutor.new(
        fallback_policy: :discard,
        max_queue: 5,
        max_threads: 4,
        min_threads: 1,
        name: @name
      )
    end

    private

    def calculate_sync_interval(sync_interval)
      if sync_interval.is_a?(Numeric)
        proc { sync_interval }
      else
        sync_interval || ExponentialBackoff.new(initial_delay: 8, max_delay: 60 * 5)
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
prefab-cloud-ruby-1.8.8.pre.1 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.7 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.6 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.5 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.4 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.3 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.2 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.1 lib/prefab/periodic_sync.rb
prefab-cloud-ruby-1.8.0 lib/prefab/periodic_sync.rb