aws-sdk-s3 1.229.0 → 1.243.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.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +111 -0
  3. data/VERSION +1 -1
  4. data/lib/aws-sdk-s3/bucket.rb +24 -0
  5. data/lib/aws-sdk-s3/bucket_notification.rb +3 -3
  6. data/lib/aws-sdk-s3/client.rb +144 -29
  7. data/lib/aws-sdk-s3/client_api.rb +26 -0
  8. data/lib/aws-sdk-s3/customizations/object.rb +40 -28
  9. data/lib/aws-sdk-s3/default_executor.rb +65 -19
  10. data/lib/aws-sdk-s3/directory_downloader.rb +9 -3
  11. data/lib/aws-sdk-s3/directory_uploader.rb +4 -0
  12. data/lib/aws-sdk-s3/express_credentials.rb +4 -1
  13. data/lib/aws-sdk-s3/express_credentials_provider.rb +23 -12
  14. data/lib/aws-sdk-s3/file_downloader.rb +21 -14
  15. data/lib/aws-sdk-s3/multipart_file_uploader.rb +22 -15
  16. data/lib/aws-sdk-s3/multipart_stream_uploader.rb +32 -17
  17. data/lib/aws-sdk-s3/multipart_upload_error.rb +1 -1
  18. data/lib/aws-sdk-s3/object.rb +105 -0
  19. data/lib/aws-sdk-s3/object_multipart_copier.rb +1 -0
  20. data/lib/aws-sdk-s3/object_summary.rb +72 -0
  21. data/lib/aws-sdk-s3/plugins/express_session_auth.rb +10 -2
  22. data/lib/aws-sdk-s3/presigned_post.rb +50 -1
  23. data/lib/aws-sdk-s3/presigner.rb +1 -1
  24. data/lib/aws-sdk-s3/transfer_manager.rb +57 -37
  25. data/lib/aws-sdk-s3/types.rb +211 -15
  26. data/lib/aws-sdk-s3.rb +1 -1
  27. data/sig/bucket.rbs +3 -0
  28. data/sig/bucket_notification.rbs +3 -3
  29. data/sig/client.rbs +37 -12
  30. data/sig/customizations/errors.rbs +17 -0
  31. data/sig/errors.rbs +20 -20
  32. data/sig/multipart_upload_error.rbs +9 -0
  33. data/sig/object.rbs +18 -0
  34. data/sig/object_summary.rbs +9 -0
  35. data/sig/resource.rbs +1 -0
  36. data/sig/transfer_manager.rbs +31 -0
  37. data/sig/types.rbs +34 -10
  38. metadata +6 -3
@@ -380,7 +380,9 @@ module Aws
380
380
  # and {Client#upload_part} can be provided.
381
381
  #
382
382
  # @option options [Integer] :thread_count (10) The number of parallel multipart uploads.
383
- # An additional thread is used internally for task coordination.
383
+ # An additional thread is used internally for task coordination. This also bounds
384
+ # how many parts are buffered ahead of the upload, limiting memory usage to roughly
385
+ # `2 * :thread_count * :part_size`.
384
386
  #
385
387
  # @option options [Boolean] :tempfile (false) Normally read data is stored
386
388
  # in memory when building the parts in order to complete the underlying
@@ -405,18 +407,22 @@ module Aws
405
407
  # @see Client#upload_part
406
408
  def upload_stream(options = {}, &block)
407
409
  upload_opts = options.merge(bucket: bucket_name, key: key)
408
- executor = DefaultExecutor.new(max_threads: upload_opts.delete(:thread_count))
409
- uploader = MultipartStreamUploader.new(
410
- client: client,
411
- executor: executor,
412
- tempfile: upload_opts.delete(:tempfile),
413
- part_size: upload_opts.delete(:part_size)
414
- )
415
- Aws::Plugins::UserAgent.metric('RESOURCE_MODEL') do
416
- uploader.upload(upload_opts, &block)
410
+ thread_count = upload_opts.delete(:thread_count) || DefaultExecutor::DEFAULT_MAX_THREADS
411
+ executor = DefaultExecutor.new(max_threads: thread_count, max_queue: thread_count)
412
+ begin
413
+ uploader = MultipartStreamUploader.new(
414
+ client: client,
415
+ executor: executor,
416
+ tempfile: upload_opts.delete(:tempfile),
417
+ part_size: upload_opts.delete(:part_size)
418
+ )
419
+ Aws::Plugins::UserAgent.metric('RESOURCE_MODEL') do
420
+ uploader.upload(upload_opts, &block)
421
+ end
422
+ true
423
+ ensure
424
+ executor.shutdown
417
425
  end
