Class: MisarMail::Core::Transport

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

Overview

HTTP transport shared by the generated resource layer.

Everything the SDK does goes through one of three transports — HTTP for REST, SSE for streaming, WebSocket for push — and all three authenticate the same way: the account API key, sent as a bearer token. There is no second credential path. What a key may do, and how much of it, is decided server-side from the subscription behind that key.

Constant Summary collapse

RETRYABLE_STATUSES =
[429, 500, 502, 503, 504].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, base_url: "https://api.misar.io/mail", max_retries: 3, timeout: 30) ⇒ Transport

Returns a new instance of Transport.

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
# File 'lib/misar_mail/core/transport.rb', line 23

def initialize(api_key, base_url: "https://api.misar.io/mail", max_retries: 3, timeout: 30)
  raise ArgumentError, "A MisarMail API key is required" if api_key.nil? || api_key.empty?

  @api_key = api_key
  @base_url = base_url.chomp("/")
  @max_retries = max_retries
  @timeout = timeout
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



21
22
23
# File 'lib/misar_mail/core/transport.rb', line 21

def api_key
  @api_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



21
22
23
# File 'lib/misar_mail/core/transport.rb', line 21

def base_url
  @base_url
end

Instance Method Details

#headersObject



58
59
60
61
62
63
# File 'lib/misar_mail/core/transport.rb', line 58

def headers
  {
    "Authorization" => "Bearer #{@api_key}",
    "Content-Type" => "application/json"
  }
end

#request(method, path, body = nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/misar_mail/core/transport.rb', line 32

def request(method, path, body = nil)
  uri = URI.parse("#{@base_url}#{path}")
  attempt = 0

  loop do
    response = perform(uri, method, body)

    if RETRYABLE_STATUSES.include?(response.code.to_i) && attempt < @max_retries - 1
      sleep(backoff(attempt, response))
      attempt += 1
      next
    end

    return decode(response)
  rescue StandardError => e
    raise if e.is_a?(MisarMail::Error)

    if attempt < @max_retries - 1
      sleep(backoff(attempt))
      attempt += 1
      next
    end
    raise MisarMail::NetworkError.new(e.message)
  end
end