-
-
Notifications
You must be signed in to change notification settings - Fork 797
/
Copy pathWebSocketClients.js
269 lines (216 loc) · 6.59 KB
/
WebSocketClients.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
import { OPEN } from 'ws'
import {
WebSocketConnectEvent,
WebSocketDisconnectEvent,
WebSocketEvent,
} from './lambda-events/index.js'
import debugLog from '../../debugLog.js'
import serverlessLog from '../../serverlessLog.js'
import {
DEFAULT_WEBSOCKETS_API_ROUTE_SELECTION_EXPRESSION,
DEFAULT_WEBSOCKETS_ROUTE,
} from '../../config/index.js'
import { jsonPath } from '../../utils/index.js'
const { parse, stringify } = JSON
export default class WebSocketClients {
#clients = new Map()
#lambda = null
#options = null
#webSocketRoutes = new Map()
#websocketsApiRouteSelectionExpression = null
#idleTimeouts = new WeakMap()
#hardTimeouts = new WeakMap()
constructor(serverless, options, lambda, v3Utils) {
this.#lambda = lambda
this.#options = options
this.#websocketsApiRouteSelectionExpression =
serverless.service.provider.websocketsApiRouteSelectionExpression ||
DEFAULT_WEBSOCKETS_API_ROUTE_SELECTION_EXPRESSION
if (v3Utils) {
this.log = v3Utils.log
this.progress = v3Utils.progress
this.writeText = v3Utils.writeText
this.v3Utils = v3Utils
}
}
_addWebSocketClient(client, connectionId) {
this.#clients.set(client, connectionId)
this.#clients.set(connectionId, client)
this._onWebSocketUsed(connectionId)
this._addHardTimeout(client, connectionId)
}
_removeWebSocketClient(client) {
const connectionId = this.#clients.get(client)
this.#clients.delete(client)
this.#clients.delete(connectionId)
return connectionId
}
_getWebSocketClient(connectionId) {
return this.#clients.get(connectionId)
}
_addHardTimeout(client, connectionId) {
const timeoutId = setTimeout(() => {
if (this.log) {
this.log.debug(`timeout:hard:${connectionId}`)
} else {
debugLog(`timeout:hard:${connectionId}`)
}
client.close(1001, 'Going away')
}, this.#options.webSocketHardTimeout * 1000)
this.#hardTimeouts.set(client, timeoutId)
}
_clearHardTimeout(client) {
const timeoutId = this.#hardTimeouts.get(client)
clearTimeout(timeoutId)
}
_onWebSocketUsed(connectionId) {
const client = this._getWebSocketClient(connectionId)
this._clearIdleTimeout(client)
if (this.log) {
this.log.debug(`timeout:idle:${connectionId}:reset`)
} else {
debugLog(`timeout:idle:${connectionId}:reset`)
}
const timeoutId = setTimeout(() => {
if (this.log) {
this.log.debug(`timeout:idle:${connectionId}:trigger`)
} else {
debugLog(`timeout:idle:${connectionId}:trigger`)
}
client.close(1001, 'Going away')
}, this.#options.webSocketIdleTimeout * 1000)
this.#idleTimeouts.set(client, timeoutId)
}
_clearIdleTimeout(client) {
const timeoutId = this.#idleTimeouts.get(client)
clearTimeout(timeoutId)
}
async _processEvent(websocketClient, connectionId, route, event) {
let functionKey = this.#webSocketRoutes.get(route)
if (!functionKey && route !== '$connect' && route !== '$disconnect') {
functionKey = this.#webSocketRoutes.get('$default')
}
if (!functionKey) {
return
}
const sendError = (err) => {
if (websocketClient.readyState === OPEN) {
websocketClient.send(
stringify({
connectionId,
message: 'Internal server error',
requestId: '1234567890',
}),
)
}
// mimic AWS behaviour (close connection) when the $connect route handler throws
if (route === '$connect') {
websocketClient.close()
}
if (this.log) {
this.log.debug(`Error in route handler '${functionKey}'`, err)
} else {
debugLog(`Error in route handler '${functionKey}'`, err)
}
}
const lambdaFunction = this.#lambda.get(functionKey)
lambdaFunction.setEvent(event)
// let result
try {
/* result = */ await lambdaFunction.runHandler()
// TODO what to do with "result"?
} catch (err) {
if (this.log) {
this.log.error(err)
} else {
console.log(err)
}
sendError(err)
}
}
_getRoute(value) {
let json
try {
json = parse(value)
} catch (err) {
return DEFAULT_WEBSOCKETS_ROUTE
}
const routeSelectionExpression =
this.#websocketsApiRouteSelectionExpression.replace('request.body', '')
const route = jsonPath(json, routeSelectionExpression)
if (typeof route !== 'string') {
return DEFAULT_WEBSOCKETS_ROUTE
}
return route || DEFAULT_WEBSOCKETS_ROUTE
}
addClient(webSocketClient, request, connectionId) {
this._addWebSocketClient(webSocketClient, connectionId)
const connectEvent = new WebSocketConnectEvent(
connectionId,
request,
this.#options,
).create()
this._processEvent(webSocketClient, connectionId, '$connect', connectEvent)
webSocketClient.on('close', () => {
if (this.log) {
this.log.debug(`disconnect:${connectionId}`)
} else {
debugLog(`disconnect:${connectionId}`)
}
this._removeWebSocketClient(webSocketClient)
const disconnectEvent = new WebSocketDisconnectEvent(
connectionId,
).create()
this._clearHardTimeout(webSocketClient)
this._clearIdleTimeout(webSocketClient)
this._processEvent(
webSocketClient,
connectionId,
'$disconnect',
disconnectEvent,
)
})
webSocketClient.on('message', (message) => {
if (this.log) {
this.log.debug(`message:${message}`)
} else {
debugLog(`message:${message}`)
}
const route = this._getRoute(message)
if (this.log) {
this.log.debug(`route:${route} on connection=${connectionId}`)
} else {
debugLog(`route:${route} on connection=${connectionId}`)
}
const event = new WebSocketEvent(connectionId, route, message).create()
this._onWebSocketUsed(connectionId)
this._processEvent(webSocketClient, connectionId, route, event)
})
}
addRoute(functionKey, route) {
// set the route name
this.#webSocketRoutes.set(route, functionKey)
if (this.log) {
this.log.notice(`route '${route}'`)
} else {
serverlessLog(`route '${route}'`)
}
}
close(connectionId) {
const client = this._getWebSocketClient(connectionId)
if (client) {
client.close()
return true
}
return false
}
send(connectionId, payload) {
const client = this._getWebSocketClient(connectionId)
if (client) {
this._onWebSocketUsed(connectionId)
client.send(payload)
return true
}
return false
}
}