Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/database/postgres/delete-patches.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45// This manages deleting patches. The underlying problem is that there could be a large number of patches, which stalls the DB.6// It's better to keep the number of row deletions small, to speed up the operation, only lock less rows for a shorter amount of time, etc.78import debug from "debug";9const L = debug("hub:db:delete-patches");10import { PostgreSQL } from "./types";11import { delay } from "awaiting";1213// max number of patches to delete at once – 10000 should take a few seconds14const MAX_AT_ONCE = parseInt(15process.env.SYNCSTRING_DELETE_MAX_AT_ONCE ?? "10000"16);17// delay between deleting a chunk of patches18const DELAY_S = parseInt(process.env.SYNCSTRING_DELETE_DELAY_CHUNK_S ?? "1");1920interface DeletePatchesOpts {21db: PostgreSQL;22string_id: string;23cb?: Function;24}2526async function patchset_limit(opts: {27db: PostgreSQL;28string_id: string;29}): Promise<string | undefined> {30const { db, string_id } = opts;31const q = await db.async_query({32query: "SELECT time FROM patches",33where: { "string_id = $::CHAR(40)": string_id },34limit: 1,35offset: MAX_AT_ONCE,36});37if (q.rows.length == 0) {38return undefined;39} else {40return q.rows[0].time;41}42}4344export async function delete_patches(opts: DeletePatchesOpts): Promise<void> {45const { db, string_id, cb } = opts;4647while (true) {48const limit = await patchset_limit({ db, string_id });4950L(`deleting patches string_id='${string_id}' until limit='${limit}'`);51const where = { "string_id = $::CHAR(40)": string_id };52if (limit != null) {53where["time <= $::TIMESTAMP"] = limit;54}55await db.async_query({56query: "DELETE FROM patches",57where,58timeout_s: 300, // delete ops could take a bit59});60if (limit != null) {61await delay(DELAY_S * 1000);62} else {63break;64}65}6667if (typeof cb === "function") cb();68}697071