"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisSubscriber = exports.RedisPublisher = void 0;
/**
 * ⚠️ Publisher, Subscriber 必须 connect 之后再开始发布订阅，否则会先进入 PubSub mode，不能发送 AUTH 命令
 */
const log_1 = require("@/utils/log");
const redis_db_1 = require("./redis-db");
const log = new log_1.Logger('redis-pub-sub');
class RedisPublisher {
    constructor(channel) {
        this.queue = [];
        this.isConnected = false;
        if (!channel) {
            const e = new Error('channelId should not be empty');
            log.error('%s', e === null || e === void 0 ? void 0 : e.stack);
            throw e;
        }
        this.channel = channel;
        this.client = redis_db_1.RedisDB.client.duplicate();
        redis_db_1.listenRedisEvent(this.client);
        this.init();
    }
    /**
     * 发布 message 到 channel
     */
    publish(message) {
        if (this.isConnected)
            this.realPublish(message);
        else
            this.queue.push(message);
    }
    /**
     * 断开连接。暂写作空实现，redis 进入 PubSub mode 后，不能发送其他任何指令
     */
    disconnect() { }
    /**
     * 真正的 publish 到 redis
     */
    realPublish(message) {
        const msgStr = typeof message !== 'string' ? JSON.stringify(message) : message;
        try {
            this.client.publish(this.channel, msgStr);
        }
        catch (e) {
            log.error('publish %s to channel %s error: %s', msgStr, this.channel, e.stack);
        }
    }
    /**
     * 初始化数据库连接，建立后清空 publish 队列
     */
    async init() {
        await this.client.connect();
        log.info('redis publisher client created, %s', this.channel);
        this.isConnected = true;
        this.queue.forEach(this.realPublish.bind(this));
    }
}
exports.RedisPublisher = RedisPublisher;
class RedisSubscriber {
    constructor(channel) {
        this.isConnected = false;
        this.operateQueue = [];
        /**
         * 取消订阅
         */
        this.unsubscribe = () => this.client.unsubscribe(this.channel);
        /**
         * 取消订阅含通配符 * 的 channel
         */
        this.pUnsubscribe = () => this.client.pUnsubscribe(this.channel);
        /**
         * 断开连接。暂写作空实现，redis 进入 PubSub mode 后，不能发送其他任何指令
         */
        this.disconnect = () => { };
        if (!channel) {
            const e = new Error('channelId should not be empty');
            log.error('%s', e === null || e === void 0 ? void 0 : e.stack);
            throw e;
        }
        this.channel = channel;
        this.client = redis_db_1.RedisDB.client.duplicate();
        redis_db_1.listenRedisEvent(this.client);
        this.init();
    }
    /**
     * 订阅到 channel
     */
    subscribe(cb) {
        if (this.isConnected)
            this.client.subscribe(this.channel, cb);
        else
            this.operateQueue.push([this.subscribe, cb]);
    }
    /**
     * 含通配符 * 的订阅
     */
    pSubscribe(cb) {
        if (this.isConnected)
            this.client.pSubscribe(this.channel, cb);
        else
            this.operateQueue.push([this.pSubscribe, cb]);
    }
    /**
     * 初始化数据库连接，建立后清空提前调用的指令队列
     */
    async init() {
        if (this.isConnected)
            return;
        await this.client.connect();
        log.info('redis subscriber client created, %s', this.channel);
        this.isConnected = true;
        if (this.operateQueue) {
            this.operateQueue.forEach(([fn, cb]) => {
                fn.call(this, cb);
            });
        }
    }
}
exports.RedisSubscriber = RedisSubscriber;
