calmlens 0.25.0 → 0.27.3

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,234 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module CalmLens
6
+ # What the API answered to the request that returned a result: its HTTP status, its headers
7
+ # (lowercase names), its `X-Request-Id` and the `Idempotency-Key` the request carried (nil
8
+ # without one). Quote the request ID when contacting support.
9
+ LastResponse = Data.define(:status, :headers, :request_id, :idempotency_key)
10
+
11
+ # A read-only API object, such as an {Asset} or a {Folder}. Every result is one.
12
+ #
13
+ # Fields have snake_case readers (`asset.classification.moderation.decision`) and can also be read
14
+ # with `[]`, by the reader's Symbol or the API's camelCase String. A field the API added after this
15
+ # release has no reader but is kept: read it with `[]` and it appears in {#to_h}. Records whose
16
+ # keys are data, such as `categories` (keyed by category) and `metadata` values, are frozen Hashes
17
+ # with the API's String keys. A reader returns nil both for a field the API left out and for a
18
+ # null one; {#key?} tells them apart.
19
+ #
20
+ # case asset
21
+ # in { classification: { moderation: { status: 'allowed' } } } then publish(asset)
22
+ # end
23
+ class Model
24
+ # The model classes, generated from the API's schemas in lib/calmlens/models.rb.
25
+ @fields = {}.freeze
26
+
27
+ class << self
28
+ # The fields this class declares: reader => [API key, conversion].
29
+ # @api private
30
+ attr_reader :fields
31
+
32
+ # The reader name of an API key: `projectId` → `project_id`, `self-harm` → `self_harm`.
33
+ # @api private
34
+ def field_name(key) = key.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').tr('-', '_').downcase
35
+
36
+ # Declares the fields of a generated class and their readers. A field whose name is already a
37
+ # public method (`hash`) has no reader; read it with `[]`.
38
+ # @api private
39
+ def declare(fields)
40
+ @fields = fields.freeze
41
+ fields.each_key do |name|
42
+ define_method(name) { @values[name] } unless method_defined?(name)
43
+ end
44
+ end
45
+
46
+ # Converts a JSON value for a field: a model, an Array or Hash of them, or a frozen value.
47
+ # @api private
48
+ def convert(conversion, value)
49
+ case conversion
50
+ in [:model, name] then value.is_a?(Hash) ? CalmLens.const_get(name).new(value) : frozen(value)
51
+ in [:array, inner] then value.is_a?(Array) ? value.map { |item| convert(inner, item) }.freeze : frozen(value)
52
+ in [:map, inner] then value.is_a?(Hash) ? value.to_h { |key, item| [key, convert(inner, item)] }.freeze : frozen(value)
53
+ else frozen(value)
54
+ end
55
+ end
56
+
57
+ # A deep-frozen copy of a JSON value.
58
+ # @api private
59
+ def frozen(value)
60
+ case value
61
+ when Hash then value.to_h { |key, item| [key.frozen? ? key : key.dup.freeze, frozen(item)] }.freeze
62
+ when Array then value.map { |item| frozen(item) }.freeze
63
+ when String then value.frozen? ? value : value.dup.freeze
64
+ else value
65
+ end
66
+ end
67
+
68
+ # A value back in the API's JSON form.
69
+ # @api private
70
+ def wire(value)
71
+ case value
72
+ when Model then value.to_h
73
+ when Array then value.map { |item| wire(item) }
74
+ when Hash then value.transform_values { |item| wire(item) }
75
+ else value
76
+ end
77
+ end
78
+ end
79
+
80
+ # The response that returned this result, or nil for an object inside one.
81
+ # @return [LastResponse, nil]
82
+ attr_reader :last_response
83
+
84
+ # @param values [Hash{String => Object}] the API's JSON object
85
+ # @param last_response [LastResponse, nil]
86
+ def initialize(values, last_response: nil)
87
+ raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, "Expected an object for #{self.class}") unless values.is_a?(Hash)
88
+
89
+ @last_response = last_response
90
+ @values = {}
91
+ @keys = {}
92
+ fields = self.class.fields
93
+ values.each do |key, value|
94
+ name = Model.field_name(key).to_sym
95
+ @keys[name] = key.to_s.frozen? ? key.to_s : key.to_s.dup.freeze
96
+ @values[name] = Model.convert(fields.dig(name, 1), value)
97
+ end
98
+ @values.freeze
99
+ @keys.freeze
100
+ freeze
101
+ end
102
+
103
+ # The value of a field, by reader name (`:project_id`) or API key (`'projectId'`), or nil.
104
+ def [](key) = @values[name_of(key)]
105
+
106
+ # The value at a path of fields, as Hash#dig and Struct#dig read one:
107
+ # `asset.dig(:classification, :moderation, :decision)`. Array indexes and map keys work too.
108
+ def dig(key, *rest)
109
+ value = self[key]
110
+ rest.empty? || value.nil? ? value : value.dig(*rest)
111
+ end
112
+
113
+ # The values of several fields, by reader name or API key.
114
+ def values_at(*keys) = keys.map { |key| self[key] }
115
+
116
+ # Whether the API sent the field, even as null.
117
+ def key?(key) = @values.key?(name_of(key))
118
+
119
+ # The fields the API sent, as reader names.
120
+ def keys = @values.keys
121
+
122
+ # The object in the API's JSON form: camelCase String keys, every field the API sent.
123
+ # @return [Hash{String => Object}]
124
+ def to_h = @keys.to_h { |name, key| [key, Model.wire(@values[name])] }
125
+
126
+ # The fields by reader name, for pattern matching (`in { status: 'allowed' }`).
127
+ def deconstruct_keys(keys) = keys ? @values.slice(*keys) : @values
128
+
129
+ def to_json(*) = to_h.to_json(*)
130
+
131
+ def ==(other) = other.instance_of?(self.class) && other.to_h == to_h
132
+ alias eql? ==
133
+
134
+ def hash = [self.class, to_h].hash
135
+
136
+ def inspect
137
+ fields = @values.map { |name, value| "#{name}=#{value.inspect}" }
138
+ "#<#{self.class.name} #{fields.join(', ')}>"
139
+ end
140
+
141
+ def pretty_print(printer) = printer.text(inspect)
142
+
143
+ private
144
+
145
+ def name_of(key) = key.is_a?(Symbol) && @values.key?(key) ? key : Model.field_name(key).to_sym
146
+ end
147
+
148
+ # One page of a list, such as {Assets#list}'s. Enumerating it yields this page's items;
149
+ # {#auto_paging_each} fetches the following pages as it goes, with the same options.
150
+ #
151
+ # client.assets.list(page_size: 100).auto_paging_each { |asset| index(asset) }
152
+ class Page < Model
153
+ include Enumerable
154
+
155
+ # @api private
156
+ # @param fetch [Proc, nil] fetches the page after a cursor, with the options of this one
157
+ # @param cursor [String, nil] the cursor this page was fetched with
158
+ def initialize(values, fetch: nil, cursor: nil, last_response: nil)
159
+ @fetch = fetch
160
+ @cursor = cursor
161
+ super(values, last_response: last_response)
162
+ end
163
+
164
+ # The page in the API's JSON form, as for any model (not Enumerable#to_h).
165
+ def to_h = Model.instance_method(:to_h).bind_call(self)
166
+
167
+ # Yields each item on this page; fetches no more pages.
168
+ def each(&)
169
+ return enum_for(:each) unless block_given?
170
+
171
+ page_items.each(&)
172
+ self
173
+ end
174
+
175
+ # Whether this page has no items.
176
+ def empty? = page_items.empty?
177
+
178
+ # Whether there is a page after this one.
179
+ def next_page?
180
+ cursor = self[:next_cursor]
181
+ self[:has_more] == true && cursor.is_a?(String) && !cursor.empty? && !page_items.empty?
182
+ end
183
+
184
+ # The page after this one, fetched with this page's options; an empty page when there is none.
185
+ def next_page
186
+ return _ = self.class.new({ 'items' => [], 'hasMore' => false, 'nextCursor' => self[:next_cursor] }) unless next_page? && @fetch
187
+
188
+ @fetch.call(self[:next_cursor])
189
+ end
190
+
191
+ # Yields this page and each one after it, fetching them as needed. Raises `sdk/invalid-response`
192
+ # (with `details['cursor']`) instead of repeating pages when the API hands back a cursor it
193
+ # already returned.
194
+ def each_page
195
+ return enum_for(:each_page) unless block_given?
196
+
197
+ page = self
198
+ sent = [@cursor].compact
199
+ loop do
200
+ following = page.next_page?
201
+ if following
202
+ cursor = page[:next_cursor]
203
+ if sent.include?(cursor)
204
+ raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE,
205
+ 'The API returned a cursor it had already returned, with more pages to follow',
206
+ details: { 'cursor' => cursor })
207
+ end
208
+ sent << cursor
209
+ end
210
+ yield page
211
+ break unless following
212
+
213
+ page = page.next_page
214
+ end
215
+ nil
216
+ end
217
+
218
+ # Yields every item on this page and the pages after it, fetching them as needed.
219
+ def auto_paging_each(&block)
220
+ return enum_for(:auto_paging_each) unless block
221
+
222
+ each_page { |page| page.each(&block) }
223
+ end
224
+
225
+ private
226
+
227
+ def page_items
228
+ value = self[:items]
229
+ raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, "#{self.class} has no items") unless value.is_a?(Array)
230
+
231
+ value
232
+ end
233
+ end
234
+ end