// npm import * as AWS from 'aws-sdk'; // @ownzones import { s3Lib as ownS3 } from '@ownzones/lib'; import { redisClient } from '../../utils/async-wrappers'; // app import { CacheManagerEvent, CacheType, ConfigurationError, DynamodbCacheManager, ICacheManager, ICacheManagerOptions, RedisCacheManager, } from '.'; import { config, log } from '../../config'; import { ISegment } from '../playlist-builder'; export class CacheManagerFactory { public static create(): ICacheManager { const { cacheSelect, cacheAutostart, cacheCleanupInterval, } = config; const baseOptions: ICacheManagerOptions = { autoStartGC: cacheAutostart, cleanupInterval: cacheCleanupInterval, }; let cacheManager: ICacheManager; if (cacheSelect === CacheType.REDIS) { const { cacheRedis, cachePrefix, } = config; if (!cacheRedis) { throw new ConfigurationError('The config is missing the redis cache configuration object'); } const redisOptions: typeof cacheRedis & { tls?: {} } = cacheRedis; if (process.env.FORCE_REDIS_SSL && process.env.FORCE_REDIS_SSL.toLowerCase() === 'true') { redisOptions.tls = {}; } cacheManager = new RedisCacheManager({ ...baseOptions, client: redisClient.createClient(redisOptions), keys: { prefix: cachePrefix, }, }); } else if (cacheSelect === CacheType.DYNAMO) { const { cacheDynamo } = config; cacheManager = new DynamodbCacheManager({ ...baseOptions, client: new AWS.DynamoDB.DocumentClient({ region: cacheDynamo.region, endpoint: config.cacheDynamo.endpoint, }), scoreIndexName: cacheDynamo.scoreIndexName, tableName: cacheDynamo.tableName as string, paginationLimit: cacheDynamo.paginationLimit, partitionSegmentsPerFiles: cacheDynamo.partitionSegmentsPerFiles, }); } else { throw new ConfigurationError('The config is missing the cache select setting'); } cacheManager.on(CacheManagerEvent.REMOVE_CACHE, (segment: ISegment) => { void (async () => { try { const orgSegmentS3Properties = ownS3.parseUrl(segment.s3Path as string); await ownS3.s3.deleteObject({ Bucket: orgSegmentS3Properties.bucket, Key: orgSegmentS3Properties.key, }).promise(); } catch (error) { log.error(`could not delete the s3 object after the segment cache removal: ${segment.id as string}`, error); } })(); }); return cacheManager; } }