"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QueueManager = exports.MemoryQueue = void 0;
class MemoryQueue {
    constructor(topic) {
        this.topic = topic;
        // private readonly listeners: QueueListener[] = [];
        this.listeners = [];
        this.messages = [];
    }
    addListener(handler) {
        this.listeners.push(handler);
        this.raise(); // <-- there's how we beat the latency without losing messages.
    }
    /** Queues the given message and raises `newMessage` in the listeners.  */
    push(msg) {
        this.messages.push(msg);
        this.raise(); // these calls could pile up, but in that case theyd just fade out as the queue empties.
    }
    /** triggers each listener for whatever is in the queue until it is empty. */
    raise() {
        if (this.listeners.length === 0)
            return;
        let msg = this.messages.pop();
        while (msg) {
            for (let listener of this.listeners) {
                try {
                    listener(msg);
                }
                catch (err) {
                    // TODO: log the error
                }
            }
            msg = this.messages.pop();
        }
    }
}
exports.MemoryQueue = MemoryQueue;
/** Lightweight, single use custodian of subscribeable message queues. */
class QueueManager {
    constructor() {
        this.queues = {};
    }
    push(msg, topic) {
        this.getsertQueue(topic).push(msg);
    }
    subscribeTo(topic, handler) {
        this.getsertQueue(topic).addListener(handler);
    }
    /** Creates a queue for the given message topic (Idempotent). */
    getsertQueue(topic) {
        let q = this.queues[topic];
        if (!q) {
            q = new MemoryQueue(topic);
            this.queues[topic] = q;
        }
        return q;
    }
}
exports.QueueManager = QueueManager;
//# sourceMappingURL=relay-queue-manager.js.map