calmlens 0.24.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.
@@ -32,7 +32,8 @@ module CalmLens
32
32
  attr_accessor :defer_upload_checks
33
33
 
34
34
  def initialize(api_key:, project_id:, base_url:, cdn_base_url:, timeout:, open_timeout:, max_retries:,
35
- retry_base_delay:, max_response_bytes:, upload_timeout:, part_size_bytes:, transport:)
35
+ retry_base_delay:, max_retry_delay:, max_response_bytes:, upload_timeout:, part_size_bytes:, transport:,
36
+ user_agent: USER_AGENT, logger: nil, log_level: nil, on_request: nil)
36
37
  @api_key = api_key
37
38
  @part_size_bytes = part_size_bytes
38
39
  @project_id = project_id
@@ -42,9 +43,15 @@ module CalmLens
42
43
  @open_timeout = open_timeout
43
44
  @max_retries = max_retries
44
45
  @retry_base_delay = retry_base_delay
46
+ @max_retry_delay = max_retry_delay
45
47
  @max_response_bytes = max_response_bytes
46
48
  @upload_timeout = upload_timeout
47
49
  @transport = transport
50
+ @user_agent = user_agent
51
+ @logger = logger
52
+ @log_level = log_level
53
+ @on_request = on_request
54
+ @last_response_key = :"calmlens_last_response_#{object_id}"
48
55
  @lenses = {}
49
56
  @lens_lock = Mutex.new
50
57
  end
@@ -70,6 +77,9 @@ module CalmLens
70
77
 
71
78
  def project(path) = "/projects/#{Internal.segment(@project_id)}/#{path}"
72
79
 
80
+ # What the API answered to this thread's latest request, for the result's `last_response`.
81
+ def last_response = Thread.current[@last_response_key]
82
+
73
83
  # Sends an API request and returns the parsed JSON body (nil for an empty 204 or DELETE response).
74
84
  #
75
85
  # @param idempotent [Boolean] send an `Idempotency-Key` (generated unless the caller gave one),
@@ -78,9 +88,10 @@ module CalmLens
78
88
  def request(method, path, request_options:, query: {}, body: nil, raw: nil, headers: {}, idempotent: false,
79
89
  upload: false)
80
90
  url = @base_url + path
81
- params = Internal.query(query)
91
+ params = Internal.query(query.merge(request_options.fetch(:extra_query, {}).transform_keys(&:to_s)))
82
92
  url += "?#{URI.encode_www_form(params)}" unless params.empty?
83
- headers = headers.merge('Accept' => 'application/json')
93
+ headers = Internal.headers(request_options.fetch(:headers, {})).merge(headers).merge('Accept' => 'application/json')
94
+ body = with_extra_body(body, request_options[:extra_body]) if raw.nil?
84
95
  unless body.nil?
85
96
  raw = JSON.generate(body)
86
97
  headers['Content-Type'] = 'application/json'
@@ -94,7 +105,15 @@ module CalmLens
94
105
  headers['Idempotency-Key'] = request_options[:idempotency_key] || SecureRandom.uuid if idempotent || request_options[:idempotency_key]
95
106
  limit = request_options.fetch(:max_response_bytes, @max_response_bytes)
96
107
  deadline = request_options.fetch(:upload_timeout, @upload_timeout) if upload
97
- execute(method, url, headers, raw, request_options, deadline: deadline) { |response| parse(method, response, limit) }
108
+ key = headers['Idempotency-Key']
109
+ execute(method, url, headers, raw, request_options, deadline: deadline) { |response| parse(method, response, limit, key) }
110
+ end
111
+
112
+ # A JSON body with the caller's `extra_body` fields added.
113
+ def with_extra_body(body, extra)
114
+ return body if extra.nil? || extra.empty? || !(body.nil? || body.is_a?(Hash))
115
+
116
+ (body || {}).merge(extra.transform_keys(&:to_s))
98
117
  end
99
118
 
100
119
  # Sends a CDN request, retrying like an API read, and returns the last response rather than
@@ -173,7 +192,7 @@ module CalmLens
173
192
 
174
193
  def headers_for(extra, authenticate: true)
175
194
  headers = extra.reject { |name, _| %w[x-api-key user-agent authorization].include?(name.downcase) }
176
- .merge('User-Agent' => USER_AGENT)
195
+ .merge('User-Agent' => @user_agent)
177
196
  authenticate ? headers.merge('X-Api-Key' => @api_key) : headers
178
197
  end
179
198
 
@@ -217,15 +236,9 @@ module CalmLens
217
236
  loop do
218
237
  body&.rewind if attempt.positive?
219
238
  context = { again: retryable && attempt < retries, attempt: attempt, limit: limit, deadline: deadline,
220
- allow_http_errors: allow_http_errors }
221
- outcome, value = send_attempt(request, context, &handler)
222
- if outcome == :error
223
- delay = http_delay(value.retry_after, attempt)
224
- raise value unless context[:again] && delay <= ServerClient::RETRY_AFTER_MAX && value.retryable?
225
-
226
- outcome = :retry
227
- value = delay
228
- end
239
+ allow_http_errors: allow_http_errors, started: Process.clock_gettime(Process::CLOCK_MONOTONIC),
240
+ authenticate: authenticate }
241
+ outcome, value = observed_attempt(request, context, &handler)
229
242
  return value if outcome == :ok
