From b6003f7e87db5ee8a19f38c724de9311f715b5d8 Mon Sep 17 00:00:00 2001 From: zkldi <20380519+zkldi@users.noreply.github.com> Date: Sun, 17 Jul 2022 16:17:51 +0100 Subject: [PATCH] refactor: use a util for script exec --- server/src/scripts/clone-and-anonymise-db.ts | 40 +++++++++++++------ server/src/scripts/folders/folder-cache.ts | 11 ++--- .../scripts/iidx-tierlist/get-sp12-data.ts | 9 +---- server/src/scripts/init-sequence-docs.ts | 9 +---- server/src/scripts/set-indexes.ts | 11 ++--- .../scripts/state-sync/dedupe-score-ids.ts | 15 ++----- .../scripts/state-sync/recalc-all-scores.ts | 13 +----- .../state-sync/recalc-game-profiles.ts | 9 +---- .../src/scripts/state-sync/recalc-sessions.ts | 9 +---- .../src/scripts/state-sync/update-all-pbs.ts | 12 +----- server/src/scripts/sync-database.ts | 10 +---- server/src/scripts/validate-database.ts | 21 ++-------- server/src/utils/misc.ts | 15 +++++++ 13 files changed, 71 insertions(+), 113 deletions(-) diff --git a/server/src/scripts/clone-and-anonymise-db.ts b/server/src/scripts/clone-and-anonymise-db.ts index fb48a7aa1..347db312e 100644 --- a/server/src/scripts/clone-and-anonymise-db.ts +++ b/server/src/scripts/clone-and-anonymise-db.ts @@ -102,20 +102,34 @@ function CloneDB(nsFrom: string, nsTo: string) { } if (require.main === module) { - CloneDB(options.nsFrom, options.nsTo); - - // Don't run any risks -- there's no way we're ever accidentally anonymising the production database. - // any nsTo argument MUST start with anon- if (!options.nsTo.startsWith("anon-")) { - AnonymiseDB(options.nsTo) - .then(() => { - logger.info(`Anonymised database successfully. Saved to ${options.nsTo}.`); - process.exit(0); - }) - .catch((err: unknown) => { - logger.error(`Failed to anonymise database.`, { err }, () => { - process.exit(1); + logger.error( + `Tried to clone to and anonymise ${options.nsTo}, which is illegal. Anonymised DBs must start with anon-.`, + () => { + process.exit(1); + } + ); + } else { + // else guard here is important, as the above statement doesn't immediately halt + // execution + // -- return isn't valid at top level, and i can't be bothered wrapping this in + // a useless fn. + CloneDB(options.nsFrom, options.nsTo); + + // Don't run any risks -- there's no way we're ever accidentally anonymising the production database. + // any nsTo argument MUST start with anon- + + if (options.nsTo.startsWith("anon-")) { + AnonymiseDB(options.nsTo) + .then(() => { + logger.info(`Anonymised database successfully. Saved to ${options.nsTo}.`); + process.exit(0); + }) + .catch((err: unknown) => { + logger.error(`Failed to anonymise database.`, { err }, () => { + process.exit(1); + }); }); - }); + } } } diff --git a/server/src/scripts/folders/folder-cache.ts b/server/src/scripts/folders/folder-cache.ts index d700c0833..5a0cfdfc8 100644 --- a/server/src/scripts/folders/folder-cache.ts +++ b/server/src/scripts/folders/folder-cache.ts @@ -1,12 +1,9 @@ import { InitaliseFolderChartLookup } from "../../utils/folder"; import CreateLogCtx from "lib/logger/logger"; +import { WrapScriptPromise } from "utils/misc"; const logger = CreateLogCtx(__filename); -InitaliseFolderChartLookup() - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error(`Failed to initialise folder chart lookup.`, { err }, () => { - process.exit(1); - }); - }); +if (require.main === module) { + WrapScriptPromise(InitaliseFolderChartLookup(), logger); +} diff --git a/server/src/scripts/iidx-tierlist/get-sp12-data.ts b/server/src/scripts/iidx-tierlist/get-sp12-data.ts index 1e927b614..faa1dc420 100644 --- a/server/src/scripts/iidx-tierlist/get-sp12-data.ts +++ b/server/src/scripts/iidx-tierlist/get-sp12-data.ts @@ -5,6 +5,7 @@ import db from "external/mongo/db"; import CreateLogCtx from "lib/logger/logger"; import fetch from "node-fetch"; import p from "prudence"; +import { WrapScriptPromise } from "utils/misc"; import { FindChartWithPTDF } from "utils/queries/charts"; import { FindSongOnTitle } from "utils/queries/songs"; import type { ChartDocument, Difficulties, integer } from "tachi-common"; @@ -221,11 +222,5 @@ async function HumanisedTitleLookup(originalTitle: string) { } if (require.main === module) { - FetchSP12Data() - .then(process.exit(0)) - .catch((err) => { - logger.error(`Failed to fetch sp12 data. ${err}`, err, () => { - process.exit(1); - }); - }); + WrapScriptPromise(FetchSP12Data(), logger); } diff --git a/server/src/scripts/init-sequence-docs.ts b/server/src/scripts/init-sequence-docs.ts index 399c5735d..ea123b954 100644 --- a/server/src/scripts/init-sequence-docs.ts +++ b/server/src/scripts/init-sequence-docs.ts @@ -1,14 +1,9 @@ import { InitSequenceDocs } from "external/mongo/sequence-docs"; import CreateLogCtx from "lib/logger/logger"; +import { WrapScriptPromise } from "utils/misc"; const logger = CreateLogCtx(__filename); if (require.main === module) { - InitSequenceDocs() - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error(`Failed to initialise sequence documents.`, { err }, () => { - process.exit(1); - }); - }); + WrapScriptPromise(InitSequenceDocs(), logger); } diff --git a/server/src/scripts/set-indexes.ts b/server/src/scripts/set-indexes.ts index 6dd2d7030..c8a5d0d10 100644 --- a/server/src/scripts/set-indexes.ts +++ b/server/src/scripts/set-indexes.ts @@ -2,6 +2,7 @@ import { SetIndexes } from "../external/mongo/indexes"; import { Command } from "commander"; import CreateLogCtx from "lib/logger/logger"; +import { WrapScriptPromise } from "utils/misc"; const program = new Command(); @@ -16,10 +17,6 @@ program.option( program.parse(process.argv); const options: { db: string; reset?: boolean } = program.opts(); -SetIndexes(options.db, options.reset === true) - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error(`Failed to set indexes.`, { err }, () => { - process.exit(1); - }); - }); +if (require.main === module) { + WrapScriptPromise(SetIndexes(options.db, options.reset === true), logger); +} diff --git a/server/src/scripts/state-sync/dedupe-score-ids.ts b/server/src/scripts/state-sync/dedupe-score-ids.ts index 750ece312..738525996 100644 --- a/server/src/scripts/state-sync/dedupe-score-ids.ts +++ b/server/src/scripts/state-sync/dedupe-score-ids.ts @@ -1,5 +1,6 @@ import db from "external/mongo/db"; import CreateLogCtx from "lib/logger/logger"; +import { WrapScriptPromise } from "utils/misc"; import type { IObjectID } from "monk"; import type { integer } from "tachi-common"; @@ -34,14 +35,6 @@ async function DedupeScoreIDs() { } } -DedupeScoreIDs() - .then(() => { - logger.info(`Finished deduping score IDs.`, () => { - process.exit(0); - }); - }) - .catch((err: unknown) => { - logger.error(`Failed to dedupe score IDs.`, { err }, () => { - process.exit(1); - }); - }); +if (require.main === module) { + WrapScriptPromise(DedupeScoreIDs(), logger); +} diff --git a/server/src/scripts/state-sync/recalc-all-scores.ts b/server/src/scripts/state-sync/recalc-all-scores.ts index 637e418cc..d1c279e4c 100644 --- a/server/src/scripts/state-sync/recalc-all-scores.ts +++ b/server/src/scripts/state-sync/recalc-all-scores.ts @@ -1,18 +1,9 @@ import CreateLogCtx from "lib/logger/logger"; import { RecalcAllScores } from "utils/calculations/recalc-scores"; +import { WrapScriptPromise } from "utils/misc"; const logger = CreateLogCtx(__filename); if (require.main === module) { - RecalcAllScores() - .then(() => { - logger.info(`Successfully recalced all scores.`, () => { - process.exit(0); - }); - }) - .catch((err: unknown) => { - logger.error(`Failed to recalc all scores.`, { err }, () => { - process.exit(1); - }); - }); + WrapScriptPromise(RecalcAllScores(), logger); } diff --git a/server/src/scripts/state-sync/recalc-game-profiles.ts b/server/src/scripts/state-sync/recalc-game-profiles.ts index 4efeaa5cb..bb98a9d9c 100644 --- a/server/src/scripts/state-sync/recalc-game-profiles.ts +++ b/server/src/scripts/state-sync/recalc-game-profiles.ts @@ -2,6 +2,7 @@ import db from "external/mongo/db"; import CreateLogCtx from "lib/logger/logger"; import { UpdateUsersGamePlaytypeStats } from "lib/score-import/framework/user-game-stats/update-ugs"; +import { WrapScriptPromise } from "utils/misc"; import { FormatUserDoc } from "utils/user"; import type { Game, Playtype, ScoreDocument } from "tachi-common"; @@ -42,11 +43,5 @@ export async function RecalcGameProfiles() { } if (require.main === module) { - RecalcGameProfiles() - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error(`Failed to recalc game profiles.`, { err }, () => { - process.exit(1); - }); - }); + WrapScriptPromise(RecalcGameProfiles(), logger); } diff --git a/server/src/scripts/state-sync/recalc-sessions.ts b/server/src/scripts/state-sync/recalc-sessions.ts index 2e5ba736e..d8bcf4625 100644 --- a/server/src/scripts/state-sync/recalc-sessions.ts +++ b/server/src/scripts/state-sync/recalc-sessions.ts @@ -1,14 +1,9 @@ import CreateLogCtx from "lib/logger/logger"; import { RecalcSessions } from "utils/calculations/recalc-sessions"; +import { WrapScriptPromise } from "utils/misc"; const logger = CreateLogCtx(__filename); if (require.main === module) { - RecalcSessions() - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error(`Failed to recalc sessions.`, { err }, () => { - process.exit(1); - }); - }); + WrapScriptPromise(RecalcSessions(), logger); } diff --git a/server/src/scripts/state-sync/update-all-pbs.ts b/server/src/scripts/state-sync/update-all-pbs.ts index d6b33d794..ca833e8e6 100644 --- a/server/src/scripts/state-sync/update-all-pbs.ts +++ b/server/src/scripts/state-sync/update-all-pbs.ts @@ -1,18 +1,10 @@ /* eslint-disable no-await-in-loop */ import CreateLogCtx from "lib/logger/logger"; import { UpdateAllPBs } from "utils/calculations/recalc-scores"; +import { WrapScriptPromise } from "utils/misc"; const logger = CreateLogCtx(__filename); if (require.main === module) { - UpdateAllPBs() - .then(() => { - logger.info(`Successfully updated all PBs.`); - process.exit(0); - }) - .catch((err: unknown) => { - logger.error(`Failed to update all PBs.`, { err }, () => { - process.exit(1); - }); - }); + WrapScriptPromise(UpdateAllPBs(), logger); } diff --git a/server/src/scripts/sync-database.ts b/server/src/scripts/sync-database.ts index 5d9073bf3..20a61af4c 100644 --- a/server/src/scripts/sync-database.ts +++ b/server/src/scripts/sync-database.ts @@ -12,7 +12,7 @@ import { UpdateMilestoneSubscriptions } from "lib/targets/milestones"; import { RecalcAllScores } from "utils/calculations/recalc-scores"; import { UpdateGameSongIDCounter } from "utils/db"; import { InitaliseFolderChartLookup } from "utils/folder"; -import { ArrayDiff, IsSupported } from "utils/misc"; +import { ArrayDiff, IsSupported, WrapScriptPromise } from "utils/misc"; import type { KtLogger } from "lib/logger/logger"; import type { BulkWriteOperation, DeleteWriteOpResultObject } from "mongodb"; import type { ICollection } from "monk"; @@ -385,11 +385,5 @@ async function SynchroniseDBWithSeeds() { } if (require.main === module) { - SynchroniseDBWithSeeds() - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error(String(err), () => { - process.exit(1); - }); - }); + WrapScriptPromise(SynchroniseDBWithSeeds(), logger); } diff --git a/server/src/scripts/validate-database.ts b/server/src/scripts/validate-database.ts index 9103fdc42..bd2836a0a 100644 --- a/server/src/scripts/validate-database.ts +++ b/server/src/scripts/validate-database.ts @@ -4,6 +4,7 @@ import { Command } from "commander"; import { monkDB } from "external/mongo/db"; import { DatabaseSchemas } from "external/mongo/schemas"; import CreateLogCtx from "lib/logger/logger"; +import { WrapScriptPromise } from "utils/misc"; import { FormatPrError } from "utils/prudence"; import type { Databases } from "external/mongo/db"; import type { FindResult } from "monk"; @@ -64,24 +65,8 @@ export async function ValidateAllCollections() { if (require.main === module) { if (typeof options.collection === "string") { // @hack This should be typechecked and warned about outside of ValidateCollection. - ValidateCollection(options.collection as Databases) - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error( - `Failed to validate collection ${options.collection}?`, - { err }, - () => { - process.exit(1); - } - ); - }); + WrapScriptPromise(ValidateCollection(options.collection as Databases), logger); } else { - ValidateAllCollections() - .then(() => process.exit(0)) - .catch((err: unknown) => { - logger.error(`Failed to validate all collections?`, { err }, () => { - process.exit(1); - }); - }); + WrapScriptPromise(ValidateAllCollections(), logger); } } diff --git a/server/src/utils/misc.ts b/server/src/utils/misc.ts index 329c4efaf..d48b990aa 100644 --- a/server/src/utils/misc.ts +++ b/server/src/utils/misc.ts @@ -4,6 +4,7 @@ import { GetGameConfig } from "tachi-common"; import { exec } from "child_process"; import crypto from "crypto"; import { URL } from "url"; +import type { KtLogger } from "lib/logger/logger"; import type { Game, GamePTConfig, integer, Playtype } from "tachi-common"; // https://github.com/sindresorhus/escape-string-regexp/blob/main/index.js @@ -259,3 +260,17 @@ export function IsNullish(maybeValue: T | null | undefined): maybeValue is nu export function IsRecord(maybeRecord: unknown): maybeRecord is Record { return typeof maybeRecord === "object" && maybeRecord !== null; } + +/** + * Wrap a promise in an error handler that exits the process safely, and logs + * when it completes. + */ +export function WrapScriptPromise(promise: Promise, logger: KtLogger) { + promise + .then(() => logger.info(`Finished executing.`, () => process.exit(0))) + .catch((err: unknown) => { + logger.error(`Failed executing.`, { err }, () => { + process.exit(1); + }); + }); +}