calmlens 0.25.0 → 0.27.2

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.
@@ -20,6 +20,8 @@ module CalmLens
20
20
  # An error response did not carry a CalmLens error code, or the API answered with a redirect,
21
21
  # which the SDK never follows.
22
22
  HTTP_ERROR = 'sdk/http-error'
23
+ # The caller cancelled the call before it finished.
24
+ CANCELLED = 'sdk/cancelled'
23
25
  # A webhook signature or timestamp did not verify.
24
26
  INVALID_WEBHOOK_SIGNATURE = 'sdk/invalid-webhook-signature'
25
27
  # A verified webhook body was not a CalmLens event payload.
@@ -41,18 +43,32 @@ module CalmLens
41
43
  # Include it when contacting support.
42
44
  # @!attribute [r] headers
43
45
  # @return [Hash{String => String}] response headers with lowercase names (empty without a response).
46
+ # @!attribute [r] body
47
+ # @return [String, nil] the error response's body as received, at most {BODY_LIMIT} bytes, such as
48
+ # a proxy's HTML page; nil without a response.
49
+ # @!attribute [r] http_method
50
+ # @return [String, nil] the request's HTTP method, for an API error response.
51
+ # @!attribute [r] url
52
+ # @return [String, nil] the request's URL, for an API error response.
44
53
  class Error < StandardError
45
- attr_reader :code, :details, :status, :request_id, :headers
54
+ # The most bytes of an error response body {#body} keeps.
55
+ BODY_LIMIT = 64 * 1024
56
+
57
+ attr_reader :code, :details, :status, :request_id, :headers, :body, :http_method, :url
46
58
 
47
59
  # @param code [String]
48
60
  # @param message [String, nil] defaults to the code.
49
- def initialize(code, message = nil, details: nil, status: nil, headers: {}, request_id: nil)
50
- super("[calmlens] #{message || code}")
61
+ def initialize(code, message = nil, details: nil, status: nil, headers: {}, request_id: nil, body: nil,
62
+ http_method: nil, url: nil)
63
+ super(message || code)
51
64
  @code = code
52
65
  @details = details
53
66
  @status = status
54
67
  @headers = headers.freeze
55
68
  @request_id = request_id || headers['x-request-id']
69
+ @body = body&.byteslice(0, BODY_LIMIT)&.freeze
70
+ @http_method = http_method
71
+ @url = url
56
72
  end
57
73
 
58
74
  # @return [Integer, nil] whole seconds to wait before retrying, from the `Retry-After` header
@@ -92,15 +108,21 @@ module CalmLens
92
108
 
93
109
  # Builds the most specific error class for a code and HTTP status.
94
110
  # @return [Error]
95
- def self.build(code, message = nil, status: nil, **options)
111
+ def self.build(code, message = nil, status: nil, **)
96
112
  klass = if status then APIError.class_for(status)
113
+ # An error response without a CalmLens code is an API error even without a status.
114
+ elsif code == SdkErrorCodes::HTTP_ERROR then APIError
97
115
  elsif code == SdkErrorCodes::TIMEOUT then TimeoutError
98
116
  elsif code == SdkErrorCodes::TRANSPORT_ERROR then ConnectionError
99
- elsif code == SdkErrorCodes::INVALID_RESPONSE then InvalidResponseError
100
- elsif code == SdkErrorCodes::INVALID_CONFIG then ConfigurationError
117
+ elsif code == SdkErrorCodes::CANCELLED then CancelledError
118
+ elsif [SdkErrorCodes::INVALID_RESPONSE, SdkErrorCodes::RESPONSE_TOO_LARGE].include?(code) then InvalidResponseError
119
+ elsif [SdkErrorCodes::INVALID_WEBHOOK_SIGNATURE, SdkErrorCodes::INVALID_WEBHOOK_PAYLOAD].include?(code)
120
+ WebhookVerificationError
121
+ # `sdk/no-fetch` is the configuration error of SDKs that need a fetch implementation.
122
+ elsif [SdkErrorCodes::INVALID_CONFIG, 'sdk/no-fetch'].include?(code) then ConfigurationError
101
123
  else InvalidArgumentError
