forked from minio/minio-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.ts
2009 lines (1823 loc) · 63.8 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as fs from 'node:fs'
import type { IncomingMessage } from 'node:http'
import * as http from 'node:http'
import * as https from 'node:https'
import path from 'node:path'
import type { Readable as ReadableStream } from 'node:stream'
import * as stream from 'node:stream'
import async from 'async'
import { isBrowser } from 'browser-or-node'
import _ from 'lodash'
import { mkdirp } from 'mkdirp'
import Xml from 'xml'
import { asCallback, asCallbackFn } from './as-callback.ts'
import { fsp, streamPromise } from './async.ts'
import { CredentialProvider } from './CredentialProvider.ts'
import * as errors from './errors.ts'
import { S3Error } from './errors.ts'
import { extensions } from './extensions.ts'
import type { MetaData } from './helpers.ts'
import {
DEFAULT_REGION,
extractMetadata,
getVersionId,
insertContentType,
isAmazonEndpoint,
isBoolean,
isEmpty,
isFunction,
isNumber,
isObject,
isOptionalFunction,
isReadableStream,
isString,
isValidBucketName,
isValidEndpoint,
isValidObjectName,
isValidPort,
isValidPrefix,
isVirtualHostStyle,
makeDateLong,
pipesetup,
prependXAMZMeta,
readableStream,
sanitizeETag,
toSha256,
uriEscape,
uriResourceEscape,
} from './helpers.ts'
import { qs } from './qs.ts'
import type { Region } from './s3-endpoints.ts'
import { getS3Endpoint } from './s3-endpoints.ts'
import { signV4 } from './signing.ts'
import * as transformers from './transformers.ts'
import type {
Binary,
BucketItemFromList,
BucketItemStat,
GetObjectOpt,
IRequest,
MakeBucketOpt,
NoResultCallback,
RequestHeaders,
ResultCallback,
StatObjectOpts,
UploadedObjectInfo,
} from './type.ts'
import { drainResponse, findCallback, readAsBuffer } from './typed-client.ts'
import type { Part } from './xml-parsers.ts'
import * as xmlParsers from './xml-parsers.ts'
const requestOptionProperties = [
'agent',
'ca',
'cert',
'ciphers',
'clientCertEngine',
'crl',
'dhparam',
'ecdhCurve',
'family',
'honorCipherOrder',
'key',
'passphrase',
'pfx',
'rejectUnauthorized',
'secureOptions',
'secureProtocol',
'servername',
'sessionIdContext',
] as const
export interface ClientOptions {
endPoint: string
accessKey: string
secretKey: string
useSSL?: boolean
port?: number
region?: Region
transport?: typeof http | typeof https
sessionToken?: string
partSize?: number
pathStyle?: boolean
credentialsProvider?: CredentialProvider
s3AccelerateEndpoint?: string
}
// will be replaced by rollup plugin
const version = process.env.MINIO_JS_PACKAGE_VERSION || 'development'
const Package = { version }
export type RequestMethod = 'HEAD' | 'GET' | 'POST' | 'DELETE' | 'PUT'
export type RequestOption = Partial<IRequest> & {
method: RequestMethod
bucketName?: string
objectName?: string
region?: string
query?: string
pathStyle?: boolean
}
export class Client {
protected transport: typeof http | typeof https
protected host: string
protected port: number
protected protocol: string
protected accessKey: string
protected secretKey: string
protected sessionToken?: string
protected userAgent: string
protected anonymous: boolean
protected pathStyle: boolean
protected regionMap: Record<string, string>
public region?: string
protected credentialsProvider?: CredentialProvider
protected partSize: number = 64 * 1024 * 1024
protected overRidePartSize?: boolean
protected maximumPartSize = 5 * 1024 * 1024 * 1024
protected maxObjectSize = 5 * 1024 * 1024 * 1024 * 1024
public enableSHA256: boolean
protected s3AccelerateEndpoint?: string
protected reqOptions: Record<string, unknown>
private readonly clientExtensions: extensions
private logStream?: stream.Writable
constructor(params: ClientOptions) {
// @ts-expect-error deprecated property
if (params.secure !== undefined) {
throw new Error('"secure" option deprecated, "useSSL" should be used instead')
}
// Default values if not specified.
if (params.useSSL === undefined) {
params.useSSL = true
}
if (!params.port) {
params.port = 0
}
// Validate input params.
if (!isValidEndpoint(params.endPoint)) {
throw new errors.InvalidEndpointError(`Invalid endPoint : ${params.endPoint}`)
}
if (!isValidPort(params.port)) {
throw new errors.InvalidArgumentError(`Invalid port : ${params.port}`)
}
if (!isBoolean(params.useSSL)) {
throw new errors.InvalidArgumentError(
`Invalid useSSL flag type : ${params.useSSL}, expected to be of type "boolean"`,
)
}
// Validate region only if its set.
if (params.region) {
if (!isString(params.region)) {
throw new errors.InvalidArgumentError(`Invalid region : ${params.region}`)
}
}
const host = params.endPoint.toLowerCase()
let port = params.port
let protocol: string
let transport
// Validate if configuration is not using SSL
// for constructing relevant endpoints.
if (params.useSSL) {
// Defaults to secure.
transport = https
protocol = 'https:'
port = port || 443
} else {
transport = http
protocol = 'http:'
port = port || 80
}
// if custom transport is set, use it.
if (params.transport) {
if (!isObject(params.transport)) {
throw new errors.InvalidArgumentError(
`Invalid transport type : ${params.transport}, expected to be type "object"`,
)
}
transport = params.transport
}
// User Agent should always following the below style.
// Please open an issue to discuss any new changes here.
//
// MinIO (OS; ARCH) LIB/VER APP/VER
//
const libraryComments = `(${process.platform}; ${process.arch})`
const libraryAgent = `MinIO ${libraryComments} minio-js/${Package.version}`
// User agent block ends.
this.transport = transport
this.host = host
this.port = port
this.protocol = protocol
this.accessKey = params.accessKey
this.secretKey = params.secretKey
this.sessionToken = params.sessionToken
this.userAgent = `${libraryAgent}`
// Default path style is true
if (params.pathStyle === undefined) {
this.pathStyle = true
} else {
this.pathStyle = params.pathStyle
}
if (!this.accessKey) {
this.accessKey = ''
}
if (!this.secretKey) {
this.secretKey = ''
}
this.anonymous = !this.accessKey || !this.secretKey
if (params.credentialsProvider) {
this.credentialsProvider = params.credentialsProvider
this.checkAndRefreshCreds()
}
this.regionMap = {}
if (params.region) {
this.region = params.region
}
if (params.partSize) {
this.partSize = params.partSize
this.overRidePartSize = true
}
if (this.partSize < 5 * 1024 * 1024) {
throw new errors.InvalidArgumentError(`Part size should be greater than 5MB`)
}
if (this.partSize > 5 * 1024 * 1024 * 1024) {
throw new errors.InvalidArgumentError(`Part size should be less than 5GB`)
}
// SHA256 is enabled only for authenticated http requests. If the request is authenticated
// and the connection is https we use x-amz-content-sha256=UNSIGNED-PAYLOAD
// header for signature calculation.
this.enableSHA256 = !this.anonymous && !params.useSSL
this.s3AccelerateEndpoint = params.s3AccelerateEndpoint || undefined
this.reqOptions = {}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.clientExtensions = new extensions(this)
}
/**
* This is s3 Specific and does not hold validity in any other Object storage.
*/
private getAccelerateEndPointIfSet(bucketName: string, objectName?: string) {
if (!isEmpty(this.s3AccelerateEndpoint) && !isEmpty(bucketName) && !isEmpty(objectName)) {
// http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
// Disable transfer acceleration for non-compliant bucket names.
if (bucketName.includes('.')) {
throw new Error(`Transfer Acceleration is not supported for non compliant bucket:${bucketName}`)
}
// If transfer acceleration is requested set new host.
// For more details about enabling transfer acceleration read here.
// http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
return this.s3AccelerateEndpoint
}
return false
}
/**
* @param endPoint - valid S3 acceleration end point
*/
public setS3TransferAccelerate(endPoint: string) {
this.s3AccelerateEndpoint = endPoint
}
/**
* Sets the supported request options.
*/
public setRequestOptions(options: Pick<https.RequestOptions, (typeof requestOptionProperties)[number]>) {
// TODO: add options type details
if (!isObject(options)) {
throw new TypeError('request options should be of type "object"')
}
this.reqOptions = _.pick(options, requestOptionProperties)
}
/**
* returns options object that can be used with http.request()
* Takes care of constructing virtual-host-style or path-style hostname
*/
protected getRequestOptions(opts: RequestOption): IRequest & { host: string; headers: Record<string, string> } {
const method = opts.method
const region = opts.region
const bucketName = opts.bucketName
let objectName = opts.objectName
const headers = opts.headers
const query = opts.query
let reqOptions = {
method,
headers: {} as RequestHeaders,
protocol: this.protocol,
}
// Verify if virtual host supported.
let virtualHostStyle
if (bucketName) {
virtualHostStyle = isVirtualHostStyle(this.host, this.protocol, bucketName, this.pathStyle)
}
let path = '/'
let host = this.host
let port: undefined | number
if (this.port) {
port = this.port
}
if (objectName) {
objectName = `${uriResourceEscape(objectName)}`
}
// For Amazon S3 endpoint, get endpoint based on region.
if (isAmazonEndpoint(host)) {
const accelerateEndPoint = this.getAccelerateEndPointIfSet(bucketName!, objectName)
if (accelerateEndPoint) {
host = `${accelerateEndPoint}`
} else {
host = getS3Endpoint(region!)
}
}
if (virtualHostStyle && !opts.pathStyle) {
// For all hosts which support virtual host style, `bucketName`
// is part of the hostname in the following format:
//
// var host = 'bucketName.example.com'
//
if (bucketName) {
host = `${bucketName}.${host}`
}
if (objectName) {
path = `/${objectName}`
}
} else {
// For all S3 compatible storage services we will fallback to
// path style requests, where `bucketName` is part of the URI
// path.
if (bucketName) {
path = `/${bucketName}`
}
if (objectName) {
path = `/${bucketName}/${objectName}`
}
}
if (query) {
path += `?${query}`
}
reqOptions.headers.host = host
if ((reqOptions.protocol === 'http:' && port !== 80) || (reqOptions.protocol === 'https:' && port !== 443)) {
reqOptions.headers.host = `${host}:${port}`
}
reqOptions.headers['user-agent'] = this.userAgent
if (headers) {
// have all header keys in lower case - to make signing easy
for (const [k, v] of Object.entries(headers)) {
reqOptions.headers[k.toLowerCase()] = v
}
}
// Use any request option specified in minioClient.setRequestOptions()
reqOptions = Object.assign({}, this.reqOptions, reqOptions)
return {
...reqOptions,
headers: Object.fromEntries(Object.entries(reqOptions.headers).map(([key, value]) => [key, value.toString()])),
host,
port,
path,
} satisfies https.RequestOptions
}
/**
* Set application specific information.
*
* Generates User-Agent in the following style.
*
* MinIO (OS; ARCH) LIB/VER APP/VER
*
* @param appName - Application name.
* @param appVersion - Application version.
*/
public setAppInfo(appName: string, appVersion: string) {
if (!isString(appName)) {
throw new TypeError(`Invalid appName: ${appName}`)
}
if (appName.trim() === '') {
throw new errors.InvalidArgumentError('Input appName cannot be empty.')
}
if (!isString(appVersion)) {
throw new TypeError(`Invalid appVersion: ${appVersion}`)
}
if (appVersion.trim() === '') {
throw new errors.InvalidArgumentError('Input appVersion cannot be empty.')
}
this.userAgent = `${this.userAgent} ${appName}/${appVersion}`
}
/**
* Calculate part size given the object size. Part size will be at least this.partSize
*
* @param size - total size
*
* @internal
*/
protected calculatePartSize(size: number) {
if (!isNumber(size)) {
throw new TypeError('size should be of type "number"')
}
if (size > this.maxObjectSize) {
throw new TypeError(`size should not be more than ${this.maxObjectSize}`)
}
if (this.overRidePartSize) {
return this.partSize
}
let partSize = this.partSize
for (;;) {
// while(true) {...} throws linting error.
// If partSize is big enough to accomodate the object size, then use it.
if (partSize * 10000 > size) {
return partSize
}
// Try part sizes as 64MB, 80MB, 96MB etc.
partSize += 16 * 1024 * 1024
}
}
/**
* log the request, response, error
*/
private logHTTP(reqOptions: IRequest, response: http.IncomingMessage | null, err?: unknown) {
// if no logStream available return.
if (!this.logStream) {
return
}
if (!isObject(reqOptions)) {
throw new TypeError('reqOptions should be of type "object"')
}
if (response && !isReadableStream(response)) {
throw new TypeError('response should be of type "Stream"')
}
if (err && !(err instanceof Error)) {
throw new TypeError('err should be of type "Error"')
}
const logStream = this.logStream
const logHeaders = (headers: RequestHeaders) => {
Object.entries(headers).forEach(([k, v]) => {
if (k == 'authorization') {
if (isString(v)) {
const redactor = new RegExp('Signature=([0-9a-f]+)')
v = v.replace(redactor, 'Signature=**REDACTED**')
}
}
logStream.write(`${k}: ${v}\n`)
})
logStream.write('\n')
}
logStream.write(`REQUEST: ${reqOptions.method} ${reqOptions.path}\n`)
logHeaders(reqOptions.headers)
if (response) {
this.logStream.write(`RESPONSE: ${response.statusCode}\n`)
logHeaders(response.headers as RequestHeaders)
}
if (err) {
logStream.write('ERROR BODY:\n')
const errJSON = JSON.stringify(err, null, '\t')
logStream.write(`${errJSON}\n`)
}
}
/**
* Enable tracing
*/
public traceOn(stream?: stream.Writable) {
if (!stream) {
stream = process.stdout
}
this.logStream = stream
}
/**
* Disable tracing
*/
public traceOff() {
this.logStream = undefined
}
/**
* make new request with promise response
* always return response
*/
makeRequestAsync(
options: RequestOption,
payload: Binary | Uint8Array = '',
expectedCodes: number[] = [200],
region = '',
returnResponse = true,
): Promise<IncomingMessage> {
if (!isObject(options)) {
throw new TypeError('options should be of type "object"')
}
if (!isString(payload) && !isObject(payload)) {
// Buffer is of type 'object'
throw new TypeError('payload should be of type "string" or "Buffer"')
}
expectedCodes.forEach((statusCode) => {
if (!isNumber(statusCode)) {
throw new TypeError('statusCode should be of type "number"')
}
})
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isBoolean(returnResponse)) {
throw new TypeError('returnResponse should be of type "boolean"')
}
if (!options.headers) {
options.headers = {}
}
if (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE') {
options.headers['content-length'] = payload.length.toString()
}
const sha256sum = this.enableSHA256 ? toSha256(payload) : ''
const stream = readableStream(payload)
return this.makeRequestStreamAsync(options, stream, sha256sum, expectedCodes, region, returnResponse)
}
/**
* new request with promise
* always return response
*/
protected async makeRequestAsyncOmit(
options: RequestOption,
payload: Binary | Uint8Array = '',
statusCodes: number[] = [200],
region = '',
): Promise<void> {
await this.makeRequestAsync(options, payload, statusCodes, region, false)
}
/**
* makeRequest is the primitive used by the apis for making S3 requests.
* payload can be empty string in case of no payload.
* statusCode is the expected statusCode. If response.statusCode does not match
* we parse the XML error and call the callback with the error message.
*
* A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion.
*
* @internal
*/
makeRequest(
options: RequestOption,
payload: Binary | Uint8Array,
expectedCodes: number[],
region: string,
returnResponse: boolean,
cb: (err: null | unknown, response: IncomingMessage) => void,
) {
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
if (!options.headers) {
options.headers = {}
}
if (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE') {
options.headers['content-length'] = payload.length.toString()
}
cbStyleReturn(this.makeRequestAsync(options, payload, expectedCodes, region, returnResponse), cb)
}
/**
* makeRequestStream will be used directly instead of makeRequest in case the payload
* is available as a stream. for ex. putObject
*
* @internal
*/
makeRequestStreamAsync(
options: RequestOption,
stream: stream.Readable | Buffer,
sha256sum: string,
statusCodes: number[] = [200],
region = '',
returnResponse = true,
) {
if (!isObject(options)) {
throw new TypeError('options should be of type "object"')
}
if (!(Buffer.isBuffer(stream) || isReadableStream(stream))) {
throw new errors.InvalidArgumentError('stream should be a Buffer or readable Stream')
}
if (!isString(sha256sum)) {
throw new TypeError('sha256sum should be of type "string"')
}
statusCodes.forEach((statusCode) => {
if (!isNumber(statusCode)) {
throw new TypeError('statusCode should be of type "number"')
}
})
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isBoolean(returnResponse)) {
throw new TypeError('returnResponse should be of type "boolean"')
}
// sha256sum will be empty for anonymous or https requests
if (!this.enableSHA256 && sha256sum.length !== 0) {
throw new errors.InvalidArgumentError(`sha256sum expected to be empty for anonymous or https requests`)
}
// sha256sum should be valid for non-anonymous http requests.
if (this.enableSHA256 && sha256sum.length !== 64) {
throw new errors.InvalidArgumentError(`Invalid sha256sum : ${sha256sum}`)
}
const regionPromise = region ? Promise.resolve(region) : this.getBucketRegionAsync(options.bucketName!)
const req = () => {
return regionPromise.then(
(reg) =>
new Promise<http.IncomingMessage>((resolve, reject) => {
options.region = reg
const reqOptions = this.getRequestOptions(options)
if (!this.anonymous) {
// For non-anonymous https requests sha256sum is 'UNSIGNED-PAYLOAD' for signature calculation.
if (!this.enableSHA256) {
sha256sum = 'UNSIGNED-PAYLOAD'
}
const date = new Date()
reqOptions.headers['x-amz-date'] = makeDateLong(date)
reqOptions.headers['x-amz-content-sha256'] = sha256sum
if (this.sessionToken) {
reqOptions.headers['x-amz-security-token'] = this.sessionToken
}
this.checkAndRefreshCreds()
reqOptions.headers.authorization = signV4(reqOptions, this.accessKey, this.secretKey, reg, date)
}
const req = this.transport.request(reqOptions, (response) => {
if (!response.statusCode) {
return reject(new Error("BUG: response doesn't have a statusCode"))
}
if (!statusCodes.includes(response.statusCode)) {
// For an incorrect region, S3 server always sends back 400.
// But we will do cache invalidation for all errors so that,
// in future, if AWS S3 decides to send a different status code or
// XML error code we will still work fine.
delete this.regionMap[options.bucketName!]
// @ts-expect-error looks like `getErrorTransformer` want a `http.ServerResponse`,
// but we only have a http.IncomingMessage here
const errorTransformer = transformers.getErrorTransformer(response)
pipesetup(response, errorTransformer).on('error', (e) => {
this.logHTTP(reqOptions, response, e)
reject(e)
})
return
}
this.logHTTP(reqOptions, response)
if (returnResponse) {
return resolve(response)
}
// We drain the socket so that the connection gets closed. Note that this
// is not expensive as the socket will not have any data.
response.on('data', Discard)
resolve(response)
})
req.on('error', (e) => {
this.logHTTP(reqOptions, null, e)
reject(e)
})
if (Buffer.isBuffer(stream)) {
req.end(stream)
} else {
pipesetup(stream, req)
}
}),
)
}
return req()
}
/// Bucket operations
/**
* Creates the bucket `bucketName`.
*
* @param bucketName - Name of the bucket
* @param region - region, see ts types for valid values, or use empty string.
* @param makeOpts - Options to create a bucket.
* @param callback? - if no callback. will return a promise.
*/
makeBucket(bucketName: string, region: Region, makeOpts: MakeBucketOpt, callback: NoResultCallback): void
makeBucket(bucketName: string, region: Region, callback: NoResultCallback): void
makeBucket(bucketName: string, callback: NoResultCallback): void
makeBucket(bucketName: string, region?: Region, makeOpts?: MakeBucketOpt): Promise<void>
// there is also a deprecated Backward Compatibility sign
// makeBucket(bucketName: string, makeOpts: MakeBucketOpt, callback: NoResultCallback): void
makeBucket(
bucketName: string,
regionOrCallback?: string | NoResultCallback | MakeBucketOpt, // MakeBucketOpt as second params is deprecated
makeOptsOrCallback?: MakeBucketOpt | NoResultCallback,
callback?: NoResultCallback,
): void | Promise<void> {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`)
}
let [[region = '', makeOpts = {}], cb] = findCallback<
[string, MakeBucketOpt] | [MakeBucketOpt, string],
NoResultCallback
>([regionOrCallback, makeOptsOrCallback, callback])
if (isObject(region)) {
// Backward Compatibility
// makeBucket(bucketName: string, makeOpts: MakeBucketOpt, callback: NoResultCallback): void
makeOpts = region as MakeBucketOpt
region = ''
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"')
}
if (!isObject(makeOpts)) {
throw new TypeError('makeOpts should be of type "object"')
}
let payload = ''
// Region already set in constructor, validate if
// caller requested bucket location is same.
if (region && this.region) {
if (region !== this.region) {
throw new errors.InvalidArgumentError(`Configured region ${this.region}, requested ${region}`)
}
}
// sending makeBucket request with XML containing 'us-east-1' fails. For
// default region server expects the request without body
if (region && region !== DEFAULT_REGION) {
const createBucketConfiguration = []
createBucketConfiguration.push({
_attr: {
xmlns: 'http://s3.amazonaws.com/doc/2006-03-01/',
},
})
createBucketConfiguration.push({
LocationConstraint: region,
})
const payloadObject = {
CreateBucketConfiguration: createBucketConfiguration,
}
payload = Xml(payloadObject)
}
const method = 'PUT'
const headers: RequestHeaders = {}
if (makeOpts.ObjectLocking) {
headers['x-amz-bucket-object-lock-enabled'] = true
}
if (!region) {
region = DEFAULT_REGION
}
const finalRegion = region // type narrow
const requestOpt: RequestOption = { method, bucketName, headers }
return asCallbackFn(cb, async () => {
try {
await this.makeRequestAsyncOmit(requestOpt, payload, [200], finalRegion)
} catch (err: unknown) {
if (region === '' || region === DEFAULT_REGION) {
if (err instanceof S3Error) {
const errCode = err.code
const errRegion = err.region
if (errCode === 'AuthorizationHeaderMalformed' && errRegion !== '') {
// Retry with region returned as part of error
await this.makeRequestAsyncOmit(requestOpt, payload, [200], errCode)
}
}
}
throw err
}
})
}
/**
* List of buckets created.
*/
listBuckets(): Promise<BucketItemFromList[]>
listBuckets(callback: ResultCallback<BucketItemFromList[]>): void
listBuckets(cb?: ResultCallback<BucketItemFromList[]>): void | Promise<BucketItemFromList[]> {
const method = 'GET'
return asCallbackFn(cb, async () => {
const response = await this.makeRequestAsync({ method }, '', [200], DEFAULT_REGION)
const body = await readAsBuffer(response)
return xmlParsers.parseListBucket(body.toString())
})
}
listIncompleteUploads(bucket: string, prefix: string, recursive: boolean): stream.Readable {
if (prefix === undefined) {
prefix = ''
}
if (recursive === undefined) {
recursive = false
}
if (!isValidBucketName(bucket)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucket)
}
if (!isValidPrefix(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`)
}
if (!isBoolean(recursive)) {
throw new TypeError('recursive should be of type "boolean"')
}
const delimiter = recursive ? '' : '/'
let keyMarker = ''
let uploadIdMarker = ''
const uploads: unknown[] = []
let ended = false
const readStream = new stream.Readable({ objectMode: true })
readStream._read = () => {
// push one upload info per _read()
if (uploads.length) {
return readStream.push(uploads.shift())
}
if (ended) {
return readStream.push(null)
}
this.listIncompleteUploadsQuery(bucket, prefix, keyMarker, uploadIdMarker, delimiter)
.on('error', (e) => readStream.emit('error', e))
.on('data', (result) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
result.prefixes.forEach((prefix) => uploads.push(prefix))
async.eachSeries(
result.uploads,
(upload, cb) => {
// for each incomplete upload add the sizes of its uploaded parts
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.listParts(bucket, upload.key, upload.uploadId).then(
(parts: any) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
upload.size = parts.reduce((acc, item) => acc + item.size, 0)
uploads.push(upload)
cb()
},
(err: any) => cb(err),
)
},
(err) => {
if (err) {
readStream.emit('error', err)
return
}
if (result.isTruncated) {
keyMarker = result.nextKeyMarker
uploadIdMarker = result.nextUploadIdMarker
} else {
ended = true
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
readStream._read()
},
)
})
}
return readStream
}
/**
* Remove a bucket.
*
* @param bucketName - name of the bucket
*/
bucketExists(bucketName: string, callback: ResultCallback<boolean>): void
bucketExists(bucketName: string): Promise<boolean>
// * `callback(err)` _function_ : `err` is `null` if the bucket exists
bucketExists(bucketName: string, cb?: ResultCallback<boolean>): void | Promise<boolean> {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
const method = 'HEAD'
return asCallbackFn(cb, async () => {
try {
await this.makeRequestAsyncOmit({ method, bucketName }, '', [200], '')
} catch (err) {
if (err instanceof S3Error) {
if (err.code == 'NoSuchBucket' || err.code == 'NotFound') {
return false
}
}
throw err
}
return true
})
}
/**
* Remove a bucket
*
* @param bucketName - name of the bucket
* @param callback
*/
removeBucket(bucketName: string, callback: NoResultCallback): void
removeBucket(bucketName: string): Promise<void>
// * `callback(err)` _function_ : `err` is `null` if the bucket is removed successfully.
removeBucket(bucketName: string, cb?: NoResultCallback): void | Promise<void> {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName)
}
const method = 'DELETE'
return asCallbackFn(cb, async () => {
await this.makeRequestAsyncOmit({ method, bucketName }, '', [204], '')
delete this.regionMap[bucketName]
})
}
/**
* Remove the partially uploaded object.
*
* @param bucketName - name of the bucket
* @param objectName - name of the object
* @param callback - callback function is called with non `null` value in case of error
*/
removeIncompleteUpload(bucketName: string, objectName: string, callback: NoResultCallback): void
removeIncompleteUpload(bucketName: string, objectName: string): Promise<void>
removeIncompleteUpload(bucketName: string, objectName: string, cb?: NoResultCallback): void | Promise<void> {
if (!isValidBucketName(bucketName)) {
throw new errors.IsValidBucketNameError('Invalid bucket name: ' + bucketName)
}
if (!isValidObjectName(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name: ${objectName}`)
}
if (!isOptionalFunction(cb)) {
throw new TypeError('callback should be of type "function"')
}
return asCallbackFn(cb, async () => {
const uploadId = await this.findUploadId(bucketName, objectName)
if (!uploadId) {
return
}
const method = 'DELETE'
const query = `uploadId=${uploadId}`
await this.makeRequestAsync(
{
method,
bucketName,
objectName,