prontuno 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE.md +9 -0
- data/README.md +495 -0
- data/lib/prontuno/client.rb +64 -0
- data/lib/prontuno/errors.rb +92 -0
- data/lib/prontuno/http_client.rb +345 -0
- data/lib/prontuno/pagination.rb +49 -0
- data/lib/prontuno/resources/api_keys.rb +41 -0
- data/lib/prontuno/resources/base.rb +66 -0
- data/lib/prontuno/resources/domains.rb +28 -0
- data/lib/prontuno/resources/emails.rb +103 -0
- data/lib/prontuno/resources/sent_email_attachments.rb +27 -0
- data/lib/prontuno/resources/smtp_credentials.rb +43 -0
- data/lib/prontuno/resources/suppressions.rb +34 -0
- data/lib/prontuno/resources/usage.rb +12 -0
- data/lib/prontuno/resources/webhooks.rb +60 -0
- data/lib/prontuno/transport.rb +87 -0
- data/lib/prontuno/util.rb +59 -0
- data/lib/prontuno/version.rb +5 -0
- data/lib/prontuno/webhook.rb +125 -0
- data/lib/prontuno.rb +23 -0
- metadata +65 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "time"
|
|
5
|
+
require "uri"
|
|
6
|
+
|
|
7
|
+
module Prontuno
|
|
8
|
+
# Sends requests to the Prontuno API: authentication, retries, and response parsing.
|
|
9
|
+
# Use {Prontuno::Client} rather than this class directly.
|
|
10
|
+
class HttpClient
|
|
11
|
+
DEFAULT_BASE_URL = "https://api.prontuno.net/v1"
|
|
12
|
+
DEFAULT_TIMEOUT = 30
|
|
13
|
+
DEFAULT_MAX_RETRIES = 2
|
|
14
|
+
DEFAULT_MAX_RESPONSE_SIZE = 10 * 1024 * 1024
|
|
15
|
+
MAX_RETRY_DELAY = 60
|
|
16
|
+
USER_AGENT = "prontuno-ruby/#{VERSION}".freeze
|
|
17
|
+
LOOPBACK_HOSTS = %w[localhost 127.0.0.1 [::1]].freeze
|
|
18
|
+
REQUEST_OPTIONS = %i[timeout max_retries max_response_size headers].freeze
|
|
19
|
+
IDEMPOTENT_REQUEST_OPTIONS = (REQUEST_OPTIONS + %i[idempotency_key]).freeze
|
|
20
|
+
NO_BODY = Object.new.freeze
|
|
21
|
+
|
|
22
|
+
attr_reader :base_url, :timeout, :max_retries, :max_response_size, :user_agent, :transport
|
|
23
|
+
attr_accessor :last_response
|
|
24
|
+
|
|
25
|
+
def initialize(api_key: nil, sending_key: nil, management_key: nil, base_url: nil, timeout: nil,
|
|
26
|
+
max_retries: nil, max_response_size: nil, app_info: nil, transport: nil, sleeper: nil)
|
|
27
|
+
shared_key = normalize_key(api_key)
|
|
28
|
+
@sending_key = normalize_key(sending_key) || shared_key
|
|
29
|
+
@management_key = normalize_key(management_key) || shared_key
|
|
30
|
+
unless @sending_key || @management_key
|
|
31
|
+
raise ConfigError, "A non-empty Prontuno API key is required (api_key, sending_key, or management_key)"
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
@timeout = validate_timeout(timeout.nil? ? DEFAULT_TIMEOUT : timeout)
|
|
35
|
+
@max_retries = validate_max_retries(max_retries.nil? ? DEFAULT_MAX_RETRIES : max_retries)
|
|
36
|
+
@max_response_size = validate_max_response_size(
|
|
37
|
+
max_response_size.nil? ? DEFAULT_MAX_RESPONSE_SIZE : max_response_size
|
|
38
|
+
)
|
|
39
|
+
@base_url = normalize_base_url(base_url.nil? ? (base_url_from_env || DEFAULT_BASE_URL) : base_url)
|
|
40
|
+
@user_agent = build_user_agent(app_info)
|
|
41
|
+
@transport = transport || Transport::NetHttp.new
|
|
42
|
+
raise ConfigError, "transport must respond to #call" unless @transport.respond_to?(:call)
|
|
43
|
+
|
|
44
|
+
@sleeper = sleeper || ->(seconds) { Kernel.sleep(seconds) }
|
|
45
|
+
raise ConfigError, "sleeper must respond to #call" unless @sleeper.respond_to?(:call)
|
|
46
|
+
|
|
47
|
+
@last_response = nil
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# @param method [String] "GET", "POST", "PATCH" or "DELETE"
|
|
51
|
+
# @param path [String] relative to the base URL
|
|
52
|
+
# @param body [Object] serialized as JSON when given
|
|
53
|
+
# @param query [Hash] nil values are skipped
|
|
54
|
+
# @param sending [Boolean] authenticate with the sending key instead of the management key
|
|
55
|
+
# @param options [Hash] per-request options
|
|
56
|
+
# @param allowed [Array<Symbol>] the option names this call accepts
|
|
57
|
+
def request(method, path, body: NO_BODY, query: nil, sending: false, options: {}, allowed: REQUEST_OPTIONS)
|
|
58
|
+
settings = request_settings(options, allowed)
|
|
59
|
+
api_key = sending ? @sending_key : @management_key
|
|
60
|
+
unless api_key
|
|
61
|
+
role, option = sending ? %w[sending sending_key] : %w[management management_key]
|
|
62
|
+
raise ConfigError,
|
|
63
|
+
"#{method} /#{path} requires a #{role} API key; pass #{option} (or api_key) when creating the client"
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
headers = build_headers(settings[:headers], api_key)
|
|
67
|
+
serialized = nil
|
|
68
|
+
unless body.equal?(NO_BODY)
|
|
69
|
+
set_header(headers, "Content-Type", "application/json")
|
|
70
|
+
serialized = JSON.generate(body)
|
|
71
|
+
end
|
|
72
|
+
idempotency_key = settings[:idempotency_key]
|
|
73
|
+
set_header(headers, "Idempotency-Key", idempotency_key) if idempotency_key
|
|
74
|
+
|
|
75
|
+
transport_request = Transport::Request.new(
|
|
76
|
+
http_method: method,
|
|
77
|
+
url: build_url(path, query),
|
|
78
|
+
headers: headers,
|
|
79
|
+
body: serialized,
|
|
80
|
+
timeout: settings[:timeout],
|
|
81
|
+
max_response_size: settings[:max_response_size]
|
|
82
|
+
)
|
|
83
|
+
perform_with_retries(transport_request, settings[:max_retries], idempotency_key)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def inspect
|
|
87
|
+
"#<#{self.class.name} base_url=#{@base_url.inspect}>"
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
private
|
|
91
|
+
|
|
92
|
+
def perform_with_retries(request, max_retries, idempotency_key)
|
|
93
|
+
safe_to_retry = %w[GET DELETE].include?(request.http_method) || !idempotency_key.nil?
|
|
94
|
+
# Set once an attempt may have reached the API without a usable response, so a
|
|
95
|
+
# retried DELETE that finds the resource already gone counts as success.
|
|
96
|
+
may_have_applied = false
|
|
97
|
+
attempt = 0
|
|
98
|
+
|
|
99
|
+
loop do
|
|
100
|
+
retry_allowed = safe_to_retry && attempt < max_retries
|
|
101
|
+
begin
|
|
102
|
+
status, headers, parsed = perform_attempt(request)
|
|
103
|
+
rescue ResponseSizeError
|
|
104
|
+
raise
|
|
105
|
+
rescue StandardError => e
|
|
106
|
+
raise connection_failure(e, request.timeout) unless retry_allowed
|
|
107
|
+
|
|
108
|
+
may_have_applied = true
|
|
109
|
+
pause(retry_delay(attempt))
|
|
110
|
+
attempt += 1
|
|
111
|
+
next
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
@last_response = Util.response_metadata(headers)
|
|
115
|
+
return parsed if status.between?(200, 299)
|
|
116
|
+
|
|
117
|
+
error = ApiError.new(status: status, body: normalize_error_body(parsed), headers: headers)
|
|
118
|
+
return nil if may_have_applied && already_deleted?(request, error)
|
|
119
|
+
raise error unless retry_allowed && retryable_response?(error)
|
|
120
|
+
|
|
121
|
+
may_have_applied ||= error.status == 408 || error.status >= 500
|
|
122
|
+
pause(retry_delay(attempt, headers))
|
|
123
|
+
attempt += 1
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# One HTTP attempt. Returns [status, headers, parsed_body].
|
|
128
|
+
def perform_attempt(request)
|
|
129
|
+
response = @transport.call(request)
|
|
130
|
+
status = Integer(response.status)
|
|
131
|
+
headers = Util.normalize_headers(response.headers)
|
|
132
|
+
return [status, headers, nil] if status == 204
|
|
133
|
+
|
|
134
|
+
text = read_body(response.body, headers, request.max_response_size)
|
|
135
|
+
[status, headers, parse_body(status, text)]
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def connection_failure(error, timeout)
|
|
139
|
+
case error
|
|
140
|
+
when ConnectionError then error
|
|
141
|
+
when ::Timeout::Error then TimeoutError.new(timeout)
|
|
142
|
+
else ConnectionError.new("Could not connect to the Prontuno API: #{error.message}")
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
def read_body(body, headers, limit)
|
|
147
|
+
declared = Util.integer_header(headers["content-length"])
|
|
148
|
+
raise ResponseSizeError, limit if declared && declared > limit
|
|
149
|
+
|
|
150
|
+
text = +""
|
|
151
|
+
text.force_encoding(Encoding::BINARY)
|
|
152
|
+
if body.is_a?(String)
|
|
153
|
+
text << body.b
|
|
154
|
+
raise ResponseSizeError, limit if text.bytesize > limit
|
|
155
|
+
elsif body
|
|
156
|
+
body.each do |chunk|
|
|
157
|
+
text << chunk.to_s.b
|
|
158
|
+
raise ResponseSizeError, limit if text.bytesize > limit
|
|
159
|
+
end
|
|
160
|
+
end
|
|
161
|
+
text.force_encoding(Encoding::UTF_8)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def parse_body(status, text)
|
|
165
|
+
success = status >= 200 && status < 300
|
|
166
|
+
if text.empty?
|
|
167
|
+
raise ConnectionError, "Prontuno API returned an empty response" if success
|
|
168
|
+
|
|
169
|
+
return nil
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
begin
|
|
173
|
+
JSON.parse(text, symbolize_names: true)
|
|
174
|
+
rescue JSON::ParserError, EncodingError
|
|
175
|
+
raise ConnectionError, "Prontuno API returned invalid JSON" if success
|
|
176
|
+
|
|
177
|
+
{ error: { code: "invalid_response", message: text.scrub, retryable: false } }
|
|
178
|
+
end
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def normalize_error_body(value)
|
|
182
|
+
value.is_a?(Hash) ? value : {}
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# A DELETE retried after an attempt that may have succeeded finds the resource gone.
|
|
186
|
+
def already_deleted?(request, error)
|
|
187
|
+
return false unless request.http_method == "DELETE"
|
|
188
|
+
|
|
189
|
+
error.status == 404 || (error.status == 409 && error.code == "already_revoked")
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def retryable_response?(error)
|
|
193
|
+
error.status == 408 ||
|
|
194
|
+
error.status == 429 ||
|
|
195
|
+
error.status >= 500 ||
|
|
196
|
+
(error.status == 409 && error.code == "idempotency_request_in_progress")
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
def retry_delay(attempt, headers = nil)
|
|
200
|
+
retry_after = headers && headers["retry-after"]
|
|
201
|
+
if retry_after && !retry_after.strip.empty?
|
|
202
|
+
seconds = Util.parse_float(retry_after)
|
|
203
|
+
return [seconds, MAX_RETRY_DELAY].min if seconds && seconds >= 0
|
|
204
|
+
|
|
205
|
+
date = parse_http_date(retry_after)
|
|
206
|
+
return (date - Time.now).clamp(0, MAX_RETRY_DELAY) if date
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
[0.5 * (2**attempt), 5].min * (0.75 + (rand * 0.5))
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def parse_http_date(value)
|
|
213
|
+
Time.httpdate(value.strip)
|
|
214
|
+
rescue ArgumentError
|
|
215
|
+
begin
|
|
216
|
+
Time.rfc2822(value.strip)
|
|
217
|
+
rescue ArgumentError
|
|
218
|
+
nil
|
|
219
|
+
end
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def pause(seconds)
|
|
223
|
+
@sleeper.call(seconds)
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def request_settings(options, allowed)
|
|
227
|
+
unknown = options.keys - allowed
|
|
228
|
+
raise ArgumentError, "Unknown request option(s): #{unknown.join(", ")}" unless unknown.empty?
|
|
229
|
+
|
|
230
|
+
{
|
|
231
|
+
timeout: options[:timeout].nil? ? @timeout : validate_timeout(options[:timeout]),
|
|
232
|
+
max_retries: options[:max_retries].nil? ? @max_retries : validate_max_retries(options[:max_retries]),
|
|
233
|
+
max_response_size: if options[:max_response_size].nil?
|
|
234
|
+
@max_response_size
|
|
235
|
+
else
|
|
236
|
+
validate_max_response_size(options[:max_response_size])
|
|
237
|
+
end,
|
|
238
|
+
headers: validate_headers(options[:headers]),
|
|
239
|
+
idempotency_key: validate_idempotency_key(options[:idempotency_key])
|
|
240
|
+
}
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
def build_headers(extra, api_key)
|
|
244
|
+
headers = {}
|
|
245
|
+
extra.each { |name, value| headers[name.to_s] = value.to_s }
|
|
246
|
+
set_header(headers, "Accept", "application/json")
|
|
247
|
+
set_header(headers, "Authorization", "Bearer #{api_key}")
|
|
248
|
+
set_header(headers, "User-Agent", @user_agent)
|
|
249
|
+
headers
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
# Replaces any header with the same name, ignoring case.
|
|
253
|
+
def set_header(headers, name, value)
|
|
254
|
+
headers.delete_if { |key, _| key.casecmp?(name) }
|
|
255
|
+
headers[name] = value
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def build_url(path, query)
|
|
259
|
+
url = "#{@base_url}/#{path.delete_prefix("/")}"
|
|
260
|
+
pairs = (query || {}).compact.map { |key, value| [key.to_s, value.to_s] }
|
|
261
|
+
pairs.empty? ? url : "#{url}?#{URI.encode_www_form(pairs)}"
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
def validate_timeout(value)
|
|
265
|
+
unless value.is_a?(Numeric) && value.real? && value.to_f.finite? && value.positive?
|
|
266
|
+
raise ConfigError, "timeout must be a positive number of seconds"
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
value
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
def validate_max_retries(value)
|
|
273
|
+
raise ConfigError, "max_retries must be a non-negative Integer" unless value.is_a?(Integer) && value >= 0
|
|
274
|
+
|
|
275
|
+
value
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
def validate_max_response_size(value)
|
|
279
|
+
raise ConfigError, "max_response_size must be a positive Integer" unless value.is_a?(Integer) && value.positive?
|
|
280
|
+
|
|
281
|
+
value
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
def validate_headers(value)
|
|
285
|
+
return {} if value.nil?
|
|
286
|
+
raise ConfigError, "headers must be a Hash" unless value.is_a?(Hash)
|
|
287
|
+
|
|
288
|
+
value
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
def validate_idempotency_key(value)
|
|
292
|
+
return nil if value.nil? || value == ""
|
|
293
|
+
raise ConfigError, "idempotency_key must be a String" unless value.is_a?(String)
|
|
294
|
+
|
|
295
|
+
value
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
def normalize_key(value)
|
|
299
|
+
value.is_a?(String) && !value.strip.empty? ? value.strip : nil
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
def base_url_from_env
|
|
303
|
+
value = ENV.fetch("PRONTUNO_BASE_URL", nil)&.strip
|
|
304
|
+
value.nil? || value.empty? ? nil : value
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
# Require HTTPS so the API key is never sent in plain text. Plain HTTP is only
|
|
308
|
+
# accepted for loopback hosts, whose traffic never leaves the machine.
|
|
309
|
+
def normalize_base_url(value)
|
|
310
|
+
uri = parse_absolute_url(value)
|
|
311
|
+
scheme = uri.scheme.downcase
|
|
312
|
+
if scheme == "http"
|
|
313
|
+
unless LOOPBACK_HOSTS.include?(uri.host.downcase)
|
|
314
|
+
raise ConfigError, "base_url must use https (plain http is only allowed for loopback hosts)"
|
|
315
|
+
end
|
|
316
|
+
elsif scheme != "https"
|
|
317
|
+
raise ConfigError, "base_url must use https"
|
|
318
|
+
end
|
|
319
|
+
|
|
320
|
+
uri.scheme = scheme
|
|
321
|
+
uri.host = uri.host.downcase
|
|
322
|
+
uri.to_s.delete_suffix("/")
|
|
323
|
+
end
|
|
324
|
+
|
|
325
|
+
def parse_absolute_url(value)
|
|
326
|
+
uri = URI.parse(value.to_s)
|
|
327
|
+
raise ConfigError, "base_url must be a valid absolute URL" if uri.scheme.nil? || uri.host.nil? || uri.host.empty?
|
|
328
|
+
|
|
329
|
+
uri
|
|
330
|
+
rescue URI::InvalidURIError
|
|
331
|
+
raise ConfigError, "base_url must be a valid absolute URL"
|
|
332
|
+
end
|
|
333
|
+
|
|
334
|
+
# The SDK's own identifier always comes first, so requests can be traced to an SDK version.
|
|
335
|
+
def build_user_agent(app_info)
|
|
336
|
+
return USER_AGENT if app_info.nil?
|
|
337
|
+
if !app_info.is_a?(String) || app_info.match?(/[\x00-\x1f\x7f]/)
|
|
338
|
+
raise ConfigError, "app_info must be a single-line String"
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
trimmed = app_info.strip
|
|
342
|
+
trimmed.empty? ? USER_AGENT : "#{USER_AGENT} #{trimmed}"
|
|
343
|
+
end
|
|
344
|
+
end
|
|
345
|
+
end
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Prontuno
|
|
4
|
+
# Stops automatic pagination from looping forever on inconsistent API responses.
|
|
5
|
+
class PaginationGuard
|
|
6
|
+
DEFAULT_MAX_PAGES = 1_000
|
|
7
|
+
|
|
8
|
+
def self.validate_max_pages(max_pages)
|
|
9
|
+
resolved = max_pages.nil? ? DEFAULT_MAX_PAGES : max_pages
|
|
10
|
+
raise ConfigError, "max_pages must be a positive Integer" unless resolved.is_a?(Integer) && resolved.positive?
|
|
11
|
+
|
|
12
|
+
resolved
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def initialize(max_pages, initial_cursor)
|
|
16
|
+
@max_pages = self.class.validate_max_pages(max_pages)
|
|
17
|
+
@pages = 0
|
|
18
|
+
@seen_cursors = {}
|
|
19
|
+
@seen_cursors[initial_cursor] = true if cursor?(initial_cursor)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Returns the cursor for the next page, or nil when there are no more pages.
|
|
23
|
+
def next_cursor(pagination)
|
|
24
|
+
@pages += 1
|
|
25
|
+
pagination = {} unless pagination.is_a?(Hash)
|
|
26
|
+
return nil unless pagination[:has_more]
|
|
27
|
+
|
|
28
|
+
if @pages >= @max_pages
|
|
29
|
+
raise ConnectionError, "Prontuno API pagination exceeded the maximum of #{@max_pages} pages"
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
cursor = pagination[:next_cursor]
|
|
33
|
+
unless cursor?(cursor)
|
|
34
|
+
raise ConnectionError,
|
|
35
|
+
"Prontuno API pagination indicated more results without a next cursor"
|
|
36
|
+
end
|
|
37
|
+
raise ConnectionError, "Prontuno API returned a repeated pagination cursor" if @seen_cursors.key?(cursor)
|
|
38
|
+
|
|
39
|
+
@seen_cursors[cursor] = true
|
|
40
|
+
cursor
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
def cursor?(value)
|
|
46
|
+
value.is_a?(String) && !value.empty?
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Prontuno
|
|
4
|
+
module Resources
|
|
5
|
+
# `client.api_keys`: API keys. Requires a management key with `api_keys:*`.
|
|
6
|
+
class ApiKeys < Base
|
|
7
|
+
# The plaintext `key` is returned only once, so store it securely. Never retried
|
|
8
|
+
# automatically.
|
|
9
|
+
#
|
|
10
|
+
# @example
|
|
11
|
+
# client.api_keys.create(name: "Production sender", type: "sending", domain_id: "dom_...")
|
|
12
|
+
def create(params = {}, **kwargs)
|
|
13
|
+
body, options = split_params(params, kwargs)
|
|
14
|
+
post("api-keys", body, options: options)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# Includes revoked keys.
|
|
18
|
+
def retrieve(api_key_id, **options)
|
|
19
|
+
get("api-keys/#{id("API key", api_key_id)}", options: options)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Permanently revokes the key. Requests using it fail immediately. Returns nil.
|
|
23
|
+
def revoke(api_key_id, **options)
|
|
24
|
+
delete_request("api-keys/#{id("API key", api_key_id)}", options: options)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# @param status [String, nil] "active" (the API's default), "revoked" or "all"
|
|
28
|
+
# @param type [String, nil] "sending", "receiving", "mcp" or "management"
|
|
29
|
+
def list(limit: nil, cursor: nil, status: nil, type: nil, **options)
|
|
30
|
+
get("api-keys", query: { limit: limit, cursor: cursor, status: status, type: type }, options: options)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def list_all(limit: nil, cursor: nil, status: nil, type: nil, max_pages: nil, **options, &block)
|
|
34
|
+
fetch = lambda do |page_cursor|
|
|
35
|
+
list(limit: limit, cursor: page_cursor, status: status, type: type, **options)
|
|
36
|
+
end
|
|
37
|
+
paginate(max_pages, cursor, fetch, &block)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Prontuno
|
|
4
|
+
module Resources
|
|
5
|
+
# Shared behavior for API resources.
|
|
6
|
+
class Base
|
|
7
|
+
def initialize(http)
|
|
8
|
+
@http = http
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def inspect
|
|
12
|
+
"#<#{self.class.name}>"
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
private
|
|
16
|
+
|
|
17
|
+
def get(path, query: nil, options: {})
|
|
18
|
+
@http.request("GET", path, query: query, options: options)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def post(path, body = HttpClient::NO_BODY, options: {}, sending: false, allowed: HttpClient::REQUEST_OPTIONS)
|
|
22
|
+
@http.request("POST", path, body: body, sending: sending, options: options, allowed: allowed)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def patch(path, body, options: {})
|
|
26
|
+
@http.request("PATCH", path, body: body, options: options)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def delete_request(path, options: {})
|
|
30
|
+
@http.request("DELETE", path, options: options)
|
|
31
|
+
nil
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def id(label, value)
|
|
35
|
+
Util.path_id(label, value)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Splits keyword arguments into body fields and request options, and merges the
|
|
39
|
+
# fields into `params`, so both `create(name: "x")` and `create({ name: "x" }, timeout: 5)`
|
|
40
|
+
# work.
|
|
41
|
+
def split_params(params, kwargs)
|
|
42
|
+
raise ArgumentError, "params must be a Hash" unless params.is_a?(Hash)
|
|
43
|
+
|
|
44
|
+
options = kwargs.slice(*HttpClient::REQUEST_OPTIONS)
|
|
45
|
+
[params.merge(kwargs.except(*HttpClient::REQUEST_OPTIONS)), options]
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Yields every item to `each_item`, or returns an Enumerator that fetches pages as it's
|
|
49
|
+
# iterated. `fetch_page` receives the cursor for each page and returns that page.
|
|
50
|
+
def paginate(max_pages, cursor, fetch_page, &each_item)
|
|
51
|
+
PaginationGuard.validate_max_pages(max_pages)
|
|
52
|
+
enumerator = Enumerator.new do |yielder|
|
|
53
|
+
guard = PaginationGuard.new(max_pages, cursor)
|
|
54
|
+
next_cursor = cursor
|
|
55
|
+
loop do
|
|
56
|
+
page = fetch_page.call(next_cursor) || {}
|
|
57
|
+
Array(page[:data]).each { |item| yielder << item }
|
|
58
|
+
next_cursor = guard.next_cursor(page[:pagination])
|
|
59
|
+
break unless next_cursor
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
each_item ? enumerator.each(&each_item) : enumerator
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Prontuno
|
|
4
|
+
module Resources
|
|
5
|
+
# `client.domains`: sending domains.
|
|
6
|
+
class Domains < Base
|
|
7
|
+
# @example
|
|
8
|
+
# client.domains.create(domain: "mg.example.com")
|
|
9
|
+
def create(params = {}, **kwargs)
|
|
10
|
+
body, options = split_params(params, kwargs)
|
|
11
|
+
post("domains", body, options: options)
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def retrieve(domain_id, **options)
|
|
15
|
+
get("domains/#{id("domain", domain_id)}", options: options)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def list(limit: nil, cursor: nil, **options)
|
|
19
|
+
get("domains", query: { limit: limit, cursor: cursor }, options: options)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def list_all(limit: nil, cursor: nil, max_pages: nil, **options, &block)
|
|
23
|
+
fetch = ->(page_cursor) { list(limit: limit, cursor: page_cursor, **options) }
|
|
24
|
+
paginate(max_pages, cursor, fetch, &block)
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Prontuno
|
|
4
|
+
module Resources
|
|
5
|
+
# `client.emails`: send email and read what was sent.
|
|
6
|
+
class Emails < Base
|
|
7
|
+
# @return [SentEmailAttachments]
|
|
8
|
+
attr_reader :attachments
|
|
9
|
+
|
|
10
|
+
def initialize(http)
|
|
11
|
+
super
|
|
12
|
+
@attachments = SentEmailAttachments.new(http)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Sends one email. Uses the sending key.
|
|
16
|
+
#
|
|
17
|
+
# @param email [Hash] `from`, `to`, `subject`, and `text` and/or `html`; optionally `cc`,
|
|
18
|
+
# `bcc`, `reply_to`, `headers` and `attachments`. Symbol or String keys.
|
|
19
|
+
# @param options [Hash] `idempotency_key:`, `timeout:`, `max_retries:`,
|
|
20
|
+
# `max_response_size:`, `headers:`
|
|
21
|
+
# @return [Hash] `{ emails: [...] }`
|
|
22
|
+
def send(email = nil, **options)
|
|
23
|
+
require_email_hash(email, "send")
|
|
24
|
+
post("emails", normalize_email(email), options: options, sending: true,
|
|
25
|
+
allowed: HttpClient::IDEMPOTENT_REQUEST_OPTIONS)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Sends up to 1,000 separate emails in one request. If any item is invalid, nothing is
|
|
29
|
+
# sent. Uses the sending key.
|
|
30
|
+
#
|
|
31
|
+
# @param emails [Array<Hash>]
|
|
32
|
+
# @return [Hash] `{ emails: [[...], ...] }`
|
|
33
|
+
def send_batch(emails = nil, **options)
|
|
34
|
+
require_email_hash({}, "send_batch") if emails.nil?
|
|
35
|
+
raise ArgumentError, "emails must be an Array" unless emails.is_a?(Array)
|
|
36
|
+
|
|
37
|
+
post("emails/batch", { emails: emails.map { |email| normalize_email(email) } },
|
|
38
|
+
options: options, sending: true, allowed: HttpClient::IDEMPOTENT_REQUEST_OPTIONS)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# One email with its status, timestamps, stored text and HTML bodies, and attachments.
|
|
42
|
+
def retrieve(email_id, **options)
|
|
43
|
+
get("emails/#{id("email", email_id)}", options: options)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# One page of sent emails.
|
|
47
|
+
# @return [Hash] `{ data: [...], pagination: { limit:, has_more:, next_cursor: } }`
|
|
48
|
+
def list(limit: nil, cursor: nil, domain_id: nil, status: nil, **options)
|
|
49
|
+
get("emails", query: { limit: limit, cursor: cursor, domain_id: domain_id, status: status },
|
|
50
|
+
options: options)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Every sent email matching the filters, fetching pages as needed. Yields each email,
|
|
54
|
+
# or returns an Enumerator without a block.
|
|
55
|
+
def list_all(limit: nil, cursor: nil, domain_id: nil, status: nil, max_pages: nil, **options, &block)
|
|
56
|
+
fetch = lambda do |page_cursor|
|
|
57
|
+
list(limit: limit, cursor: page_cursor, domain_id: domain_id, status: status, **options)
|
|
58
|
+
end
|
|
59
|
+
paginate(max_pages, cursor, fetch, &block)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
private
|
|
63
|
+
|
|
64
|
+
# Without braces, Ruby passes `send(from: ..., to: ...)` as keyword arguments, which
|
|
65
|
+
# are request options here (and `headers` is both an email field and an option).
|
|
66
|
+
def require_email_hash(email, method)
|
|
67
|
+
return unless email.nil?
|
|
68
|
+
|
|
69
|
+
raise ArgumentError,
|
|
70
|
+
"Pass the email as a Hash in braces, then any request options: " \
|
|
71
|
+
"emails.#{method}({ from: ..., to: ... }, idempotency_key: ...)"
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def normalize_email(email)
|
|
75
|
+
raise ArgumentError, "email must be a Hash" unless email.is_a?(Hash)
|
|
76
|
+
|
|
77
|
+
normalized = email.transform_keys(&:to_s)
|
|
78
|
+
attachments = normalized["attachments"]
|
|
79
|
+
return normalized if attachments.nil?
|
|
80
|
+
raise ArgumentError, "attachments must be an Array" unless attachments.is_a?(Array)
|
|
81
|
+
|
|
82
|
+
normalized.merge("attachments" => attachments.map { |attachment| normalize_attachment(attachment) })
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# Binary Strings and IO objects are base64-encoded. Other Strings are sent as they are,
|
|
86
|
+
# and the API reads them as base64 unless `encoding` says otherwise.
|
|
87
|
+
def normalize_attachment(attachment)
|
|
88
|
+
raise ArgumentError, "each attachment must be a Hash" unless attachment.is_a?(Hash)
|
|
89
|
+
|
|
90
|
+
normalized = attachment.transform_keys(&:to_s)
|
|
91
|
+
content = normalized["content"]
|
|
92
|
+
bytes = if content.respond_to?(:read)
|
|
93
|
+
content.read.to_s.b
|
|
94
|
+
elsif content.is_a?(String) && content.encoding == Encoding::BINARY
|
|
95
|
+
content
|
|
96
|
+
end
|
|
97
|
+
return normalized if bytes.nil?
|
|
98
|
+
|
|
99
|
+
normalized.merge("content" => [bytes].pack("m0"), "encoding" => "base64")
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Prontuno
|
|
4
|
+
module Resources
|
|
5
|
+
# `client.emails.attachments`: files attached to sent emails.
|
|
6
|
+
class SentEmailAttachments < Base
|
|
7
|
+
# One page of a sent email's attachments, each with a fresh one-hour `download_url`
|
|
8
|
+
# (nil while the file hasn't finished uploading).
|
|
9
|
+
def list(email_id, limit: nil, cursor: nil, **options)
|
|
10
|
+
get("emails/#{id("email", email_id)}/attachments", query: { limit: limit, cursor: cursor }, options: options)
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# Every attachment on a sent email, fetching pages as needed.
|
|
14
|
+
def list_all(email_id, limit: nil, cursor: nil, max_pages: nil, **options, &block)
|
|
15
|
+
id("email", email_id)
|
|
16
|
+
fetch = ->(page_cursor) { list(email_id, limit: limit, cursor: page_cursor, **options) }
|
|
17
|
+
paginate(max_pages, cursor, fetch, &block)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Attachment metadata with a fresh signed `download_url` that expires after one hour.
|
|
21
|
+
# Raises a 403 `attachment_unavailable` ApiError while the file hasn't finished uploading.
|
|
22
|
+
def retrieve(email_id, attachment_id, **options)
|
|
23
|
+
get("emails/#{id("email", email_id)}/attachments/#{id("attachment", attachment_id)}", options: options)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|