pinesandbox 0.3.19 → 0.3.21

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.
@@ -0,0 +1,785 @@
1
+ require "faraday"
2
+ require "json"
3
+ require "pathname"
4
+ require "securerandom"
5
+ require "stringio"
6
+ require "time"
7
+ require "uri"
8
+ require_relative "adapters/coordinator_adapter"
9
+ require_relative "clock"
10
+ require_relative "errors"
11
+ require_relative "response_handler"
12
+ require_relative "streamed_read"
13
+ require_relative "version"
14
+ require_relative "models/artifact_file"
15
+ require_relative "timeouts"
16
+ require_relative "adapters/connect_aware_net_http"
17
+
18
+ module PineSandbox
19
+ # @api private — what a path in a Computer's artifacts may be, checked the
20
+ # same way by every SDK, pine-artifact and Pine before any request (a copy
21
+ # of contract/artifact-paths.json, which the test suite runs).
22
+ module ArtifactPath
23
+ MAX_BYTES = 900
24
+ # The C0 and C1 control characters.
25
+ CONTROL = /[\u0000-\u001F\u007F-\u009F]/
26
+
27
+ module_function
28
+
29
+ # Returns `path` as UTF-8 when it is 1 to MAX_BYTES bytes of valid UTF-8
30
+ # with no control character and no empty, "." or ".." segment (so no
31
+ # leading, trailing or doubled "/"); raises ArgumentError otherwise.
32
+ # Anything else is allowed. `name` is the argument, for the message.
33
+ def check!(path, name: "artifact path")
34
+ raise ArgumentError, "#{name} must be a String" unless path.is_a?(String)
35
+ raise ArgumentError, "#{name} must be 1 to #{MAX_BYTES} bytes" unless path.bytesize.between?(1, MAX_BYTES)
36
+
37
+ utf8 = path.dup.force_encoding(Encoding::UTF_8)
38
+ raise ArgumentError, "#{name} must be valid UTF-8" unless utf8.valid_encoding?
39
+ raise ArgumentError, "#{name} must not contain a control character" if utf8.match?(CONTROL)
40
+ if utf8.split("/", -1).any? { |segment| segment.empty? || segment == "." || segment == ".." }
41
+ raise ArgumentError, "#{name} must not have an empty, \".\" or \"..\" segment"
42
+ end
43
+
44
+ utf8
45
+ end
46
+ end
47
+
48
+ # @api private — the content type an upload gets when it names none, the
49
+ # same in every SDK whatever the host's MIME database holds (a copy of
50
+ # contract/artifact-content-types.json, which the test suite checks this
51
+ # table against).
52
+ module ArtifactContentType
53
+ DEFAULT = "application/octet-stream"
54
+ # By extension, in lower case.
55
+ TYPES = {
56
+ "css" => "text/css",
57
+ "csv" => "text/csv",
58
+ "doc" => "application/msword",
59
+ "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
60
+ "gif" => "image/gif",
61
+ "gz" => "application/gzip",
62
+ "htm" => "text/html",
63
+ "html" => "text/html",
64
+ "jpeg" => "image/jpeg",
65
+ "jpg" => "image/jpeg",
66
+ "js" => "text/javascript",
67
+ "json" => "application/json",
68
+ "md" => "text/markdown",
69
+ "mp3" => "audio/mpeg",
70
+ "mp4" => "video/mp4",
71
+ "pdf" => "application/pdf",
72
+ "png" => "image/png",
73
+ "ppt" => "application/vnd.ms-powerpoint",
74
+ "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
75
+ "svg" => "image/svg+xml",
76
+ "tar" => "application/x-tar",
77
+ "tsv" => "text/tab-separated-values",
78
+ "txt" => "text/plain",
79
+ "wav" => "audio/wav",
80
+ "webm" => "video/webm",
81
+ "webp" => "image/webp",
82
+ "xls" => "application/vnd.ms-excel",
83
+ "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
84
+ "xml" => "application/xml",
85
+ "yaml" => "application/yaml",
86
+ "yml" => "application/yaml",
87
+ "zip" => "application/zip"
88
+ }.freeze
89
+
90
+ module_function
91
+
92
+ # The type for the extension of `path`'s last segment: what follows its
93
+ # last ".", unless that "." starts the segment, in lower case. DEFAULT
94
+ # for any other path.
95
+ def for_path(path)
96
+ segment = path.rpartition("/").last
97
+ dot = segment.rindex(".")
98
+ return DEFAULT unless dot&.positive?
99
+
100
+ TYPES.fetch(segment[(dot + 1)..].downcase, DEFAULT)
101
+ end
102
+ end
103
+
104
+ # client.artifacts(computer_id) — a Computer's artifacts: the files it keeps
105
+ # beyond its sessions, reachable with the project key whether the Computer
106
+ # is running or stopped.
107
+ #
108
+ # artifacts = client.artifacts(computer_id)
109
+ # page = artifacts.list(prefix: "research/") # page.files, page.folders, page.next_page_token
110
+ # artifacts.upload("inputs/brief.txt", Pathname("brief.txt"), note: "the brief")
111
+ # artifacts.download("reports/q3.pdf", "q3.pdf") # => bytes written
112
+ # artifacts.open("reports/q3.csv") { |chunk| io.write(chunk) }
113
+ # artifacts.copy(other_computer_id, "templates/form.pdf", "inputs/form.pdf")
114
+ # artifacts.delete("inputs/brief.txt")
115
+ #
116
+ # A path is relative to the Computer's artifacts, such as "reports/q3.pdf":
117
+ # 1 to 900 bytes of UTF-8 with no control character and no empty, "." or
118
+ # ".." segment, or the call raises ArgumentError before any request.
119
+ # The handle gets one short-lived storage token from Pine, then sends every
120
+ # request to storage itself: no file passes through Pine. It keeps the
121
+ # token and gets a new one before it lapses, or once when storage refuses
122
+ # it. A missing file is ArtifactNotFoundError; any other refusal from
123
+ # storage is the status tier's ApiError, with storage's message, and an
124
+ # answer the storage protocol doesn't allow, such as a success whose body
125
+ # isn't a JSON object, is PineSandbox::Error. An error's #retryable? follows
126
+ # the storage rule every SDK shares (contract/storage-retry.json): true for
127
+ # a request timeout, a 429 and any 5xx but 501. An error's #op names the
128
+ # route with "{object}" for the file's name; the path is only in typed
129
+ # fields such as ArtifactNotFoundError#path. Public links are the running
130
+ # Computer's: Computer#artifact_link.
131
+ class Artifacts
132
+ include PineSandbox::ResponseHandler
133
+
134
+ # A token is replaced this many seconds before it expires.
135
+ TOKEN_RENEW_BEFORE = 300
136
+
137
+ # The storage token and where the artifacts are. The access token never
138
+ # appears in #inspect.
139
+ Token = Struct.new(:access_token, :expires_at, :endpoint, :bucket, :prefix, :writable,
140
+ :used_bytes, :limit_bytes, :copy_from, keyword_init: true) do
141
+ def self.from_payload(payload)
142
+ new(access_token: payload["access_token"], expires_at: Time.iso8601(payload["expires_at"]),
143
+ endpoint: payload["endpoint"].delete_suffix("/"), bucket: payload["bucket"],
144
+ prefix: payload["prefix"], writable: payload["writable"], used_bytes: payload["used_bytes"],
145
+ limit_bytes: payload["limit_bytes"], copy_from: payload["copy_from"] || {})
146
+ end
147
+
148
+ def inspect = "#<PineSandbox::Artifacts::Token bucket=#{bucket.inspect} prefix=#{prefix.inspect} [access_token redacted]>"
149
+ alias_method :to_s, :inspect
150
+
151
+ def pretty_print(printer) = printer.text(inspect)
152
+ end
153
+ private_constant :Token
154
+
155
+ # An upload's bytes, readable from any offset: a String, a local file (a
156
+ # Pathname), or an IO whose size is known, read from its current position.
157
+ class Upload
158
+ attr_reader :size
159
+
160
+ def initialize(source)
161
+ @start = 0
162
+ case source
163
+ when String
164
+ @io = StringIO.new(source)
165
+ @size = source.bytesize
166
+ when Pathname
167
+ @path = source
168
+ @size = File.size(source)
169
+ else
170
+ unless %i[read size seek pos].all? { |name| source.respond_to?(name) }
171
+ raise ArgumentError, "source must be a String of bytes, a Pathname, or an IO whose size is known"
172
+ end
173
+
174
+ @io = source
175
+ @start = source.pos
176
+ @size = source.size - @start
177
+ end
178
+ end
179
+
180
+ # Yields the bytes from `offset` to the end, as an IO.
181
+ def from(offset)
182
+ io = @path ? File.open(@path, "rb") : @io
183
+ io.seek(@start + offset)
184
+ yield io
185
+ ensure
186
+ io&.close if @path
187
+ end
188
+ end
189
+ private_constant :Upload
190
+
191
+ BlockError = StreamedRead::BlockError
192
+ private_constant :BlockError
193
+
194
+ attr_reader :computer_id
195
+
196
+ # @api private — Client#artifacts builds the handle. `token_source` is
197
+ # the project-key Portal client (#artifact_token).
198
+ def initialize(computer_id:, token_source:, clock: PineSandbox::SYSTEM_CLOCK, timeouts: Timeouts::DEFAULT)
199
+ @computer_id = computer_id
200
+ @token_source = token_source
201
+ @clock = clock
202
+ @timeouts = timeouts
203
+ @tokens = {}
204
+ @connections = {}
205
+ @mutex = Mutex.new
206
+ end
207
+
208
+ # One page of the files under `prefix` ("" for all of them, "research/"
209
+ # for one folder). Unless `recursive`, a file in a deeper folder is
210
+ # summarized by its folder in the page's #folders. Pass a page's
211
+ # #next_page_token as `page_token` for the next one; `page_size` caps how
212
+ # many files and folders a page holds.
213
+ #
214
+ # @return [PineSandbox::Models::ArtifactPage]
215
+ def list(prefix: "", recursive: false, page_token: nil, page_size: nil)
216
+ unless page_size.nil? || (page_size.is_a?(Integer) && page_size.positive?)
217
+ raise ArgumentError, "page_size must be a positive integer"
218
+ end
219
+
220
+ with_token do |token|
221
+ params = { "prefix" => "#{token.prefix}#{prefix}" }
222
+ params["delimiter"] = "/" unless recursive
223
+ params["pageToken"] = page_token if page_token
224
+ params["maxResults"] = page_size if page_size
225
+ route = objects_route(token)
226
+ op = "GET /#{route}"
227
+ response = resending { storage_request(token, :get, route, op: op, params: params) }
228
+ raise_storage_error!(response, op: op) unless response.success?
229
+
230
+ body = parse_answer(response, op: op)
231
+ Models::ArtifactPage.new(
232
+ files: Array(body["items"]).map { |object| Models::ArtifactFile.from_object(object, prefix: token.prefix) },
233
+ folders: Array(body["prefixes"]).map { |folder| folder.delete_prefix(token.prefix) },
234
+ next_page_token: body["nextPageToken"]
235
+ )
236
+ end
237
+ end
238
+
239
+ # Saves `source` as the file at `path`, replacing any file there, and
240
+ # returns the saved file. `source` is the bytes (a String), a local file
241
+ # (a Pathname), or an IO whose size is known, such as a File, StringIO or
242
+ # Tempfile, read from its current position. `content_type` defaults to
243
+ # the one every SDK gives the path's extension, else
244
+ # application/octet-stream; `note` is kept with the file and listed with
245
+ # it.
246
+ #
247
+ # The bytes go to storage in one resumable transfer, whose start is sent
248
+ # again when its answer is lost. After a dropped connection or a storage
249
+ # answer worth retrying mid-transfer (a request timeout, a 429 or a 5xx but
250
+ # 501), the SDK waits (RetryPolicy's stream backoff), asks storage how much
251
+ # it kept, and sends the rest; it gives up after
252
+ # RetryPolicy::STREAM_RECONNECT_BUDGET tries in a row that moved nothing.
253
+ # Raises ArtifactStorageFullError, sending nothing, while the Computer's
254
+ # artifacts are over their limit; after one, the next upload or copy asks
255
+ # Pine again, so room made by deleting files is used.
256
+ #
257
+ # @return [PineSandbox::Models::ArtifactFile]
258
+ def upload(path, source, content_type: nil, note: nil)
259
+ path = ArtifactPath.check!(path)
260
+ upload = Upload.new(source)
261
+ content_type ||= ArtifactContentType.for_path(path)
262
+ token, session = with_token(write: true) do |current|
263
+ [current, start_upload(current, "#{current.prefix}#{path}", upload.size, content_type, note)]
264
+ end
265
+ Models::ArtifactFile.from_object(send_upload(session, upload, content_type), prefix: token.prefix)
266
+ end
267
+
268
+ # Saves the file at `path` to the local file `destination` and returns
269
+ # the number of bytes written. The bytes land in a temporary file beside
270
+ # `destination` that is renamed over it once complete, so `destination`
271
+ # is never left half-written. It resumes as #open does.
272
+ def download(path, destination)
273
+ path = ArtifactPath.check!(path)
274
+ destination = File.expand_path(destination.to_s)
275
+ part = File.join(File.dirname(destination), ".#{File.basename(destination)}.#{SecureRandom.hex(6)}.part")
276
+ written = File.open(part, File::WRONLY | File::CREAT | File::EXCL | File::BINARY) do |file|
277
+ receive(path) { |chunk| file.write(chunk) }
278
+ end
279
+ File.rename(part, destination)
280
+ written
281
+ ensure
282
+ File.delete(part) if part && File.exist?(part)
283
+ end
284
+
285
+ # The file at `path` as a stream, for copying onward without holding it
286
+ # in memory: yields binary chunks as they arrive. Without a block,
287
+ # returns an Enumerator of the chunks that sends the request only when
288
+ # iterated (`artifacts.open(path).each { |chunk| io.write(chunk) }`).
289
+ #
290
+ # After a dropped connection, a request timeout, a 429 or a 5xx but 501,
291
+ # the SDK waits (RetryPolicy's stream backoff) and asks again from the
292
+ # next byte, of
293
+ # the same version of the file: one replaced meanwhile raises storage's
294
+ # PreconditionFailedError rather than joining two versions. It gives up
295
+ # after RetryPolicy::STREAM_RECONNECT_BUDGET tries in a row that received
296
+ # nothing. A missing file raises ArtifactNotFoundError before any chunk.
297
+ #
298
+ # @yieldparam chunk [String] the next bytes, binary encoding.
299
+ # @return [nil, Enumerator]
300
+ def open(path, &block)
301
+ path = ArtifactPath.check!(path)
302
+ return enum_for(:open, path) unless block
303
+
304
+ receive(path, &block)
305
+ nil
306
+ end
307
+
308
+ # Copies the file at `from_path` in `from_computer_id` (this Computer or
309
+ # another of the project's) to `path` in this one, replacing any file
310
+ # there, and returns the copy. Storage copies the bytes itself; nothing is
311
+ # downloaded, and a step whose answer was lost is sent again. Raises
312
+ # ArtifactNotFoundError for `from_path` when that file isn't there, and
313
+ # ArtifactStorageFullError, copying nothing, while this Computer's
314
+ # artifacts are over their limit.
315
+ #
316
+ # @return [PineSandbox::Models::ArtifactFile]
317
+ def copy(from_computer_id, from_path, path)
318
+ unless from_computer_id.to_s.match?(Computer::UUID_V7)
319
+ raise ArgumentError, "from_computer_id must be a lowercase UUIDv7"
320
+ end
321
+ from_path = ArtifactPath.check!(from_path, name: "from_path")
322
+ path = ArtifactPath.check!(path)
323
+
324
+ # A copy within this Computer reads with its own token, under its own
325
+ # prefix; another Computer's files need a token that may read them.
326
+ source_id = from_computer_id == @computer_id ? nil : from_computer_id
327
+ # A large file takes several rewrite calls; each answer says how to go on.
328
+ rewrite_token = nil
329
+ op = nil
330
+ loop do
331
+ token, body = with_token(copy_from: source_id, write: true) do |current|
332
+ source_prefix = source_id ? current.copy_from.fetch(source_id) : current.prefix
333
+ source, source_label = object_route(current, "#{source_prefix}#{from_path}")
334
+ target = "/rewriteTo/b/#{escape(current.bucket)}/o/"
335
+ route = "#{source}#{target}#{escape("#{current.prefix}#{path}")}"
336
+ op = "POST /#{source_label}#{target}{object}"
337
+ params = rewrite_token ? { "rewriteToken" => rewrite_token } : {}
338
+ # Rewriting the same object to the same name again changes nothing,
339
+ # so a rewrite whose answer was lost is sent again.
340
+ response = resending { storage_request(current, :post, route, op: op, params: params, json: {}) }
341
+ raise_storage_error!(response, op: op, path: from_path) unless response.success?
342
+
343
+ [current, parse_answer(response, op: op)]
344
+ end
345
+ if body["done"] == true
346
+ unless body["resource"].is_a?(Hash)
347
+ raise PineSandbox::Error, PineSandbox.with_context("storage ended the copy without the copy", op: op)
348
+ end
349
+
350
+ return Models::ArtifactFile.from_object(body["resource"], prefix: token.prefix)
351
+ end
352
+
353
+ rewrite_token = body["rewriteToken"]
354
+ if rewrite_token.to_s.empty?
355
+ raise PineSandbox::Error, PineSandbox.with_context("storage stopped the copy without finishing it", op: op)
356
+ end
357
+ end
358
+ end
359
+
360
+ # Deletes the file at `path`. Raises ArtifactNotFoundError when it isn't
361
+ # there. A delete whose answer was lost is sent again; when that finds no
362
+ # file, the first one removed it, and the delete succeeds. Returns true.
363
+ def delete(path)
364
+ path = ArtifactPath.check!(path)
365
+ with_token do |token|
366
+ route, label = object_route(token, "#{token.prefix}#{path}")
367
+ op = "DELETE /#{label}"
368
+ resent = false
369
+ response = resending do |resend|
370
+ resent = resend
371
+ storage_request(token, :delete, route, op: op)
372
+ end
373
+ next if response.status == 404 && resent
374
+
375
+ raise_storage_error!(response, op: op, path: path) unless response.success?
376
+ end
377
+ true
378
+ end
379
+
380
+ private
381
+
382
+ # Runs the block with a current storage token: this Computer's or, with
383
+ # `copy_from`, one that may also read that Computer's artifacts. When
384
+ # storage refuses the token (401), runs it once more with a new one.
385
+ # `write` needs a writable token: a kept one that isn't is replaced, and
386
+ # a new one that isn't either means the artifacts are over their limit.
387
+ def with_token(copy_from: nil, write: false)
388
+ current = token(copy_from, write: write)
389
+ renewed = false
390
+ begin
391
+ if write && !current.writable
392
+ raise ArtifactStorageFullError.new(used_bytes: current.used_bytes, limit_bytes: current.limit_bytes)
393
+ end
394
+
395
+ yield current
396
+ rescue UnauthorizedError
397
+ raise if renewed
398
+
399
+ renewed = true
400
+ current = token(copy_from, refused: current, write: write)
401
+ retry
402
+ end
403
+ end
404
+
405
+ # The kept token for `copy_from`, or a new one when there is none, when it
406
+ # expires within TOKEN_RENEW_BEFORE, when it is the one storage `refused`,
407
+ # or when a `write` finds it read-only (files may have been deleted since).
408
+ def token(copy_from, refused: nil, write: false)
409
+ @mutex.synchronize do
410
+ kept = @tokens[copy_from]
411
+ usable = kept && !kept.equal?(refused) && (kept.writable || !write) &&
412
+ @clock.now < kept.expires_at - TOKEN_RENEW_BEFORE
413
+ return kept if usable
414
+
415
+ payload = @token_source.artifact_token(@computer_id, copy_from: copy_from)
416
+ @tokens[copy_from] = Token.from_payload(payload)
417
+ end
418
+ end
419
+
420
+ # A connection to a storage origin. No credential rides on it: each
421
+ # request carries its own.
422
+ def connection(origin)
423
+ @mutex.synchronize do
424
+ @connections[origin] ||= Faraday.new(url: origin) do |conn|
425
+ conn.headers["User-Agent"] = PineSandbox::USER_AGENT
426
+ conn.options.open_timeout = @timeouts.connect
427
+ conn.options.timeout = @timeouts.request
428
+ conn.adapter Adapters::ConnectAwareNetHttp
429
+ end
430
+ end
431
+ end
432
+
433
+ # Sends one storage request with the token as its bearer. `op` names it
434
+ # in errors.
435
+ def storage_request(token, method, route, op:, params: {}, json: nil, headers: {})
436
+ transport(op) do
437
+ connection(token.endpoint).run_request(method, route, nil, nil) do |req|
438
+ req.params.update(params)
439
+ req.headers["Authorization"] = "Bearer #{token.access_token}"
440
+ req.headers["Accept"] = "application/json"
441
+ headers.each { |name, value| req.headers[name] = value }
442
+ if json
443
+ req.headers["Content-Type"] = "application/json"
444
+ req.body = JSON.generate(json)
445
+ end
446
+ end
447
+ end
448
+ end
449
+
450
+ # Runs the block, a request safe to send again, once more after each
451
+ # transport fault or answer the storage retry rule allows, with
452
+ # RetryPolicy's transient backoff, up to RetryPolicy::TRANSIENT_ATTEMPTS
453
+ # sends, and returns the last answer. Yields whether an earlier send may
454
+ # have reached storage, so this one may find its work already done; one
455
+ # whose connection never opened did not.
456
+ def resending
457
+ attempt = 0
458
+ reached = false
459
+ loop do
460
+ attempt += 1
461
+ begin
462
+ response = yield reached
463
+ reached = true
464
+ rescue PineSandbox::ConnectionError, PineSandbox::TimeoutError => e
465
+ reached ||= !(e.is_a?(PineSandbox::ConnectionError) && e.not_sent?)
466
+ raise if attempt >= RetryPolicy::TRANSIENT_ATTEMPTS
467
+ else
468
+ return response unless retry_status?(response.status) && attempt < RetryPolicy::TRANSIENT_ATTEMPTS
469
+ end
470
+ @clock.sleep(RetryPolicy.transient_backoff(attempt, @clock))
471
+ end
472
+ end
473
+
474
+ # Opens a resumable upload of `size` bytes to the object `name` and
475
+ # returns its session URI.
476
+ def start_upload(token, name, size, content_type, note)
477
+ body = { name: name, contentType: content_type }
478
+ body[:metadata] = { "pine-note" => note } unless note.nil?
479
+ route = "upload/#{objects_route(token)}"
480
+ op = "POST /#{route}"
481
+ # Starting a session writes nothing, and a session a lost answer left
482
+ # unused expires on its own, so a start is sent again.
483
+ response = resending do
484
+ storage_request(
485
+ token, :post, route, op: op,
486
+ params: { "uploadType" => "resumable", "name" => name }, json: body,
487
+ headers: { "X-Upload-Content-Type" => content_type, "X-Upload-Content-Length" => size.to_s }
488
+ )
489
+ end
490
+ raise_storage_error!(response, op: op) unless response.success?
491
+
492
+ session = response.headers["location"].to_s
493
+ raise PineSandbox::Error, PineSandbox.with_context("storage opened no upload session", op: op) if session.empty?
494
+
495
+ session
496
+ end
497
+
498
+ # Sends the upload's bytes to its session and returns the saved object.
499
+ # A PUT that ends without the whole file (a dropped connection, an answer
500
+ # worth retrying, or a 308 that kept only part) is followed, after a
501
+ # wait, by asking storage how much it kept; the rest goes in the next PUT.
502
+ # The budget counts tries in a row that moved nothing.
503
+ def send_upload(session, upload, content_type)
504
+ op = "PUT #{URI(session).path}"
505
+ offset = 0
506
+ failures = 0
507
+ loop do
508
+ outcome = upload_call(op) { put_bytes(session, upload, offset, content_type) }
509
+ until finished?(outcome)
510
+ raise_upload_failure!(outcome, op) unless interrupted?(outcome)
511
+
512
+ failures += 1
513
+ raise_upload_failure!(outcome, op) if failures > RetryPolicy::STREAM_RECONNECT_BUDGET
514
+ @clock.sleep(RetryPolicy.stream_backoff(failures, @clock))
515
+ outcome = upload_call(op) { query_upload(session, upload.size, content_type) }
516
+ break if outcome.is_a?(Faraday::Response) && outcome.status == 308
517
+ end
518
+ return parse_answer(outcome, op: op) if finished?(outcome)
519
+
520
+ kept = kept_bytes(outcome)
521
+ failures = 0 if kept > offset
522
+ offset = kept
523
+ end
524
+ end
525
+
526
+ # The session URI is the upload's credential, so these PUTs carry no
527
+ # Authorization. Once storage keeps every byte, the PUT asks for the
528
+ # finished upload instead.
529
+ def put_bytes(session, upload, offset, content_type)
530
+ return query_upload(session, upload.size, content_type) if upload.size.positive? && offset >= upload.size
531
+
532
+ upload.from(offset) do |body|
533
+ connection(origin(session)).put(session) do |req|
534
+ req.headers["Content-Type"] = content_type
535
+ req.headers["Content-Length"] = (upload.size - offset).to_s
536
+ req.headers["Content-Range"] = "bytes #{offset}-#{upload.size - 1}/#{upload.size}" if upload.size.positive?
537
+ req.body = body
538
+ end
539
+ end
540
+ end
541
+
542
+ def query_upload(session, size, content_type)
543
+ connection(origin(session)).put(session) do |req|
544
+ req.headers["Content-Type"] = content_type
545
+ req.headers["Content-Length"] = "0"
546
+ req.headers["Content-Range"] = "bytes */#{size}"
547
+ req.body = ""
548
+ end
549
+ end
550
+
551
+ # An upload request's response, or the transport fault that ended it.
552
+ def upload_call(op)
553
+ transport(op) { yield }
554
+ rescue PineSandbox::ConnectionError, PineSandbox::TimeoutError => e
555
+ e
556
+ end
557
+
558
+ def finished?(outcome) = outcome.is_a?(Faraday::Response) && [200, 201].include?(outcome.status)
559
+
560
+ def interrupted?(outcome)
561
+ !outcome.is_a?(Faraday::Response) || outcome.status == 308 || retry_status?(outcome.status)
562
+ end
563
+
564
+ # Raises why an upload stopped: its transport fault, storage's refusal,
565
+ # or, after a 308, that storage stopped taking bytes.
566
+ def raise_upload_failure!(outcome, op)
567
+ raise outcome unless outcome.is_a?(Faraday::Response)
568
+ if outcome.status == 308
569
+ raise PineSandbox::Error, PineSandbox.with_context("storage stopped the upload without finishing it", op: op)
570
+ end
571
+
572
+ raise_storage_error!(outcome, op: op)
573
+ end
574
+
575
+ # The bytes storage holds, from a 308's `Range: bytes=0-N` (none without it).
576
+ def kept_bytes(response)
577
+ last = response.headers["range"].to_s[/\Abytes=0-(\d+)\z/, 1]
578
+ last ? Integer(last, 10) + 1 : 0
579
+ end
580
+
581
+ # Passes the file at `path` to the block in chunks, each byte once, and
582
+ # returns how many it passed. After a dropped connection or an answer
583
+ # worth retrying it waits and asks again from the next byte with a Range request pinned
584
+ # to the version the first answer named, so a file replaced meanwhile
585
+ # fails (storage's 412) instead of joining two versions. The budget
586
+ # counts tries in a row that received nothing. The block's own error
587
+ # ends the read as it is.
588
+ def receive(path, &sink)
589
+ received = 0
590
+ failures = 0
591
+ generation = nil
592
+ loop do
593
+ before = received
594
+ begin
595
+ read_object(path, from: received, generation: generation) do |chunk, headers|
596
+ generation ||= headers["x-goog-generation"]
597
+ sink.call(chunk)
598
+ received += chunk.bytesize
599
+ end
600
+ return received
601
+ rescue BlockError => e
602
+ raise e.error
603
+ rescue PineSandbox::Error => e
604
+ raise unless resumable?(e)
605
+
606
+ failures = received > before ? 1 : failures + 1
607
+ raise if failures > RetryPolicy::STREAM_RECONNECT_BUDGET
608
+
609
+ @clock.sleep(RetryPolicy.stream_backoff(failures, @clock))
610
+ end
611
+ end
612
+ end
613
+
614
+ # Whether a failed read is worth resuming: a dropped connection, a
615
+ # timeout, or an answer worth retrying.
616
+ def resumable?(error)
617
+ case error
618
+ when PineSandbox::ConnectionError, PineSandbox::TimeoutError then true
619
+ when ApiError then retry_status?(error.status.to_i)
620
+ else false
621
+ end
622
+ end
623
+
624
+ # Whether a storage answer of `status` is worth sending again, by the rule
625
+ # every SDK shares (contract/storage-retry.json): a request timeout, a 429
626
+ # and any 5xx but 501. A 412 means the file changed under a read pinned to
627
+ # its version, so it never is.
628
+ def retry_status?(status) = status == 408 || status == 429 || (status >= 500 && status != 501)
629
+
630
+ # GETs the file's bytes from byte `from` on, passing each new chunk of a
631
+ # successful answer, with its headers, to the block. A read from a later
632
+ # byte asks for `generation` only. Any other answer raises before a
633
+ # chunk: ArtifactNotFoundError for a missing file.
634
+ def read_object(path, from: 0, generation: nil, &sink)
635
+ with_token do |token|
636
+ route, label = object_route(token, "#{token.prefix}#{path}")
637
+ stream_media(token, route, "GET /#{label}", path, from, generation, sink)
638
+ end
639
+ end
640
+
641
+ def stream_media(token, route, op, path, from, generation, sink)
642
+ delivered = 0
643
+ # The bytes at the answer's start that were passed on before, known
644
+ # once the first chunk shows the answer.
645
+ repeated = nil
646
+ deliver = lambda do |chunk, answer|
647
+ repeated ||= repeated_bytes(answer, from, op)
648
+ delivered += chunk.bytesize
649
+ fresh = chunk.byteslice([repeated, chunk.bytesize].min..)
650
+ repeated -= chunk.bytesize - fresh.bytesize
651
+ pass_on(sink, fresh, answer) unless fresh.empty?
652
+ end
653
+ response = StreamedRead.read(deliver) do |on_data|
654
+ transport(op) do
655
+ connection(token.endpoint).get(route) do |req|
656
+ req.params["alt"] = "media"
657
+ req.headers["Authorization"] = "Bearer #{token.access_token}"
658
+ if from.positive?
659
+ req.headers["Range"] = "bytes=#{from}-"
660
+ req.params["ifGenerationMatch"] = generation if generation
661
+ end
662
+ req.options.on_data = on_data
663
+ end
664
+ end
665
+ end
666
+ raise_storage_error!(response, op: op, path: path) unless response.success?
667
+ # Net::HTTP ends a body that stops short of its length like a complete
668
+ # one, so a connection dropped mid-file is caught here.
669
+ declared = declared_bytes(response)
670
+ if declared && delivered < declared
671
+ raise PineSandbox::ConnectionError,
672
+ PineSandbox.with_context("storage connection ended after #{delivered} of #{declared} bytes", op: op)
673
+ end
674
+ response
675
+ end
676
+
677
+ # How many bytes at the start of a media answer to a read from byte
678
+ # `from` were passed on before: `from` when storage sends the whole file,
679
+ # none when it sends the range asked for. A range from anywhere else is
680
+ # PineSandbox::Error. `answer` is the Faraday env or response.
681
+ def repeated_bytes(answer, from, op)
682
+ return 0 unless from.positive?
683
+ return from unless answer.status == 206
684
+
685
+ range = answer_headers(answer)["content-range"].to_s
686
+ start = range[/\Abytes (\d+)-/, 1]
687
+ return 0 if start && Integer(start, 10) == from
688
+
689
+ raise PineSandbox::Error,
690
+ PineSandbox.with_context("storage resumed the artifact at the wrong place (Content-Range #{range.inspect})", op: op)
691
+ end
692
+
693
+ # The bytes a media answer says it carries, when it says so plainly (not
694
+ # for a compressed one, whose length is of the compressed bytes).
695
+ def declared_bytes(response)
696
+ encoding = response.headers["content-encoding"].to_s
697
+ return unless encoding.empty? || encoding.casecmp?("identity")
698
+
699
+ range = response.headers["content-range"].to_s.match(%r{\Abytes (\d+)-(\d+)/})
700
+ return Integer(range[2], 10) - Integer(range[1], 10) + 1 if response.status == 206 && range
701
+
702
+ length = response.headers["content-length"].to_s
703
+ Integer(length, 10) if length.match?(/\A\d+\z/)
704
+ end
705
+
706
+ # Passes a chunk, with its answer's headers, to the block.
707
+ def pass_on(sink, chunk, answer) = StreamedRead.pass(sink, chunk, answer_headers(answer))
708
+
709
+ # The headers of `answer`, a Faraday env or response.
710
+ def answer_headers(answer) = answer.respond_to?(:response_headers) ? answer.response_headers : answer.headers
711
+
712
+ # Maps a transport fault to the SDK's typed errors. `op` carries no query,
713
+ # so an upload session's id never reaches a message.
714
+ def transport(op)
715
+ yield
716
+ rescue Faraday::TimeoutError => e
717
+ raise PineSandbox::TimeoutError, PineSandbox.with_context("storage request timed out: #{e.message}", op: op)
718
+ rescue Faraday::ConnectionFailed, Faraday::SSLError => e
719
+ error = PineSandbox::ConnectionError.new(PineSandbox.with_context("storage connection failed: #{e.message}", op: op))
720
+ error.not_sent = Adapters::ConnectAwareNetHttp.not_sent?(e)
721
+ raise error
722
+ end
723
+
724
+ # Raises the error for a storage answer that isn't a success, of the
725
+ # operation `op`. For a call on one file (`path`), a 404 is
726
+ # ArtifactNotFoundError; anything else is the status tier's ApiError with
727
+ # storage's own message. Its #retryable? is the storage rule's.
728
+ def raise_storage_error!(response, op:, path: nil)
729
+ body = parse_error_answer(response.body)
730
+ detail = body["error"].is_a?(Hash) ? body["error"]["message"].to_s : ""
731
+ fields = { status: response.status, response_body: response.body.to_s,
732
+ problem_extensions: { "op" => op, "retryable" => retry_status?(response.status) } }
733
+ error =
734
+ if response.status == 404 && path
735
+ ArtifactNotFoundError.new(path: path, error_message: "no artifact at #{path}", **fields)
736
+ else
737
+ message = detail.empty? ? "storage request failed (HTTP #{response.status})" : detail
738
+ status_tier_class_for(response.status).new(error_message: message, **fields)
739
+ end
740
+ seconds = Integer(response.headers["retry-after"].to_s.strip, 10, exception: false)
741
+ error.retry_after = seconds if seconds&.positive?
742
+ raise error
743
+ end
744
+
745
+ # A success answer's JSON object. Any other body is an answer the storage
746
+ # protocol doesn't allow.
747
+ def parse_answer(response, op:)
748
+ parsed = JSON.parse(response.body.to_s)
749
+ return parsed if parsed.is_a?(Hash)
750
+
751
+ raise PineSandbox::Error, PineSandbox.with_context("storage answered with JSON that isn't an object", op: op)
752
+ rescue JSON::ParserError
753
+ raise PineSandbox::Error, PineSandbox.with_context("storage answered with a body that isn't JSON", op: op)
754
+ end
755
+
756
+ # An error answer's JSON object, or {} when its body is none: the error
757
+ # keeps the raw body either way.
758
+ def parse_error_answer(body)
759
+ parsed = JSON.parse(body.to_s)
760
+ parsed.is_a?(Hash) ? parsed : {}
761
+ rescue JSON::ParserError
762
+ {}
763
+ end
764
+
765
+ # The JSON API route of the objects in the token's bucket.
766
+ def objects_route(token) = "storage/v1/b/#{escape(token.bucket)}/o"
767
+
768
+ # The JSON API route of the object `name`, and the same route with
769
+ # "{object}" for the name, for errors.
770
+ def object_route(token, name)
771
+ objects = objects_route(token)
772
+ ["#{objects}/#{escape(name)}", "#{objects}/{object}"]
773
+ end
774
+
775
+ # Percent-encodes every byte but the unreserved ones, "/" and " " included.
776
+ def escape(segment)
777
+ segment.to_s.b.gsub(/[^A-Za-z0-9\-._~]/n) { |byte| format("%%%02X", byte.ord) }
778
+ end
779
+
780
+ def origin(url)
781
+ uri = URI(url)
782
+ "#{uri.scheme}://#{uri.host}#{":#{uri.port}" unless uri.port == uri.default_port}"
783
+ end
784
+ end
785
+ end