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/util/failing-to-save.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
/*
7
If we are having repeated hash mismatches when trying to save a particular path,
8
then this function will return true. This can be used by the caller to
9
reconnect and fix everything. This is basically a stupid workaround for a subtle
10
but very annoying bug that I don't know how to reproduce or fix...
11
*/
12
13
// Trigger a failure if there have been THRESHOLD.fails during
14
// the last THRESHOLD.interval_s seconds.
15
const THRESHOLD = { fails: 3, interval_s: 60 };
16
17
interface PathState {
18
path: string;
19
failures: number[];
20
}
21
22
function is_failing(x: PathState): boolean {
23
const cutoff = new Date().getTime() - THRESHOLD.interval_s * 1000;
24
const failures: number[] = [];
25
let t: number;
26
for (t of x.failures) {
27
if (t >= cutoff) {
28
failures.push(t);
29
}
30
}
31
if (failures.length >= THRESHOLD.fails) {
32
x.failures = [];
33
return true;
34
} else {
35
x.failures = failures;
36
return false;
37
}
38
}
39
40
const state: { [key: string]: PathState } = {};
41
42
export function failing_to_save(
43
path: string,
44
hash: number,
45
expected_hash?: number
46
): boolean {
47
if (expected_hash == null) {
48
return false;
49
}
50
if (!state[path]) {
51
state[path] = { path: path, failures: [] };
52
}
53
54
if (hash != expected_hash) {
55
state[path].failures.push(new Date().getTime());
56
return is_failing(state[path]);
57
}
58
59
// definitely NOT failing.
60
return false;
61
}
62
63