Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

databaseMigrationLog.ts

42 lines1.7 KB

1// The server logs these around pending migrations; the desktop reads them from its output tail,
2// which keeps only the last few thousand characters, so each progress line also marks a running upgrade.
3import type { DatabaseMigrationProgress } from "@t3tools/contracts";
4​
5export const DATABASE_MIGRATIONS_STARTED_MESSAGE = "Running database migrations";
6export const DATABASE_MIGRATION_PROGRESS_MESSAGE = "Upgrading database";
7export const DATABASE_MIGRATIONS_FINISHED_MESSAGE = "Migrations ran successfully";
8​
9export function isRunningDatabaseMigrations(output: string): boolean {
10 return (
11 Math.max(
12 output.lastIndexOf(DATABASE_MIGRATIONS_STARTED_MESSAGE),
13 output.lastIndexOf(DATABASE_MIGRATION_PROGRESS_MESSAGE),
14 ) > output.lastIndexOf(DATABASE_MIGRATIONS_FINISHED_MESSAGE)
15 );
17​
18export function databaseMigrationProgress(
19 output: string,
20 previous: DatabaseMigrationProgress | null = null,
21): DatabaseMigrationProgress | null {
22 if (!isRunningDatabaseMigrations(output)) {
23 return output.includes(DATABASE_MIGRATIONS_FINISHED_MESSAGE) ? null : previous;
24 }
25 const start = output.lastIndexOf(DATABASE_MIGRATIONS_STARTED_MESSAGE);
26 const step = output.lastIndexOf(DATABASE_MIGRATION_PROGRESS_MESSAGE);
27 if (step < start) return null;
28 const end = output.indexOf("\n", step);
29 const line = output.slice(step, end === -1 ? undefined : end);
30 const match =
31 /^Upgrading database \((\d+) of (\d+)\)/.exec(line) ??
32 /(?:progress=|"progress"\s*:\s*)"(\d+) of (\d+)"/.exec(line);
33 if (!match) return previous;
34 const current = Number(match[1]);
35 const total = Number(match[2]);
36 return Number.isSafeInteger(current) &&
37 Number.isSafeInteger(total) &&
38 current > 0 &&
39 current <= total
40 ? { current, total }
41 : previous;