Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/sync/syncdoc-info.ts
1452 views
1
import { client_db } from "@cocalc/util/db-schema/client-db";
2
3
export async function getSyncDocType({
4
client,
5
project_id,
6
path,
7
}): Promise<{ type: "db" | "string"; opts?: any }> {
8
// instead of just "querying the db" (i.e., conat in this case),
9
// we create the synctable. This avoids race conditions, since we
10
// can wait until data is written, and also abstracts away the
11
// internal structure.
12
let syncdocs;
13
try {
14
const string_id = client_db.sha1(project_id, path);
15
syncdocs = await client.synctable_conat(
16
{ syncstrings: [{ project_id, path, string_id, doctype: null }] },
17
{
18
stream: false,
19
atomic: false,
20
immutable: false,
21
},
22
);
23
let s = syncdocs.get_one();
24
if (s?.doctype == null) {
25
// wait until there is a syncstring and its doctype is set (this should be done by the frontend)
26
await syncdocs.wait(() => {
27
s = syncdocs.get_one();
28
return s?.doctype != null;
29
}, 10);
30
}
31
let doctype;
32
try {
33
doctype = JSON.parse(s.doctype);
34
} catch (err) {
35
console.warn("malformed doctype", err);
36
doctype = { type: "string" };
37
}
38
if (doctype.type !== "db" && doctype.type !== "string") {
39
// ensure valid type
40
console.warn("invalid docstype", doctype.type);
41
doctype.type = "string";
42
}
43
return doctype;
44
} finally {
45
// be sure to close this no matter what, since no value in watching changes.
46
syncdocs?.close();
47
}
48
}
49
50