aboutsummaryrefslogtreecommitdiff
path: root/src/lib/workers-list.js
blob: c7b3ab1d44d414b9f5b866f5d58237793addecd0 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
const intersection = require('lodash/intersection')
const config = require('./config')
const {getLogger} = require('./logger')
const {RequestMessage, PingMessage} = require('./server')
const throttle = require('lodash/throttle')

class WorkersList {

    constructor() {
        /**
         * @type {{connection: Connection, targets: string[]}[]}
         */
        this.workers = []

        /**
         * @type {object.<string, boolean>}
         */
        this.targetsToPoke = {}

        /**
         * @type {object.<string, boolean>}
         */
        this.targetsWaitingToPoke = {}

        /**
         * @type {NodeJS.Timeout}
         */
        this.pingInterval = setInterval(this.sendPings, config.get('ping_interval') * 1000)

        /**
         * @type {Logger}
         */
        this.logger = getLogger('WorkersList')
    }

    /**
     * @param {Connection} connection
     * @param {string[]} targets
     */
    add(connection, targets) {
        this.logger.info(`add: connection from ${connection.remoteAddr()}, targets ${JSON.stringify(targets)}`)

        this.workers.push({connection, targets})
        connection.on('close', () => {
            this.logger.info(`connection from ${connection.remoteAddr()} closed, removing worker`)
            this.workers = this.workers.filter(worker => {
                return worker.connection !== connection
            })
        })

        let waiting = Object.keys(this.targetsWaitingToPoke)
        if (!waiting.length)
            return

        let intrs = intersection(waiting, targets)
        if (intrs.length) {
            this.logger.info('add: found intersection with waiting targets:', intrs, 'going to poke new worker')
            this._pokeWorkerConnection(connection, intrs)
            for (let target of intrs)
                delete this.targetsWaitingToPoke[target]
            this.logger.trace(`add: this.targetsWaitingToPoke:`, this.targetsWaitingToPoke)
        }
    }

    /**
     * @param {string[]} targets
     */
    poke(targets) {
        this.logger.debug('poke:', targets)

        if (!Array.isArray(targets))
            throw new Error('targets must be Array')

        for (let t of targets)
            this.targetsToPoke[t] = true

        this._pokeWorkers()
    }

    /**
     * @private
     */
    _pokeWorkers = throttle(() => {
        const targets = Object.keys(this.targetsToPoke)
        this.targetsToPoke = {}

        const found = {}
        for (const worker of this.workers) {
            const intrs = intersection(worker.targets, targets)
            intrs.forEach(t => {
                found[t] = true
            })
            if (intrs.length > 0)
                this._pokeWorkerConnection(worker.connection, targets)
        }

        for (let target of targets) {
            if (!(target in found)) {
                this.logger.debug(`_pokeWorkers: worker responsible for ${target} not found. we'll remember it`)
                this.targetsWaitingToPoke[target] = true
            }
            this.logger.trace('_pokeWorkers: this.targetsWaitingToPoke:', this.targetsWaitingToPoke)
        }
    }, config.get('poke_throttle_interval') * 1000, {leading: true})

    /**
     * @param {Connection} connection
     * @param {string[]} targets
     * @private
     */
    _pokeWorkerConnection(connection, targets) {
        this.logger.debug('_pokeWorkerConnection:', connection.remoteAddr(), targets)

        connection.sendRequest(
            new RequestMessage('poll', {
                targets
            })
        )
        .then(error => {
            this.logger.error('_pokeWorkerConnection:', error)
        })
    }

    /**
     * @return {{targets: string[], remoteAddr: string, remotePort: number}[]}
     */
    async getInfo(pollWorkers = false) {
        const promises = []

        const workers = [...this.workers]

        for (let i = 0; i < workers.length; i++) {
            let worker = workers[i]

            let P
            if (pollWorkers) {
                P = worker.connection.sendRequest(new RequestMessage('status'))
            } else {
                P = Promise.resolve()
            }

            promises.push(P)
        }

        const results = await Promise.allSettled(promises)

        let info = []
        for (let i = 0; i < results.length; i++) {
            const result = results[i]
            const worker = workers[i]
            const workerInfo = {
                remoteAddr: worker.connection.socket?.remoteAddress,
                remotePort: worker.connection.socket?.remotePort,
                targets: worker.targets
            }

            if (pollWorkers) {
                if (result.status === 'fulfilled') {
                    /**
                     * @type {ResponseMessage}
                     */
                    let response = result.value
                    workerInfo.workerStatus = response.data
                } else if (result.status === 'rejected') {
                    workerInfo.workerStatusError = result.reason?.message
                }
            }

            info.push(workerInfo)
        }

        return info
    }

    /**
     * @private
     */
    sendPings = () => {
        this.workers
            .forEach(w => {
                this.logger.trace(`sending ping to ${w.connection.remoteAddr()}`)
                w.connection.send(new PingMessage())
            })
    }

}

module.exports = WorkersList