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,7 +20,6 @@ module CalmLens
20
20
  'assets.each' => %w[cursor filter pageSize sort].freeze,
21
21
  'assets.eachChild' => %w[assetId cursor pageSize sort].freeze,
22
22
  'assets.eachTimelineSegment' => %w[assetId cursor pageSize].freeze,
23
- 'assets.explain' => %w[assetId rerun].freeze,
24
23
  'assets.list' => %w[cursor filter pageSize sort].freeze,
25
24
  'assets.listChildren' => %w[assetId cursor pageSize sort].freeze,
26
25
  'assets.listTimeline' => %w[assetId cursor pageSize].freeze,
@@ -10,37 +10,29 @@ module CalmLens
10
10
  OPERATIONS = 'policies'
11
11
 
12
12
  # Lists one page of the organisation's policies, oldest 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 [PolicyPage] {Page#auto_paging_each} fetches the rest.
18
+ def list(**options)
19
19
  call(options, __method__) do |api, request|
20
- cursor_page(request('GET', '/policies', query: api, request_options: request), 'policy')
20
+ page(PolicyPage, request('GET', '/policies', query: api, request_options: request), options) { list(**_1) }
21
21
  end
22
22
  end
23
23
 
24
- # Iterates every policy of the organisation, fetching pages as needed.
25
- # @param options [Hash] the options of {#list}; `cursor` sets the starting position.
26
- # @yieldparam policy [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
- # @option options [String] :policy_id
35
- # @return [Hash] the policy
36
- def retrieve(options)
37
- call(options, __method__) { |api, request| request('GET', policy_path(api), request_options: request) }
24
+ # @param policy_id [String]
25
+ # @return [Policy]
26
+ def retrieve(policy_id, **options)
27
+ call(with_ids(options, policy_id: policy_id), __method__) do |api, request|
28
+ build(Policy, request('GET', policy_path(api), request_options: request))
29
+ end
38
30
  end
39
31
 
40
32
  # The policy the project moderates with.
41
- # @return [Hash] the policy
42
- def retrieve_assigned(options = {})
43
- call(options, __method__) { |_api, request| request('GET', project('policy'), request_options: request) }
33
+ # @return [Policy]
34
+ def retrieve_assigned(**options)
35
+ call(options, __method__) { |_api, request| build(Policy, request('GET', project('policy'), request_options: request)) }
44
36
  end
45
37
 
46
38
  # Creates a policy from `settings` (defining every category) with a `name`, or a copy of the
@@ -48,70 +40,70 @@ module CalmLens
48
40
  # assigned to a project or named on an upload preset.
49
41
  # @option options [String] :name required with `settings`; a preset copy defaults to its name
50
42
  # @option options [String] :description
51
- # @option options [Hash] :settings `categorySettings` with every category, each with its
52
- # `action`, `allowances` and `restrictions`
43
+ # @option options [Hash, PolicySettings] :settings `category_settings` with every category, each
44
+ # with its `action`, `allowances` and `restrictions`, or another policy's `settings`
53
45
  # @option options [String] :preset_id `general-community`, `children-platform`, `education-support`
54
46
  # or `wholesome-community`
55
- # @return [Hash] the policy
56
- def create(options)
57
- call(options, __method__) { |api, request| request('POST', '/policies', body: api, request_options: request) }
47
+ # @return [Policy]
48
+ def create(**options)
49
+ call(options, __method__) { |api, request| build(Policy, request('POST', '/policies', body: api, request_options: request)) }
58
50
  end
59
51
 
60
52
  # Changes the name, description or settings (complete, defining every category); later
61
53
  # moderation uses them. Saving a `live` policy pins it.
62
- # @option options [String] :policy_id
54
+ # @param policy_id [String]
63
55
  # @option options [Integer] :revision the policy's current revision
64
56
  # @option options [String] :name
65
57
  # @option options [String] :description
66
58
  # @option options [Hash] :settings
67
- # @return [Hash] the policy
68
- def update(options)
69
- call(options, __method__) do |api, request|
70
- request('PATCH', policy_path(api), body: without(api, 'policyId'), request_options: request)
59
+ # @return [Policy]
60
+ def update(policy_id, **options)
61
+ call(with_ids(options, policy_id: policy_id), __method__) do |api, request|
62
+ build(Policy, request('PATCH', policy_path(api), body: without(api, 'policyId'), request_options: request))
71
63
  end
