-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
279 lines (224 loc) · 8.32 KB
/
index.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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
'use strict'
const Redis = require('ioredis')
const ProtocolVersion = 4
const DefaultTimeouts = {
connect: 1000,
reconnect: 3000,
ack: 5000,
customCommands: 2000
}
class MismatchedSequenceNumber extends Error {
constructor(currentSeqNo, expectedSeqNo, ...args) {
super(...args)
this.current = currentSeqNo
this.expected = expectedSeqNo
}
get [Symbol.toStringTag]() {
return `current=${this.current} expected=${this.expected}`
}
}
class ConfigurationError extends Error {}
class ConnectionError extends Error {}
module.exports = class {
constructor (localId, prefix, redisCfg, options = {}) {
this.id = localId
this.prefix = prefix
this.redisCfg = redisCfg
this.displayId = null
this.timeouts = options.timeouts || DefaultTimeouts
this.reconnectable = options.hasOwnProperty('allowReconnections') ? options.allowReconnections : true
this.disconnectOnExitSignals = options.hasOwnProperty('disconnectOnExitSignals') ? options.disconnectOnExitSignals : true
this.messageStats = options.hasOwnProperty('messageStats') ? options.messageStats : { rx: 0, tx: 0 }
this.awaitingAckedResponse = {}
}
async clear () {
return this._estabPublish('clear')
}
async writeAt (column, row, message) {
return this._estabPublish(`writeat ${column} ${row} ${message}`)
}
async toggleDisplay (on) {
return this._estabPublish(`toggleDisplay ${!!on ? 'on' : 'off'}`)
}
async toggleCursor (on) {
return this._estabPublish(`toggleCursor ${!!on ? 'on' : 'off'}`)
}
async toggleCursorBlink (on) {
return this._estabPublish(`toggleCursorBlink ${!!on ? 'on' : 'off'}`)
}
disconnect () {
return this._disconnect(true)
}
async issueCustomCommand (command, ...args) {
return new Promise(async (resolve, reject) => {
if (!this._hasConnectedOnce || !this._ackChan) {
reject(`not connected`)
return
}
const nextSeqNo = this._seqNo + 1
this.awaitingAckedResponse[nextSeqNo] = { command, resolve }
let sentSeqNo = await this._estabPublish(`${command} ${args.join(' ')}`)
if (sentSeqNo !== nextSeqNo) {
throw new MismatchedSequenceNumber(sentSeqNo, nextSeqNo, 'sent vs. next')
}
this.awaitingAckedResponse[nextSeqNo].timeoutHandle = setTimeout(() => {
delete this.awaitingAckedResponse[sentSeqNo]
reject(`custom command '${command}' timed out waiting for response (seqNo=${sentSeqNo})!`)
}, this.timeouts.customCommands)
});
}
async connect (displayId, onDisconnect, onReconnect) {
if (!this.id || !displayId || !this.prefix) {
throw new ConfigurationError(`Unspecified id (${this.id}), displayId (${displayId}) or prefix (${this.prefix})`)
}
this.displayId = displayId
this._hasConnectedOnce = false
this._connectConn = new Redis(this.redisCfg)
this._on = {
disconnect: onDisconnect,
reconnect: onReconnect
}
if (!this.publishConn) {
this.publishConn = new Redis(this.redisCfg)
}
if (!this.publishConn || !this._connectConn) {
throw new ConfigurationError('Cannot connect to Redis server')
}
return new Promise((resolve, reject) => {
this._respChan = `${this.prefix}ctrl-init:request:resp`
this._connectConn.on('message', (_channel, message) => {
this.messageStats.rx++
const comps = message.split(' ')
if (comps.length >= 3 && comps[0] === this.displayId && comps[2] === this.id) {
if (comps[1] === 'ok') {
const estabChan = `${this.prefix}estab:${this.displayId}|${this.id}`
this._estabPublish = async (m) => {
if (!this._toHandle) {
this._toHandle = setTimeout(() => {
this._disconnect()
}, this.timeouts.ack)
}
this._seqNo += 1
await this._publish(estabChan, `${this._seqNo} ${m}`)
return this._seqNo
}
this._ackChan = `${estabChan}:ack`
this._ackListener = new Redis(this.redisCfg)
this._ackListener.on('message', (_c, message) => {
this.messageStats.rx++
const comps = message.split(/\s+/)
const mSN = Number(comps[0])
if (Number.isNaN(mSN)) {
return
}
if (this.awaitingAckedResponse[mSN]) {
clearTimeout(this.awaitingAckedResponse[mSN].timeoutHandle)
this.awaitingAckedResponse[mSN].resolve(comps.splice(1).join(' '))
delete this.awaitingAckedResponse[mSN]
}
if (mSN === this._expectNextAckIs) {
clearTimeout(this._toHandle)
this._toHandle = null
this._expectNextAckIs = mSN + 1
} else {
throw new MismatchedSequenceNumber(mSN, this._expectNextAckIs)
}
})
this._ackListener.subscribe(this._ackChan, (err) => {
if (err) {
return reject('Ack listener setup')
}
if (this.disconnectOnExitSignals) {
const sigHandler = (_signal) => {
// allows the option to be changed at runtime (though it probably shouldn't be...)
if (this.disconnectOnExitSignals) {
this._disconnect(true);
}
process.exit(0);
}
['SIGINT', 'SIGTERM', 'SIGHUP'].forEach((signal) => process.on(signal, sigHandler));
}
return resolve(this)
})
this._connectConn.unsubscribe(this._respChan)
if (this._hasConnectedOnce) {
if (this._on.reconnect) {
this._on.reconnect(this, estabChan, this._retryCount)
}
}
// not sure these are all necessary...
clearTimeout(this._rcHandle)
clearTimeout(this._toHandle)
clearTimeout(this._connectTOHandle)
this._rcHandle = this._toHandle = this._connectTOHandle = null
this._hasConnectedOnce = true
this._retryCount = 0
} else if (comps[1] === 'reject') {
comps[3].__proto__.wasFatal = true
reject(comps[3])
if (comps[3] === 'bad_protocol_version') {
this.reconnectable = false
this._disconnect()
}
}
}
})
this._realConnect(reject)
})
}
_publish (channel, message) {
this.messageStats.tx++
return this.publishConn.publish(channel, message)
}
_realConnect (reject = (msg) => { throw new ConnectionError(msg) }) {
this._seqNo = 0
this._expectNextAckIs = 1
this._connectConn.subscribe(this._respChan, (err) => {
if (err) {
return reject('Subscription reject')
}
})
const connParams = [`${this.prefix}ctrl-init`, `${this.id} request ${this.displayId} ${ProtocolVersion}`]
this._publish(...connParams)
this._connectTOHandle = setTimeout(() => {
if (this._rcHandle) {
++this._retryCount
}
clearTimeout(this._rcHandle)
this._rcHandle = null
this._disconnect(false, true)
}, this.timeouts.connect)
}
_disconnect (selfIssued = false, fromConnectTimeout = false) {
if (selfIssued) {
this._estabPublish('disconnect')
}
if (this._on.disconnect && this._hasConnectedOnce && !fromConnectTimeout) {
this._on.disconnect(this._expectNextAckIs, this._seqNo)
}
this._estabPublish = (..._a) => { }
clearTimeout(this._toHandle)
this._toHandle = null
if (this._ackListener) {
this._ackListener.unsubscribe(this._ackChan)
this._ackListener.disconnect()
delete this._ackListener, this._ackListener = this._ackChan = null
}
if (!this.reconnectable || selfIssued) {
clearTimeout(this._rcHandle)
clearTimeout(this._toHandle)
clearTimeout(this._connectTOHandle)
}
if (selfIssued) {
this._connectConn.disconnect()
this.publishConn.disconnect()
}
// return before reconnect if reconnect is disabled or if disconnect() was called directly (selfIssued===true)
if (!this.reconnectable || selfIssued) {
return
}
if (!this._rcHandle) {
this._rcHandle = setTimeout(this._realConnect.bind(this), this.timeouts.reconnect || 0)
}
}
}