aws-sdk-s3 1.192.0 → 1.201.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.
@@ -0,0 +1,304 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aws
4
+ module S3
5
+ # A high-level S3 transfer utility that provides enhanced upload and download capabilities with automatic
6
+ # multipart handling, progress tracking, and handling of large files. The following features are supported:
7
+ #
8
+ # * upload a file with multipart upload
9
+ # * upload a stream with multipart upload
10
+ # * download a S3 object with multipart download
11
+ # * track transfer progress by using progress listener
12
+ #
13
+ # ## Executor Management
14
+ # TransferManager uses executors to handle concurrent operations during multipart transfers. You can control
15
+ # concurrency behavior by providing a custom executor or relying on the default executor management.
16
+ #
17
+ # ### Default Behavior
18
+ # When no `:executor` is provided, TransferManager creates a new DefaultExecutor for each individual
19
+ # operation (`download_file`, `upload_file`, etc.) and automatically shuts it down when that operation completes.
20
+ # Each operation gets its own isolated thread pool with the specified `:thread_count` (default 10 threads).
21
+ #
22
+ # ### Custom Executor
23
+ # You can provide your own executor (e.g., `Concurrent::ThreadPoolExecutor`) for fine-grained control over thread
24
+ # pools and resource management. When using a custom executor, you are responsible for shutting it down
25
+ # when finished. The executor may be reused across multiple TransferManager operations.
26
+ #
27
+ # Custom executors must implement the same interface as DefaultExecutor.
28
+ #
29
+ # **Required methods:**
30
+ #
31
+ # * `post(*args, &block)` - Execute a task with given arguments and block
32
+ # * `kill` - Immediately terminate all running tasks
33
+ #
34
+ # **Optional methods:**
35
+ #
36
+ # * `shutdown(timeout = nil)` - Gracefully shutdown the executor with optional timeout
37
+ #
38
+ # @example Using default executor (automatic creation and shutdown)
39
+ # tm = TransferManager.new # No executor provided
40
+ # # DefaultExecutor created, used, and shutdown automatically
41
+ # tm.download_file('/path/to/file', bucket: 'bucket', key: 'key')
42
+ #
43
+ # @example Using custom executor (manual shutdown required)
44
+ # require 'concurrent-ruby'
45
+ #
46
+ # executor = Concurrent::ThreadPoolExecutor.new(max_threads: 5)
47
+ # tm = TransferManager.new(executor: executor)
48
+ # tm.download_file('/path/to/file1', bucket: 'bucket', key: 'key1')
49
+ # executor.shutdown # You must shutdown custom executors
50
+ #
51
+ class TransferManager
52
+
53
+ # @param [Hash] options
54
+ # @option options [S3::Client] :client (S3::Client.new)
55
+ # The S3 client to use for {TransferManager} operations. If not provided, a new default client
56
+ # will be created automatically.
57
+ # @option options [Object] :executor
58
+ # The executor to use for multipart operations. Must implement the same interface as {DefaultExecutor}.
59
+ # If not provided, a new {DefaultExecutor} will be created automatically for each operation and
60
+ # shutdown after completion. When provided a custom executor, it will be reused across operations, and
61
+ # you are responsible for shutting it down when finished.
62
+ def initialize(options = {})
63
+ @client = options[:client] || Client.new
64
+ @executor = options[:executor]
65
+ end
66
+
67
+ # @return [S3::Client]
68
+ attr_reader :client
69
+
70
+ # @return [Object]
71
+ attr_reader :executor
72
+
73
+ # Downloads a file in S3 to a path on disk.
74
+ #
75
+ # # small files (< 5MB) are downloaded in a single API call
76
+ # tm = TransferManager.new
77
+ # tm.download_file('/path/to/file', bucket: 'bucket', key: 'key')
78
+ #
79
+ # Files larger than 5MB are downloaded using multipart method:
80
+ #
81
+ # # large files are split into parts and the parts are downloaded in parallel
82
+ # tm.download_file('/path/to/large_file', bucket: 'bucket', key: 'key')
83
+ #
84
+ # You can provide a callback to monitor progress of the download:
85
+ #
86
+ # # bytes and part_sizes are each an array with 1 entry per part
87
+ # # part_sizes may not be known until the first bytes are retrieved
88
+ # progress = proc do |bytes, part_sizes, file_size|
89
+ # bytes.map.with_index do |b, i|
90
+ # puts "Part #{i + 1}: #{b} / #{part_sizes[i]}".join(' ') + "Total: #{100.0 * bytes.sum / file_size}%"
91
+ # end
92
+ # end
93
+ # tm.download_file('/path/to/file', bucket: 'bucket', key: 'key', progress_callback: progress)
94
+ #
95
+ # @param [String, Pathname, File, Tempfile] destination
96
+ # Where to download the file to. This can either be a String or Pathname to the file, an open File object,
97
+ # or an open Tempfile object. If you pass an open File or Tempfile object, then you are responsible for
98
+ # closing it after the download completes. Download behavior varies by destination type:
99
+ #
100
+ # * **String/Pathname paths**: Downloads to a temporary file first, then atomically moves to the final
101
+ # destination. This prevents corruption of any existing file if the download fails.
102
+ # * **File/Tempfile objects**: Downloads directly to the file object without using temporary files.
103
+ # You are responsible for managing the file object's state and closing it after the download completes.
104
+ # If the download fails, the file object may contain partial data.
105
+ #
106
+ # @param [String] bucket
107
+ # The name of the S3 bucket to upload to.
108
+ #
109
+ # @param [String] key
110
+ # The object key name in S3 bucket.
111
+ #
112
+ # @param [Hash] options
113
+ # Additional options for {Client#get_object} and #{Client#head_object} may be provided.
114
+ #
115
+ # @option options [String] :mode ("auto") `"auto"`, `"single_request"` or `"get_range"`
116
+ #
117
+ # * `"auto"` mode is enabled by default, which performs `multipart_download`
118
+ # * `"single_request`" mode forces only 1 GET request is made in download
119
+ # * `"get_range"` mode requires `:chunk_size` parameter to configured in customizing each range size
120
+ #
121
+ # @option options [Integer] :chunk_size required in `"get_range"` mode.
122
+ #
123
+ # @option options [Integer] :thread_count (10) Customize threads used in the multipart download.
124
+ # Only used when no custom executor is provided (creates {DefaultExecutor} with given thread count).
125
+ #
126
+ # @option options [String] :checksum_mode ("ENABLED")
127
+ # When `"ENABLED"` and the object has a stored checksum, it will be used to validate the download and will
128
+ # raise an `Aws::Errors::ChecksumError` if checksum validation fails. You may provide a `on_checksum_validated`
129
+ # callback if you need to verify that validation occurred and which algorithm was used.
130
+ # To disable checksum validation, set `checksum_mode` to `"DISABLED"`.
131
+ #
132
+ # @option options [Callable] :on_checksum_validated
133
+ # Called each time a request's checksum is validated with the checksum algorithm and the
134
+ # response. For multipart downloads, this will be called for each part that is downloaded and validated.
135
+ #
136
+ # @option options [Proc] :progress_callback
137
+ # A Proc that will be called when each chunk of the download is received. It will be invoked with
138
+ # `bytes_read`, `part_sizes`, `file_size`. When the object is downloaded as parts (rather than by ranges),
139
+ # the `part_sizes` will not be known ahead of time and will be `nil` in the callback until the first bytes
140
+ # in the part are received.
141
+ #
142
+ # @raise [MultipartDownloadError] Raised when an object validation fails outside of service errors.
143
+ #
144
+ # @return [Boolean] Returns `true` when the file is downloaded without any errors.
145
+ #
146
+ # @see Client#get_object
147
+ # @see Client#head_object
148
+ def download_file(destination, bucket:, key:, **options)
149
+ download_opts = options.merge(bucket: bucket, key: key)
150
+ executor = @executor || DefaultExecutor.new(max_threads: download_opts.delete(:thread_count))
151
+ downloader = FileDownloader.new(client: @client, executor: executor)
152
+ downloader.download(destination, download_opts)
153
+ executor.shutdown unless @executor
154
+ true
155
+ end
156
+
157
+ # Uploads a file from disk to S3.
158
+ #
159
+ # # a small file are uploaded with PutObject API
160
+ # tm = TransferManager.new
161
+ # tm.upload_file('/path/to/small_file', bucket: 'bucket', key: 'key')
162
+ #
163
+ # Files larger than or equal to `:multipart_threshold` are uploaded using multipart upload APIs.
164
+ #
165
+ # # large files are automatically split into parts and the parts are uploaded in parallel
166
+ # tm.upload_file('/path/to/large_file', bucket: 'bucket', key: 'key')
167
+ #
168
+ # The response of the S3 upload API is yielded if a block given.
169
+ #
170
+ # # API response will have etag value of the file
171
+ # tm.upload_file('/path/to/file', bucket: 'bucket', key: 'key') do |response|
172
+ # etag = response.etag
173
+ # end
174
+ #
175
+ # You can provide a callback to monitor progress of the upload:
176
+ #
177
+ # # bytes and totals are each an array with 1 entry per part
178
+ # progress = proc do |bytes, totals|
179
+ # bytes.map.with_index do |b, i|
180
+ # puts "Part #{i + 1}: #{b} / #{totals[i]} " + "Total: #{100.0 * bytes.sum / totals.sum}%"
181
+ # end
182
+ # end
183
+ # tm.upload_file('/path/to/file', bucket: 'bucket', key: 'key', progress_callback: progress)
184
+ #
185
+ # @param [String, Pathname, File, Tempfile] source
186
+ # A file on the local file system that will be uploaded. This can either be a `String` or `Pathname` to the
187
+ # file, an open `File` object, or an open `Tempfile` object. If you pass an open `File` or `Tempfile` object,
188
+ # then you are responsible for closing it after the upload completes. When using an open Tempfile, rewind it
189
+ # before uploading or else the object will be empty.
190
+ #
191
+ # @param [String] bucket
192
+ # The name of the S3 bucket to upload to.
193
+ #
194
+ # @param [String] key
195
+ # The object key name for the uploaded file.
196
+ #
197
+ # @param [Hash] options
198
+ # Additional options for {Client#put_object} when file sizes below the multipart threshold.
199
+ # For files larger than the multipart threshold, options for {Client#create_multipart_upload},
200
+ # {Client#complete_multipart_upload}, and {Client#upload_part} can be provided.
201
+ #
202
+ # @option options [Integer] :multipart_threshold (104857600)
203
+ # Files larger han or equal to `:multipart_threshold` are uploaded using the S3 multipart upload APIs.
204
+ # Default threshold is `100MB`.
205
+ #
206
+ # @option options [Integer] :thread_count (10) Customize threads used in the multipart upload.
207
+ # Only used when no custom executor is provided (creates {DefaultExecutor} with the given thread count).
208
+ #
209
+ # @option options [Proc] :progress_callback (nil)
210
+ # A Proc that will be called when each chunk of the upload is sent.
211
+ # It will be invoked with `[bytes_read]` and `[total_sizes]`.
212
+ #
213
+ # @raise [MultipartUploadError] If a file is being uploaded in parts, and the upload can not be completed,
214
+ # then the upload is aborted and this error is raised. The raised error has a `#errors` method that
215
+ # returns the failures that caused the upload to be aborted.
216
+ #
217
+ # @return [Boolean] Returns `true` when the file is uploaded without any errors.
218
+ #
219
+ # @see Client#put_object
220
+ # @see Client#create_multipart_upload
221
+ # @see Client#complete_multipart_upload
222
+ # @see Client#upload_part
223
+ def upload_file(source, bucket:, key:, **options)
224
+ upload_opts = options.merge(bucket: bucket, key: key)
225
+ executor = @executor || DefaultExecutor.new(max_threads: upload_opts.delete(:thread_count))
226
+ uploader = FileUploader.new(
227
+ multipart_threshold: upload_opts.delete(:multipart_threshold),
228
+ client: @client,
229
+ executor: executor
230
+ )
231
+ response = uploader.upload(source, upload_opts)
232
+ yield response if block_given?
233
+ executor.shutdown unless @executor
234
+ true
235
+ end
236
+
237
+ # Uploads a stream in a streaming fashion to S3.
238
+ #
239
+ # Passed chunks automatically split into multipart upload parts and the parts are uploaded in parallel.
240
+ # This allows for streaming uploads that never touch the disk.
241
+ #
242
+ # **Note**: There are known issues in JRuby until jruby-9.1.15.0, so avoid using this with older JRuby versions.
243
+ #
244
+ # @example Streaming chunks of data
245
+ # tm = TransferManager.new
246
+ # tm.upload_stream(bucket: 'bucket', key: 'key') do |write_stream|
247
+ # 10.times { write_stream << 'foo' }
248
+ # end
249
+ # @example Streaming chunks of data
250
+ # tm.upload_stream(bucket: 'bucket', key: 'key') do |write_stream|
251
+ # IO.copy_stream(IO.popen('ls'), write_stream)
252
+ # end
253
+ # @example Streaming chunks of data
254
+ # tm.upload_stream(bucket: 'bucket', key: 'key') do |write_stream|
255
+ # IO.copy_stream(STDIN, write_stream)
256
+ # end
257
+ #
258
+ # @param [String] bucket
259
+ # The name of the S3 bucket to upload to.
260
+ #
261
+ # @param [String] key
262
+ # The object key name for the uploaded file.
263
+ #
264
+ # @param [Hash] options
265
+ # Additional options for {Client#create_multipart_upload}, {Client#complete_multipart_upload}, and
266
+ # {Client#upload_part} can be provided.
267
+ #
268
+ # @option options [Integer] :thread_count (10)
269
+ # The number of parallel multipart uploads. Only used when no custom executor is provided (creates
270
+ # {DefaultExecutor} with the given thread count). An additional thread is used internally for task coordination.
271
+ #
272
+ # @option options [Boolean] :tempfile (false)
273
+ # Normally read data is stored in memory when building the parts in order to complete the underlying
274
+ # multipart upload. By passing `:tempfile => true`, the data read will be temporarily stored on disk reducing
275
+ # the memory footprint vastly.
276
+ #
277
+ # @option options [Integer] :part_size (5242880)
278
+ # Define how big each part size but the last should be. Default `:part_size` is `5 * 1024 * 1024`.
279
+ #
280
+ # @raise [MultipartUploadError] If an object is being uploaded in parts, and the upload can not be completed,
281
+ # then the upload is aborted and this error is raised. The raised error has a `#errors` method that returns
282
+ # the failures that caused the upload to be aborted.
283
+ #
284
+ # @return [Boolean] Returns `true` when the object is uploaded without any errors.
285
+ #
286
+ # @see Client#create_multipart_upload
287
+ # @see Client#complete_multipart_upload
288
+ # @see Client#upload_part
289
+ def upload_stream(bucket:, key:, **options, &block)
290
+ upload_opts = options.merge(bucket: bucket, key: key)
291
+ executor = @executor || DefaultExecutor.new(max_threads: upload_opts.delete(:thread_count))
292
+ uploader = MultipartStreamUploader.new(
293
+ client: @client,
294
+ executor: executor,
295
+ tempfile: upload_opts.delete(:tempfile),
296
+ part_size: upload_opts.delete(:part_size)
297
+ )
298
+ uploader.upload(upload_opts, &block)
299
+ executor.shutdown unless @executor
300
+ true
301
+ end
302
+ end
303
+ end
304
+ end