2020-06-23 17:29:44 +00:00
|
|
|
const logger = require('logger-sharelatex')
|
2016-10-24 15:36:09 +00:00
|
|
|
|
2020-07-07 10:06:02 +00:00
|
|
|
module.exports = {
|
2020-08-13 11:12:12 +00:00
|
|
|
startDrainTimeWindow(io, minsToDrain, callback) {
|
2020-06-23 17:29:44 +00:00
|
|
|
const drainPerMin = io.sockets.clients().length / minsToDrain
|
2020-07-07 10:06:02 +00:00
|
|
|
// enforce minimum drain rate
|
2020-08-13 11:12:12 +00:00
|
|
|
this.startDrain(io, Math.max(drainPerMin / 60, 4), callback)
|
2020-07-07 10:06:02 +00:00
|
|
|
},
|
2019-08-13 10:12:04 +00:00
|
|
|
|
2020-08-13 11:12:12 +00:00
|
|
|
startDrain(io, rate, callback) {
|
2020-06-23 17:29:44 +00:00
|
|
|
// Clear out any old interval
|
|
|
|
clearInterval(this.interval)
|
2021-09-14 08:36:24 +00:00
|
|
|
logger.info({ rate }, 'starting drain')
|
2020-06-23 17:29:44 +00:00
|
|
|
if (rate === 0) {
|
|
|
|
return
|
2020-07-07 10:06:02 +00:00
|
|
|
}
|
|
|
|
let pollingInterval
|
|
|
|
if (rate < 1) {
|
2020-06-23 17:29:44 +00:00
|
|
|
// allow lower drain rates
|
|
|
|
// e.g. rate=0.1 will drain one client every 10 seconds
|
|
|
|
pollingInterval = 1000 / rate
|
|
|
|
rate = 1
|
|
|
|
} else {
|
|
|
|
pollingInterval = 1000
|
|
|
|
}
|
2020-07-07 10:06:02 +00:00
|
|
|
this.interval = setInterval(() => {
|
2020-08-13 11:12:12 +00:00
|
|
|
const requestedAllClientsToReconnect = this.reconnectNClients(io, rate)
|
|
|
|
if (requestedAllClientsToReconnect && callback) {
|
|
|
|
callback()
|
|
|
|
callback = undefined
|
|
|
|
}
|
2020-07-07 10:06:02 +00:00
|
|
|
}, pollingInterval)
|
2020-06-23 17:29:44 +00:00
|
|
|
},
|
2019-08-13 10:12:04 +00:00
|
|
|
|
2020-06-23 17:29:44 +00:00
|
|
|
RECONNECTED_CLIENTS: {},
|
|
|
|
reconnectNClients(io, N) {
|
|
|
|
let drainedCount = 0
|
2020-07-07 10:06:02 +00:00
|
|
|
for (const client of io.sockets.clients()) {
|
2020-06-23 17:29:44 +00:00
|
|
|
if (!this.RECONNECTED_CLIENTS[client.id]) {
|
|
|
|
this.RECONNECTED_CLIENTS[client.id] = true
|
2021-09-14 08:36:24 +00:00
|
|
|
logger.debug(
|
2020-06-23 17:29:44 +00:00
|
|
|
{ client_id: client.id },
|
|
|
|
'Asking client to reconnect gracefully'
|
|
|
|
)
|
|
|
|
client.emit('reconnectGracefully')
|
|
|
|
drainedCount++
|
|
|
|
}
|
|
|
|
const haveDrainedNClients = drainedCount === N
|
|
|
|
if (haveDrainedNClients) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (drainedCount < N) {
|
2021-09-14 08:36:24 +00:00
|
|
|
logger.info('All clients have been told to reconnectGracefully')
|
2020-08-13 11:12:12 +00:00
|
|
|
return true
|
2020-06-23 17:29:44 +00:00
|
|
|
}
|
2020-08-13 11:12:12 +00:00
|
|
|
return false
|
2021-07-13 11:04:45 +00:00
|
|
|
},
|
2020-06-23 17:29:44 +00:00
|
|
|
}
|