418
- executor.shutdown
419
- true
420
426
  end
421
427
  deprecated(:upload_stream, use: 'Aws::S3::TransferManager#upload_stream', version: 'next major version')
422
428
 
@@ -480,17 +486,20 @@ module Aws
480
486
  def upload_file(source, options = {})
481
487
  upload_opts = options.merge(bucket: bucket_name, key: key)
482
488
  executor = DefaultExecutor.new(max_threads: upload_opts.delete(:thread_count))
483
- uploader = FileUploader.new(
484
- client: client,
485
- executor: executor,
486
- multipart_threshold: upload_opts.delete(:multipart_threshold)
487
- )
488
- response = Aws::Plugins::UserAgent.metric('RESOURCE_MODEL') do
489
- uploader.upload(source, upload_opts)
489
+ begin
490
+ uploader = FileUploader.new(
491
+ client: client,
492
+ executor: executor,
493
+ multipart_threshold: upload_opts.delete(:multipart_threshold)
494
+ )
495
+ response = Aws::Plugins::UserAgent.metric('RESOURCE_MODEL') do
496
+ uploader.upload(source, upload_opts)
497
+ end
498
+ yield response if block_given?
499
+ true
500
+ ensure
501
+ executor.shutdown
490
502
  end
491
- yield response if block_given?
492
- executor.shutdown
493
- true
494
503
  end
495
504
  deprecated(:upload_file, use: 'Aws::S3::TransferManager#upload_file', version: 'next major version')
496
505
 
@@ -561,13 +570,16 @@ module Aws
561
570
  # @see Client#head_object
562
571
  def download_file(destination, options = {})
563
572
  download_opts = options.merge(bucket: bucket_name, key: key)
564
- executor = DefaultExecutor.new(max_threads: download_opts.delete([:thread_count]))
565
- downloader = FileDownloader.new(client: client, executor: executor)
566
- Aws::Plugins::UserAgent.metric('RESOURCE_MODEL') do
567
- downloader.download(destination, download_opts)
573
+ executor = DefaultExecutor.new(max_threads: download_opts.delete(:thread_count))
574
+ begin
575
+ downloader = FileDownloader.new(client: client, executor: executor)
576
+ Aws::Plugins::UserAgent.metric('RESOURCE_MODEL') do
577
+ downloader.download(destination, download_opts)
578
+ end
579
+ true
580
+ ensure
581
+ executor.shutdown
568
582
  end
569
- executor.shutdown
570
- true
571
583
  end
572
584
  deprecated(:download_file, use: 'Aws::S3::TransferManager#download_file', version: 'next major version')
573
585
 
@@ -4,6 +4,13 @@ module Aws
4
4
  module S3
5
5
  # @api private
6
6
  class DefaultExecutor
7
+ # Raised when a task is posted to an executor that is shutting down or has been shut down.
8
+ class RejectedExecutionError < RuntimeError
9
+ def initialize(msg = 'Executor has been shutdown and is no longer accepting tasks')
10
+ super
11
+ end
12
+ end
13
+
7
14
  DEFAULT_MAX_THREADS = 10
8
15
  RUNNING = :running
9
16
  SHUTTING_DOWN = :shutting_down
@@ -11,10 +18,12 @@ module Aws
11
18
 
12
19
  def initialize(options = {})
13
20
  @max_threads = options[:max_threads] || DEFAULT_MAX_THREADS
21
+ @max_queue = options[:max_queue] || 0
14
22
  @state = RUNNING
15
- @queue = Queue.new
23
+ @queue = @max_queue.zero? ? Queue.new : SizedQueue.new(@max_queue)
16
24
  @pool = []
17
25
  @mutex = Mutex.new
26
+ @fatal_error = nil
18
27
  end
19
28
 
20
29
  # Submits a task for execution.
