"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstanceRegistryService = void 0;
const backend_common_1 = require("@n8n/backend-common");
const config_1 = require("@n8n/config");
const di_1 = require("@n8n/di");
const node_crypto_1 = require("node:crypto");
const n8n_core_1 = require("n8n-core");
const constants_1 = require("../../constants");
const instance_registry_types_1 = require("./instance-registry.types");
let InstanceRegistryService = class InstanceRegistryService {
    constructor(instanceSettings, executionsConfig, logger) {
        this.instanceSettings = instanceSettings;
        this.executionsConfig = executionsConfig;
        this.logger = logger;
        this.heartbeatInterval = null;
        this.instanceKey = (0, node_crypto_1.randomUUID)();
        this.registeredAt = 0;
        this.logger = this.logger.scoped('instance-registry');
    }
    async init() {
        this.storage = await this.selectStorage();
        this.registeredAt = Date.now();
        const registration = this.buildRegistration();
        await this.storage.register(registration);
        this.startHeartbeat();
        this.logger.info('Instance registered', {
            instanceKey: this.instanceKey,
            backend: this.storage.kind,
            instanceType: this.instanceSettings.instanceType,
        });
    }
    async shutdown() {
        if (!this.storage)
            return;
        this.stopHeartbeat();
        try {
            await this.storage.unregister(this.instanceKey);
        }
        catch (error) {
            this.logger.warn('Failed to unregister during shutdown', { error });
        }
        try {
            await this.storage.destroy();
        }
        catch (error) {
            this.logger.warn('Failed to destroy storage during shutdown', { error });
        }
        this.logger.debug('Instance unregistered');
    }
    async getAllInstances() {
        return await this.storage.getAllRegistrations();
    }
    getLocalInstance() {
        return this.buildRegistration();
    }
    async getLastKnownState() {
        return await this.storage.getLastKnownState();
    }
    async saveLastKnownState(state) {
        await this.storage.saveLastKnownState(state);
    }
    async cleanupStaleMembers() {
        return await this.storage.cleanupStaleMembers();
    }
    get storageBackend() {
        return this.storage.kind;
    }
    buildRegistration() {
        return {
            schemaVersion: 1,
            instanceKey: this.instanceKey,
            hostId: this.instanceSettings.hostId,
            instanceType: this.instanceSettings.instanceType,
            instanceRole: this.instanceSettings.instanceRole,
            version: constants_1.N8N_VERSION,
            registeredAt: this.registeredAt,
            lastSeen: Date.now(),
        };
    }
    async selectStorage() {
        const useRedis = this.instanceSettings.isMultiMain || this.executionsConfig.mode === 'queue';
        if (useRedis) {
            const { RedisInstanceStorage } = await Promise.resolve().then(() => __importStar(require('./storage/redis-instance-storage')));
            const { Container } = await Promise.resolve().then(() => __importStar(require('@n8n/di')));
            return Container.get(RedisInstanceStorage);
        }
        const { MemoryInstanceStorage } = await Promise.resolve().then(() => __importStar(require('./storage/memory-storage')));
        return new MemoryInstanceStorage();
    }
    startHeartbeat() {
        this.heartbeatInterval = setInterval(async () => {
            try {
                await this.storage.heartbeat(this.buildRegistration());
                this.logger.debug('Heartbeat updated');
            }
            catch (error) {
                this.logger.warn('Heartbeat failed', { error });
            }
        }, instance_registry_types_1.REGISTRY_CONSTANTS.HEARTBEAT_INTERVAL_MS);
    }
    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }
};
exports.InstanceRegistryService = InstanceRegistryService;
exports.InstanceRegistryService = InstanceRegistryService = __decorate([
    (0, di_1.Service)(),
    __metadata("design:paramtypes", [n8n_core_1.InstanceSettings,
        config_1.ExecutionsConfig,
        backend_common_1.Logger])
], InstanceRegistryService);
//# sourceMappingURL=instance-registry.service.js.map