102
124
  end
103
- klass.new(code, message, status: status, **options)
125
+ klass.new(code, message, status: status, **)
104
126
  end
105
127
 
106
128
  # @api private
@@ -126,6 +148,8 @@ module CalmLens
126
148
  when 403 then PermissionDeniedError
127
149
  when 404 then NotFoundError
128
150
  when 409 then ConflictError
151
+ when 413 then PayloadTooLargeError
152
+ when 422 then UnprocessableEntityError
129
153
  when 429 then RateLimitError
130
154
  when 500..599 then ServerError
131
155
  else APIError
@@ -143,6 +167,10 @@ module CalmLens
143
167
  class NotFoundError < APIError; end
144
168
  # HTTP 409: the request conflicts with the resource's current state.
145
169
  class ConflictError < APIError; end
170
+ # HTTP 413: the request body was larger than the API accepts.
171
+ class PayloadTooLargeError < APIError; end
172
+ # HTTP 422: the request was well formed but can't be applied, such as an upload CalmLens can't process.
173
+ class UnprocessableEntityError < APIError; end
146
174
  # HTTP 429: the request was throttled. See {Error#retry_after}.
147
175
  class RateLimitError < APIError; end
148
176
  # HTTP 5xx: CalmLens failed to handle the request.
@@ -153,7 +181,12 @@ module CalmLens
153
181
 
154
182
  # Connecting, sending or receiving exceeded its timeout, or {Assets#wait_for_decision} had no
155
183
  # decision in time (`sdk/timeout`).
156
- class TimeoutError < ConnectionError; end
184
+ class TimeoutError < Error; end
185
+
186
+ # The caller cancelled the call (`sdk/cancelled`): an exception raised into the calling thread,
187
+ # such as `Thread#raise` or a `Timeout.timeout` around the call, stopped it before it finished.
188
+ # The original exception is in `cause`.
189
+ class CancelledError < Error; end
157
190
 
158
191
  # A successful response could not be read (`sdk/invalid-response`) or was too large
159
192
  # (`sdk/response-too-large`).
@@ -7,52 +7,26 @@ module CalmLens
7
7
  OPERATIONS = 'events'
8
8
 
9
9
  # Lists events after a cursor, oldest first. Without `cursor`, returns no events and a
10
- # `nextCursor` for the current time: save it, then pass each response's `nextCursor` as `cursor`.
10
+ # `next_cursor` for the current time: save it, then pass each page's `next_cursor` as `cursor`.
11
11
  # `types` and `asset_id` narrow the feed to some event types or one asset's events. A cursor
12
12
  # belongs to the filters it was issued with, so pass the same ones with each `cursor`.
13
- # @option options [String] :cursor the `nextCursor` of a previous response
13
+ #
14
+ # {Page#each_page} follows the feed until `has_more` is false; persist each page's
15
+ # `next_cursor` once its events are handled, and resume from it later.
16
+ # @option options [String] :cursor the `next_cursor` of a previous page
14
17
  # @option options [Integer] :page_size 1 to 100, default 50
15
18
  # @option options [Array<String>] :types event types to list, such as `asset.blocked`
16
19
  # @option options [String] :asset_id list only this asset's events
17
- # @return [Hash] `{'items', 'nextCursor', 'hasMore'}`; `nextCursor` is never nil
18
- def list(options = {})
20
+ # @return [EventPage] `next_cursor` is never nil.
21
+ def list(**options)
19
22
  call(options, __method__) do |api, request|
