worker-websocket-ctrl
Version:
Share a websocket using a Worker/SharedWorker communicating through comlink
165 lines (164 loc) • 6.72 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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 });
exports.WorkerWsController = void 0;
const Comlink = __importStar(require("comlink"));
let ws = null;
let subscribers = new Set();
let _getProtocols = null;
const DEFAULT_KEEPALIVE_INTERVAL_SEG = 30;
const DEFAULT_KEEPALIVE_TIMEOUT_SEG = 5;
const DEFAULT_RECONNECT_SEG = 5;
class WorkerWsController {
constructor(workerCtx, path, options = {}) {
var _a, _b, _c, _d;
this.workerCtx = workerCtx;
this.path = path;
this.options = options;
this.apiUrl = '';
this.apiUrlToJoin = '';
if (path.startsWith('/')) {
this.path = path.substring(1);
}
this.keepAliveInterval = ((_a = options.keepaliveInterval) !== null && _a !== void 0 ? _a : DEFAULT_KEEPALIVE_INTERVAL_SEG) * 1000;
this.keepAliveTimeout = ((_b = options.keepaliveTimeout) !== null && _b !== void 0 ? _b : DEFAULT_KEEPALIVE_TIMEOUT_SEG) * 1000;
this.reconnectDelay = ((_c = options.reconnectDelay) !== null && _c !== void 0 ? _c : DEFAULT_RECONNECT_SEG) * 1000;
this.closeDelay = ((_d = options.closeDelay) !== null && _d !== void 0 ? _d : 0) * 1000;
}
start(apiUrl, getProtocols) {
this.apiUrl = apiUrl;
this.apiUrlToJoin = apiUrl.endsWith('/') ? apiUrl.substring(0, apiUrl.length - 1) : apiUrl;
_getProtocols = getProtocols !== null && getProtocols !== void 0 ? getProtocols : null;
if (ws != null)
return;
this.startWs();
}
subscribe(onEvent, ping, onConnect, onDisconnect, onClose) {
const s = { onEvent, ping, onConnect, onDisconnect, onClose };
subscribers.add(s);
const keepAliveRef = this.keepAlive(s);
const unsubscribe = Comlink.proxy(() => {
subscribers.delete(s);
clearInterval(keepAliveRef);
if (this.closeDelay !== 0) {
if (this.closeRef)
clearTimeout(this.closeRef);
this.closeRef = setTimeout(() => this.checkSubscriptions(), this.closeDelay);
}
else {
this.checkSubscriptions();
}
});
if ((ws === null || ws === void 0 ? void 0 : ws.readyState) === WebSocket.OPEN)
onConnect();
return unsubscribe;
}
sendMessage(data) {
ws === null || ws === void 0 ? void 0 : ws.send(data);
}
startWs() {
return __awaiter(this, void 0, void 0, function* () {
if (ws)
return;
try {
const protocols = yield (_getProtocols === null || _getProtocols === void 0 ? void 0 : _getProtocols(this.path));
if (_getProtocols && !protocols)
return this.startReconnect();
const socket = ws = this.openSocket(protocols !== null && protocols !== void 0 ? protocols : undefined);
socket.onmessage = (msg) => {
subscribers.forEach(s => s.onEvent(msg.data));
};
socket.onopen = () => {
this.stopReconnect();
subscribers.forEach(s => s.onConnect());
};
socket.onclose = () => {
subscribers.forEach(s => s.onDisconnect());
this.startReconnect();
};
}
catch (error) {
console.error(error);
this.startReconnect();
}
});
}
startReconnect() {
if (this.reconnectRef == null)
this.reconnectRef = setInterval(() => {
try {
ws === null || ws === void 0 ? void 0 : ws.close();
}
catch (_a) { }
ws = null;
this.startWs();
}, this.reconnectDelay);
}
stopReconnect() {
if (this.reconnectRef != null) {
clearInterval(this.reconnectRef);
this.reconnectRef = null;
}
}
keepAlive(s) {
const intervalRef = setInterval(() => {
const timeoutRef = setTimeout(() => {
subscribers.delete(s);
clearInterval(intervalRef);
s.onClose();
this.checkSubscriptions();
}, this.keepAliveTimeout);
s.ping(Comlink.proxy(() => {
clearTimeout(timeoutRef);
}));
}, this.keepAliveInterval);
return intervalRef;
}
checkSubscriptions() {
if (!subscribers.size) {
if (ws) {
ws.onclose = null;
this.stopReconnect();
if (this.closeRef)
clearTimeout(this.closeRef);
this.closeRef = null;
try {
ws.close();
}
catch (_a) { }
}
this.workerCtx.close();
}
}
openSocket(protocols) {
return new WebSocket(this.path.length ? `${this.apiUrlToJoin}/${this.path}` : this.apiUrl, protocols);
}
}
exports.WorkerWsController = WorkerWsController;