"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MeshService = exports.MeshNoHandlerError = exports.MeshHandlerError = exports.MeshRequestTimeoutError = exports.__ΩMeshServiceOptions = exports.__ΩMeshNode = exports.__ΩMeshMessageMap = void 0;
const __ΩReturnType = ['T', 'args', '', 'ReturnType', 'l>e"!R"RPde#!P"@2"h"!/#qk#\'QRb!Pde"!p)w$y'];
const __ΩRecord = ['K', 'T', 'Record', 'l\'e#"Rb!b"Pde"!N#!w#y'];
const __ΩError = ['name', 'message', 'stack', 'Error', 'P&4!&4"&4#8Mw$y'];
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const os_1 = require("os");
const type_1 = require("@deepkit/type");
const lodash_1 = require("lodash");
const redis_1 = require("../helpers/redis/redis");
/*@ts-ignore*/
var { __ΩLeaderServiceOptions } = require('./leader');
const leader_1 = require("./leader");
const logger_1 = require("./logger");
const __ΩMeshMessageMap = [() => __ΩRecord, 'request', 'response', 'MeshMessageMap', '&P#4"#4#Mo!#w$y'];
exports.__ΩMeshMessageMap = __ΩMeshMessageMap;
const __ΩMeshNode = ['instanceId', 'hostname', 'self', 'MeshNode', 'P\'4!&4")4#Mw$y'];
exports.__ΩMeshNode = __ΩMeshNode;
const __ΩMeshServiceOptions = ['heartbeatIntervalMs', 'nodeTtlMs', 'requestTimeoutMs', () => __ΩLeaderServiceOptions, 'leaderOptions', 'MeshServiceOptions', 'P\'4!8\'4"8\'4#8n$4%8Mw&y'];
exports.__ΩMeshServiceOptions = __ΩMeshServiceOptions;
class MeshRequestTimeoutError extends Error {
    constructor(instanceId, type) {
        super(`Mesh request to instance ${instanceId} timed out (type: ${type})`);
        this.name = 'MeshRequestTimeoutError';
    }
}
exports.MeshRequestTimeoutError = MeshRequestTimeoutError;
MeshRequestTimeoutError.__type = [() => Error, 'instanceId', 'type', 'constructor', 'MeshRequestTimeoutError', 'P7!P\'2"&2#"0$5w%'];
class MeshHandlerError extends Error {
    constructor(message) {
        super(message);
        this.name = 'MeshHandlerError';
    }
}
exports.MeshHandlerError = MeshHandlerError;
MeshHandlerError.__type = [() => Error, 'message', 'constructor', 'MeshHandlerError', 'P7!P&2""0#5w$'];
class MeshNoHandlerError extends Error {
    constructor(type) {
        super(`No handler registered for mesh message type: ${type}`);
        this.name = 'MeshNoHandlerError';
    }
}
exports.MeshNoHandlerError = MeshNoHandlerError;
MeshNoHandlerError.__type = [() => Error, 'type', 'constructor', 'MeshNoHandlerError', 'P7!P&2""0#5w$'];
// --- Constants ---
const NO_HANDLER_ERROR_PREFIX = 'MESH_NO_HANDLER:';
// --- Lua Scripts ---
const HEARTBEAT_SCRIPT = `
local time = redis.call("time")
local now_ms = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
redis.call("zadd", KEYS[1], now_ms, ARGV[1])
return 1
`;
const CLEANUP_SCRIPT = `
local time = redis.call("time")
local now_ms = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
local cutoff = now_ms - tonumber(ARGV[1])
local expired = redis.call("zrangebyscore", KEYS[1], "-inf", cutoff)
for i, id in ipairs(expired) do
    redis.call("zrem", KEYS[1], id)
    redis.call("hdel", KEYS[2], id)
end
return expired
`;
const __ΩMeshRedisClient = [() => __ΩReturnType, () => redis_1.createRedis, "client", 'key', 'instanceId', '', 'HEARTBEAT', 'heartbeatsKey', 'nodesKey', 'ttlMs', 'CLEANUP', 'MeshRedisClient', 'Pi"o!".#fPP&2$&2%\'`/&4\'P&2(&2)&2*&F`/&4+MKw,y'];
const getMeshRedis = (0, lodash_1.memoize)(() => {
    const { client, prefix } = (0, redis_1.createRedis)('MESH');
    client.defineCommand('HEARTBEAT', { lua: HEARTBEAT_SCRIPT, numberOfKeys: 1 });
    client.defineCommand('CLEANUP', { lua: CLEANUP_SCRIPT, numberOfKeys: 2 });
    return { client: client, prefix };
});
const __ΩMeshRequest = ['requestId', 'senderInstanceId', 'type', 'data', 'timeoutMs', 'MeshRequest', 'P&4!\'4"&4##4$\'4%8Mw&y'];
const __ΩMeshResponse = ['requestId', true, 'reply', 'data', 'error', 'MeshResponse', 'P&4!."4##4$8&4%8Mw&y'];
const __ΩMeshHeartbeat = ['requestId', true, 'heartbeat', 'MeshHeartbeat', 'P&4!."4#Mw$y'];
const __ΩPendingRequest = ['value', '', 'resolve', () => __ΩError, 'reason', 'reject', () => __ΩReturnType, () => setTimeout, 'timer', 'type', 'targetInstanceId', 'PendingRequest', 'PP#2!$/"4#Pn$2%$/"4&i(o\'"4)&4*\'4+Mw,y'];
// --- MeshService ---
class MeshService {
    constructor(key, options) {
        this._instanceId = 0;
        this.prefix = '';
        this.running = false;
        this.heartbeatTimer = null;
        this.leaderService = null;
        this.subscriberClient = null;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        this.handlers = (Map.Ω = [['&'], ['data', '', 'P"2!"/"']], new Map());
        this.pendingRequests = (Map.Ω = [['&'], [() => __ΩPendingRequest, 'n!']], new Map());
        this.activeHandlerIntervals = (Set.Ω = [[() => __ΩReturnType, () => setInterval, 'i"o!"']], new Set());
        this.nodeCleanedUpCallback = null;
        this.logger = (0, logger_1.createLogger)(this);
        this.key = key;
        this.heartbeatIntervalMs = options?.heartbeatIntervalMs ?? 5000;
        this.nodeTtlMs = options?.nodeTtlMs ?? 15000;
        this.requestTimeoutMs = options?.requestTimeoutMs ?? 10000;
        this.leaderOptions = options?.leaderOptions;
    }
    get instanceId() {
        return this._instanceId;
    }
    registerHandler(type, handler) {
        this.handlers.set(type, handler);
    }
    setNodeCleanedUpCallback(cb) {
        this.nodeCleanedUpCallback = cb;
    }
    async getNodes() {
        if (!this.running) {
            throw new Error('MeshService is not running');
        }
        const { client } = getMeshRedis();
        const members = await client.zrange(this.heartbeatsKey(), 0, -1);
        if (members.length === 0)
            return [];
        const hostnames = await client.hmget(this.nodesKey(), ...members);
        return members.map(__assignType((id, i) => ({
            instanceId: parseInt(id, 10),
            hostname: hostnames[i] ?? 'unknown',
            self: parseInt(id, 10) === this._instanceId
        }), ['id', 'i', '', 'P"2!"2""/#']));
    }
    async invoke(instanceId, type, data) {
        if (!this.running) {
            throw new Error('MeshService is not running');
        }
        // Local invocation — call handler directly
        if (instanceId === this._instanceId) {
            const handler = this.handlers.get(type);
            if (!handler)
                throw new MeshNoHandlerError(type);
            return handler(data);
        }
        // Remote invocation via pub/sub
        const requestId = (0, type_1.uuid)();
        const channel = this.channelForInstance(instanceId);
        // Serialize before registering pending request to avoid leaked timers on stringify failure
        const message = {
            requestId,
            senderInstanceId: this._instanceId,
            type,
            data,
            timeoutMs: this.requestTimeoutMs
        };
        const payload = JSON.stringify(message);
        return (Promise.Ω = [[() => type, () => data, "request", "response", '!Pdi!h!!qe!!!jPdi"!h!!f.#fqe!!!jf.$f']], new Promise(__assignType((resolve, reject) => {
            const timer = setTimeout(() => {
                this.pendingRequests.delete(requestId);
                reject(new MeshRequestTimeoutError(instanceId, type));
            }, this.requestTimeoutMs);
            this.pendingRequests.set(requestId, {
                resolve: resolve,
                reject,
                timer,
                type,
                targetInstanceId: instanceId
            });
            const { client } = getMeshRedis();
            client.publish(channel, payload).catch(__assignType(err => {
                clearTimeout(timer);
                this.pendingRequests.delete(requestId);
                reject(new Error(`Failed to publish mesh request: ${err instanceof Error ? err.message : String(err)}`));
            }, ['err', '', 'P"2!"/"']));
        }, ['resolve', 'reject', '', 'P"2!"2""/#'])));
    }
    async start() {
        if (this.running) {
            throw new Error('MeshService is already running');
        }
        const { client, prefix } = getMeshRedis();
        this.prefix = prefix;
        // Acquire unique instance ID
        this._instanceId = await client.incr(this.nextIdKey());
        // Create subscriber and subscribe to own channel
        const { client: subClient } = (0, redis_1.createRedis)('MESH');
        this.subscriberClient = subClient;
        try {
            const channel = this.channelForInstance(this._instanceId);
            await subClient.subscribe(channel);
            subClient.on('message', __assignType((_channel, message) => {
                this.handleMessage(message);
            }, ['_channel', 'message', '', 'P&2!&2""/#']));
            // Register heartbeat and node metadata
            await client.HEARTBEAT(this.heartbeatsKey(), String(this._instanceId));
            await client.hset(this.nodesKey(), String(this._instanceId), (0, os_1.hostname)());
        }
        catch (err) {
            // Clean up subscriber on partial init failure
            try {
                await subClient.unsubscribe();
                await subClient.quit();
            }
            catch {
                // ignore cleanup errors
            }
            this.subscriberClient = null;
            throw err;
        }
        this.running = true;
        // Start heartbeat interval
        this.heartbeatTimer = setInterval(() => this.doHeartbeat(), this.heartbeatIntervalMs);
        // Start leader service for cleanup duties
        this.leaderService = new leader_1.LeaderService(`mesh:${this.key}`, this.leaderOptions);
        this.leaderService.start();
        this.logger.info('mesh node started', { instanceId: this._instanceId, key: this.key });
    }
    async stop() {
        this.running = false;
        // Stop leader service
        if (this.leaderService) {
            await this.leaderService.stop();
            this.leaderService = null;
        }
        // Stop heartbeat
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
        // Clear all active handler heartbeat intervals
        for (const interval of this.activeHandlerIntervals) {
            clearInterval(interval);
        }
        this.activeHandlerIntervals.clear();
        // Reject all pending requests
        for (const [requestId, pending] of this.pendingRequests) {
            clearTimeout(pending.timer);
            pending.reject(new Error('MeshService stopped'));
            this.pendingRequests.delete(requestId);
        }
        // Unsubscribe and quit subscriber
        if (this.subscriberClient) {
            try {
                await this.subscriberClient.unsubscribe();
                await this.subscriberClient.quit();
            }
            catch {
                // ignore errors during cleanup
            }
            this.subscriberClient = null;
        }
        // Remove self from heartbeats and nodes
        try {
            const { client } = getMeshRedis();
            await client.zrem(this.heartbeatsKey(), String(this._instanceId));
            await client.hdel(this.nodesKey(), String(this._instanceId));
        }
        catch {
            // ignore errors during cleanup
        }
        this.logger.info('mesh node stopped', { instanceId: this._instanceId, key: this.key });
    }
    // --- Private ---
    nextIdKey() {
        return `${this.prefix}:mesh:${this.key}:next_id`;
    }
    heartbeatsKey() {
        return `${this.prefix}:mesh:${this.key}:heartbeats`;
    }
    nodesKey() {
        return `${this.prefix}:mesh:${this.key}:nodes`;
    }
    channelForInstance(instanceId) {
        return `${this.prefix}:mesh:${this.key}:node:${instanceId}`;
    }
    async doHeartbeat() {
        if (!this.running)
            return;
        try {
            const { client } = getMeshRedis();
            await client.HEARTBEAT(this.heartbeatsKey(), String(this._instanceId));
        }
        catch (err) {
            this.logger.warn('mesh heartbeat failed', { err });
        }
        // If leader, run cleanup
        if (this.leaderService?.isLeader) {
            await this.doCleanup();
        }
    }
    async doCleanup() {
        try {
            const { client } = getMeshRedis();
            const expired = await client.CLEANUP(this.heartbeatsKey(), this.nodesKey(), String(this.nodeTtlMs));
            if (expired.length > 0) {
                this.logger.info('cleaned up expired mesh nodes', { expired });
                for (const idStr of expired) {
                    const id = parseInt(idStr, 10);
                    try {
                        await this.nodeCleanedUpCallback?.(id);
                    }
                    catch (err) {
                        this.logger.warn('node cleanup callback error', { err, instanceId: id });
                    }
                }
            }
        }
        catch (err) {
            this.logger.warn('mesh cleanup failed', { err });
        }
    }
    handleMessage(raw) {
        if (!this.running)
            return;
        let msg;
        try {
            msg = JSON.parse(raw);
        }
        catch (err) {
            this.logger.warn('failed to parse mesh message', { err, raw });
            return;
        }
        if (typeof msg !== 'object' || msg === null) {
            this.logger.warn('invalid mesh message: not an object', { raw });
            return;
        }
        const obj = msg;
        if ('heartbeat' in obj && obj.heartbeat) {
            this.handleHeartbeatMessage(obj);
        }
        else if ('reply' in obj && obj.reply) {
            this.handleResponseMessage(obj);
        }
        else {
            this.handleRequestMessage(obj);
        }
    }
    handleHeartbeatMessage(msg) {
        const pending = this.pendingRequests.get(msg.requestId);
        if (!pending)
            return;
        // Reset timeout
        clearTimeout(pending.timer);
        pending.timer = setTimeout(() => {
            this.pendingRequests.delete(msg.requestId);
            pending.reject(new MeshRequestTimeoutError(pending.targetInstanceId, pending.type));
        }, this.requestTimeoutMs);
    }
    handleResponseMessage(msg) {
        const pending = this.pendingRequests.get(msg.requestId);
        if (!pending)
            return;
        clearTimeout(pending.timer);
        this.pendingRequests.delete(msg.requestId);
        if (msg.error !== undefined) {
            if (typeof msg.error === 'string' && msg.error.startsWith(NO_HANDLER_ERROR_PREFIX)) {
                pending.reject(new MeshNoHandlerError(msg.error.slice(NO_HANDLER_ERROR_PREFIX.length)));
            }
            else {
                pending.reject(new MeshHandlerError(msg.error));
            }
        }
        else {
            pending.resolve(msg.data);
        }
    }
    handleRequestMessage(msg) {
        if (!this.running)
            return;
        if (typeof msg.requestId !== 'string' || typeof msg.senderInstanceId !== 'number' || typeof msg.type !== 'string') {
            this.logger.warn('invalid mesh request: missing or malformed fields', { msg });
            return;
        }
        const handler = this.handlers.get(msg.type);
        const { client } = getMeshRedis();
        const senderChannel = this.channelForInstance(msg.senderInstanceId);
        if (!handler) {
            const response = {
                requestId: msg.requestId,
                reply: true,
                error: `${NO_HANDLER_ERROR_PREFIX}${msg.type}`
            };
            client.publish(senderChannel, JSON.stringify(response)).catch(__assignType(err => {
                this.logger.warn('failed to publish no-handler response', { err });
            }, ['err', '', 'P"2!"/"']));
            return;
        }
        // Use the caller's timeout for heartbeat interval (fall back to our own)
        const effectiveTimeoutMs = msg.timeoutMs ?? this.requestTimeoutMs;
        const heartbeatInterval = setInterval(() => {
            const heartbeat = {
                requestId: msg.requestId,
                heartbeat: true
            };
            client.publish(senderChannel, JSON.stringify(heartbeat)).catch(__assignType(err => {
                this.logger.warn('failed to publish handler heartbeat', { err });
            }, ['err', '', 'P"2!"/"']));
        }, effectiveTimeoutMs * 0.75);
        this.activeHandlerIntervals.add(heartbeatInterval);
        // Execute handler
        Promise.resolve()
            .then(() => handler(msg.data))
            .then(__assignType(result => {
            clearInterval(heartbeatInterval);
            this.activeHandlerIntervals.delete(heartbeatInterval);
            const response = {
                requestId: msg.requestId,
                reply: true,
                data: result
            };
            client.publish(senderChannel, JSON.stringify(response)).catch(__assignType(err => {
                this.logger.warn('failed to publish handler response', { err });
            }, ['err', '', 'P"2!"/"']));
        }, ['result', '', 'P"2!"/"']))
            .catch(__assignType(err => {
            clearInterval(heartbeatInterval);
            this.activeHandlerIntervals.delete(heartbeatInterval);
            const response = {
                requestId: msg.requestId,
                reply: true,
                error: err instanceof Error ? err.message : String(err)
            };
            client.publish(senderChannel, JSON.stringify(response)).catch(__assignType(publishErr => {
                this.logger.warn('failed to publish handler error response', { err: publishErr });
            }, ['publishErr', '', 'P"2!"/"']));
        }, ['err', '', 'P"2!"/"']));
    }
}
exports.MeshService = MeshService;
MeshService.__type = ['T', '_instanceId', function () { return 0; }, 'key', 'prefix', function () { return ''; }, 'running', function () { return false; }, 'heartbeatIntervalMs', 'nodeTtlMs', 'requestTimeoutMs', () => __ΩLeaderServiceOptions, 'leaderOptions', () => __ΩReturnType, () => setInterval, 'heartbeatTimer', function () { return null; }, () => leader_1.LeaderService, 'leaderService', function () { return null; }, () => __ΩReturnType, () => redis_1.createRedis, "client", 'subscriberClient', function () { return null; }, 'handlers', function () { return (Map.Ω = [['&'], ['data', '', 'P"2!"/"']], new Map()); }, 'pendingRequests', function () { return (Map.Ω = [['&'], [() => __ΩPendingRequest, 'n!']], new Map()); }, 'activeHandlerIntervals', function () { return (Set.Ω = [[() => __ΩReturnType, () => setInterval, 'i"o!"']], new Set()); }, 'instanceId', '', 'nodeCleanedUpCallback', function () { return null; }, 'logger', function () { return (0, logger_1.createLogger)(this); }, () => __ΩMeshServiceOptions, 'options', 'constructor', 'type', "request", 'data', "response", "response", 'handler', 'registerHandler', 'cb', 'setNodeCleanedUpCallback', () => __ΩMeshNode, 'getNodes', "request", "response", 'invoke', 'start', 'stop', 'nextIdKey', 'heartbeatsKey', 'nodesKey', 'channelForInstance', 'doHeartbeat', 'doCleanup', 'raw', 'handleMessage', () => __ΩMeshHeartbeat, 'msg', 'handleHeartbeatMessage', () => __ΩMeshResponse, 'handleResponseMessage', () => __ΩMeshRequest, 'handleRequestMessage', 'MeshService', 'b!\'3";>#&3$;&3%;>&)3\';>(\'3);\'3*;\'3+;n,3-8;Pi/o.",J30;>1PP72,J33;>4Pi6o5".7f,J38;>9!3:;>;!3<;>=!3>;>?PP\'2@P$$`J/A,J3B;>C!3D;>EP&2$nF2G8"0H!P"2IPe#!"f.Jf2KPe$!"f.Lfe$!"f.Mf`J/A2N$0OPP\'2@P$$`J/A2P$0QPnRF`0SP\'2@"2Ie"!"f.Tf2Ke"!"f.Uf`0VP$`0WP$`0XP&0Y;P&0Z;P&0[;P\'2@&0\\;P$`0];P$`0^;P&2_$0`;Pna2b$0c;Pnd2b$0e;Pnf2b$0g;5wh'];
//# sourceMappingURL=mesh.js.map