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)
190 return response.Body as Readable
193 // ---------------------------------------------------------------------------
202 removeObjectByFullKey,
211 createObjectReadStream
214 // ---------------------------------------------------------------------------
216 async function uploadToStorage (options: {
218 objectStorageKey: string
219 bucketInfo: BucketInfo
222 const { content, objectStorageKey, bucketInfo, isPrivate } = options
224 const input: PutObjectCommandInput = {
226 Bucket: bucketInfo.BUCKET_NAME,
227 Key: buildKey(objectStorageKey, bucketInfo),
228 ACL: getACL(isPrivate)
231 const parallelUploads3 = new Upload({
234 partSize: CONFIG.OBJECT_STORAGE.MAX_UPLOAD_PART,
236 // `leavePartsOnError` must be set to `true` to avoid silently dropping failed parts
237 // More detailed explanation:
238 // https://github.com/aws/aws-sdk-js-v3/blob/v3.164.0/lib/lib-storage/src/Upload.ts#L274
239 // https://github.com/aws/aws-sdk-js-v3/issues/2311#issuecomment-939413928
240 leavePartsOnError: true,
244 const response = (await parallelUploads3.done()) as CompleteMultipartUploadCommandOutput
245 // Check is needed even if the HTTP status code is 200 OK
246 // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html
247 if (!response.Bucket) {
248 const message = `Error uploading ${objectStorageKey} to bucket ${bucketInfo.BUCKET_NAME}`
249 logger.error(message, { response, ...lTags() })
250 throw new Error(message)
254 'Completed %s%s in bucket %s',
255 bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags()
258 return getInternalUrl(bucketInfo, objectStorageKey)
261 async function applyOnPrefix (options: {
263 bucketInfo: BucketInfo
264 commandBuilder: (obj: _Object) => Parameters<S3Client['send']>[0]
266 continuationToken?: string
268 const { prefix, bucketInfo, commandBuilder, continuationToken } = options
270 const s3Client = getClient()
272 const commandPrefix = buildKey(prefix, bucketInfo)
273 const listCommand = new ListObjectsV2Command({
274 Bucket: bucketInfo.BUCKET_NAME,
275 Prefix: commandPrefix,
276 ContinuationToken: continuationToken
279 const listedObjects = await s3Client.send(listCommand)
281 if (isArray(listedObjects.Contents) !== true) {
282 const message = `Cannot apply function on ${commandPrefix} prefix in bucket ${bucketInfo.BUCKET_NAME}: no files listed.`
284 logger.error(message, { response: listedObjects, ...lTags() })
285 throw new Error(message)
288 await map(listedObjects.Contents, object => {
289 const command = commandBuilder(object)
291 return s3Client.send(command)
292 }, { concurrency: 10 })
294 // Repeat if not all objects could be listed at once (limit of 1000?)
295 if (listedObjects.IsTruncated) {
296 await applyOnPrefix({ ...options, continuationToken: listedObjects.ContinuationToken })
300 function getACL (isPrivate: boolean) {
302 ? CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PRIVATE
303 : CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PUBLIC