72
64
  end
73
65
 
74
66
  # Restores the settings of the preset release a `pinned` or `copy` policy is pinned to.
75
- # @option options [String] :policy_id
67
+ # @param policy_id [String]
76
68
  # @option options [Integer] :revision the policy's current revision
77
69
  # @option options [Integer] :preset_version the pinned `preset.version` you reviewed
78
- # @return [Hash] the policy
79
- def reset(options)
80
- call(options, __method__) do |api, request|
81
- request('POST', "#{policy_path(api)}/reset", body: without(api, 'policyId'), request_options: request)
70
+ # @return [Policy]
71
+ def reset(policy_id, **options)
72
+ call(with_ids(options, policy_id: policy_id), __method__) do |api, request|
73
+ build(Policy, request('POST', "#{policy_path(api)}/reset", body: without(api, 'policyId'), request_options: request))
82
74
  end
83
75
  end
84
76
 
85
77
  # Moves an unchanged `pinned` or `copy` policy to the latest release of its preset.
86
- # @option options [String] :policy_id
78
+ # @param policy_id [String]
87
79
  # @option options [Integer] :revision the policy's current revision
88
80
  # @option options [Integer] :preset_version the `preset.latestVersion` you reviewed
89
- # @return [Hash] the policy
90
- def upgrade(options)
91
- call(options, __method__) do |api, request|
92
- request('POST', "#{policy_path(api)}/upgrade", body: without(api, 'policyId'), request_options: request)
81
+ # @return [Policy]
82
+ def upgrade(policy_id, **options)
83
+ call(with_ids(options, policy_id: policy_id), __method__) do |api, request|
84
+ build(Policy, request('POST', "#{policy_path(api)}/upgrade", body: without(api, 'policyId'), request_options: request))
93
85
  end
94
86
  end
95
87
 
96
88
  # Switches automatic updates on (mode `live`) or off (mode `pinned`) for the organisation's own
97
89
  # preset policy. Switching on replaces the saved settings with the latest preset settings under
98
90
  # the same ID; switching off pins the current preset version with unchanged settings.
99
- # @option options [String] :policy_id
91
+ # @param policy_id [String]
100
92
  # @option options [Boolean] :enabled
101
93
  # @option options [Integer] :revision the policy's current revision
102
94
  # @option options [Integer] :preset_version the preset's `latestVersion`
103
- # @return [Hash] the policy
104
- def set_automatic_updates(options) # rubocop:disable Naming/AccessorMethodName -- the shared SDK surface name
105
- call(options, __method__) do |api, request|
106
- request('PUT', "#{policy_path(api)}/automatic-updates", body: without(api, 'policyId'), request_options: request)
95
+ # @return [Policy]
96
+ def set_automatic_updates(policy_id, **options)
97
+ call(with_ids(options, policy_id: policy_id), __method__) do |api, request|
98
+ build(Policy, request('PUT', "#{policy_path(api)}/automatic-updates", body: without(api, 'policyId'), request_options: request))
107
99
  end
108
100
  end
109
101
 
110
102
  # Deletes a policy that no project or upload preset uses.
111
- # @option options [String] :policy_id
103
+ # @param policy_id [String]
112
104
  # @return [nil]
113
- def delete(options)
114
- call(options, __method__) do |api, request|
105
+ def delete(policy_id, **options)
106
+ call(with_ids(options, policy_id: policy_id), __method__) do |api, request|
115
107
  request('DELETE', policy_path(api), request_options: request)
116
108
  nil
117
109
  end
@@ -120,9 +112,9 @@ module CalmLens
120
112
  # Chooses the policy the project moderates with. Later uploads use it, except those through an
121
113
  # upload preset that names its own policy.
122
114
  # @option options [String] :policy_id
123
- # @return [Hash] the policy
124
- def assign(options)
125
- call(options, __method__) { |api, request| request('PUT', project('policy'), body: api, request_options: request) }
115
+ # @return [Policy]
116
+ def assign(**options)
117
+ call(options, __method__) { |api, request| build(Policy, request('PUT', project('policy'), body: api, request_options: request)) }
126
118
  end
127
119
 
128
120
  private
