puzzle/src/server/GameLog.ts

93 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-12-22 22:35:09 +01:00
import fs from 'fs'
2021-05-29 11:44:55 +02:00
import readline from 'readline'
import stream from 'stream'
import Time from '../common/Time'
import { Timestamp } from '../common/Types'
import { logger } from './../common/Util'
import { DATA_DIR } from './../server/Dirs'
const log = logger('GameLog.js')
2020-12-22 22:35:09 +01:00
const LINES_PER_LOG_FILE = 10000
const POST_GAME_LOG_DURATION = 5 * Time.MIN
const shouldLog = (finishTs: Timestamp, currentTs: Timestamp): boolean => {
// when not finished yet, always log
if (!finishTs) {
return true
}
// in finished games, log max POST_GAME_LOG_DURATION after
// the game finished, to record winning dance moves etc :P
const timeSinceGameEnd = currentTs - finishTs
return timeSinceGameEnd <= POST_GAME_LOG_DURATION
}
const filename = (gameId: string, offset: number) => `${DATA_DIR}/log_${gameId}-${offset}.log`
const idxname = (gameId: string) => `${DATA_DIR}/log_${gameId}.idx.log`
2020-12-22 22:54:31 +01:00
2021-05-29 15:36:03 +02:00
const create = (gameId: string): void => {
const idxfile = idxname(gameId)
if (!fs.existsSync(idxfile)) {
const logfile = filename(gameId, 0)
fs.appendFileSync(logfile, "")
fs.appendFileSync(idxfile, JSON.stringify({
total: 0,
currentFile: logfile,
perFile: LINES_PER_LOG_FILE,
}))
2020-12-22 22:54:31 +01:00
}
}
2021-05-29 15:36:03 +02:00
const exists = (gameId: string): boolean => {
const idxfile = idxname(gameId)
return fs.existsSync(idxfile)
2020-12-22 22:54:31 +01:00
}
2021-05-29 15:36:03 +02:00
const _log = (gameId: string, ...args: Array<any>): void => {
const idxfile = idxname(gameId)
if (!fs.existsSync(idxfile)) {
2020-12-22 22:54:31 +01:00
return
}
const idx = JSON.parse(fs.readFileSync(idxfile, 'utf-8'))
idx.total++
fs.appendFileSync(idx.currentFile, JSON.stringify(args) + "\n")
// prepare next log file
if (idx.total % idx.perFile === 0) {
const logfile = filename(gameId, idx.total)
fs.appendFileSync(logfile, "")
idx.currentFile = logfile
}
fs.writeFileSync(idxfile, JSON.stringify(idx))
2020-12-22 22:35:09 +01:00
}
const get = (
2021-05-29 11:44:55 +02:00
gameId: string,
offset: number = 0,
): any[] => {
const idxfile = idxname(gameId)
if (!fs.existsSync(idxfile)) {
return []
}
const file = filename(gameId, offset)
2020-12-22 22:54:31 +01:00
if (!fs.existsSync(file)) {
return []
}
const log = fs.readFileSync(file, 'utf-8').split("\n")
return log.map(line => {
return JSON.parse(line)
2020-12-22 22:35:09 +01:00
})
}
export default {
shouldLog,
2020-12-22 22:54:31 +01:00
create,
exists,
log: _log,
2020-12-22 22:35:09 +01:00
get,
}