230
243
 
231
244
  pause(value)
@@ -233,12 +246,78 @@ module CalmLens
233
246
  end
234
247
  end
235
248
 
249
+ # One attempt, reported to the hook and logger: `[:ok, result]` or `[:retry, seconds]`; an error
250
+ # that won't be retried is raised.
251
+ def observed_attempt(request, context, &)
252
+ log(:debug) do
253
+ "calmlens: sending #{request.method} #{loggable_path(request.url,
254
+ context[:authenticate]) || '[cdn]'} attempt=#{context[:attempt] + 1}"
255
+ end
256
+ begin
257
+ outcome, value = send_attempt(request, context, &)
258
+ rescue Error => e
259
+ observe(request, context, nil, e)
260
+ raise
261
+ end
262
+ if outcome == :error
263
+ delay = http_delay(value.retry_after, context[:attempt])
264
+ unless context[:again] && delay <= ServerClient::RETRY_AFTER_MAX && value.retryable?
265
+ observe(request, context, nil, value)
266
+ raise value
267
+ end
268
+
269
+ context[:error] = value
270
+ outcome = :retry
271
+ value = delay
272
+ end
273
+ observe(request, context, outcome == :retry ? value : nil, context[:error])
274
+ [outcome, value]
275
+ end
276
+
277
+ # Reports one attempt to the `on_request` hook and the logger: never the API key, bodies or a
278
+ # CDN URL, which may be signed.
279
+ def observe(request, context, delay, error)
280
+ return unless @on_request || @logger
281
+
282
+ event = { operation: Thread.current[:calmlens_operation], method: request.method,
283
+ path: loggable_path(request.url, context[:authenticate]), attempt: context[:attempt] + 1, delay: delay,
284
+ status: context[:status] || error&.status, request_id: context[:request_id] || error&.request_id,
285
+ error_code: error&.code, duration: (Process.clock_gettime(Process::CLOCK_MONOTONIC) - context[:started]).round(6) }
286
+ @on_request&.call(event)
287
+ log(:info) do
288
+ outcome = if delay
289
+ "retrying in #{delay}s"
290
+ else
291
+ (error ? "failed with #{error.code}" : 'done')
292
+ end
293
+ "calmlens: #{event[:operation] || request.method} #{event[:method]} #{event[:path] || '[cdn]'} " \
294
+ "status=#{event[:status].inspect} attempt=#{event[:attempt]} duration=#{event[:duration]}s " \
295
+ "request_id=#{event[:request_id].inspect} #{outcome}"
296
+ end
297
+ end
298
+
299
+ # The path of an API request, without its query; nil for a CDN URL without the API key, which may be signed.
300
+ def loggable_path(url, authenticate)
301
+ authenticate ? URI(url).path : nil
302
+ rescue URI::Error
303
+ nil
304
+ end
305
+
306
+ def log(level, &)
307
+ return unless @logger
308
+ return if level == :debug && @log_level != 'debug'
309
+
310
+ @logger.public_send(level, &)
311
+ end
312
+
236
313
  # One attempt: `[:ok, result]`, `[:error, error]` for an error response, or `[:retry, seconds]`.
237
314
  # A response returned to the caller (or its streaming block) is never retried.
238
315
  def send_attempt(request, context, &handler)
239
316
  delivered = false
240
317
  within(context[:deadline]) do
241
318
  send_request(request) do |response|
319
+ context[:status] = response.status
320
+ context[:request_id] = response.headers['x-request-id']
242
321
  raise redirect_error(response) if redirect?(response)
243
322
 
244
323
  if context[:allow_http_errors] && !response.success?
@@ -246,7 +325,7 @@ module CalmLens
246
325
  retry_status = RETRYABLE_STATUSES.include?(response.status) && delay <= ServerClient::RETRY_AFTER_MAX
247
326
  next [:retry, delay] if context[:again] && retry_status
248
327
  end
249
- next [:error, http_error(response, context[:limit])] unless response.success? || context[:allow_http_errors]
328
+ next [:error, http_error(response, context[:limit], request)] unless response.success? || context[:allow_http_errors]
250
329
 
251
330
  delivered = true
252
331
  [:ok, handler.call(response)]
@@ -255,6 +334,7 @@ module CalmLens
255
334
  rescue Error => e
256
335
  raise unless context[:again] && !delivered && e.retryable?
257
336
 
337
+ context[:error] = e
258
338
  [:retry, backoff(context[:attempt])]
259
339
  end
260
340
 
@@ -308,7 +388,7 @@ module CalmLens
308
388
 
309
389
  # Exponential backoff with jitter: half the delay is fixed, the other half random.
310
390
  def backoff(attempt)
311
- delay = [@retry_base_delay * (2**attempt), ServerClient::RETRY_MAX_DELAY].min
391
+ delay = [@retry_base_delay * (2**attempt), @max_retry_delay].min
312
392
  ((delay / 2.0) + (rand * delay / 2.0)).round(3)
313
393
  end
314
394
 
