Class: Pickpoint::Transport::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, http:, auth:, max_retries:, retry_base:) ⇒ Client

Returns a new instance of Client.



28
29
30
31
32
33
34
# File 'lib/pickpoint/transport.rb', line 28

def initialize(base_url:, http:, auth:, max_retries:, retry_base:)
  @base_url = base_url
  @http = http
  @auth = auth
  @max_retries = max_retries
  @retry_base = retry_base
end

Instance Method Details

#do(opts) ⇒ Object



36
37
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
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
# File 'lib/pickpoint/transport.rb', line 36

def do(opts)
  attempt = 0
  auth_retried = false

  loop do
    url = build_url(opts)
    headers = {}
    @auth.apply!(headers)
    body = opts.body.nil? ? nil : JSON.generate(opts.body)
    headers["Content-Type"] = "application/json" unless body.nil?

    begin
      status, raw = @http.request(opts.method || "GET", url, headers: headers, body: body)
    rescue StandardError => e
      raise APIError.new(code: "NETWORK", message: "network error: #{e}") if attempt >= @max_retries

      sleep_backoff(attempt)
      attempt += 1
      next
    end

    if status == 401
      if !auth_retried && @auth.bearer? && @auth.refresh_after_unauthorized
        auth_retried = true
        next
      end
      raise APIError.new(status: status, code: "API_AUTH", message: "auth failed (401)", body: raw)
    end

    if [402, 403].include?(status)
      raise APIError.new(status: status, code: "API_AUTH", message: "auth failed", body: raw)
    end

    return "" if status == 204

    if status == 409
      raise APIError.new(
        status: 409,
        code: "CONFLICT",
        message: message_from_body(raw, 409),
        body: raw
      )
    end

    if status == 400 || (status >= 404 && status < 500)
      return opts.empty || "" if opts.on_client_error == ON_EMPTY

      code = status == 404 ? "NOT_FOUND" : "CLIENT_ERROR"
      raise APIError.new(
        status: status,
        code: code,
        message: message_from_body(raw, status),
        body: raw
      )
    end

    if status >= 500
      if attempt >= @max_retries
        raise APIError.new(
          status: status,
          code: "SERVER_ERROR",
          message: "server error after retries",
          body: raw
        )
      end
      sleep_backoff(attempt)
      attempt += 1
      next
    end

    return raw if status >= 200 && status < 300

    return opts.empty || "" if status >= 400 && status < 500 && opts.on_client_error == ON_EMPTY

    raise APIError.new(
      status: status,
      code: "CLIENT_ERROR",
      message: message_from_body(raw, status),
      body: raw
    )
  end
end