mailset 0.7.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,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # One recipient's line in the delivery log: a message to three people has
5
+ # three. Addresses and outcomes only, never a subject or anything from the
6
+ # body.
7
+ class DeliveryLine < Model
8
+ # @!attribute [r] id
9
+ # The line's id.
10
+ # @return [String]
11
+ field :id, 'id', :string, required: true
12
+
13
+ # @!attribute [r] at
14
+ # When it happened, in ms since the epoch.
15
+ # @return [Integer]
16
+ field :at, 'at', :integer, required: true
17
+
18
+ # @!attribute [r] sender
19
+ # The mailbox it left from, whichever of its addresses was in From. For
20
+ # a domain key's mail, the From address.
21
+ # @return [String, nil]
22
+ field :sender, 'sender', [:nullable, :string], required: true
23
+
24
+ # @!attribute [r] recipient
25
+ # The address it went to.
26
+ # @return [String]
27
+ field :recipient, 'recipient', :string, required: true
28
+
29
+ # @!attribute [r] status
30
+ # What became of it: one of {Mailset::DeliveryStatus::VALUES}. `sent`:
31
+ # Mailset handed it on. `delivered`: the recipient's server took it.
32
+ # `delayed`: that server asked to try later, and it will be. `bounced`:
33
+ # it came back. `complained`: the recipient marked it as spam.
34
+ # `rejected`: it was refused before it left. `expired`: its
35
+ # `deliver_by` came while it waited. `skipped`: Mailset left the address
36
+ # out on purpose (see {Sent#skipped}).
37
+ # @return [String]
38
+ field :status, 'status', :DeliveryStatus, required: true
39
+
40
+ # @!attribute [r] reason
41
+ # Why, in words for people, when the status needs saying why.
42
+ # @return [String, nil]
43
+ field :reason, 'reason', [:nullable, :string], required: true
44
+
45
+ # @!attribute [r] message
46
+ # The send this line is about: the `id` its receipt answered.
47
+ # @return [String, nil]
48
+ field :message, 'message', :string
49
+
50
+ # @!attribute [r] message_id
51
+ # Its Message-ID header, without the angle brackets: `message_id` from
52
+ # `send_email`.
53
+ # @return [String, nil]
54
+ field :message_id, 'messageId', :string
55
+
56
+ # @!attribute [r] client
57
+ # Which client sent it, from the `Mailset-Client` header its request
58
+ # carried: `name` is one of Mailset's SDKs by its language, `cli`,
59
+ # `web`, `ios` or `other`, and `version` its version. Nil when its
60
+ # request named none.
61
+ # @return [Mailset::DeliveryClient, nil]
62
+ field :client, 'client', [:nullable, :DeliveryClient], required: true, default: nil
63
+ end
64
+
65
+ # One page of the delivery log, newest first: what `mailset.delivery.search` answers.
66
+ class DeliveryPage < Model
67
+ # @!attribute [r] lines
68
+ # @return [Array<Mailset::DeliveryLine>]
69
+ field :lines, 'lines', [:array, :DeliveryLine], required: true
70
+
71
+ # @!attribute [r] next
72
+ # Pass it back as `cursor:` for the next page. Nil on the last one.
73
+ # @return [String, nil]
74
+ field :next, 'next', [:nullable, :string], required: true
75
+ end
76
+
77
+ module Resources
78
+ # `mailset.delivery`: the delivery log of this client's key.
79
+ class Delivery < Base
80
+ # Finds what became of the mail this key sent, one line per recipient,
81
+ # newest first (`delivery.search`). A key sees only what left the
82
+ # mailbox it sends as, or for a domain key the addresses it sends as,
83
+ # so a search by `recipient:` answers "did Ana get her receipt?" and
84
+ # nothing about anyone else's mail. It needs a key
85
+ # that can send. For each change as it happens, use the hook instead: see
86
+ # {Mailset::Webhooks}.
87
+ #
88
+ # page = mailset.delivery.search(recipient: 'ana@example.org', since: Date.today - 1)
89
+ # page.lines.each { |line| puts "#{line.status} #{line.reason}" }
90
+ # older = mailset.delivery.search(recipient: 'ana@example.org', cursor: page.next) if page.next
91
+ #
92
+ # @param id [String, nil] only the lines of one send: the `id` its receipt answered.
93
+ # @param message_id [String, nil] only the lines of the message with this
94
+ # Message-ID, the `message_id` its receipt answered.
95
+ # @param recipient [String, nil] a recipient's whole address, or part of
96
+ # one, such as `@example.org`.
97
+ # @param sender [String, nil] one of the addresses this key sends as, or part of one.
98
+ # @param status [String, nil] only lines with this status: one of
99
+ # {Mailset::DeliveryStatus::VALUES}.
100
+ # @param since [Time, Date, Integer, String, nil] from this moment on: a
101
+ # Time, ms since the epoch, or a day (a Date, or `'2026-11-30'`), which
102
+ # counts from its start in UTC.
103
+ # @param until [Time, Date, Integer, String, nil] up to this moment,
104
+ # written like `since`. A day counts to its end in UTC.
105
+ # @param limit [Integer, nil] how many lines a page holds, 1 to 200. 50 unless told.
106
+ # @param cursor [String, nil] the `next` of the page before, for the page after it.
107
+ # @param request_options [Hash] `org:`, `approval:`, `timeout:` for this call.
108
+ # @return [Mailset::DeliveryPage]
109
+ # @raise [Mailset::Error] when the key is refused or Mailset can't be reached.
110
+ def search(id: nil, message_id: nil, recipient: nil, sender: nil, status: nil, since: nil, until: nil,
111
+ limit: nil, cursor: nil, request_options: {})
112
+ input = {
113
+ 'id' => id, 'messageId' => message_id,
114
+ 'recipient' => recipient, 'sender' => sender, 'status' => status&.to_s,
115
+ 'since' => moment(since, 'since'), 'until' => moment(binding.local_variable_get(:until), 'until'),
116
+ 'limit' => limit, 'cursor' => cursor
117
+ }.compact
118
+ data = transport.command('delivery.search', input, **call_options(request_options))
119
+ page_of(data)
120
+ end
121
+
122
+ private
123
+
124
+ # A moment as Mailset takes it: ms for a Time, a day for a Date, anything else as written.
125
+ def moment(value, what)
126
+ return nil if value.nil?
127
+ return value if value.is_a?(Integer) || value.is_a?(String)
128
+ return Types.ms(value) if Types.time?(value)
129
+ return value.iso8601 if value.is_a?(::Date)
130
+
131
+ raise InvalidRequestError, "#{what} takes a Time, a Date, ms since the epoch, or a day like 2026-11-30."
132
+ end
133
+
134
+ def page_of(data)
135
+ events = data.is_a?(Hash) ? data['events'] : nil
136
+ raise unreachable unless events.is_a?(Array)
137
+
138
+ lines = events.map { |event| line_of(event) }
139
+ raise unreachable if lines.any?(&:nil?)
140
+
141
+ DeliveryPage.new(lines: lines, next: data['next'].is_a?(String) ? data['next'] : nil)
142
+ end
143
+
144
+ def line_of(value)
145
+ return nil unless value.is_a?(Hash) && value['id'].is_a?(String) && value['at'].is_a?(Integer) &&
146
+ value['recipient'].is_a?(String) && value['status'].is_a?(String)
147
+
148
+ # A status this version doesn't know still shows, as Mailset names it.
149
+ DeliveryLine.new(
150
+ id: value['id'], at: value['at'], recipient: value['recipient'], status: value['status'],
151
+ sender: text_of(value['sender']), reason: text_of(value['reason']),
152
+ message: text_of(value['message']), message_id: text_of(value['messageId']),
153
+ client: client_of(value['client'])
154
+ )
155
+ end
156
+
157
+ # A line's client, or nil for none, or for one that doesn't read.
158
+ def client_of(value)
159
+ return nil unless value.is_a?(Hash) && value['name'].is_a?(String)
160
+
161
+ # A name this version doesn't know still shows, as Mailset names it.
162
+ DeliveryClient.new(name: value['name'], version: text_of(value['version']))
163
+ end
164
+
165
+ def text_of(value)
166
+ value.is_a?(String) ? value : nil
167
+ end
168
+
169
+ def unreachable
170
+ ServerError.new('The Mailset API can’t be reached.', code: 'unavailable', command: 'delivery.search')
171
+ end
172
+ end
173
+ end
174
+ end
@@ -0,0 +1,272 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # Mailset refused, or couldn't be reached. `code` is stable; `message` is
5
+ # Mailset's words, for people. Each family has its own class, so a rescue
6
+ # can be as narrow as it likes:
7
+ #
8
+ # rescue Mailset::RateLimitError => e # limit_reached
9
+ # retry_later(at: e.retry_at)
10
+ # rescue Mailset::Error => e # anything else
11
+ # logger.error("#{e.code}: #{e.message} #{e.help}")
12
+ #
13
+ # What Ruby prints for one it never rescued ends with {#help}: where the
14
+ # docs say what the code means, and where to ask.
15
+ class Error < StandardError
16
+ # A stable code: `invalid_input`, `unauthorized`, `forbidden`,
17
+ # `not_found`, `conflict`, `limit_reached`, `step_up_required`,
18
+ # `expired`, `unavailable` or `internal`.
19
+ # @return [String]
20
+ attr_reader :code
21
+
22
+ # The HTTP status Mailset answered with, or nil when it never answered.
23
+ # @return [Integer, nil]
24
+ attr_reader :status
25
+
26
+ # Why it was refused, when Mailset says. `recipient`: that address can't
27
+ # get mail (its domain takes none, or it bounced or reported spam before),
28
+ # so ask the person to check it. `mail_domain`: a domain key was asked for
29
+ # a domain that holds your team's mailboxes; make a key for one mailbox
30
+ # instead. Others: `domain_pending`, `domain_blocked`, `provider_refused`,
31
+ # and any value a newer Mailset adds, as text. An Apple Hide My Email
32
+ # address, a temporary inbox or someone who unsubscribed is never a
33
+ # refusal: see {Sent#skipped}.
34
+ # @return [String, nil]
35
+ attr_reader :refusal
36
+
37
+ # On `limit_reached` for mail with a `deliver_by`: the soonest it could
38
+ # go, in ms since the epoch. Send it again then, or with a later deadline.
39
+ # @return [Integer, nil]
40
+ attr_reader :retry_at
41
+
42
+ # On `invalid_input`: each field that was wrong, and what's wrong with it.
43
+ # @return [Array<Mailset::ErrorIssue>]
44
+ attr_reader :issues
45
+
46
+ # On `step_up_required`: what a passkey has to approve. See {Approvals}.
47
+ # @return [Mailset::StepUpPurpose, nil]
48
+ attr_reader :purpose
49
+
50
+ # The command that was refused, by its id, when it was one.
51
+ # @return [String, nil]
52
+ attr_reader :command
53
+
54
+ # When this credential can't run the command: the one that can,
55
+ # `MAILSET_TOKEN` or `MAILSET_KEY`, with the grant it needs.
56
+ # @return [String, nil]
57
+ attr_reader :needs
58
+
59
+ # Where the docs say what this code means and what to do.
60
+ # @return [String]
61
+ attr_reader :docs
62
+
63
+ # The docs' link and where to ask, in one line: what a log should keep
64
+ # beside `message`.
65
+ # @return [String]
66
+ attr_reader :help
67
+
68
+ # The code a class stands for when none is given.
69
+ def self.default_code
70
+ 'internal'
71
+ end
72
+
73
+ # The error for a code, of its family's class.
74
+ # @return [Mailset::Error]
75
+ def self.of(code, message, status: nil, **details)
76
+ klass = FAMILIES[code] || Error
77
+ klass = ConnectionError if code == 'unavailable' && status.nil?
78
+ klass.new(message, code: code, status: status, **details)
79
+ end
80
+
81
+ # A refusal as Mailset words it (`{"code", "message", …}`), or nil when
82
+ # the value isn't one.
83
+ # @api private
84
+ def self.from_body(body, status: nil, command: nil)
85
+ return nil unless body.is_a?(Hash) && body['code'].is_a?(String) && body['message'].is_a?(String)
86
+
87
+ of(
88
+ body['code'], body['message'],
89
+ status: status, command: command,
90
+ refusal: body['refusal'].is_a?(String) ? body['refusal'] : nil,
91
+ retry_at: body['retryAt'].is_a?(Integer) ? body['retryAt'] : nil,
92
+ issues: issues_of(body['issues']),
93
+ purpose: purpose_of(body['purpose'])
94
+ )
95
+ end
96
+
97
+ def self.issues_of(value)
98
+ return [] unless value.is_a?(Array)
99
+
100
+ value.filter_map do |issue|
101
+ next unless issue.is_a?(Hash) && issue['path'].is_a?(Array) && issue['message'].is_a?(String)
102
+
103
+ path = issue['path'].select { |part| part.is_a?(String) || part.is_a?(Integer) }
104
+ ErrorIssue.new(path: path, message: issue['message'])
105
+ end
106
+ end
107
+
108
+ def self.purpose_of(value)
109
+ return nil unless value.is_a?(Hash) && value['kind'].is_a?(String) && value['id'].is_a?(String)
110
+
111
+ StepUpPurpose.new(kind: value['kind'], id: value['id'], org: value['org'].is_a?(String) ? value['org'] : nil)
112
+ end
113
+ private_class_method :issues_of, :purpose_of
114
+
115
+ def initialize(message = nil, code: self.class.default_code, status: nil, refusal: nil, retry_at: nil,
116
+ issues: [], purpose: nil, command: nil, needs: nil)
117
+ super(message || code)
118
+ @code = code
119
+ @status = status
120
+ @refusal = refusal
121
+ @retry_at = retry_at
122
+ @issues = issues.freeze
123
+ @purpose = purpose
124
+ @command = command
125
+ @needs = needs
126
+ @docs = "#{ERROR_DOCS}##{code}"
127
+ @help = "Docs: #{@docs}. Ask us: #{SUPPORT}"
128
+ end
129
+
130
+ # Whether the last try ran out of time: a {TimeoutError}.
131
+ def timed_out?
132
+ false
133
+ end
134
+
135
+ if Exception.method_defined?(:detailed_message)
136
+ # What Ruby prints for it: Mailset's words, then {#help} on a line of its own.
137
+ def detailed_message(highlight: false, **options)
138
+ "#{super}\n#{help}"
139
+ end
140
+ else
141
+ # What Ruby prints for it: Mailset's words, then {#help} on a line of its own.
142
+ def full_message(highlight: false, order: :top)
143
+ super.sub(message) { "#{message}\n#{help}" }
144
+ end
145
+ end
146
+
147
+ # Every field as JSON, with the API's names.
148
+ # @return [Hash{String => Object}]
149
+ def to_h
150
+ {
151
+ 'code' => code,
152
+ 'message' => message,
153
+ 'status' => status,
154
+ 'needs' => needs,
155
+ 'docs' => docs,
156
+ 'help' => help,
157
+ 'issues' => issues.map(&:to_h),
158
+ 'purpose' => purpose&.to_h,
159
+ 'refusal' => refusal,
160
+ 'retryAt' => retry_at,
161
+ 'command' => command,
162
+ 'timedOut' => timed_out?
163
+ }
164
+ end
165
+
166
+ def inspect
167
+ "#<#{self.class.name} #{code}: #{message}>"
168
+ end
169
+ end
170
+
171
+ # `unauthorized`: the key or token isn't one Mailset takes (revoked,
172
+ # expired or wrong), or a webhook's signature doesn't match.
173
+ class AuthenticationError < Error
174
+ def self.default_code
175
+ 'unauthorized'
176
+ end
177
+ end
178
+
179
+ # `forbidden`: this credential may not do that. {Error#needs} says what may.
180
+ class PermissionError < Error
181
+ def self.default_code
182
+ 'forbidden'
183
+ end
184
+ end
185
+
186
+ # `invalid_input`: something given is wrong. {Error#issues} says what.
187
+ class InvalidRequestError < Error
188
+ def self.default_code
189
+ 'invalid_input'
190
+ end
191
+ end
192
+
193
+ # `not_found`.
194
+ class NotFoundError < Error
195
+ def self.default_code
196
+ 'not_found'
197
+ end
198
+ end
199
+
200
+ # `conflict`: it clashes with what's there, such as a name already taken.
201
+ class ConflictError < Error
202
+ def self.default_code
203
+ 'conflict'
204
+ end
205
+ end
206
+
207
+ # `limit_reached`: a sending limit, a plan's limit or a size. With a
208
+ # `deliver_by`, {Error#retry_at} says when it could go.
209
+ class RateLimitError < Error
210
+ def self.default_code
211
+ 'limit_reached'
212
+ end
213
+ end
214
+
215
+ # `step_up_required`: a person has to approve it with their passkey.
216
+ # {Error#purpose} says what; see {Approvals}, or give the client `on_approval:`.
217
+ class PasskeyRequiredError < Error
218
+ def self.default_code
219
+ 'step_up_required'
220
+ end
221
+ end
222
+
223
+ # `expired`: too late, such as an old webhook signature or an approval
224
+ # nobody gave in time.
225
+ class ExpiredError < Error
226
+ def self.default_code
227
+ 'expired'
228
+ end
229
+ end
230
+
231
+ # `unavailable` with no answer: Mailset couldn't be reached (the network,
232
+ # a dropped connection, a try's timeout), after every retry.
233
+ class ConnectionError < Error
234
+ def self.default_code
235
+ 'unavailable'
236
+ end
237
+ end
238
+
239
+ # `unavailable` because the last try ran out of time: each try may take the
240
+ # client's `timeout:` (30 seconds unless told), and every try did. A kind
241
+ # of {ConnectionError}, so a rescue of either catches it.
242
+ class TimeoutError < ConnectionError
243
+ # Always true.
244
+ def timed_out?
245
+ true
246
+ end
247
+ end
248
+
249
+ # `internal`, or `unavailable` with an answer that wasn't Mailset's:
250
+ # something broke on the way or on Mailset's side, after every retry.
251
+ class ServerError < Error
252
+ def self.default_code
253
+ 'internal'
254
+ end
255
+ end
256
+
257
+ class Error
258
+ # Each code's class.
259
+ FAMILIES = {
260
+ 'unauthorized' => AuthenticationError,
261
+ 'forbidden' => PermissionError,
262
+ 'invalid_input' => InvalidRequestError,
263
+ 'not_found' => NotFoundError,
264
+ 'conflict' => ConflictError,
265
+ 'limit_reached' => RateLimitError,
266
+ 'step_up_required' => PasskeyRequiredError,
267
+ 'expired' => ExpiredError,
268
+ 'unavailable' => ServerError,
269
+ 'internal' => ServerError
270
+ }.freeze
271
+ end
272
+ end