@@ -330,7 +410,9 @@ module CalmLens
330
410
  status: response.status, headers: response.headers)
331
411
  end
332
412
 
333
- def parse(method, response, limit)
413
+ def parse(method, response, limit, idempotency_key = nil)
414
+ Thread.current[@last_response_key] = LastResponse.new(status: response.status, headers: response.headers.dup.freeze,
415
+ request_id: response.request_id, idempotency_key: idempotency_key)
334
416
  text = read(response, limit).dup.force_encoding(Encoding::UTF_8)
335
417
  return nil if text.empty? && (response.status == 204 || method == 'DELETE')
336
418
 
@@ -340,9 +422,11 @@ module CalmLens
340
422
  status: response.status, headers: response.headers)
341
423
  end
342
424
 
343
- # The error for a non-2xx response: the API's code and details, or `sdk/http-error`.
344
- def http_error(response, limit)
425
+ # The error for a non-2xx response: the API's code and details, or `sdk/http-error`, with the
426
+ # body as received. A CDN request's URL is left out: a signed URL grants access.
427
+ def http_error(response, limit, request)
345
428
  text = read(response, limit).dup.force_encoding(Encoding::UTF_8)
429
+ where = { body: text, http_method: request.method, url: (request.url if request.url.start_with?(@base_url)) }
346
430
  data = begin
347
431
  JSON.parse(text)
348
432
  rescue JSON::ParserError, EncodingError
@@ -350,7 +434,7 @@ module CalmLens
350
434
  end
351
435
  unless data.is_a?(Hash) && data['code'].is_a?(String)
352
436
  return Error.build(SdkErrorCodes::HTTP_ERROR, "HTTP #{response.status}", status: response.status,
353
- headers: response.headers)
437
+ headers: response.headers, **where)
354
438
  end
355
439
 
356
440
  # The X-Request-Id header, or the body's `requestId` when a proxy dropped the header.
@@ -358,7 +442,7 @@ module CalmLens
358
442
  message = data['message'].is_a?(String) ? data['message'] : nil
359
443
  details = data['details'].is_a?(Hash) ? data['details'] : nil
360
444
  Error.build(data['code'], message, status: response.status, details: details, headers: response.headers,
361
- request_id: request_id)
445
+ request_id: request_id, **where)
362
446
  rescue InvalidResponseError => e
363
447
  e
364
448
  end
