Initial commit
CI / Сборка (push) Canceled after 0s
CI / Деплой на стейджинг (push) Canceled after 0s
CI / Проверка кода (push) Canceled after 0s
CI / Сборка (pull_request) Successful in 1m33s
Стенд master
CI / Деплой на стейджинг (pull_request) Successful in 8s
CI / Проверка кода (pull_request) Successful in 1m32s

This commit is contained in:
arswarog committed 2026-11-10 17:22:12 +03:00
commit 1420aad1ae
92 files changed
+19114

No files matched your search

+221
View File
@@ -0,0 +1,221 @@
import { type Dirent, existsSync, readdirSync, readFileSync, writeFileSync } from 'fs';
import * as path from 'path';
import { format, resolveConfig } from 'prettier';
export const workspaceRoot = path.resolve(__dirname, '..');
const apiSrcDir = path.join(workspaceRoot, 'apps', 'api', 'src');
const outputFile = path.join(apiSrcDir, 'migrations.ts');
// Миграции лежат по модулям: apps/api/src/<module>/migrations/<timestamp>-<name>.ts.
const MIGRATIONS_DIR_NAME = 'migrations';
const HEADER =
'// Файл сгенерирован автоматически (tools/buildDataSource.ts). Не редактировать вручную.';
// Только именованный экспорт: render() строит именованный импорт, поэтому
// `export default class` всё равно дал бы не компилирующийся файл — пусть лучше
// падает на понятном "не найден export class".
const EXPORT_CLASS_RE = /export\s+class\s+(\w+)/g;
// Ровно 13 цифр: TypeORM берёт timestamp как parseInt(className.substr(-13))
// (MigrationExecutor.getMigrations) и падает, если там не число.
const TIMESTAMP_PREFIX_RE = /^(\d{13})-/;
// Файлы-спутники, которые могут лежать рядом с миграциями и миграциями не являются.
const COMPANION_FILE_RE = /\.(d|spec|test)\.ts$/;
export interface MigrationEntry {
/** Путь относительно apps/api/src, с расширением .ts */
file: string;
className: string;
}
export function fail(prefix: string, message: string): never {
console.error(`[${prefix}] ОШИБКА: ${message}`);
process.exit(1);
}
// Объявление, а не стрелочная константа: сужение типов по never-возврату
// (files после catch, timestampMatch после проверки) работает только для function.
function failBuild(message: string): never {
fail('buildDataSource', message);
}
// Список каталогов миграций: любой apps/api/src/**/migrations.
function findMigrationsDirs(dir: string): string[] {
let entries: Dirent[];
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
failBuild(`не удалось прочитать директорию: ${dir}`);
}
const found: string[] = [];
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === 'node_modules') {
continue;
}
const fullPath = path.join(dir, entry.name);
if (entry.name === MIGRATIONS_DIR_NAME) {
found.push(fullPath);
continue;
}
found.push(...findMigrationsDirs(fullPath));
}
return found;
}
// Порядок — по timestamp из имени файла (возрастание): имя файла начинается ровно с
// 13 цифр, поэтому лексикографическая сортировка совпадает с числовой. Одинаковые
// имена файлов в разных модулях упорядочиваются по пути.
export function readMigrations(): MigrationEntry[] {
const migrationFiles = findMigrationsDirs(apiSrcDir)
.flatMap((dir) =>
readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isFile())
.map((entry) => path.posix.join(path.relative(apiSrcDir, dir), entry.name))
.filter((file) => file.endsWith('.ts') && !COMPANION_FILE_RE.test(file)),
)
.sort((a, b) => {
const byName = path.posix.basename(a).localeCompare(path.posix.basename(b));
return byName !== 0 ? byName : a.localeCompare(b);
});
// Каталогов migrations может не быть ни одного: проект может ещё не иметь
// миграций. Тогда список пустой, а сборка не падает.
const entries = migrationFiles.map((file): MigrationEntry => {
const timestampMatch = TIMESTAMP_PREFIX_RE.exec(path.posix.basename(file));
if (!timestampMatch) {
failBuild(
`имя файла "${file}" не начинается с 13-значного timestamp ` +
'(ожидается формат "<13 цифр>-<name>.ts")',
);
}
const source = readFileSync(path.join(apiSrcDir, file), 'utf8');
const classNames = [...source.matchAll(EXPORT_CLASS_RE)].map((match) => match[1]);
if (classNames.length === 0) {
failBuild(`в файле "${file}" не найден "export class"`);
}
// Брать первый попавшийся нельзя: TypeORM выводит timestamp из имени класса,
// и вспомогательный экспорт выше миграции молча подменил бы порядок.
if (classNames.length > 1) {
failBuild(
`в файле "${file}" найдено несколько "export class" (${classNames.join(', ')}); ` +
'в файле миграции должен быть ровно один экспортируемый класс',
);
}
const className = classNames[0];
// Инвариант TypeORM: он игнорирует порядок массива и сортирует по
// parseInt(className.substr(-13)). Если суффикс класса расходится с префиксом
// файла, миграции применяются не в том порядке, а в таблице migrations
// оказывается чужой timestamp.
if (className.slice(-13) !== timestampMatch[1]) {
failBuild(
`в файле "${file}" класс "${className}" оканчивается на ` +
`"${className.slice(-13)}", а имя файла — на "${timestampMatch[1]}"; ` +
'TypeORM берёт timestamp из имени класса, суффиксы обязаны совпадать',
);
}
return { file, className };
});
const seen = new Map<string, string>();
for (const entry of entries) {
const duplicate = seen.get(entry.className);
if (duplicate) {
failBuild(
`класс "${entry.className}" объявлен дважды: "${duplicate}" и "${entry.file}"`,
);
}
seen.set(entry.className, entry.file);
}
return entries;
}
function render(entries: MigrationEntry[]): string {
if (entries.length === 0) {
return `${HEADER}\n\nexport const migrations = [];\n`;
}
const imports = entries
.map(
(entry) =>
`import { ${entry.className} } from './${entry.file.slice(0, -'.ts'.length)}';`,
)
.join('\n');
const list = entries.map((entry) => ` ${entry.className},`).join('\n');
return `${HEADER}\n\n${imports}\n\nexport const migrations = [\n${list}\n];\n`;
}
async function main(): Promise<void> {
const entries = readMigrations();
const prettierConfig = await resolveConfig(outputFile);
const formatted = await format(render(entries), {
...prettierConfig,
filepath: outputFile,
parser: 'typescript',
});
const relativeOutput = path.relative(workspaceRoot, outputFile);
const current = existsSync(outputFile) ? readFileSync(outputFile, 'utf8') : null;
const upToDate = current === formatted;
console.log(`[buildDataSource] миграций найдено: ${entries.length}`);
// --check ничего не пишет и падает при расхождении. Сравнение идёт с тем же
// отформатированным текстом, что и запись, поэтому CI не нужно поднимать
// git diff и отличать «список устарел» от «git не смог прочитать репозиторий».
if (process.argv.includes('--check')) {
if (!upToDate) {
failBuild(
`${relativeOutput} расходится со списком файлов миграций. ` +
'Перегенерируйте: yarn nx run api:db-migrations-list — и закоммитьте результат',
);
}
console.log(`[buildDataSource] актуален: ${relativeOutput}`);
return;
}
// Пишем только при реальном изменении: build зависит от этого таргета, а
// api:serve следит за src/ — перезапись с тем же содержимым дёргает mtime
// и загоняет watch-режим в бесконечный цикл пересборок.
if (upToDate) {
console.log(`[buildDataSource] без изменений: ${relativeOutput}`);
return;
}
writeFileSync(outputFile, formatted, 'utf8');
console.log(`[buildDataSource] записано: ${relativeOutput}`);
}
// Модуль импортируется из tools/checkDataSource.ts ради readMigrations(),
// поэтому генерация запускается только при прямом вызове файла.
if (require.main === module) {
main().catch((error) => {
failBuild(error instanceof Error ? error.message : String(error));
});
}
+73
View File
@@ -0,0 +1,73 @@
// Проверка собранного артефакта apps/api/dist/data-source.js.
// Запускается после `nx run api:build` в CI (ci.yaml и production.yaml).
//
// Проверяем не «список непустой», а то, что состав миграций в собранном бандле
// посимвольно совпадает со списком, который даёт генератор по файлам на диске.
// Ожидаемый список берётся вызовом readMigrations() из tools/buildDataSource.ts,
// а не разбором сгенерированного им же файла: правила фильтрации и валидации
// имён живут в одном месте (там же проверяется инвариант TypeORM
// parseInt(className.substr(-13)) === префикс имени файла).
import * as path from 'path';
import { fail, readMigrations, workspaceRoot } from './buildDataSource';
const DATA_SOURCE_FILE = path.join(workspaceRoot, 'apps', 'api', 'dist', 'data-source.js');
// Объявление, а не стрелочная константа: сужение типов по never-возврату
// (loaded после catch) работает только для function.
function failCheck(message: string): never {
fail('checkDataSource', message);
}
function loadDataSource(): { options: { migrations?: unknown } } {
let loaded;
try {
loaded = require(DATA_SOURCE_FILE);
} catch (error) {
failCheck(
`не удалось загрузить ${DATA_SOURCE_FILE}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
// Бандл может отдать как сам DataSource, так и { default: DataSource } —
// зависит от output.library.export, поэтому разворачиваем оба варианта.
const dataSource = loaded?.default ?? loaded;
// Проверяем поведение, а не имя конструктора: имя пережило бы только
// отключённую минификацию, а поведение — это то, чем пользуется typeorm CLI.
if (typeof dataSource?.initialize !== 'function' || typeof dataSource.options !== 'object') {
failCheck(`ожидался DataSource, получено: ${JSON.stringify(dataSource)}`);
}
return dataSource;
}
function main(): void {
const { migrations } = loadDataSource().options;
const expected = readMigrations().map((entry) => entry.className);
// Элементы списка — классы миграций; у не-класса name окажется undefined и
// расхождение выведется в том же диффе, что и любое другое.
const actual = Array.isArray(migrations)
? migrations.map((migration) => (migration as { name?: string })?.name)
: [migrations];
if (actual.join(',') !== expected.join(',')) {
failCheck(
'состав миграций в бандле расходится с файлами на диске.\n' +
` в бандле (${actual.length}): ${actual.join(', ')}\n` +
` на диске (${expected.length}): ${expected.join(', ')}\n` +
' перегенерируйте список (yarn nx run api:db-migrations-list) и пересоберите api',
);
}
console.log(
`[checkDataSource] OK: миграций в бандле ${expected.length}, ` +
'состав совпадает с файлами миграций',
);
}
main();
+205
View File
@@ -0,0 +1,205 @@
import { readdir, readFile } from 'fs/promises';
import path, { resolve } from 'path';
import { config } from 'dotenv';
import { omit } from 'lodash';
import { Pool, PoolClient } from 'pg';
interface SnapshotEntity {
table: string;
arrayFields?: string[];
omitFields?: string[];
updateExisting?: boolean;
}
export async function applySnapshot(
snapshot: Record<string, Array<object>>,
connection: PoolClient,
) {
const entities: SnapshotEntity[] = [
{ table: 'admin_settings' },
{ table: 'users' },
{ table: 'projects' },
{ table: 'canonical_brand_data' },
{ table: 'entity_audit_logs' },
{ table: 'entity_completeness_tracking' },
{ table: 'entity_facts' },
{ table: 'entity_home_pages' },
{ table: 'external_connectors' },
{ table: 'external_profiles' },
{ table: 'file' },
{ table: 'json_ld_schemas' },
{ table: 'migration_1772363000000_default_user_role_users' },
{ table: 'nap_consistency_scores' },
{ table: 'project_entities' },
{ table: 'project_entity_data' },
{ table: 'project_licenses' },
{ table: 'project_members' },
{ table: 'project_metrics' },
{ table: 'project_products' },
{ table: 'project_team_members' },
{ table: 'roles' },
{ table: 'sync_logs' },
{ table: 'user_roles' },
{ table: 'website_checks' },
{ table: 'wikidata_edit_queue' },
{ table: 'wikidata_entities' },
{ table: 'subscription_plans' },
{ table: 'brand_questions', arrayFields: ['questions'] },
{ table: 'public_metric_requests', arrayFields: ['keywords', 'modelsUsed'] },
];
await nuke(entities, connection);
if (!entities) {
console.log('no entities');
}
if (!snapshot) {
console.log('no snaphot');
}
for (const updateTable of entities.map(genUpdateTable)) {
await updateTable(snapshot, connection);
}
}
function genUpdateTable(snapshotEntity: SnapshotEntity) {
let processRow = (row: object) => row;
const save = snapshotEntity.updateExisting ? update : insert;
if ('omitFields' in snapshotEntity && snapshotEntity.omitFields?.length) {
processRow = (row: object) => omit(row, snapshotEntity.omitFields!);
}
return async (snapshot: Record<string, Array<object>>, connection: PoolClient) => {
const data = snapshot[snapshotEntity.table].map(processRow);
const ids = snapshot[snapshotEntity.table]
.map((row: any): number => row?.id)
.filter(Boolean);
const lastId = Math.max(...ids);
if (!data) {
return;
}
await save(snapshotEntity, data, connection);
if (Number.isFinite(lastId)) {
await connection.query(
`ALTER SEQUENCE IF EXISTS ${snapshotEntity.table}_id_seq RESTART WITH ${lastId + 1}`,
);
}
};
}
async function insert(entity: SnapshotEntity, rows: object[], connection: PoolClient) {
if (!rows.length) {
return;
}
const keys = Object.keys(rows[0]).map((column) => `"${column}"`);
const values = rows.map((row) => serializeObjects(row, entity.arrayFields));
const placeholders = values.map(wrapReturnedInBrackets(genRowPlaceholders));
const query = `INSERT INTO ${entity.table} (${keys}) VALUES ${placeholders}`;
return connection.query(query, values.flat());
}
async function update(entity: SnapshotEntity, rows: object[], connection: PoolClient) {
if (!rows.length) {
return;
}
const keys = Object.keys(rows[0]).map((column) => `"${column}"`);
const promises = rows.map((row: any) => {
const placeholders = genRowPlaceholders(keys).map((val, idx) => keys[idx] + '=' + val);
const values = serializeObjects(row, entity.arrayFields);
return connection.query(
`UPDATE ${entity.table} SET ${placeholders} WHERE id=${row.id};`,
values,
);
});
return Promise.all(promises);
}
function wrapReturnedInBrackets(fn: (...args: any[]) => any) {
return (...args: any) => '(' + fn(...args) + ')';
}
function genRowPlaceholders(row: any[], offsetByRows?: number) {
const rowIdx = offsetByRows || 0;
return row.map((_, colIdx) => row.length * rowIdx + colIdx + 1).map((idx) => '$' + idx);
}
function serializeObjects(row: any, leaveAsIs: string[] = []) {
return Object.entries(row).map(([key, value]) => {
if (leaveAsIs.includes(key)) {
return value;
}
if (typeof value !== 'object' || value === null) {
return value;
}
return JSON.stringify(value);
});
}
async function nuke(entities: SnapshotEntity[], connection: PoolClient) {
const tables = new Set(entities.map(({ table }) => table));
return connection
.query(`TRUNCATE TABLE ${[...tables].join(',')} RESTART IDENTITY CASCADE;`)
.catch(console.error);
}
export async function readSnapshot(basePath: string) {
const files = await readdir(basePath);
const entries = await Promise.all(
files.map(async (filename) => {
const tableName = filename.split('.').slice(0, -1).join('.');
const text = await readFile(resolve(basePath, filename), { encoding: 'utf8' });
const rows = JSON.parse(text);
const entry = [tableName, rows];
return entry;
}),
);
return Object.fromEntries(entries) as Record<string, Array<object>>;
}
const nodeEnv = process.env.NODE_ENV || 'production';
config({ path: path.resolve(process.cwd(), `.env.${nodeEnv}`) });
config({ path: path.resolve(process.cwd(), '.env') });
const pool = new Pool({
host: process.env.POSTGRES_HOST,
port: +process.env.POSTGRES_PORT!,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
});
const snapshotDir = path.join(__dirname, '../db-snapshot');
async function main() {
const db = await pool.connect();
console.log('ДБ подключена');
const snapshot = await readSnapshot(snapshotDir);
await applySnapshot(snapshot, db);
console.log('Снимок применён к базе данных');
db.release();
await pool.end();
}
main();
+91
View File
@@ -0,0 +1,91 @@
import { access, mkdir, rm, writeFile } from 'fs/promises';
import path from 'path';
import { config } from 'dotenv';
import { Pool, types } from 'pg';
const nodeEnv = process.env.NODE_ENV || 'production';
config({ path: path.resolve(process.cwd(), `.env.${nodeEnv}`) });
config({ path: path.resolve(process.cwd(), '.env') });
const pool = new Pool({
host: process.env.POSTGRES_HOST,
port: +process.env.POSTGRES_PORT!,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
});
const snapshotDir = path.join(__dirname, '../db-snapshot');
const excludedTables = ['migrations', 'oauth_providers'];
// так как в ДБ используются поля без часового пояса, а по умолчанию pg будет ставить UTC
function disableTZProcessing() {
types.setTypeParser(1114, function (stringValue) {
return stringValue;
});
}
async function main() {
disableTZProcessing();
const db = await pool.connect();
console.log('ДБ подключена');
await db.query("SET timezone TO 'GMT';");
const tables = await db
.query(
`
SELECT c.relname AS tablename, (array_agg(a.attname))[1] AS key
FROM pg_index i
JOIN pg_class c ON c.oid = i.indrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(i.indkey)
WHERE i.indisprimary
AND n.nspname = 'public'
AND c.relname NOT IN (${excludedTables.map(wrapInQuotes).join(',')})
GROUP BY c.relname
ORDER BY c.relname;
`,
)
.then((response): { tablename: string; key: string }[] => response.rows);
const promises = tables.map(async (table) => {
const data = await db.query(`SELECT * FROM ${table.tablename} ORDER BY "${table.key}"`);
return { ...table, rows: data.rows };
});
const entries = await Promise.all(promises);
await access(snapshotDir).then(
async () => {
await rm(snapshotDir, { recursive: true });
},
() => {},
);
await mkdir(snapshotDir, { recursive: true });
const report = await Promise.all(
entries.map(async (table) =>
writeFile(
path.join(snapshotDir, table.tablename + '.json'),
JSON.stringify(table.rows, null, 4) + '\n',
'utf8',
),
),
);
console.log('Сохранено таблиц: `\x1b[0;32m' + report.length + '\x1b[0m`');
db.release();
await pool.end();
}
function wrapInQuotes(text: string) {
return "'" + text + "'";
}
main();