use structed logging

This commit is contained in:
evanpelle
2024-09-01 12:51:20 -07:00
parent 735a2ae57b
commit 026a0cddbe
10 changed files with 292 additions and 31 deletions
+54 -15
View File
@@ -27,6 +27,8 @@ class Client {
private random = new PseudoRandom(1234)
private ip: Promise<string | null> = null
constructor() {
this.lobbiesContainer = document.getElementById('lobbies-container');
}
@@ -35,6 +37,7 @@ class Client {
setFavicon()
this.terrainMap = loadTerrainMap()
this.startLobbyPolling()
this.ip = getClientIP()
setupUsernameCallback((username) => {
console.log('Username updated:', username);
if (this.game != null) {
@@ -100,7 +103,7 @@ class Client {
}
}
private joinLobby(lobby: Lobby) {
private async joinLobby(lobby: Lobby) {
const lobbyButton = document.getElementById('lobby-button');
if (lobbyButton) {
this.isLobbyHighlighted = !this.isLobbyHighlighted;
@@ -115,21 +118,26 @@ class Client {
if (this.game != null) {
return;
}
this.terrainMap.then(tm => {
this.game = createClientGame(getUsername(), new PseudoRandom(Date.now()).nextID(), lobby.id, getConfig(), tm);
this.game.join();
const g = this.game;
window.addEventListener('beforeunload', function (event) {
console.log('Browser is closing');
g.stop();
});
})
const [terrainMap, clientIP] = await Promise.all([
this.terrainMap,
this.ip
]);
console.log(`got ip ${clientIP}`)
this.game = createClientGame(
getUsername(),
new PseudoRandom(Date.now()).nextID(), // TODO this can cause dup ids
clientIP,
lobby.id,
getConfig(),
terrainMap
);
this.game.join();
const g = this.game;
window.addEventListener('beforeunload', function (event) {
console.log('Browser is closing');
g.stop();
});
}
}
function getUsername(): string {
@@ -154,6 +162,37 @@ function setupUsernameCallback(callback: (username: string) => void): void {
}
async function getClientIP(timeoutMs: number = 1000): Promise<string | null> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
const response: Response = await fetch('https://api.ipify.org?format=json', {
signal: controller.signal
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: {ip: string} = await response.json();
return data.ip;
} catch (error) {
if (error instanceof Error) {
if (error.name === 'AbortError') {
console.error('Request timed out');
} else {
console.error('Error fetching IP:', error.message);
}
} else {
console.error('An unknown error occurred');
}
return null;
} finally {
clearTimeout(timeoutId);
}
}
// Initialize the client when the DOM is loaded
+4 -1
View File
@@ -12,7 +12,7 @@ import {TerrainRenderer} from "./graphics/TerrainRenderer";
export function createClientGame(name: string, clientID: ClientID, gameID: GameID, config: Config, terrainMap: TerrainMap): ClientGame {
export function createClientGame(name: string, clientID: ClientID, ip: string | null, gameID: GameID, config: Config, terrainMap: TerrainMap): ClientGame {
let eventBus = new EventBus()
let game = createGame(terrainMap, eventBus, config)
let terrainRenderer = new TerrainRenderer(game)
@@ -21,6 +21,7 @@ export function createClientGame(name: string, clientID: ClientID, gameID: GameI
return new ClientGame(
name,
clientID,
ip,
gameID,
eventBus,
game,
@@ -47,6 +48,7 @@ export class ClientGame {
constructor(
public playerName: string,
private id: ClientID,
private clientIP: string | null,
private gameID: GameID,
private eventBus: EventBus,
private gs: Game,
@@ -67,6 +69,7 @@ export class ClientGame {
type: "join",
gameID: this.gameID,
clientID: this.id,
clientIP: this.clientIP,
lastTurn: this.turns.length
})
)
+2 -2
View File
@@ -114,9 +114,9 @@ export const ClientIntentMessageSchema = ClientBaseMessageSchema.extend({
export const ClientJoinMessageSchema = ClientBaseMessageSchema.extend({
type: z.literal('join'),
clientID: z.string(),
clientIP: z.string().nullable(),
gameID: z.string(),
// The last turn the client saw.
lastTurn: z.number()
lastTurn: z.number() // The last turn the client saw.
})
export const ClientLeaveMessageSchema = ClientBaseMessageSchema.extend({
+5 -1
View File
@@ -3,5 +3,9 @@ import {ClientID} from '../core/Schemas';
export class Client {
constructor(public readonly id: ClientID, public readonly ws: WebSocket) { }
constructor(
public readonly id: ClientID,
public readonly ip: string | null,
public readonly ws: WebSocket
) { }
}
+7
View File
@@ -2,6 +2,7 @@ import {ClientMessage, ClientMessageSchema, Intent, ServerStartGameMessage, Serv
import {Config} from "../core/configuration/Config";
import {Client} from "./Client";
import WebSocket from 'ws';
import {slog} from "./StructuredLog";
export enum GamePhase {
@@ -30,6 +31,12 @@ export class GameServer {
public addClient(client: Client, lastTurn: number) {
console.log(`game ${this.id} adding client ${client.id}`)
slog('client_joined_game', `client ${client.id} (re)joining game ${this.id}`, {
clientID: client.id,
clientIP: client.ip,
gameID: this.id,
isRejoin: lastTurn > 0
})
// Remove stale client if this is a reconnect
this.clients = this.clients.filter(c => c.id != client.id)
this.clients.push(client)
+3 -3
View File
@@ -8,6 +8,7 @@ import {Client} from './Client';
import {ClientMessage, ClientMessageSchema} from '../core/Schemas';
import {GamePhase} from './GameServer';
import {getConfig} from '../core/configuration/Config';
import {LogSeverity, slog} from './StructuredLog';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -31,11 +32,10 @@ app.get('/lobbies', (req, res) => {
wss.on('connection', (ws) => {
ws.on('message', (message: string) => {
console.log(`got message ${message}`)
const clientMsg: ClientMessage = ClientMessageSchema.parse(JSON.parse(message))
slog('websocket_msg', 'server received websocket message', clientMsg, LogSeverity.DEBUG)
if (clientMsg.type == "join") {
console.log('got join request')
gm.addClient(new Client(clientMsg.clientID, ws), clientMsg.gameID, clientMsg.lastTurn)
gm.addClient(new Client(clientMsg.clientID, clientMsg.clientIP, ws), clientMsg.gameID, clientMsg.lastTurn)
}
// TODO: send error message
})
+21
View File
@@ -0,0 +1,21 @@
export enum LogSeverity {
DEBUG = 'DEBUG',
INFO = 'INFO',
WARN = 'WARN',
ERROR = 'ERROR',
FATAL = 'FATAL'
}
export function slog(eventType: string, description, data: any, severity = LogSeverity.INFO): void {
const logEntry = {
eventType: eventType,
description: description,
severity: severity,
data: data
};
if (process.env.GAME_ENV == 'dev') {
console.log(description)
} else {
console.log(JSON.stringify(logEntry));
}
}