@@ -23,12 +32,15 @@ module Aws
23
32
  # @return [Boolean] Returns true if the task was submitted successfully
24
33
  def post(*args, &block)
25
34
  @mutex.synchronize do
26
- raise 'Executor has been shutdown and is no longer accepting tasks' unless @state == RUNNING
35
+ raise RejectedExecutionError unless @state == RUNNING
27
36
 
28
- @queue << [args, block]
29
37
  ensure_worker_available
30
38
  end
39
+ # Outside the mutex so a caller blocked on a full queue can't hold up #shutdown or #kill.
40
+ @queue.push([args, block])
31
41
  true
42
+ rescue ClosedQueueError
43
+ raise RejectedExecutionError
32
44
  end
33
45
 
34
46
  # Immediately terminates all worker threads and clears pending tasks.
@@ -38,6 +50,7 @@ module Aws
38
50
  def kill
39
51
  @mutex.synchronize do
40
52
  @state = SHUTDOWN
53
+ @queue.close
41
54
  @pool.each(&:kill)
42
55
  @pool.clear
43
56
  @queue.clear
@@ -52,35 +65,58 @@ module Aws
52
65
  # If nil, waits indefinitely. If timeout expires, remaining threads are killed.
53
66
  # @return [Boolean] true when shutdown is complete
54
67
  def shutdown(timeout = nil)
68
+ return true unless begin_shutdown
69
+
70
+ deadline = timeout && (Time.now + timeout)
71
+ join_workers(deadline)
72
+ kill_remaining_workers if timeout
73
+
74
+ finalize_shutdown
75
+ raise @fatal_error if @fatal_error
76
+
77
+ true
78
+ end
79
+
80
+ private
81
+
82
+ def begin_shutdown
55
83
  @mutex.synchronize do
56
- return true if @state == SHUTDOWN
84
+ return false if @state == SHUTDOWN
57
85
 
58
86
  @state = SHUTTING_DOWN
59
- @pool.size.times { @queue << :shutdown }
87
+ # Close rather than push sentinels, which could block on a full queue.
88
+ @queue.close
60
89
  end
90
+ true
91
+ end
61
92
 
62
- if timeout
63
- deadline = Time.now + timeout
64
- @pool.each do |thread|
65
- remaining = deadline - Time.now
66
- break if remaining <= 0
93
+ def join_workers(deadline)
94
+ until (threads = @mutex.synchronize { @pool.select(&:alive?) }).empty?
95
+ threads.each do |thread|
96
+ remaining = deadline - Time.now if deadline
97
+ break if remaining && remaining <= 0
67
98
 
68
- thread.join([remaining, 0].max)
99
+ begin
100
+ thread.join(remaining && [remaining, 0].max)
101
+ rescue Exception # rubocop:disable Lint/RescueException
102
+ nil # recorded by #replace_worker and raised by #shutdown
103
+ end
69
104
  end
70
- @pool.select(&:alive?).each(&:kill)
71
- else
72
- @pool.each(&:join)
105
+ break if deadline && Time.now >= deadline
73
106
  end
107
+ end
108
+
109
+ def kill_remaining_workers
110
+ @mutex.synchronize { @pool.select(&:alive?).each(&:kill) }
111
+ end
74
112
 
113
+ def finalize_shutdown
75
114
  @mutex.synchronize do
76
115
  @pool.clear
77
116
  @state = SHUTDOWN
78
117
  end
79
- true
80
118
  end
81
119
 
82
- private
83
-
84
120
  def ensure_worker_available
85
121
  return unless @state == RUNNING
86
122
 
@@ -91,11 +127,21 @@ module Aws
91
127
  def spawn_worker
92
128
  Thread.new do
93
129
  while (job = @queue.shift)
94
- break if job == :shutdown
95
-
96
130
  args, block = job
97
131
  block.call(*args)
98
132
  end
133
+ rescue Exception => e # rubocop:disable Lint/RescueException
134
+ # Replace this worker so queued tasks still run.
135
+ replace_worker(e)
136
+ raise
137
+ end
138
+ end
139
+
140
+ def replace_worker(error)
141
+ @mutex.synchronize do
142
+ @fatal_error ||= error
143
+ @pool.delete(Thread.current)
144
+ @pool << spawn_worker unless @state == SHUTDOWN
99
145
  end
