Class: Segment::Analytics::Request

Inherits:
Object
  • Object
show all
Includes:
Defaults::Request, Logging, Utils
Defined in:
lib/segment/analytics/request.rb

Constant Summary

Constants included from Utils

Utils::UTC_OFFSET_WITHOUT_COLON, Utils::UTC_OFFSET_WITH_COLON

Constants included from Defaults::Request

Defaults::Request::BACKOFF, Defaults::Request::HEADERS, Defaults::Request::HOST, Defaults::Request::PATH, Defaults::Request::PORT, Defaults::Request::RETRIES, Defaults::Request::SSL

Class Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

included, logger, #logger, logger=

Methods included from Utils

#date_in_iso8601, #datetime_in_iso8601, #formatted_offset, #isoify_dates, #isoify_dates!, #seconds_to_utc_offset, #stringify_keys, #symbolize_keys, #symbolize_keys!, #time_in_iso8601, #uid

Constructor Details

#initialize(options = {}) ⇒ Request

public: Creates a new request object to send analytics batch


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/segment/analytics/request.rb', line 18

def initialize(options = {})
  options[:host] ||= HOST
  options[:port] ||= PORT
  options[:ssl] ||= SSL
  options[:headers] ||= HEADERS
  @path = options[:path] || PATH
  @retries = options[:retries] || RETRIES
  @backoff = options[:backoff] || BACKOFF

  http = Net::HTTP.new(options[:host], options[:port])
  http.use_ssl = options[:ssl]
  http.read_timeout = 8
  http.open_timeout = 4

  @http = http
end

Class Attribute Details

.stubObject

Returns the value of attribute stub


74
75
76
# File 'lib/segment/analytics/request.rb', line 74

def stub
  @stub
end

Instance Method Details

#post(write_key, batch) ⇒ Object

public: Posts the write key and batch of messages to the API.

returns - Response of the status and error if it exists


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/segment/analytics/request.rb', line 38

def post(write_key, batch)
  status, error = nil, nil
  remaining_retries = @retries
  backoff = @backoff
  headers = { 'Content-Type' => 'application/json', 'accept' => 'application/json' }
  begin
    payload = JSON.generate :sentAt => datetime_in_iso8601(Time.new), :batch => batch
    request = Net::HTTP::Post.new(@path, headers)
    request.basic_auth write_key, nil

    if self.class.stub
      status = 200
      error = nil
      logger.debug "stubbed request to #{@path}: write key = #{write_key}, payload = #{payload}"
    else
      res = @http.request(request, payload)
      status = res.code.to_i
      body = JSON.parse(res.body)
      error = body["error"]
    end
  rescue Exception => e
    unless (remaining_retries -=1).zero?
      sleep(backoff)
      retry
    end

    logger.error e.message
    e.backtrace.each { |line| logger.error line }
    status = -1
    error = "Connection error: #{e}"
  end

  Response.new status, error
end