nohead 0.8.0 → 0.10.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.
data/lib/nohead/client.rb CHANGED
@@ -6,66 +6,108 @@ require "time"
6
6
  require "uri"
7
7
 
8
8
  module Nohead
9
+ # A retry about to happen, as `on_retry:` gets it: `attempt` is 1 for a
10
+ # request's first retry, `delay` the seconds the client waits before it,
11
+ # `url` the URL retried, `status` the status that failed (nil when the
12
+ # connection did), and `error` the APIError or ConnectionError (nil for
13
+ # a status from storage).
14
+ RetryEvent = Data.define(:attempt, :delay, :url, :status, :error)
15
+
9
16
  # A client for the Nohead API, authenticated with a project API key.
10
17
  #
11
18
  # nohead = Nohead::Client.new # NOHEAD_API_KEY
12
19
  # nohead.records.list("posts").each { |post| puts post.data["title"] }
13
20
  class Client
14
21
  DEFAULT_BASE_URL = "https://api.nohead.io"
22
+
23
+ # Each warning is given once per process, as the other SDKs do: an app
24
+ # that builds a client per request would otherwise warn on every one.
25
+ WARNED = Set.new
26
+ WARNED_LOCK = Mutex.new
27
+ private_constant :WARNED_LOCK
28
+
29
+ def self.first_warning?(key) = WARNED_LOCK.synchronize { !WARNED.add?(key).nil? }
15
30
  RETRYABLE_STATUSES = [429, 500, 502, 503, 504].freeze
16
31
  MAX_RETRY_AFTER = 60
17
32
 
18
33
  attr_reader :records, :revisions, :drafts, :collections, :fields, :migrations, :assets, :webhooks,
19
34
  :audit_events, :feature_flags, :me, :health
20
35
 
36
+ # The key's project ID, looked up once, and once at a time, for a client
37
+ # and its copies (with_options).
38
+ class ProjectLookup
39
+ def initialize(id)
40
+ @id = id
41
+ @lock = Mutex.new
42
+ end
43
+
44
+ def get
45
+ @id || @lock.synchronize { @id ||= yield }
46
+ end
47
+ end
48
+ private_constant :ProjectLookup
49
+
21
50
  # api_key:: A project API key ("nohead_sk_...", or "nohead_pk_..." when
22
51
  # published-only). Defaults to NOHEAD_API_KEY.
23
- # base_url:: Defaults to NOHEAD_API_URL, else https://api.nohead.io.
52
+ # base_url:: The API's address, an http or https URL. Defaults to
53
+ # https://api.nohead.io (the environment isn't read for it).
24
54
  # project_id:: The key's project. Looked up once with GET /v1/me when omitted.
25
55
  # max_retries:: Retries of failed requests (see the README, "Retries").
26
- # timeout:: Seconds per attempt.
56
+ # timeout:: The longest wait in seconds without progress, per attempt:
57
+ # connecting, waiting for the response, and between reads
58
+ # and writes of a body. A response that keeps arriving
59
+ # doesn't time out.
27
60
  # headers:: Headers added to every request.
28
61
  # warnings:: Warn about deprecated operations and plan usage (once each).
62
+ # on_retry:: Called with a RetryEvent before each retry's wait, for
63
+ # example to log it.
64
+ # rich_text:: How rich text fields read in the records and drafts
65
+ # returned: "document" (the API's default), "html" or
66
+ # "markdown". A method's own `rich_text:` wins.
67
+ #
68
+ # An empty string is the same as leaving an option out.
29
69
  def initialize(api_key: nil, base_url: nil, project_id: nil, max_retries: 2, timeout: 60,
30
- headers: {}, warnings: true, transport: Transport.new)
70
+ headers: {}, warnings: true, on_retry: nil, rich_text: nil, transport: Transport.new)
31
71
  @api_key = present(api_key) || present(ENV.fetch("NOHEAD_API_KEY", nil)) or
32
72
  raise Error, "Missing API key: pass api_key or set NOHEAD_API_KEY"
33
- @base_url = (present(base_url) || present(ENV.fetch("NOHEAD_API_URL", nil)) ||
34
- DEFAULT_BASE_URL).chomp("/")
35
- @project_id = project_id
73
+ @base_url = checked_base_url(present(base_url) || DEFAULT_BASE_URL)
74
+ @project = ProjectLookup.new(present(project_id))
36
75
  @max_retries = max_retries