20
- request('GET', project('events'), query: feed_query(api), request_options: request)
21
- end
22
- end
23
-
24
- # Iterates pages from `cursor` until `hasMore` is false. Persist each page's `nextCursor` once its
25
- # events are handled, and resume from it later. Raises `sdk/invalid-response` (with
26
- # `details['cursor']`) instead of looping when a page with more to follow repeats a cursor.
27
- # @yieldparam page [Hash]
28
- # @return [Enumerator, nil] an Enumerator when no block is given.
29
- def each_page(options = {})
30
- return enum_for(:each_page, options) unless block_given?
31
-
32
- api, request = call(options, __method__) { |*split| split }
33
- sent = api.key?('cursor') ? [api['cursor']] : []
34
- loop do
35
- page = list(api.merge('request_options' => request))
36
- unless page.is_a?(Hash) && page['items'].is_a?(Array) && page['nextCursor'].is_a?(String)
37
- raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, 'Events page has no items or next cursor')
23
+ response = request('GET', project('events'), query: feed_query(api), request_options: request)
24
+ unless response.is_a?(Hash) && response['nextCursor'].is_a?(String)
25
+ raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, 'Events page has no next cursor')
38
26
  end
39
27
 
40
- new_cursor!(sent, page['nextCursor']) if page['hasMore'] == true
41
- yield page
42
- break unless page['hasMore'] == true
43
-
44
- api = api.merge('cursor' => page['nextCursor'])
28
+ page(EventPage, response, options) { list(**_1) }
45
29
  end
46
- nil
47
- end
48
-
49
- # Iterates the events after `cursor`, across pages. See {#each_page} to track the cursor.
50
- # @yieldparam event [Hash]
51
- # @return [Enumerator, nil] an Enumerator when no block is given.
52
- def each(options = {}, &block)
53
- return enum_for(:each, options) unless block
54
-
55
- each_page(options) { |page| page['items'].each(&block) }
56
30
  end
57
31
 
58
32
  private
@@ -67,7 +41,16 @@ module CalmLens
67
41
  end
68
42
  end
69
43
 
70
- # Reads an event's facts: an {Events#list} item, a webhook delivery body or a {WebhookEvent}.
44
+ # A page of the events feed. The feed goes on while `has_more` is true, even past an empty page:
45
+ # events can arrive in the meantime.
46
+ class EventPage
47
+ def next_page?
48
+ cursor = self[:next_cursor]
49
+ self[:has_more] == true && cursor.is_a?(String) && !cursor.empty?
50
+ end
51
+ end
52
+
53
+ # Reads an event's facts: an {Events#list} item, a webhook delivery body or a {Event}.
71
54
  # {CalmLens.get_event_fact} and {CalmLens.get_event_facts} call it.
72
55
  module EventFacts
73
56
  module_function
@@ -75,7 +58,7 @@ module CalmLens
75
58
  # The value of one of an event's facts, by key, such as `'flagged-categories'`, or nil when the
76
59
  # event doesn't carry it. A key the event repeats gives its first value. The fact's `url`, when
77
60
  # it has one, is on the fact in the event's `facts`.
78
- # @param event [WebhookEvent, Hash] a parsed delivery, or an event or delivery body with string keys
61
+ # @param event [Event, Hash] a parsed delivery, or an event or delivery body with string keys
79
62
  # @param key [String]
80
63
  # @return [Object, nil]
81
64
  def value(event, key)
@@ -85,7 +68,7 @@ module CalmLens
85
68
 
86
69
  # An event's facts as a Hash of values by key, such as `{ 'flagged-categories' => ['hate'] }`.
87
70
  # A key the event repeats keeps its first value, as {.value} reads it.
88
- # @param event [WebhookEvent, Hash] a parsed delivery, or an event or delivery body with string keys
71
+ # @param event [Event, Hash] a parsed delivery, or an event or delivery body with string keys
89
72
  # @return [Hash{String => Object}]
90
73
  def values(event)
91
74
  facts_of(event).each_with_object({}) { |fact, found| found[fact['key']] = fact['value'] unless found.key?(fact['key']) }
@@ -93,8 +76,8 @@ module CalmLens
93
76
 
94
77
  # The well-formed facts of an event, in order.
95
78
  def facts_of(event)
96
- facts = event.is_a?(Hash) ? event['facts'] : event.facts
97
- facts.is_a?(Array) ? facts.select { |fact| fact.is_a?(Hash) && fact['key'].is_a?(String) } : []
79
+ facts = event['facts']
80
+ facts.is_a?(Array) ? facts.select { |fact| (fact.is_a?(Hash) || fact.is_a?(Model)) && fact['key'].is_a?(String) } : []
98
81
  end
