Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/project/blobs.ts
1447 views
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
*/
9
10
import { getLogger } from "@cocalc/backend/logger";
11
import * as message from "@cocalc/util/message";
12
import { defaults, required, uuid } from "@cocalc/util/misc";
13
import { CB } from "@cocalc/util/types/database";
14
15
const winston = getLogger("blobs");
16
17
type BlobCB = CB<any, { sha1: string; error: string }>;
18
19
type CBEntry = [BlobCB, string];
20
21
const _save_blob_callbacks: { [key: string]: CBEntry[] } = {};
22
23
interface Opts {
24
sha1: string;
25
cb: BlobCB;
26
timeout?: number;
27
}
28
29
export function receive_save_blob_message(opts: Opts): void {
30
// temporarily used by file_session_manager
31
opts = defaults(opts, {
32
sha1: required,
33
cb: required,
34
timeout: 30, // seconds; maximum time in seconds to wait for response message
35
});
36
winston.debug(`receive_save_blob_message: ${opts.sha1}`);
37
const { sha1 } = opts;
38
const id = uuid();
39
_save_blob_callbacks[sha1] ??= [];
40
_save_blob_callbacks[sha1].push([opts.cb, id]);
41
42
// Timeout functionality -- send a response after opts.timeout seconds,
43
// in case no hub responded.
44
if (!opts.timeout) {
45
return;
46
}
47
48
const f = function (): void {
49
const v = _save_blob_callbacks[sha1];
50
if (v != null) {
51
const mesg = message.save_blob({
52
sha1,
53
error: `timed out after local hub waited for ${opts.timeout} seconds`,
54
});
55
56
const w: CBEntry[] = [];
57
for (let x of v) {
58
// this is O(n) instead of O(1), but who cares since n is usually 1.
59
if (x[1] === id) {
60
x[0](mesg);
61
} else {
62
w.push(x);
63
}
64
}
65
66
if (w.length === 0) {
67
delete _save_blob_callbacks[sha1];
68
} else {
69
_save_blob_callbacks[sha1] = w;
70
}
71
}
72
};
73
74
setTimeout(f, opts.timeout * 1000);
75
}
76
77
export function handle_save_blob_message(mesg): void {
78
winston.debug(`handle_save_blob_message: ${mesg.sha1}`);
79
const v = _save_blob_callbacks[mesg.sha1];
80
if (v != null) {
81
for (let x of v) {
82
x[0](mesg);
83
}
84
delete _save_blob_callbacks[mesg.sha1];
85
}
86
}
87
88