ws update

pull/17/head
DmitriyA 2025-05-23 04:06:37 -04:00
parent 37690dc79f
commit fcab8fa2b8
12 changed files with 11609 additions and 11397 deletions

22613
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@ import { Controller, Post, Get, Body, Res, Req, UnauthorizedException, UseGuards
import { AuthService } from './auth.service';
import { Response, Request } from 'express';
import { JwtAuthGuard } from './jwt-auth.guard';
import { Logger } from '@nestjs/common/services';
import { Logger } from '@nestjs/common';
@Controller('auth')
export class AuthController {
@ -13,19 +13,17 @@ export class AuthController {
@Get('check')
@UseGuards(JwtAuthGuard)
async checkAuth(@Req() req: Request) {
this.logger.debug(`Check auth request. Cookies: ${JSON.stringify(req.cookies)}`);
this.logger.debug(`Check auth request. Headers: ${JSON.stringify(req.headers)}`);
this.logger.debug(`Проверен запрос на авторизацию. Cookies: ${JSON.stringify(req.cookies)}`);
if (!req.user) {
this.logger.warn('Unauthorized access attempt');
throw new UnauthorizedException('Пользователь не аутентифицирован');
}
// Явно указываем тип для req.user
const user = req.user as { userId: number; username: string; login?: string };
const userWithoutPassword = { ...user };
this.logger.log(`User authenticated: ${user.username}`);
this.logger.log(`Аутентифицированный пользователь: ${user.username}`);
return {
isAuthenticated: true,
user: userWithoutPassword
@ -36,11 +34,8 @@ export class AuthController {
async login(
@Body() body: { login: string; password: string },
@Res({ passthrough: true }) res: Response,
@Req() req: Request
) {
this.logger.debug(`Login attempt for user: ${body.login}`);
this.logger.debug(`Request cookies: ${JSON.stringify(req.cookies)}`);
this.logger.debug(`Request headers: ${JSON.stringify(req.headers)}`);
const user = await this.authService.validateUser(body.login, body.password);
if (!user) {
@ -59,8 +54,6 @@ export class AuthController {
});
this.logger.log(`User ${body.login} successfully logged in`);
this.logger.debug(`Set cookie: access_token=${access_token.substring(0, 10)}...`);
return {
success: true,
user: {

39
src/auth/auth.dto.ts Normal file
View File

@ -0,0 +1,39 @@
/* import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
@ApiProperty({
example: 'admin@example.com',
description: 'User email or login',
required: true
})
login: string;
@ApiProperty({
example: 'yourStrongPassword123',
description: 'User password',
required: true,
minLength: 6
})
password: string;
}
export class CheckAuthResponse {
@ApiProperty({ example: true, description: 'Статус аутентификации' })
isAuthenticated: boolean;
@ApiProperty({
example: { userId: 1, username: 'admin', login: 'admin@example.com' },
description: 'Пользовательская информация без конфиденциальных данных'
})
user: {
userId: number;
username: string;
login?: string;
};
}
export class LogoutResponse {
@ApiProperty({ example: true, description: 'Статус успешного выхода из системы' })
success: boolean;
}
*/

View File

@ -7,6 +7,6 @@ export class AuthGuard implements CanActivate {
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
return !!request.user; // Проверка что пользователь аутентифицирован
return !!request.user;
}
}

View File

@ -13,7 +13,7 @@ import * as cookieParser from 'cookie-parser';
TypeOrmModule.forFeature([User]),
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET,
secret: process.env.JWT_SECRET || 'your-secret-key',
signOptions: { expiresIn: '1h' },
}),
],

View File

@ -24,7 +24,7 @@ export class AuthService {
async login(user: any) {
const payload = {
username: user.login, // Используем username в payload
username: user.login,
sub: user.id
};
return {

View File

@ -14,7 +14,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
},
]),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
secretOrKey: process.env.JWT_SECRET || 'your-secret-key',
});
}

View File

@ -1,15 +1,49 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { Logger } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const logger = new Logger('Bootstrap');
// Установка глобального префикса для всех маршрутов
app.setGlobalPrefix('api');
// Настройка Swagger
const config = new DocumentBuilder()
.setTitle('МУФ API')
.setDescription('API для сбора метрик и аутентификации')
.setVersion('1.0')
.addBearerAuth(
{
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
name: 'JWT',
description: 'Enter JWT token',
in: 'header',
},
'JWT-auth', // Это имя для схемы безопасности
)
.addCookieAuth('access_token') // Для cookie-based аутентификации
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document, {
swaggerOptions: {
persistAuthorization: true,
tagsSorter: 'alpha',
operationsSorter: 'alpha',
docExpansion: 'none',
filter: true,
},
customSiteTitle: 'MSF API Documentation',
});
// Настройка CORS
app.enableCors({
origin: [process.env.FRONTEND_URL, "http://dev.msf.enode"],
origin: [process.env.FRONTEND_URL, "http://dev.msf.enode"],
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
allowedHeaders: 'Content-Type, Authorization, X-Requested-With',
@ -18,6 +52,8 @@ async function bootstrap() {
optionsSuccessStatus: 204
});
await app.listen(process.env.PORT ?? 3000);
const port = process.env.PORT ?? 3000;
await app.listen(port);
logger.log(`Application is running on: http://localhost:${port}/api/docs`);
}
bootstrap();

View File

@ -1,11 +1,21 @@
import { Controller, Get, Query } from '@nestjs/common';
import { PrometheusService } from './prometheus.service';
import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
@ApiTags('Metrics - HTTP')
@Controller('metrics')
export class MetricsController {
constructor(private readonly prometheusService: PrometheusService) { }
@Get()
@ApiOperation({ summary: 'Получиние данных по конкретной метрике' })
@ApiQuery({ name: 'metric', required: true, description: 'Имя метрики для извлечения' })
@ApiQuery({ name: 'start', required: false, description: 'Начальная временная метка для запроса диапазона' })
@ApiQuery({ name: 'end', required: false, description: 'Конечная временная метка для запроса диапазона' })
@ApiQuery({ name: 'step', required: false, description: 'Размер шага для запроса диапазона' })
@ApiResponse({ status: 200, description: 'Успешно получены метрические данные' })
@ApiResponse({ status: 400, description: 'Указанные недопустимые параметры' })
@ApiResponse({ status: 500, description: 'Внутренняя ошибка сервера' })
async getMetrics(
@Query('metric') metric: string,
@Query('start') start: number,
@ -19,11 +29,15 @@ export class MetricsController {
}
@Get('/all')
@ApiOperation({ summary: 'Получение списка всех метрик' })
@ApiResponse({ status: 200, description: 'Список извлеченных метрик' })
async getAllMetrics() {
return this.prometheusService.fetchAllMetrics();
}
@Get('/all-values')
@ApiOperation({ summary: 'Получение списка всех метрик и их значения' })
@ApiResponse({ status: 200, description: 'Все метрики с полученными значениями' })
async getAllMetricsWithValues() {
return this.prometheusService.fetchAllMetricsWithValues();
}

View File

@ -1,4 +1,11 @@
import { WebSocketGateway, WebSocketServer, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect, SubscribeMessage } from '@nestjs/websockets';
import {
WebSocketGateway,
WebSocketServer,
OnGatewayInit,
OnGatewayConnection,
OnGatewayDisconnect,
SubscribeMessage,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { PrometheusService } from './prometheus.service';
import { Logger } from '@nestjs/common';
@ -20,7 +27,7 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
clients: Set<string>;
}>();
constructor(private readonly prometheusService: PrometheusService) { }
constructor(private readonly prometheusService: PrometheusService) {}
afterInit(server: Server) {
this.logger.log('WebSocket Gateway initialized');
@ -34,49 +41,89 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
this.activeSockets.delete(client.id);
// Очистка всех подписок этого клиента
for (const [metric, subscription] of this.metricSubscriptions) {
subscription.clients.delete(client.id);
if (subscription.clients.size === 0) {
subscription.stopUpdates();
this.metricSubscriptions.delete(metric);
}
}
}
@SubscribeMessage('unsubscribe-all')
handleUnsubscribeAll(client: Socket) {
for (const [metric, subscription] of this.metricSubscriptions) {
subscription.clients.delete(client.id);
if (subscription.clients.size === 0) {
subscription.stopUpdates();
this.metricSubscriptions.delete(metric);
}
}
}
@SubscribeMessage('get-metrics')
async handleGetMetrics(client: Socket, payload: any) {
const { metric, start, end, step, isRangeQuery } = payload;
const { metric, start, end, step, isRangeQuery, requestId, filters = {} } = payload;
try {
if (isRangeQuery) {
// Обработка разового запроса
const data = await this.prometheusService.fetchMetricsRange(metric, start, end, step);
client.emit(`metrics-range-${metric}`, data);
if (!metric) {
client.emit('metrics-error', {
error: 'Metric name is required',
requestId
});
return;
}
if (isRangeQuery) {
try {
const data = await this.prometheusService.fetchMetricsRange(metric, start, end, step, filters);
client.emit('metrics-data', { metric, data, requestId });
return;
} catch (error) {
client.emit('metrics-error', {
error: error.message,
requestId
});
return;
}
}
// Исправлено: передаем функцию, а не клиента
try {
const stopUpdates = await this.sendPeriodicUpdates(
metric,
step || 5000,
(data) => {
client.emit('metrics-data', { metric, data });
}
client.emit('metrics-data', { metric, data, requestId });
},
filters
);
client.on('disconnect', () => stopUpdates());
client.on('unsubscribe-metric', () => stopUpdates());
const cleanup = () => {
stopUpdates();
client.off('disconnect', cleanup);
client.off('unsubscribe-metric', cleanup);
};
client.on('disconnect', cleanup);
client.on('unsubscribe-metric', cleanup);
} catch (error) {
this.logger.error(`Error fetching metrics: ${error.message}`);
client.emit('metrics-error', {
metric,
error: error.message
error: error.message,
requestId
});
}
}
@SubscribeMessage('subscribe-metric')
async handleSubscribeMetric(client: Socket, payload: { metric: string, interval?: number }) {
const { metric } = payload;
async handleSubscribeMetric(client: Socket, payload: { metric: string; interval?: number }) {
const { metric, interval = 5000 } = payload;
if (!this.metricSubscriptions.has(metric)) {
const stopUpdates = await this.sendPeriodicUpdates(
metric,
payload.interval || 5000,
interval,
(data) => {
this.server.emit('metrics-data', { metric, data });
}
@ -87,11 +134,7 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
clients: new Set([client.id])
});
} else {
// Исправлено: добавлена проверка на существование подписки
const subscription = this.metricSubscriptions.get(metric);
if (subscription) {
subscription.clients.add(client.id);
}
this.metricSubscriptions.get(metric)?.clients.add(client.id);
}
const unsubscribe = () => {
@ -109,14 +152,18 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
client.on('unsubscribe-metric', unsubscribe);
}
// Метод для периодической отправки обновлений
async sendPeriodicUpdates(metric: string, interval: number, callback: (data: any) => void) {
async sendPeriodicUpdates(
metric: string,
interval: number,
callback: (data: any) => void,
filters: Record<string, string> = {}
) {
const timer = setInterval(async () => {
try {
const data = await this.prometheusService.fetchMetrics(metric);
callback(data); // Используем переданный callback
const data = await this.prometheusService.fetchMetricsWithFilters(metric, filters);
callback(data);
} catch (error) {
this.logger.error(`Error in periodic update for ${metric}: ${error.message}`);
this.logger.error(`Error in periodic update for ${metric}:`, error.message);
}
}, interval);
@ -125,4 +172,4 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
this.logger.log(`Stopped updates for ${metric}`);
};
}
}
}

View File

@ -1,9 +1,13 @@
export interface PrometheusMetric {
__name__?: string;
[key: string]: string | number | undefined;
__name__: string;
device?: string;
instance?: string;
job?: string;
source_id?: string;
status: string;
timestamp: number;
value: number;
type: string; // Тип метрики ("gauge", "counter", и т. д.)
description?: string; // Описание метрики
status?: string; // Добавляем поле для статуса
type: string;
description?: string;
[key: string]: string | number | undefined;
}

View File

@ -52,53 +52,131 @@ export class PrometheusService {
// Получаем данные метрики (текущие значения)
async fetchMetrics(metric: string): Promise<PrometheusMetric[]> {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query`, {
params: { query: metric },
})
);
try {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query`, {
params: { query: metric },
})
);
const metricType = await this.fetchMetricType(metric);
const metricDescription = await this.fetchMetricDescription(metric);
const metricType = await this.fetchMetricType(metric);
const metricDescription = await this.fetchMetricDescription(metric);
return response.data.data.result.map((entry): PrometheusMetric => ({
...entry.metric,
timestamp: entry.value[0] * 1000,
value: parseFloat(entry.value[1]),
type: metricType || 'unknown',
description: metricDescription,
status: entry.metric.status || 'green', // Используем статус из Prometheus или 'green' по умолчанию
}));
return response.data.data.result.map((entry): PrometheusMetric => ({
__name__: entry.metric.__name__ || metric,
device: entry.metric.device,
instance: entry.metric.instance,
job: entry.metric.job,
source_id: entry.metric.source_id,
status: entry.metric.status || '0', // По умолчанию '0' (аналог 'green' в старом формате)
timestamp: entry.value[0] * 1000,
value: parseFloat(entry.value[1]),
type: metricType || 'gauge', // По умолчанию 'gauge'
description: metricDescription,
...entry.metric // Добавляем остальные поля метрики
}));
} catch (error) {
console.error(`Error fetching metrics for ${metric}:`, error);
throw error;
}
}
async fetchMetricsWithFilters(metric: string, filters: Record<string, string>): Promise<PrometheusMetric[]> {
try {
const query = this.buildFilteredQuery(metric, filters);
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query`, {
params: { query }
})
);
const metricType = await this.fetchMetricType(metric);
const metricDescription = await this.fetchMetricDescription(metric);
return response.data.data.result.map((entry): PrometheusMetric => ({
__name__: entry.metric.__name__ || metric,
device: entry.metric.device,
instance: entry.metric.instance,
job: entry.metric.job,
source_id: entry.metric.source_id,
status: entry.metric.status || '0',
timestamp: entry.value[0] * 1000,
value: parseFloat(entry.value[1]),
type: metricType || 'gauge',
description: metricDescription,
...entry.metric
}));
} catch (error) {
console.error(`Error fetching metrics with filters for ${metric}:`, error);
throw error;
}
}
private buildFilteredQuery(metric: string, filters: Record<string, string>): string {
const filterParts = Object.entries(filters)
.filter(([_, value]) => value !== undefined && value !== null && value !== "")
.map(([key, value]) => {
// Для source_id добавляем module$ префикс, если его нет
if (key === 'source_id' && !value.startsWith('module$')) {
return `${key}="module$${value}"`;
}
return `${key}="${value}"`;
});
const query = filterParts.length > 0
? `${metric}{${filterParts.join(',')}}`
: metric;
console.log('Generated PromQL query:', query); // Добавьте этот лог
return query;
}
// Получаем данные метрики за интервал
async fetchMetricsRange(metric: string, start: number, end: number, step: number): Promise<PrometheusMetric[]> {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query_range`, {
params: {
query: metric,
start,
end,
step,
},
})
);
async fetchMetricsRange(metric: string, start: number, end: number, step: number, filters: Record<string, string> = {}): Promise<PrometheusMetric[]> {
const query = this.buildFilteredQuery(metric, filters); // <-- ВНЕ try
try {
console.log('Executing range query:', { query, start, end, step });
const metricType = await this.fetchMetricType(metric);
const metricDescription = await this.fetchMetricDescription(metric);
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query_range`, {
params: {
query,
start,
end,
step: step.toString()
},
})
);
return response.data.data.result.flatMap((entry) =>
entry.values.map((value): PrometheusMetric => ({
...entry.metric,
timestamp: value[0] * 1000,
value: parseFloat(value[1]),
type: metricType || 'unknown',
description: metricDescription,
status: entry.metric.status || 'green', // Используем статус из Prometheus или 'green' по умолчанию
}))
);
const metricType = await this.fetchMetricType(metric);
const metricDescription = await this.fetchMetricDescription(metric);
return response.data.data.result.flatMap((entry) =>
entry.values.map((value): PrometheusMetric => ({
__name__: entry.metric.__name__ || metric,
device: entry.metric.device,
instance: entry.metric.instance,
job: entry.metric.job,
source_id: entry.metric.source_id,
status: entry.metric.status || '0',
timestamp: value[0] * 1000,
value: parseFloat(value[1]),
type: metricType || 'gauge',
description: metricDescription,
...entry.metric
}))
);
} catch (error) {
console.error('Error in fetchMetricsRange:', {
error: error.response?.data || error.message,
query,
filters
});
throw error;
}
}
// Получаем список всех метрик
async fetchAllMetrics(): Promise<string[]> {
const response = await lastValueFrom(