99
82
  private_class_method :facts_of
100
83
  end
@@ -8,71 +8,66 @@ module CalmLens
8
8
 
9
9
  # Lists one page of child folders, sorted by name unless `sort` says otherwise.
10
10
  # @option options [String] :parent_id list this folder's children; omit for the project root
11
- # @option options [String] :cursor the previous page's `nextCursor`
11
+ # @option options [String] :cursor the previous page's `next_cursor`
12
12
  # @option options [Integer] :page_size 1 to 100, default 50
13
13
  # @option options [String] :sort `name` (the default) or `createdAt`, descending when prefixed with `-`
14
14
  # @option options [String] :search only children whose name contains it
15
- # @return [Hash] a cursor page (items, nextCursor, hasMore) with ancestors.
16
- def list(options = {})
15
+ # @return [FolderPage] with the folder's `ancestors`; {Page#auto_paging_each} fetches the rest.
16
+ def list(**options)
17
17
  call(options, __method__) do |api, request|
18
- cursor_page(request('GET', project('folders'), query: api, request_options: request), 'folder')
18
+ page(FolderPage, request('GET', project('folders'), query: api, request_options: request), options) { list(**_1) }
19
19
  end
20
20
  end
21
21
 
22
- # Iterates every child folder of `parent_id` (or the project root), fetching pages as needed.
23
- # @param options [Hash] the options of {#list}; `cursor` sets the starting position.
24
- # @yieldparam folder [Hash]
25
- # @return [Enumerator, nil] an Enumerator when no block is given.
26
- def each(options = {}, &block)
27
- return enum_for(:each, options) unless block
28
-
29
- each_item(options, __method__, method(:list), &block)
30
- end
31
-
32
22
  # @option options [String] :name
33
23
  # @option options [String, nil] :parent_id
34
- # @return [Hash] the folder
35
- def create(options)
36
- call(options, __method__) { |api, request| request('POST', project('folders'), body: api, request_options: request) }
24
+ # @return [Folder]
25
+ def create(**options)
26
+ call(options, __method__) do |api, request|
27
+ build(Folder, request('POST', project('folders'), body: api, request_options: request))
28
+ end
37
29
  end
38
30
 
39
- # @option options [String] :folder_id
40
- # @return [Hash] the folder
41
- def retrieve(options)
42
- call(options, __method__) do |api, request|
43
- request('GET', "/folders/#{Internal.segment(api['folderId'])}", request_options: request)
31
+ # @param folder_id [String]
32
+ # @return [Folder]
33
+ def retrieve(folder_id, **options)
34
+ call(with_ids(options, folder_id: folder_id), __method__) do |api, request|
35
+ build(Folder, request('GET', folder_path(api), request_options: request))
44
36
  end
45
37
  end
46
38
 
47
- # @option options [String] :folder_id
39
+ # @param folder_id [String]
48
40
  # @option options [String] :name
49
- # @return [Hash] the folder
50
- def update(options)
51
- call(options, __method__) do |api, request|
52
- request('PATCH', "/folders/#{Internal.segment(api['folderId'])}", body: without(api, 'folderId'),
53
- request_options: request)
41
+ # @return [Folder]
42
+ def update(folder_id, **options)
43
+ call(with_ids(options, folder_id: folder_id), __method__) do |api, request|
44
+ build(Folder, request('PATCH', folder_path(api), body: without(api, 'folderId'), request_options: request))
54
45
  end
55
46
  end
56
47
 
57
48
  # Moves a folder under another, or to the root with `parent_id: nil`.
58
- # @option options [String] :folder_id
49
+ # @param folder_id [String]
59
50
  # @option options [String, nil] :parent_id
60
- # @return [Hash] the folder
61
- def move(options)
62
- call(options, __method__) do |api, request|
63
- request('POST', "/folders/#{Internal.segment(api['folderId'])}/move",
64
- body: { 'parentId' => Internal.required(api, 'parentId') }, request_options: request)
51
+ # @return [Folder]
52
+ def move(folder_id, **options)
53
+ call(with_ids(options, folder_id: folder_id), __method__) do |api, request|
54
+ build(Folder, request('POST', "#{folder_path(api)}/move", body: { 'parentId' => Internal.required(api, 'parentId') },
55
+ request_options: request))
65
56
  end
