Path: blob/master/src/packages/database/postgres/delete-patches.ts
1503 views
/*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 getLogger from "@cocalc/backend/logger";9import type { PostgreSQL } from "./types";10import { delay } from "awaiting";1112const logger = getLogger("database:delete-patches");1314// max number of patches to delete at once – 10000 should take a few seconds15const MAX_AT_ONCE = parseInt(16process.env.SYNCSTRING_DELETE_MAX_AT_ONCE ?? "10000",17);18// delay between deleting a chunk of patches19const DELAY_S = parseInt(process.env.SYNCSTRING_DELETE_DELAY_CHUNK_S ?? "1");2021interface DeletePatchesOpts {22db: PostgreSQL;23string_id: string;24cb?: Function;25}2627async function patchset_limit(opts: {28db: PostgreSQL;29string_id: string;30}): Promise<string | undefined> {31const { db, string_id } = opts;32const q = await db.async_query({33query: "SELECT time FROM patches",34where: { "string_id = $::CHAR(40)": string_id },35limit: 1,36offset: MAX_AT_ONCE,37});38if (q.rows.length == 0) {39return undefined;40} else {41return q.rows[0].time;42}43}4445export async function delete_patches(opts: DeletePatchesOpts): Promise<void> {46const { db, string_id, cb } = opts;4748while (true) {49const limit = await patchset_limit({ db, string_id });5051logger.debug(52`deleting patches string_id='${string_id}' until limit='${limit}'`,53);54const where = { "string_id = $::CHAR(40)": string_id };55if (limit != null) {56where["time <= $::TIMESTAMP"] = limit;57}58await db.async_query({59query: "DELETE FROM patches",60where,61timeout_s: 300, // delete ops could take a bit62});63if (limit != null) {64await delay(DELAY_S * 1000);65} else {66break;67}68}6970if (typeof cb === "function") cb();71}727374