Class: Cacho::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/cacho.rb

Constant Summary collapse

Error =
Class.new(StandardError)
NotFound =
Class.new(Error)

Instance Method Summary collapse

Constructor Details

#initialize(callbacks = {}) ⇒ Client

Returns a new instance of Client.



37
38
39
40
41
# File 'lib/cacho.rb', line 37

def initialize(callbacks = {})
  @http = Net::HTTP::Persistent.new
  @callbacks = callbacks
  @callbacks[:configure_http].(@http) if @callbacks[:configure_http]
end

Instance Method Details

#protect(options = {}) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/cacho.rb', line 148

def protect(options = {})
  throttle = options.fetch(:throttle, 1)
  maximum_retries = options.fetch(:retries, nil)
  retries = 0

  begin
    result = yield

    retries = 0

    return result
  rescue SocketError, \
         EOFError, \
         Errno::ECONNREFUSED, \
         Errno::ECONNRESET, \
         Errno::EHOSTUNREACH, \
         Errno::ENETUNREACH, \
         Net::HTTP::Persistent::Error, \
         Errno::ETIMEDOUT

    retries += 1

    $stderr.puts("-> #{$!.class}: #{$!.message}")

    sleep([retries ** 2 * throttle, 300].min)

    retry if maximum_retries.nil? || retries < maximum_retries
  end
end

#request(verb, url, options = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/cacho.rb', line 55

def request(verb, url, options = {})
  uri = self.uri(url, options)

  loop do
    request = Net::HTTP.const_get(verb.capitalize).new(uri.request_uri)

    @callbacks[:before_request].(request) if @callbacks[:before_request]

    request["User-Agent"] = "Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0"

    if options.include?(:headers)
      options[:headers].each do |key, value|
        request[key] = value
      end
    end

    request["Accept-Encoding"] = "gzip"

    if verb == :post
      post_data = options.fetch(:data, {})

      case options[:content_type]
      when :json
        request["Content-Type"] = "application/json; charset=utf-8"
        request.body = post_data.to_json
      else
        request.body = URI.encode_www_form(post_data)
      end
    end

    if options[:content_encoding] == :deflate
      request["Content-Encoding"] = "deflate"

      request.body = Zlib::Deflate.deflate(request.body)
    end

    $stderr.puts("-> #{verb.upcase} #{uri}")

    if verb_idempotent?(verb)
      res = protect { @http.request(uri, request) }
    else
      res = @http.request(uri, request)
    end

    body = res.body

    if res["Content-Encoding"] == "gzip"
      body = Zlib::GzipReader.new(StringIO.new(body)).read
    end

    if res["Content-Type"]
      if charset = res["Content-Type"][/\bcharset=(.+)\b/, 1]
        body.force_encoding(charset)
        body.encode!(Encoding.default_external)
      end

      if res["Content-Type"].start_with?("application/json")
        parsed = JSON.parse(body)
      else
        parsed = body
      end
    end

    if @callbacks[:rate_limit_detector]
      if seconds = @callbacks[:rate_limit_detector].(res, body, parsed)
        $stderr.puts("Rate limited for #{seconds} seconds.")
        sleep(seconds)
        next
      end
    end

    case res.code
    when "200"
      return parsed
    when "303" , "302" , "301"
      if res["Location"].to_s.index(/^https?:\/\//)
        uri = URI(res["Location"])
      else
        uri = URI.join(uri, res["Location"])
      end
      $stderr.puts("Redirected to #{res["Location"]} (#{uri})")
    when "404"
      return nil
    else
      raise "Got #{res.code}: #{body.inspect}"
    end
  end
end

#uri(url, options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/cacho.rb', line 43

def uri(url, options = {})
  query = options.fetch(:query, {}).dup

  @callbacks[:process_query].(query) if @callbacks[:process_query]

  uri = URI(url)

  uri.query = URI.encode_www_form(query) if query.size > 0

  uri
end

#verb_idempotent?(verb) ⇒ Boolean

Returns:

  • (Boolean)


144
145
146
# File 'lib/cacho.rb', line 144

def verb_idempotent?(verb)
  verb == :get || verb == :head || verb == :options
end