37
76
  @timeout = timeout
38
- @headers = headers.to_h { |key, value| [key.to_s, value.to_s] }
77
+ @headers = merge_headers({}, headers.to_h)
39
78
  @warnings = warnings
79
+ @on_retry = on_retry
80
+ @rich_text = present(rich_text)
40
81
  @transport = transport
41
- @warned = {}
82
+ build_resources
83
+ end
42
84
 
43
- @records = Resources::Records.new(self)
44
- @revisions = Resources::RevisionsById.new(self)
45
- @drafts = Resources::Drafts.new(self)
46
- @collections = Resources::Collections.new(self)
47
- @fields = Resources::Fields.new(self)
48
- @migrations = Resources::Migrations.new(self)
49
- @assets = Resources::Assets.new(self)
50
- @webhooks = Resources::Webhooks.new(self)
51
- @audit_events = Resources::AuditEvents.new(self)
52
- @feature_flags = Resources::FeatureFlags.new(self)
53
- @me = Resources::Me.new(self)
54
- @health = Resources::Health.new(self)
85
+ # A copy of the client with other settings, which shares its transport
86
+ # and project lookup: `nohead.with_options(timeout: 5).records.get(id)`.
87
+ # `headers:` are added to the client's.
88
+ def with_options(timeout: @timeout, max_retries: @max_retries, headers: {}, on_retry: @on_retry,
89
+ rich_text: @rich_text)
90
+ dup.tap do |copy|
91
+ copy.configure(timeout, max_retries, merge_headers(@headers, headers.to_h), on_retry, present(rich_text))
92
+ end
55
93
  end
56
94
 
57
95
  # Full-text search across the key's project (or some of its collections),
58
96
  # most relevant first, through the first 1,000 hits. `filter` takes
59
97
  # `published_at` ({ published_at: { exists: true } } for published
60
- # records), as records.list does.
61
- def search(query, collections: nil, filter: nil, limit: nil, cursor: nil)
62
- filter = { collection: (collections.nil? ? nil : { in: collections }), **filter.to_h.transform_keys(&:to_sym) }
63
- paginate("projects_search", query: { q: query, filter: filter, limit: limit, cursor: cursor })
98
+ # records), as records.list does. `collections` wins over a `collection`
99
+ # filter.
100
+ def search(query, collections: nil, filter: nil, limit: nil, cursor: nil, rich_text: nil)
101
+ filter = filter.to_h.transform_keys(&:to_sym)
102
+ filter = filter.merge(collection: { in: collections }) unless collections.nil?
103
+ paginate("projects_search", query: { q: query, filter: filter, limit: limit, cursor: cursor },
104
+ rich_text: rich_text)
64
105
  end
65
106
 
66
- # The API key's project, from GET /v1/me the first time.
107
+ # The API key's project, from GET /v1/me the first time. Threads that
108
+ # need it at the same time wait for one lookup.
67
109
  def project_id
68
- @project_id ||= begin
110
+ @project.get do
69
111
  me = request("me_get")
70
112
  me.api_key or raise Error, "The credentials are not a project API key"
71
113
  me.api_key.project_id
@@ -76,20 +118,23 @@ module Nohead
76
118
  # result. The resources call this; it is public for operations the SDK
77
119
  # does not wrap yet.
78
120
  def request(operation, path: {}, query: {}, body: nil, idempotency_key: nil,
79
- change_note: nil, if_match: nil)
80
- NoheadObject.wrap(send_request(operation, path: path, query: query, body: body,
81
- idempotency_key: idempotency_key,
82
- change_note: change_note, if_match: if_match))
121
+ change_note: nil, if_match: nil, rich_text: nil)
122
+ NoheadObject.wrap(exchange(operation, path: path, query: query, body: body, idempotency_key: idempotency_key,
123
+ change_note: change_note, if_match: if_match, rich_text: rich_text).first)
83
124
  end
84
125
 
85
126
  # A list operation as a Page that fetches the following pages as needed.
86
- def paginate(operation, path: {}, query: {})
127
+ def paginate(operation, path: {}, query: {}, rich_text: nil)
87
128
  params = query.dup
88
129
  cursor = params.delete(:cursor)