@@ -9,45 +9,35 @@ module CalmLens
9
9
  OPERATIONS = 'uploadPresets'
10
10
 
11
11
  # Lists one page of the project's upload presets, oldest 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 [UploadPresetPage] {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('upload-presets'), query: api, request_options: request), 'upload preset')
19
+ page(UploadPresetPage, request('GET', project('upload-presets'), query: api, request_options: request), options) { list(**_1) }
20
20
  end
21
21
  end
22
22
 
23
- # Iterates every upload preset of the project, fetching pages as needed.
24
- # @param options [Hash] the options of {#list}; `cursor` sets the starting position.
25
- # @yieldparam upload_preset [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
23
  # Creates each preset, or replaces it with the definition sent, by `key`. Fields left out take
34
24
  # their defaults; an unchanged preset keeps its revision. Every preset is checked before any is
35
25
  # saved. Send each preset's `revision` (0 for one that must not exist yet) to refuse a change
36
26
  # made since with `upload-preset/revision-conflict`.
37
27
  # @option options [Array<Hash>] :upload_presets `[{key:, name:, revision:, access:, enabled:, ...}]`,
38
28
  # at most 50
39
- # @return [Hash] `uploadPresets`: the stored presets, in the order sent.
40
- def ensure(options)
29
+ # @return [UploadPresetsEnsured] `upload_presets`: the stored presets, in the order sent.
30
+ def ensure(**options)
41
31
  call(options, __method__) do |api, request|
42
- request('PUT', project('upload-presets'), body: api, request_options: request)
32
+ build(UploadPresetsEnsured, request('PUT', project('upload-presets'), body: api, request_options: request))
43
33
  end
44
34
  end
45
35
 
46
36
  # Deletes an upload preset. Browsers can no longer upload through it; assets already uploaded stay.
47
- # @option options [String] :upload_preset_id
37
+ # @param upload_preset_id [String]
48
38
  # @return [nil]
49
- def delete(options)
50
- call(options, __method__) do |api, request|
39
+ def delete(upload_preset_id, **options)
40
+ call(with_ids(options, upload_preset_id: upload_preset_id), __method__) do |api, request|
51
41
  request('DELETE', "/upload-presets/#{Internal.segment(api['uploadPresetId'])}", request_options: request)
52
42
  nil
53
43
  end
@@ -61,9 +51,11 @@ module CalmLens
61
51
  # The prefix of this resource's operations in Internal::OPTION_KEYS.
62
52
  OPERATIONS = 'projectSettings'
63
53
 
64
- # @return [Hash] `projectId`, `revision` and `settings`.
65
- def get(options = {})
66
- call(options, __method__) { |_api, request| request('GET', project('settings'), request_options: request) }
54
+ # @return [ProjectSettingsResource] `project_id`, `revision` and `settings`.
55
+ def get(**options)
56
+ call(options, __method__) do |_api, request|
57
+ build(ProjectSettingsResource, request('GET', project('settings'), request_options: request))
58
+ end
67
59
  end
68
60
 
69
61
  # Replaces the project's settings; unchanged settings keep their revision. The project's policy
@@ -72,9 +64,11 @@ module CalmLens
72
64
  # @option options [Hash] :settings the complete settings
73
65
  # @option options [Numeric] :search_indexing_budget_units needed when turning on
74
66
  # `aiMediaSearchEnabled`: the most indexing units you accept for existing media
75
- # @return [Hash] `projectId`, `revision` and `settings`.
76
- def update(options)
77
- call(options, __method__) { |api, request| request('PUT', project('settings'), body: api, request_options: request) }
67
+ # @return [ProjectSettingsResource] `project_id`, `revision` and `settings`.
68
+ def update(**options)
69
+ call(options, __method__) do |api, request|
70
+ build(ProjectSettingsResource, request('PUT', project('settings'), body: api, request_options: request))
71
+ end
78
72
  end
79
73
  end
80
74
 
@@ -85,25 +79,29 @@ module CalmLens
85
79
  # The prefix of this resource's operations in Internal::OPTION_KEYS.
86
80
  OPERATIONS = 'metadataFields'
87
81
 
