client.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import type { S3Client } from '@aws-sdk/client-s3'
  2. import { logger } from '@server/helpers/logger.js'
  3. import { isProxyEnabled } from '@server/helpers/proxy.js'
  4. import { getAgent } from '@server/helpers/requests.js'
  5. import { CONFIG } from '@server/initializers/config.js'
  6. import { lTags } from './logger.js'
  7. async function getProxyRequestHandler () {
  8. if (!isProxyEnabled()) return null
  9. const { agent } = getAgent()
  10. const { NodeHttpHandler } = await import('@smithy/node-http-handler')
  11. return new NodeHttpHandler({
  12. httpAgent: agent.http,
  13. httpsAgent: agent.https
  14. })
  15. }
  16. let endpointParsed: URL
  17. function getEndpointParsed () {
  18. if (endpointParsed) return endpointParsed
  19. endpointParsed = new URL(getEndpoint())
  20. return endpointParsed
  21. }
  22. let s3ClientPromise: Promise<S3Client>
  23. function getClient () {
  24. if (s3ClientPromise) return s3ClientPromise
  25. s3ClientPromise = (async () => {
  26. const OBJECT_STORAGE = CONFIG.OBJECT_STORAGE
  27. const { S3Client } = await import('@aws-sdk/client-s3')
  28. const s3Client = new S3Client({
  29. endpoint: getEndpoint(),
  30. region: OBJECT_STORAGE.REGION,
  31. credentials: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID
  32. ? {
  33. accessKeyId: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID,
  34. secretAccessKey: OBJECT_STORAGE.CREDENTIALS.SECRET_ACCESS_KEY
  35. }
  36. : undefined,
  37. requestHandler: await getProxyRequestHandler()
  38. })
  39. logger.info('Initialized S3 client %s with region %s.', getEndpoint(), OBJECT_STORAGE.REGION, lTags())
  40. return s3Client
  41. })()
  42. return s3ClientPromise
  43. }
  44. // ---------------------------------------------------------------------------
  45. export {
  46. getEndpointParsed,
  47. getClient
  48. }
  49. // ---------------------------------------------------------------------------
  50. let endpoint: string
  51. function getEndpoint () {
  52. if (endpoint) return endpoint
  53. const endpointConfig = CONFIG.OBJECT_STORAGE.ENDPOINT
  54. endpoint = endpointConfig.startsWith('http://') || endpointConfig.startsWith('https://')
  55. ? CONFIG.OBJECT_STORAGE.ENDPOINT
  56. : 'https://' + CONFIG.OBJECT_STORAGE.ENDPOINT
  57. return endpoint
  58. }