66
57
  end
67
58
 
68
59
  # Deletes an empty folder.
69
- # @option options [String] :folder_id
60
+ # @param folder_id [String]
70
61
  # @return [nil]
71
- def delete(options)
72
- call(options, __method__) do |api, request|
73
- request('DELETE', "/folders/#{Internal.segment(api['folderId'])}", request_options: request)
62
+ def delete(folder_id, **options)
63
+ call(with_ids(options, folder_id: folder_id), __method__) do |api, request|
64
+ request('DELETE', folder_path(api), request_options: request)
74
65
  nil
75
66
  end
76
67
  end
68
+
69
+ private
70
+
71
+ def folder_path(api) = "/folders/#{Internal.segment(api['folderId'])}"
77
72
  end
78
73
  end
@@ -9,103 +9,88 @@ module CalmLens
9
9
  OPERATIONS = 'hashLists'
10
10
 
11
11
  # Lists one page of the project's hash lists, newest first unless `sort` says otherwise.
12
- # @option options [String] :cursor the previous page's `nextCursor`
12
+ # @option options [String] :cursor the previous page's `next_cursor`
13
13
  # @option options [Integer] :page_size 1 to 100, default 50
14
14
  # @option options [String] :sort `createdAt` and `id`, comma-separated, descending when prefixed
15
15
  # with `-`; `-createdAt` by default
16
- # @return [Hash] a cursor page: items, nextCursor and hasMore.
17
- def list(options = {})
16
+ # @return [HashListPage] {Page#auto_paging_each} fetches the rest.
17
+ def list(**options)
18
18
  call(options, __method__) do |api, request|
19
- cursor_page(request('GET', project('hash-lists'), query: api, request_options: request), 'hash list')
19
+ page(HashListPage, request('GET', project('hash-lists'), query: api, request_options: request), options) { list(**_1) }
20
20
  end
21
21
  end
22
22
 
23
- # Iterates every hash list, fetching pages as needed.
24
- # @param options [Hash] the options of {#list}; `cursor` sets the starting position.
25
- # @yieldparam hash_list [Hash]
26
- # @return [Enumerator, nil] an Enumerator when no block is given.
27
- def each(options = {}, &block)
28
- return enum_for(:each, options) unless block
29
-
30
- each_item(options, __method__, method(:list), &block)
31
- end
32
-
33
- # @option options [String] :hash_list_id
34
- # @return [Hash] the hash list
35
- def retrieve(options)
36
- call(options, __method__) { |api, request| request('GET', list_path(api), request_options: request) }
23
+ # @param hash_list_id [String]
24
+ # @return [HashList]
25
+ def retrieve(hash_list_id, **options)
26
+ call(with_ids(options, hash_list_id: hash_list_id), __method__) do |api, request|
27
+ build(HashList, request('GET', list_path(api), request_options: request))
28
+ end
37
29
  end
38
30
 
39
31
  # @option options [String] :name
40
32
  # @option options [String] :action `flag` or `block`
41
33
  # @option options [String, nil] :description
42
- # @return [Hash] the hash list
43
- def create(options)
44
- call(options, __method__) { |api, request| request('POST', project('hash-lists'), body: api, request_options: request) }
34
+ # @return [HashList]
35
+ def create(**options)
36
+ call(options, __method__) do |api, request|
37
+ build(HashList, request('POST', project('hash-lists'), body: api, request_options: request))
38
+ end
45
39
  end
46
40
 
47
41
  # Renames a list or changes what its matches do. The new action applies to later uploads.
48
- # @option options [String] :hash_list_id
42
+ # @param hash_list_id [String]
49
43
  # @option options [String] :name
50
44
  # @option options [String, nil] :description
51
45
  # @option options [String] :action `flag` or `block`