88
- # @return [Hash] `projectId`, `revision` and `fields`.
89
- def list(options = {})
90
- call(options, __method__) { |_api, request| request('GET', project('metadata-fields'), request_options: request) }
82
+ # @return [MetadataFieldsResource] `project_id`, `revision` and `fields`.
83
+ def list(**options)
84
+ call(options, __method__) do |_api, request|
85
+ build(MetadataFieldsResource, request('GET', project('metadata-fields'), request_options: request))
86
+ end
91
87
  end
92
88
 
93
89
  # Creates each field, or replaces it by ID. Other fields are kept; new ones are added at the end.
94
90
  # @option options [Integer] :revision the revision you read
95
91
  # @option options [Array<Hash>] :fields `[{id:, title:, type:, icon:, color:, description:}]`
96
- # @return [Hash] `projectId`, `revision` and `fields`.
97
- def ensure(options)
98
- call(options, __method__) { |api, request| request('PUT', project('metadata-fields'), body: api, request_options: request) }
92
+ # @return [MetadataFieldsResource] `project_id`, `revision` and `fields`.
93
+ def ensure(**options)
94
+ call(options, __method__) do |api, request|
95
+ build(MetadataFieldsResource, request('PUT', project('metadata-fields'), body: api, request_options: request))
96
+ end
99
97
  end
100
98
 
101
99
  # Deletes a field definition; assets keep the metadata values they hold.
102
- # @option options [String] :field_id
100
+ # @param field_id [String]
103
101
  # @option options [Integer] :revision the revision you read
104
102
  # @return [nil]
105
- def delete(options)
106
- call(options, __method__) do |api, request|
103
+ def delete(field_id, **options)
104
+ call(with_ids(options, field_id: field_id), __method__) do |api, request|
107
105
  request('DELETE', project("metadata-fields/#{Internal.segment(api['fieldId'])}"),
108
106
  query: without(api, 'fieldId'), request_options: request)
109
107
  nil
@@ -38,80 +38,57 @@ module CalmLens
38
38
  api, request = Internal.options(options)
39
39
  nullable = Internal::NULLABLE_OPTION_KEYS.fetch(operation, [])
40
40
  api = api.reject { |key, value| value.nil? && !nullable.include?(key) } unless keep_nil
41
- yield api, request
41
+ outer = Thread.current[:calmlens_operation]
42
+ Thread.current[:calmlens_operation] ||= operation
43
+ begin
44
+ yield api, request
45
+ ensure
46
+ Thread.current[:calmlens_operation] = outer
47
+ end
42
48
  rescue Error
43
49
  raise
44
50
  rescue KeyError, TypeError, ArgumentError, JSON::GeneratorError, EncodingError, URI::Error, FloatDomainError => e
45
51
  raise InvalidArgumentError.new(SdkErrorCodes::INVALID_ARGUMENT, e.message), cause: e
46
52
  end
47
53
 
54
+ # Options are the snake_case keywords a method declares, plus `request_options:`. Ruby passes
55
+ # them as Symbols; camelCase or String names are refused like misspelt ones.
48
56
  def check_option_keys(options, operation)
49
57
  return unless options.is_a?(Hash)
50
58
 
51
59
  allowed = LOCAL_OPTION_KEYS.fetch(operation) { Internal::OPTION_KEYS.fetch(operation) }
52
60
  unknown = options.keys.reject do |key|
53
- %w[request_options requestOptions].include?(key.to_s) || allowed.include?(Internal.camelize(key))
61
+ key == :request_options || (key.is_a?(Symbol) && Internal.snake(key) == key.to_s && allowed.include?(Internal.camelize(key)))
54
62
  end
55
63
  return if unknown.empty?
56
64
 
57
- raise Internal.invalid("Unknown option#{'s' if unknown.size > 1} for #{operation}: #{unknown.join(', ')}")
65
+ raise Internal.invalid("Unknown option#{'s' if unknown.size > 1} for #{operation}: #{unknown.map(&:inspect).join(', ')}")
58
66
  end
59
67
 
60
- def request(...) = @session.request(...)
61
- def project(path) = @session.project(path)
62
-
63
- def without(options, *keys) = options.except(*keys)
68
+ # A method's options with the IDs it takes as arguments, such as `asset_id`.
69
+ def with_ids(options, **ids)
70
+ given = ids.keys & options.keys
71
+ raise Internal.invalid("Pass #{given.join(', ')} as an argument, not an option") unless given.empty?
64
72
 