100
146
  end
101
147
  end
@@ -148,8 +148,9 @@ module Aws
148
148
  stream_objects
149
149
  @object_queue << DONE_MARKER
150
150
  rescue ClosedQueueError
151
- # abort requested
152
- rescue StandardError => e
151
+ nil # abort requested
152
+ # Any error, or the consumer waits on the queue forever
153
+ rescue Exception => e # rubocop:disable Lint/RescueException
153
154
  close
154
155
  raise e
155
156
  end
@@ -208,7 +209,12 @@ module Aws
208
209
  end
209
210
 
210
211
  def validate_key(key)
211
- segments = key.split('/')
212
+ validation_key = key
213
+ if File::ALT_SEPARATOR
214
+ validation_key = key.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
215
+ end
216
+
217
+ segments = validation_key.split(File::SEPARATOR)
212
218
  return unless segments.any? { |s| %w[. ..].include?(s) }
213
219
 
214
220
  DirectoryDownloadError.new("invalid key '#{key}': contains '.' or '..' path segments")
@@ -156,6 +156,10 @@ module Aws
156
156
  # encountered a traversal error, we must abort immediately
157
157
  close
158
158
  raise DirectoryUploadError, "Directory traversal failed for '#{@source_dir}': #{e.message}"
159
+ # Any other error, or the consumer waits on the queue forever
160
+ rescue Exception => e # rubocop:disable Lint/RescueException
161
+ close
162
+ raise e
159
163
  end
160
164
 
161
165
  while (file = @file_queue.shift) && file != DONE_MARKER
@@ -14,6 +14,7 @@ module Aws
14
14
 
15
15
  def initialize(options = {})
16
16
  @client = options[:client]
17
+ @base_credentials = options[:base_credentials]
17
18
  @create_session_params = {}
18
19
  options.each_pair do |key, value|
19
20
  if self.class.create_session_options.include?(key)
@@ -30,7 +31,9 @@ module Aws
30
31
  private
31
32
 
32
33
  def refresh
