feat: Complete NestJS backend scaffold — 22 modules, 39 entities, WebSocket gateway
All checks were successful
Test Asgard Runner / test (push) Successful in 3s
All checks were successful
Test Asgard Runner / test (push) Successful in 3s
Full backend rewrite from Rust/Axum to NestJS/TypeScript. - 22 feature modules (auth, servers, wipes, maps, plugins, players, console, chat, team, notifications, settings, schedules, analytics, alerts, status, store, webstore, admin, setup, migration, users, licenses) - 39 TypeORM entities matching PostgreSQL schema (12 migrations) - Common infrastructure: JWT/RBAC guards, decorators, exception filter - NATS service with pub/sub/request-reply - Socket.IO WebSocket gateway with NATS bridge - Docker: NestJS Dockerfile + updated docker-compose.yml - Zero compile errors (npx tsc --noEmit clean) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
116
backend-nest/src/modules/console/console.gateway.ts
Normal file
116
backend-nest/src/modules/console/console.gateway.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import {
|
||||
WebSocketGateway,
|
||||
WebSocketServer,
|
||||
SubscribeMessage,
|
||||
OnGatewayConnection,
|
||||
OnGatewayDisconnect,
|
||||
MessageBody,
|
||||
ConnectedSocket,
|
||||
} from '@nestjs/websockets';
|
||||
import { Server, Socket } from 'socket.io';
|
||||
import { Logger, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
/**
|
||||
* Console Gateway
|
||||
*
|
||||
* Provides real-time WebSocket connectivity for server console I/O.
|
||||
* Clients connect with JWT token in query params, join a room by license_id,
|
||||
* and can send/receive console commands and output.
|
||||
*/
|
||||
@WebSocketGateway({ namespace: '/ws', cors: true })
|
||||
export class ConsoleGateway implements OnGatewayConnection, OnGatewayDisconnect {
|
||||
@WebSocketServer()
|
||||
server: Server;
|
||||
|
||||
private readonly logger = new Logger(ConsoleGateway.name);
|
||||
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Handle client connection
|
||||
* Extract JWT from query param, validate, and join room by license_id
|
||||
*/
|
||||
async handleConnection(client: Socket) {
|
||||
try {
|
||||
const token = client.handshake.query.token as string;
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('No token provided');
|
||||
}
|
||||
|
||||
// Verify JWT
|
||||
const payload = this.jwtService.verify(token);
|
||||
const licenseId = payload.license_id;
|
||||
|
||||
if (!licenseId) {
|
||||
throw new UnauthorizedException('Invalid token: no license_id');
|
||||
}
|
||||
|
||||
// Store license_id on socket for later use
|
||||
client.data.licenseId = licenseId;
|
||||
client.data.userId = payload.sub;
|
||||
|
||||
// Join room specific to this license
|
||||
await client.join(licenseId);
|
||||
|
||||
this.logger.log(`Client ${client.id} connected to license ${licenseId}`);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error';
|
||||
this.logger.error(`Connection failed: ${message}`);
|
||||
client.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle client disconnection
|
||||
*/
|
||||
handleDisconnect(client: Socket) {
|
||||
const licenseId = client.data.licenseId;
|
||||
this.logger.log(`Client ${client.id} disconnected from license ${licenseId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle console input from client
|
||||
* Forward the command to NATS for execution on the game server
|
||||
*/
|
||||
@SubscribeMessage('console_input')
|
||||
async handleConsoleInput(
|
||||
@ConnectedSocket() client: Socket,
|
||||
@MessageBody() data: { command: string },
|
||||
) {
|
||||
const licenseId = client.data.licenseId;
|
||||
|
||||
if (!data.command) {
|
||||
return { error: 'Command is required' };
|
||||
}
|
||||
|
||||
this.logger.debug(`Console input from ${licenseId}: ${data.command}`);
|
||||
|
||||
// Forward to NATS
|
||||
await this.natsService.sendServerCommand(licenseId, 'command', {
|
||||
command: data.command,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send console output or event to all clients in a license room
|
||||
*/
|
||||
sendToLicense(licenseId: string, event: string, data: any) {
|
||||
this.server.to(licenseId).emit(event, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast console output to a specific license
|
||||
* This method would be called by a NATS subscriber when output is received
|
||||
*/
|
||||
broadcastConsoleOutput(licenseId: string, output: string) {
|
||||
this.sendToLicense(licenseId, 'console_output', { output });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user