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