ruby-anvil 0.0.1.pre.rc.1

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/anvil/auth.rb ADDED
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Anvil
6
+ # Builds the Authorization header, the same way node-anvil and python-anvil do.
7
+ #
8
+ # An API key goes as HTTP Basic, `base64(api_key + ":")`: a username with an
9
+ # empty password. Anvil's OAuth access tokens are JWTs, which the API wants
10
+ # verbatim; any other token is base64 encoded, which the API still accepts for
11
+ # backwards compatibility.
12
+ module Auth
13
+ # Three dot-separated base64url segments. The signature can be empty.
14
+ JWT_PATTERN = /\A[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*\z/
15
+
16
+ module_function
17
+
18
+ # @param api_key [String, nil]
19
+ # @param access_token [String, nil] wins when both are given
20
+ # @return [String]
21
+ # @raise [ConfigurationError] when neither is given
22
+ def build_header(api_key: nil, access_token: nil)
23
+ unless access_token.nil? || access_token.empty?
24
+ return "Bearer #{access_token}" if jwt?(access_token)
25
+
26
+ return "Bearer #{encode(access_token)}"
27
+ end
28
+ return "Basic #{encode("#{api_key}:")}" unless api_key.nil? || api_key.empty?
29
+
30
+ raise ConfigurationError, "An api_key or an access_token is required"
31
+ end
32
+
33
+ # Whether a token is a JWT: three base64url segments whose header and
34
+ # payload decode to JSON objects, the header carrying a string `alg`.
35
+ #
36
+ # Stricter than the API's own check, so anything this says yes to the API
37
+ # treats as a JWT too.
38
+ #
39
+ # @param token [Object]
40
+ # @return [Boolean]
41
+ def jwt?(token)
42
+ return false unless token.is_a?(String) && token.match?(JWT_PATTERN)
43
+
44
+ header, payload = token.split(".").first(2).map { |segment| decode_json_segment(segment) }
45
+ !!(header && payload && header["alg"].is_a?(String))
46
+ end
47
+
48
+ # Decodes one base64url segment of a JWT with pack/unpack, not the base64 gem: CONTRIBUTING.md says why.
49
+ #
50
+ # @api private
51
+ def decode_json_segment(segment)
52
+ padded = segment + ("=" * (-segment.length % 4))
53
+ decoded = JSON.parse(padded.tr("-_", "+/").unpack1("m0"))
54
+ decoded.is_a?(Hash) ? decoded : nil
55
+ rescue ArgumentError, JSON::ParserError, Encoding::CompatibilityError
56
+ nil
57
+ end
58
+
59
+ # Strict base64, no line breaks.
60
+ #
61
+ # @api private
62
+ def encode(value)
63
+ [value].pack("m0")
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,624 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "stringio"
7
+ require "uri"
8
+
9
+ module Anvil
10
+ # The Anvil API client.
11
+ #
12
+ # client = Anvil::Client.new(api_key: ENV.fetch("ANVIL_API_KEY"))
13
+ # pdf = client.fill_pdf("kA6Da9CuGqUtc6QiBDRR", data: { name: "Sally" })
14
+ # File.binwrite("filled.pdf", pdf.data)
15
+ #
16
+ # Every endpoint is derived from `base_url`, so pointing the client at
17
+ # staging points all of it at staging:
18
+ #
19
+ # Anvil::Client.new(api_key: key, base_url: "https://staging.useanvil.com")
20
+ #
21
+ # Requests are rate limited for you. The client starts conservatively, then
22
+ # adopts your organization's real limit from the first response's headers. A
23
+ # 429 is retried after the delay the API asks for.
24
+ #
25
+ # Failures raise: see {Anvil::Error} and its subclasses.
26
+ class Client
27
+ # Where the API lives unless you say otherwise.
28
+ DEFAULT_BASE_URL = "https://app.useanvil.com"
29
+
30
+ # What the client allows itself before the API tells it the real limit.
31
+ DEFAULT_REQUEST_LIMIT = 1
32
+ DEFAULT_REQUEST_LIMIT_MS = 1000
33
+
34
+ # How many times a request the API could not answer is retried. Zero turns
35
+ # it off. A 429 does not count against this: the limiter retries it for as
36
+ # long as the API keeps asking.
37
+ DEFAULT_MAX_RETRIES = 5
38
+
39
+ # The statuses worth sending again: the API was reached but could not answer.
40
+ RETRY_STATUSES = [500, 502, 503, 504].freeze
41
+
42
+ # The first retry waits this long, each one after it twice as long.
43
+ RETRY_BACKOFF_MS = 100
44
+
45
+ # Seconds to wait for a connection, and for a response.
46
+ DEFAULT_TIMEOUT = 300
47
+
48
+ # The shapes a response body can be asked for.
49
+ DATA_TYPES = %i[string io stream json].freeze
50
+ # The shapes a PDF or a zip can be asked for.
51
+ BINARY_DATA_TYPES = %i[string io stream].freeze
52
+
53
+ # The HTTP methods {#request_rest} will send.
54
+ HTTP_METHODS = {
55
+ get: Net::HTTP::Get,
56
+ post: Net::HTTP::Post,
57
+ put: Net::HTTP::Put,
58
+ patch: Net::HTTP::Patch,
59
+ delete: Net::HTTP::Delete,
60
+ head: Net::HTTP::Head
61
+ }.freeze
62
+
63
+ # @return [String] the API this client talks to, without a trailing slash
64
+ attr_reader :base_url
65
+ # @return [String] the Authorization header every request is sent with
66
+ attr_reader :auth_header
67
+ # @return [String] the User-Agent every request is sent with
68
+ attr_reader :user_agent
69
+ # @return [RateLimiter] the limiter in force, replaced once the API's own
70
+ # limit is known
71
+ attr_reader :rate_limiter
72
+ # @return [Integer] how many times a 429 is retried
73
+ attr_reader :max_retries
74
+
75
+ # @param api_key [String] an API key from your Anvil organization settings.
76
+ # Defaults to the `ANVIL_API_KEY` environment variable
77
+ # @param access_token [String] an OAuth access token, instead of an API key
78
+ # @param base_url [String] the Anvil environment to talk to
79
+ # @param user_agent [String] overrides the User-Agent header
80
+ # @param request_limit [Integer] requests allowed per interval before the
81
+ # API's own limit is known
82
+ # @param request_limit_ms [Integer] that interval, in milliseconds
83
+ # @param max_retries [Integer] how many times to retry a request the API
84
+ # could not answer. Zero turns it off; a 429 is always retried
85
+ # @param timeout [Numeric] seconds to wait for a connection, and for a response
86
+ # @param share_rate_limiter [Boolean] share one limiter per process with
87
+ # every other client for the same environment and credentials
88
+ # @param rate_limiter [RateLimiter] a limiter of your own, instead
89
+ # @raise [ConfigurationError] when neither an API key nor an access token
90
+ # was given
91
+ def initialize(
92
+ api_key: ENV.fetch("ANVIL_API_KEY", nil),
93
+ access_token: nil,
94
+ base_url: DEFAULT_BASE_URL,
95
+ user_agent: nil,
96
+ request_limit: DEFAULT_REQUEST_LIMIT,
97
+ request_limit_ms: DEFAULT_REQUEST_LIMIT_MS,
98
+ max_retries: DEFAULT_MAX_RETRIES,
99
+ timeout: DEFAULT_TIMEOUT,
100
+ share_rate_limiter: true,
101
+ rate_limiter: nil
102
+ )
103
+ @auth_header = Auth.build_header(api_key: api_key, access_token: access_token)
104
+ @base_url = (base_url || DEFAULT_BASE_URL).to_s.sub(%r{/+\z}, "")
105
+ raise ConfigurationError, "base_url must be an http(s) URL" unless @base_url.match?(%r{\Ahttps?://})
106
+
107
+ @user_agent = user_agent || "ruby-anvil/#{Anvil::VERSION}"
108
+ @max_retries = max_retries.to_i
109
+ @timeout = timeout
110
+ @rate_limiter = rate_limiter || build_rate_limiter(share_rate_limiter, request_limit, request_limit_ms)
111
+ end
112
+
113
+ # Fills a PDF template with your data and returns the filled PDF.
114
+ #
115
+ # pdf = client.fill_pdf("kA6Da9CuGqUtc6QiBDRR", {
116
+ # title: "My PDF",
117
+ # data: { someFieldId: "Hello World!" }
118
+ # })
119
+ # File.binwrite("filled.pdf", pdf.data)
120
+ #
121
+ # @param pdf_template_id [String] the PDF template's eid, from its page in
122
+ # the Anvil dashboard
123
+ # @param payload [Payloads::FillPdf, Hash] the data to fill it with. Its
124
+ # keys can be passed as keyword arguments instead
125
+ # @param data_type [Symbol] `:string`, `:io` or `:stream`
126
+ # @param version_number [Integer] which version of the template to fill.
127
+ # Defaults to the latest published version; pass {Anvil::VERSION_LATEST}
128
+ # for the current draft
129
+ # @param to [IO] an IO to write a `:stream` response to
130
+ # @yieldparam chunk [String] each chunk of a `:stream` response
131
+ # @return [RestResponse]
132
+ def fill_pdf(pdf_template_id, payload = nil, data_type: :string, version_number: nil, to: nil,
133
+ **payload_kwargs, &block)
134
+ validate_data_type!(data_type, BINARY_DATA_TYPES)
135
+ raise ConfigurationError, "A pdf_template_id is required" if blank?(pdf_template_id)
136
+
137
+ path = "/api/v1/fill/#{escape(pdf_template_id)}.pdf"
138
+ path = "#{path}?versionNumber=#{escape(version_number)}" unless version_number.nil?
139
+
140
+ request_rest(
141
+ path,
142
+ method: :post,
143
+ body: payload || payload_kwargs,
144
+ data_type: data_type,
145
+ to: to,
146
+ &block
147
+ )
148
+ end
149
+
150
+ # Generates a PDF from HTML and CSS, or from markdown.
151
+ #
152
+ # pdf = client.generate_pdf(
153
+ # title: "Example",
154
+ # type: "html",
155
+ # data: { html: "<h1>Hello</h1>", css: "h1 { color: red }" }
156
+ # )
157
+ #
158
+ # @param payload [Payloads::GeneratePdf, Hash] the content to render. Its
159
+ # keys can be passed as keyword arguments instead
160
+ # @param data_type [Symbol] `:string`, `:io` or `:stream`
161
+ # @param to [IO] an IO to write a `:stream` response to
162
+ # @yieldparam chunk [String] each chunk of a `:stream` response
163
+ # @return [RestResponse]
164
+ def generate_pdf(payload = nil, data_type: :string, to: nil, **payload_kwargs, &block)
165
+ validate_data_type!(data_type, BINARY_DATA_TYPES)
166
+
167
+ request_rest(
168
+ "/api/v1/generate-pdf",
169
+ method: :post,
170
+ body: payload || payload_kwargs,
171
+ data_type: data_type,
172
+ to: to,
173
+ &block
174
+ )
175
+ end
176
+
177
+ # Downloads a document group's documents as a zip.
178
+ #
179
+ # @param document_group_eid [String]
180
+ # @param data_type [Symbol] `:string`, `:io` or `:stream`
181
+ # @param to [IO] an IO to write a `:stream` response to
182
+ # @yieldparam chunk [String] each chunk of a `:stream` response
183
+ # @return [RestResponse]
184
+ def download_documents(document_group_eid, data_type: :string, to: nil, &block)
185
+ validate_data_type!(data_type, BINARY_DATA_TYPES)
186
+ raise ConfigurationError, "A document_group_eid is required" if blank?(document_group_eid)
187
+
188
+ path = "/api/document-group/#{escape(document_group_eid)}.zip"
189
+ request_rest(path, method: :get, data_type: data_type, to: to, &block)
190
+ end
191
+
192
+ # Creates an Etch e-sign packet, and sends it to the first signer unless
193
+ # it is a draft.
194
+ #
195
+ # packet = client.create_etch_packet(variables: Anvil::Payloads::CreateEtchPacket.new(
196
+ # name: "Test Docs",
197
+ # is_test: true,
198
+ # files: [Anvil::Payloads::EtchFile.new(id: "template", cast_eid: "05xXsZko33JIO6aq5Pnr")],
199
+ # signers: [Anvil::Payloads::EtchSigner.new(id: "signer1", name: "Sally", email: "sally@example.com")]
200
+ # ))
201
+ # packet.details_url
202
+ #
203
+ # @param variables [Payloads::CreateEtchPacket, Hash]
204
+ # @param response_query [String] the fields to select on the new packet
205
+ # @param mutation [String] replaces the whole mutation, response query and all
206
+ # @return [Types::EtchPacket]
207
+ def create_etch_packet(variables:, response_query: nil, mutation: nil)
208
+ query = mutation || GraphQL::Mutations.create_etch_packet(*[response_query].compact)
209
+ response = request_graphql(query: query, variables: variables)
210
+ Types::EtchPacket.from_h(response["createEtchPacket"])
211
+ end
212
+
213
+ # Reads an Etch packet.
214
+ #
215
+ # @param eid [String] the packet's eid, a shorthand for `variables: { eid: }`
216
+ # @param variables [Hash] the query's variables, when you would rather pass them whole
217
+ # @param response_query [String] the fields to select
218
+ # @return [Types::EtchPacket]
219
+ def get_etch_packet(eid: nil, variables: nil, response_query: nil)
220
+ variables = merge_variables({ "eid" => eid }, variables)
221
+ query = GraphQL::Queries.etch_packet(*[response_query].compact)
222
+ response = request_graphql(query: query, variables: variables)
223
+ Types::EtchPacket.from_h(response["etchPacket"])
224
+ end
225
+
226
+ # Reads whoever the API key or access token belongs to.
227
+ #
228
+ # user = client.get_current_user
229
+ # user.email
230
+ # user.organizations.map(&:slug)
231
+ #
232
+ # @param response_query [String] the fields to select
233
+ # @return [Types::User]
234
+ def get_current_user(response_query: nil)
235
+ response = request_graphql(query: GraphQL::Queries.current_user(*[response_query].compact))
236
+ Types::User.from_h(response["currentUser"])
237
+ end
238
+
239
+ # Generates a signing URL for one signer of an existing packet. The signer
240
+ # must have been created with a `signer_type` of "embedded".
241
+ #
242
+ # @param signer_eid [String] the signer's eid, from the created packet
243
+ # @param client_user_id [String] your own id for the person signing
244
+ # @param variables [Hash] the mutation's variables, when you would rather
245
+ # pass them whole
246
+ # @return [String] the URL to send the signer to
247
+ def generate_etch_sign_url(signer_eid: nil, client_user_id: nil, variables: nil)
248
+ variables = merge_variables(
249
+ { "signerEid" => signer_eid, "clientUserId" => client_user_id },
250
+ variables
251
+ )
252
+ response = request_graphql(query: GraphQL::Mutations.generate_etch_sign_url, variables: variables)
253
+ response["generateEtchSignURL"]
254
+ end
255
+
256
+ # Submits data to one webform of a Workflow.
257
+ #
258
+ # @param variables [Payloads::ForgeSubmit, Hash]
259
+ # @param response_query [String] the fields to select on the submission
260
+ # @param mutation [String] replaces the whole mutation, response query and all
261
+ # @return [Types::Submission]
262
+ def forge_submit(variables:, response_query: nil, mutation: nil)
263
+ query = mutation || GraphQL::Mutations.forge_submit(*[response_query].compact)
264
+ response = request_graphql(query: query, variables: variables)
265
+ Types::Submission.from_h(response["forgeSubmit"])
266
+ end
267
+
268
+ # Removes a Workflow submission and everything in it. This cannot be undone.
269
+ #
270
+ # @param eid [String] the weld data's eid, a shorthand for `variables: { eid: }`
271
+ # @param variables [Hash] the mutation's variables, when you would rather
272
+ # pass them whole
273
+ # @param mutation [String] replaces the whole mutation
274
+ # @return [Boolean] whether it was removed
275
+ # rubocop:disable-next Naming/PredicateMethod -- it answers with a boolean, it does not ask one
276
+ def remove_weld_data(eid: nil, variables: nil, mutation: nil)
277
+ variables = merge_variables({ "eid" => eid }, variables)
278
+ query = mutation || GraphQL::Mutations.remove_weld_data
279
+ response = request_graphql(query: query, variables: variables)
280
+ !!response["removeWeldData"]
281
+ end
282
+
283
+ # Runs any GraphQL query or mutation, for the ones this client has no
284
+ # method of its own for.
285
+ #
286
+ # response = client.request_graphql(
287
+ # query: "query WeldData($eid: String!) { weldData(eid: $eid) { eid isComplete } }",
288
+ # variables: { eid: "nxflNZqxDUbltLUbYWK" }
289
+ # )
290
+ # response["weldData"]["isComplete"]
291
+ #
292
+ # Files anywhere in `variables` are uploaded as multipart, per the GraphQL
293
+ # multipart request spec. Prepare each one with {Anvil.prepare_graphql_file}.
294
+ #
295
+ # @param query [String] the query or mutation
296
+ # @param variables [Hash, Payloads::Base]
297
+ # @return [GraphQLResponse]
298
+ # @raise [GraphQLError] when the response carries GraphQL errors
299
+ # @see https://www.useanvil.com/docs/api/graphql/reference/
300
+ def request_graphql(query:, variables: {})
301
+ operation = { query: query, variables: normalize_payload(variables) || {} }
302
+ raise ConfigurationError, "Invalid File schema detected" unless Uploads.valid_upload_schema?(operation)
303
+
304
+ clone, found = Uploads.extract_files(operation)
305
+ operations = JSON.generate(clone)
306
+
307
+ response =
308
+ if found.empty?
309
+ request_rest(
310
+ "/graphql",
311
+ method: :post,
312
+ body: operations,
313
+ headers: { "Content-Type" => "application/json" },
314
+ data_type: :json
315
+ )
316
+ else
317
+ request_multipart_graphql(operations: operations, found: found)
318
+ end
319
+
320
+ GraphQLResponse.new(status_code: response.status_code, headers: response.headers, body: response.data)
321
+ end
322
+
323
+ # Runs any REST request against the API, for the endpoints this client has
324
+ # no method of its own for.
325
+ #
326
+ # response = client.request_rest("/api/v1/generate-pdf", method: :post, body: payload)
327
+ #
328
+ # @param path [String] a path from `base_url`, or a whole URL
329
+ # @param method [Symbol] `:get`, `:post`, `:put`, `:patch`, `:delete` or `:head`
330
+ # @param body [Hash, Payloads::Base, String, nil] a Hash is sent as JSON
331
+ # @param headers [Hash] extra request headers
332
+ # @param data_type [Symbol] `:string`, `:io`, `:json` or `:stream`
333
+ # @param to [IO] an IO to write a `:stream` response to
334
+ # @yieldparam chunk [String] each chunk of a `:stream` response
335
+ # @return [RestResponse]
336
+ def request_rest(path, method: :get, body: nil, headers: {}, data_type: :string, to: nil, &block)
337
+ validate_data_type!(data_type, DATA_TYPES)
338
+
339
+ uri = build_uri(path)
340
+ request = build_request(uri, method: method, headers: headers)
341
+ apply_body(request, body)
342
+
343
+ perform(uri, request, data_type: data_type, to: to, &block)
344
+ end
345
+
346
+ private
347
+
348
+ def request_multipart_graphql(operations:, found:)
349
+ map = {}
350
+ found.each_with_index { |(_upload, paths), index| map[(index + 1).to_s] = paths }
351
+
352
+ multipart = Multipart.build(operations: operations, map: JSON.generate(map), uploads: found.map(&:first))
353
+ begin
354
+ uri = build_uri("/graphql")
355
+ request = build_request(uri, method: :post, headers: { "Content-Type" => multipart.content_type })
356
+ request.body_stream = multipart.io
357
+ request["Content-Length"] = multipart.content_length.to_s
358
+
359
+ perform(uri, request, data_type: :json)
360
+ ensure
361
+ multipart.close
362
+ end
363
+ end
364
+
365
+ # Runs the request under the rate limiter, which retries a 429 for as long
366
+ # as the API keeps asking, and retries here what the API could not answer.
367
+ def perform(uri, request, data_type:, to: nil, &block)
368
+ attempt = 0
369
+
370
+ begin
371
+ rate_limiter.run do
372
+ rewind_body(request)
373
+ send_request(uri, request, data_type: data_type, to: to, &block)
374
+ end
375
+ rescue ServerError, ConnectionError => e
376
+ attempt += 1
377
+ raise if attempt > max_retries || !retryable?(e)
378
+
379
+ sleep(retry_delay(e, attempt))
380
+ retry
381
+ end
382
+ end
383
+
384
+ # A 5xx the API named as temporary, or a connection that never got there.
385
+ # A timeout is not retried: the request may well have been acted on.
386
+ def retryable?(error)
387
+ return RETRY_STATUSES.include?(error.status_code) if error.is_a?(ServerError)
388
+
389
+ !error.cause_error.is_a?(Timeout::Error)
390
+ end
391
+
392
+ # The delay the response asked for, or exponential backoff.
393
+ def retry_delay(error, attempt)
394
+ asked = error.is_a?(ServerError) ? error.headers["retry-after"] : nil
395
+ return RateLimiter.retry_delay_seconds(asked) if asked
396
+
397
+ (RETRY_BACKOFF_MS * (2**(attempt - 1))) / 1000.0
398
+ end
399
+
400
+ def send_request(uri, request, data_type:, to: nil, &block)
401
+ http = Net::HTTP.new(uri.hostname, uri.port)
402
+ http.use_ssl = uri.scheme == "https"
403
+ http.open_timeout = @timeout
404
+ http.read_timeout = @timeout
405
+
406
+ # Net::HTTP#request hands back the raw response, not the block's value,
407
+ # so the handled result comes out through this
408
+ result = nil
409
+ http.start do |session|
410
+ session.request(request) do |response|
411
+ result = handle_response(response, data_type: data_type, to: to, &block)
412
+ end
413
+ end
414
+ result
415
+ rescue Timeout::Error, SystemCallError, IOError, OpenSSL::SSL::SSLError,
416
+ Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, SocketError => e
417
+ raise ConnectionError.new("Could not reach #{uri}: #{e.message}", cause_error: e)
418
+ end
419
+
420
+ def handle_response(response, data_type:, to: nil, &block)
421
+ status_code = response.code.to_i
422
+ headers = normalize_headers(response)
423
+ rate_limiter.update_from_headers(headers)
424
+
425
+ raise_rate_limited(response, status_code, headers) if status_code == 429
426
+
427
+ # Whatever was asked for, a JSON body is read and parsed: the GraphQL
428
+ # endpoint reports failure in a 200, and the REST endpoints answer with
429
+ # JSON when they fail even though they return PDFs when they succeed.
430
+ raw = json?(headers["content-type"]) ? read_all(response) : nil
431
+ json = raw && parse_json(raw)
432
+
433
+ check_for_errors(response, status_code, headers, raw, json)
434
+ data = extract_data(response, data_type: data_type, to: to, raw: raw, json: json, &block)
435
+
436
+ RestResponse.new(status_code: status_code, headers: headers, data: data)
437
+ end
438
+
439
+ def check_for_errors(response, status_code, headers, raw, json)
440
+ # GraphQL reports failure in a 200, so its errors array is checked whatever
441
+ # the status. A 2xx carrying only `message` or `name` is NOT an error: node
442
+ # treats it as one, and the SDK conventions call that a legacy divergence.
443
+ raise_response_error(status_code, json, headers, response.message) if graphql_errors?(json)
444
+ return if status_code < 300
445
+
446
+ raise_response_error(
447
+ status_code, json, headers, response.message,
448
+ body: json || raw || read_all(response)
449
+ )
450
+ end
451
+
452
+ def extract_data(response, data_type:, to:, raw:, json:, &block)
453
+ case data_type
454
+ when :json then json || parse_json(raw || read_all(response))
455
+ when :io then StringIO.new(raw || read_all(response))
456
+ when :stream then stream_body(response, to: to, raw: raw, &block)
457
+ else raw || read_all(response)
458
+ end
459
+ end
460
+
461
+ # Hands each chunk to the block or writes it to `to:` as it arrives, so a
462
+ # large PDF never has to be held whole.
463
+ def stream_body(response, to:, raw: nil, &block)
464
+ raise ConfigurationError, "A data_type of :stream needs a block or a `to:` IO to write to" unless block || to
465
+
466
+ written = 0
467
+ consume = lambda do |chunk|
468
+ written += chunk.bytesize
469
+ to&.write(chunk)
470
+ block&.call(chunk)
471
+ end
472
+
473
+ # A JSON body was already read whole to check it for errors
474
+ if raw
475
+ consume.call(raw)
476
+ else
477
+ response.read_body { |chunk| consume.call(chunk) }
478
+ end
479
+
480
+ written
481
+ end
482
+
483
+ def raise_rate_limited(response, status_code, headers)
484
+ drain(response)
485
+ retry_after = headers["retry-after"]&.to_f
486
+
487
+ raise RateLimitError.new(
488
+ "Rate limited by the Anvil API. Retry after #{retry_after || "an unspecified number of"} seconds.",
489
+ retry_after: retry_after,
490
+ status_code: status_code,
491
+ headers: headers
492
+ )
493
+ end
494
+
495
+ def graphql_errors?(json)
496
+ json.is_a?(Hash) && json["errors"].is_a?(Array) && !json["errors"].empty?
497
+ end
498
+
499
+ def raise_response_error(status_code, json, headers, status_text, body: nil)
500
+ errors = Errors.normalize(json, status_text: blank?(status_text) ? "Unknown Error" : status_text)
501
+
502
+ error_class =
503
+ if status_code >= 300
504
+ Errors.error_class_for(status_code)
505
+ elsif graphql_errors?(json)
506
+ GraphQLError
507
+ else
508
+ ResponseError
509
+ end
510
+
511
+ raise error_class.new(
512
+ nil,
513
+ status_code: status_code,
514
+ errors: errors,
515
+ body: body.nil? ? json : body,
516
+ headers: headers
517
+ )
518
+ end
519
+
520
+ def build_uri(path)
521
+ url = path.to_s.start_with?("http://", "https://") ? path.to_s : "#{base_url}#{path}"
522
+ URI.parse(url)
523
+ rescue URI::InvalidURIError => e
524
+ raise ConfigurationError, "Invalid URL #{path.inspect}: #{e.message}"
525
+ end
526
+
527
+ def build_request(uri, method:, headers: {})
528
+ klass = HTTP_METHODS[method.to_s.downcase.to_sym]
529
+ raise ConfigurationError, "Unsupported HTTP method #{method.inspect}" if klass.nil?
530
+
531
+ request = klass.new(uri)
532
+ request["Authorization"] = auth_header
533
+ request["User-Agent"] = user_agent
534
+ # Streaming a response is simpler, and the chunk sizes honest, when the
535
+ # body is not compressed in flight
536
+ request["Accept-Encoding"] = "identity"
537
+ headers.each { |name, value| request[name.to_s] = value unless value.nil? }
538
+ request
539
+ end
540
+
541
+ def apply_body(request, body)
542
+ return if body.nil?
543
+ return if body.respond_to?(:empty?) && body.empty? && !body.is_a?(String)
544
+
545
+ if body.is_a?(String)
546
+ request.body = body
547
+ return
548
+ end
549
+
550
+ request["Content-Type"] ||= "application/json"
551
+ request.body = JSON.generate(normalize_payload(body))
552
+ end
553
+
554
+ def rewind_body(request)
555
+ request.body_stream&.rewind
556
+ rescue IOError, NoMethodError
557
+ nil
558
+ end
559
+
560
+ # Turns a payload object into the Hash the API wants, and leaves a Hash alone.
561
+ def normalize_payload(payload)
562
+ return nil if payload.nil?
563
+ return payload.to_h if payload.is_a?(Payloads::Base)
564
+
565
+ payload
566
+ end
567
+
568
+ def merge_variables(named, variables)
569
+ given = normalize_payload(variables) || {}
570
+ named.compact.merge(given.to_h)
571
+ end
572
+
573
+ def build_rate_limiter(shared, limit, interval_ms)
574
+ return RateLimiter.new(limit: limit, interval_ms: interval_ms) unless shared
575
+
576
+ RateLimiter.shared(
577
+ base_url: @base_url,
578
+ auth_header: @auth_header,
579
+ limit: limit,
580
+ interval_ms: interval_ms
581
+ )
582
+ end
583
+
584
+ def normalize_headers(response)
585
+ response.each_header.to_h { |name, value| [name.to_s.downcase, value] }
586
+ end
587
+
588
+ def json?(content_type)
589
+ content_type.to_s.downcase.include?("application/json")
590
+ end
591
+
592
+ def parse_json(body)
593
+ return nil if body.nil? || body.empty?
594
+
595
+ JSON.parse(body)
596
+ rescue JSON::ParserError => e
597
+ raise ConnectionError.new("Could not parse the API's JSON response: #{e.message}", cause_error: e)
598
+ end
599
+
600
+ def read_all(response)
601
+ response.read_body || ""
602
+ end
603
+
604
+ def drain(response)
605
+ response.read_body { |_chunk| nil }
606
+ rescue IOError
607
+ nil
608
+ end
609
+
610
+ def validate_data_type!(data_type, allowed)
611
+ return if allowed.include?(data_type)
612
+
613
+ raise ConfigurationError, "data_type must be one of #{allowed.map(&:inspect).join(", ")}"
614
+ end
615
+
616
+ def escape(value)
617
+ URI.encode_www_form_component(value.to_s)
618
+ end
619
+
620
+ def blank?(value)
621
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
622
+ end
623
+ end
624
+ end