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/sync/open-synctables.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/*6All SyncTables that are currently open and being managed in this project.78*/910import { callback } from "awaiting";11import { SyncTable } from "@cocalc/sync/table";12import { is_array } from "@cocalc/util/misc";1314const open_synctables: { [key: string]: SyncTable } = {};15const wait_for: { [key: string]: Function[] } = {};1617export function key(query): string {18const table: string = Object.keys(query)[0];19if (!table) {20throw Error("no table in query");21}22let c = query[table];23if (c == null) {24throw Error("invalid query format");25}26if (is_array(c)) {27c = c[0];28}29const string_id = c.string_id;30if (string_id == null) {31throw Error(32"open-syncstring-tables is only for queries with a specified string_id field" +33"(patches, cursors, eval_inputs, eval_outputs, etc.): query=" +34JSON.stringify(query)35);36}37return `${table}.${string_id}`;38}3940export function register_synctable(query: any, synctable: SyncTable): void {41const k = key(query);42open_synctables[k] = synctable;43synctable.on("closed", function () {44delete open_synctables[k];45});46if (wait_for[k] != null) {47handle_wait_for(k, synctable);48}49}5051export async function get_synctable(query, client): Promise<SyncTable> {52const k = key(query);53const log = client.dbg(`get_synctable(key=${k})`);54log("open_synctables = ", Object.keys(open_synctables));55log("key=", k, "query=", query);56const s = open_synctables[k];57if (s != null) {58// easy - already have it.59log("done");60return s;61}62function f(cb: Function) {63log("f got called");64add_to_wait_for(k, cb);65}66log("waiting...");67const synctable = await callback(f);68log(`got the synctable! ${JSON.stringify((synctable as any).query)}`);69return synctable;70}7172function add_to_wait_for(k: string, cb: Function): void {73if (wait_for[k] == null) {74wait_for[k] = [cb];75} else {76wait_for[k].push(cb);77}78}7980function handle_wait_for(k: string, synctable: SyncTable): void {81if (wait_for[k] == null) {82return;83}84const v: Function[] = wait_for[k];85delete wait_for[k];86for (const cb of v) {87cb(undefined, synctable);88}89}909192