Sha256: e361bdc7f2861ad31c3a36f90c3a579cb9cb5da717a31ed26c75e84f64aeb05e

Contents?: true

Size: 1.93 KB

Versions: 10

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)
          fetch_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 fetch_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

10 entries across 10 versions & 1 rubygems

Version Path
alephant-broker-3.13.0 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.12.0 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.11.0 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.10.2 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.10.1 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.10.0 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.9.2 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.9.1 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.9.0 lib/alephant/broker/load_strategy/http.rb
alephant-broker-3.8.0 lib/alephant/broker/load_strategy/http.rb