postwire 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,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Postwire
4
+ # Module responsible for wrapping email sending API
5
+ module Emails
6
+ class << self
7
+ # Sends an email.
8
+ #
9
+ # @param params [Hash] Email parameters
10
+ # @option params [String] :from The sender email address (required)
11
+ # @option params [Array<String>, String] :to The recipient email address(es) (required)
12
+ # @option params [String] :subject The email subject
13
+ # @option params [String] :html The HTML content of the email
14
+ # @option params [String] :text The plain text content of the email
15
+ # @option params [String] :tag A tag to categorise the email, e.g. "password_reset"
16
+ # @option params [Hash] :metadata Up to 50 key/value pairs of your own, e.g.
17
+ # { customer_id: "cus_123" }. Returned when you fetch the email and included
18
+ # in webhook payloads.
19
+ #
20
+ # @return [Postwire::Response] The response containing the email ID
21
+ def send(params, options: {})
22
+ raise ArgumentError, ":from is required" unless params[:from] || params["from"]
23
+ raise ArgumentError, ":to is required" unless params[:to] || params["to"]
24
+
25
+ path = "emails"
26
+ Postwire::Request.new(path, params, "post", options: options).perform
27
+ end
28
+
29
+ # Retrieve a single email.
30
+ #
31
+ # @param email_id [String] The email ID (required)
32
+ #
33
+ # @return [Postwire::Response] The email object
34
+ def get(email_id)
35
+ raise ArgumentError, "email_id is required" if email_id.nil? || email_id.to_s.empty?
36
+
37
+ path = "emails/#{email_id}"
38
+ Postwire::Request.new(path, {}, "get").perform
39
+ end
40
+
41
+ # List emails with optional pagination.
42
+ #
43
+ # @param options [Hash] Optional parameters for pagination
44
+ # @option options [Integer] :limit Maximum number of emails to return (1-100, default 20)
45
+ # @option options [String] :after Cursor for pagination (newer emails)
46
+ # @option options [String] :before Cursor for pagination (older emails)
47
+ #
48
+ # @return [Postwire::Response] Paginated list of emails
49
+ def list(options = {})
50
+ path = "emails"
51
+
52
+ # Build query parameters, filtering out nil values
53
+ query_params = {}
54
+ query_params[:limit] = options[:limit] if options[:limit]
55
+ query_params[:after] = options[:after] if options[:after]
56
+ query_params[:before] = options[:before] if options[:before]
57
+
58
+ Postwire::Request.new(path, query_params, "get").perform
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Postwire
4
+ # Errors wrapper class
5
+ class Error < StandardError
6
+ # 4xx HTTP status code
7
+ ClientError = Class.new(self)
8
+
9
+ # 5xx HTTP status code
10
+ ServerError = Class.new(self)
11
+
12
+ # code 500
13
+ InternalServerError = Class.new(ServerError)
14
+
15
+ # code 400, 401, 404, 422 - these are client errors (4xx)
16
+ InvalidRequestError = Class.new(ClientError)
17
+
18
+ # code 404
19
+ NotFoundError = Class.new(ClientError)
20
+
21
+ # code 429
22
+ class RateLimitExceededError < ClientError
23
+ attr_reader :rate_limit_limit, :rate_limit_remaining, :rate_limit_reset, :retry_after
24
+
25
+ def initialize(msg, code = nil, headers = {})
26
+ super(msg, code, headers)
27
+ @rate_limit_limit = headers["ratelimit-limit"]&.to_i
28
+ @rate_limit_remaining = headers["ratelimit-remaining"]&.to_i
29
+ @rate_limit_reset = headers["ratelimit-reset"]&.to_i
30
+ @retry_after = headers["retry-after"]&.to_i
31
+ end
32
+ end
33
+
34
+ ERRORS = {
35
+ 400 => Postwire::Error::InvalidRequestError,
36
+ 401 => Postwire::Error::InvalidRequestError,
37
+ 404 => Postwire::Error::NotFoundError,
38
+ 422 => Postwire::Error::InvalidRequestError,
39
+ 429 => Postwire::Error::RateLimitExceededError,
40
+ 500 => Postwire::Error::InternalServerError
41
+ }.freeze
42
+
43
+ attr_reader :code, :headers
44
+
45
+ def initialize(msg, code = nil, headers = {})
46
+ super(msg)
47
+ @code = code
48
+ @headers = headers
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,278 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "postwire"
5
+
6
+ module Postwire
7
+ # Mailer class used by railtie
8
+ class Mailer
9
+ attr_accessor :config, :settings
10
+
11
+ # These are set as `headers` by the Rails API, but these will be filtered out
12
+ # when constructing the Postwire API payload, since they're are sent as post params.
13
+ IGNORED_HEADERS = %w[
14
+ cc bcc
15
+ from reply-to to subject mime-version
16
+ html text
17
+ content-type tag metadata scheduled_at
18
+ headers options
19
+ ].freeze
20
+
21
+ SUPPORTED_OPTIONS = %w[idempotency_key].freeze
22
+
23
+ def initialize(config)
24
+ @config = config
25
+ @settings = config.is_a?(Hash) ? config : {}
26
+
27
+ # Check for API key in settings first, then fall back to global config
28
+ raise Postwire::Error.new("Make sure your API Key is set", @config) unless api_key
29
+ end
30
+
31
+ # Returns the API key from settings or global config
32
+ def api_key
33
+ @settings[:api_key] || Postwire.api_key
34
+ end
35
+
36
+ # Returns the base URL from settings or global config
37
+ def base_url
38
+ @settings[:host] || @settings[:base_url] || Postwire.base_url
39
+ end
40
+
41
+ #
42
+ # Overwritten deliver! method
43
+ #
44
+ # @param Mail mail
45
+ #
46
+ # @return Object Postwire response
47
+ #
48
+ def deliver!(mail)
49
+ params = build_params(mail)
50
+ options = get_options(mail) if mail[:options].present?
51
+ options ||= {}
52
+
53
+ # Pass api_key and base_url from settings to the request
54
+ options[:api_key] = api_key
55
+ options[:base_url] = base_url
56
+
57
+ resp = Postwire::Emails.send(params, options: options)
58
+ mail.message_id = resp[:id] if resp[:error].nil?
59
+ resp
60
+ end
61
+
62
+ #
63
+ # Builds the payload for sending
64
+ #
65
+ # @param Mail mail rails mail object
66
+ #
67
+ # @return Hash hash with all Postwire params
68
+ #
69
+ def build_params(mail)
70
+ params = {
71
+ from: get_from(mail),
72
+ to: mail.to,
73
+ subject: mail.subject
74
+ }
75
+ params.merge!(get_addons(mail))
76
+ params.merge!(get_headers(mail))
77
+ params.merge!(get_tag(mail))
78
+ params.merge!(get_metadata(mail))
79
+ params[:attachments] = get_attachments(mail) if mail.attachments.present?
80
+ params.merge!(get_contents(mail))
81
+ params
82
+ end
83
+
84
+ #
85
+ # Add custom headers fields.
86
+ #
87
+ # Both ways are supported:
88
+ #
89
+ # 1. Through the `#mail()` method ie:
90
+ # mail(headers: { "X-Custom-Header" => "value" })
91
+ #
92
+ # 2. Through the Rails `#headers` method ie:
93
+ # headers["X-Custom-Header"] = "value"
94
+ #
95
+ #
96
+ # setting the header values through the `#mail` method will overwrite values set
97
+ # through the `#headers` method using the same key.
98
+ #
99
+ # @param Mail mail Rails Mail object
100
+ #
101
+ # @return Hash hash with headers param
102
+ #
103
+ def get_headers(mail)
104
+ params = {}
105
+
106
+ if mail[:headers].present? || unignored_headers(mail).present?
107
+ params[:headers] = {}
108
+ params[:headers].merge!(headers_values(mail)) if unignored_headers(mail).present?
109
+ params[:headers].merge!(mail_headers_values(mail)) if mail[:headers].present?
110
+ end
111
+
112
+ params
113
+ end
114
+
115
+ #
116
+ # Adds additional options fields.
117
+ # Currently supports only :idempotency_key
118
+ #
119
+ # @param Mail mail Rails Mail object
120
+ # @return Hash hash with headers param
121
+ #
122
+ def get_options(mail)
123
+ opts = {}
124
+ if mail[:options].present?
125
+ opts.merge!(mail[:options].unparsed_value)
126
+ opts.delete_if { |k, _v| !SUPPORTED_OPTIONS.include?(k.to_s) }
127
+ end
128
+ opts
129
+ end
130
+
131
+ # Remove nils from header values
132
+ def cleanup_headers(headers)
133
+ headers.delete_if { |_k, v| v.nil? }
134
+ end
135
+
136
+ # Gets the values of the headers that are set through the `#mail` method
137
+ #
138
+ # @param Mail mail Rails Mail object
139
+ # @return Hash hash with mail headers values
140
+ def mail_headers_values(mail)
141
+ params = {}
142
+ mail[:headers].unparsed_value.each do |k, v|
143
+ params[k.to_s] = v
144
+ end
145
+ cleanup_headers(params)
146
+ params
147
+ end
148
+
149
+ # Gets the values of the headers that are set through the `#headers` method
150
+ #
151
+ # @param Mail mail Rails Mail object
152
+ # @return Hash hash with headers values
153
+ def headers_values(mail)
154
+ params = {}
155
+ unignored_headers(mail).each do |h|
156
+ params[h.name.to_s] = h.unparsed_value
157
+ end
158
+ cleanup_headers(params)
159
+ params
160
+ end
161
+
162
+ #
163
+ # Add tag field
164
+ #
165
+ # @param Mail mail Rails Mail object
166
+ #
167
+ # @return Hash hash with tag param
168
+ #
169
+ def get_tag(mail)
170
+ params = {}
171
+ params[:tag] = mail[:tag].unparsed_value if mail[:tag].present?
172
+ params
173
+ end
174
+
175
+ #
176
+ # Add metadata field, set through the `#mail` method ie:
177
+ # mail(metadata: { customer_id: "cus_123" })
178
+ #
179
+ # @param Mail mail Rails Mail object
180
+ #
181
+ # @return Hash hash with metadata param
182
+ #
183
+ def get_metadata(mail)
184
+ params = {}
185
+ params[:metadata] = mail[:metadata].unparsed_value if mail[:metadata].present?
186
+ params
187
+ end
188
+
189
+ #
190
+ # Add cc, bcc, reply_to fields
191
+ #
192
+ # @param Mail mail Rails Mail Object
193
+ #
194
+ # @return Hash hash containing cc/bcc/reply_to attrs
195
+ #
196
+ def get_addons(mail)
197
+ params = {}
198
+ params[:cc] = mail.cc if mail.cc.present?
199
+ params[:bcc] = mail.bcc if mail.bcc.present?
200
+ params[:reply_to] = mail.reply_to if mail.reply_to.present?
201
+ params
202
+ end
203
+
204
+ #
205
+ # Gets the body of the email
206
+ #
207
+ # @param Mail mail Rails Mail Object
208
+ #
209
+ # @return Hash hash containing html/text or both attrs
210
+ #
211
+ def get_contents(mail)
212
+ params = {}
213
+ case mail.mime_type
214
+ when "text/plain"
215
+ params[:text] = mail.body.decoded
216
+ when "text/html"
217
+ params[:html] = mail.body.decoded
218
+ when "multipart/alternative", "multipart/mixed", "multipart/related"
219
+ params[:text] = mail.text_part.decoded if mail.text_part
220
+ params[:html] = mail.html_part.decoded if mail.html_part
221
+ end
222
+ params
223
+ end
224
+
225
+ #
226
+ # Properly gets the `from` attr
227
+ #
228
+ # @param Mail input object
229
+ #
230
+ # @return String `from` string
231
+ #
232
+ def get_from(input)
233
+ return input.from.first if input[:from].nil?
234
+
235
+ from = input[:from].formatted
236
+ return from.first if from.is_a? Array
237
+
238
+ from.to_s
239
+ end
240
+
241
+ #
242
+ # Handle attachments when present
243
+ # Uses base64 encoding for better API compatibility
244
+ #
245
+ # @return Array attachments array
246
+ #
247
+ def get_attachments(mail)
248
+ attachments = []
249
+ mail.attachments.each do |part|
250
+ # Get decoded content and ensure binary encoding for consistent base64 output
251
+ content = part.body.decoded.dup
252
+ content = content.force_encoding(Encoding::BINARY)
253
+
254
+ attachment = {
255
+ filename: part.filename,
256
+ content: Base64.strict_encode64(content),
257
+ content_type: part.content_type
258
+ }
259
+
260
+ # Rails uses the auto generated cid for inline attachments
261
+ attachment[:content_id] = part.cid if part.inline?
262
+ attachments.append(attachment)
263
+ end
264
+ attachments
265
+ end
266
+
267
+ #
268
+ # Get all headers that are not ignored
269
+ #
270
+ # @param Mail mail
271
+ #
272
+ # @return Array headers
273
+ #
274
+ def unignored_headers(mail)
275
+ @unignored_headers ||= mail.header_fields.reject { |h| IGNORED_HEADERS.include?(h.name.downcase) }
276
+ end
277
+ end
278
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Postwire
4
+ # Helper class for building paginated query strings
5
+ class PaginationHelper
6
+ class << self
7
+ # Builds a paginated path with query parameters
8
+ #
9
+ # @param base_path [String] the base API path
10
+ # @param query_params [Hash] optional pagination parameters
11
+ # @option query_params [Integer] :limit Number of items to retrieve (max 100)
12
+ # @option query_params [String] :after ID after which to retrieve more items
13
+ # @option query_params [String] :before ID before which to retrieve more items
14
+ # @return [String] the path with query parameters
15
+ def build_paginated_path(base_path, query_params = nil)
16
+ return base_path if query_params.nil? || query_params.empty?
17
+
18
+ # Filter out nil values and convert to string keys
19
+ filtered_params = query_params.compact.transform_keys(&:to_s)
20
+
21
+ # Build query string
22
+ query_string = filtered_params.map { |k, v| "#{k}=#{URI.encode_www_form_component(v.to_s)}" }.join("&")
23
+
24
+ return base_path if query_string.empty?
25
+
26
+ "#{base_path}?#{query_string}"
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "postwire"
4
+ require "postwire/mailer"
5
+
6
+ module Postwire
7
+ # Main railtime class
8
+ class Railtie < ::Rails::Railtie
9
+ ActiveSupport.on_load(:action_mailer) do
10
+ add_delivery_method :postwire, Postwire::Mailer
11
+ ActiveSupport.run_load_hooks(:postwire_mailer, Postwire::Mailer)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Postwire
4
+ # This class is responsible for making the appropriate HTTP calls
5
+ # and raising the specific errors based on the response.
6
+ class Request
7
+ attr_accessor :body, :verb, :options
8
+
9
+ def initialize(path = "", body = {}, verb = "POST", options: {})
10
+ # Allow api_key override via options, fall back to global config
11
+ api_key = options[:api_key] || Postwire.api_key
12
+ raise ArgumentError, "API key is required. Set via Postwire.api_key= or pass :api_key in options" if api_key.nil?
13
+
14
+ api_key = api_key.call if api_key.is_a?(Proc)
15
+
16
+ # Allow base_url override via options, fall back to global config
17
+ @base_url = options[:base_url] || Postwire.base_url
18
+
19
+ @path = path
20
+ @body = body
21
+ @verb = verb
22
+ @options = options
23
+ @headers = {
24
+ "Content-Type" => "application/json",
25
+ "Accept" => "application/json",
26
+ "User-Agent" => "Postwire:v#{Postwire::VERSION}",
27
+ "Authorization" => "Bearer #{api_key}"
28
+ }
29
+
30
+ set_idempotency_key
31
+ end
32
+
33
+ # Performs the HTTP call
34
+ def perform
35
+ resp = connection.run_request(@verb.downcase.to_sym, request_url, request_body, @headers)
36
+
37
+ data = parse_body(resp)
38
+ headers = extract_headers(resp)
39
+
40
+ handle_error!(data, resp) if error_response?(resp, data)
41
+
42
+ Postwire::Response.new(data, headers)
43
+ end
44
+
45
+ def handle_error!(data, resp = nil)
46
+ code = data[:statusCode] || response_status(resp)
47
+ body = data[:message]
48
+ headers = resp.nil? ? (data[:headers] || {}) : extract_headers(resp)
49
+
50
+ # get error from the known list of errors
51
+ error_class = Postwire::Error::ERRORS[code] || Postwire::Error
52
+ raise error_class.new(body, code, headers)
53
+ end
54
+
55
+ private
56
+
57
+ # The Faraday connection used to perform the request.
58
+ def connection
59
+ @connection ||= Faraday.new(request: { timeout: request_timeout })
60
+ end
61
+
62
+ # Joins the base URL and path without letting a base path segment
63
+ # (such as the `/api` prefix) be discarded, which URI.join would do.
64
+ # Query parameters for GET requests are appended here.
65
+ def request_url
66
+ url = "#{@base_url.chomp("/")}/#{@path.delete_prefix("/")}"
67
+ return url unless get_request_with_query?
68
+
69
+ separator = url.include?("?") ? "&" : "?"
70
+ "#{url}#{separator}#{URI.encode_www_form(@body)}"
71
+ end
72
+
73
+ # The serialized request body, or nil when there is nothing to send.
74
+ def request_body
75
+ return nil if get_request_with_query? || @body.nil? || @body.empty?
76
+
77
+ @body.to_json
78
+ end
79
+
80
+ # Timeout from options, global config, or default
81
+ def request_timeout
82
+ @options[:timeout] || Postwire.timeout || Postwire::DEFAULT_TIMEOUT
83
+ end
84
+
85
+ def get_request_with_query?
86
+ @verb.downcase == "get" && !@body.nil? && !@body.empty?
87
+ end
88
+
89
+ # Parses the response body into a symbol-keyed hash.
90
+ def parse_body(resp)
91
+ body = resp.respond_to?(:body) ? resp.body : resp
92
+ return {} if body.nil?
93
+ # Already-parsed bodies (middleware or test doubles) are used as-is
94
+ return symbolize(body) if body.is_a?(Hash) || body.is_a?(Array)
95
+ return {} if body.to_s.strip.empty?
96
+
97
+ symbolize(JSON.parse(body))
98
+ rescue JSON::ParserError, TypeError
99
+ raise Postwire::Error::InternalServerError.new("Postwire API returned an unexpected response", nil)
100
+ end
101
+
102
+ def symbolize(data)
103
+ data.is_a?(Hash) ? data.transform_keys(&:to_sym) : data
104
+ end
105
+
106
+ # An error is signalled either by the HTTP status or by a statusCode
107
+ # carried in the response body.
108
+ def error_response?(resp, data)
109
+ status = response_status(resp)
110
+ return true if status && status >= 400
111
+ return false unless data.is_a?(Hash)
112
+
113
+ code = data[:statusCode]
114
+ !code.nil? && code != 200 && code != 201
115
+ end
116
+
117
+ def response_status(resp)
118
+ resp.respond_to?(:status) ? resp.status : nil
119
+ end
120
+
121
+ def set_idempotency_key
122
+ # Only set idempotency key if the verb is POST for now.
123
+ #
124
+ # Does not set it if the idempotency_key is nil or empty
125
+ if @verb.downcase == "post" && !@options[:idempotency_key].nil? && !@options[:idempotency_key].empty?
126
+ @headers["Idempotency-Key"] = @options[:idempotency_key]
127
+ end
128
+ end
129
+
130
+ # Extract and normalize headers from the response
131
+ def extract_headers(resp)
132
+ return {} unless resp.respond_to?(:headers)
133
+
134
+ resp.headers.to_h.transform_keys { |k| k.to_s.downcase }
135
+ end
136
+ end
137
+ end