aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/object-storage/shared/client.ts
blob: 85682c4926e397c877764e52e29b79c98dadf9b0 (plain) (blame)
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
import { S3Client } from '@aws-sdk/client-s3'
import { logger } from '@server/helpers/logger'
import { CONFIG } from '@server/initializers/config'
import { lTags } from './logger'

let endpointParsed: URL
function getEndpointParsed () {
  if (endpointParsed) return endpointParsed

  endpointParsed = new URL(getEndpoint())

  return endpointParsed
}

let s3Client: S3Client
function getClient () {
  if (s3Client) return s3Client

  const OBJECT_STORAGE = CONFIG.OBJECT_STORAGE

  s3Client = new S3Client({
    endpoint: getEndpoint(),
    region: OBJECT_STORAGE.REGION,
    credentials: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID
      ? {
        accessKeyId: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID,
        secretAccessKey: OBJECT_STORAGE.CREDENTIALS.SECRET_ACCESS_KEY
      }
      : undefined
  })

  // FIXME: https://github.com/aws/aws-sdk-js-v3/issues/2445 workaround
  s3Client.middlewareStack.add(
    (next, _context) => (args: any) => {
      if (typeof args.request?.body === 'string' && args.request.body.includes('CompletedMultipartUpload')) {
        args.request.body = args.request.body.replace(/CompletedMultipartUpload/g, 'CompleteMultipartUpload')
      }
      return next(args)
    },
    {
      step: 'build',
      priority: 'high'
    }
  )

  logger.info('Initialized S3 client %s with region %s.', getEndpoint(), OBJECT_STORAGE.REGION, lTags())

  return s3Client
}

// ---------------------------------------------------------------------------

export {
  getEndpointParsed,
  getClient
}

// ---------------------------------------------------------------------------

let endpoint: string
function getEndpoint () {
  if (endpoint) return endpoint

  const endpointConfig = CONFIG.OBJECT_STORAGE.ENDPOINT
  endpoint = endpointConfig.startsWith('http://') || endpointConfig.startsWith('https://')
    ? CONFIG.OBJECT_STORAGE.ENDPOINT
    : 'https://' + CONFIG.OBJECT_STORAGE.ENDPOINT

  return endpoint
}