UNPKG

@atomist/automation-client

Version:

Atomist API for software low-level client

85 lines 2.8 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const TinyQueue = require("tinyqueue"); const WebSocket = require("ws"); const logger_1 = require("../../../util/logger"); const WebSocketMessageClient_1 = require("./WebSocketMessageClient"); /** * Lifecycle owning a WebSocket connection wrt message sending */ class QueuingWebSocketLifecycle { constructor() { // This is odd but the only way to the types working this.messages = new TinyQueue(); } /** * Set the WebSocket to manage * @param ws */ set(ws) { this.ws = ws; } /** * Is the WebSocket is connected and healthy */ connected() { return !!this.ws && this.ws.readyState === WebSocket.OPEN; } /** * Get the raw WebSocket that is managed here */ get() { return this.ws; } /** * Reset the WebSocket */ reset() { this.ws = null; } /** * Send a message over the managed WebSocket * If the WebSocket isn't connected, messages are queued for later * when a WebSocket is connected again. * @param msg */ send(msg) { if (!this) { logger_1.logger.warn(`WebSocket has been destroyed before we were able to send the message`); return; } else if (this.connected()) { WebSocketMessageClient_1.sendMessage(msg, this.ws, true); } else { if (!this.timer) { this.init(); } this.messages.push(msg); } } /** * Init the internal queue processing */ init() { this.timer = setInterval(() => __awaiter(this, void 0, void 0, function* () { const queuedMessages = []; while (this.messages.length > 0) { queuedMessages.push(this.messages.pop()); } queuedMessages.forEach(this.send); }), 1000); this.timer.unref(); } } exports.QueuingWebSocketLifecycle = QueuingWebSocketLifecycle; //# sourceMappingURL=WebSocketLifecycle.js.map