65
- # Fetches cursor pages lazily, from `start`, until a page has no next cursor, says there is no
66
- # more or is empty. A page with more to follow that hands back a cursor this iteration already
67
- # sent raises `sdk/invalid-response` rather than repeating pages forever.
68
- def pages(start, &fetch)
69
- Enumerator.new do |out|
70
- cursor = start
71
- sent = []
72
- loop do
73
- page = fetch.call(cursor)
74
- items = page.is_a?(Hash) ? page['items'] : nil
75
- raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, 'Page has no items') unless items.is_a?(Array)
76
-
77
- following = page['nextCursor']
78
- more = following.is_a?(String) && !following.empty? && page['hasMore'] == true && !items.empty?
79
- new_cursor!(sent, following) if more
80
- out << page
81
- break unless more
82
-
83
- cursor = following
84
- end
85
- end
73
+ options.merge(ids)
86
74
  end
87
75
 
88
- # A list's response, once it is a cursor page: a Hash with an `items` Array. `what` names the
89
- # items in the `sdk/invalid-response` error otherwise.
90
- def cursor_page(response, what)
91
- return response if response.is_a?(Hash) && response['items'].is_a?(Array)
76
+ def request(...) = @session.request(...)
77
+ def project(path) = @session.project(path)
92
78
 
93
- raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, "Invalid #{what} page")
94
- end
79
+ def without(options, *keys) = options.except(*keys)
95
80
 
96
- # Iterates the items of every page `list` returns for `options`, from its `cursor`, yielding each
97
- # to `block`. `method` names the public iterator, whose options are checked like the list's.
98
- def each_item(options, method, list, &block)
99
- api, request = call(options, method) { |*split| split }
100
- listing = pages(api['cursor']) { |cursor| list.call(api.merge('cursor' => cursor, 'request_options' => request)) }
101
- listing.each { |page| page['items'].each(&block) }
102
- nil
103
- end
81
+ # The `klass` model of a response, with the response as its `last_response`.
82
+ def build(klass, json, **) = klass.new(json, last_response: @session.last_response, **)
104
83
 
105
- # Records a cursor an iteration sends, raising `sdk/invalid-response` (with `details['cursor']`)
106
- # when a page with more to follow hands back one it already sent, which would repeat pages forever.
107
- def new_cursor!(sent, cursor)
108
- if sent.include?(cursor)
109
- raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE,
110
- 'The API returned a cursor it had already returned, with more pages to follow',
111
- details: { 'cursor' => cursor })
84
+ # A list's response as a `klass` page, which fetches the page after a cursor with `options`
85
+ # through `list`.
86
+ def page(klass, response, options, &list)
87
+ unless response.is_a?(Hash) && response['items'].is_a?(Array)
88
+ raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, "Invalid #{klass} response")
112
89
  end
113
90
 
114
- sent << cursor
91
+ build(klass, response, fetch: ->(cursor) { list.call(options.merge(cursor: cursor)) }, cursor: options[:cursor])
115
92
  end
116
93
  end
117
94
  end
@@ -1,6 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CalmLens
4
+ # Pixel dimensions of the representation served by the CDN.
5
+ ServedAssetInfo = Struct.new(:width, :height, keyword_init: true)
6
+
4
7
  # An HTTP response. {CDN#serve} returns one; custom transports and the mock produce them.
5
8
  #
6
9
  # The body is read at most once: either stream it with {#each_chunk} or read it with {#body}.
@@ -32,6 +35,32 @@ module CalmLens
32
35
  Integer(headers['content-length'], 10, exception: false)
33
36
  end
34
37
 
38
+ # Reads served image dimensions from the headers without consuming the body.
39
+ # @return [ServedAssetInfo, nil]
40
+ # Named like CDN#get_asset_info and the other SDKs' response method.
41
+ def get_asset_info # rubocop:disable Naming/AccessorMethodName
42
+ header = "#{headers['x-calmlens-asset-info']},"
43
+ dimensions = {}
44
+ start = 0
45
+ header.scan(/"(?:[^"\\]|\\.)*"|[",]/) do |delimiter|
46
+ return nil if delimiter == '"'
47
+ next unless delimiter == ','
48
+
49
+ match = Regexp.last_match
50
+ member = header[start...match.begin(0)].strip
51
+ start = match.end(0)
52
+ key = member.split(/[=; \t]/, 2).first
53
+ next unless %w[width height].include?(key)
54
+
55
+ dimension = /\A(?:width|height)=([0-9]{1,15})\z/.match(member)
56
+ return nil unless dimension && !dimensions.key?(key) && dimension[1].to_i.positive?
57
+
58
+ dimensions[key] = dimension[1].to_i
59
+ end
60
+ width, height = dimensions.values_at('width', 'height')
61
+ ServedAssetInfo.new(width: width, height: height).freeze if width && height
62
+ end
63
+
35
64
  # @return [Boolean] true for a 2xx status.