89
130
  fetch = lambda do |next_cursor|
90
- list = send_request(operation, path: path, query: params.merge(cursor: next_cursor))
91
- Page.new(NoheadObject.wrap(list.fetch("data")), NoheadObject.wrap(list.fetch("meta")),
92
- &fetch)
131
+ list, status = exchange(operation, path: path, query: params.merge(cursor: next_cursor),
132
+ rich_text: rich_text)
133
+ unless list.is_a?(Hash) && list["data"].is_a?(Array) && list["meta"].is_a?(Hash)
134
+ raise Error, "The API's response could not be read (HTTP #{status})"
135
+ end
136
+
137
+ Page.new(NoheadObject.wrap(list["data"]), NoheadObject.wrap(list["meta"]), &fetch)
93
138
  end
94
139
  fetch.call(cursor)
95
140
  end
@@ -104,10 +149,14 @@ module Nohead
104
149
  headers.merge("Content-Length" => source.byte_size.to_s),
105
150
  source.io, @timeout)
106
151
  return response unless RETRYABLE_STATUSES.include?(response.status) && attempt < retries
107
- rescue ConnectionError
152
+
153
+ failed = { status: response.status }
154
+ rescue ConnectionError => e
108
155
  raise if attempt >= retries
156
+
157
+ failed = { error: e }
109
158
  end
110
- pause(backoff(attempt))
159
+ wait_to_retry(url, attempt, backoff(attempt), **failed)
111
160
  attempt += 1
112
161
  source.rewind
113
162
  end
@@ -115,35 +164,67 @@ module Nohead
115
164
 
116
165
  def inspect = "#<Nohead::Client #{@base_url}>"
117
166
 
167
+ protected
168
+
169
+ # with_options' settings, on its copy.
170
+ def configure(timeout, max_retries, headers, on_retry, rich_text)
171
+ @timeout = timeout
172
+ @max_retries = max_retries
173
+ @headers = headers
174
+ @on_retry = on_retry
175
+ @rich_text = rich_text
176
+ end
177
+
118
178
  private
119
179
 
120
- def send_request(operation, path: {}, query: {}, body: nil, idempotency_key: nil,
121
- change_note: nil, if_match: nil)
180
+ def initialize_copy(source)
181
+ super
182
+ build_resources # theirs send through `source`
183
+ end
184
+
185
+ def build_resources
186
+ @records = Resources::Records.new(self)
187
+ @revisions = Resources::RevisionsById.new(self)
188
+ @drafts = Resources::Drafts.new(self)
189
+ @collections = Resources::Collections.new(self)
190
+ @fields = Resources::Fields.new(self)
191
+ @migrations = Resources::Migrations.new(self)
192
+ @assets = Resources::Assets.new(self)
193
+ @webhooks = Resources::Webhooks.new(self)
194
+ @audit_events = Resources::AuditEvents.new(self)
195
+ @feature_flags = Resources::FeatureFlags.new(self)
196
+ @me = Resources::Me.new(self)
197
+ @health = Resources::Health.new(self)
198
+ end
199
+
200
+ # The parsed body of a 2xx response, and its status.
201
+ def exchange(operation, path: {}, query: {}, body: nil, idempotency_key: nil,
202
+ change_note: nil, if_match: nil, rich_text: nil)
122
203
  method, template = OPERATIONS.fetch(operation)
123
- url = build_url(template, path) + query_string(query)
204
+ url = build_url(template, path) + query_string(query.merge(rich_text_query(operation, rich_text)))
124
205
  headers = request_headers(method, body, idempotency_key, change_note, if_match)
125
206
  payload = body.nil? ? nil : JSON.generate(json_ready(body))
126
207
  attempt = 0
127
208
  loop do
128
209
  begin
129
210
  response = @transport.call(method, url, headers, payload, @timeout)
130
- rescue ConnectionError
211
+ rescue ConnectionError => e
131
212
  raise if attempt >= @max_retries
132
213
 
133
- pause(backoff(attempt))
214
+ wait_to_retry(url, attempt, backoff(attempt), error: e)
134
215
  attempt += 1
135
216
  next
136
217
  end
137
218
 
138
219
  warn_about(operation, response.headers)
139
220
  parsed = parse(response)
140
- return parsed if response.status.between?(200, 299)
221
+ return [parsed, response.status] if response.status.between?(200, 299)
141
222
 
