cubbot/src/modules/Time.ts

108 lines
2.6 KiB
TypeScript
Raw Normal View History

2020-04-19 17:02:07 +00:00
import { EventEmitter } from 'events'
import { SERVER_TICK_RATE, SERVER_TPS } from '../utils/constants'
import { longToNumber } from '../utils/func'
import Module from '../utils/Module'
2020-04-17 14:26:33 +00:00
interface IUpdateTime {
age: number[]
time: number[]
}
2020-04-19 17:02:07 +00:00
interface IConf {
/** Log if server lost ticks */
minTps: number,
/** Log if server lost tps */
maxSpt: number,
/** Log if client is not in sync */
maxOffset: number
}
interface IEmitter {
on(event: 'tick', listener: (age: number) => void): this
}
/** Monitor time and ticks */
export default class Time extends Module<IConf> {
private _events = new EventEmitter()
public get events(): IEmitter {
return this._events
}
2020-04-17 14:26:33 +00:00
private _age!: number
2020-04-19 17:02:07 +00:00
/** Ticks since world creation */
2020-04-17 14:26:33 +00:00
public get age() {
return this._age
}
2020-04-19 17:02:07 +00:00
private _distAge!: number
2020-04-17 14:26:33 +00:00
private _time!: number
2020-04-19 17:02:07 +00:00
/** Ticks of the day */
2020-04-17 14:26:33 +00:00
public get time() {
return this._time
}
private _tps!: number
2020-04-19 17:02:07 +00:00
/** Processed Tick per seconds */
2020-04-17 14:26:33 +00:00
public get tps() {
return this._tps
}
2020-04-19 17:02:07 +00:00
private _spt!: number
/** Processed Tick per seconds */
public get spt() {
return this._spt
2020-04-17 14:26:33 +00:00
}
private _at: number = Date.now()
2020-04-19 17:02:07 +00:00
private _clock?: NodeJS.Timeout
public umount() {
if (this._clock) {
clearInterval(this._clock)
this._clock = undefined
}
}
protected mount() {
2020-04-17 14:26:33 +00:00
this.client.on('update_time', (data: IUpdateTime) => {
const now = Date.now()
const age = longToNumber(data.age)
2020-04-19 17:02:07 +00:00
if (this._distAge) {
this._tps = age - this._distAge
if (this.tps <= this.conf.minTps) {
this.logger.debug('Server Lag: %s / 20 tps', this.tps, SERVER_TPS)
}
this._spt = (now - this._at) / this.tps
if (this.spt >= this.conf.maxSpt) {
this.logger.debug('Network Lag: %s / %s spt', this.spt, SERVER_TICK_RATE)
2020-04-17 14:26:33 +00:00
}
2020-04-19 17:02:07 +00:00
const offset = age - this._age
if (Math.abs(offset) > this.conf.maxOffset) {
this.logger.debug('Client Off-sync %s ticks', offset)
2020-04-17 14:26:33 +00:00
}
}
2020-04-19 17:02:07 +00:00
this._distAge = this._age = age
2020-04-17 14:26:33 +00:00
this._at = now
this._time = Math.abs(data.time[1]) % 24000
})
2020-04-19 17:02:07 +00:00
this._clock = setInterval(() => this._events.emit('tick', ++this._age), SERVER_TICK_RATE)
}
protected getConf(): IConf {
return {
minTps: SERVER_TPS - 1,
maxSpt: SERVER_TICK_RATE + 10,
maxOffset: 1,
}
2020-04-17 14:26:33 +00:00
}
}