36
65
  def success? = status.between?(200, 299)
37
66
 
@@ -18,9 +18,9 @@ module CalmLens
18
18
  DEFAULT_TIMEOUT = 120
19
19
  DEFAULT_OPEN_TIMEOUT = 10
20
20
  DEFAULT_MAX_RETRIES = 2
21
- # Seconds before the first retry; later retries wait twice as long each time, up to RETRY_MAX_DELAY.
21
+ # Seconds before the first retry; later retries wait twice as long each time, up to `max_retry_delay`.
22
22
  DEFAULT_RETRY_BASE_DELAY = 0.5
23
- RETRY_MAX_DELAY = 8
23
+ DEFAULT_MAX_RETRY_DELAY = 8
24
24
  # A `Retry-After` longer than this many seconds is returned to the caller instead of waited out.
25
25
  RETRY_AFTER_MAX = 60
26
26
  # The largest response body read, in bytes (32 MiB).
@@ -58,9 +58,9 @@ module CalmLens
58
58
  # @return [MetadataFields]
59
59
  attr_reader :metadata_fields
60
60
 
61
- # @param api_key [String] a project API key. Keep it on your server.
62
- # @param project_id [String]
63
- # @param base_url [String] the API base URL.
61
+ # @param api_key [String] a project API key, `CALMLENS_API_KEY` by default. Keep it on your server.
62
+ # @param project_id [String] `CALMLENS_PROJECT_ID` by default.
63
+ # @param base_url [String] the API base URL, `CALMLENS_BASE_URL` when set.
64
64
  # @param cdn_base_url [String] the CDN base URL.
65
65
  # @param timeout [Numeric] seconds allowed for each socket read or write, including waiting for a
66
66
  # moderation decision. It is not a deadline for a whole transfer, so large uploads and downloads
@@ -76,27 +76,50 @@ module CalmLens
76
76
  # `idempotency/request-in-progress` are retried with jittered exponential backoff, honouring
77
77
  # `Retry-After`. Other writes are never retried. 0 disables retries.
78
78
  # @param retry_base_delay [Numeric] seconds before the first retry when the API gives no
79
- # `Retry-After`; later retries wait up to twice as long each time, at most 8 seconds.
79
+ # `Retry-After`; later retries wait up to twice as long each time, at most `max_retry_delay`.
80
+ # @param max_retry_delay [Numeric] the longest wait between retries, in seconds, when the API gives
81
+ # no `Retry-After`; 8 by default.
80
82
  # @param part_size_bytes [Integer] content larger than this many bytes whose size the client knows
81
83
  # and can read again (a binary String, base64, or a File, StringIO or other seekable IO) is
82
84
  # uploaded in parts of this size: each part is retried on its own, and calling again with the
83
85
  # same `idempotency_key` resumes an interrupted upload. From 5 MiB to 64 MiB; default 8 MiB.
84
86
  # @param transport [#call, nil] a custom {Transport}; defaults to {Transport::NetHTTP}.
87
+ # @param app_info [Hash, nil] `{name:, version:, url:}` of your integration, added to the
88
+ # `User-Agent` as `name/version (url)`; `version` and `url` are optional.
89
+ # @param logger [Logger, nil] logs each request attempt: its operation, method, path, status,
90
+ # attempt, duration and request ID, never the API key, bodies, upload tokens or CDN URLs. With
91
+ # `CALMLENS_LOG` set and no logger, logs to standard error.
92
+ # @param log_level [String, nil] `info` (each attempt's outcome) or `debug` (also each attempt as
93
+ # it starts); `CALMLENS_LOG` by default, else `info` when a logger is given.
94
+ # @param on_request [#call, nil] called after each attempt with
95
+ # `{operation:, method:, path:, attempt:, delay:, status:, request_id:, error_code:, duration:}`:
96
+ # `operation` is the method, such as `assets.retrieve` (nil for {#request}), `delay` the wait
97
+ # before the next attempt (nil when there is none), `error_code` the attempt's error, `duration`
98
+ # its seconds, and `path` nil for a CDN URL, which may be signed. Use it for metrics or tracing.
85
99
  # @raise [ConfigurationError] `sdk/invalid-config` for a missing or malformed setting.