142
223
  error = Nohead.api_error(response.status, parsed, response.headers)
143
224
  delay = retry_delay(error, attempt)
144
225
  raise error if delay.nil?
145
226
 
146
- pause(delay)
227
+ wait_to_retry(url, attempt, delay, status: response.status, error: error)
147
228
  attempt += 1
148
229
  end
149
230
  end
@@ -156,14 +237,26 @@ module Nohead
156
237
 
157
238
  values["project_id"] ||= project_id if template.include?("{project_id}")
158
239
  path = template.gsub(/\{(\w+)\}/) do
159
- value = values[Regexp.last_match(1)]
160
- raise Error, "Missing #{Regexp.last_match(1)}" if value.nil? || value.to_s.empty?
240
+ name = Regexp.last_match(1)
241
+ value = values[name]
242
+ raise Error, "Missing #{name}" if value.nil? || value.to_s.empty?
243
+ # Encoded, "." and ".." would still be resolved as the path's own segments.
244
+ raise Error, %(Invalid #{name}: "#{value}") if %w[. ..].include?(value.to_s)
161
245
 
162
- URI.encode_www_form_component(value.to_s).gsub("+", "%20")
246
+ URI.encode_uri_component(value.to_s)
163
247
  end
164
248
  @base_url + path
165
249
  end
166
250
 
251
+ # The request's `rich_text`, else the client's, for an operation that
252
+ # takes it. Others never send the client's.
253
+ def rich_text_query(operation, rich_text)
254
+ return { rich_text: present(rich_text) || @rich_text } if RICH_TEXT_OPERATIONS.include?(operation)
255
+ raise ArgumentError, "#{operation} does not take rich_text" if present(rich_text)
256
+
257
+ {}
258
+ end
259
+
167
260
  # Query parameters as the API reads them: hashes become key[sub]=...
168
261
  # (filter[price][lt]=50), arrays are comma-separated (expand=author,tags)
169
262
  # with \, for a comma inside a value and \\ for a backslash, times are
@@ -196,33 +289,69 @@ module Nohead
196
289
  case value
197
290
  when Hash then value.to_h { |key, inner| [key.to_s, json_ready(inner)] }
198
291
  when Array then value.map { |item| json_ready(item) }
199
- when Time, DateTime then value.to_time.utc.iso8601(3)
200
- when Date then value.iso8601
292
+ when Time, DateTime, Date then scalar(value)
201
293
  when Symbol then value.to_s
202
294
  else value
203
295
  end
204
296
  end
205
297
 
298
+ # The SDK's headers, then the client's `headers:`, then the ones request
299
+ # options set, which win.
206
300
  def request_headers(method, body, idempotency_key, change_note, if_match)
207
- headers = {
208
- "Accept" => "application/json",
209
- "Authorization" => "Bearer #{@api_key}",
210
- "Nohead-Client" => "sdk-ruby/#{VERSION}",
211
- "User-Agent" => "nohead-ruby/#{VERSION} ruby/#{RUBY_VERSION}"
212
- }.merge(@headers)
213
- headers["Content-Type"] = "application/json" unless body.nil?
214
- headers["Idempotency-Key"] = idempotency_key || SecureRandom.uuid unless method == "GET"
215
- unless if_match.nil?
216
- revision = if_match.respond_to?(:revision) ? if_match.revision : if_match
217
- headers["If-Match"] = %("#{revision}")
218
- end
301
+ headers = merge_headers({
302
+ "Accept" => "application/json",
303
+ "Authorization" => "Bearer #{@api_key}",
304
+ "Nohead-Client" => "sdk-ruby/#{VERSION}",
305
+ "User-Agent" => "nohead-ruby/#{VERSION} ruby/#{RUBY_VERSION}"
306
+ }, @headers)
307
+ options = {}
308
+ options["Content-Type"] = "application/json" unless body.nil?
309
+ options["Idempotency-Key"] = present(idempotency_key) || SecureRandom.uuid unless method == "GET"
310
+ options["If-Match"] = %("#{revision_of(if_match)}") unless if_match.nil?
219
311
  # Percent-encoded UTF-8, as encodeURIComponent: header values are bytes
220
312
  # (the API decodes it). Notes in other encodings are converted first.
221
- if change_note
313
+ if present(change_note)
222
314
  note = change_note.to_s.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
223
- headers["Nohead-Change-Note"] = URI.encode_uri_component(note)
315
+ options["Nohead-Change-Note"] = URI.encode_uri_component(note)
224
316
  end
225
- headers
317
+ merge_headers(headers, options)
318
+ end
319
+
320
+ # `extra` over `headers`, matching names without regard to case, so each
321
+ # name is sent once.
322
+ def merge_headers(headers, extra)
323
+ extra.each_with_object(headers.dup) do |(name, value), merged|
324
+ name = name.to_s
325
+ merged.delete_if { |key, _| key.casecmp?(name) }
326
+ merged[name] = value.to_s
327
+ end
328
+ end
329
+
330
+ # A revision number, or a record or draft (anything with a revision, a
331
+ # Hash too).
332
+ def revision_of(if_match)
333
+ revision = if if_match.is_a?(Hash)
334
+ if_match.key?(:revision) ? if_match[:revision] : if_match["revision"]
335
+ else
336
+ if_match.respond_to?(:revision) ? if_match.revision : if_match
337
+ end
338
+ return revision if revision.is_a?(Integer)
339
+
340
+ raise ArgumentError, "if_match takes a revision number, or a record, draft or hash with a revision"
341
+ end
342
+
343
+ def checked_base_url(url)
344
+ # A loop rather than a regex, which backtracks on long runs of slashes.
345
+ url = url.to_s
346
+ stop = url.length
347
+ stop -= 1 while stop.positive? && url[stop - 1] == "/"
348
+ url = url[0, stop]
349
+ uri = URI.parse(url)
350
+ return url if %w[http https].include?(uri.scheme&.downcase) && !uri.host.to_s.empty?
351
+
352
+ raise Error, "base_url must be an http or https URL"
353
+ rescue URI::InvalidURIError
354
+ raise Error, "base_url must be an http or https URL"
226
355
  end
227
356
 
228
357
  def parse(response)
@@ -252,6 +381,11 @@ module Nohead
252
381
  [0.5 * (2**attempt), 8.0].min * (1 - (rand * 0.25))
253
382
  end
254
383
 
384
+ def wait_to_retry(url, attempt, delay, status: nil, error: nil)
385
+ @on_retry&.call(RetryEvent.new(attempt: attempt + 1, delay: delay, url: url, status: status, error: error))
386
+ pause(delay)
387
+ end
388
+
255
389
  def pause(seconds)
256
390
  sleep(seconds) if seconds.positive?
257
391
  end
@@ -259,15 +393,13 @@ module Nohead
259
393
  def warn_about(operation, headers)
260
394
  return unless @warnings
261
395
 
262
- if headers["deprecation"] && !@warned[operation]
263
- @warned[operation] = true
396
+ if !headers["deprecation"].to_s.strip.empty? && self.class.first_warning?(operation)
264
397
  sunset = headers["sunset"] ? " and will be removed after #{headers['sunset']}" : ""
265
398
  link = headers["link"].to_s[/<([^>]+)>/, 1]
266
399
  warn "[nohead] #{operation} is deprecated#{sunset}#{". See #{link}" if link}"
267
400
  end
268
- return unless headers["nohead-usage-warning"] && !@warned[:usage]
401
+ return unless headers["nohead-usage-warning"] && self.class.first_warning?(:usage)
269
402
 
270
- @warned[:usage] = true
271
403
  warn "[nohead] Over a plan limit: #{headers['nohead-usage-warning']}"
272
404
  end
273
405
 
data/lib/nohead/errors.rb CHANGED
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "json"
4
+
3
5
  module Nohead
4
6
  # The base of every error the SDK raises.
5
7
  class Error < StandardError; end
@@ -18,22 +20,36 @@ module Nohead
18
20
  attr_reader :headers
19
21
  # The parsed response body, or its text when it was not JSON.
20
22
  attr_reader :body
23
+ # The API's own message, without the status, type and request ID that
24
+ # `message` adds.
25
+ attr_reader :api_message
21
26
 
22
27
  def initialize(status, body, headers)
23
- error = Nohead.error_envelope(body)
28
+ # The SDK doesn't follow redirects: one means the base URL is off.
29
+ error = redirect?(status) ? {} : Nohead.error_envelope(body)
24
30
  @status = status
25
- @type = error["type"]
31
+ @type = redirect?(status) ? "redirect" : error["type"]
26
32
  @request_id = error["request_id"] || headers["x-request-id"]
27
33
  @details = Array(error["details"]).map { |detail| NoheadObject.wrap(detail) }
28
34
  @headers = headers
29
35
  @body = body
30
- super(error["message"] || "Request failed with status #{status}")
36
+ @api_message = if redirect?(status)
37
+ to = headers["location"].to_s.empty? ? "" : " to #{headers['location']}"
38
+ "The API answered with a redirect#{to}; check the base URL"
39
+ else
40
+ error["message"] || "Request failed with status #{status}"
41
+ end
42
+ super(@api_message)
31
43
  end
32
44
 
33
45
  def to_s
34
46
  suffix = request_id ? " (request #{request_id})" : ""
35
47
  "#{status} #{type || 'error'}: #{super}#{suffix}"
36
48
  end
49
+
50
+ private
51
+
52
+ def redirect?(status) = status.between?(300, 399)
37
53
  end
38
54
 
39
55
  class InvalidRequestError < APIError; end
@@ -99,7 +115,8 @@ module Nohead
99
115
 
100
116
  # The error for a response, by its `type`, or by status when it has none.
101
117
  def self.api_error(status, body, headers)
102
- klass = ERROR_CLASSES[error_envelope(body)["type"]] ||
118
+ klass = (APIError if status < 400) ||
119
+ ERROR_CLASSES[error_envelope(body)["type"]] ||
103
120
  if status == 503 then ServiceUnavailableError
104
121
  elsif status >= 500 then InternalServerError
105
122
  else APIError
@@ -114,13 +131,20 @@ module Nohead
114
131
  return {} unless error.is_a?(Hash)
115
132
 
116
133
  fields = error.slice("type", "message", "request_id").select { |_, value| value.is_a?(String) }
117
- # Only hashes: current_revision reads each detail's fields.
118
- fields["details"] = error["details"].grep(Hash) if error["details"].is_a?(Array)
134
+ fields["details"] = error["details"].map { |detail| error_detail(detail) } if error["details"].is_a?(Array)
119
135
  fields
120
136
  end
121
137
 
138
+ # A detail that isn't an object is kept, as its text, with the code "unknown".
139
+ def self.error_detail(detail)
140
+ return detail if detail.is_a?(Hash)
141
+
142
+ { "code" => "unknown", "message" => detail.is_a?(String) ? detail : JSON.generate(detail) }
143
+ end
144
+
145
+ # Seconds from `Retry-After`: a number of seconds or an HTTP date, else nil.
122
146
  def self.retry_after_seconds(headers)
123
- value = headers["retry-after"] or return nil
147
+ value = headers["retry-after"]&.strip or return nil
124
148
  return [Float(value), 0].max if value.match?(/\A\d+(\.\d+)?\z/)
125
149
 
126
150
  [Time.httpdate(value) - Time.now, 0].max
data/lib/nohead/images.rb CHANGED
@@ -13,29 +13,42 @@ module Nohead
13
13
  module_function
14
14
 
15
15
  # A rendition of an image (an asset, as an object or a Hash, or its `image_url`). fit: "contain"
16
- # fits inside the box, "cover" fills it, cropping, "fill" stretches to it.
16
+ # (the default, also for nil) fits inside the box, "cover" fills it, cropping, "fill" stretches to it.
17
17
  # gravity: is what a crop keeps ("sm" for smart, "fp:0.5:0.3" for a focal
18
18
  # point); options: any other processing options, as written in a URL
19
- # (["bl:2"]).
19
+ # (["bl:2"]). An empty string is the same as leaving an option out.
20
20
  def url(image, width: nil, height: nil, fit: "contain", format: nil, quality: nil, dpr: nil,
21
21
  gravity: nil, options: [])
22
+ gravity, format = [gravity, format].map { |value| value unless value.to_s.empty? }
23
+ options = [*options].reject { |option| option.to_s.empty? }
22
24
  base = base_of(image)
23
25
  check_options([gravity, *options])
24
26
  at = base.index("/plain/")
25
- parts = [resize(fit, width, height), ("g:#{gravity}" if gravity), ("dpr:#{dpr}" if dpr),
27
+ dpr = number(dpr)
28
+ quality = number(quality)
29
+ parts = [resize(fit, number(width), number(height)), ("g:#{gravity}" if gravity), ("dpr:#{dpr}" if dpr),
26
30
  ("q:#{quality}" if quality), *options].compact
27
31
  base[0...at] + parts.map { |part| "/#{part}" }.join + source(base[at..], format)
28
32
  end
29
33
 
30
- # rs:<fit>:<width>:<height>, or nothing without a size (0 is none).
34
+ # rs:<fit>:<width>:<height>, or nothing without a size.
31
35
  def resize(fit, width, height)
32
- type = FITS.fetch(fit.to_s) { raise ArgumentError, "fit must be one of #{FITS.keys.join(', ')}" }
33
- width = nil if width&.zero?
34
- height = nil if height&.zero?
36
+ fit = fit.to_s.empty? ? "contain" : fit.to_s
37
+ type = FITS.fetch(fit) { raise ArgumentError, "fit must be one of #{FITS.keys.join(', ')}" }
35
38
  "rs:#{type}:#{width || 0}:#{height || 0}" if width || height
36
39
  end
37
40
  private_class_method :resize
38
41
 
42
+ # A number as the other SDKs write it (2.0 is 2), or nil for none (0 and "" are none).
43
+ def number(value)
44
+ return nil if value == ""
45
+ return value unless value.is_a?(Numeric)
46
+ return nil if value.zero?
47
+
48
+ value.is_a?(Float) && value.finite? && value == value.round ? value.round : value
49
+ end
50
+ private_class_method :number
51
+
39
52
  def base_of(image)
40
53
  base = case image
41
54
  when String then image
@@ -97,4 +97,15 @@ module Nohead
97
97
 
98
98
  # The objects whose `data` is a record's field values.
99
99
  RECORD_DATA_OBJECTS = %w[draft record record_revision revert_preview].to_set.freeze
100
+
101
+ # The operations that take `rich_text`: how rich text fields read in the
102
+ # records and drafts they return.
103
+ RICH_TEXT_OPERATIONS = %w[
104
+ collections_search drafts_create drafts_discard drafts_get
105
+ drafts_list drafts_merge drafts_schedule drafts_unschedule
106
+ drafts_update projects_search record_drafts_list record_revisions_revert
107
+ records_bulk records_create records_delete records_get
108
+ records_list records_publish records_restore records_unpublish
109
+ records_update
110
+ ].to_set.freeze
100
111
  end
@@ -7,8 +7,9 @@ module Nohead
7
7
  # Uploads a file and returns the `ready` asset: creates the upload, sends
8
8
  # the bytes straight to storage, then completes it (which checks the
9
9
  # file). `file` is a path or an IO; for bytes, pass StringIO.new(bytes).
10
- # Raises UploadError if storage refuses the bytes, and ValidationError if
11
- # the file fails the checks.
10
+ # Raises UploadError if the bytes don't reach storage (it refuses them,
11
+ # can't be reached or times out, with the ConnectionError as its
12
+ # `cause`), and ValidationError if the file fails the checks.
12
13
  #
13
14
  # With an `idempotency_key`, running the same upload again resumes it:
14
15
  # the key starts the upload, and an asset that is already `ready` is
@@ -31,7 +32,11 @@ module Nohead
31
32
  end
32
33
  end
33
34
  upload = created.upload
34
- response = @client.put_upload(upload.url, upload["method"], upload.headers.to_h, source)
35
+ response = begin
36
+ @client.put_upload(upload.url, upload["method"], upload.headers.to_h, source)
37
+ rescue ConnectionError => e
38
+ raise UploadError, "Could not upload #{source.filename}: #{e.message}"
39
+ end
35
40
  ensure
36
41
  source.close
37
42
  end
@@ -105,16 +110,6 @@ module Nohead
105
110
  def usage(asset)
106
111
  @client.request("assets_usage", path: { asset_id: asset })
107
112
  end
108
-
109
- private
110
-
111
- # One value as it is, several as `[in]`; an empty list (like an asset
112
- # field's accepted_types) is no filter.
113
- def one_or_in(value)
114
- return value unless value.is_a?(Array)
115
-
116
- value.empty? ? nil : { in: value }
117
- end
118
113
  end
119
114
  end
120
115
  end