UNPKG

@cocalc/project

Version:
86 lines (85 loc) 2.77 kB
"use strict"; /* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ Object.defineProperty(exports, "__esModule", { value: true }); exports.symmetric_channel = exports.browser_symmetric_channel = void 0; /* Channels used for maybe nothing right now. I thought this would be useful, but it hasn't yet turned out to be. */ const events_1 = require("events"); const sync_tables = {}; function get_name(name) { return `symmetric_channel:${name}`; } async function browser_symmetric_channel(_, primus, logger, name) { name = get_name(name); // The code below is way more complicated because SymmetricChannel // can be made *before* this sync function is called. If that // happens, and we also have to set the channel of SymmetricChannel. if (sync_tables[name] !== undefined && sync_tables[name].channel !== undefined) { // fully initialized return name; } const channel = primus.channel(name); let local; if (sync_tables[name] !== undefined) { local = sync_tables[name].local; local.channel = channel; sync_tables[name].channel = channel; } else { local = new SymmetricChannel(channel); sync_tables[name] = { local, channel, }; } channel.on("connection", function (spark) { // Now handle a connection logger.debug("sync", name, `conn from ${spark.address.ip} -- ${spark.id}`); spark.on("end", function () { logger.debug("sync", name, `closed ${spark.address.ip} -- ${spark.id}`); }); spark.on("data", function (data) { local._data_from_spark(data); channel.forEach(function (spark0, id) { if (id !== spark.id) { spark0.write(data); } }); }); }); return name; } exports.browser_symmetric_channel = browser_symmetric_channel; class SymmetricChannel extends events_1.EventEmitter { constructor(channel) { super(); this.channel = channel; } // Returns true if immediate write succeeds write(data) { if (this.channel !== undefined) { return this.channel.write(data); } return false; } _data_from_spark(data) { this.emit("data", data); } } function symmetric_channel(name) { name = get_name(name); if (sync_tables[name] !== undefined) { return sync_tables[name].local; } const local = new SymmetricChannel(undefined); sync_tables[name] = { local }; return local; } exports.symmetric_channel = symmetric_channel; //# sourceMappingURL=symmetric_channel.js.map