52
- # @return [Hash] the hash list
53
- def update(options)
54
- call(options, __method__) do |api, request|
55
- request('PATCH', list_path(api), body: without(api, 'hashListId'), request_options: request)
46
+ # @return [HashList]
47
+ def update(hash_list_id, **options)
48
+ call(with_ids(options, hash_list_id: hash_list_id), __method__) do |api, request|
49
+ build(HashList, request('PATCH', list_path(api), body: without(api, 'hashListId'), request_options: request))
56
50
  end
57
51
  end
58
52
 
59
53
  # Deletes the list and every entry in it. Later uploads are no longer compared with it.
60
- # @option options [String] :hash_list_id
54
+ # @param hash_list_id [String]
61
55
  # @return [nil]
62
- def delete(options)
63
- call(options, __method__) do |api, request|
56
+ def delete(hash_list_id, **options)
57
+ call(with_ids(options, hash_list_id: hash_list_id), __method__) do |api, request|
64
58
  request('DELETE', list_path(api), request_options: request)
65
59
  nil
66
60
  end
67
61
  end
68
62
 
69
63
  # Lists one page of a list's entries, newest first unless `sort` says otherwise.
70
- # @option options [String] :hash_list_id
71
- # @option options [String] :cursor the previous page's `nextCursor`
64
+ # @param hash_list_id [String]
65
+ # @option options [String] :cursor the previous page's `next_cursor`
72
66
  # @option options [Integer] :page_size 1 to 100, default 50
73
67
  # @option options [String] :sort `createdAt` and `id`, comma-separated, descending when prefixed
74
68
  # with `-`; `-createdAt` by default
75
- # @return [Hash] a cursor page: items, nextCursor and hasMore.
76
- def list_entries(options)
77
- call(options, __method__) do |api, request|
78
- request('GET', "#{list_path(api)}/entries", query: without(api, 'hashListId'), request_options: request)
69
+ # @return [HashListEntryPage] {Page#auto_paging_each} fetches the rest.
70
+ def list_entries(hash_list_id, **options)
71
+ call(with_ids(options, hash_list_id: hash_list_id), __method__) do |api, request|
72
+ response = request('GET', "#{list_path(api)}/entries", query: without(api, 'hashListId'), request_options: request)
73
+ page(HashListEntryPage, response, options) { list_entries(hash_list_id, **_1) }
79
74
  end
80
75
  end
81
76
 
82
- # Iterates every entry of a list, fetching pages as needed.
83
- # @param options [Hash] the options of {#list_entries}; `cursor` sets the starting position.
84
- # @yieldparam entry [Hash]
85
- # @return [Enumerator, nil] an Enumerator when no block is given.
86
- def each_entry(options, &block)
87
- return enum_for(:each_entry, options) unless block
88
-
89
- each_item(options, __method__, method(:list_entries), &block)
90
- end
91
-
92
77
  # Adds a PDQ hash, or an image asset's hash; a hash already in the list returns its entry.
93
- # @option options [String] :hash_list_id
78
+ # @param hash_list_id [String]
94
79
  # @option options [String] :hash 64 hexadecimal characters; send this or `asset_id`
95
80
  # @option options [Integer] :quality
96
81
  # @option options [String] :asset_id an image asset whose hash to add
97
82
  # @option options [String] :label
98
- # @return [Hash] the entry
99
- def add_entry(options)
100
- call(options, __method__) do |api, request|
101
- request('POST', "#{list_path(api)}/entries", body: without(api, 'hashListId'), request_options: request)
83
+ # @return [HashListEntry] read its hash with `entry[:hash]`, since `hash` is Ruby's own method.
84
+ def add_entry(hash_list_id, **options)
85
+ call(with_ids(options, hash_list_id: hash_list_id), __method__) do |api, request|
86
+ build(HashListEntry, request('POST', "#{list_path(api)}/entries", body: without(api, 'hashListId'), request_options: request))
102
87
  end
103
88
  end
104
89
 
105
- # @option options [String] :entry_id
90
+ # @param entry_id [String]
106
91
  # @return [nil]
