add winston logger (#289)

This commit is contained in:
evanpelle
2025-03-18 14:36:30 -07:00
committed by GitHub
parent bd2c270ba3
commit 6499569240
8 changed files with 362 additions and 75 deletions
+246 -1
View File
@@ -55,6 +55,7 @@
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4",
"wheelnav": "^1.7.1",
"winston": "^3.17.0",
"ws": "^8.18.0",
"zod": "^3.23.8"
},
@@ -73,6 +74,7 @@
"@types/sinon": "^17.0.3",
"@types/systeminformation": "^3.23.1",
"@types/uuid": "^10.0.0",
"@types/winston": "^2.4.4",
"@types/ws": "^8.5.11",
"autoprefixer": "^10.4.20",
"babel-jest": "^29.7.0",
@@ -2876,6 +2878,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/@colors/colors": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",
"integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==",
"license": "MIT",
"engines": {
"node": ">=0.1.90"
}
},
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
@@ -2900,6 +2911,17 @@
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
"integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==",
"license": "MIT",
"dependencies": {
"colorspace": "1.1.x",
"enabled": "2.0.x",
"kuler": "^2.0.0"
}
},
"node_modules/@datastructures-js/heap": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@datastructures-js/heap/-/heap-4.3.3.tgz",
@@ -6577,6 +6599,12 @@
"integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==",
"license": "MIT"
},
"node_modules/@types/triple-beam": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==",
"license": "MIT"
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
@@ -6599,6 +6627,17 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/winston": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/@types/winston/-/winston-2.4.4.tgz",
"integrity": "sha512-BVGCztsypW8EYwJ+Hq+QNYiT/MUyCif0ouBH+flrY66O5W+KIXAMML6E/0fJpm7VjIzgangahl5S03bJJQGrZw==",
"deprecated": "This is a stub types definition. winston provides its own type definitions, so you do not need this installed.",
"dev": true,
"license": "MIT",
"dependencies": {
"winston": "*"
}
},
"node_modules/@types/ws": {
"version": "8.5.12",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz",
@@ -7368,7 +7407,6 @@
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"dev": true,
"license": "MIT"
},
"node_modules/asynckit": {
@@ -8326,6 +8364,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/color": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz",
"integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==",
"license": "MIT",
"dependencies": {
"color-convert": "^1.9.3",
"color-string": "^1.6.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -8344,6 +8392,31 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
"node_modules/color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"license": "MIT",
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"node_modules/color/node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"license": "MIT",
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/color/node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
"license": "MIT"
},
"node_modules/colord": {
"version": "2.9.3",
"resolved": "https://registry.npmjs.org/colord/-/colord-2.9.3.tgz",
@@ -8356,6 +8429,16 @@
"integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
"license": "MIT"
},
"node_modules/colorspace": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz",
"integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==",
"license": "MIT",
"dependencies": {
"color": "^3.1.3",
"text-hex": "1.0.x"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -9745,6 +9828,12 @@
"node": ">= 4"
}
},
"node_modules/enabled": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",
"integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
@@ -10538,6 +10627,12 @@
"bser": "2.1.1"
}
},
"node_modules/fecha": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
"integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==",
"license": "MIT"
},
"node_modules/file-entry-cache": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
@@ -10729,6 +10824,12 @@
"dev": true,
"license": "ISC"
},
"node_modules/fn.name": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz",
"integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==",
"license": "MIT"
},
"node_modules/follow-redirects": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
@@ -13035,6 +13136,12 @@
"node": ">=6"
}
},
"node_modules/kuler": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
"integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==",
"license": "MIT"
},
"node_modules/launch-editor": {
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.9.1.tgz",
@@ -13694,6 +13801,23 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/logform": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz",
"integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==",
"license": "MIT",
"dependencies": {
"@colors/colors": "1.6.0",
"@types/triple-beam": "^1.3.2",
"fecha": "^4.2.0",
"ms": "^2.1.1",
"safe-stable-stringify": "^2.3.1",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/long": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
@@ -14793,6 +14917,15 @@
"wrappy": "1"
}
},
"node_modules/one-time": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz",
"integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==",
"license": "MIT",
"dependencies": {
"fn.name": "1.x.x"
}
},
"node_modules/onetime": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
@@ -16549,6 +16682,15 @@
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/safe-stable-stringify": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -16849,6 +16991,21 @@
"dev": true,
"license": "ISC"
},
"node_modules/simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
"integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==",
"license": "MIT",
"dependencies": {
"is-arrayish": "^0.3.1"
}
},
"node_modules/simple-swizzle/node_modules/is-arrayish": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==",
"license": "MIT"
},
"node_modules/sinon": {
"version": "18.0.1",
"resolved": "https://registry.npmjs.org/sinon/-/sinon-18.0.1.tgz",
@@ -17115,6 +17272,15 @@
"node": "^14.17.0 || ^16.13.0 || >=18.0.0"
}
},
"node_modules/stack-trace": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
"integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/stack-utils": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz",
@@ -17815,6 +17981,12 @@
"node": ">=8"
}
},
"node_modules/text-hex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
"integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==",
"license": "MIT"
},
"node_modules/thenify": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
@@ -17945,6 +18117,15 @@
"tree-kill": "cli.js"
}
},
"node_modules/triple-beam": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
"integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==",
"license": "MIT",
"engines": {
"node": ">= 14.0.0"
}
},
"node_modules/ts-api-utils": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.0.1.tgz",
@@ -19090,6 +19271,70 @@
"integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==",
"license": "MIT"
},
"node_modules/winston": {
"version": "3.17.0",
"resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz",
"integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==",
"license": "MIT",
"dependencies": {
"@colors/colors": "^1.6.0",
"@dabh/diagnostics": "^2.0.2",
"async": "^3.2.3",
"is-stream": "^2.0.0",
"logform": "^2.7.0",
"one-time": "^1.0.0",
"readable-stream": "^3.4.0",
"safe-stable-stringify": "^2.3.1",
"stack-trace": "0.0.x",
"triple-beam": "^1.3.0",
"winston-transport": "^4.9.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/winston-transport": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
"integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==",
"license": "MIT",
"dependencies": {
"logform": "^2.7.0",
"readable-stream": "^3.6.2",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/winston-transport/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/winston/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
+2
View File
@@ -35,6 +35,7 @@
"@types/sinon": "^17.0.3",
"@types/systeminformation": "^3.23.1",
"@types/uuid": "^10.0.0",
"@types/winston": "^2.4.4",
"@types/ws": "^8.5.11",
"autoprefixer": "^10.4.20",
"babel-jest": "^29.7.0",
@@ -122,6 +123,7 @@
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4",
"wheelnav": "^1.7.1",
"winston": "^3.17.0",
"ws": "^8.18.0",
"zod": "^3.23.8"
},
+11 -8
View File
@@ -4,9 +4,12 @@ import {
GameEnv,
getServerConfigFromServer,
} from "../core/configuration/Config";
import { logger } from "./Logger";
const config = getServerConfigFromServer();
const log = logger.child({ component: "Archive" });
// R2 client configuration
const r2 = new S3({
region: "auto", // R2 ignores region, but it's required by the SDK
@@ -29,13 +32,13 @@ export async function archive(gameRecord: GameRecord) {
// Archive full game if there are turns
if (gameRecord.turns.length > 0) {
console.log(
log.info(
`${gameRecord.id}: game has more than zero turns, attempting to write to full game to R2`,
);
await archiveFullGameToR2(gameRecord);
}
} catch (error) {
console.error(`${gameRecord.id}: Final archive error: ${error}`, {
log.error(`${gameRecord.id}: Final archive error: ${error}`, {
message: error?.message || error,
stack: error?.stack,
name: error?.name,
@@ -76,9 +79,9 @@ async function archiveAnalyticsToR2(gameRecord: GameRecord) {
ContentType: "application/json",
});
console.log(`${gameRecord.id}: successfully wrote game analytics to R2`);
log.info(`${gameRecord.id}: successfully wrote game analytics to R2`);
} catch (error) {
console.error(
log.error(
`${gameRecord.id}: Error writing game analytics to R2: ${error}`,
{
message: error?.message || error,
@@ -109,11 +112,11 @@ async function archiveFullGameToR2(gameRecord: GameRecord) {
ContentType: "application/json",
});
} catch (error) {
console.log(`error saving game ${gameRecord.id}`);
log.error(`error saving game ${gameRecord.id}`);
throw error;
}
console.log(`${gameRecord.id}: game record successfully written to R2`);
log.info(`${gameRecord.id}: game record successfully written to R2`);
}
export async function readGameRecord(
@@ -130,7 +133,7 @@ export async function readGameRecord(
return JSON.parse(bodyContents) as GameRecord;
} catch (error) {
// Log the error for monitoring purposes
console.error(`${gameId}: Error reading game record from R2: ${error}`, {
log.error(`${gameId}: Error reading game record from R2: ${error}`, {
message: error?.message || error,
stack: error?.stack,
name: error?.name,
@@ -153,7 +156,7 @@ export async function gameRecordExists(gameId: GameID): Promise<boolean> {
if (error.name === "NotFound") {
return false;
}
console.error(`${gameId}: Error checking archive existence: ${error}`, {
log.error(`${gameId}: Error checking archive existence: ${error}`, {
message: error?.message || error,
stack: error?.stack,
name: error?.name,
+8 -4
View File
@@ -3,11 +3,15 @@ import { GameConfig, GameID } from "../core/Schemas";
import { Client } from "./Client";
import { GamePhase, GameServer } from "./GameServer";
import { Difficulty, GameMapType, GameType } from "../core/game/Game";
import { Logger } from "winston";
export class GameManager {
private games: Map<GameID, GameServer> = new Map();
constructor(private config: ServerConfig) {
constructor(
private config: ServerConfig,
private log: Logger,
) {
setInterval(() => this.tick(), 1000);
}
@@ -25,7 +29,7 @@ export class GameManager {
}
createGame(id: GameID, gameConfig: GameConfig | undefined) {
const game = new GameServer(id, Date.now(), this.config, {
const game = new GameServer(id, this.log, Date.now(), this.config, {
gameMap: GameMapType.World,
gameType: GameType.Private,
difficulty: Difficulty.Medium,
@@ -61,7 +65,7 @@ export class GameManager {
try {
game.start();
} catch (error) {
console.log(`error starting game ${id}: ${error}`);
this.log.error(`error starting game ${id}: ${error}`);
}
}
}
@@ -70,7 +74,7 @@ export class GameManager {
try {
game.end();
} catch (error) {
console.log(`error ending game ${id}: ${error}`);
this.log.error(`error ending game ${id}: ${error}`);
}
} else {
active.set(id, game);
+24 -19
View File
@@ -21,7 +21,7 @@ import { archive } from "./Archive";
import { Client } from "./Client";
import { slog } from "./StructuredLog";
import { gatekeeper } from "./Gatekeeper";
import { Logger } from "winston";
export enum GamePhase {
Lobby = "LOBBY",
Active = "ACTIVE",
@@ -49,12 +49,17 @@ export class GameServer {
// This field is currently only filled at victory
private allPlayersStats: AllPlayersStats = {};
private log: Logger;
constructor(
public readonly id: string,
readonly log_: Logger,
public readonly createdAt: number,
private config: ServerConfig,
public gameConfig: GameConfig,
) {}
) {
this.log = log_.child({ gameID: id });
}
public updateGameConfig(gameConfig: GameConfig): void {
if (gameConfig.gameMap != null) {
@@ -81,7 +86,7 @@ export class GameServer {
}
public addClient(client: Client, lastTurn: number) {
console.log(`${this.id}: adding client ${client.clientID}`);
this.log.info(`adding client ${client.clientID}`);
slog({
logKey: "client_joined_game",
msg: `client ${client.clientID} (re)joining game ${this.id}`,
@@ -102,7 +107,7 @@ export class GameServer {
(c) => c.ip == client.ip && c.clientID != client.clientID,
).length >= 3
) {
console.log(
this.log.info(
`cannot add client ${client.clientID}, already have 3 ips (${client.ip})`,
);
return;
@@ -136,7 +141,7 @@ export class GameServer {
if (this.allClients.has(clientMsg.clientID)) {
const client = this.allClients.get(clientMsg.clientID);
if (client.persistentID != clientMsg.persistentID) {
console.warn(
this.log.warn(
`Client ID ${clientMsg.clientID} sent incorrect id ${clientMsg.persistentID}, does not match persistent id ${client.persistentID}`,
);
return;
@@ -150,7 +155,7 @@ export class GameServer {
if (clientMsg.gameID == this.id) {
this.addIntent(clientMsg.intent);
} else {
console.warn(
this.log.warn(
`${this.id}: client ${clientMsg.clientID} sent to wrong game`,
);
}
@@ -167,14 +172,14 @@ export class GameServer {
this.allPlayersStats = clientMsg.allPlayersStats;
}
} catch (error) {
console.log(
this.log.info(
`error handline websocket request in game server: ${error}`,
);
}
}),
);
client.ws.on("close", () => {
console.log(`${this.id}: client ${client.clientID} disconnected`);
this.log.info(`${this.id}: client ${client.clientID} disconnected`);
this.activeClients = this.activeClients.filter(
(c) => c.clientID != client.clientID,
);
@@ -216,7 +221,7 @@ export class GameServer {
this.config.turnIntervalMs(),
);
this.activeClients.forEach((c) => {
console.log(`${this.id}: sending start message to ${c.clientID}`);
this.log.info(`${this.id}: sending start message to ${c.clientID}`);
this.sendStartGameMsg(c.ws, 0);
});
}
@@ -266,7 +271,7 @@ export class GameServer {
}),
);
} catch (error) {
console.log(
this.log.info(
`error sending message for game ${this.id}, error ${error}`.substring(
0,
250,
@@ -289,7 +294,7 @@ export class GameServer {
client.ws.close(1000, "game has ended");
}
});
console.log(
this.log.info(
`${this.id}: ending game ${this.id} with ${this.turns.length} turns`,
);
try {
@@ -315,7 +320,7 @@ export class GameServer {
),
);
} else {
console.log(`${this.id}: no clients joined, not archiving game`);
this.log.info(`${this.id}: no clients joined, not archiving game`);
}
} catch (error) {
let errorDetails;
@@ -334,7 +339,7 @@ export class GameServer {
}
}
console.error("Error archiving game record details:", {
this.log.error("Error archiving game record details:", {
gameId: this.id,
errorType: typeof error,
error: errorDetails,
@@ -347,7 +352,7 @@ export class GameServer {
const alive = [];
for (const client of this.activeClients) {
if (now - client.lastPing > 60_000) {
console.log(
this.log.info(
`${this.id}: no pings from ${client.clientID}, terminating connection`,
);
if (client.ws.readyState === WebSocket.OPEN) {
@@ -359,7 +364,7 @@ export class GameServer {
}
this.activeClients = alive;
if (now > this.createdAt + this.maxGameDuration) {
console.warn(`${this.id}: game past max duration ${this.id}`);
this.log.warn(`${this.id}: game past max duration ${this.id}`);
return GamePhase.Finished;
}
@@ -369,7 +374,7 @@ export class GameServer {
if (this.gameConfig.gameType != GameType.Public) {
if (this._hasStarted) {
if (noActive && noRecentPings) {
console.log(`${this.id}: private game: ${this.id} complete`);
this.log.info(`${this.id}: private game: ${this.id} complete`);
return GamePhase.Finished;
} else {
return GamePhase.Active;
@@ -443,7 +448,7 @@ export class GameServer {
for (const oos of outOfSyncClients) {
if (!this.outOfSyncClients.has(oos.clientID)) {
console.warn(
this.log.warn(
`Game ${this.id}: has out of sync client ${oos.clientID} on turn ${lastHashTurn}`,
);
this.outOfSyncClients.add(oos.clientID);
@@ -461,13 +466,13 @@ export class GameServer {
if (serverDesync.success) {
const desyncMsg = JSON.stringify(serverDesync.data);
for (const c of outOfSyncClients) {
console.log(
this.log.info(
`game: ${this.id}: sending desync to client ${c.clientID}`,
);
c.ws.send(desyncMsg);
}
} else {
console.warn(`failed to create desync message ${serverDesync.error}`);
this.log.warn(`failed to create desync message ${serverDesync.error}`);
}
}
}
+27
View File
@@ -0,0 +1,27 @@
import winston from "winston";
// Custom format to add severity tag based on log level
const addSeverityFormat = winston.format((info) => {
return {
...info,
severity: info.level,
};
});
// Define your base/parent logger
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
addSeverityFormat(),
winston.format.json(),
),
defaultMeta: {
service: "openfront",
environment: process.env.NODE_ENV,
},
transports: [new winston.transports.Console()],
});
// Export both the main logger and the child logger factory
export { logger };
+17 -20
View File
@@ -4,16 +4,14 @@ import express from "express";
import { GameMapType, GameType, Difficulty } from "../core/game/Game";
import { generateID } from "../core/Util";
import { PseudoRandom } from "../core/PseudoRandom";
import {
GameEnv,
getServerConfigFromServer,
} from "../core/configuration/Config";
import { getServerConfigFromServer } from "../core/configuration/Config";
import { GameConfig, GameInfo } from "../core/Schemas";
import path from "path";
import rateLimit from "express-rate-limit";
import { fileURLToPath } from "url";
import { gatekeeper, LimiterType } from "./Gatekeeper";
import { setupMetricsServer } from "./MasterMetrics";
import { logger } from "./Logger";
const config = getServerConfigFromServer();
const readyWorkers = new Set();
@@ -25,6 +23,8 @@ const server = http.createServer(app);
const metricsApp = express();
const metricsServer = http.createServer(metricsApp);
const log = logger.child({ component: "Master" });
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.use(express.json());
@@ -76,8 +76,8 @@ export async function startMaster() {
);
}
console.log(`Primary ${process.pid} is running`);
console.log(`Setting up ${config.numWorkers()} workers...`);
log.info(`Primary ${process.pid} is running`);
log.info(`Setting up ${config.numWorkers()} workers...`);
// Fork workers
for (let i = 0; i < config.numWorkers(); i++) {
@@ -85,23 +85,23 @@ export async function startMaster() {
WORKER_ID: i,
});
console.log(`Started worker ${i} (PID: ${worker.process.pid})`);
log.info(`Started worker ${i} (PID: ${worker.process.pid})`);
}
cluster.on("message", (worker, message) => {
if (message.type === "WORKER_READY") {
const workerId = message.workerId;
readyWorkers.add(workerId);
console.log(
log.info(
`Worker ${workerId} is ready. (${readyWorkers.size}/${config.numWorkers()} ready)`,
);
// Start scheduling when all workers are ready
if (readyWorkers.size === config.numWorkers()) {
console.log("All workers ready, starting game scheduling");
log.info("All workers ready, starting game scheduling");
const scheduleLobbies = () => {
schedulePublicGame().catch((error) => {
console.error("Error scheduling public game:", error);
log.error("Error scheduling public game:", error);
});
};
@@ -122,28 +122,28 @@ export async function startMaster() {
cluster.on("exit", (worker, code, signal) => {
const workerId = (worker as any).process?.env?.WORKER_ID;
if (!workerId) {
console.error(`worker crashed could not find id`);
log.error(`worker crashed could not find id`);
return;
}
console.warn(
log.warn(
`Worker ${workerId} (PID: ${worker.process.pid}) died with code: ${code} and signal: ${signal}`,
);
console.log(`Restarting worker ${workerId}...`);
log.info(`Restarting worker ${workerId}...`);
// Restart the worker with the same ID
const newWorker = cluster.fork({
WORKER_ID: workerId,
});
console.log(
log.info(
`Restarted worker ${workerId} (New PID: ${newWorker.process.pid})`,
);
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Master HTTP server listening on port ${PORT}`);
log.info(`Master HTTP server listening on port ${PORT}`);
});
// Setup the metrics server
@@ -181,7 +181,7 @@ async function fetchLobbies(): Promise<number> {
return json as GameInfo;
})
.catch((error) => {
console.error(`Error fetching game ${gameID}:`, error);
log.error(`Error fetching game ${gameID}:`, error);
// Return null or a placeholder if fetch fails
return null;
});
@@ -260,10 +260,7 @@ async function schedulePublicGame() {
const data = await response.json();
} catch (error) {
console.error(
`Failed to schedule public game on worker ${workerPath}:`,
error,
);
log.error(`Failed to schedule public game on worker ${workerPath}:`, error);
throw error;
}
}
+27 -23
View File
@@ -18,14 +18,18 @@ import { GameType } from "../core/game/Game";
import { archive, readGameRecord } from "./Archive";
import { gatekeeper, LimiterType } from "./Gatekeeper";
import { metrics } from "./WorkerMetrics";
import { logger } from "./Logger";
const config = getServerConfigFromServer();
let log = logger.child({ component: "Worker" });
// Worker setup
export function startWorker() {
// Get worker ID from environment variable
const workerId = parseInt(process.env.WORKER_ID || "0");
console.log(`Worker ${workerId} starting...`);
log = log.child({ workerId: workerId });
log.info(`Worker ${workerId} starting...`);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -34,7 +38,7 @@ export function startWorker() {
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const gm = new GameManager(config);
const gm = new GameManager(config, log);
// Set up periodic metrics updates
setInterval(() => {
@@ -81,7 +85,7 @@ export function startWorker() {
gatekeeper.httpHandler(LimiterType.Post, async (req, res) => {
const id = req.params.id;
if (!id) {
console.warn(`cannot create game, id not found`);
log.warn(`cannot create game, id not found`);
return;
}
// TODO: if game is public make sure request came from localhohst!!!
@@ -91,7 +95,7 @@ export function startWorker() {
gc?.gameType == GameType.Public &&
req.headers[config.adminHeader()] !== config.adminToken()
) {
console.warn(
log.warn(
`cannot create public game ${id}, ip ${clientIP} incorrect admin token`,
);
return res.status(400);
@@ -100,7 +104,7 @@ export function startWorker() {
// Double-check this worker should host this game
const expectedWorkerId = config.workerIndex(id);
if (expectedWorkerId !== workerId) {
console.warn(
log.warn(
`This game ${id} should be on worker ${expectedWorkerId}, but this is worker ${workerId}`,
);
return res.status(400);
@@ -108,7 +112,7 @@ export function startWorker() {
const game = gm.createGame(id, gc);
console.log(
log.info(
`Worker ${workerId}: IP ${clientIP} creating game ${game.isPublic() ? "Public" : "Private"} with id ${id}`,
);
res.json(game.gameInfo());
@@ -119,14 +123,14 @@ export function startWorker() {
app.post(
"/api/start_game/:id",
gatekeeper.httpHandler(LimiterType.Post, async (req, res) => {
console.log(`starting private lobby with id ${req.params.id}`);
log.info(`starting private lobby with id ${req.params.id}`);
const game = gm.game(req.params.id);
if (!game) {
return;
}
if (game.isPublic()) {
const clientIP = req.ip || req.socket.remoteAddress || "unknown";
console.log(
log.info(
`cannot start public game ${game.id}, game is public, ip: ${clientIP}`,
);
return;
@@ -142,7 +146,7 @@ export function startWorker() {
// TODO: only update public game if from local host
const lobbyID = req.params.id;
if (req.body.gameType == GameType.Public) {
console.log(`cannot update game ${lobbyID} to public`);
log.info(`cannot update game ${lobbyID} to public`);
return res.status(400);
}
const game = gm.game(lobbyID);
@@ -151,7 +155,7 @@ export function startWorker() {
}
if (game.isPublic()) {
const clientIP = req.ip || req.socket.remoteAddress || "unknown";
console.warn(`cannot update public game ${game.id}, ip: ${clientIP}`);
log.warn(`cannot update public game ${game.id}, ip: ${clientIP}`);
return res.status(400);
}
game.updateGameConfig({
@@ -182,7 +186,7 @@ export function startWorker() {
gatekeeper.httpHandler(LimiterType.Get, async (req, res) => {
const game = gm.game(req.params.id);
if (game == null) {
console.log(`lobby ${req.params.id} not found`);
log.info(`lobby ${req.params.id} not found`);
return res.status(404);
}
res.json(game.gameInfo());
@@ -206,7 +210,7 @@ export function startWorker() {
config.env() != GameEnv.Dev &&
gameRecord.gitCommit != config.gitCommit()
) {
console.warn(
log.warn(
`git commit mismatch for game ${req.params.id}, expected ${config.gitCommit()}, got ${gameRecord.gitCommit}`,
);
return res.status(409).json({
@@ -235,7 +239,7 @@ export function startWorker() {
const clientIP = req.ip || req.socket.remoteAddress || "unknown";
if (!gameRecord) {
console.log("game record not found in request");
log.info("game record not found in request");
res.status(404).json({ error: "Game record not found" });
return;
}
@@ -253,7 +257,7 @@ export function startWorker() {
if (req.headers[config.adminHeader()] !== config.adminToken()) {
return res.status(403).end("Access denied");
}
console.log(`metrics requested on worker ${workerId}`);
log.info(`metrics requested on worker ${workerId}`);
try {
const metricsData = await metrics.register.metrics();
@@ -284,7 +288,7 @@ export function startWorker() {
// Verify this worker should handle this game
const expectedWorkerId = config.workerIndex(clientMsg.gameID);
if (expectedWorkerId !== workerId) {
console.warn(
log.warn(
`Worker mismatch: Game ${clientMsg.gameID} should be on worker ${expectedWorkerId}, but this is worker ${workerId}`,
);
return;
@@ -306,7 +310,7 @@ export function startWorker() {
);
if (!wasFound) {
console.log(
log.info(
`game ${clientMsg.gameID} not found on worker ${workerId}`,
);
// Handle game not found case
@@ -315,7 +319,7 @@ export function startWorker() {
// Handle other message types
} catch (error) {
console.warn(
log.warn(
`error handling websocket message for ${ip}: ${error}`.substring(
0,
250,
@@ -335,21 +339,21 @@ export function startWorker() {
// The load balancer will handle routing to this server based on path
const PORT = config.workerPortByIndex(workerId);
server.listen(PORT, () => {
console.log(`Worker ${workerId} running on http://localhost:${PORT}`);
console.log(`Handling requests with path prefix /w${workerId}/`);
log.info(`Worker ${workerId} running on http://localhost:${PORT}`);
log.info(`Handling requests with path prefix /w${workerId}/`);
// Signal to the master process that this worker is ready
if (process.send) {
process.send({
type: "WORKER_READY",
workerId: workerId,
});
console.log(`Worker ${workerId} signaled ready state to master`);
log.info(`Worker ${workerId} signaled ready state to master`);
}
});
// Global error handler
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(`Error in ${req.method} ${req.path}:`, err);
log.error(`Error in ${req.method} ${req.path}:`, err);
slog({
logKey: "server_error",
msg: `Unhandled exception in ${req.method} ${req.path}: ${err.message}`,
@@ -361,7 +365,7 @@ export function startWorker() {
// Process-level error handlers
process.on("uncaughtException", (err) => {
console.error(`Worker ${workerId} uncaught exception:`, err);
log.error(`Worker ${workerId} uncaught exception:`, err);
slog({
logKey: "uncaught_exception",
msg: `Worker ${workerId} uncaught exception: ${err.message}`,
@@ -371,7 +375,7 @@ export function startWorker() {
});
process.on("unhandledRejection", (reason, promise) => {
console.error(
log.error(
`Worker ${workerId} unhandled rejection at:`,
promise,
"reason:",