1 import { map } from 'bluebird'
2 import { createReadStream, createWriteStream, ensureDir, ReadStream } from 'fs-extra'
3 import { dirname } from 'path'
4 import { Readable } from 'stream'
7 CompleteMultipartUploadCommandOutput,
12 PutObjectCommandInput,
14 } from '@aws-sdk/client-s3'
15 import { Upload } from '@aws-sdk/lib-storage'
16 import { pipelinePromise } from '@server/helpers/core-utils'
17 import { isArray } from '@server/helpers/custom-validators/misc'
18 import { logger } from '@server/helpers/logger'
19 import { CONFIG } from '@server/initializers/config'
20 import { getInternalUrl } from '../urls'
21 import { getClient } from './client'
22 import { lTags } from './logger'
29 async function listKeysOfPrefix (prefix: string, bucketInfo: BucketInfo) {
30 const s3Client = getClient()
32 const commandPrefix = bucketInfo.PREFIX + prefix
33 const listCommand = new ListObjectsV2Command({
34 Bucket: bucketInfo.BUCKET_NAME,
38 const listedObjects = await s3Client.send(listCommand)
40 if (isArray(listedObjects.Contents) !== true) return []
42 return listedObjects.Contents.map(c => c.Key)
45 // ---------------------------------------------------------------------------
47 async function storeObject (options: {
49 objectStorageKey: string
50 bucketInfo: BucketInfo
53 const { inputPath, objectStorageKey, bucketInfo, isPrivate } = options
55 logger.debug('Uploading file %s to %s%s in bucket %s', inputPath, bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags())
57 const fileStream = createReadStream(inputPath)
59 return uploadToStorage({ objectStorageKey, content: fileStream, bucketInfo, isPrivate })
62 // ---------------------------------------------------------------------------
64 function updateObjectACL (options: {
65 objectStorageKey: string
66 bucketInfo: BucketInfo
69 const { objectStorageKey, bucketInfo, isPrivate } = options
71 const key = buildKey(objectStorageKey, bucketInfo)
73 logger.debug('Updating ACL file %s in bucket %s', key, bucketInfo.BUCKET_NAME, lTags())
75 const command = new PutObjectAclCommand({
76 Bucket: bucketInfo.BUCKET_NAME,
78 ACL: getACL(isPrivate)
81 return getClient().send(command)
84 function updatePrefixACL (options: {
86 bucketInfo: BucketInfo
89 const { prefix, bucketInfo, isPrivate } = options
91 logger.debug('Updating ACL of files in prefix %s in bucket %s', prefix, bucketInfo.BUCKET_NAME, lTags())
93 return applyOnPrefix({
96 commandBuilder: obj => {
97 logger.debug('Updating ACL of %s inside prefix %s in bucket %s', obj.Key, prefix, bucketInfo.BUCKET_NAME, lTags())
99 return new PutObjectAclCommand({
100 Bucket: bucketInfo.BUCKET_NAME,
102 ACL: getACL(isPrivate)
108 // ---------------------------------------------------------------------------
110 function removeObject (objectStorageKey: string, bucketInfo: BucketInfo) {
111 const key = buildKey(objectStorageKey, bucketInfo)
113 return removeObjectByFullKey(key, bucketInfo)
116 function removeObjectByFullKey (fullKey: string, bucketInfo: BucketInfo) {
117 logger.debug('Removing file %s in bucket %s', fullKey, bucketInfo.BUCKET_NAME, lTags())
119 const command = new DeleteObjectCommand({
120 Bucket: bucketInfo.BUCKET_NAME,
124 return getClient().send(command)
127 async function removePrefix (prefix: string, bucketInfo: BucketInfo) {
128 // FIXME: use bulk delete when s3ninja will support this operation
130 logger.debug('Removing prefix %s in bucket %s', prefix, bucketInfo.BUCKET_NAME, lTags())
132 return applyOnPrefix({
135 commandBuilder: obj => {
136 logger.debug('Removing %s inside prefix %s in bucket %s', obj.Key, prefix, bucketInfo.BUCKET_NAME, lTags())
138 return new DeleteObjectCommand({
139 Bucket: bucketInfo.BUCKET_NAME,
146 // ---------------------------------------------------------------------------
148 async function makeAvailable (options: {
151 bucketInfo: BucketInfo
153 const { key, destination, bucketInfo } = options
155 await ensureDir(dirname(options.destination))
157 const command = new GetObjectCommand({
158 Bucket: bucketInfo.BUCKET_NAME,
159 Key: buildKey(key, bucketInfo)
161 const response = await getClient().send(command)
163 const file = createWriteStream(destination)
164 await pipelinePromise(response.Body as Readable, file)
169 function buildKey (key: string, bucketInfo: BucketInfo) {
170 return bucketInfo.PREFIX + key
173 // ---------------------------------------------------------------------------
175 async function createObjectReadStream (options: {
177 bucketInfo: BucketInfo
180 const { key, bucketInfo, rangeHeader } = options
182 const command = new GetObjectCommand({
183 Bucket: bucketInfo.BUCKET_NAME,
184 Key: buildKey(key, bucketInfo),
188 const response = await getClient().send(command)
192 stream: response.Body as Readable
196 // ---------------------------------------------------------------------------
205 removeObjectByFullKey,
214 createObjectReadStream
217 // ---------------------------------------------------------------------------
219 async function uploadToStorage (options: {
221 objectStorageKey: string
222 bucketInfo: BucketInfo
225 const { content, objectStorageKey, bucketInfo, isPrivate } = options
227 const input: PutObjectCommandInput = {
229 Bucket: bucketInfo.BUCKET_NAME,
230 Key: buildKey(objectStorageKey, bucketInfo),
231 ACL: getACL(isPrivate)
234 const parallelUploads3 = new Upload({
237 partSize: CONFIG.OBJECT_STORAGE.MAX_UPLOAD_PART,
239 // `leavePartsOnError` must be set to `true` to avoid silently dropping failed parts
240 // More detailed explanation:
241 // https://github.com/aws/aws-sdk-js-v3/blob/v3.164.0/lib/lib-storage/src/Upload.ts#L274
242 // https://github.com/aws/aws-sdk-js-v3/issues/2311#issuecomment-939413928
243 leavePartsOnError: true,
247 const response = (await parallelUploads3.done()) as CompleteMultipartUploadCommandOutput
248 // Check is needed even if the HTTP status code is 200 OK
249 // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html
250 if (!response.Bucket) {
251 const message = `Error uploading ${objectStorageKey} to bucket ${bucketInfo.BUCKET_NAME}`
252 logger.error(message, { response, ...lTags() })
253 throw new Error(message)
257 'Completed %s%s in bucket %s',
258 bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags()
261 return getInternalUrl(bucketInfo, objectStorageKey)
264 async function applyOnPrefix (options: {
266 bucketInfo: BucketInfo
267 commandBuilder: (obj: _Object) => Parameters<S3Client['send']>[0]
269 continuationToken?: string
271 const { prefix, bucketInfo, commandBuilder, continuationToken } = options
273 const s3Client = getClient()
275 const commandPrefix = buildKey(prefix, bucketInfo)
276 const listCommand = new ListObjectsV2Command({
277 Bucket: bucketInfo.BUCKET_NAME,
278 Prefix: commandPrefix,
279 ContinuationToken: continuationToken
282 const listedObjects = await s3Client.send(listCommand)
284 if (isArray(listedObjects.Contents) !== true) {
285 const message = `Cannot apply function on ${commandPrefix} prefix in bucket ${bucketInfo.BUCKET_NAME}: no files listed.`
287 logger.error(message, { response: listedObjects, ...lTags() })
288 throw new Error(message)
291 await map(listedObjects.Contents, object => {
292 const command = commandBuilder(object)
294 return s3Client.send(command)
295 }, { concurrency: 10 })
297 // Repeat if not all objects could be listed at once (limit of 1000?)
298 if (listedObjects.IsTruncated) {
299 await applyOnPrefix({ ...options, continuationToken: listedObjects.ContinuationToken })
303 function getACL (isPrivate: boolean) {
305 ? CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PRIVATE
306 : CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PUBLIC