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 async function updateObjectACL (options: {
65 objectStorageKey: string
66 bucketInfo: BucketInfo
69 const { objectStorageKey, bucketInfo, isPrivate } = options
71 const acl = getACL(isPrivate)
74 const key = buildKey(objectStorageKey, bucketInfo)
76 logger.debug('Updating ACL file %s in bucket %s', key, bucketInfo.BUCKET_NAME, lTags())
78 const command = new PutObjectAclCommand({
79 Bucket: bucketInfo.BUCKET_NAME,
84 await getClient().send(command)
87 function updatePrefixACL (options: {
89 bucketInfo: BucketInfo
92 const { prefix, bucketInfo, isPrivate } = options
94 const acl = getACL(isPrivate)
97 logger.debug('Updating ACL of files in prefix %s in bucket %s', prefix, bucketInfo.BUCKET_NAME, lTags())
99 return applyOnPrefix({
102 commandBuilder: obj => {
103 logger.debug('Updating ACL of %s inside prefix %s in bucket %s', obj.Key, prefix, bucketInfo.BUCKET_NAME, lTags())
105 return new PutObjectAclCommand({
106 Bucket: bucketInfo.BUCKET_NAME,
114 // ---------------------------------------------------------------------------
116 function removeObject (objectStorageKey: string, bucketInfo: BucketInfo) {
117 const key = buildKey(objectStorageKey, bucketInfo)
119 return removeObjectByFullKey(key, bucketInfo)
122 function removeObjectByFullKey (fullKey: string, bucketInfo: BucketInfo) {
123 logger.debug('Removing file %s in bucket %s', fullKey, bucketInfo.BUCKET_NAME, lTags())
125 const command = new DeleteObjectCommand({
126 Bucket: bucketInfo.BUCKET_NAME,
130 return getClient().send(command)
133 async function removePrefix (prefix: string, bucketInfo: BucketInfo) {
134 // FIXME: use bulk delete when s3ninja will support this operation
136 logger.debug('Removing prefix %s in bucket %s', prefix, bucketInfo.BUCKET_NAME, lTags())
138 return applyOnPrefix({
141 commandBuilder: obj => {
142 logger.debug('Removing %s inside prefix %s in bucket %s', obj.Key, prefix, bucketInfo.BUCKET_NAME, lTags())
144 return new DeleteObjectCommand({
145 Bucket: bucketInfo.BUCKET_NAME,
152 // ---------------------------------------------------------------------------
154 async function makeAvailable (options: {
157 bucketInfo: BucketInfo
159 const { key, destination, bucketInfo } = options
161 await ensureDir(dirname(options.destination))
163 const command = new GetObjectCommand({
164 Bucket: bucketInfo.BUCKET_NAME,
165 Key: buildKey(key, bucketInfo)
167 const response = await getClient().send(command)
169 const file = createWriteStream(destination)
170 await pipelinePromise(response.Body as Readable, file)
175 function buildKey (key: string, bucketInfo: BucketInfo) {
176 return bucketInfo.PREFIX + key
179 // ---------------------------------------------------------------------------
181 async function createObjectReadStream (options: {
183 bucketInfo: BucketInfo
186 const { key, bucketInfo, rangeHeader } = options
188 const command = new GetObjectCommand({
189 Bucket: bucketInfo.BUCKET_NAME,
190 Key: buildKey(key, bucketInfo),
194 const response = await getClient().send(command)
198 stream: response.Body as Readable
202 // ---------------------------------------------------------------------------
211 removeObjectByFullKey,
220 createObjectReadStream
223 // ---------------------------------------------------------------------------
225 async function uploadToStorage (options: {
227 objectStorageKey: string
228 bucketInfo: BucketInfo
231 const { content, objectStorageKey, bucketInfo, isPrivate } = options
233 const input: PutObjectCommandInput = {
235 Bucket: bucketInfo.BUCKET_NAME,
236 Key: buildKey(objectStorageKey, bucketInfo)
239 const acl = getACL(isPrivate)
240 if (acl) input.ACL = acl
242 const parallelUploads3 = new Upload({
245 partSize: CONFIG.OBJECT_STORAGE.MAX_UPLOAD_PART,
247 // `leavePartsOnError` must be set to `true` to avoid silently dropping failed parts
248 // More detailed explanation:
249 // https://github.com/aws/aws-sdk-js-v3/blob/v3.164.0/lib/lib-storage/src/Upload.ts#L274
250 // https://github.com/aws/aws-sdk-js-v3/issues/2311#issuecomment-939413928
251 leavePartsOnError: true,
255 const response = (await parallelUploads3.done()) as CompleteMultipartUploadCommandOutput
256 // Check is needed even if the HTTP status code is 200 OK
257 // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html
258 if (!response.Bucket) {
259 const message = `Error uploading ${objectStorageKey} to bucket ${bucketInfo.BUCKET_NAME}`
260 logger.error(message, { response, ...lTags() })
261 throw new Error(message)
265 'Completed %s%s in bucket %s',
266 bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags()
269 return getInternalUrl(bucketInfo, objectStorageKey)
272 async function applyOnPrefix (options: {
274 bucketInfo: BucketInfo
275 commandBuilder: (obj: _Object) => Parameters<S3Client['send']>[0]
277 continuationToken?: string
279 const { prefix, bucketInfo, commandBuilder, continuationToken } = options
281 const s3Client = getClient()
283 const commandPrefix = buildKey(prefix, bucketInfo)
284 const listCommand = new ListObjectsV2Command({
285 Bucket: bucketInfo.BUCKET_NAME,
286 Prefix: commandPrefix,
287 ContinuationToken: continuationToken
290 const listedObjects = await s3Client.send(listCommand)
292 if (isArray(listedObjects.Contents) !== true) {
293 const message = `Cannot apply function on ${commandPrefix} prefix in bucket ${bucketInfo.BUCKET_NAME}: no files listed.`
295 logger.error(message, { response: listedObjects, ...lTags() })
296 throw new Error(message)
299 await map(listedObjects.Contents, object => {
300 const command = commandBuilder(object)
302 return s3Client.send(command)
303 }, { concurrency: 10 })
305 // Repeat if not all objects could be listed at once (limit of 1000?)
306 if (listedObjects.IsTruncated) {
307 await applyOnPrefix({ ...options, continuationToken: listedObjects.ContinuationToken })
311 function getACL (isPrivate: boolean) {
313 ? CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PRIVATE
314 : CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PUBLIC