"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RepoCacheS3 = void 0;
const stream_1 = require("stream");
const client_s3_1 = require("@aws-sdk/client-s3");
const logger_1 = require("../../../../logger");
const s3_1 = require("../../../s3");
const streams_1 = require("../../../streams");
const base_1 = require("./base");
class RepoCacheS3 extends base_1.RepoCacheBase {
    constructor(repository, fingerprint, url) {
        super(repository, fingerprint);
        const { Bucket, Key } = (0, s3_1.parseS3Url)(url);
        this.dir = this.getCacheFolder(Key);
        this.bucket = Bucket;
        this.s3Client = (0, s3_1.getS3Client)();
    }
    async read() {
        const cacheFileName = this.getCacheFileName();
        const s3Params = {
            Bucket: this.bucket,
            Key: cacheFileName,
        };
        try {
            const { Body: res } = await this.s3Client.send(new client_s3_1.GetObjectCommand(s3Params));
            if (res instanceof stream_1.Readable) {
                logger_1.logger.debug('RepoCacheS3.read() - success');
                return await (0, streams_1.streamToString)(res);
            }
            logger_1.logger.warn(`RepoCacheS3.read() - failure - expecting Readable return type got '${typeof res}' type instead`);
        }
        catch (err) {
            // https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
            if (err.name === 'NoSuchKey') {
                logger_1.logger.debug('RepoCacheS3.read() - No cached file found');
            }
            else {
                logger_1.logger.warn({ err }, 'RepoCacheS3.read() - failure');
            }
        }
        return null;
    }
    async write(data) {
        const cacheFileName = this.getCacheFileName();
        const s3Params = {
            Bucket: this.bucket,
            Key: cacheFileName,
            Body: JSON.stringify(data),
            ContentType: 'application/json',
        };
        try {
            await this.s3Client.send(new client_s3_1.PutObjectCommand(s3Params));
        }
        catch (err) {
            logger_1.logger.warn({ err }, 'RepoCacheS3.write() - failure');
        }
    }
    getCacheFolder(pathname) {
        if (!pathname) {
            return '';
        }
        if (pathname.endsWith('/')) {
            return pathname;
        }
        logger_1.logger.warn({ pathname }, 'RepoCacheS3.getCacheFolder() - appending missing trailing slash to pathname');
        return pathname + '/';
    }
    getCacheFileName() {
        return `${this.dir}${this.platform}/${this.repository}/cache.json`;
    }
}
exports.RepoCacheS3 = RepoCacheS3;
//# sourceMappingURL=s3.js.map