Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Access Response Headers for Rate Limiting (Help Scout)

I'm using the helpscout ruby gem and trying to check when request limit is under a certain number (i.e 2 requests remaining) and sleep the loop for the remaining interval to allow for rate limit to be reset.

Is there a way to access the response headers from an API when making a request? https://developer.helpscout.com/help-desk-api/#basic-rate-limiting

X-RateLimit-Interval-*  Length of the rate limiting interval in seconds

X-RateLimit-Limit-* Maximum number of requests per interval

X-RateLimit-Remaining-* Number of requests remaining in the current rate limit interval

Intercom (https://developers.intercom.com/reference#rate-limiting) allows your to check the rate_limit_details and returns the headers, but I can't find anything for Help Scout or understand how to access them.

intercom.rate_limit_details
#=> {:limit=>180, :remaining=>179, :reset_at=>2014-10-07 14:58:00 +0100}
like image 849
VegaStudios Avatar asked Feb 11 '18 22:02

VegaStudios


1 Answers

The issue is the helpscout gem doesn't capture that info. If you look at the source code

https://github.com/hramos/helpscout/blob/db8da936853c8df694186ab11100d4482f74d302/lib/helpscout/models.rb#L44

  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
    end
  end

When an error occurs they only capture status and message. You can enhance the class below if you want to capture additional header values

  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message, :limit

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
      @limit = object["header"]["X-RateLimit-...."]
    end
  end

But this would only tell you limits when you get an error. You can enhance the library further to capture these limits on every call. You will need to modify the client.rb

https://github.com/hramos/helpscout/blob/2449bc2604667edfca5ed934c8e61cd129b17af5/lib/helpscout/client.rb

module HelpScout
  class Client
    include HTTParty
    @@last_headers

    def self.get(*more)
        response = HTTParty.get(*more)
        @@last_headers = response.headers
        return response
    end

    def self.last_headers
        @@last_headers
    end

    ....
    ....
 end

So doing HelpScout.last_headers will give you the headers from last response and then you can capture whichever field you need from the same

like image 160
Tarun Lalwani Avatar answered Nov 17 '22 00:11

Tarun Lalwani