Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/S3Client.php

raw symbols SCIP
1 <?php
2 namespace Aws\S3;
3
4 use Aws\Api\ApiProvider;
5 use Aws\Api\DocModel;
6 use Aws\Api\Service;
7 use Aws\AwsClient;
8 use Aws\CacheInterface;
9 use Aws\ClientResolver;
10 use Aws\Command;
11 use Aws\CommandInterface;
12 use Aws\Configuration\ConfigurationResolver;
13 use Aws\Exception\AwsException;
14 use Aws\HandlerList;
15 use Aws\Identity\S3\S3ExpressIdentityProvider;
16 use Aws\InputValidationMiddleware;
17 use Aws\Middleware;
18 use Aws\ResultInterface;
19 use Aws\Retry\ConfigurationInterface as RetryConfigurationInterface;
20 use Aws\Retry\QuotaManager;
21 use Aws\Retry\V3\OptIn as NewRetriesOptIn;
22 use Aws\Retry\V3\RetryMiddleware as RetryV3Middleware;
23 use Aws\RetryMiddleware;
24 use Aws\RetryMiddlewareV2;
25 use Aws\S3\Parser\GetBucketLocationResultMutator;
26 use Aws\S3\Parser\S3Parser;
27 use Aws\S3\Parser\ValidateResponseChecksumResultMutator;
28 use Aws\S3\RegionalEndpoint\ConfigurationProvider;
29 use Aws\S3\UseArnRegion\Configuration;
30 use Aws\S3\UseArnRegion\ConfigurationInterface;
31 use Aws\S3\UseArnRegion\ConfigurationProvider as UseArnRegionConfigurationProvider;
32 use GuzzleHttp\Exception\RequestException;
33 use GuzzleHttp\Promise\PromiseInterface;
34 use Psr\Http\Message\RequestInterface;
35
36 /**
37 * Client used to interact with **Amazon Simple Storage Service (Amazon S3)**.
38 *
39 * @method \Aws\Result abortMultipartUpload(array $args = [])
40 * @method \GuzzleHttp\Promise\Promise abortMultipartUploadAsync(array $args = [])
41 * @method \Aws\Result completeMultipartUpload(array $args = [])
42 * @method \GuzzleHttp\Promise\Promise completeMultipartUploadAsync(array $args = [])
43 * @method \Aws\Result copyObject(array $args = [])
44 * @method \GuzzleHttp\Promise\Promise copyObjectAsync(array $args = [])
45 * @method \Aws\Result createBucket(array $args = [])
46 * @method \GuzzleHttp\Promise\Promise createBucketAsync(array $args = [])
47 * @method \Aws\Result createBucketMetadataConfiguration(array $args = [])
48 * @method \GuzzleHttp\Promise\Promise createBucketMetadataConfigurationAsync(array $args = [])
49 * @method \Aws\Result createBucketMetadataTableConfiguration(array $args = [])
50 * @method \GuzzleHttp\Promise\Promise createBucketMetadataTableConfigurationAsync(array $args = [])
51 * @method \Aws\Result createMultipartUpload(array $args = [])
52 * @method \GuzzleHttp\Promise\Promise createMultipartUploadAsync(array $args = [])
53 * @method \Aws\Result createSession(array $args = [])
54 * @method \GuzzleHttp\Promise\Promise createSessionAsync(array $args = [])
55 * @method \Aws\Result deleteBucket(array $args = [])
56 * @method \GuzzleHttp\Promise\Promise deleteBucketAsync(array $args = [])
57 * @method \Aws\Result deleteBucketAnalyticsConfiguration(array $args = [])
58 * @method \GuzzleHttp\Promise\Promise deleteBucketAnalyticsConfigurationAsync(array $args = [])
59 * @method \Aws\Result deleteBucketCors(array $args = [])
60 * @method \GuzzleHttp\Promise\Promise deleteBucketCorsAsync(array $args = [])
61 * @method \Aws\Result deleteBucketEncryption(array $args = [])
62 * @method \GuzzleHttp\Promise\Promise deleteBucketEncryptionAsync(array $args = [])
63 * @method \Aws\Result deleteBucketIntelligentTieringConfiguration(array $args = [])
64 * @method \GuzzleHttp\Promise\Promise deleteBucketIntelligentTieringConfigurationAsync(array $args = [])
65 * @method \Aws\Result deleteBucketInventoryConfiguration(array $args = [])
66 * @method \GuzzleHttp\Promise\Promise deleteBucketInventoryConfigurationAsync(array $args = [])
67 * @method \Aws\Result deleteBucketLifecycle(array $args = [])
68 * @method \GuzzleHttp\Promise\Promise deleteBucketLifecycleAsync(array $args = [])
69 * @method \Aws\Result deleteBucketMetadataConfiguration(array $args = [])
70 * @method \GuzzleHttp\Promise\Promise deleteBucketMetadataConfigurationAsync(array $args = [])
71 * @method \Aws\Result deleteBucketMetadataTableConfiguration(array $args = [])
72 * @method \GuzzleHttp\Promise\Promise deleteBucketMetadataTableConfigurationAsync(array $args = [])
73 * @method \Aws\Result deleteBucketMetricsConfiguration(array $args = [])
74 * @method \GuzzleHttp\Promise\Promise deleteBucketMetricsConfigurationAsync(array $args = [])
75 * @method \Aws\Result deleteBucketOwnershipControls(array $args = [])
76 * @method \GuzzleHttp\Promise\Promise deleteBucketOwnershipControlsAsync(array $args = [])
77 * @method \Aws\Result deleteBucketPolicy(array $args = [])
78 * @method \GuzzleHttp\Promise\Promise deleteBucketPolicyAsync(array $args = [])
79 * @method \Aws\Result deleteBucketReplication(array $args = [])
80 * @method \GuzzleHttp\Promise\Promise deleteBucketReplicationAsync(array $args = [])
81 * @method \Aws\Result deleteBucketTagging(array $args = [])
82 * @method \GuzzleHttp\Promise\Promise deleteBucketTaggingAsync(array $args = [])
83 * @method \Aws\Result deleteBucketWebsite(array $args = [])
84 * @method \GuzzleHttp\Promise\Promise deleteBucketWebsiteAsync(array $args = [])
85 * @method \Aws\Result deleteObject(array $args = [])
86 * @method \GuzzleHttp\Promise\Promise deleteObjectAsync(array $args = [])
87 * @method \Aws\Result deleteObjectTagging(array $args = [])
88 * @method \GuzzleHttp\Promise\Promise deleteObjectTaggingAsync(array $args = [])
89 * @method \Aws\Result deleteObjects(array $args = [])
90 * @method \GuzzleHttp\Promise\Promise deleteObjectsAsync(array $args = [])
91 * @method \Aws\Result deletePublicAccessBlock(array $args = [])
92 * @method \GuzzleHttp\Promise\Promise deletePublicAccessBlockAsync(array $args = [])
93 * @method \Aws\Result getBucketAbac(array $args = [])
94 * @method \GuzzleHttp\Promise\Promise getBucketAbacAsync(array $args = [])
95 * @method \Aws\Result getBucketAccelerateConfiguration(array $args = [])
96 * @method \GuzzleHttp\Promise\Promise getBucketAccelerateConfigurationAsync(array $args = [])
97 * @method \Aws\Result getBucketAcl(array $args = [])
98 * @method \GuzzleHttp\Promise\Promise getBucketAclAsync(array $args = [])
99 * @method \Aws\Result getBucketAnalyticsConfiguration(array $args = [])
100 * @method \GuzzleHttp\Promise\Promise getBucketAnalyticsConfigurationAsync(array $args = [])
101 * @method \Aws\Result getBucketCors(array $args = [])
102 * @method \GuzzleHttp\Promise\Promise getBucketCorsAsync(array $args = [])
103 * @method \Aws\Result getBucketEncryption(array $args = [])
104 * @method \GuzzleHttp\Promise\Promise getBucketEncryptionAsync(array $args = [])
105 * @method \Aws\Result getBucketIntelligentTieringConfiguration(array $args = [])
106 * @method \GuzzleHttp\Promise\Promise getBucketIntelligentTieringConfigurationAsync(array $args = [])
107 * @method \Aws\Result getBucketInventoryConfiguration(array $args = [])
108 * @method \GuzzleHttp\Promise\Promise getBucketInventoryConfigurationAsync(array $args = [])
109 * @method \Aws\Result getBucketLifecycle(array $args = [])
110 * @method \GuzzleHttp\Promise\Promise getBucketLifecycleAsync(array $args = [])
111 * @method \Aws\Result getBucketLifecycleConfiguration(array $args = [])
112 * @method \GuzzleHttp\Promise\Promise getBucketLifecycleConfigurationAsync(array $args = [])
113 * @method \Aws\Result getBucketLocation(array $args = [])
114 * @method \GuzzleHttp\Promise\Promise getBucketLocationAsync(array $args = [])
115 * @method \Aws\Result getBucketLogging(array $args = [])
116 * @method \GuzzleHttp\Promise\Promise getBucketLoggingAsync(array $args = [])
117 * @method \Aws\Result getBucketMetadataConfiguration(array $args = [])
118 * @method \GuzzleHttp\Promise\Promise getBucketMetadataConfigurationAsync(array $args = [])
119 * @method \Aws\Result getBucketMetadataTableConfiguration(array $args = [])
120 * @method \GuzzleHttp\Promise\Promise getBucketMetadataTableConfigurationAsync(array $args = [])
121 * @method \Aws\Result getBucketMetricsConfiguration(array $args = [])
122 * @method \GuzzleHttp\Promise\Promise getBucketMetricsConfigurationAsync(array $args = [])
123 * @method \Aws\Result getBucketNotification(array $args = [])
124 * @method \GuzzleHttp\Promise\Promise getBucketNotificationAsync(array $args = [])
125 * @method \Aws\Result getBucketNotificationConfiguration(array $args = [])
126 * @method \GuzzleHttp\Promise\Promise getBucketNotificationConfigurationAsync(array $args = [])
127 * @method \Aws\Result getBucketOwnershipControls(array $args = [])
128 * @method \GuzzleHttp\Promise\Promise getBucketOwnershipControlsAsync(array $args = [])
129 * @method \Aws\Result getBucketPolicy(array $args = [])
130 * @method \GuzzleHttp\Promise\Promise getBucketPolicyAsync(array $args = [])
131 * @method \Aws\Result getBucketPolicyStatus(array $args = [])
132 * @method \GuzzleHttp\Promise\Promise getBucketPolicyStatusAsync(array $args = [])
133 * @method \Aws\Result getBucketReplication(array $args = [])
134 * @method \GuzzleHttp\Promise\Promise getBucketReplicationAsync(array $args = [])
135 * @method \Aws\Result getBucketRequestPayment(array $args = [])
136 * @method \GuzzleHttp\Promise\Promise getBucketRequestPaymentAsync(array $args = [])
137 * @method \Aws\Result getBucketTagging(array $args = [])
138 * @method \GuzzleHttp\Promise\Promise getBucketTaggingAsync(array $args = [])
139 * @method \Aws\Result getBucketVersioning(array $args = [])
140 * @method \GuzzleHttp\Promise\Promise getBucketVersioningAsync(array $args = [])
141 * @method \Aws\Result getBucketWebsite(array $args = [])
142 * @method \GuzzleHttp\Promise\Promise getBucketWebsiteAsync(array $args = [])
143 * @method \Aws\Result getObject(array $args = [])
144 * @method \GuzzleHttp\Promise\Promise getObjectAsync(array $args = [])
145 * @method \Aws\Result getObjectAcl(array $args = [])
146 * @method \GuzzleHttp\Promise\Promise getObjectAclAsync(array $args = [])
147 * @method \Aws\Result getObjectAttributes(array $args = [])
148 * @method \GuzzleHttp\Promise\Promise getObjectAttributesAsync(array $args = [])
149 * @method \Aws\Result getObjectLegalHold(array $args = [])
150 * @method \GuzzleHttp\Promise\Promise getObjectLegalHoldAsync(array $args = [])
151 * @method \Aws\Result getObjectLockConfiguration(array $args = [])
152 * @method \GuzzleHttp\Promise\Promise getObjectLockConfigurationAsync(array $args = [])
153 * @method \Aws\Result getObjectRetention(array $args = [])
154 * @method \GuzzleHttp\Promise\Promise getObjectRetentionAsync(array $args = [])
155 * @method \Aws\Result getObjectTagging(array $args = [])
156 * @method \GuzzleHttp\Promise\Promise getObjectTaggingAsync(array $args = [])
157 * @method \Aws\Result getObjectTorrent(array $args = [])
158 * @method \GuzzleHttp\Promise\Promise getObjectTorrentAsync(array $args = [])
159 * @method \Aws\Result getPublicAccessBlock(array $args = [])
160 * @method \GuzzleHttp\Promise\Promise getPublicAccessBlockAsync(array $args = [])
161 * @method \Aws\Result headBucket(array $args = [])
162 * @method \GuzzleHttp\Promise\Promise headBucketAsync(array $args = [])
163 * @method \Aws\Result headObject(array $args = [])
164 * @method \GuzzleHttp\Promise\Promise headObjectAsync(array $args = [])
165 * @method \Aws\Result listBucketAnalyticsConfigurations(array $args = [])
166 * @method \GuzzleHttp\Promise\Promise listBucketAnalyticsConfigurationsAsync(array $args = [])
167 * @method \Aws\Result listBucketIntelligentTieringConfigurations(array $args = [])
168 * @method \GuzzleHttp\Promise\Promise listBucketIntelligentTieringConfigurationsAsync(array $args = [])
169 * @method \Aws\Result listBucketInventoryConfigurations(array $args = [])
170 * @method \GuzzleHttp\Promise\Promise listBucketInventoryConfigurationsAsync(array $args = [])
171 * @method \Aws\Result listBucketMetricsConfigurations(array $args = [])
172 * @method \GuzzleHttp\Promise\Promise listBucketMetricsConfigurationsAsync(array $args = [])
173 * @method \Aws\Result listBuckets(array $args = [])
174 * @method \GuzzleHttp\Promise\Promise listBucketsAsync(array $args = [])
175 * @method \Aws\Result listDirectoryBuckets(array $args = [])
176 * @method \GuzzleHttp\Promise\Promise listDirectoryBucketsAsync(array $args = [])
177 * @method \Aws\Result listMultipartUploads(array $args = [])
178 * @method \GuzzleHttp\Promise\Promise listMultipartUploadsAsync(array $args = [])
179 * @method \Aws\Result listObjectVersions(array $args = [])
180 * @method \GuzzleHttp\Promise\Promise listObjectVersionsAsync(array $args = [])
181 * @method \Aws\Result listObjects(array $args = [])
182 * @method \GuzzleHttp\Promise\Promise listObjectsAsync(array $args = [])
183 * @method \Aws\Result listObjectsV2(array $args = [])
184 * @method \GuzzleHttp\Promise\Promise listObjectsV2Async(array $args = [])
185 * @method \Aws\Result listParts(array $args = [])
186 * @method \GuzzleHttp\Promise\Promise listPartsAsync(array $args = [])
187 * @method \Aws\Result putBucketAbac(array $args = [])
188 * @method \GuzzleHttp\Promise\Promise putBucketAbacAsync(array $args = [])
189 * @method \Aws\Result putBucketAccelerateConfiguration(array $args = [])
190 * @method \GuzzleHttp\Promise\Promise putBucketAccelerateConfigurationAsync(array $args = [])
191 * @method \Aws\Result putBucketAcl(array $args = [])
192 * @method \GuzzleHttp\Promise\Promise putBucketAclAsync(array $args = [])
193 * @method \Aws\Result putBucketAnalyticsConfiguration(array $args = [])
194 * @method \GuzzleHttp\Promise\Promise putBucketAnalyticsConfigurationAsync(array $args = [])
195 * @method \Aws\Result putBucketCors(array $args = [])
196 * @method \GuzzleHttp\Promise\Promise putBucketCorsAsync(array $args = [])
197 * @method \Aws\Result putBucketEncryption(array $args = [])
198 * @method \GuzzleHttp\Promise\Promise putBucketEncryptionAsync(array $args = [])
199 * @method \Aws\Result putBucketIntelligentTieringConfiguration(array $args = [])
200 * @method \GuzzleHttp\Promise\Promise putBucketIntelligentTieringConfigurationAsync(array $args = [])
201 * @method \Aws\Result putBucketInventoryConfiguration(array $args = [])
202 * @method \GuzzleHttp\Promise\Promise putBucketInventoryConfigurationAsync(array $args = [])
203 * @method \Aws\Result putBucketLifecycle(array $args = [])
204 * @method \GuzzleHttp\Promise\Promise putBucketLifecycleAsync(array $args = [])
205 * @method \Aws\Result putBucketLifecycleConfiguration(array $args = [])
206 * @method \GuzzleHttp\Promise\Promise putBucketLifecycleConfigurationAsync(array $args = [])
207 * @method \Aws\Result putBucketLogging(array $args = [])
208 * @method \GuzzleHttp\Promise\Promise putBucketLoggingAsync(array $args = [])
209 * @method \Aws\Result putBucketMetricsConfiguration(array $args = [])
210 * @method \GuzzleHttp\Promise\Promise putBucketMetricsConfigurationAsync(array $args = [])
211 * @method \Aws\Result putBucketNotification(array $args = [])
212 * @method \GuzzleHttp\Promise\Promise putBucketNotificationAsync(array $args = [])
213 * @method \Aws\Result putBucketNotificationConfiguration(array $args = [])
214 * @method \GuzzleHttp\Promise\Promise putBucketNotificationConfigurationAsync(array $args = [])
215 * @method \Aws\Result putBucketOwnershipControls(array $args = [])
216 * @method \GuzzleHttp\Promise\Promise putBucketOwnershipControlsAsync(array $args = [])
217 * @method \Aws\Result putBucketPolicy(array $args = [])
218 * @method \GuzzleHttp\Promise\Promise putBucketPolicyAsync(array $args = [])
219 * @method \Aws\Result putBucketReplication(array $args = [])
220 * @method \GuzzleHttp\Promise\Promise putBucketReplicationAsync(array $args = [])
221 * @method \Aws\Result putBucketRequestPayment(array $args = [])
222 * @method \GuzzleHttp\Promise\Promise putBucketRequestPaymentAsync(array $args = [])
223 * @method \Aws\Result putBucketTagging(array $args = [])
224 * @method \GuzzleHttp\Promise\Promise putBucketTaggingAsync(array $args = [])
225 * @method \Aws\Result putBucketVersioning(array $args = [])
226 * @method \GuzzleHttp\Promise\Promise putBucketVersioningAsync(array $args = [])
227 * @method \Aws\Result putBucketWebsite(array $args = [])
228 * @method \GuzzleHttp\Promise\Promise putBucketWebsiteAsync(array $args = [])
229 * @method \Aws\Result putObject(array $args = [])
230 * @method \GuzzleHttp\Promise\Promise putObjectAsync(array $args = [])
231 * @method \Aws\Result putObjectAcl(array $args = [])
232 * @method \GuzzleHttp\Promise\Promise putObjectAclAsync(array $args = [])
233 * @method \Aws\Result putObjectLegalHold(array $args = [])
234 * @method \GuzzleHttp\Promise\Promise putObjectLegalHoldAsync(array $args = [])
235 * @method \Aws\Result putObjectLockConfiguration(array $args = [])
236 * @method \GuzzleHttp\Promise\Promise putObjectLockConfigurationAsync(array $args = [])
237 * @method \Aws\Result putObjectRetention(array $args = [])
238 * @method \GuzzleHttp\Promise\Promise putObjectRetentionAsync(array $args = [])
239 * @method \Aws\Result putObjectTagging(array $args = [])
240 * @method \GuzzleHttp\Promise\Promise putObjectTaggingAsync(array $args = [])
241 * @method \Aws\Result putPublicAccessBlock(array $args = [])
242 * @method \GuzzleHttp\Promise\Promise putPublicAccessBlockAsync(array $args = [])
243 * @method \Aws\Result renameObject(array $args = [])
244 * @method \GuzzleHttp\Promise\Promise renameObjectAsync(array $args = [])
245 * @method \Aws\Result restoreObject(array $args = [])
246 * @method \GuzzleHttp\Promise\Promise restoreObjectAsync(array $args = [])
247 * @method \Aws\Result selectObjectContent(array $args = [])
248 * @method \GuzzleHttp\Promise\Promise selectObjectContentAsync(array $args = [])
249 * @method \Aws\Result updateBucketMetadataInventoryTableConfiguration(array $args = [])
250 * @method \GuzzleHttp\Promise\Promise updateBucketMetadataInventoryTableConfigurationAsync(array $args = [])
251 * @method \Aws\Result updateBucketMetadataJournalTableConfiguration(array $args = [])
252 * @method \GuzzleHttp\Promise\Promise updateBucketMetadataJournalTableConfigurationAsync(array $args = [])
253 * @method \Aws\Result updateObjectEncryption(array $args = [])
254 * @method \GuzzleHttp\Promise\Promise updateObjectEncryptionAsync(array $args = [])
255 * @method \Aws\Result uploadPart(array $args = [])
256 * @method \GuzzleHttp\Promise\Promise uploadPartAsync(array $args = [])
257 * @method \Aws\Result uploadPartCopy(array $args = [])
258 * @method \GuzzleHttp\Promise\Promise uploadPartCopyAsync(array $args = [])
259 * @method \Aws\Result writeGetObjectResponse(array $args = [])
260 * @method \GuzzleHttp\Promise\Promise writeGetObjectResponseAsync(array $args = [])
261 */
262 class S3Client extends AwsClient implements S3ClientInterface
263 {
264 private const DIRECTORY_BUCKET_REGEX = '/^[a-zA-Z0-9_-]+--[a-z0-9]+-az\d+--x-s3'
265 .'(?!.*(?:-s3alias|--ol-s3|\.mrap))$/';
266 use S3ClientTrait;
267
268 /** @var array */
269 private static $mandatoryAttributes = ['Bucket', 'Key'];
270
271 /** @var array */
272 private static $checksumOptionEnum = [
273 'when_supported' => true,
274 'when_required' => true
275 ];
276
277 public static function getArguments()
278 {
279 $args = parent::getArguments();
280 $args['retries']['fn'] = [__CLASS__, '_applyRetryConfig'];
281 $args['api_provider']['fn'] = [__CLASS__, '_applyApiProvider'];
282
283 return
284 [
285 'request_checksum_calculation' => [
286 'type' => 'config',
287 'valid' => ['string'],
288 'doc' => 'Valid values are `when_supported` and `when_required`. Default is `when_supported`.'
289 . ' `when_supported` results in checksum calculation when an operation has modeled checksum support.'
290 . ' `when_required` results in checksum calculation when an operation has modeled checksum support and'
291 . ' request checksums are modeled as required.',
292 'fn' => [__CLASS__, '_apply_request_checksum_calculation'],
293 'default' => [__CLASS__, '_default_request_checksum_calculation'],
294 ],
295 'response_checksum_validation' => [
296 'type' => 'config',
297 'valid' => ['string'],
298 'doc' => 'Valid values are `when_supported` and `when_required`. Default is `when_supported`.'
299 . ' `when_supported` results in checksum validation when an operation has modeled checksum support.'
300 . ' `when_required` results in checksum validation when an operation has modeled checksum support and'
301 . ' `CheckSumMode` is set to `enabled`.',
302 'fn' => [__CLASS__, '_apply_response_checksum_validation'],
303 'default' => [__CLASS__, '_default_response_checksum_validation'],
304 ]
305 ]
306 + $args + [
307 'bucket_endpoint' => [
308 'type' => 'config',
309 'valid' => ['bool'],
310 'doc' => 'Set to true to send requests to a hardcoded '
311 . 'bucket endpoint rather than create an endpoint as a '
312 . 'result of injecting the bucket into the URL. This '
313 . 'option is useful for interacting with CNAME endpoints.',
314 ],
315 'use_arn_region' => [
316 'type' => 'config',
317 'valid' => [
318 'bool',
319 Configuration::class,
320 CacheInterface::class,
321 'callable'
322 ],
323 'doc' => 'Set to true to allow passed in ARNs to override'
324 . ' client region. Accepts...',
325 'fn' => [__CLASS__, '_apply_use_arn_region'],
326 'default' => [UseArnRegionConfigurationProvider::class, 'defaultProvider'],
327 ],
328 'use_accelerate_endpoint' => [
329 'type' => 'config',
330 'valid' => ['bool'],
331 'doc' => 'Set to true to send requests to an S3 Accelerate'
332 . ' endpoint by default. Can be enabled or disabled on'
333 . ' individual operations by setting'
334 . ' \'@use_accelerate_endpoint\' to true or false. Note:'
335 . ' you must enable S3 Accelerate on a bucket before it can'
336 . ' be accessed via an Accelerate endpoint.',
337 'default' => false,
338 ],
339 'use_path_style_endpoint' => [
340 'type' => 'config',
341 'valid' => ['bool'],
342 'doc' => 'Set to true to send requests to an S3 path style'
343 . ' endpoint by default.'
344 . ' Can be enabled or disabled on individual operations by setting'
345 . ' \'@use_path_style_endpoint\' to true or false.',
346 'default' => false,
347 ],
348 'disable_multiregion_access_points' => [
349 'type' => 'config',
350 'valid' => ['bool'],
351 'doc' => 'Set to true to disable the usage of'
352 . ' multi region access points. These are enabled by default.'
353 . ' Can be enabled or disabled on individual operations by setting'
354 . ' \'@disable_multiregion_access_points\' to true or false.',
355 'default' => false,
356 ],
357 'disable_express_session_auth' => [
358 'type' => 'config',
359 'valid' => ['bool'],
360 'doc' => 'Set to true to disable the usage of'
361 . ' s3 express session authentication. This is enabled by default.',
362 'default' => [__CLASS__, '_default_disable_express_session_auth'],
363 ],
364 's3_express_identity_provider' => [
365 'type' => 'config',
366 'valid' => [
367 'bool',
368 'callable'
369 ],
370 'doc' => 'Specifies the provider used to generate identities to sign s3 express requests. '
371 . 'Set to `false` to disable s3 express auth, or a callable provider used to create s3 express '
372 . 'identities or return null.',
373 'default' => [__CLASS__, '_default_s3_express_identity_provider'],
374 ],
375 ];
376 }
377
378 /**
379 * {@inheritdoc}
380 *
381 * In addition to the options available to
382 * {@see Aws\AwsClient::__construct}, S3Client accepts the following
383 * options:
384 *
385 * - bucket_endpoint: (bool) Set to true to send requests to a
386 * hardcoded bucket endpoint rather than create an endpoint as a result
387 * of injecting the bucket into the URL. This option is useful for
388 * interacting with CNAME endpoints. Note: if you are using version 2.243.0
389 * and above and do not expect the bucket name to appear in the host, you will
390 * also need to set `use_path_style_endpoint` to `true`.
391 * - calculate_md5: (bool) Set to false to disable calculating an MD5
392 * for all Amazon S3 signed uploads.
393 * - s3_us_east_1_regional_endpoint:
394 * (Aws\S3\RegionalEndpoint\ConfigurationInterface|Aws\CacheInterface\|callable|string|array)
395 * Specifies whether to use regional or legacy endpoints for the us-east-1
396 * region. Provide an Aws\S3\RegionalEndpoint\ConfigurationInterface object, an
397 * instance of Aws\CacheInterface, a callable configuration provider used
398 * to create endpoint configuration, a string value of `legacy` or
399 * `regional`, or an associative array with the following keys:
400 * endpoint_types: (string) Set to `legacy` or `regional`, defaults to
401 * `legacy`
402 * - use_accelerate_endpoint: (bool) Set to true to send requests to an S3
403 * Accelerate endpoint by default. Can be enabled or disabled on
404 * individual operations by setting '@use_accelerate_endpoint' to true or
405 * false. Note: you must enable S3 Accelerate on a bucket before it can be
406 * accessed via an Accelerate endpoint.
407 * - use_arn_region: (Aws\S3\UseArnRegion\ConfigurationInterface,
408 * Aws\CacheInterface, bool, callable) Set to true to enable the client
409 * to use the region from a supplied ARN argument instead of the client's
410 * region. Provide an instance of Aws\S3\UseArnRegion\ConfigurationInterface,
411 * an instance of Aws\CacheInterface, a callable that provides a promise for
412 * a Configuration object, or a boolean value. Defaults to false (i.e.
413 * the SDK will not follow the ARN region if it conflicts with the client
414 * region and instead throw an error).
415 * - use_dual_stack_endpoint: (bool) Set to true to send requests to an S3
416 * Dual Stack endpoint by default, which enables IPv6 Protocol.
417 * Can be enabled or disabled on individual operations by setting
418 * '@use_dual_stack_endpoint\' to true or false. Note:
419 * you cannot use it together with an accelerate endpoint.
420 * - use_path_style_endpoint: (bool) Set to true to send requests to an S3
421 * path style endpoint by default.
422 * Can be enabled or disabled on individual operations by setting
423 * '@use_path_style_endpoint\' to true or false. Note:
424 * you cannot use it together with an accelerate endpoint.
425 * - disable_multiregion_access_points: (bool) Set to true to disable
426 * sending multi region requests. They are enabled by default.
427 * Can be enabled or disabled on individual operations by setting
428 * '@disable_multiregion_access_points\' to true or false. Note:
429 * you cannot use it together with an accelerate or dualstack endpoint.
430 *
431 * @param array $args
432 */
433 public function __construct(array $args)
434 {
435 if (
436 !isset($args['s3_us_east_1_regional_endpoint'])
437 || $args['s3_us_east_1_regional_endpoint'] instanceof CacheInterface
438 ) {
439 $args['s3_us_east_1_regional_endpoint'] = ConfigurationProvider::defaultProvider($args);
440 }
441 $this->addBuiltIns($args);
442 parent::__construct($args);
443 $stack = $this->getHandlerList();
444 $config = $this->getConfig();
445 $stack->appendInit(SSECMiddleware::wrap($this->getEndpoint()->getScheme()), 's3.ssec');
446 $stack->appendBuild(
447 ApplyChecksumMiddleware::wrap($this->getApi(), $this->getConfig()),
448 's3.checksum'
449 );
450 $stack->appendBuild(
451 Middleware::contentType(['PutObject', 'UploadPart']),
452 's3.content_type'
453 );
454
455 if ($this->getConfig('bucket_endpoint')) {
456 $stack->appendBuild(BucketEndpointMiddleware::wrap(
457 $this->isUseEndpointV2(), $args['endpoint'] ?? null), 's3.bucket_endpoint'
458 );
459 } elseif (!$this->isUseEndpointV2()) {
460 $stack->appendBuild(
461 S3EndpointMiddleware::wrap(
462 $this->getRegion(),
463 $this->getConfig('endpoint_provider'),
464 [
465 'accelerate' => $this->getConfig('use_accelerate_endpoint'),
466 'path_style' => $this->getConfig('use_path_style_endpoint'),
467 'use_fips_endpoint' => $this->getConfig('use_fips_endpoint'),
468 'dual_stack' =>
469 $this->getConfig('use_dual_stack_endpoint')->isUseDualStackEndpoint(),
470
471 ]
472 ),
473 's3.endpoint_middleware'
474 );
475 }
476
477 $stack->appendBuild(
478 BucketEndpointArnMiddleware::wrap(
479 $this->getApi(),
480 $this->getRegion(),
481 [
482 'use_arn_region' => $this->getConfig('use_arn_region'),
483 'accelerate' => $this->getConfig('use_accelerate_endpoint'),
484 'path_style' => $this->getConfig('use_path_style_endpoint'),
485 'dual_stack' =>
486 $this->getConfig('use_dual_stack_endpoint')->isUseDualStackEndpoint(),
487 'use_fips_endpoint' => $this->getConfig('use_fips_endpoint'),
488 'disable_multiregion_access_points' =>
489 $this->getConfig('disable_multiregion_access_points'),
490 'endpoint' => $args['endpoint'] ?? null
491 ],
492 $this->isUseEndpointV2()
493 ),
494 's3.bucket_endpoint_arn'
495 );
496 if ($this->getConfig('disable_express_session_auth')) {
497 $stack->prependSign(
498 $this->getDisableExpressSessionAuthMiddleware(),
499 's3.disable_express_session_auth'
500 );
501 }
502
503 $stack->appendValidate(
504 InputValidationMiddleware::wrap($this->getApi(), self::$mandatoryAttributes),
505 'input_validation_middleware'
506 );
507 $stack->appendSign(ExpiresParsingMiddleware::wrap(), 's3.expires_parsing');
508 $stack->appendSign(PutObjectUrlMiddleware::wrap(), 's3.put_object_url');
509 $stack->appendSign(PermanentRedirectMiddleware::wrap(), 's3.permanent_redirect');
510 $stack->appendInit(Middleware::sourceFile($this->getApi()), 's3.source_file');
511 $stack->appendInit($this->getSaveAsParameter(), 's3.save_as');
512 $stack->appendInit($this->getLocationConstraintMiddleware(), 's3.location');
513 $stack->appendInit($this->getEncodingTypeMiddleware(), 's3.auto_encode');
514 $stack->appendInit($this->getHeadObjectMiddleware(), 's3.head_object');
515 $this->processModel($this->isUseEndpointV2());
516 if ($this->isUseEndpointV2()) {
517 $stack->after('builder',
518 's3.check_empty_path_with_query',
519 $this->getEmptyPathWithQuery());
520 }
521 }
522
523 /**
524 * Determine if a string is a valid name for a DNS compatible Amazon S3
525 * bucket.
526 *
527 * DNS compatible bucket names can be used as a subdomain in a URL (e.g.,
528 * "<bucket>.s3.amazonaws.com").
529 *
530 * @param string $bucket Bucket name to check.
531 *
532 * @return bool
533 */
534 public static function isBucketDnsCompatible($bucket)
535 {
536 if (!is_string($bucket)) {
537 return false;
538 }
539 $bucketLen = strlen($bucket);
540
541 return ($bucketLen >= 3 && $bucketLen <= 63) &&
542 // Cannot look like an IP address
543 !filter_var($bucket, FILTER_VALIDATE_IP) &&
544 preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket);
545 }
546
547 public static function _apply_use_arn_region($value, array &$args, HandlerList $list)
548 {
549 if ($value instanceof CacheInterface) {
550 $value = UseArnRegionConfigurationProvider::defaultProvider($args);
551 }
552 if (is_callable($value)) {
553 $value = $value();
554 }
555 if ($value instanceof PromiseInterface) {
556 $value = $value->wait();
557 }
558 if ($value instanceof ConfigurationInterface) {
559 $args['use_arn_region'] = $value;
560 } else {
561 // The Configuration class itself will validate other inputs
562 $args['use_arn_region'] = new Configuration($value);
563 }
564 }
565
566 public static function _default_request_checksum_calculation(array $args): string
567 {
568 return ConfigurationResolver::resolve(
569 'request_checksum_calculation',
570 ApplyChecksumMiddleware::DEFAULT_CALCULATION_MODE,
571 'string',
572 $args
573 );
574 }
575
576 public static function _apply_request_checksum_calculation(
577 string $value,
578 array &$args
579 ): void
580 {
581 $value = strtolower($value);
582 if (array_key_exists($value, self::$checksumOptionEnum)) {
583 $args['request_checksum_calculation'] = $value;
584 } else {
585 $validValues = implode(' | ', array_keys(self::$checksumOptionEnum));
586 throw new \InvalidArgumentException(
587 'invalid value provided for `request_checksum_calculation`.'
588 . ' valid values are: ' . $validValues . '.'
589 );
590 }
591 }
592
593 public static function _default_response_checksum_validation(array $args): string
594 {
595 return ConfigurationResolver::resolve(
596 'response_checksum_validation',
597 ValidateResponseChecksumResultMutator::DEFAULT_VALIDATION_MODE,
598 'string',
599 $args
600 );
601 }
602
603 public static function _apply_response_checksum_validation(
604 $value,
605 array &$args
606 ): void
607 {
608 $value = strtolower($value);
609 if (array_key_exists($value, self::$checksumOptionEnum)) {
610 $args['response_checksum_validation'] = $value;
611 } else {
612 $validValues = implode(' | ', array_keys(self::$checksumOptionEnum));
613 throw new \InvalidArgumentException(
614 'invalid value provided for `response_checksum_validation`.'
615 . ' valid values are: ' . $validValues . '.'
616 );
617 }
618 }
619
620 public static function _default_disable_express_session_auth(array &$args)
621 {
622 return ConfigurationResolver::resolve(
623 's3_disable_express_session_auth',
624 false,
625 'bool',
626 $args
627 );
628 }
629
630 public static function _default_s3_express_identity_provider(array $args)
631 {
632 if ($args['config']['disable_express_session_auth']) {
633 return false;
634 }
635 return new S3ExpressIdentityProvider($args['region']);
636 }
637
638 public function createPresignedRequest(CommandInterface $command, $expires, array $options = [])
639 {
640 $command = clone $command;
641 $list = $command->getHandlerList();
642 $list->remove('signer');
643
644 //Removes checksum calculation behavior by default
645 if (empty($command['ChecksumAlgorithm'])
646 && empty($command['AddContentMD5'])
647 ) {
648 $list->remove('s3.checksum');
649 }
650
651 $request = \Aws\serialize($command);
652
653 //Applies ContentSHA256 parameter, if provided and not applied
654 // by middleware
655 $commandName = $command->getName();
656 if (!empty($command['ContentSHA256']
657 && isset(ApplyChecksumMiddleware::$sha256[$commandName])
658 && !$request->hasHeader('X-Amz-Content-Sha256')
659 )) {
660 $request = $request->withHeader(
661 'X-Amz-Content-Sha256',
662 $command['ContentSHA256']
663 );
664 }
665
666 $signing_name = $command['@context']['signing_service']
667 ?? $this->getSigningName($request->getUri()->getHost());
668 $signature_version = $this->getSignatureVersionFromCommand($command);
669
670 /** @var \Aws\Signature\SignatureInterface $signer */
671 $signer = call_user_func(
672 $this->getSignatureProvider(),
673 $signature_version,
674 $signing_name,
675 $this->getConfig('signing_region')
676 );
677 if ($signature_version == 'v4-s3express') {
678 $provider = $this->getConfig('s3_express_identity_provider');
679 $credentials = $provider($command)->wait();
680 } else {
681 $credentials = $this->getCredentials()->wait();
682 }
683 return $signer->presign(
684 $request,
685 $credentials,
686 $expires,
687 $options
688 );
689 }
690
691 /**
692 * Returns the URL to an object identified by its bucket and key.
693 *
694 * The URL returned by this method is not signed nor does it ensure that the
695 * bucket and key given to the method exist. If you need a signed URL, then
696 * use the {@see \Aws\S3\S3Client::createPresignedRequest} method and get
697 * the URI of the signed request.
698 *
699 * @param string $bucket The name of the bucket where the object is located
700 * @param string $key The key of the object
701 *
702 * @return string The URL to the object
703 */
704 public function getObjectUrl($bucket, $key)
705 {
706 $command = $this->getCommand('GetObject', [
707 'Bucket' => $bucket,
708 'Key' => $key
709 ]);
710
711 return (string) \Aws\serialize($command)->getUri();
712 }
713
714 /**
715 * Raw URL encode a key and allow for '/' characters
716 *
717 * @param string $key Key to encode
718 *
719 * @return string Returns the encoded key
720 */
721 public static function encodeKey($key)
722 {
723 return str_replace('%2F', '/', rawurlencode($key));
724 }
725
726 /**
727 * Provides a middleware that removes the need to specify LocationConstraint on CreateBucket.
728 *
729 * @return \Closure
730 */
731 private function getLocationConstraintMiddleware()
732 {
733 $region = $this->getRegion();
734 return static function (callable $handler) use ($region) {
735 return function (Command $command, $request = null) use ($handler, $region) {
736 if ($command->getName() === 'CreateBucket'
737 && !self::isDirectoryBucket($command['Bucket'])
738 ) {
739 $locationConstraint = $command['CreateBucketConfiguration']['LocationConstraint']
740 ?? null;
741
742 if ($locationConstraint === 'us-east-1') {
743 unset($command['CreateBucketConfiguration']);
744 } elseif ('us-east-1' !== $region && empty($locationConstraint)) {
745 if (isset($command['CreateBucketConfiguration'])) {
746 $command['CreateBucketConfiguration']['LocationConstraint'] = $region;
747 } else {
748 $command['CreateBucketConfiguration'] = ['LocationConstraint' => $region];
749 }
750 }
751 }
752
753 return $handler($command, $request);
754 };
755 };
756 }
757
758 /**
759 * Provides a middleware that supports the `SaveAs` parameter.
760 *
761 * @return \Closure
762 */
763 private function getSaveAsParameter()
764 {
765 return static function (callable $handler) {
766 return function (Command $command, $request = null) use ($handler) {
767 if ($command->getName() === 'GetObject' && isset($command['SaveAs'])) {
768 $command['@http']['sink'] = $command['SaveAs'];
769 unset($command['SaveAs']);
770 }
771
772 return $handler($command, $request);
773 };
774 };
775 }
776
777 /**
778 * Provides a middleware that disables content decoding on HeadObject
779 * commands.
780 *
781 * @return \Closure
782 */
783 private function getHeadObjectMiddleware()
784 {
785 return static function (callable $handler) {
786 return function (
787 CommandInterface $command,
788 ?RequestInterface $request = null
789 ) use ($handler) {
790 if ($command->getName() === 'HeadObject'
791 && !isset($command['@http']['decode_content'])
792 ) {
793 $command['@http']['decode_content'] = false;
794 }
795
796 return $handler($command, $request);
797 };
798 };
799 }
800
801 /**
802 * Provides a middleware that autopopulates the EncodingType parameter on
803 * ListObjects commands.
804 *
805 * @return \Closure
806 */
807 private function getEncodingTypeMiddleware()
808 {
809 return static function (callable $handler) {
810 return function (Command $command, $request = null) use ($handler) {
811 $autoSet = false;
812 if ($command->getName() === 'ListObjects'
813 && empty($command['EncodingType'])
814 ) {
815 $command['EncodingType'] = 'url';
816 $autoSet = true;
817 }
818
819 return $handler($command, $request)
820 ->then(function (ResultInterface $result) use ($autoSet) {
821 if ($result['EncodingType'] === 'url' && $autoSet) {
822 static $topLevel = [
823 'Delimiter',
824 'Marker',
825 'NextMarker',
826 'Prefix',
827 ];
828 static $nested = [
829 ['Contents', 'Key'],
830 ['CommonPrefixes', 'Prefix'],
831 ];
832
833 foreach ($topLevel as $key) {
834 if (isset($result[$key])) {
835 $result[$key] = urldecode($result[$key]);
836 }
837 }
838 foreach ($nested as $steps) {
839 if (isset($result[$steps[0]])) {
840 foreach ($result[$steps[0]] as $key => $part) {
841 if (isset($part[$steps[1]])) {
842 $result[$steps[0]][$key][$steps[1]]
843 = urldecode($part[$steps[1]]);
844 }
845 }
846 }
847 }
848
849 }
850
851 return $result;
852 });
853 };
854 };
855 }
856
857 /**
858 * Provides a middleware that checks for an empty path and a
859 * non-empty query string.
860 *
861 * @return \Closure
862 */
863 private function getEmptyPathWithQuery()
864 {
865 return static function (callable $handler) {
866 return function (Command $command, RequestInterface $request) use ($handler) {
867 $uri = $request->getUri();
868 if (empty($uri->getPath()) && !empty($uri->getQuery())) {
869 $uri = $uri->withPath('/');
870 $request = $request->withUri($uri);
871 }
872
873 return $handler($command, $request);
874 };
875 };
876 }
877
878 /**
879 * Provides a middleware that disables express session auth when
880 * customers opt out of it.
881 *
882 * @return \Closure
883 */
884 private function getDisableExpressSessionAuthMiddleware()
885 {
886 return static function (callable $handler) {
887 return static function (
888 CommandInterface $command,
889 ?RequestInterface $request = null
890 ) use ($handler) {
891 if (!empty($command['@context']['signature_version'])
892 && $command['@context']['signature_version'] === 'v4-s3express'
893 ) {
894 $command['@context']['signature_version'] = 's3v4';
895 }
896 return $handler($command, $request);
897 };
898 };
899 }
900
901 /**
902 * Special handling for when the service name is s3-object-lambda.
903 * So, if the host contains s3-object-lambda, then the service name
904 * returned is s3-object-lambda, otherwise the default signing service is returned.
905 * @param string $host The host to validate if is a s3-object-lambda URL.
906 * @return string returns the signing service name to be used
907 */
908 private function getSigningName($host)
909 {
910 if (strpos( $host, 's3-object-lambda')) {
911 return 's3-object-lambda';
912 }
913
914 return $this->getConfig('signing_name');
915 }
916
917 /**
918 * If EndpointProviderV2 is used, removes `Bucket` from request URIs.
919 * This is now handled by the endpoint ruleset.
920 *
921 * Additionally adds a synthetic shape `ExpiresString` and modifies
922 * `Expires` type to ensure it remains set to `timestamp`.
923 *
924 * @param array $args
925 * @return void
926 *
927 * @internal
928 */
929 private function processModel(bool $isUseEndpointV2): void
930 {
931 $definition = $this->getApi()->getDefinition();
932
933 if ($isUseEndpointV2) {
934 foreach($definition['operations'] as &$operation) {
935 if (isset($operation['http']['requestUri'])) {
936 $requestUri = $operation['http']['requestUri'];
937 if ($requestUri === "/{Bucket}") {
938 $requestUri = str_replace('/{Bucket}', '/', $requestUri);
939 } else {
940 $requestUri = str_replace('/{Bucket}', '', $requestUri);
941 // If we're left with just a query string, prepend '/'
942 if (str_starts_with($requestUri, '?')) {
943 $requestUri = '/' . $requestUri;
944 }
945 }
946 $operation['http']['requestUri'] = $requestUri;
947 }
948 }
949 }
950
951 foreach ($definition['shapes'] as $key => &$value) {
952 $suffix = 'Output';
953 if (str_ends_with($key, $suffix)) {
954 if (isset($value['members']['Expires'])) {
955 $value['members']['Expires']['deprecated'] = true;
956 $value['members']['ExpiresString'] = [
957 'shape' => 'ExpiresString',
958 'location' => 'header',
959 'locationName' => 'Expires'
960 ];
961 }
962 }
963 }
964 $definition['shapes']['ExpiresString']['type'] = 'string';
965 $definition['shapes']['Expires']['type'] = 'timestamp';
966
967 $this->getApi()->setDefinition($definition);
968 }
969
970 /**
971 * Adds service-specific client built-in values
972 *
973 * @return void
974 */
975 private function addBuiltIns($args)
976 {
977 if (isset($args['region'])
978 && $args['region'] !== 'us-east-1'
979 ) {
980 return false;
981 }
982
983 if (!isset($args['region'])
984 && ConfigurationResolver::resolve('region', '', 'string') !== 'us-east-1'
985 ) {
986 return false;
987 }
988
989 $key = 'AWS::S3::UseGlobalEndpoint';
990 $result = $args['s3_us_east_1_regional_endpoint'] instanceof \Closure ?
991 $args['s3_us_east_1_regional_endpoint']()->wait() : $args['s3_us_east_1_regional_endpoint'];
992
993 if (is_string($result)) {
994 if ($result === 'regional') {
995 $value = false;
996 } else if ($result === 'legacy') {
997 $value = true;
998 } else {
999 return;
1000 }
1001 } else {
1002 if ($result->isFallback()
1003 || $result->getEndpointsType() === 'legacy'
1004 ) {
1005 $value = true;
1006 } else {
1007 $value = false;
1008 }
1009 }
1010 $this->clientBuiltIns[$key] = $value;
1011 }
1012
1013 /**
1014 * Determines whether a bucket is a directory bucket.
1015 * Only considers the availability zone/suffix format
1016 *
1017 * @param string $bucket
1018 * @return bool
1019 */
1020 public static function isDirectoryBucket(string $bucket): bool
1021 {
1022 return preg_match(self::DIRECTORY_BUCKET_REGEX, $bucket) === 1;
1023 }
1024
1025 /** @internal */
1026 public static function _applyRetryConfig($value, $args, HandlerList $list)
1027 {
1028 if (!$value) {
1029 return;
1030 }
1031
1032 $config = \Aws\Retry\ConfigurationProvider::unwrap($value);
1033
1034 if ($config->getMode() === 'legacy') {
1035 self::appendLegacyModeRetries($config, $list);
1036 return;
1037 }
1038
1039 if (NewRetriesOptIn::isEnabled()) {
1040 self::appendStandardModeRetriesNew($config, $args, $list);
1041 return;
1042 }
1043
1044 self::appendStandardModeRetries($config, $args, $list);
1045 }
1046
1047 private static function appendLegacyModeRetries(
1048 RetryConfigurationInterface $config,
1049 HandlerList $list
1050 ): void
1051 {
1052 $maxRetries = $config->getMaxAttempts() - 1;
1053 $baseDecider = RetryMiddleware::createDefaultDecider($maxRetries);
1054
1055 $decider = function ($retries, $command, $request, $result, $error) use ($baseDecider, $maxRetries) {
1056 $effectiveMax = $command['@retries'] ?? $maxRetries;
1057
1058 if ($baseDecider($retries, $command, $request, $result, $error)) {
1059 return true;
1060 }
1061
1062 if ($error instanceof AwsException && $retries < $effectiveMax) {
1063 return self::isS3SocketIssue($error, $command->getName());
1064 }
1065
1066 return false;
1067 };
1068
1069 $list->appendSign(
1070 Middleware::retry($decider, [RetryMiddleware::class, 'exponentialDelay']),
1071 'retry'
1072 );
1073 }
1074
1075 private static function appendStandardModeRetries(
1076 RetryConfigurationInterface $config,
1077 $args,
1078 HandlerList $list
1079 ): void
1080 {
1081 // decider that combines V2's default decider with S3-specific checks.
1082 $defaultDecider = RetryMiddlewareV2::createDefaultDecider(
1083 new QuotaManager(),
1084 $config->getMaxAttempts()
1085 );
1086
1087 $list->appendSign(
1088 RetryMiddlewareV2::wrap(
1089 $config,
1090 [
1091 'collect_stats' => $args['stats']['retries'],
1092 'decider' => function (
1093 $attempts,
1094 CommandInterface $cmd,
1095 $result
1096 ) use ($defaultDecider, $config) {
1097 if ($defaultDecider($attempts, $cmd, $result)) {
1098 return true;
1099 }
1100 if ($result instanceof AwsException
1101 && $attempts < $config->getMaxAttempts()
1102 ) {
1103 return self::isS3SocketIssue($result, $cmd->getName());
1104 }
1105 return false;
1106 },
1107 ]
1108 ),
1109 'retry'
1110 );
1111 }
1112
1113 private static function appendStandardModeRetriesNew(
1114 RetryConfigurationInterface $config,
1115 $args,
1116 HandlerList $list
1117 ): void
1118 {
1119 // AWS_NEW_RETRIES_2026 path. The base middleware already handles
1120 // the standard retryable shapes, so this decider only adds the
1121 // S3-specific socket carve-out.
1122 $list->appendSign(
1123 RetryV3Middleware::wrap(
1124 $config,
1125 [
1126 'collect_stats' => $args['stats']['retries'],
1127 'service' => $args['service'],
1128 'decider' => function (
1129 $attempts,
1130 CommandInterface $cmd,
1131 $result
1132 ) {
1133 return $result instanceof AwsException
1134 && self::isS3SocketIssue($result, $cmd->getName());
1135 },
1136 ]
1137 ),
1138 'retry'
1139 );
1140 }
1141
1142 private static function isS3SocketIssue(AwsException $error, string $commandName): bool
1143 {
1144 $response = $error->getResponse();
1145 if (!empty($response) && $response->getStatusCode() >= 400) {
1146 return strpos(
1147 (string) $response->getBody(),
1148 'Your socket connection to the server'
1149 ) !== false;
1150 }
1151
1152 // All commands except CompleteMultipartUpload are idempotent and may
1153 // be retried without worry if a networking error has occurred.
1154 return $error->getPrevious() instanceof RequestException
1155 && $commandName !== 'CompleteMultipartUpload';
1156 }
1157
1158 /** @internal */
1159 public static function _applyApiProvider($value, array &$args, HandlerList $list)
1160 {
1161 ClientResolver::_apply_api_provider($value, $args);
1162 $s3Parser = new S3Parser(
1163 $args['parser'],
1164 $args['error_parser'],
1165 $args['api'],
1166 $args['exception_class']
1167 );
1168 $s3Parser->addS3ResultMutator(
1169 'get-bucket-location',
1170 new GetBucketLocationResultMutator()
1171 );
1172 $s3Parser->addS3ResultMutator(
1173 'validate-response-checksum',
1174 new ValidateResponseChecksumResultMutator(
1175 $args['api'],
1176 ['response_checksum_validation' => $args['response_checksum_validation']]
1177 )
1178 );
1179 $args['parser'] = $s3Parser;
1180 }
1181
1182 /**
1183 * @internal
1184 * @codeCoverageIgnore
1185 */
1186 public static function applyDocFilters(array $api, array $docs)
1187 {
1188 $b64 = '<div class="alert alert-info">This value will be base64 encoded on your behalf.</div>';
1189 $opt = '<div class="alert alert-info">This value will be computed for you it is not supplied.</div>';
1190
1191 // Add a note on the CopyObject docs
1192 $s3ExceptionRetryMessage = "<p>Additional info on response behavior: if there is"
1193 . " an internal error in S3 after the request was successfully received,"
1194 . " a 200 response will be returned with an <code>S3Exception</code> embedded"
1195 . " in it; this will still be caught and retried by"
1196 . " <code>RetryMiddleware.</code></p>";
1197
1198 $docs['operations']['CopyObject'] .= $s3ExceptionRetryMessage;
1199 $docs['operations']['CompleteMultipartUpload'] .= $s3ExceptionRetryMessage;
1200 $docs['operations']['UploadPartCopy'] .= $s3ExceptionRetryMessage;
1201 $docs['operations']['UploadPart'] .= $s3ExceptionRetryMessage;
1202
1203 // Add note about stream ownership in the putObject call
1204 $guzzleStreamMessage = "<p>Additional info on behavior of the stream"
1205 . " parameters: Psr7 takes ownership of streams and will automatically close"
1206 . " streams when this method is called with a stream as the <code>Body</code>"
1207 . " parameter. To prevent this, set the <code>Body</code> using"
1208 . " <code>GuzzleHttp\Psr7\stream_for</code> method with a is an instance of"
1209 . " <code>Psr\Http\Message\StreamInterface</code>, and it will be returned"
1210 . " unmodified. This will allow you to keep the stream in scope. </p>";
1211 $docs['operations']['PutObject'] .= $guzzleStreamMessage;
1212
1213 // Add the SourceFile parameter.
1214 $docs['shapes']['SourceFile']['base'] = 'The path to a file on disk to use instead of the Body parameter.';
1215 $api['shapes']['SourceFile'] = ['type' => 'string'];
1216 $api['shapes']['PutObjectRequest']['members']['SourceFile'] = ['shape' => 'SourceFile'];
1217 $api['shapes']['UploadPartRequest']['members']['SourceFile'] = ['shape' => 'SourceFile'];
1218
1219 // Add the ContentSHA256 parameter.
1220 $docs['shapes']['ContentSHA256']['base'] = 'A SHA256 hash of the body content of the request.';
1221 $api['shapes']['ContentSHA256'] = ['type' => 'string'];
1222 $api['shapes']['PutObjectRequest']['members']['ContentSHA256'] = ['shape' => 'ContentSHA256'];
1223 $api['shapes']['UploadPartRequest']['members']['ContentSHA256'] = ['shape' => 'ContentSHA256'];
1224 $docs['shapes']['ContentSHA256']['append'] = $opt;
1225
1226 // Add the AddContentMD5 parameter.
1227 $docs['shapes']['AddContentMD5']['base'] = 'Set to true to calculate the ContentMD5 for the upload.';
1228 $api['shapes']['AddContentMD5'] = ['type' => 'boolean'];
1229 $api['shapes']['PutObjectRequest']['members']['AddContentMD5'] = ['shape' => 'AddContentMD5'];
1230 $api['shapes']['UploadPartRequest']['members']['AddContentMD5'] = ['shape' => 'AddContentMD5'];
1231
1232 // Add the SaveAs parameter.
1233 $docs['shapes']['SaveAs']['base'] = 'The path to a file on disk to save the object data.';
1234 $api['shapes']['SaveAs'] = ['type' => 'string'];
1235 $api['shapes']['GetObjectRequest']['members']['SaveAs'] = ['shape' => 'SaveAs'];
1236
1237 // Several SSECustomerKey documentation updates.
1238 $docs['shapes']['SSECustomerKey']['append'] = $b64;
1239 $docs['shapes']['CopySourceSSECustomerKey']['append'] = $b64;
1240 $docs['shapes']['SSECustomerKeyMd5']['append'] = $opt;
1241
1242 // Add the ObjectURL to various output shapes and documentation.
1243 $docs['shapes']['ObjectURL']['base'] = 'The URI of the created object.';
1244 $api['shapes']['ObjectURL'] = ['type' => 'string'];
1245 $api['shapes']['PutObjectOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
1246 $api['shapes']['CopyObjectOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
1247 $api['shapes']['CompleteMultipartUploadOutput']['members']['ObjectURL'] = ['shape' => 'ObjectURL'];
1248
1249 // Fix references to Location Constraint.
1250 unset($api['shapes']['CreateBucketRequest']['payload']);
1251 $api['shapes']['BucketLocationConstraint']['enum'] = [
1252 "ap-northeast-1",
1253 "ap-southeast-2",
1254 "ap-southeast-1",
1255 "cn-north-1",
1256 "eu-central-1",
1257 "eu-west-1",
1258 "us-east-1",
1259 "us-west-1",
1260 "us-west-2",
1261 "sa-east-1",
1262 ];
1263
1264 // Add a note that the ContentMD5 is automatically computed, except for with PutObject and UploadPart
1265 $docs['shapes']['ContentMD5']['append'] = '<div class="alert alert-info">The value will be computed on '
1266 . 'your behalf.</div>';
1267 $docs['shapes']['ContentMD5']['excludeAppend'] = ['PutObjectRequest', 'UploadPartRequest'];
1268
1269 //Add a note to ContentMD5 for PutObject and UploadPart that specifies the value is required
1270 // When uploading to a bucket with object lock enabled and that it is not computed automatically
1271 $objectLock = '<div class="alert alert-info">This value is required if uploading to a bucket '
1272 . 'which has Object Lock enabled. It will not be calculated for you automatically. If you wish to have '
1273 . 'the value calculated for you, use the `AddContentMD5` parameter.</div>';
1274 $docs['shapes']['ContentMD5']['appendOnly'] = [
1275 'message' => $objectLock,
1276 'shapes' => ['PutObjectRequest', 'UploadPartRequest']
1277 ];
1278
1279 // Add `ExpiresString` shape to output structures which contain `Expires`
1280 // Deprecate existing `Expires` shapes in output structures
1281 // Add/Update documentation for both `ExpiresString` and `Expires`
1282 // Ensure `Expires` type remains timestamp
1283 foreach ($api['shapes'] as $key => &$value) {
1284 $suffix = 'Output';
1285 if (substr($key, -strlen($suffix)) === $suffix) {
1286 if (isset($value['members']['Expires'])) {
1287 $value['members']['Expires']['deprecated'] = true;
1288 $value['members']['ExpiresString'] = [
1289 'shape' => 'ExpiresString',
1290 'location' => 'header',
1291 'locationName' => 'Expires'
1292 ];
1293 $docs['shapes']['Expires']['refs'][$key . '$Expires']
1294 .= '<p>This output shape has been deprecated. Please refer to <code>ExpiresString</code> instead.</p>.';
1295 }
1296 }
1297 }
1298 $api['shapes']['ExpiresString']['type'] = 'string';
1299 $docs['shapes']['ExpiresString']['base'] = 'The unparsed string value of the <code>Expires</code> output member.';
1300 $api['shapes']['Expires']['type'] = 'timestamp';
1301
1302 return [
1303 new Service($api, ApiProvider::defaultProvider()),
1304 new DocModel($docs)
1305 ];
1306 }
1307
1308 /**
1309 * @internal
1310 * @codeCoverageIgnore
1311 */
1312 public static function addDocExamples($examples)
1313 {
1314 $getObjectExample = [
1315 'input' => [
1316 'Bucket' => 'arn:aws:s3:us-east-1:123456789012:accesspoint:myaccesspoint',
1317 'Key' => 'my-key'
1318 ],
1319 'output' => [
1320 'Body' => 'class GuzzleHttp\Psr7\Stream#208 (7) {...}',
1321 'ContentLength' => '11',
1322 'ContentType' => 'application/octet-stream',
1323 ],
1324 'comments' => [
1325 'input' => '',
1326 'output' => 'Simplified example output'
1327 ],
1328 'description' => 'The following example retrieves an object by referencing the bucket via an S3 accesss point ARN. Result output is simplified for the example.',
1329 'id' => '',
1330 'title' => 'To get an object via an S3 access point ARN'
1331 ];
1332 if (isset($examples['GetObject'])) {
1333 $examples['GetObject'] []= $getObjectExample;
1334 } else {
1335 $examples['GetObject'] = [$getObjectExample];
1336 }
1337
1338 $putObjectExample = [
1339 'input' => [
1340 'Bucket' => 'arn:aws:s3:us-east-1:123456789012:accesspoint:myaccesspoint',
1341 'Key' => 'my-key',
1342 'Body' => 'my-body',
1343 ],
1344 'output' => [
1345 'ObjectURL' => 'https://my-bucket.s3.us-east-1.amazonaws.com/my-key'
1346 ],
1347 'comments' => [
1348 'input' => '',
1349 'output' => 'Simplified example output'
1350 ],
1351 'description' => 'The following example uploads an object by referencing the bucket via an S3 accesss point ARN. Result output is simplified for the example.',
1352 'id' => '',
1353 'title' => 'To upload an object via an S3 access point ARN'
1354 ];
1355 if (isset($examples['PutObject'])) {
1356 $examples['PutObject'] []= $putObjectExample;
1357 } else {
1358 $examples['PutObject'] = [$putObjectExample];
1359 }
1360
1361 return $examples;
1362 }
1363
1364 /**
1365 * @param CommandInterface $command
1366 * @return array|mixed|null
1367 */
1368 private function getSignatureVersionFromCommand(CommandInterface $command)
1369 {
1370 return $command['@context']['signature_version']
1371 ?? $this->getConfig('signature_version');
1372 }
1373 }