86
- def initialize(api_key:, project_id:, base_url: DEFAULT_BASE_URL, cdn_base_url: DEFAULT_CDN_BASE_URL,
100
+ def initialize(api_key: ENV.fetch('CALMLENS_API_KEY', nil), project_id: ENV.fetch('CALMLENS_PROJECT_ID', nil),
101
+ base_url: ENV.fetch('CALMLENS_BASE_URL', DEFAULT_BASE_URL), cdn_base_url: DEFAULT_CDN_BASE_URL,
87
102
  timeout: DEFAULT_TIMEOUT, open_timeout: DEFAULT_OPEN_TIMEOUT, upload_timeout: nil,
88
103
  max_retries: DEFAULT_MAX_RETRIES, retry_base_delay: DEFAULT_RETRY_BASE_DELAY,
89
- max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES, part_size_bytes: DEFAULT_PART_SIZE_BYTES, transport: nil)
104
+ max_retry_delay: DEFAULT_MAX_RETRY_DELAY, max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
105
+ part_size_bytes: DEFAULT_PART_SIZE_BYTES, transport: nil, app_info: nil, logger: nil, log_level: nil,
106
+ on_request: nil)
90
107
  check_config(api_key, project_id, timeout, open_timeout, max_retries, retry_base_delay, transport)
108
+ observability = ServerClient.observability(logger, log_level, on_request)
109
+ unless max_retry_delay.is_a?(Numeric) && max_retry_delay.real? && max_retry_delay.to_f.finite? && max_retry_delay >= 0
110
+ raise ConfigurationError.new(SdkErrorCodes::INVALID_CONFIG, 'max_retry_delay must be a non-negative number')
111
+ end
112
+
91
113
  check_limits(upload_timeout, max_response_bytes, part_size_bytes)
92
114
  @project_id = project_id
93
115
  @base_url = ServerClient.check_url(base_url, 'base_url')
94
116
  @cdn_base_url = ServerClient.check_url(cdn_base_url, 'cdn_base_url')
95
117
  @session = Session.new(api_key: api_key, project_id: project_id, base_url: @base_url,
96
118
  cdn_base_url: @cdn_base_url, timeout: timeout, open_timeout: open_timeout,
97
- max_retries: max_retries, retry_base_delay: retry_base_delay,
119
+ max_retries: max_retries, retry_base_delay: retry_base_delay, max_retry_delay: max_retry_delay,
98
120
  max_response_bytes: max_response_bytes, upload_timeout: upload_timeout,
99
- part_size_bytes: part_size_bytes, transport: transport || Transport::NetHTTP.new)
121
+ part_size_bytes: part_size_bytes, transport: transport || Transport::NetHTTP.new,
122
+ user_agent: ServerClient.user_agent(app_info), **observability)
100
123
  @assets = Assets.new(@session)
101
124
  @folders = Folders.new(@session)
102
125
  @hash_lists = HashLists.new(@session)
@@ -135,12 +158,77 @@ module CalmLens
135
158
  # definition again returns the lens unchanged. More than 100 new definitions are sent in
136
159
  # consecutive requests, in order. {#lenses} manages lenses one by one.
137
160
  # @option options [Array<Hash>] :lenses `[{identifier:, name:, type:, transform:, ...}]`, each served unless `active: false`
