add config.performance.unfurlSrvCacheTtl option for caching resolveSrv calls
This commit is contained in:
@ -1,4 +1,5 @@
|
||||
const crypto = require('crypto')
|
||||
const dns = require('dns')
|
||||
|
||||
const TimeTracker = require('./time')
|
||||
const Server = require('./server')
|
||||
@ -313,6 +314,62 @@ class ServerRegistration {
|
||||
color: this.data.color
|
||||
}
|
||||
}
|
||||
|
||||
unfurlSrv (callback) {
|
||||
// Skip unfurling SRV, instantly return pre-configured data
|
||||
if (config.performance && config.performance.skipUnfurlSrv) {
|
||||
callback(this.data.ip, this.data.port)
|
||||
return
|
||||
}
|
||||
|
||||
const timestamp = new Date().getTime()
|
||||
|
||||
// If a cached copy exists and is within its TTL, instantly return
|
||||
if (this._lastUnfurlSrv && timestamp - this._lastUnfurlSrv.timestamp <= config.performance.unfurlSrvCacheTtl) {
|
||||
callback(this._lastUnfurlSrv.ip, this._lastUnfurlSrv.port)
|
||||
return
|
||||
}
|
||||
|
||||
// Group callbacks into an array
|
||||
// Once resolved, fire callbacks sequentially
|
||||
// This avoids callbacks possibly executing out of order
|
||||
if (!this._unfurlSrvCallbackQueue) {
|
||||
this._unfurlSrvCallbackQueue = []
|
||||
}
|
||||
|
||||
this._unfurlSrvCallbackQueue.push(callback)
|
||||
|
||||
// Prevent multiple #resolveSrv calls per ServerRegistration
|
||||
if (!this._isUnfurlingSrv) {
|
||||
this._isUnfurlingSrv = true
|
||||
|
||||
dns.resolveSrv('_minecraft._tcp' + this.data.ip, (_, records) => {
|
||||
this._lastUnfurlSrv = {
|
||||
timestamp
|
||||
}
|
||||
|
||||
if (records && records.length > 0) {
|
||||
this._lastUnfurlSrv.ip = records[0].name
|
||||
this._lastUnfurlSrv.port = records[0].port
|
||||
} else {
|
||||
// Provide fallback to pre-configured data
|
||||
this._lastUnfurlSrv.ip = this.data.ip
|
||||
this._lastUnfurlSrv.port = this.data.port
|
||||
}
|
||||
|
||||
// Fire the waiting callbacks in queue
|
||||
// Release blocking flag to allow new #resolveSrv calls
|
||||
this._isUnfurlingSrv = false
|
||||
|
||||
for (const callback of this._unfurlSrvCallbackQueue) {
|
||||
callback(this._lastUnfurlSrv.ip, this._lastUnfurlSrv.port)
|
||||
}
|
||||
|
||||
// Reset the callback queue
|
||||
this._unfurlSrvCallbackQueue = []
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ServerRegistration
|
||||
|
Reference in New Issue
Block a user