-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoCull.js
60 lines (52 loc) · 1.98 KB
/
autoCull.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
if (!process.env.PROD)
require('dotenv').config()
const Convergence = require("@convergence/convergence");
const WebSocket = require('ws');
const {stopAndRemoveContainer} = require("./helpers/docker")
const domainUrl = `${process.env.OT_SERVER_URL}/realtime/convergence/default`
const convergenceOptions = {
webSocket: {class: WebSocket}
}
class AutoCull {
constructor() {
this.convergenceDomain = null;
}
connect = async () => {
this.convergenceDomain = await Convergence.connectAnonymously(domainUrl, JSON.stringify({isBot: true}), convergenceOptions)
}
checkAndCull = async (roomId, shouldCull)=>{
const participantsCount = await getParticipantCount(this.convergenceDomain, roomId) - 1;
if(shouldCull && participantsCount > 0){
// Cancel culling and return
shouldCull=false
return {shouldCull, isRunning: true};
}
if(shouldCull) {
// Cull
try{
await stopAndRemoveContainer(roomId)
console.log(`AutoCull : Container ${roomId} culled due to inactivity`)
} catch (e) {
if(JSON.parse(e).code === 404)
console.warn("Container does not exist, assuming it has crashed")
else
console.error(e)
}
return {shouldCull, isRunning: false};
}
if (participantsCount===0) {
// Cull in next iteration
shouldCull = true
console.log(`AutoCull : Container ${roomId} added to cull in next iteration`)
return {shouldCull, isRunning: true};
}
return {shouldCull: false, isRunning: true}
}
}
const getParticipantCount = async (domain, roomId) => {
const model = await domain.models().open(roomId)
const activity = await domain.activities().join(model.modelId())
const participants = activity.participants()
return participants.length
};
module.exports = AutoCull