107
- def remove_entry(options)
108
- call(options, __method__) do |api, request|
92
+ def remove_entry(entry_id, **options)
93
+ call(with_ids(options, entry_id: entry_id), __method__) do |api, request|
109
94
  request('DELETE', "/hash-list-entries/#{Internal.segment(api['entryId'])}", request_options: request)
110
95
  nil
111
96
  end
@@ -8,7 +8,8 @@ module CalmLens
8
8
  # @api private
9
9
  module Internal
10
10
  # Per-call settings accepted under the `request_options:` option of any method.
11
- REQUEST_OPTIONS = %i[idempotency_key timeout open_timeout upload_timeout max_retries max_response_bytes].freeze
11
+ REQUEST_OPTIONS = %i[idempotency_key timeout open_timeout upload_timeout max_retries max_response_bytes headers extra_query
12
+ extra_body].freeze
12
13
  # A key the API can receive as a header value; the API checks the rest (1 to 255 printable
13
14
  # ASCII characters without a space at either end) and answers `idempotency/invalid-key`.
14
15
  IDEMPOTENCY_KEY = /\A[^\r\n\0]+\z/
@@ -29,9 +30,13 @@ module CalmLens
29
30
  key.to_s.gsub(/_+([a-z0-9])/i) { Regexp.last_match(1).upcase }
30
31
  end
31
32
 
33
+ # Converts one option name to snake_case: `assetId` → `asset_id`.
34
+ def snake(key) = key.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase
35
+
32
36
  # Converts every Hash key to camelCase strings, except inside `metadata`, whose keys are yours.
33
37
  def normalize(value)
34
38
  case value
39
+ when Model then value.to_h
35
40
  when Hash
36
41
  value.to_h do |key, item|
37
42
  name = camelize(key)
@@ -76,6 +81,11 @@ module CalmLens
76
81
 
77
82
  limit = request[:max_response_bytes]
78
83
  raise invalid('max_response_bytes must be a positive Integer') unless limit.nil? || (limit.is_a?(Integer) && limit.positive?)
84
+
85
+ headers(request[:headers]) if request.key?(:headers)
86
+ %i[extra_query extra_body].each do |name|
87
+ raise invalid("#{name} must be a Hash") unless request[name].nil? || request[name].is_a?(Hash)
88
+ end
79
89
  end
80
90
 
81
91
  def positive?(value)
@@ -10,27 +10,17 @@ module CalmLens
10
10
  OPERATIONS = 'lenses'
11
11
 
12
12
  # Lists one page of the project's lenses, newest first unless `sort` says otherwise.
13
- # @option options [String] :cursor the previous page's `nextCursor`
13
+ # @option options [String] :cursor the previous page's `next_cursor`
14
14
  # @option options [Integer] :page_size 1 to 100, default 50
15
15
  # @option options [String] :sort `createdAt` and `id`, comma-separated, descending when prefixed
16
16
  # with `-`; `-createdAt` by default
17
- # @return [Hash] a cursor page: items, nextCursor and hasMore.
18
- def list(options = {})
17
+ # @return [LensPage] {Page#auto_paging_each} fetches the rest.
18
+ def list(**options)
19
19
  call(options, __method__) do |api, request|
20
- cursor_page(request('GET', project('lenses'), query: api, request_options: request), 'lens')
20
+ page(LensPage, request('GET', project('lenses'), query: api, request_options: request), options) { list(**_1) }
21
21
  end
22
22
  end
23
23
 
24
- # Iterates every lens of the project, fetching pages as needed.
25
- # @param options [Hash] the options of {#list}; `cursor` sets the starting position.
26
- # @yieldparam lens [Hash]
27
- # @return [Enumerator, nil] an Enumerator when no block is given.
28
- def each(options = {}, &block)
29
- return enum_for(:each, options) unless block
30
-
31
- each_item(options, __method__, method(:list), &block)
32
- end
33
-
34
24
  # Creates a lens; its identifier must be new to the project (`lens/identifier-taken` otherwise).
35
25
  # @option options [String] :identifier
36
26
  # @option options [String] :name
@@ -38,55 +28,58 @@ module CalmLens
38
28
  # @option options [Boolean] :active whether the CDN serves it; true by default