138
- # @return [Array<Hash>] the saved lenses, in the given order.
139
- def ensure_lenses(options) = @lenses.ensure_lenses(options)
161
+ # @return [Array<Lens>] the saved lenses, in the given order.
162
+ def ensure_lenses(**) = @lenses.__send__(:ensure_lenses, **)
163
+
164
+ # Creates or updates one lens. Takes one lens definition as keywords; see {#ensure_lenses}.
165
+ # @return [Lens] the saved lens
166
+ def ensure_lens(**) = @lenses.__send__(:ensure_lens, **)
167
+
168
+ # Sends a request to any API path with the client's authentication, retries and error mapping,
169
+ # for endpoints this release has no method for. Reads are retried; writes only with
170
+ # `request_options: {idempotency_key:}`.
171
+ # @param method [String] `GET`, `POST`, `PUT`, `PATCH` or `DELETE`
172
+ # @param path [String] beneath the base URL, such as `/projects/prj_1/assets`
173
+ # @param query [Hash] query parameters
174
+ # @param body [Hash, nil] a JSON body
175
+ # @param headers [Hash{String => String}] extra headers; the API key and user agent are the client's
176
+ # @return [Model, Object, nil] a {Model} for a JSON object (with `last_response`), else the parsed JSON
177
+ def request(method, path, query: {}, body: nil, headers: {}, request_options: {})
178
+ verb = method.to_s.upcase
179
+ raise Internal.invalid('method must be GET, POST, PUT, PATCH or DELETE') unless %w[GET POST PUT PATCH DELETE].include?(verb)
180
+ raise Internal.invalid('path must start with / and stay on the API') unless path.is_a?(String) && path.match?(%r{\A/(?!/)})
181
+ raise Internal.invalid('query must be a Hash') unless query.is_a?(Hash)
182
+
183
+ _, options = Internal.options({ request_options: request_options })
184
+ outer = Thread.current[:calmlens_operation]
185
+ # A raw request has no operation name.
186
+ Thread.current[:calmlens_operation] = nil
187
+ json = @session.request(verb, path, query: query.transform_keys(&:to_s), body: body && Internal.normalize(body),
188
+ headers: Internal.headers(headers), request_options: options)
189
+ json.is_a?(Hash) ? Model.new(json, last_response: @session.last_response) : json
190
+ ensure
191
+ Thread.current[:calmlens_operation] = outer
192
+ end
193
+
194
+ # The `User-Agent`, with your integration's name, version and URL.
195
+ # @api private
196
+ def self.user_agent(app_info)
197
+ return Session::USER_AGENT if app_info.nil?
198
+
199
+ info = app_info.to_h.transform_keys(&:to_sym)
200
+ name, version, url = info.values_at(:name, :version, :url)
201
+ unless name.is_a?(String) && name.match?(%r{\A[^\s/()]+\z}) && [version, url].all? do |part|
202
+ part.nil? || (part.is_a?(String) && part.match?(Internal::HEADER_VALUE))
203
+ end
204
+ raise ConfigurationError.new(SdkErrorCodes::INVALID_CONFIG, 'app_info needs a name without spaces, and String version and url')
205
+ end
140
206
 
141
- # Creates or updates one lens. Takes one lens definition; see {#ensure_lenses}.
142
- # @return [Hash] the saved lens
143
- def ensure_lens(options) = @lenses.ensure_lens(options)
207
+ "#{Session::USER_AGENT} #{[name, version].compact.join('/')}#{" (#{url})" if url}"
208
+ end
209
+
210
+ # Writes log lines to standard error when `CALMLENS_LOG` is set without a logger; any Ruby
211
+ # `Logger` works in its place.
212
+ # @api private
213
+ class StderrLogger
214
+ def info(&) = warn(yield)
215
+ def debug(&) = warn(yield)
216
+ end
217
+
218
+ # The logger, level and hook the session reports attempts to.
219
+ # @api private
220
+ def self.observability(logger, log_level, on_request)
221
+ level = (log_level || ENV.fetch('CALMLENS_LOG', nil))&.to_s&.downcase
222
+ raise ConfigurationError.new(SdkErrorCodes::INVALID_CONFIG, 'log_level must be info or debug') unless [nil, 'info',
223
+ 'debug'].include?(level)
224
+ unless on_request.nil? || on_request.respond_to?(:call)
225
+ raise ConfigurationError.new(SdkErrorCodes::INVALID_CONFIG,
226
+ 'on_request must respond to call')
227
+ end
228
+
229
+ logger ||= StderrLogger.new if level
230
+ { logger: logger, log_level: level || (logger && 'info'), on_request: on_request }
231
+ end
144
232
 
145
233
  # @api private
146
234
  def self.check_url(value, name)