33
- c = @client.create_session(@create_session_params).credentials
34
+ request = @client.build_request(:create_session, @create_session_params)
35
+ request.context[:sigv4_credentials] = @base_credentials if @base_credentials
36
+ c = request.send_request.credentials
34
37
  @credentials = Credentials.new(
35
38
  c.access_key_id,
36
39
  c.secret_access_key,
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'securerandom'
4
+
3
5
  module Aws
4
6
  module S3
5
7
  # @api private
@@ -10,9 +12,12 @@ module Aws
10
12
  # Returns Credentials class for S3 Express. Accepts CreateSession
11
13
  # params as options. See {Client#create_session} for details.
12
14
  class ExpressCredentialsProvider
15
+ CACHE_KEY_SECRET = SecureRandom.random_bytes(64)
16
+ private_constant :CACHE_KEY_SECRET
17
+
13
18
  # @param [Hash] options
14
19
  # @option options [Client] :client The S3 client used to create the
15
- # session.
20
+ # session when one is not given to {#express_credentials_for}.
16
21
  # @option options [String] :session_mode (see: {Client#create_session})
17
22
  # @option options [Boolean] :caching (true) When true, credentials will
18
23
  # be cached.
@@ -27,11 +32,12 @@ module Aws
27
32
  @cache = Aws::S3.express_credentials_cache
28
33
  end
29
34
 
30
- def express_credentials_for(bucket)
35
+ def express_credentials_for(bucket, client = @client)
36
+ credentials = client.config.credentials&.credentials
31
37
  if @caching
32
- cached_credentials_for(bucket)
38
+ cached_credentials_for(bucket, client, credentials)
33
39
  else
34
- new_credentials_for(bucket)
40
+ new_credentials_for(bucket, client, credentials)
35
41
  end
36
42
  end
37
43
 
@@ -39,18 +45,23 @@ module Aws
39
45
 
40
46
  private
41
47
 
42
- def cached_credentials_for(bucket)
43
- if @cache.key?(bucket)
44
- @cache[bucket]
45
- else
46
- @cache[bucket] = new_credentials_for(bucket)
47
- end
48
+ def cached_credentials_for(bucket, client, credentials)
49
+ @cache[cache_key(bucket, credentials)] ||= new_credentials_for(bucket, client, credentials)
50
+ end
51
+
52
+ def cache_key(bucket, credentials)
53
+ identity = "#{credentials&.access_key_id}#{credentials&.secret_access_key}"
54
+ "#{OpenSSL::HMAC.hexdigest('SHA256', CACHE_KEY_SECRET, identity)}#{bucket}"
48
55
  end
49
56
 
50
- def new_credentials_for(bucket)
57
+ def new_credentials_for(bucket, client, credentials)
58
+ # Sign with this snapshot, but report the provider's UserAgent metrics.
59
+ credentials = credentials&.dup
60
+ credentials&.metrics = client.config.credentials.metrics
51
61
  ExpressCredentials.new(
52
62
  bucket: bucket,
53
- client: @client,
63
+ client: client,
64
+ base_credentials: credentials,
54
65
  **@options
55
66
  )
56
67
  end
@@ -60,7 +60,7 @@ module Aws
60
60
  end
61
61
 
62
62
  def download_with_executor(part_list, total_size, opts)
63
- download_attempts = 0
63
+ queued_parts = 0
64
64
  completion_queue = Queue.new
65
65
  abort_download = false
66
66
  error = nil
@@ -69,24 +69,31 @@ module Aws
69
69
  while (part = part_list.shift)
70
70
  break if abort_download
71
71
 
72
- download_attempts += 1
73
- @executor.post(part) do |p|
74
- update_progress(progress, p)
75
- resp = @client.get_object(p.params)
76
- range = extract_range(resp.content_range)
77
- validate_range(range, p.params[:range]) if p.params[:range]
78
- write(resp.body, range, opts)
79
-
80
- execute_checksum_callback(resp, opts)
72
+ begin
73
+ @executor.post(part) do |p|
74
+ update_progress(progress, p)
75
+ resp = @client.get_object(p.params)
76
+ range = extract_range(resp.content_range)
77
+ validate_range(range, p.params[:range]) if p.params[:range]
78
+ write(resp.body, range, opts)
79
+
80
+ execute_checksum_callback(resp, opts)
81
+ # Any error, or a corrupt file replaces the destination
82
+ rescue Exception => e # rubocop:disable Lint/RescueException
83
+ abort_download = true
84
+ error = e
85
+ ensure
86
+ completion_queue << :done
87
+ end
88
+ queued_parts += 1
81
89
  rescue StandardError => e
82
- abort_download = true
90
+ # Rejected by the executor, wait for queued parts so none write after cleanup
83
91
  error = e
84
- ensure
85
- completion_queue << :done
92
+ break
86
93
  end
87
94
  end
88
95
 
89
- download_attempts.times { completion_queue.pop }
96
+ queued_parts.times { completion_queue.pop }
90
97
  raise error unless error.nil?
91
98
  end
92
99
 
@@ -140,7 +140,7 @@ module Aws
140
140
  end
141
141
 
142
142
  def upload_with_executor(pending, completed, options)
143
- upload_attempts = 0
143
+ queued_parts = 0
144
144
  completion_queue = Queue.new
145
145
  abort_upload = false
146
146
  errors = []
@@ -149,25 +149,32 @@ module Aws
149
149
  while (part = pending.shift)
150
150
  break if abort_upload
151
151
 
152
- upload_attempts += 1
153
- @executor.post(part) do |p|
154
- Thread.current[:net_http_override_body_stream_chunk] = @http_chunk_size if @http_chunk_size
155
- update_progress(progress, p)
156
- resp = @client.upload_part(p)
157
- completed_part = { etag: resp.etag, part_number: p[:part_number] }
158
- apply_part_checksum(resp, completed_part)
159
- completed.push(completed_part)
152
+ begin
153
+ @executor.post(part) do |p|
154
+ Thread.current[:net_http_override_body_stream_chunk] = @http_chunk_size if @http_chunk_size
155
+ update_progress(progress, p)
156
+ resp = @client.upload_part(p)
157
+ completed_part = { etag: resp.etag, part_number: p[:part_number] }
158
+ apply_part_checksum(resp, completed_part)
159
+ completed.push(completed_part)
160
+ # Any error, or the upload completes without this part.
161
+ rescue Exception => e # rubocop:disable Lint/RescueException
162
+ abort_upload = true
163
+ errors << e
164
+ ensure
165
+ p[:body].close
166
+ Thread.current[:net_http_override_body_stream_chunk] = nil if @http_chunk_size
167
+ completion_queue << :done
168
+ end
169
+ queued_parts += 1
160
170
  rescue StandardError => e
161
- abort_upload = true
171
+ # Rejected by the executor; abort rather than orphan the upload.
162
172
  errors << e
163
- ensure
164
- p[:body].close
165
- Thread.current[:net_http_override_body_stream_chunk] = nil if @http_chunk_size
166
- completion_queue << :done
173
+ break
167
174
  end
168
175
  end
169
176
 
170
- upload_attempts.times { completion_queue.pop }
177
+ queued_parts.times { completion_queue.pop }
171
178
  errors
172
179
  end
173
180
 
@@ -113,18 +113,22 @@ module Aws
113
113
  def read_to_part_body(read_pipe)
114
114
  return if read_pipe.closed?
115
115
 
116
- temp_io = @tempfile ? Tempfile.new('aws-sdk-s3-upload_stream') : StringIO.new(String.new)
117
- temp_io.binmode
118
- bytes_copied = IO.copy_stream(read_pipe, temp_io, @part_size)
119
- temp_io.rewind
120
- if bytes_copied.zero?
121
- if temp_io.is_a?(Tempfile)
116
+ if @tempfile
117
+ temp_io = Tempfile.new('aws-sdk-s3-upload_stream')
118
+ temp_io.binmode
119
+ bytes_copied = IO.copy_stream(read_pipe, temp_io, @part_size)
120
+ temp_io.rewind
121
+ if bytes_copied.zero?
122
122
  temp_io.close
123
123
  temp_io.unlink
124
+ nil
125
+ else
126
+ temp_io
124
127
  end
125
- nil
126
128
  else
127
- temp_io
129
+ # A single sized read; copy_stream into a StringIO grows by doubling and fragments the heap.
130
+ data = read_pipe.read(@part_size)
131
+ data.nil? ? nil : StringIO.new(data)
128
132
  end
129
133
  end
130
134
 
@@ -139,20 +143,31 @@ module Aws
139
143
  end
140
144
  break unless part_body || current_part_num == 1
141
145
 
142
- queued_parts += 1
143
- @executor.post(part_body, current_part_num, options) do |body, num, opts|
144
- part = opts.merge(body: body, part_number: num)
145
- resp = @client.upload_part(part)
146
- completed_part = create_completed_part(resp, part)
147
- completed.push(completed_part)
146
+ begin
147
+ @executor.post(part_body, current_part_num, options) do |body, num, opts|
148
+ part = opts.merge(body: body, part_number: num)
149
+ resp = @client.upload_part(part)
150
+ completed_part = create_completed_part(resp, part)
151
+ completed.push(completed_part)
152
+ # Any error, or the upload completes without this part.
153
+ rescue Exception => e # rubocop:disable Lint/RescueException
154
+ mutex.synchronize do
155
+ errors.push(e)
156
+ read_pipe.close_read unless read_pipe.closed?
157
+ end
158
+ ensure
159
+ clear_body(body)
160
+ completion_queue << :done
161
+ end
162
+ queued_parts += 1
148
163
  rescue StandardError => e
164
+ # Rejected by the executor. Closing the pipe stops the producer so the upload can abort.
149
165
  mutex.synchronize do
150
166
  errors.push(e)
151
167
  read_pipe.close_read unless read_pipe.closed?
152
168
  end
153
- ensure
154
- clear_body(body)
155
- completion_queue << :done
169
+ clear_body(part_body)
170
+ break
156
171
  end
157
172
  end
158
173
  queued_parts.times { completion_queue.pop }
@@ -10,7 +10,7 @@ module Aws
10
10
  super(message)
11
11
  end
12
12
 
13
- # @return [Array<StandardError>] The list of errors encountered when uploading or aborting the upload.
13
+ # @return [Array<Exception>] The list of errors encountered when uploading or aborting the upload.
14
14
  attr_reader :errors
15
15
  end
16
16
  end