@@ -27,7 +27,7 @@ module CalmLens
27
27
  'classification.status' => { kind: 'text', nullable: false, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
28
28
  'classification.updatedAt' => { kind: 'number', nullable: true, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
29
29
  'classification.completedAt' => { kind: 'number', nullable: true, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
30
- 'classification.moderation.status' => { kind: 'text', nullable: false, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
30
+ 'classification.moderation.decision' => { kind: 'text', nullable: true, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
31
31
  'content.status' => { kind: 'text', nullable: false, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
32
32
  'content.removalReason' => { kind: 'text', nullable: true, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
33
33
  'content.updatedAt' => { kind: 'number', nullable: true, operators: ['==', '!=', '>', '>=', '<', '<=', '=in=', '=out='].freeze }.freeze,
@@ -24,7 +24,7 @@ module CalmLens
24
24
  end
25
25
 
26
26
  # In-memory records behind {MockServerClient}. Change them to arrange a test, such as setting an
27
- # asset's `classification.moderation.status`.
27
+ # asset's `classification.moderation.decision`.
28
28
  #
29
29
  # @!attribute assets [Hash{String => Hash}] assets by ID, with API field names.
30
30
  # @!attribute folders [Hash{String => Hash}] folders by ID.
@@ -48,7 +48,7 @@ module CalmLens
48
48
  SEARCH_FIELDS = { 'name' => %w[name], 'id' => %w[id], 'externalId' => %w[externalId],
49
49
  'description' => %w[description], 'tags' => %w[tags], 'type' => %w[type],
50
50
  'content.format' => %w[content format], 'content.extension' => %w[content extension],
51
- 'classification.moderation.status' => %w[classification moderation status] }.freeze
51
+ 'classification.moderation.decision' => %w[classification moderation decision] }.freeze
52
52
  MAX_SEARCH_TOKENS = 8
53
53
  MAX_SEARCH_PAGE_SIZE = 20
54
54
  MAX_SEARCH_QUERY_LENGTH = 200
@@ -166,9 +166,6 @@ module CalmLens
166
166
  @asset_event_sequences = Hash.new(0)
167
167
  # The processing options each asset was uploaded with, which the API keeps but doesn't return.
168
168
  @processing_options = {}
169
- # Decided assets whose re-run (`assets.explain` with `rerun: true`) is still queued: they keep
170
- # their decision until `complete_processing` decides them.
171
- @reruns = {}
172
169
  end
173
170
 
174
171
  # Adds an event to the feed, filling the fields the API always sets. Its `actor` is the mock's
@@ -194,7 +191,7 @@ module CalmLens
194
191
  if item && !event.key?('asset')
195
192
  asset = snapshot(item)
196
193
  announced = ANNOUNCED_STATUSES[event['type']]
197
- asset['classification']['moderation']['status'] = announced if announced
194
+ asset['classification']['moderation']['decision'] = announced if announced
198
195
  event = event.merge('asset' => asset)
199
196
  end
200
197
  add_event(event)
@@ -215,17 +212,13 @@ module CalmLens
215
212
  end
216
213
 
217
214
  # Finishes processing an asset as the pipeline would, with `decision` or else what `moderate`
218
- # answers for the `complete` trigger, and returns it; nil when there is no such asset. A decided
219
- # asset whose re-run is still queued counts as processing.
215
+ # answers for the `complete` trigger, and returns it; nil when there is no such asset.
220
216
  def complete_processing(asset_id, decision)
221
217
  item = own_asset(asset_id)
222
218
  return unless item
219
+ raise Internal.invalid("Asset #{asset_id} isn't processing") unless item['classification']['status'] == 'processing'
223
220
 
224
- rerun = @reruns.key?(asset_id)
225
- raise Internal.invalid("Asset #{asset_id} isn't processing") unless rerun || item['classification']['status'] == 'processing'
226
-
227
- settled = decision.nil? ? nil : MockDecision.from(decision)
228
- rerun ? settle_rerun(item, 'complete', settled) : moderate_stored(item, 'complete', settled)
221
+ moderate_stored(item, 'complete', decision.nil? ? nil : MockDecision.from(decision))
229
222
  deep_copy(item)
230
223
  end
231
224
 
@@ -269,8 +262,6 @@ module CalmLens
269
262
  # review is the mock API key's, which has no ID. A decision through the API (`by_api_key`) has
270
263
  # the API key as its events' actor; the test hook's is a reviewer's (a `user`).
271
264
  def record_decision(item, decision, note, by_api_key)
272
- # Like the API: a queued re-run no longer replaces a reviewed decision.
273
- @reruns.delete(item['id'])
274
265
  apply_outcome(item, decision, 'requested')
275
266
  # Like the API: the human review queue's decision settles its review, one through the API
276
267
  # leaves it waiting.
@@ -302,8 +293,8 @@ module CalmLens
302
293
  invalid!('validation/invalid-value', 'confirmPurge') if decision == 'purged' && json['confirmPurge'] != true
303
294
  processing = item['upload']['status'] == 'uploading' || item['classification']['status'] == 'processing'
304
295
  fail!(ErrorCodes::ASSET_PROCESSING) if processing
305
- status = item['classification']['moderation']['status']
306
- fail!(ErrorCodes::ASSET_DECISION_NOT_ALLOWED) if status == 'pending' && !%w[blocked purged].include?(decision)
296
+ status = item['classification']['moderation']['decision']
297
+ fail!(ErrorCodes::ASSET_DECISION_NOT_ALLOWED) if status.nil? && !%w[blocked purged].include?(decision)
307
298
  fail!(ErrorCodes::ASSET_DECISION_UNCHANGED) if status == decision
308
299
  fail!(ErrorCodes::ASSET_CONTENT_PURGED) if status == 'purged' && decision != 'blocked'
309
300
 
@@ -316,7 +307,7 @@ module CalmLens
316
307
  { 'id' => item['id'], 'externalId' => item['externalId'], 'uploadPresetId' => item['uploadPresetId'],
317
308
  'upload' => { 'status' => item['upload']['status'] },
318
309
  'classification' => { 'status' => item['classification']['status'], 'testInput' => item['classification']['testInput'],
319
- 'moderation' => { 'status' => item['classification']['moderation']['status'] } },
310
+ 'moderation' => { 'decision' => item['classification']['moderation']['decision'] } },
320
311
  'content' => { 'status' => item['content']['status'] } }
321
312
  end
322
313
 
@@ -732,7 +723,7 @@ module CalmLens
732
723
  def show_project_settings
733
724
  settings = { 'retainContent' => true, 'optOutJurisdictions' => [], 'blockUnmoderatedAssets' => true,
734
725
  'storeSensitiveMetadata' => false,
735
- 'streamingEnabled' => false, 'aiMediaSearchEnabled' => false, 'remoteUrlRule' => nil,
726
+ 'streamingEnabled' => false, 'aiMediaSearchEnabled' => false, 'linkCheckingEnabled' => false, 'remoteUrlRule' => nil,
736
727
  'websiteSubmissionsPerMinute' => nil }.merge(@project_settings)
737
728
  settings['humanReview'] = { 'allowedSamplePercent' => 0, 'restrictedSamplePercent' => 0, 'uncertaintyMarginPercent' => 0,
738
729
  'reviewMissingEvidence' => false }.merge(@project_settings['humanReview'] || {})
@@ -800,7 +791,12 @@ module CalmLens
800
791
  normalized = text.downcase
801
792
  tokens = normalized.split(/\s+/).uniq.first(MAX_SEARCH_TOKENS)
802
793
  items = project_assets.filter_map do |item|
803
- values = SEARCH_FIELDS.transform_values { |path| Array(item.dig(*path)).join(' ').downcase }
794
+ # An undecided asset's decision is searched as `pending`, as the API does.
795
+ values = SEARCH_FIELDS.to_h do |field, path|
796
+ value = item.dig(*path)
797
+ value = 'pending' if value.nil? && field == 'classification.moderation.decision'
798
+ [field, Array(value).join(' ').downcase]
799
+ end
804
800
  next unless tokens.all? { |token| values.each_value.any? { |value| value.include?(token) } }
805
801
 
806
802
  fields = values.filter_map { |field, value| field if tokens.any? { |token| value.include?(token) } }
@@ -882,7 +878,7 @@ module CalmLens
882
878
  'completedAt' => nil, 'progress' => nil, 'testInput' => false,
883
879
  # Like the API, moderation's results are null until it decides, and a
884
880
  # feature's result is null until it has run.
885
- 'moderation' => { 'status' => 'pending', 'manualReviews' => [], 'automatedStatus' => nil,
881
+ 'moderation' => { 'decision' => nil, 'manualReviews' => [], 'automatedStatus' => nil,
886
882
  'policy' => nil, 'pendingReview' => nil, 'source' => nil, 'rule' => nil,
887
883
  'explanationComplete' => nil,
888
884
  'categories' => nil, 'flaggedCategories' => [], 'regions' => [],
@@ -1173,7 +1169,7 @@ module CalmLens
1173
1169
  def update_classification(classification, processing, moderation, now)
1174
1170
  classification.merge!('status' => processing, 'failureReason' => processing == 'failed' ? 'processing-error' : nil,
1175
1171
  'updatedAt' => now, 'completedAt' => processing == 'completed' ? now : nil)
1176
- classification['moderation']['status'] = moderation
1172
+ classification['moderation']['decision'] = moderation == 'pending' ? nil : moderation
1177
1173
  end
1178
1174
 
1179
1175
  # Like the API, the earlier posts CalmLens used go with the stored content.
@@ -1243,7 +1239,6 @@ module CalmLens
1243
1239
  in ['DELETE', 'content'] then remove_content(item)
1244
1240
  in ['GET', 'children'] then page(project_assets.select { |child| child['parentId'] == id }, query, id)
1245
1241
  in ['POST', 'retry'] then retry_asset(item)
1246
- in ['POST', 'explain'] then explain(item, json['rerun'])
1247
1242
  in ['POST', 'decision'] then decide_request(item, json)
1248
1243
  in ['POST', 'move']
1249
1244
  check_folder(json['folderId']) if json['folderId']
@@ -1286,7 +1281,7 @@ module CalmLens
1286
1281
 
1287
1282
  # Like the API: back to processing, to be moderated again, with an `asset.retried` event.
1288
1283
  def retry_asset(item)
1289
- unless item['classification']['status'] == 'failed' && item['classification']['moderation']['status'] == 'pending'
1284
+ unless item['classification']['status'] == 'failed' && item['classification']['moderation']['decision'].nil?
1290
1285
  fail!(ErrorCodes::ASSET_NOT_RETRYABLE)
1291
1286
  end
1292
1287
  fail!(ErrorCodes::ASSET_CONTENT_UNAVAILABLE) if item['content']['status'] == 'removed'
@@ -1296,43 +1291,6 @@ module CalmLens
1296
1291
  moderate_stored(item, 'retry')
1297
1292
  end
1298
1293
 
1299
- def explain(item, rerun)
1300
- fail!(ErrorCodes::ASSET_NOT_DECIDED) unless item['classification']['status'] == 'completed'
1301
- moderation = item['classification']['moderation']
1302
- unless rerun
1303
- # Like the API: the evidence is completed and every action stays as decided.
1304
- return item unless moderation['explanationComplete'] == false
1305
-
1306
- moderation['explanationComplete'] = true
1307
- return touch(item)
1308
- end
1309
- fail!(ErrorCodes::ASSET_REVIEWED) unless moderation.fetch('manualReviews', []).empty?
1310
- fail!(ErrorCodes::ASSET_CONTENT_UNAVAILABLE) if item['content']['status'] == 'removed'
1311
-
1312
- # Like the API: the request is recorded, and the asset returns as it was. It keeps its decision
1313
- # while it's moderated again under the current policy.
1314
- add_event('type' => 'asset.rerun-requested', 'severity' => 'low', 'assetId' => item['id'],
1315
- 'asset' => snapshot(item), 'actor' => deep_copy(API_KEY_ACTOR),
1316
- 'facts' => [asset_name_fact(item), { 'key' => 'asset-type', 'value' => item['type'] },
1317
- { 'key' => 'moderation-status', 'value' => moderation['status'] }])
1318
- response = deep_copy(item)
1319
- settle_rerun(item, 'rerun')
1320
- response
1321
- end
1322
-
1323
- # Applies a re-run's decision to a decided asset like the pipeline: `pending` stays queued for
1324
- # `complete_processing`, `failed` keeps the asset's decision, and any other replaces it with the
1325
- # pipeline's events.
1326
- def settle_rerun(item, trigger, decision = nil)
1327
- decision ||= decision_for(item, trigger, true)
1328
- @reruns.delete(item['id'])
1329
- if decision.status == 'pending'
1330
- @reruns[item['id']] = true
1331
- elsif decision.status != 'failed'
1332
- moderate_stored(item, trigger, decision)
1333
- end
1334
- end
1335
-
1336
1294
  # Signs an asset URL like the API (`POST /projects/:projectId/signed-asset-urls`): a grant to one
1337
1295
  # asset, by ID or external ID, until it expires, serving the original only when asked. Only the
1338
1296
  # mock's CDN accepts the grant.
@@ -1820,13 +1778,15 @@ module CalmLens
1820
1778
  deliver(method, item, resource, params, selected ? options || {} : nil, authorised)
1821
1779
  end
1822
1780
 
1823
- # What a grant doesn't cover, or, like the CDN, a private asset for anyone without a grant or the
1824
- # project's API key: it answers as an unknown asset does, whatever its state, except for its
1825
- # info, which has its own rule. An error response, or nil.
1781
+ # What a grant doesn't cover, or, like the CDN, removed content for anyone (isAssetContentNotKept)
1782
+ # and a private asset for anyone without a grant or the project's API key: each answers as an
1783
+ # unknown asset does, whatever its state, except for its info, which has its own rule. An error
1784
+ # response, or nil.
1826
1785
  def refuse_viewer(item, resource, grant, headers)
1827
1786
  if resource == 'original' && grant && !grant[:original]
1828
1787
  return error(ErrorCodes::SIGNED_URL_ORIGINAL_NOT_GRANTED, "This signed asset URL doesn't grant the original file", status: 403)
1829
1788
  end
1789
+ return asset_not_found if resource != 'info' && item['content']['status'] == 'removed'
1830
1790
  return if grant || item['visibility'] == 'public' || header(headers, 'X-Api-Key') == @api_key
1831
1791
 
1832
1792
  asset_not_found unless resource == 'info'
@@ -1872,7 +1832,7 @@ module CalmLens
1872
1832
  restricted = item['visibility'] != 'public'
1873
1833
  return asset_not_found if restricted && !authorised
1874
1834
 
1875
- restricted ||= %w[blocked purged].include?(item['classification']['moderation']['status'])
1835
+ restricted ||= %w[blocked purged].include?(item['classification']['moderation']['decision'])
1876
1836
  return not_available if restricted && !authorised
1877
1837
 
1878
1838
  claims = JSON.parse(params.fetch('viewerClaims', '{}'))
@@ -1888,7 +1848,7 @@ module CalmLens
1888
1848
 
1889
1849
  # Whether a viewer can see an asset's content now, decided as the other resources decide it.
1890
1850
  def availability(item, age_confirmed)
1891
- moderation = item['classification']['moderation']['status']
1851
+ moderation = item['classification']['moderation']['decision']
1892
1852
  if item['content']['safetyHold'] || item['upload']['status'] == 'uploading' || %w[blocked purged].include?(moderation) ||
1893
1853
  item['classification']['status'] == 'failed' || item['content']['status'] == 'removed'
1894
1854
  'unavailable'
@@ -1933,10 +1893,9 @@ module CalmLens
1933
1893
  # The delivery checks, which refuse everyone, then age and access, as an error response, or nil.
1934
1894
  # Only the original needs the upload still stored.
1935
1895
  def refuse_delivery(item, resource, stored, params, authorised)
1936
- moderation = item['classification']['moderation']['status']
1896
+ moderation = item['classification']['moderation']['decision']
1937
1897
  if (resource == 'original' && stored.nil?) || item['upload']['status'] == 'uploading' ||
1938
- %w[blocked purged].include?(moderation) || item['classification']['status'] == 'failed' ||
1939
- item['content']['status'] == 'removed'
1898
+ %w[blocked purged].include?(moderation) || item['classification']['status'] == 'failed'
1940
1899
  return not_available
1941
1900
  end
1942
1901
  if moderation == 'age-restricted' && !viewer_age_confirmed?(params)
@@ -1992,12 +1951,12 @@ module CalmLens
1992
1951
  # A preview requires access for private or blocked assets and disappears with its content.
1993
1952
  def placeholder(method, item, authorised)
1994
1953
  private_asset = item['visibility'] != 'public'
1995
- blocked = item['classification']['moderation']['status'] == 'blocked'
1954
+ blocked = item['classification']['moderation']['decision'] == 'blocked'
1996
1955
  return asset_not_found if private_asset && !authorised
1997
1956
  return not_available if blocked && !authorised
1998
1957
 
1999
1958
  thumbhash = item.dig('content', 'preview', 'thumbhash')
2000
- return not_available if thumbhash.nil? || item['classification']['moderation']['status'] == 'purged'
1959
+ return not_available if thumbhash.nil? || item['classification']['moderation']['decision'] == 'purged'
2001
1960
 
2002
1961
  cdn_response(method, Placeholder.png(thumbhash),
2003
1962
  'content-type' => 'image/png', 'cache-control' => private_asset || blocked ? 'private, no-store' : 'public, no-cache',
@@ -184,10 +184,10 @@ module CalmLens
184
184
  # - `asset` [Hash] the asset as stored, still processing (a copy).
185
185
  # - `content` [Content] the uploaded bytes and, for a `plaintext-document`, their text.
186
186
  # - `trigger` [String] why the mock is moderating it: `upload` (`assets.create`, `assets.classify`,
187
- # `text.classify` or a final part), `retry` (`assets.retry`), `rerun` (`assets.explain` with
188
- # `rerun: true`) or `complete` ({MockServerClient#complete_processing} without a decision).
187
+ # `text.classify` or a final part), `retry` (`assets.retry`) or `complete`
188
+ # ({MockServerClient#complete_processing} without a decision).
189
189
  # - `queued` [Boolean] true when the API would queue the work rather than answer with the
190
- # decision: queued uploads, retries, reruns and `complete`.
190
+ # decision: queued uploads, retries and `complete`.
191
191
  MockModerationInput = Struct.new(:asset, :content, :trigger, :queued, keyword_init: true) do
192
192
  # @return [Boolean]
193
193
  def queued? = queued
@@ -14,13 +14,14 @@ module CalmLens
14
14
  # By default the stand-in is stateful: uploads create assets you can retrieve, list, filter,
15
15
  # search, move and delete, folders and hash lists behave like the API's, the CDN serves stored bytes, and errors use
16
16
  # the API's codes, HTTP statuses and body shape. It does not classify content: the `moderate:`
17
- # callback decides each upload, retry and rerun with a status or a {MockDecision}, and the events
17
+ # callback decides each upload and retry with a status or a {MockDecision}, and the events
18
18
  # feed gets the pipeline's `asset.uploaded`, `asset.classified`, `asset.<status>` and `asset.failed`
19
19
  # events. Without it, queued uploads stay `pending` until {#complete_processing} and the rest are
20
20
  # `allowed`. Content retention follows upload, preset and project settings; when disabled, content is removed
21
21
  # once classification is `completed`, as in the API.
22
22
  # A `purged` outcome removes the content with reason `policy`. The CDN answers like the real one:
23
- # `asset/not-available` (403) for blocked, purged, failed or removed content,
23
+ # `asset/not-found` (404) for removed content, as for an unknown asset,
24
+ # `asset/not-available` (403) for blocked, purged or failed content,
24
25
  # `viewer/age-confirmation-required` (403) for an age-restricted asset without
25
26
  # `viewer_claims: {age_confirmed: true}`, whatever the key, and `auth/permission-denied` (403)
26
27
  # for a private asset unless `api_key` comes from {.create_api_key} with an `assets:download`
@@ -42,7 +43,7 @@ module CalmLens
42
43
  # @example
43
44
  # mock = CalmLens::MockServerClient.new(moderate: ->(input) { input.content.text&.include?('spam') ? 'blocked' : 'allowed' })
44
45
  # asset = mock.assets.classify(name: 'note', content: {plain_text: 'hi', type: 'text/plain'})
45
- # mock.assets.retrieve(asset_id: asset['id']).dig('classification', 'moderation', 'status') # => "allowed"
46
+ # mock.assets.retrieve(asset_id: asset['id']).dig('classification', 'moderation', 'decision') # => "allowed"
46
47
  # mock.enqueue(status: 503, body: {code: 'server/unavailable', message: 'Try again'})
47
48
  class MockServerClient < ServerClient
48
49
  # A request the mock received.
@@ -80,7 +81,7 @@ module CalmLens
80
81
  REQUEST_FAILURES = %w[transport-error timeout].freeze
81
82
  # The methods {#fail_next_request} can target, by resource. Iterators are their list calls.
82
83
  OPERATIONS = { assets: %i[search list retrieve list_children list_timeline update create classify upload_part move
83
- retry explain decide wait_for_decision remove_content delete batch],
84
+ retry decide wait_for_decision remove_content delete batch],
84
85
  folders: %i[list retrieve create update delete move],
85
86
  hash_lists: %i[list retrieve create update delete list_entries add_entry remove_entry],
86
87
  policies: %i[list retrieve retrieve_assigned create update reset upgrade set_automatic_updates delete
@@ -125,7 +126,7 @@ module CalmLens
125
126
  # @param options [Hash] the options of {UploadTokens#sign}
126
127
  # @param now [Integer] the signing time in milliseconds since the Unix epoch
127
128
  # @param nonce [String]
128
- # @return [Hash] `{'token', 'expiresAt'}`
129
+ # @return [SignedUploadToken]
129
130
  def self.sign_upload_token(api_key, options, now:, nonce:)
130
131
  UploadTokens.sign_at(api_key, options, now: now, nonce: nonce)
131
132
  rescue KeyError, TypeError, ArgumentError, JSON::GeneratorError, EncodingError => e
@@ -164,10 +165,8 @@ module CalmLens
164
165
  # {MockModerationInput} (the stored asset, its content, the trigger and whether the API would
165
166
  # queue the work) and returns a status from {MockDecision::STATUSES} or a {MockDecision}. It is
166
167
  # called on uploads (`assets.create`, `assets.classify`, `text.classify` and a final part:
167
- # trigger `upload`), `assets.retry` (`retry`), `assets.explain` with `rerun: true` (`rerun`) and
168
- # {#complete_processing} without a decision (`complete`). `pending` leaves the asset processing;
169
- # for a re-run it keeps the asset's decision until {#complete_processing}, and a failed re-run
170
- # keeps it.
168
+ # trigger `upload`), `assets.retry` (`retry`) and {#complete_processing} without a decision
169
+ # (`complete`). `pending` leaves the asset processing.
171
170
  # Without it, queued work other than `complete` stays `pending` and the rest is `allowed`. It
172
171
  # runs while the mock handles a request, so it must not call the mock.
173
172
  # @param max_retries [Integer] retries after a retryable failure; 0 by default, so a simulated
@@ -177,7 +176,7 @@ module CalmLens
177
176
  # Retries and decision checks wait no real time.
178
177
  def initialize(project_id: 'project-1', api_key: MockServerClient.create_api_key, base_url: 'https://api.calmlens.invalid/v1',
179
178
  cdn_base_url: 'https://cdn.calmlens.invalid/v1', now: MockServerClient.monotonic_clock,
180
- create_id: ->(prefix) { MockServerClient.new_id(prefix) }, moderate: nil, max_retries: 0, **options)
179
+ create_id: ->(prefix) { MockServerClient.new_id(prefix) }, moderate: nil, max_retries: 0, **)
181
180
  raise Internal.invalid('moderate must respond to call') unless moderate.nil? || moderate.respond_to?(:call)
182
181
 
183
182
  @mock_lock = Mutex.new
@@ -186,7 +185,7 @@ module CalmLens
186
185
  @failures = []
187
186
  @call_key = :"calmlens_mock_call_#{object_id}"
188
187
  super(api_key: api_key, project_id: project_id, base_url: base_url, cdn_base_url: cdn_base_url, max_retries: max_retries,
189
- **options, transport: method(:receive))
188
+ **, transport: method(:receive))
190
189
  @fake = Testing::FakeAPI.new(project_id: project_id, base_url: self.base_url, cdn_base_url: self.cdn_base_url,
191
190
  now: now, create_id: create_id, moderate: moderate, api_key: api_key,
192
191
  grants: MockServerClient.grants_of(api_key))
@@ -207,11 +206,11 @@ module CalmLens
207
206
  # `pendingReview` is settled ({Assets#decide} leaves it waiting, as with the API).
208
207
  # @param asset_id [String]
209
208
  # @param decision [String] `allowed`, `limited`, `age-restricted`, `blocked` or `purged`
210
- # @return [Hash] the asset
209
+ # @return [Asset]
211
210
  # @raise [APIError] `asset/not-found` for an unknown asset
212
211
  # @raise [InvalidArgumentError] for any other decision, such as `pending` or `failed`
213
212
  def decide(asset_id, decision)
214
- @mock_lock.synchronize { @fake.decide(asset_id, decision) } || raise(not_found)
213
+ Asset.new(@mock_lock.synchronize { @fake.decide(asset_id, decision) } || raise(not_found))
215
214
  end
216
215
 
217
216
  # Finishes processing an asset as the moderation pipeline would: with `decision`, or else what
@@ -220,12 +219,11 @@ module CalmLens
220
219
  # the asset processing. It records no manual review.
221
220
  # @param asset_id [String]
222
221
  # @param decision [String, MockDecision, nil] a status from {MockDecision::STATUSES} or a {MockDecision}
223
- # @return [Hash] the asset
222
+ # @return [Asset]
224
223
  # @raise [APIError] `asset/not-found` for an unknown asset
225
- # @raise [InvalidArgumentError] when the asset isn't processing or awaiting a queued re-run, or for
226
- # an unknown decision
224
+ # @raise [InvalidArgumentError] when the asset isn't processing, or for an unknown decision
227
225
  def complete_processing(asset_id, decision = nil)
228
- @mock_lock.synchronize { @fake.complete_processing(asset_id, decision) } || raise(not_found)
226
+ Asset.new(@mock_lock.synchronize { @fake.complete_processing(asset_id, decision) } || raise(not_found))
229
227
  end
230
228
 
231
229
  # Changes the grants of the mock's API key, as editing the key in the portal would: later
@@ -285,10 +283,10 @@ module CalmLens
285
283
  end
286
284
 
287
285
  # @see ServerClient#ensure_lenses
288
- def ensure_lenses(options) = operation('ensureLenses') { super }
286
+ def ensure_lenses(**) = operation('ensureLenses') { super }
289
287
 
290
288
  # @see ServerClient#ensure_lens
291
- def ensure_lens(options) = operation('ensureLens') { super }
289
+ def ensure_lens(**) = operation('ensureLens') { super }
292
290
 
293
291
  # Queues a JSON response for the next request.
294
292
  # @param status [Integer]
@@ -324,9 +322,9 @@ module CalmLens
324
322
  # with the `asset_id` of a stored asset carries that asset's snapshot as it is now, unless you
325
323
  # pass `asset`.
326
324
  # @param event [Hash] at least `type:`; snake_case keys are converted.
327
- # @return [Hash] the stored event
325
+ # @return [Event] the stored event
328
326
  def enqueue_event(event)
329
- @mock_lock.synchronize { JSON.parse(JSON.generate(@fake.enqueue_event(Internal.normalize(event)))) }
327
+ Event.new(@mock_lock.synchronize { JSON.parse(JSON.generate(@fake.enqueue_event(Internal.normalize(event)))) })
330
328
  end
331
329
 
332
330
  # @return [Array<Request>] copies of every request received since the mock was created or