ampost 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.
@@ -0,0 +1,162 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module Ampost
7
+ # Base class of every error the SDK raises.
8
+ class Error < StandardError; end
9
+
10
+ # The API answered with an error status.
11
+ #
12
+ # The body is `{"error": {"code", "message", "details"}}`: `code` is stable (for example
13
+ # `VALIDATION_FAILED`, `POST_NOT_FOUND`); the full list is at https://ampost.io/docs?ref=github#errors.
14
+ # `message` is `"<status> <code>: <api_message>"`.
15
+ class APIError < Error
16
+ # @return [Integer] the HTTP status
17
+ attr_reader :status
18
+ # @return [String] the stable error code, or `HTTP_<status>` when the body has none
19
+ attr_reader :code
20
+ # @return [String] the API's message
21
+ attr_reader :api_message
22
+ # @return [Hash, nil] more about the error, for example `"issues"` for a 400
23
+ attr_reader :details
24
+ # @return [Hash{String => String}] the response headers, with lowercase names
25
+ attr_reader :headers
26
+ # @return [String, nil] `X-Request-Id`: quote it when you contact support
27
+ attr_reader :request_id
28
+
29
+ def initialize(status, code, api_message, details, headers)
30
+ super("#{status} #{code}: #{api_message}")
31
+ @status = status
32
+ @code = code
33
+ @api_message = api_message
34
+ @details = details
35
+ @headers = headers.to_h.transform_keys { |name| name.to_s.downcase }
36
+ @request_id = @headers["x-request-id"]
37
+ end
38
+
39
+ # Builds the subclass for the status from a response.
40
+ #
41
+ # @param response [Ampost::Transport::Response]
42
+ # @return [APIError]
43
+ def self.from_response(response)
44
+ code, api_message, details = parse_body(response)
45
+ Ampost.error_class(response.status).new(response.status, code, api_message, details, response.headers)
46
+ end
47
+
48
+ def self.parse_body(response)
49
+ fallback_code = "HTTP_#{response.status}"
50
+ fallback_message = "Request failed"
51
+ text = response.body.to_s
52
+ begin
53
+ body = JSON.parse(text)
54
+ rescue JSON::ParserError
55
+ text = text.strip
56
+ return [fallback_code, text.empty? ? fallback_message : text[0, 500], nil]
57
+ end
58
+ return [fallback_code, fallback_message, nil] unless body.is_a?(Hash) && body.key?("error")
59
+
60
+ error = body["error"]
61
+ # A few edge routes answer {"error": "message"}.
62
+ return [fallback_code, error, nil] if error.is_a?(String)
63
+ return [fallback_code, fallback_message, nil] unless error.is_a?(Hash)
64
+
65
+ [
66
+ error["code"].is_a?(String) ? error["code"] : fallback_code,
67
+ error["message"].is_a?(String) ? error["message"] : fallback_message,
68
+ error["details"].is_a?(Hash) ? error["details"] : nil
69
+ ]
70
+ end
71
+ private_class_method :parse_body
72
+ end
73
+
74
+ # 400: the request is invalid (`VALIDATION_FAILED`, `CONTENT_TOO_LONG`, ...). `details["issues"]` lists the problems.
75
+ class BadRequestError < APIError; end
76
+
77
+ # 401: the API key is missing, wrong or revoked.
78
+ class AuthenticationError < APIError; end
79
+
80
+ # 403: the key lacks a scope, the plan lacks a feature, or the account is suspended.
81
+ class PermissionDeniedError < APIError; end
82
+
83
+ # 404: no such resource belongs to you.
84
+ class NotFoundError < APIError; end
85
+
86
+ # 409: the resource's state does not allow it, or an idempotency key was reused.
87
+ class ConflictError < APIError; end
88
+
89
+ # 413: the request body is too large; upload files with `client.media.upload`.
90
+ class PayloadTooLargeError < APIError; end
91
+
92
+ # 422: the request is well formed but cannot be done (for example analytics on Discord).
93
+ class UnprocessableEntityError < APIError; end
94
+
95
+ # 429: `RATE_LIMITED` or `QUOTA_EXCEEDED`. Retried automatically when `Retry-After` is short.
96
+ class RateLimitError < APIError
97
+ # @return [Float, nil] seconds the API asked to wait (`Retry-After`)
98
+ def retry_after
99
+ Ampost.parse_retry_after(headers["retry-after"])
100
+ end
101
+ end
102
+
103
+ # 5xx: something failed on Ampost's side or at a platform.
104
+ class InternalServerError < APIError; end
105
+
106
+ # No response: DNS, TCP, TLS or a reset connection.
107
+ class APIConnectionError < Error; end
108
+
109
+ # No response within `timeout`.
110
+ class APITimeoutError < APIConnectionError; end
111
+
112
+ # `media.upload` did not end with a usable file.
113
+ #
114
+ # `reason`: `upload_rejected` (storage refused the PUT), `failed` or `expired` (the upload's status),
115
+ # or `timeout` (still processing).
116
+ class MediaUploadError < Error
117
+ # @return [String]
118
+ attr_reader :reason
119
+ # @return [String]
120
+ attr_reader :upload_id
121
+
122
+ def initialize(message, reason, upload_id)
123
+ super(message)
124
+ @reason = reason
125
+ @upload_id = upload_id
126
+ end
127
+ end
128
+
129
+ STATUS_ERRORS = {
130
+ 400 => BadRequestError,
131
+ 401 => AuthenticationError,
132
+ 403 => PermissionDeniedError,
133
+ 404 => NotFoundError,
134
+ 409 => ConflictError,
135
+ 413 => PayloadTooLargeError,
136
+ 422 => UnprocessableEntityError,
137
+ 429 => RateLimitError
138
+ }.freeze
139
+ private_constant :STATUS_ERRORS
140
+
141
+ # @return [Class] the APIError subclass for an HTTP status
142
+ def self.error_class(status)
143
+ return InternalServerError if status >= 500
144
+
145
+ STATUS_ERRORS.fetch(status, APIError)
146
+ end
147
+
148
+ # `Retry-After` in seconds: delta-seconds or an HTTP date.
149
+ #
150
+ # @param value [String, nil]
151
+ # @return [Float, nil]
152
+ def self.parse_retry_after(value)
153
+ return nil if value.nil? || value.strip.empty?
154
+
155
+ value = value.strip
156
+ return [Float(value), 0.0].max if value.match?(/\A\d+(\.\d+)?\z/)
157
+
158
+ [Time.httpdate(value) - Time.now, 0.0].max
159
+ rescue ArgumentError
160
+ nil
161
+ end
162
+ end