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 logger.debug('Removing file %s in bucket %s', key, bucketInfo.BUCKET_NAME, lTags())
115 const command = new DeleteObjectCommand({
116 Bucket: bucketInfo.BUCKET_NAME,
120 return getClient().send(command)
123 async function removePrefix (prefix: string, bucketInfo: BucketInfo) {
124 // FIXME: use bulk delete when s3ninja will support this operation
126 logger.debug('Removing prefix %s in bucket %s', prefix, bucketInfo.BUCKET_NAME, lTags())
128 return applyOnPrefix({
131 commandBuilder: obj => {
132 logger.debug('Removing %s inside prefix %s in bucket %s', obj.Key, prefix, bucketInfo.BUCKET_NAME, lTags())
134 return new DeleteObjectCommand({
135 Bucket: bucketInfo.BUCKET_NAME,
142 // ---------------------------------------------------------------------------
144 async function makeAvailable (options: {
147 bucketInfo: BucketInfo
149 const { key, destination, bucketInfo } = options
151 await ensureDir(dirname(options.destination))
153 const command = new GetObjectCommand({
154 Bucket: bucketInfo.BUCKET_NAME,
155 Key: buildKey(key, bucketInfo)
157 const response = await getClient().send(command)
159 const file = createWriteStream(destination)
160 await pipelinePromise(response.Body as Readable, file)
165 function buildKey (key: string, bucketInfo: BucketInfo) {
166 return bucketInfo.PREFIX + key
169 // ---------------------------------------------------------------------------
171 async function createObjectReadStream (options: {
173 bucketInfo: BucketInfo
176 const { key, bucketInfo, rangeHeader } = options
178 const command = new GetObjectCommand({
179 Bucket: bucketInfo.BUCKET_NAME,
180 Key: buildKey(key, bucketInfo),
184 const response = await getClient().send(command)
186 return response.Body as Readable
189 // ---------------------------------------------------------------------------
206 createObjectReadStream
209 // ---------------------------------------------------------------------------
211 async function uploadToStorage (options: {
213 objectStorageKey: string
214 bucketInfo: BucketInfo
217 const { content, objectStorageKey, bucketInfo, isPrivate } = options
219 const input: PutObjectCommandInput = {
221 Bucket: bucketInfo.BUCKET_NAME,
222 Key: buildKey(objectStorageKey, bucketInfo),
223 ACL: getACL(isPrivate)
226 const parallelUploads3 = new Upload({
229 partSize: CONFIG.OBJECT_STORAGE.MAX_UPLOAD_PART,
231 // `leavePartsOnError` must be set to `true` to avoid silently dropping failed parts
232 // More detailed explanation:
233 // https://github.com/aws/aws-sdk-js-v3/blob/v3.164.0/lib/lib-storage/src/Upload.ts#L274
234 // https://github.com/aws/aws-sdk-js-v3/issues/2311#issuecomment-939413928
235 leavePartsOnError: true,
239 const response = (await parallelUploads3.done()) as CompleteMultipartUploadCommandOutput
240 // Check is needed even if the HTTP status code is 200 OK
241 // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html
242 if (!response.Bucket) {
243 const message = `Error uploading ${objectStorageKey} to bucket ${bucketInfo.BUCKET_NAME}`
244 logger.error(message, { response, ...lTags() })
245 throw new Error(message)
249 'Completed %s%s in bucket %s',
250 bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags()
253 return getInternalUrl(bucketInfo, objectStorageKey)
256 async function applyOnPrefix (options: {
258 bucketInfo: BucketInfo
259 commandBuilder: (obj: _Object) => Parameters<S3Client['send']>[0]
261 continuationToken?: string
263 const { prefix, bucketInfo, commandBuilder, continuationToken } = options
265 const s3Client = getClient()
267 const commandPrefix = buildKey(prefix, bucketInfo)
268 const listCommand = new ListObjectsV2Command({
269 Bucket: bucketInfo.BUCKET_NAME,
270 Prefix: commandPrefix,
271 ContinuationToken: continuationToken
274 const listedObjects = await s3Client.send(listCommand)
276 if (isArray(listedObjects.Contents) !== true) {
277 const message = `Cannot apply function on ${commandPrefix} prefix in bucket ${bucketInfo.BUCKET_NAME}: no files listed.`
279 logger.error(message, { response: listedObjects, ...lTags() })
280 throw new Error(message)
283 await map(listedObjects.Contents, object => {
284 const command = commandBuilder(object)
286 return s3Client.send(command)
287 }, { concurrency: 10 })
289 // Repeat if not all objects could be listed at once (limit of 1000?)
290 if (listedObjects.IsTruncated) {
291 await applyOnPrefix({ ...options, continuationToken: listedObjects.ContinuationToken })
295 function getACL (isPrivate: boolean) {
297 ? CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PRIVATE
298 : CONFIG.OBJECT_STORAGE.UPLOAD_ACL.PUBLIC