Sha256: 4bade4e953396c1a2edcb380a3706f513326b0759c8b29a757a6653196635831

Contents?: true

Size: 1.93 KB

Versions: 8

Compression:

Stored size: 1.93 KB

Contents

require 'alephant/broker/cache'
require 'alephant/broker/errors/content_not_found'
require 'alephant/logger'
require 'faraday'

module Alephant
  module Broker
    module LoadStrategy
      class HTTP
        include Logger

        class URL
          def generate
            raise NotImplementedError
          end
        end

        def initialize(url_generator)
          @url_generator = url_generator
        end

        def load(component_meta)
          cache_object(component_meta)
        rescue
          logger.metric "CacheMiss"
          cache.set(component_meta.cache_key, content(component_meta))
        end

        private

        attr_reader :cache, :url_generator

        def cache
          @cache ||= Cache::Client.new
        end

        def cache_object(component_meta)
          cache.get(component_meta.cache_key) { content component_meta }
        end

        def content(component_meta)
          resp = request component_meta
          {
            :content => resp.body,
            :content_type => extract_content_type_from(resp.env.response_headers)
          }
        end

        def extract_content_type_from(headers)
          headers['content-type'].split(';').first
        end

        def request(component_meta)
          before = Time.new
          component_meta.cached = false

          Faraday.get(url_for component_meta).tap do |r|
            unless r.success?
              logger.metric "ContentNotFound"
              raise Alephant::Broker::Errors::ContentNotFound
            end

            request_time = Time.new - before
            logger.metric("LoadComponentTime",
                          :unit  => "Seconds",
                          :value => request_time
                         )
          end
        end

        def url_for(component_meta)
          url_generator.generate(
            component_meta.id,
            component_meta.options
          )
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
alephant-broker-3.7.1 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.7.0 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.6.1 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.6.0 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.5.5 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.5.4 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.5.3 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.5.2 lib/alephant/broker/load_strategy/http.rb