Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/project/browser-websocket/symmetric_channel.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/*6Channels used for maybe nothing right now.78I thought this would be useful, but it hasn't yet turned out to be.9*/1011import { EventEmitter } from "events";1213const sync_tables = {};1415function get_name(name: string): string {16return `symmetric_channel:${name}`;17}1819export async function browser_symmetric_channel(20_: any,21primus: any,22logger: any,23name: string24): Promise<string> {25name = get_name(name);2627// The code below is way more complicated because SymmetricChannel28// can be made *before* this sync function is called. If that29// happens, and we also have to set the channel of SymmetricChannel.3031if (32sync_tables[name] !== undefined &&33sync_tables[name].channel !== undefined34) {35// fully initialized36return name;37}3839const channel = primus.channel(name);40let local: SymmetricChannel;4142if (sync_tables[name] !== undefined) {43local = sync_tables[name].local;44local.channel = channel;45sync_tables[name].channel = channel;46} else {47local = new SymmetricChannel(channel);48sync_tables[name] = {49local,50channel,51};52}5354channel.on("connection", function (spark: any): void {55// Now handle a connection56logger.debug("sync", name, `conn from ${spark.address.ip} -- ${spark.id}`);57spark.on("end", function () {58logger.debug("sync", name, `closed ${spark.address.ip} -- ${spark.id}`);59});60spark.on("data", function (data) {61local._data_from_spark(data);62channel.forEach(function (spark0, id) {63if (id !== spark.id) {64spark0.write(data);65}66});67});68});6970return name;71}7273class SymmetricChannel extends EventEmitter {74channel: any;7576constructor(channel?: any) {77super();78this.channel = channel;79}8081// Returns true if immediate write succeeds82write(data: any): boolean {83if (this.channel !== undefined) {84return this.channel.write(data);85}86return false;87}8889_data_from_spark(data: any): void {90this.emit("data", data);91}92}9394export function symmetric_channel(name: string): SymmetricChannel {95name = get_name(name);96if (sync_tables[name] !== undefined) {97return sync_tables[name].local;98}99const local = new SymmetricChannel(undefined);100sync_tables[name] = { local };101return local;102}103104105