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,366 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # The default of an optional input that may also be null, such as
5
+ # `tracking_domain:`: leaving it out sends nothing, where nil sends null.
6
+ OMIT = Object.new
7
+ def OMIT.inspect
8
+ 'Mailset::OMIT'
9
+ end
10
+ OMIT.freeze
11
+
12
+ # One public command as the client knows it, from {COMMANDS}: its id, where
13
+ # the client puts it (its groups' readers, then its method), the grant an
14
+ # app key needs, the credentials that may call it (`:key`, `:token`),
15
+ # whether it can stop for a passkey, and whether the gem writes it by hand.
16
+ CommandInfo = Struct.new(:id, :path, :grant, :credentials, :passkey, :hand_written)
17
+
18
+ # How the gem reads Mailset's JSON into its types, and writes them back.
19
+ # A type is a symbol (`:string`, `:integer`, `:number`, `:boolean`,
20
+ # `:null`, `:any`, or a type's name under `Mailset`, such as `:Domain`) or
21
+ # an array (`[:array, t]`, `[:map, t]`, `[:nullable, t]`,
22
+ # `[:union, t, …]`, `[:literal, value]`).
23
+ #
24
+ # @api private
25
+ module Types
26
+ PRIMITIVES = %i[string integer number boolean null any].freeze
27
+
28
+ module_function
29
+
30
+ # A type under `Mailset` by its name.
31
+ def resolve(name)
32
+ Mailset.const_get(name, false)
33
+ end
34
+
35
+ def model?(named)
36
+ named.is_a?(Class) && named < Model
37
+ end
38
+
39
+ def union?(named)
40
+ named.is_a?(Module) && named.singleton_class.include?(Union)
41
+ end
42
+
43
+ # A value from Mailset's JSON, read into the gem's types. Leniently: a
44
+ # value of another shape than its type says is kept as it came.
45
+ def parse(type, value)
46
+ case type
47
+ when Symbol
48
+ return value if PRIMITIVES.include?(type) || value.nil?
49
+
50
+ named = resolve(type)
51
+ model?(named) || union?(named) ? named.from_json(value) : value
52
+ when Array
53
+ case type[0]
54
+ when :array then value.is_a?(Array) ? value.map { |item| parse(type[1], item) } : value
55
+ when :map then value.is_a?(Hash) ? value.transform_values { |item| parse(type[1], item) } : value
56
+ when :nullable then value.nil? ? nil : parse(type[1], value)
57
+ when :union
58
+ variant = type.drop(1).find { |one| match?(one, value) }
59
+ variant ? parse(variant, value) : value
60
+ else value
61
+ end
62
+ else value
63
+ end
64
+ end
65
+
66
+ # Whether a value can be of a type, to pick a union's variant.
67
+ def match?(type, value)
68
+ case type
69
+ when :string then value.is_a?(String) || value.is_a?(Symbol)
70
+ when :integer then value.is_a?(Integer) || time?(value)
71
+ when :number then value.is_a?(Numeric)
72
+ when :boolean then [true, false].include?(value)
73
+ when :null then value.nil?
74
+ when :any then true
75
+ when Symbol
76
+ named = resolve(type)
77
+ if model?(named) then value.is_a?(Hash) || value.is_a?(named)
78
+ elsif union?(named) then value.is_a?(Hash) || value.is_a?(Model)
79
+ else value.is_a?(String) || value.is_a?(Symbol)
80
+ end
81
+ when Array
82
+ case type[0]
83
+ when :array then value.is_a?(Array)
84
+ when :map then value.is_a?(Hash)
85
+ when :nullable then value.nil? || match?(type[1], value)
86
+ when :literal then value == type[1] || (value.is_a?(Symbol) && value.to_s == type[1])
87
+ when :union then type.drop(1).any? { |one| match?(one, value) }
88
+ else false
89
+ end
90
+ else false
91
+ end
92
+ end
93
+
94
+ # A value as Mailset's JSON takes it: models as their wire Hash, a Hash
95
+ # for a model by its fields' Ruby or wire names, a Time as ms where a
96
+ # number goes (an ISO time where only text does), a Date as its day.
97
+ def dump(type, value)
98
+ return nil if value.nil?
99
+
100
+ case type
101
+ when :integer then time?(value) ? ms(value) : value
102
+ when :string then text(value)
103
+ when :any then plain(value)
104
+ when Symbol
105
+ return value if PRIMITIVES.include?(type)
106
+
107
+ named = resolve(type)
108
+ if value.is_a?(Model) then value.to_h
109
+ elsif model?(named) && value.is_a?(Hash) then named.dump_input(value)
110
+ elsif union?(named) then plain(value)
111
+ else value.is_a?(Symbol) ? value.to_s : value
112
+ end
113
+ when Array
114
+ case type[0]
115
+ when :array then value.is_a?(Array) ? value.map { |item| dump(type[1], item) } : value
116
+ when :map then value.is_a?(Hash) ? value.to_h { |key, item| [key.to_s, dump(type[1], item)] } : value
117
+ when :nullable then dump(type[1], value)
118
+ when :literal then value.is_a?(Symbol) ? value.to_s : value
119
+ when :union then dump_union(type.drop(1), value)
120
+ else plain(value)
121
+ end
122
+ else plain(value)
123
+ end
124
+ end
125
+
126
+ def dump_union(variants, value)
127
+ if time?(value) || value.is_a?(Date)
128
+ return ms(value) if variants.include?(:integer) && time?(value)
129
+
130
+ return text(value)
131
+ end
132
+ variant = variants.find { |one| match?(one, value) }
133
+ variant ? dump(variant, value) : plain(value)
134
+ end
135
+
136
+ # Any value as plain JSON: models as their wire Hash, symbols as text.
137
+ def plain(value)
138
+ case value
139
+ when Model then value.to_h
140
+ when Hash then value.to_h { |key, item| [key.to_s, plain(item)] }
141
+ when Array then value.map { |item| plain(item) }
142
+ when Symbol then value.to_s
143
+ else time?(value) ? ms(value) : value
144
+ end
145
+ end
146
+
147
+ def text(value)
148
+ if value.is_a?(Symbol) then value.to_s
149
+ elsif time?(value) then value.to_time.utc.xmlschema(3)
150
+ elsif value.is_a?(Date) then value.iso8601
151
+ else value
152
+ end
153
+ end
154
+
155
+ # A moment: a Time, a DateTime or ActiveSupport's TimeWithZone.
156
+ def time?(value)
157
+ value.is_a?(::Time) || (defined?(::DateTime) && value.is_a?(::DateTime))
158
+ end
159
+
160
+ # A moment in ms since the epoch.
161
+ def ms(value)
162
+ (value.to_time.to_r * 1000).floor
163
+ end
164
+
165
+ # Whether a field's value goes out: left out, or nil where null isn't allowed, it doesn't.
166
+ def omitted?(field, value)
167
+ return true if value.equal?(OMIT)
168
+ return false unless value.nil?
169
+
170
+ !field.required && !nullable?(field.type)
171
+ end
172
+
173
+ def nullable?(type)
174
+ %i[null any].include?(type) || (type.is_a?(Array) && type[0] == :nullable)
175
+ end
176
+ end
177
+
178
+ # What every type Mailset answers with is: readers in snake_case, `to_h`
179
+ # giving the JSON Mailset sent (camelCase), `[]` by either name, and pattern
180
+ # matching on the readers. An answer is read leniently: an unknown field is
181
+ # ignored and a missing one is absent, so `to_h` writes back what came.
182
+ #
183
+ # domain = mailset.domains.add(name: 'example.com')
184
+ # domain.name # => "example.com"
185
+ # domain.to_h # => {"name" => "example.com", …}
186
+ # case domain
187
+ # in { status: 'ready' } then …
188
+ # end
189
+ #
190
+ # A field named like a method every object has (`display`) is that field on
191
+ # its model: the gem itself never calls those methods on a model.
192
+ class Model
193
+ # One field: its Ruby name, its name on the wire, its type, whether
194
+ # Mailset always sends it (an answer) or the caller must give it (an
195
+ # input), and in an answer what it reads as when it's missing.
196
+ Field = Struct.new(:name, :wire, :type, :required, :default)
197
+
198
+ # A field with no default: missing, it stays absent.
199
+ NO_DEFAULT = Object.new.freeze
200
+
201
+ # Object#class, for a model whose field is named `class`.
202
+ CLASS_OF = ::Kernel.instance_method(:class)
203
+
204
+ class << self
205
+ # The fields, by their Ruby names.
206
+ # @return [Hash{Symbol => Field}]
207
+ def fields
208
+ @fields ||= {}
209
+ end
210
+
211
+ # The fields, by their wire names.
212
+ # @return [Hash{String => Field}]
213
+ def wire_fields
214
+ @wire_fields ||= {}
215
+ end
216
+
217
+ # Reads Mailset's JSON (a Hash with string keys) into this type. A value
218
+ # that isn't a Hash comes back as it is. A field missing from it that
219
+ # has a default (a server older than the field leaves it out) reads as
220
+ # that default: `domains` on a key's status is `[]`.
221
+ def from_json(value)
222
+ return value unless value.is_a?(Hash)
223
+
224
+ values = {}
225
+ fields.each_value do |field|
226
+ if value.key?(field.wire)
227
+ values[field.name] = Types.parse(field.type, value[field.wire])
228
+ elsif !field.default.equal?(NO_DEFAULT)
229
+ values[field.name] = Types.parse(field.type, field.default)
230
+ end
231
+ end
232
+ model = allocate
233
+ model.instance_variable_set(:@values, values.freeze)
234
+ model
235
+ end
236
+
237
+ # A Hash given where this type goes, as Mailset's JSON: its keys by
238
+ # either name, values written as their fields' types say. A key this
239
+ # type doesn't have goes as it is.
240
+ # @api private
241
+ def dump_input(hash)
242
+ out = {}
243
+ hash.each do |key, value|
244
+ field = fields[key.to_sym] || wire_fields[key.to_s]
245
+ if field.nil?
246
+ out[key.to_s] = Types.plain(value)
247
+ elsif !Types.omitted?(field, value)
248
+ out[field.wire] = Types.dump(field.type, value)
249
+ end
250
+ end
251
+ out
252
+ end
253
+
254
+ # Whether a Hash from Mailset can be this type: its fixed values match and
255
+ # the fields it always has are there.
256
+ # @api private
257
+ def fits?(hash, strict:)
258
+ fields.each_value.all? do |field|
259
+ next true unless field.required
260
+
261
+ type = field.type
262
+ if type.is_a?(Array) && type[0] == :literal
263
+ hash[field.wire] == type[1]
264
+ else
265
+ !strict || hash.key?(field.wire)
266
+ end
267
+ end
268
+ end
269
+
270
+ private
271
+
272
+ def field(name, wire, type, required: false, default: NO_DEFAULT)
273
+ info = Field.new(name, wire, type, required, default).freeze
274
+ fields[name] = info
275
+ wire_fields[wire] = info
276
+ define_method(name) { @values[name] }
277
+ end
278
+ end
279
+
280
+ # A value of this type, by its fields' Ruby names: what an input takes.
281
+ def initialize(**values)
282
+ known = __model__.fields
283
+ unknown = values.keys.reject { |key| known.key?(key) }
284
+ unless unknown.empty?
285
+ ::Kernel.raise ::ArgumentError,
286
+ "#{__model__.name} has no #{unknown.map(&:inspect).join(', ')}"
287
+ end
288
+ @values = values.reject { |_, value| value.equal?(OMIT) }.freeze
289
+ end
290
+
291
+ # Mailset's JSON for it: a Hash with the API's camelCase names. A required
292
+ # field that is null stays, as null.
293
+ # @return [Hash{String => Object}]
294
+ def to_h
295
+ out = {}
296
+ __model__.fields.each_value do |field|
297
+ next unless @values.key?(field.name)
298
+
299
+ value = @values[field.name]
300
+ next if Types.omitted?(field, value)
301
+
302
+ out[field.wire] = Types.dump(field.type, value)
303
+ end
304
+ out
305
+ end
306
+
307
+ # A field by its Ruby name (`:message_id`) or its wire name (`'messageId'`).
308
+ def [](name)
309
+ field = __model__.fields[name.to_sym] || __model__.wire_fields[name.to_s]
310
+ field && @values[field.name]
311
+ end
312
+
313
+ # For pattern matching: `in { status: 'ready' }`.
314
+ def deconstruct_keys(keys)
315
+ keys ? @values.slice(*keys) : @values
316
+ end
317
+
318
+ # The JSON Mailset sent.
319
+ def to_json(*args)
320
+ to_h.to_json(*args)
321
+ end
322
+
323
+ # For Rails' JSON: the same as `to_h`.
324
+ def as_json(*)
325
+ to_h
326
+ end
327
+
328
+ def ==(other)
329
+ other.is_a?(Model) && CLASS_OF.bind_call(other) == __model__ && other.to_h == to_h
330
+ end
331
+ alias eql? ==
332
+
333
+ def hash
334
+ [__model__, to_h].hash
335
+ end
336
+
337
+ def inspect
338
+ shown = @values.map { |name, value| "#{name}=#{value.inspect}" }
339
+ shown.empty? ? "#<#{__model__.name}>" : "#<#{__model__.name} #{shown.join(', ')}>"
340
+ end
341
+ alias to_s inspect
342
+
343
+ private
344
+
345
+ # This model's class, whatever its fields are named.
346
+ def __model__
347
+ CLASS_OF.bind_call(self)
348
+ end
349
+ end
350
+
351
+ # What a type that may be one of several is: `from_json` reads Mailset's
352
+ # JSON into the variant it is (`VARIANTS`), told apart by their fixed
353
+ # fields, such as `ok: true` or `state: 'queued'`.
354
+ module Union
355
+ # @return [Model, Object]
356
+ def from_json(value)
357
+ return value unless value.is_a?(Hash)
358
+
359
+ variants = self::VARIANTS.map { |name| Types.resolve(name) }
360
+ chosen = variants.find { |variant| variant.fits?(value, strict: true) } ||
361
+ variants.find { |variant| variant.fits?(value, strict: false) } ||
362
+ variants.first
363
+ chosen.from_json(value)
364
+ end
365
+ end
366
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ module Resources
5
+ # How a group of commands and the client run one: its input written as
6
+ # Mailset's JSON, its answer read into its type.
7
+ #
8
+ # @api private
9
+ module Calls
10
+ OPTIONS = %i[org approval timeout].freeze
11
+
12
+ private
13
+
14
+ def call_command(id, params, values, output, request_options)
15
+ Types.parse(output, transport.command(id, params.dump_input(values), **call_options(request_options)))
16
+ end
17
+
18
+ def call_options(request_options)
19
+ options = (request_options || {}).to_h.transform_keys(&:to_sym)
20
+ unknown = options.keys - OPTIONS
21
+ raise ArgumentError, "request_options takes #{OPTIONS.join(', ')}, not #{unknown.join(', ')}" unless unknown.empty?
22
+
23
+ options
24
+ end
25
+ end
26
+
27
+ # What every group of commands is: `mailset.domains`, `mailset.sending.domains`…
28
+ class Base
29
+ include Calls
30
+
31
+ # @api private
32
+ def initialize(transport)
33
+ @transport = transport
34
+ end
35
+
36
+ def inspect
37
+ "#<#{self.class.name}>"
38
+ end
39
+ alias to_s inspect
40
+
41
+ private
42
+
43
+ attr_reader :transport
44
+ end
45
+ end
46
+ end