CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/sync/table/global-cache.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
const json_stable_stringify = require("json-stable-stringify");
7
import { delay } from "awaiting";
8
9
import { SyncTable } from "./synctable";
10
11
const synctables = {};
12
13
// for debugging; in particular, verify that synctables are freed.
14
// Do not leave in production; could be slight security risk.
15
//# window?.synctables = synctables
16
17
export function synctable(
18
query,
19
options,
20
client,
21
throttle_changes: undefined | number,
22
use_cache: boolean = true
23
): SyncTable {
24
if (options == null) {
25
options = [];
26
}
27
if (!use_cache) {
28
return new SyncTable(query, options, client, throttle_changes);
29
}
30
31
const cache_key = json_stable_stringify({
32
query,
33
options,
34
throttle_changes,
35
});
36
let S: SyncTable | undefined = synctables[cache_key];
37
if (S != null) {
38
if (S.get_state() === "connected") {
39
// same behavior as newly created synctable
40
emit_connected_in_next_tick(S);
41
}
42
} else {
43
S = synctables[cache_key] = new SyncTable(
44
query,
45
options,
46
client,
47
throttle_changes
48
);
49
S.cache_key = cache_key;
50
}
51
S.reference_count += 1;
52
return S;
53
}
54
55
async function emit_connected_in_next_tick(S: SyncTable): Promise<void> {
56
await delay(0);
57
if (S.get_state() === "connected") {
58
S.emit("connected");
59
}
60
}
61
62
export function global_cache_decref(S: SyncTable): boolean {
63
if (S.reference_count && S.cache_key !== undefined) {
64
S.reference_count -= 1;
65
if (S.reference_count <= 0) {
66
delete synctables[S.cache_key];
67
return false; // not in use
68
} else {
69
return true; // still in use
70
}
71
}
72
return false;
73
}
74
75