feat: lab2 done

This commit is contained in:
2026-10-09 15:48:03 +03:00
parent f743ee10a2
commit 575f8ee386
104 changed files with 7038 additions and 1099 deletions
+75
View File
@@ -0,0 +1,75 @@
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import pg from 'pg';
import { MetricsService } from '../metrics/metrics.service.js';
import type { AppConfig } from '../config/app-config.schema.js';
@Injectable()
export class DatabaseClient implements OnModuleDestroy {
readonly pool: pg.Pool;
private readonly logger = new Logger(DatabaseClient.name);
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.pool = new pg.Pool({
connectionString: this.config.getOrThrow('DATABASE_URL'),
max: this.config.getOrThrow('DATABASE_POOL_MAX'),
connectionTimeoutMillis: this.config.getOrThrow(
'DATABASE_CONNECTION_TIMEOUT_MS',
),
statement_timeout: this.config.getOrThrow(
'DATABASE_STATEMENT_TIMEOUT_MS',
),
});
// Idle clients emit 'error' on the pool when the database drops; without a
// listener Node treats it as uncaught and terminates the process.
this.pool.on('error', (error: Error) => {
this.metrics.increment('database.pool_error');
this.logger.warn(`PostgreSQL pool error: ${error.message}`);
});
}
query<T extends pg.QueryResultRow = pg.QueryResultRow>(
label: string,
text: string,
values: readonly unknown[] = [],
): Promise<pg.QueryResult<T>> {
this.metrics.increment(label);
return this.pool.query<T>({ text, values: [...values] });
}
async health(): Promise<void> {
await this.query('health.database', 'SELECT 1');
}
async withTransaction<T>(
work: (client: pg.PoolClient) => Promise<T>,
): Promise<T> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
try {
await client.query('ROLLBACK');
} catch (rollbackError) {
this.metrics.increment('database.rollback_error');
this.logger.warn(
`Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`,
);
}
// Callers must see the operation error, not the rollback error.
throw error;
} finally {
client.release();
}
}
async onModuleDestroy(): Promise<void> {
await this.pool.end();
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MetricsModule } from '../metrics/metrics.module.js';
import { DatabaseClient } from './database.client.js';
@Module({
imports: [MetricsModule],
providers: [DatabaseClient],
exports: [DatabaseClient],
})
export class DatabaseModule {}
+63
View File
@@ -0,0 +1,63 @@
import { readdir, readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { DatabaseClient } from './database.client.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { parseAppConfig } from '../config/app-config.schema.js';
const migrationsDirectory = join(
dirname(fileURLToPath(import.meta.url)),
'migrations',
);
async function migrationFiles(): Promise<string[]> {
const files = await readdir(migrationsDirectory);
return files.filter((file) => /^\d+_.+\.sql$/u.test(file)).sort();
}
export async function runMigrations(database: DatabaseClient): Promise<void> {
await database.query(
'migrations.ensure_table',
`CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)`,
);
for (const version of await migrationFiles()) {
await database.withTransaction(async (client) => {
const applied = await client.query({
text: 'SELECT version FROM schema_migrations WHERE version = $1',
values: [version],
});
if (applied.rowCount) return;
const sql = await readFile(
join(migrationsDirectory, version),
'utf8',
);
await client.query(sql);
await client.query({
text: 'INSERT INTO schema_migrations (version) VALUES ($1)',
values: [version],
});
});
}
}
async function main(): Promise<void> {
const config = parseAppConfig(process.env as Record<string, unknown>);
const database = new DatabaseClient(
{
getOrThrow: (key: keyof typeof config) => config[key],
} as never,
new MetricsService(),
);
try {
await runMigrations(database);
} finally {
await database.onModuleDestroy();
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
@@ -0,0 +1,41 @@
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
message_version bigint NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT messages_sender_member_fk
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
ON DELETE RESTRICT
);
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
CREATE INDEX IF NOT EXISTS chat_members_user_chat_idx
ON chat_members (user_id, chat_id);
@@ -0,0 +1,5 @@
-- HTTP timestamps and keyset cursors use JavaScript millisecond precision.
-- Store the same precision so a returned cursor cannot point before its own row.
ALTER TABLE users ALTER COLUMN created_at TYPE timestamptz(3);
ALTER TABLE chats ALTER COLUMN created_at TYPE timestamptz(3);
ALTER TABLE messages ALTER COLUMN created_at TYPE timestamptz(3);