39
29
  # @option options [String, nil] :description
40
30
  # @option options [Hash, String, nil] :transform
41
- # @return [Hash] the lens
42
- def create(options)
31
+ # @return [Lens]
32
+ def create(**options)
43
33
  call(options, __method__) do |api, request|
44
- lens = request('POST', project('lenses'), body: api, request_options: request)
45
- @session.forget_lenses { |cached| cached['identifier'] == lens['identifier'] } if lens.is_a?(Hash)
34
+ lens = build(Lens, request('POST', project('lenses'), body: api, request_options: request))
35
+ @session.forget_lenses { |cached| cached['identifier'] == lens.identifier }
46
36
  lens
47
37
  end
48
38
  end
49
39
 
50
- # @option options [String] :lens_id
51
- # @return [Hash] the lens
52
- def retrieve(options)
53
- call(options, __method__) { |api, request| request('GET', lens_path(api), request_options: request) }
40
+ # @param lens_id [String]
41
+ # @return [Lens]
42
+ def retrieve(lens_id, **options)
43
+ call(with_ids(options, lens_id: lens_id), __method__) do |api, request|
44
+ build(Lens, request('GET', lens_path(api), request_options: request))
45
+ end
54
46
  end
55
47
 
56
48
  # Changes a lens's name, description, type, transform or whether the CDN serves it.
57
- # @option options [String] :lens_id
58
- # @return [Hash] the lens
59
- def update(options)
60
- call(options, __method__) do |api, request|
61
- lens = request('PATCH', lens_path(api), body: without(api, 'lensId'), request_options: request)
62
- @session.forget_lenses { |cached| cached['id'] == lens['id'] } if lens.is_a?(Hash)
49
+ # @param lens_id [String]
50
+ # @return [Lens]
51
+ def update(lens_id, **options)
52
+ call(with_ids(options, lens_id: lens_id), __method__) do |api, request|
53
+ lens = build(Lens, request('PATCH', lens_path(api), body: without(api, 'lensId'), request_options: request))
54
+ @session.forget_lenses { |cached| cached['id'] == lens.id }
63
55
  lens
64
56
  end
65
57
  end
66
58
 
67
59
  # Deletes a lens; URLs that select it stop being served.
68
- # @option options [String] :lens_id
60
+ # @param lens_id [String]
69
61
  # @return [nil]
70
- def delete(options)
71
- call(options, __method__) do |api, request|
62
+ def delete(lens_id, **options)
63
+ call(with_ids(options, lens_id: lens_id), __method__) do |api, request|
72
64
  request('DELETE', lens_path(api), request_options: request)
73
65
  @session.forget_lenses { |cached| cached['id'] == api['lensId'] }
74
66
  nil
75
67
  end
76
68
  end
77
69
 
78
- # Lens definitions are sent as given, nil fields included.
79
- # @api private
80
- def ensure_lenses(options)
81
- call(options, __method__, keep_nil: true, prefix: nil) { |api, request| @session.ensure_lenses(api['lenses'], request) }
82
- end
70
+ private
83
71
 
84
- # @api private
85
- def ensure_lens(options)
86
- call(options, __method__, keep_nil: true, prefix: nil) { |api, request| @session.ensure_lenses([api], request).first }
72
+ # Lens definitions are sent as given, nil fields included. ServerClient#ensure_lenses calls it.
73
+ def ensure_lenses(**options)
74
+ call(options, __method__, keep_nil: true, prefix: nil) do |api, request|
75
+ @session.ensure_lenses(api['lenses'], request).map { |lens| build(Lens, lens) }
76
+ end
87
77
  end
88
78
 
89
- private
79
+ # ServerClient#ensure_lens calls it.
80
+ def ensure_lens(**definition)
81
+ call(definition, __method__, keep_nil: true, prefix: nil) { |api, request| build(Lens, @session.ensure_lenses([api], request).first) }
82
+ end
90
83
 
91
84
  def lens_path(api) = "/lenses/#{Internal.segment(api['lensId'])}"
92
85
  end