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/sync/table/global-cache.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45const json_stable_stringify = require("json-stable-stringify");6import { delay } from "awaiting";78import { SyncTable } from "./synctable";910const synctables = {};1112// for debugging; in particular, verify that synctables are freed.13// Do not leave in production; could be slight security risk.14//# window?.synctables = synctables1516export function synctable(17query,18options,19client,20throttle_changes: undefined | number,21use_cache: boolean = true22): SyncTable {23if (options == null) {24options = [];25}26if (!use_cache) {27return new SyncTable(query, options, client, throttle_changes);28}2930const cache_key = json_stable_stringify({31query,32options,33throttle_changes,34});35let S: SyncTable | undefined = synctables[cache_key];36if (S != null) {37if (S.get_state() === "connected") {38// same behavior as newly created synctable39emit_connected_in_next_tick(S);40}41} else {42S = synctables[cache_key] = new SyncTable(43query,44options,45client,46throttle_changes47);48S.cache_key = cache_key;49}50S.reference_count += 1;51return S;52}5354async function emit_connected_in_next_tick(S: SyncTable): Promise<void> {55await delay(0);56if (S.get_state() === "connected") {57S.emit("connected");58}59}6061export function global_cache_decref(S: SyncTable): boolean {62if (S.reference_count && S.cache_key !== undefined) {63S.reference_count -= 1;64if (S.reference_count <= 0) {65delete synctables[S.cache_key];66return false; // not in use67} else {68return true; // still in use69}70}71return false;72}737475