-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdriver.ts
More file actions
723 lines (642 loc) · 20.3 KB
/
Copy pathdriver.ts
File metadata and controls
723 lines (642 loc) · 20.3 KB
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
/*
* flydrive
*
* (c) FlyDrive
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import mimeTypes from 'mime-types'
import { type Readable } from 'node:stream'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import {
S3Client,
PutObjectCommand,
type HeadObjectOutput,
GetObjectCommand,
HeadObjectCommand,
CopyObjectCommand,
PutObjectAclCommand,
DeleteObjectCommand,
GetObjectAclCommand,
ListObjectsV2Command,
DeleteObjectsCommand,
type PutObjectCommandInput,
type GetObjectCommandInput,
type CopyObjectCommandInput,
type HeadObjectCommandInput,
type GetObjectAclCommandInput,
type PutObjectAclCommandInput,
type DeleteObjectCommandInput,
type ListObjectsV2CommandInput,
type DeleteObjectsCommandInput,
} from '@aws-sdk/client-s3'
import debug from './debug.js'
import { type S3DriverOptions } from './types.js'
import { DriveFile } from '../../src/driver_file.js'
import { DriveDirectory } from '../../src/drive_directory.js'
import type {
WriteOptions,
DriverContract,
ObjectMetaData,
ObjectVisibility,
SignedURLOptions,
UploadSignedURLOptions,
} from '../../src/types.js'
import string from '@poppinss/utils/string'
/**
* Implementation of FlyDrive driver that reads and persists files
* to S3 complaint storage services like Digital ocean spaces,
* R2 and so on.
*/
export class S3Driver implements DriverContract {
#client: S3Client
#supportsACL: boolean = true
/**
* The URI that holds permission for public
*/
publicGrantUri = 'http://acs.amazonaws.com/groups/global/AllUsers'
constructor(public options: S3DriverOptions) {
this.#client = 'client' in options ? options.client : new S3Client(options)
if (options.supportsACL !== undefined) {
this.#supportsACL = options.supportsACL
}
if (debug.enabled) {
debug('driver config %O', {
...options,
credentials: 'REDACTED',
})
}
}
/**
* Creates the metadata for the file from the raw response
* returned by S3
*/
#createFileMetaData(apiFile: HeadObjectOutput) {
const metaData: ObjectMetaData = {
contentType: apiFile.ContentType,
contentLength: apiFile.ContentLength!,
etag: apiFile.ETag!,
lastModified: new Date(apiFile.LastModified!),
}
debug('file metadata %O', this.options.bucket, metaData)
return metaData
}
/**
* Returns S3 options for the save operations.
*/
#getSaveOptions(key: string, options?: WriteOptions): Omit<PutObjectCommandInput, 'Key'> {
/**
* Destructuring properties needed for local checks. The rest
* object will be forwarded to s3 as it is.
*/
const {
visibility, // used locally
contentType, // forwaded as metadata
cacheControl, // forwaded as metadata
contentEncoding, // forwaded as metadata
contentLength, // forwaded as metadata
contentLanguage, // forwaded as metadata
contentDisposition, // forwaded as metadata
...rest // forwarded as it is
} = options || {}
/**
* Creating S3 options with all the known and unknown properties
*/
const s3Options: Omit<PutObjectCommandInput, 'Key'> = {
Bucket: this.options.bucket,
ServerSideEncryption: this.options.encryption,
...rest,
}
/**
* Set ACL when service supports it
*/
if (this.#supportsACL) {
const isPublic = (visibility || this.options.visibility) === 'public'
s3Options.ACL = isPublic ? 'public-read' : 'private'
}
if (contentType) {
s3Options.ContentType = contentType
} else {
const detectedContentType = mimeTypes.lookup(key)
if (detectedContentType) {
debug('setting "%s" file\'s content-type to "%s"', key, detectedContentType)
s3Options.ContentType = detectedContentType
}
}
if (cacheControl) {
s3Options.CacheControl = cacheControl
}
if (contentEncoding) {
s3Options.ContentEncoding = contentEncoding
}
if (contentLength) {
s3Options.ContentLength = contentLength
}
if (contentLanguage) {
s3Options.ContentLanguage = contentLanguage
}
if (contentDisposition) {
s3Options.ContentDisposition = contentDisposition
}
debug('s3 write options %O', s3Options)
return s3Options
}
/**
* Deletes files recursively with a batch of 1000 files at a time
*/
async #deleteFilesRecursively(prefix: string, paginationToken?: string) {
/**
* Get a list of 1000 files
*/
const response = await this.#client.send(
this.createListObjectsV2Command(this.#client, {
Bucket: this.options.bucket,
ContinuationToken: paginationToken,
...(prefix !== '/' ? { Prefix: prefix } : {}),
})
)
/**
* Return early if no files exists
*/
if (!response.Contents || !response.Contents.length) {
return
}
/**
* Delete all files
*/
await this.#client.send(
this.createDeleteObjectsCommand(this.#client, {
Bucket: this.options.bucket,
Delete: {
Objects: Array.from(response.Contents).map((file) => {
return {
Key: file.Key,
}
}),
Quiet: true,
},
})
)
if (response.NextContinuationToken) {
debug('deleting next batch of files with token %s', response.NextContinuationToken)
await this.#deleteFilesRecursively(prefix, response.NextContinuationToken)
}
}
/**
* Creates S3 "PutObjectCommand". Feel free to override this method to
* manually create the command
*/
protected createPutObjectCommand(_: S3Client, options: PutObjectCommandInput) {
return new PutObjectCommand(options)
}
/**
* Creates S3 "GetObjectCommand". Feel free to override this method to
* manually create the command
*/
protected createGetObjectCommand(_: S3Client, options: GetObjectCommandInput) {
return new GetObjectCommand(options)
}
/**
* Creates S3 "HeadObjectCommand". Feel free to override this method to
* manually create the command
*/
protected createHeadObjectCommand(_: S3Client, options: HeadObjectCommandInput) {
return new HeadObjectCommand(options)
}
/**
* Creates S3 "GetObjectAclCommand". Feel free to override this method to
* manually create the command
*/
protected createGetObjectAclCommand(_: S3Client, options: GetObjectAclCommandInput) {
return new GetObjectAclCommand(options)
}
/**
* Creates S3 "PutObjectAclCommand". Feel free to override this method to
* manually create the command
*/
protected createPutObjectAclCommand(_: S3Client, options: PutObjectAclCommandInput) {
return new PutObjectAclCommand(options)
}
/**
* Creates S3 "DeleteObjectCommand". Feel free to override this method to
* manually create the command
*/
protected createDeleteObjectCommand(_: S3Client, options: DeleteObjectCommandInput) {
return new DeleteObjectCommand(options)
}
/**
* Creates S3 "CopyObjectCommand". Feel free to override this method to
* manually create the command
*/
protected createCopyObjectCommand(_: S3Client, options: CopyObjectCommandInput) {
return new CopyObjectCommand(options)
}
/**
* Creates S3 "ListObjectsV2Command". Feel free to override this method to
* manually create the command
*/
protected createListObjectsV2Command(_: S3Client, options: ListObjectsV2CommandInput) {
return new ListObjectsV2Command(options)
}
/**
* Creates S3 "DeleteObjectsCommand". Feel free to override this method to
* manually create the command
*/
protected createDeleteObjectsCommand(_: S3Client, options: DeleteObjectsCommandInput) {
return new DeleteObjectsCommand(options)
}
/**
* Returns a boolean indicating if the file exists
* or not.
*/
async exists(key: string): Promise<boolean> {
debug('checking if file exists %s:%s', this.options.bucket, key)
try {
const response = await this.#client.send(
this.createHeadObjectCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
})
)
return response.$metadata.httpStatusCode === 200
} catch (error) {
if (error.$metadata?.httpStatusCode === 404) {
return false
}
throw error
}
}
/**
* Returns the contents of a file as a UTF-8 string. An
* exception is thrown when object is missing.
*/
async get(key: string): Promise<string> {
debug('reading file contents %s:%s', this.options.bucket, key)
const response = await this.#client.send(
this.createGetObjectCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
})
)
return response.Body!.transformToString()
}
/**
* Returns the contents of the file as a Readable stream. An
* exception is thrown when the file is missing.
*/
async getStream(key: string): Promise<Readable> {
debug('reading file contents as a stream %s:%s', this.options.bucket, key)
const response = await this.#client.send(
this.createGetObjectCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
})
)
return response.Body! as Readable
}
/**
* Returns the contents of the file as an Uint8Array. An
* exception is thrown when the file is missing.
*/
async getBytes(key: string): Promise<Uint8Array> {
debug('reading file contents as array buffer %s:%s', this.options.bucket, key)
const response = await this.#client.send(
this.createGetObjectCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
})
)
return response.Body!.transformToByteArray()
}
/**
* Returns the file metadata.
*/
async getMetaData(key: string): Promise<ObjectMetaData> {
debug('fetching file metadata %s:%s', this.options.bucket, key)
const response = await this.#client.send(
this.createHeadObjectCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
})
)
return this.#createFileMetaData(response)
}
/**
* Returns the visibility of a file
*/
async getVisibility(key: string): Promise<ObjectVisibility> {
if (!this.#supportsACL) {
return this.options.visibility
}
debug('fetching file visibility %s:%s', this.options.bucket, key)
const response = await this.#client.send(
this.createGetObjectAclCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
})
)
const isPublic = (response.Grants || []).find((grant) => {
return (
grant.Grantee?.URI === this.publicGrantUri &&
(grant.Permission === 'READ' || grant.Permission === 'FULL_CONTROL')
)
})
return isPublic ? 'public' : 'private'
}
/**
* Returns the public URL of the file. This method does not check
* if the file exists or not.
*/
async getUrl(key: string): Promise<string> {
/**
* Use custom implementation when exists.
*/
const generateURL = this.options.urlBuilder?.generateURL
if (generateURL) {
debug('using custom implementation for generating public URL %s:%s', this.options.bucket, key)
return generateURL(key, this.options.bucket, this.#client)
}
debug('generating file URL %s:%s', this.options.bucket, key)
/**
* Make sure using CDN URL property
*/
if (this.options.cdnUrl) {
return new URL(key, this.options.cdnUrl).toString()
}
/**
* Use endpoint from the config (when available)
*/
if (this.#client.config.endpoint) {
const endpoint = await this.#client.config.endpoint()
let baseUrl = `${endpoint.protocol}//${endpoint.hostname}`
if (endpoint.port) {
baseUrl += `:${endpoint.port}`
}
return new URL(`/${this.options.bucket}/${key}`, baseUrl).toString()
}
/**
* Otherwise fallback to AWS based URL
*/
return new URL(`/${key}`, `https://${this.options.bucket}.s3.amazonaws.com`).toString()
}
/**
* Returns the signed/temporary URL of the file. By default, the signed URLs
* expire in 30mins, but a custom expiry can be defined using
* "options.expiresIn" property.
*/
async getSignedUrl(key: string, options?: SignedURLOptions): Promise<string> {
const { contentDisposition, contentType, expiresIn, ...rest } = Object.assign({}, options)
/**
* Options passed to GCS when generating the signed URL.
*/
const expires = string.seconds.parse(expiresIn || '30mins')
/**
* Options given to the GetObjectCommand when create a signed
* URL
*/
const signedURLOptions: GetObjectCommandInput = {
Key: key,
Bucket: this.options.bucket,
ResponseContentType: contentType,
ResponseContentDisposition: contentDisposition,
...rest,
}
/**
* Use custom implementation when exists.
*/
const generateSignedURL = this.options.urlBuilder?.generateSignedURL
if (generateSignedURL) {
debug('using custom implementation for generating signed URL %s:%s', this.options.bucket, key)
return generateSignedURL(key, signedURLOptions, this.#client, expiresIn)
}
debug('generating signed URL %s:%s', this.options.bucket, key)
return getSignedUrl(this.#client, this.createGetObjectCommand(this.#client, signedURLOptions), {
expiresIn: expires,
})
}
/**
* Returns a signed URL for uploading objects directly to S3.
*/
async getSignedUploadUrl(key: string, options?: UploadSignedURLOptions): Promise<string> {
const { contentType, expiresIn, ...rest } = Object.assign({}, options)
/**
* Options passed to GCS when generating the signed URL.
*/
const expires = string.seconds.parse(expiresIn || '30mins')
/**
* Options given to the PutObjectCommand when create a signed
* URL
*/
const signedURLOptions: PutObjectCommandInput = {
Key: key,
Bucket: this.options.bucket,
ContentType: contentType,
...rest,
}
/**
* Use custom implementation when exists.
*/
const generateSignedUploadURL = this.options.urlBuilder?.generateSignedUploadURL
if (generateSignedUploadURL) {
debug(
'using custom implementation for generating signed upload URL %s:%s',
this.options.bucket,
key
)
return generateSignedUploadURL(key, signedURLOptions, this.#client, expiresIn)
}
debug('generating signed upload URL %s:%s', this.options.bucket, key)
return getSignedUrl(this.#client, this.createPutObjectCommand(this.#client, signedURLOptions), {
expiresIn: expires,
})
}
/**
* Updates the visibility of a file
*/
async setVisibility(key: string, visibility: ObjectVisibility): Promise<void> {
if (!this.#supportsACL) {
return
}
debug('updating file visibility %s:%s to %s', this.options.bucket, key, visibility)
await this.#client.send(
this.createPutObjectAclCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
ACL: visibility === 'public' ? 'public-read' : 'private',
})
)
}
/**
* Writes a file to the bucket for the given key and contents.
*/
async put(
key: string,
contents: string | Uint8Array,
options?: WriteOptions | undefined
): Promise<void> {
debug('creating/updating file %s:%s', this.options.bucket, key)
const command = this.createPutObjectCommand(this.#client, {
...this.#getSaveOptions(key, options),
Key: key,
Body: contents,
})
await this.#client.send(command)
}
/**
* Writes a file to the bucket for the given key and stream
*/
putStream(key: string, contents: Readable, options?: WriteOptions | undefined): Promise<void> {
debug('creating/updating file %s:%s', this.options.bucket, key)
return new Promise((resolve, reject) => {
/**
* GCS internally creates a pipeline of stream and invokes the "_destroy" method
* at several occassions. Because of that, the "_destroy" method emits an event
* which cannot handled within this block of code.
*
* So the only way I have been able to make GCS streams work is by ditching the
* pipeline method and relying on the "pipe" method instead.
*/
contents.once('error', reject)
try {
const command = this.createPutObjectCommand(this.#client, {
...this.#getSaveOptions(key, options),
Key: key,
Body: contents,
})
return this.#client
.send(command)
.then(() => resolve())
.catch(reject)
} catch (error) {
reject(error)
}
})
}
/**
* Copies the source file to the destination. Both paths must
* be within the root location.
*/
async copy(source: string, destination: string, options?: WriteOptions): Promise<void> {
debug(
'copying file from %s:%s to %s:%s',
this.options.bucket,
source,
this.options.bucket,
destination
)
options = options || {}
/**
* Copy visibility from the source file to the
* destination when no inline visibility is
* defined
*/
if (!options.visibility && this.#supportsACL) {
options.visibility = await this.getVisibility(source)
}
await this.#client.send(
this.createCopyObjectCommand(this.#client, {
...this.#getSaveOptions(destination, options),
Key: destination,
CopySource: `/${this.options.bucket}/${source}`,
Bucket: this.options.bucket,
})
)
}
/**
* Moves the source file to the destination. Both paths must
* be within the root location.
*/
async move(source: string, destination: string, options?: WriteOptions): Promise<void> {
debug(
'moving file from %s:%s to %s:%s',
this.options.bucket,
source,
this.options.bucket,
destination
)
await this.copy(source, destination, options)
await this.delete(source)
}
/**
* Deletes the object from the bucket
*/
async delete(key: string) {
debug('removing file %s:%s', this.options.bucket, key)
await this.#client.send(
this.createDeleteObjectCommand(this.#client, {
Key: key,
Bucket: this.options.bucket,
})
)
}
/**
* Deletes the files and directories matching the provided
* prefix.
*/
async deleteAll(prefix: string): Promise<void> {
debug('removing all files matching prefix %s:%s', this.options.bucket, prefix)
await this.#deleteFilesRecursively(prefix)
}
/**
* Returns a list of files. The pagination token can be used to paginate
* through the files.
*/
async listAll(
prefix: string,
options?: {
recursive?: boolean
paginationToken?: string
maxResults?: number
}
): Promise<{
paginationToken?: string
objects: Iterable<DriveFile | DriveDirectory>
}> {
const self = this
let { recursive, paginationToken, maxResults } = Object.assign({ recursive: false }, options)
if (prefix) {
prefix = !recursive ? `${prefix.replace(/\/$/, '')}/` : prefix
}
debug('listing all files matching prefix %s:%s', this.options.bucket, prefix)
const response = await this.#client.send(
this.createListObjectsV2Command(this.#client, {
Bucket: this.options.bucket,
Delimiter: !recursive ? '/' : '',
ContinuationToken: paginationToken,
...(prefix !== '/' ? { Prefix: prefix } : {}),
...(maxResults !== undefined ? { MaxKeys: maxResults } : {}),
})
)
/**
* The generator is used to lazily iterate over files and
* convert them into DriveFile or DriveDirectory instances
*/
function* filesGenerator(): Iterator<
DriveFile | { isFile: false; isDirectory: true; prefix: string; name: string }
> {
if (response.CommonPrefixes) {
for (const directory of response.CommonPrefixes) {
yield new DriveDirectory(directory.Prefix!.replace(/\/$/, ''))
}
}
if (response.Contents) {
for (const file of response.Contents) {
yield new DriveFile(file.Key!, self, self.#createFileMetaData(file))
}
}
}
return {
paginationToken: response.NextContinuationToken,
objects: {
[Symbol.iterator]: filesGenerator,
},
}
}
/**
* Switch bucket at runtime if supported.
*/
bucket(bucket: string): S3Driver {
return new S3Driver({ ...this.options, bucket })
}
}