"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const PrometheusStatsSink_1 = require("./stats/PrometheusStatsSink");
const kubernetes_1 = require("./kubernetes");
const KubernetesClient = require("kubernetes-client");
class KubernetesSyncWorkerGroup extends kubernetes_1.KubernetesServer {
    constructor() {
        const group = process.env.SYNC_WORKER_GROUP;
        if (!group) {
            throw new Error("SYNC_WORKER_GROUP environment variable is not defined");
        }
        super({ labels: { group } });
        this.publicKeyPath = process.env.PUBLIC_KEY_PATH;
        if (!this.publicKeyPath) {
            throw new Error("PUBLIC_KEY_PATH environment variable is not defined");
        }
    }
    start() {
        const _super = name => super[name];
        return __awaiter(this, void 0, void 0, function* () {
            yield _super("start").call(this);
            const kubernetesConfig = kubernetes_1.getKubernetesConfig();
            const podResponse = yield kubernetes_1.getPodInfo();
            this.coreApi = new KubernetesClient.Core(kubernetesConfig).ns(podResponse.metadata.namespace);
            const syncWorkerConfig = {
                serviceName: process.env.SYNC_WORKER_SERVICE_NAME,
                endpointsName: process.env.SYNC_WORKER_ENDPOINTS_NAME || process.env.SYNC_WORKER_SERVICE_NAME,
                syncWorkerId: process.env.SYNC_WORKER_ID,
                dataPath: process.env.SYNC_WORKER_DATA_PATH || "/data",
                syncWorkerGroup: process.env.SYNC_WORKER_GROUP,
                featureToken: process.env.SYNC_WORKER_FEATURE_TOKEN,
                publicKeyPath: this.publicKeyPath,
                logLevel: "debug",
                kubernetesConfig: kubernetes_1.getKubernetesConfig(),
                enableDownloadLogCompaction: process.env.SYNC_WORKER_ENABLE_DOWNLOAD_LOG_COMPACTION === "false",
                maxDownloadSize: process.env.SYNC_WORKER_MAX_DOWNLOAD_SIZE ? Number(process.env.SYNC_WORKER_MAX_DOWNLOAD_SIZE) : undefined,
                podIp: podResponse.status.podIP,
                podRef: {
                    kind: "Pod",
                    name: podResponse.metadata.name,
                    namespace: podResponse.metadata.namespace,
                    uid: podResponse.metadata.uid,
                    resourceVersion: podResponse.metadata.resourceVersion,
                },
                nodeName: podResponse.spec.nodeName,
            };
            if (!syncWorkerConfig.serviceName) {
                throw new Error("SYNC_WORKER_SERVICE_NAME environment variable is not defined");
            }
            if (!syncWorkerConfig.syncWorkerId) {
                throw new Error("SYNC_WORKER_ID environment variable is not defined");
            }
            if (!syncWorkerConfig.featureToken) {
                throw new Error("SYNC_WORKER_FEATURE_TOKEN environment variable is not defined");
            }
            this.syncWorker = new kubernetes_1.KubernetesSyncWorker(syncWorkerConfig);
            this.syncWorker.on("shutdown", (err) => __awaiter(this, void 0, void 0, function* () {
                delete this.syncWorker;
                if (err) {
                    this.logger.error("Sync worker has shutdown due to an error", err);
                    process.exit(1);
                }
                else {
                    yield this.shutdown();
                }
            }));
            yield this.syncWorker.start({
                logger: this.logger,
                statsSink: new PrometheusStatsSink_1.PrometheusStatsSink({ registry: this.registry }),
            });
        });
    }
    shutdown() {
        const _super = name => super[name];
        return __awaiter(this, void 0, void 0, function* () {
            if (this.syncWorker) {
                yield this.syncWorker.shutdown();
            }
            yield _super("shutdown").call(this);
            process.exit(0);
        });
    }
}
if (!module.parent) {
    const server = new KubernetesSyncWorkerGroup();
    server.start().catch((err) => {
        console.log(`Could not start server: ${err.stack}`);
        process.exit(1);
    });
}
//# sourceMappingURL=KubernetesSyncWorkerGroup.js.map