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/project/blobs.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2023 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
Saving blobs to hub
8
CoCalc: Collaborative web-based SageMath, Jupyter, LaTeX and Terminals.
9
Copyright 2015, SageMath, Inc., GPL v3.
10
*/
11
12
import { getLogger } from "@cocalc/backend/logger";
13
import * as message from "@cocalc/util/message";
14
import { defaults, required, uuid } from "@cocalc/util/misc";
15
import { CB } from "@cocalc/util/types/database";
16
17
const winston = getLogger("blobs");
18
19
type BlobCB = CB<any, { sha1: string; error: string }>;
20
21
type CBEntry = [BlobCB, string];
22
23
const _save_blob_callbacks: { [key: string]: CBEntry[] } = {};
24
25
interface Opts {
26
sha1: string;
27
cb: BlobCB;
28
timeout?: number;
29
}
30
31
export function receive_save_blob_message(opts: Opts): void {
32
// temporarily used by file_session_manager
33
opts = defaults(opts, {
34
sha1: required,
35
cb: required,
36
timeout: 30, // seconds; maximum time in seconds to wait for response message
37
});
38
winston.debug(`receive_save_blob_message: ${opts.sha1}`);
39
const { sha1 } = opts;
40
const id = uuid();
41
_save_blob_callbacks[sha1] ??= [];
42
_save_blob_callbacks[sha1].push([opts.cb, id]);
43
44
// Timeout functionality -- send a response after opts.timeout seconds,
45
// in case no hub responded.
46
if (!opts.timeout) {
47
return;
48
}
49
50
const f = function (): void {
51
const v = _save_blob_callbacks[sha1];
52
if (v != null) {
53
const mesg = message.save_blob({
54
sha1,
55
error: `timed out after local hub waited for ${opts.timeout} seconds`,
56
});
57
58
const w: CBEntry[] = [];
59
for (let x of v) {
60
// this is O(n) instead of O(1), but who cares since n is usually 1.
61
if (x[1] === id) {
62
x[0](mesg);
63
} else {
64
w.push(x);
65
}
66
}
67
68
if (w.length === 0) {
69
delete _save_blob_callbacks[sha1];
70
} else {
71
_save_blob_callbacks[sha1] = w;
72
}
73
}
74
};
75
76
setTimeout(f, opts.timeout * 1000);
77
}
78
79
export function handle_save_blob_message(mesg): void {
80
winston.debug(`handle_save_blob_message: ${mesg.sha1}`);
81
const v = _save_blob_callbacks[mesg.sha1];
82
if (v != null) {
83
for (let x of v) {
84
x[0](mesg);
85
}
86
delete _save_blob_callbacks[mesg.sha1];
87
}
88
}
89
90