calmlens 0.28.1 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/lib/calmlens/assets.rb +41 -4
- data/lib/calmlens/error_codes.rb +2 -0
- data/lib/calmlens/events.rb +24 -0
- data/lib/calmlens/internal.rb +0 -26
- data/lib/calmlens/models.rb +12 -34
- data/lib/calmlens/option_keys.rb +5 -0
- data/lib/calmlens/request_options.rb +47 -0
- data/lib/calmlens/resource.rb +15 -0
- data/lib/calmlens/server_client.rb +3 -1
- data/lib/calmlens/session.rb +26 -6
- data/lib/calmlens/testing/fake_api.rb +224 -52
- data/lib/calmlens/testing.rb +78 -31
- data/lib/calmlens/version.rb +1 -1
- data/lib/calmlens/webhooks.rb +4 -6
- data/lib/calmlens.rb +1 -0
- data/sig/calmlens.rbs +17 -4
- data/sig/error_codes.rbs +1 -0
- data/sig/models.rbs +11 -25
- data/sig/types.rbs +3 -0
- metadata +3 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 61f0a6bf210af7e5d56e44b39c071c7dfa68b8a4cb09d19d18580c5ac635f5d9
|
|
4
|
+
data.tar.gz: e98d4a86b0629f3b70756e4c86e0c277b006ffa0b9cbece141e46ba74985aee2
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 82aff40edfac4bb534bee900656516bae15546f9557490cd254274526590bac6bb3f1199dcf77da9cc5c6e4b1023c72913acddf8600eb2517d11bcca23998055
|
|
7
|
+
data.tar.gz: c7bb56bfcc861de4a1de35e7a4d2ef85e9f0a4519e43a2e4fd166e2305498478789cf22364fc47bc130d79022137b8babc6e6f7ae70a1226e94612342406edef
|
data/lib/calmlens/assets.rb
CHANGED
|
@@ -7,7 +7,8 @@ module CalmLens
|
|
|
7
7
|
#
|
|
8
8
|
# Methods take an asset's ID as their first argument and options as snake_case keywords; keys
|
|
9
9
|
# inside `metadata` are sent unchanged. Any method also accepts
|
|
10
|
-
# `request_options: { idempotency_key:, timeout:, open_timeout:, max_retries: }
|
|
10
|
+
# `request_options: { idempotency_key:, timeout:, deadline_ms:, open_timeout:, max_retries: }`; `deadline_ms:`
|
|
11
|
+
# bounds the whole call: every attempt, the waits between retries and {#wait_for_decision}'s checks.
|
|
11
12
|
# Results are {Asset} models. Enum values added to the API later appear as they are, so compare
|
|
12
13
|
# `classification.moderation.decision` and similar values with known strings and treat anything
|
|
13
14
|
# else as not ready.
|
|
@@ -105,6 +106,18 @@ module CalmLens
|
|
|
105
106
|
call(with_ids(options, asset_id: asset_id), __method__) { |api, request| get_asset(api['assetId'], request) }
|
|
106
107
|
end
|
|
107
108
|
|
|
109
|
+
# Retrieves the project's asset that has this `external_id`, such as the one an
|
|
110
|
+
# `asset/duplicate-external-id` error names in `details['assetId']`.
|
|
111
|
+
# @param external_id [String] the `external_id` the asset was uploaded or updated with
|
|
112
|
+
# @return [Asset]
|
|
113
|
+
# @raise [NotFoundError] `asset/not-found` when no asset in the project has it.
|
|
114
|
+
def retrieve_by_external_id(external_id, **options)
|
|
115
|
+
call(with_ids(options, external_id: external_id), __method__) do |api, request|
|
|
116
|
+
path = project("assets/by-external-id/#{Internal.segment(api['externalId'])}")
|
|
117
|
+
build(Asset, request('GET', path, request_options: request))
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
108
121
|
# Waits until an asset is settled, its `classification.status` `completed` (with its decision in
|
|
109
122
|
# `classification.moderation.decision`) or `failed`, and returns the asset. A `queued` or `processing`
|
|
110
123
|
# asset is still waiting, even when a reviewer has already decided it. It retrieves the asset,
|
|
@@ -165,6 +178,25 @@ module CalmLens
|
|
|
165
178
|
end
|
|
166
179
|
end
|
|
167
180
|
|
|
181
|
+
# Sends an asset to the project's human review queue, such as when one of your app's users
|
|
182
|
+
# reports it, with an optional note reviewers see. It doesn't change how the asset is delivered:
|
|
183
|
+
# a reviewer's decision does. Returns the review: a new one with the reason `reported` (HTTP
|
|
184
|
+
# 201, sending `asset.review-requested`), or the one already waiting for the asset (HTTP 200),
|
|
185
|
+
# unchanged; `last_response.status` tells them apart. Retried only with
|
|
186
|
+
# `request_options: {idempotency_key:}`, which makes a repeat safe.
|
|
187
|
+
# @param asset_id [String]
|
|
188
|
+
# @option options [String] :note what the reporter said, 1 to 1499 characters
|
|
189
|
+
# @return [AssetReviewRequest] `id`, `asset_id`, `reason`, `status`, `note` and `created_at`
|
|
190
|
+
# @raise [ConflictError] `asset/not-reviewable`, whose `details['reason']` is `child-asset`,
|
|
191
|
+
# `not-moderated` or `content-unavailable`
|
|
192
|
+
# @raise [APIError] `asset/held` while the asset is under a safety hold
|
|
193
|
+
def request_review(asset_id, **options)
|
|
194
|
+
call(with_ids(options, asset_id: asset_id), __method__) do |api, request|
|
|
195
|
+
build(AssetReviewRequest, request('POST', "#{asset_path(api)}/review-requests", body: without(api, 'assetId'),
|
|
196
|
+
request_options: request))
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
|
|
168
200
|
# Removes the stored content and returns the asset with `content.status` `removed` (reason
|
|
169
201
|
# `requested`); the record and classification results are kept.
|
|
170
202
|
# @param asset_id [String]
|
|
@@ -315,7 +347,8 @@ module CalmLens
|
|
|
315
347
|
end
|
|
316
348
|
|
|
317
349
|
def poll_for_decision(asset_id, request_options, timeout)
|
|
318
|
-
|
|
350
|
+
started = @session.monotonic
|
|
351
|
+
deadline = started + timeout
|
|
319
352
|
delay = DECISION_POLL_FIRST_DELAY
|
|
320
353
|
processing = moderation = nil
|
|
321
354
|
loop do
|
|
@@ -334,12 +367,16 @@ module CalmLens
|
|
|
334
367
|
return asset if SETTLED_STATUSES.include?(processing)
|
|
335
368
|
break unless remaining.positive?
|
|
336
369
|
|
|
337
|
-
|
|
370
|
+
wait = [delay, remaining].min
|
|
371
|
+
# The next check must start before the call's deadline, too.
|
|
372
|
+
break if request_options[:deadline_at] && @session.monotonic + wait >= request_options[:deadline_at]
|
|
373
|
+
|
|
374
|
+
sleep(wait)
|
|
338
375
|
delay = [delay * DECISION_POLL_FACTOR, DECISION_POLL_MAX_DELAY].min
|
|
339
376
|
end
|
|
340
377
|
raise ::Timeout::Error
|
|
341
378
|
rescue ::Timeout::Error
|
|
342
|
-
raise TimeoutError.new(SdkErrorCodes::TIMEOUT, "Asset #{asset_id} was not settled after #{
|
|
379
|
+
raise TimeoutError.new(SdkErrorCodes::TIMEOUT, "Asset #{asset_id} was not settled after #{(@session.monotonic - started).round(3)}s",
|
|
343
380
|
details: { 'assetId' => asset_id, 'classificationStatus' => processing,
|
|
344
381
|
'moderationDecision' => moderation })
|
|
345
382
|
end
|
data/lib/calmlens/error_codes.rb
CHANGED
|
@@ -71,6 +71,7 @@ module CalmLens
|
|
|
71
71
|
ASSET_NOT_RETRYABLE = 'asset/not-retryable'
|
|
72
72
|
ASSET_CONTENT_UNAVAILABLE = 'asset/content-unavailable'
|
|
73
73
|
ASSET_CONTENT_PURGED = 'asset/content-purged'
|
|
74
|
+
ASSET_NOT_REVIEWABLE = 'asset/not-reviewable'
|
|
74
75
|
SUPPORT_TICKET_NOT_FOUND = 'support-ticket/not-found'
|
|
75
76
|
DUPLICATE_EXTERNAL_ID = 'asset/duplicate-external-id'
|
|
76
77
|
FOLDER_NOT_FOUND = 'folder/not-found'
|
|
@@ -193,6 +194,7 @@ module CalmLens
|
|
|
193
194
|
'asset/not-retryable' => 409,
|
|
194
195
|
'asset/content-unavailable' => 409,
|
|
195
196
|
'asset/content-purged' => 409,
|
|
197
|
+
'asset/not-reviewable' => 409,
|
|
196
198
|
'support-ticket/not-found' => 404,
|
|
197
199
|
'asset/duplicate-external-id' => 409,
|
|
198
200
|
'folder/not-found' => 404,
|
data/lib/calmlens/events.rb
CHANGED
|
@@ -6,6 +6,12 @@ module CalmLens
|
|
|
6
6
|
# The prefix of this resource's operations in Internal::OPTION_KEYS.
|
|
7
7
|
OPERATIONS = 'events'
|
|
8
8
|
|
|
9
|
+
# @api private
|
|
10
|
+
def initialize(session, assets)
|
|
11
|
+
super(session)
|
|
12
|
+
@assets = assets
|
|
13
|
+
end
|
|
14
|
+
|
|
9
15
|
# Lists events after a cursor, oldest first. Without `cursor`, returns no events and a
|
|
10
16
|
# `next_cursor` for the current time: save it, then pass each page's `next_cursor` as `cursor`.
|
|
11
17
|
# `types` and `asset_id` narrow the feed to some event types or one asset's events. A cursor
|
|
@@ -29,6 +35,24 @@ module CalmLens
|
|
|
29
35
|
end
|
|
30
36
|
end
|
|
31
37
|
|
|
38
|
+
# Retrieves the asset an event is about, as it is now, such as one from {#list} or a parsed
|
|
39
|
+
# webhook delivery; events carry only the asset's ID. It sends the request {Assets#retrieve}
|
|
40
|
+
# sends. The asset's `event_sequence` orders it against events: an event with a higher
|
|
41
|
+
# `asset_sequence` happened after this state, one with an equal or lower one is reflected in it.
|
|
42
|
+
# @param event [Event, Hash] an event, or an event or delivery body with string keys
|
|
43
|
+
# @param request_options [Hash, nil]
|
|
44
|
+
# @return [Asset, nil] nil for an event that isn't about an asset, without sending a request
|
|
45
|
+
# @raise [APIError] `asset/not-found` once the asset is deleted
|
|
46
|
+
def retrieve_asset(event, request_options: nil)
|
|
47
|
+
raise Internal.invalid('event must be an Event or a Hash') unless event.is_a?(Event) || event.is_a?(Hash)
|
|
48
|
+
|
|
49
|
+
asset_id = event['assetId']
|
|
50
|
+
return nil if asset_id.nil?
|
|
51
|
+
raise Internal.invalid('event assetId must be a String') unless asset_id.is_a?(String)
|
|
52
|
+
|
|
53
|
+
@assets.retrieve(asset_id, request_options: request_options)
|
|
54
|
+
end
|
|
55
|
+
|
|
32
56
|
private
|
|
33
57
|
|
|
34
58
|
# The API takes the types as one comma-separated value; an empty list filters nothing.
|
data/lib/calmlens/internal.rb
CHANGED
|
@@ -7,9 +7,6 @@ module CalmLens
|
|
|
7
7
|
# Option conversion, identifier encoding and argument checks shared by the resources.
|
|
8
8
|
# @api private
|
|
9
9
|
module Internal
|
|
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 headers extra_query
|
|
12
|
-
extra_body].freeze
|
|
13
10
|
# A key the API can receive as a header value; the API checks the rest (1 to 255 printable
|
|
14
11
|
# ASCII characters without a space at either end) and answers `idempotency/invalid-key`.
|
|
15
12
|
IDEMPOTENCY_KEY = /\A[^\r\n\0]+\z/
|
|
@@ -65,29 +62,6 @@ module CalmLens
|
|
|
65
62
|
[normalize(api), request]
|
|
66
63
|
end
|
|
67
64
|
|
|
68
|
-
def check_request_options(request)
|
|
69
|
-
key = request[:idempotency_key]
|
|
70
|
-
if !key.nil? && !(key.is_a?(String) && key.match?(IDEMPOTENCY_KEY))
|
|
71
|
-
raise invalid('idempotency_key must be a non-empty String without line breaks')
|
|
72
|
-
end
|
|
73
|
-
|
|
74
|
-
%i[timeout open_timeout upload_timeout].each do |name|
|
|
75
|
-
next if request[name].nil? || positive?(request[name])
|
|
76
|
-
|
|
77
|
-
raise invalid("#{name} must be a positive number of seconds")
|
|
78
|
-
end
|
|
79
|
-
retries = request[:max_retries]
|
|
80
|
-
raise invalid('max_retries must be a non-negative Integer') unless retries.nil? || (retries.is_a?(Integer) && retries >= 0)
|
|
81
|
-
|
|
82
|
-
limit = request[:max_response_bytes]
|
|
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
|
|
89
|
-
end
|
|
90
|
-
|
|
91
65
|
def positive?(value)
|
|
92
66
|
value.is_a?(Numeric) && value.real? && value.to_f.finite? && value.positive?
|
|
93
67
|
end
|
data/lib/calmlens/models.rb
CHANGED
|
@@ -5,6 +5,7 @@ module CalmLens
|
|
|
5
5
|
class Asset < Model; end
|
|
6
6
|
class AssetBatch < Model; end
|
|
7
7
|
class AssetPage < Page; end
|
|
8
|
+
class AssetReviewRequest < Model; end
|
|
8
9
|
class AssetSearchResult < Model; end
|
|
9
10
|
class AssetTimelinePage < Page; end
|
|
10
11
|
class CategoryPolicyScore < Model; end
|
|
@@ -48,7 +49,6 @@ module CalmLens
|
|
|
48
49
|
class Classification::PersonDetection < Model; end
|
|
49
50
|
class Classification::Progress < Model; end
|
|
50
51
|
class Event::Actor < Model; end
|
|
51
|
-
class Event::Asset < Model; end
|
|
52
52
|
class Event::Fact < Model; end
|
|
53
53
|
class MetadataFieldsResource::Field < Model; end
|
|
54
54
|
class Moderation::ManualReview < Model; end
|
|
@@ -73,9 +73,6 @@ module CalmLens
|
|
|
73
73
|
class Classification::LinkDetection::QrCode < Model; end
|
|
74
74
|
class Classification::Ocr::TextRegion < Model; end
|
|
75
75
|
class Classification::PersonDetection::Person < Model; end
|
|
76
|
-
class Event::Asset::Classification < Model; end
|
|
77
|
-
class Event::Asset::Content < Model; end
|
|
78
|
-
class Event::Asset::Upload < Model; end
|
|
79
76
|
class Moderation::ManualReview::DecidedBy < Model; end
|
|
80
77
|
class Moderation::Policy::Preset < Model; end
|
|
81
78
|
class Moderation::Raw::HashMatch < Model; end
|
|
@@ -87,7 +84,6 @@ module CalmLens
|
|
|
87
84
|
class Asset::Content::Hls::Rendition < Model; end
|
|
88
85
|
class Classification::FaceDetection::Face::AgeRange < Model; end
|
|
89
86
|
class Classification::Ocr::TextRegion::Box < Model; end
|
|
90
|
-
class Event::Asset::Classification::Moderation < Model; end
|
|
91
87
|
class UploadPreset::ProcessingOptions::Features::FaceDetection < Model; end
|
|
92
88
|
|
|
93
89
|
Asset.declare(
|
|
@@ -111,7 +107,8 @@ module CalmLens
|
|
|
111
107
|
visibility: ["visibility", nil],
|
|
112
108
|
upload: ["upload", [:model, "CalmLens::Asset::Upload"]],
|
|
113
109
|
classification: ["classification", [:model, "CalmLens::Classification"]],
|
|
114
|
-
content: ["content", [:model, "CalmLens::Asset::Content"]]
|
|
110
|
+
content: ["content", [:model, "CalmLens::Asset::Content"]],
|
|
111
|
+
event_sequence: ["eventSequence", nil]
|
|
115
112
|
)
|
|
116
113
|
|
|
117
114
|
AssetBatch.declare(
|
|
@@ -126,6 +123,15 @@ module CalmLens
|
|
|
126
123
|
has_more: ["hasMore", nil]
|
|
127
124
|
)
|
|
128
125
|
|
|
126
|
+
AssetReviewRequest.declare(
|
|
127
|
+
id: ["id", nil],
|
|
128
|
+
asset_id: ["assetId", nil],
|
|
129
|
+
reason: ["reason", nil],
|
|
130
|
+
status: ["status", nil],
|
|
131
|
+
note: ["note", nil],
|
|
132
|
+
created_at: ["createdAt", nil]
|
|
133
|
+
)
|
|
134
|
+
|
|
129
135
|
AssetSearchResult.declare(
|
|
130
136
|
query: ["query", nil],
|
|
131
137
|
items: ["items", [:array, [:model, "CalmLens::AssetSearchResult::Item"]]],
|
|
@@ -205,7 +211,6 @@ module CalmLens
|
|
|
205
211
|
description: ["description", nil],
|
|
206
212
|
asset_id: ["assetId", nil],
|
|
207
213
|
asset_sequence: ["assetSequence", nil],
|
|
208
|
-
asset: ["asset", [:model, "CalmLens::Event::Asset"]],
|
|
209
214
|
facts: ["facts", [:array, [:model, "CalmLens::Event::Fact"]]],
|
|
210
215
|
created_at: ["createdAt", nil]
|
|
211
216
|
)
|
|
@@ -478,15 +483,6 @@ module CalmLens
|
|
|
478
483
|
id: ["id", nil]
|
|
479
484
|
)
|
|
480
485
|
|
|
481
|
-
Event::Asset.declare(
|
|
482
|
-
id: ["id", nil],
|
|
483
|
-
external_id: ["externalId", nil],
|
|
484
|
-
upload_preset_id: ["uploadPresetId", nil],
|
|
485
|
-
upload: ["upload", [:model, "CalmLens::Event::Asset::Upload"]],
|
|
486
|
-
classification: ["classification", [:model, "CalmLens::Event::Asset::Classification"]],
|
|
487
|
-
content: ["content", [:model, "CalmLens::Event::Asset::Content"]]
|
|
488
|
-
)
|
|
489
|
-
|
|
490
486
|
Event::Fact.declare(
|
|
491
487
|
key: ["key", nil],
|
|
492
488
|
value: ["value", [:array, nil]],
|
|
@@ -649,20 +645,6 @@ module CalmLens
|
|
|
649
645
|
confidence: ["confidence", nil]
|
|
650
646
|
)
|
|
651
647
|
|
|
652
|
-
Event::Asset::Classification.declare(
|
|
653
|
-
status: ["status", nil],
|
|
654
|
-
test_input: ["testInput", nil],
|
|
655
|
-
moderation: ["moderation", [:model, "CalmLens::Event::Asset::Classification::Moderation"]]
|
|
656
|
-
)
|
|
657
|
-
|
|
658
|
-
Event::Asset::Content.declare(
|
|
659
|
-
status: ["status", nil]
|
|
660
|
-
)
|
|
661
|
-
|
|
662
|
-
Event::Asset::Upload.declare(
|
|
663
|
-
status: ["status", nil]
|
|
664
|
-
)
|
|
665
|
-
|
|
666
648
|
Moderation::ManualReview::DecidedBy.declare(
|
|
667
649
|
type: ["type", nil],
|
|
668
650
|
id: ["id", nil]
|
|
@@ -730,10 +712,6 @@ module CalmLens
|
|
|
730
712
|
height: ["height", nil]
|
|
731
713
|
)
|
|
732
714
|
|
|
733
|
-
Event::Asset::Classification::Moderation.declare(
|
|
734
|
-
decision: ["decision", nil]
|
|
735
|
-
)
|
|
736
|
-
|
|
737
715
|
UploadPreset::ProcessingOptions::Features::FaceDetection.declare(
|
|
738
716
|
enabled: ["enabled", nil],
|
|
739
717
|
age_estimation: ["ageEstimation", nil]
|
data/lib/calmlens/option_keys.rb
CHANGED
|
@@ -25,7 +25,9 @@ module CalmLens
|
|
|
25
25
|
'assets.listTimeline' => %w[assetId cursor pageSize].freeze,
|
|
26
26
|
'assets.move' => %w[assetId folderId].freeze,
|
|
27
27
|
'assets.removeContent' => %w[assetId].freeze,
|
|
28
|
+
'assets.requestReview' => %w[assetId note].freeze,
|
|
28
29
|
'assets.retrieve' => %w[assetId].freeze,
|
|
30
|
+
'assets.retrieveByExternalId' => %w[externalId].freeze,
|
|
29
31
|
'assets.retry' => %w[assetId].freeze,
|
|
30
32
|
'assets.search' => %w[mode pageSize query].freeze,
|
|
31
33
|
'assets.update' => %w[assetId description externalId externalUrl metadata name tags visibility].freeze,
|
|
@@ -114,5 +116,8 @@ module CalmLens
|
|
|
114
116
|
visibility
|
|
115
117
|
].freeze
|
|
116
118
|
}.freeze
|
|
119
|
+
|
|
120
|
+
# The camelCase request options every method takes in `request_options`.
|
|
121
|
+
REQUEST_OPTION_KEYS = %w[deadlineMs extraBody extraQuery headers idempotencyKey maxRetries signal timeoutMs].freeze
|
|
117
122
|
end
|
|
118
123
|
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CalmLens
|
|
4
|
+
# The per-call request options every method takes under `request_options:`, and their checks.
|
|
5
|
+
# @api private
|
|
6
|
+
module Internal
|
|
7
|
+
# The Ruby name of each request option in the contract's REQUEST_OPTION_KEYS (option_keys.rb):
|
|
8
|
+
# `timeout` is in seconds, like the client's, and `signal` has none, as a call runs in its caller's thread.
|
|
9
|
+
CONTRACT_REQUEST_OPTIONS = { 'deadlineMs' => :deadline_ms, 'extraBody' => :extra_body, 'extraQuery' => :extra_query,
|
|
10
|
+
'headers' => :headers, 'idempotencyKey' => :idempotency_key, 'maxRetries' => :max_retries,
|
|
11
|
+
'signal' => nil, 'timeoutMs' => :timeout }.freeze
|
|
12
|
+
# Per-call settings accepted under the `request_options:` option of any method: the contract's,
|
|
13
|
+
# and the connection, upload and response size limits this SDK also lets a call change.
|
|
14
|
+
REQUEST_OPTIONS = (REQUEST_OPTION_KEYS.filter_map { |key| CONTRACT_REQUEST_OPTIONS.fetch(key) } +
|
|
15
|
+
%i[open_timeout upload_timeout max_response_bytes]).freeze
|
|
16
|
+
|
|
17
|
+
module_function
|
|
18
|
+
|
|
19
|
+
def check_request_options(request)
|
|
20
|
+
key = request[:idempotency_key]
|
|
21
|
+
if !key.nil? && !(key.is_a?(String) && key.match?(IDEMPOTENCY_KEY))
|
|
22
|
+
raise invalid('idempotency_key must be a non-empty String without line breaks')
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
%i[timeout open_timeout upload_timeout].each do |name|
|
|
26
|
+
next if request[name].nil? || positive?(request[name])
|
|
27
|
+
|
|
28
|
+
raise invalid("#{name} must be a positive number of seconds")
|
|
29
|
+
end
|
|
30
|
+
retries = request[:max_retries]
|
|
31
|
+
raise invalid('max_retries must be a non-negative Integer') unless retries.nil? || (retries.is_a?(Integer) && retries >= 0)
|
|
32
|
+
|
|
33
|
+
limit = request[:max_response_bytes]
|
|
34
|
+
raise invalid('max_response_bytes must be a positive Integer') unless limit.nil? || (limit.is_a?(Integer) && limit.positive?)
|
|
35
|
+
|
|
36
|
+
deadline = request[:deadline_ms]
|
|
37
|
+
unless deadline.nil? || (deadline.is_a?(Integer) && deadline.positive?)
|
|
38
|
+
raise invalid('deadline_ms must be a positive Integer of milliseconds')
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
headers(request[:headers]) if request.key?(:headers)
|
|
42
|
+
%i[extra_query extra_body].each do |name|
|
|
43
|
+
raise invalid("#{name} must be a Hash") unless request[name].nil? || request[name].is_a?(Hash)
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
data/lib/calmlens/resource.rb
CHANGED
|
@@ -39,11 +39,16 @@ module CalmLens
|
|
|
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
41
|
outer = Thread.current[:calmlens_operation]
|
|
42
|
+
outer_deadline = Thread.current[deadline_key]
|
|
43
|
+
deadline_at = call_deadline(outer_deadline, request.delete(:deadline_ms))
|
|
44
|
+
request[:deadline_at] = deadline_at if deadline_at
|
|
42
45
|
Thread.current[:calmlens_operation] ||= operation
|
|
46
|
+
Thread.current[deadline_key] = deadline_at
|
|
43
47
|
begin
|
|
44
48
|
yield api, request
|
|
45
49
|
ensure
|
|
46
50
|
Thread.current[:calmlens_operation] = outer
|
|
51
|
+
Thread.current[deadline_key] = outer_deadline
|
|
47
52
|
end
|
|
48
53
|
rescue Error
|
|
49
54
|
raise
|
|
@@ -51,6 +56,16 @@ module CalmLens
|
|
|
51
56
|
raise InvalidArgumentError.new(SdkErrorCodes::INVALID_ARGUMENT, e.message), cause: e
|
|
52
57
|
end
|
|
53
58
|
|
|
59
|
+
# When the call's `deadline_ms` passes, in seconds on the session's clock: it starts with the
|
|
60
|
+
# call, and a call made within another keeps the earlier deadline.
|
|
61
|
+
def call_deadline(outer, milliseconds)
|
|
62
|
+
own = milliseconds && (@session.monotonic + (milliseconds / 1000.0))
|
|
63
|
+
[outer, own].compact.min
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# The thread's running call deadline for this client's session.
|
|
67
|
+
def deadline_key = :"calmlens_deadline_#{@session.object_id}"
|
|
68
|
+
|
|
54
69
|
# Options are the snake_case keywords a method declares, plus `request_options:`. Ruby passes
|
|
55
70
|
# them as Symbols; camelCase or String names are refused like misspelt ones.
|
|
56
71
|
def check_option_keys(options, operation)
|
|
@@ -126,7 +126,7 @@ module CalmLens
|
|
|
126
126
|
@policies = Policies.new(@session)
|
|
127
127
|
@text = Text.new(@session, @assets)
|
|
128
128
|
@upload_tokens = UploadTokens.new(@session, api_key)
|
|
129
|
-
@events = Events.new(@session)
|
|
129
|
+
@events = Events.new(@session, @assets)
|
|
130
130
|
@cdn = CDN.new(@session)
|
|
131
131
|
@lenses = Lenses.new(@session)
|
|
132
132
|
@upload_presets = UploadPresets.new(@session)
|
|
@@ -181,6 +181,8 @@ module CalmLens
|
|
|
181
181
|
raise Internal.invalid('query must be a Hash') unless query.is_a?(Hash)
|
|
182
182
|
|
|
183
183
|
_, options = Internal.options({ request_options: request_options })
|
|
184
|
+
deadline = options.delete(:deadline_ms)
|
|
185
|
+
options[:deadline_at] = @session.monotonic + (deadline / 1000.0) if deadline
|
|
184
186
|
outer = Thread.current[:calmlens_operation]
|
|
185
187
|
# A raw request has no operation name.
|
|
186
188
|
Thread.current[:calmlens_operation] = nil
|
data/lib/calmlens/session.rb
CHANGED
|
@@ -232,10 +232,12 @@ module CalmLens
|
|
|
232
232
|
open_timeout: request_options.fetch(:open_timeout, @open_timeout),
|
|
233
233
|
timeout: request_options.fetch(:timeout, @timeout))
|
|
234
234
|
limit = request_options.fetch(:max_response_bytes, @max_response_bytes)
|
|
235
|
+
deadline_at = request_options[:deadline_at]
|
|
235
236
|
attempt = 0
|
|
236
237
|
loop do
|
|
237
238
|
body&.rewind if attempt.positive?
|
|
238
|
-
context = { again: retryable && attempt < retries, attempt: attempt, limit: limit,
|
|
239
|
+
context = { again: retryable && attempt < retries, attempt: attempt, limit: limit, deadline_at: deadline_at,
|
|
240
|
+
deadline: attempt_deadline(request, request_options, deadline, deadline_at),
|
|
239
241
|
allow_http_errors: allow_http_errors, started: Process.clock_gettime(Process::CLOCK_MONOTONIC),
|
|
240
242
|
authenticate: authenticate }
|
|
241
243
|
outcome, value = observed_attempt(request, context, &handler)
|
|
@@ -246,6 +248,23 @@ module CalmLens
|
|
|
246
248
|
end
|
|
247
249
|
end
|
|
248
250
|
|
|
251
|
+
# The whole-attempt limit in seconds, none without an upload timeout or a call deadline. The
|
|
252
|
+
# call's deadline also shortens the attempt's connect and read timeouts, and once it has passed
|
|
253
|
+
# no attempt starts.
|
|
254
|
+
def attempt_deadline(request, request_options, upload_deadline, deadline_at)
|
|
255
|
+
return upload_deadline unless deadline_at
|
|
256
|
+
|
|
257
|
+
remaining = deadline_at - monotonic
|
|
258
|
+
raise TimeoutError.new(SdkErrorCodes::TIMEOUT, "The call's deadline passed") unless remaining.positive?
|
|
259
|
+
|
|
260
|
+
request.open_timeout = [request_options.fetch(:open_timeout, @open_timeout), remaining].min
|
|
261
|
+
request.timeout = [request_options.fetch(:timeout, @timeout), remaining].min
|
|
262
|
+
[upload_deadline, remaining].compact.min
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
# Whether a retry after `delay` seconds would start before the call's deadline.
|
|
266
|
+
def in_time?(context, delay) = context[:deadline_at].nil? || monotonic + delay < context[:deadline_at]
|
|
267
|
+
|
|
249
268
|
# One attempt, reported to the hook and logger: `[:ok, result]` or `[:retry, seconds]`; an error
|
|
250
269
|
# that won't be retried is raised.
|
|
251
270
|
def observed_attempt(request, context, &)
|
|
@@ -261,7 +280,7 @@ module CalmLens
|
|
|
261
280
|
end
|
|
262
281
|
if outcome == :error
|
|
263
282
|
delay = http_delay(value.retry_after, context[:attempt])
|
|
264
|
-
unless context[:again] && delay <= ServerClient::RETRY_AFTER_MAX && value.retryable?
|
|
283
|
+
unless context[:again] && delay <= ServerClient::RETRY_AFTER_MAX && value.retryable? && in_time?(context, delay)
|
|
265
284
|
observe(request, context, nil, value)
|
|
266
285
|
raise value
|
|
267
286
|
end
|
|
@@ -323,7 +342,7 @@ module CalmLens
|
|
|
323
342
|
if context[:allow_http_errors] && !response.success?
|
|
324
343
|
delay = http_delay(Error.parse_retry_after(response.headers['retry-after']), context[:attempt])
|
|
325
344
|
retry_status = RETRYABLE_STATUSES.include?(response.status) && delay <= ServerClient::RETRY_AFTER_MAX
|
|
326
|
-
next [:retry, delay] if context[:again] && retry_status
|
|
345
|
+
next [:retry, delay] if context[:again] && retry_status && in_time?(context, delay)
|
|
327
346
|
end
|
|
328
347
|
next [:error, http_error(response, context[:limit], request)] unless response.success? || context[:allow_http_errors]
|
|
329
348
|
|
|
@@ -332,13 +351,14 @@ module CalmLens
|
|
|
332
351
|
end
|
|
333
352
|
end
|
|
334
353
|
rescue Error => e
|
|
335
|
-
|
|
354
|
+
delay = backoff(context[:attempt])
|
|
355
|
+
raise unless context[:again] && !delivered && e.retryable? && in_time?(context, delay)
|
|
336
356
|
|
|
337
357
|
context[:error] = e
|
|
338
|
-
[:retry,
|
|
358
|
+
[:retry, delay]
|
|
339
359
|
end
|
|
340
360
|
|
|
341
|
-
# Runs one attempt within
|
|
361
|
+
# Runs one attempt within its deadline, when it has one.
|
|
342
362
|
def within(deadline, &)
|
|
343
363
|
deadline ? ::Timeout.timeout(deadline, &) : yield
|
|
344
364
|
rescue ::Timeout::Error => e
|