-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsApiGw.js
168 lines (149 loc) · 4.51 KB
/
wsApiGw.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
// License: Creative Commons Attribution-NonCommercial 4.0 International
// Based on https://github.com/JamesKyburz/aws-lambda-ws-server
'use strict';
const url = require('url'),
SourceIp = (() => {
const interfaces = require('os').networkInterfaces();
for(const iface of Object.keys(interfaces)){
for(const e of interfaces[iface]) {
if(e.family == 'IPv4' && !(e.internal)) return e.address;
}
}
return null;
})();
function wsApiGw(httpServer, wsApi) {
const apiGw = new (require('./ApiGw'))(wsApi.routes),
mappingKey = wsApi.mappingKey || 'action';
// Create web socket server on top of a regular http server
const wsServer = require('ws').Server;
const wss = new wsServer({ noServer: true });
//const {Server} = require('ws');
//const wss = new (require('ws').Server)({ noServer: true, clientTracking: true });
const clients = {};
function onSocketError(err) {
console.error(`onSocketError ${err}`);
}
httpServer.on('upgrade', async function upgrade(req, socket, head) {
socket.on('error', onSocketError);
const result = await apiGw.invoke(
'$connect', 'WEBSOCKET',
{ //event
requestContext: { routeKey: '$connect', connectionId: req.headers['sec-websocket-key'] },
headers: { ...req.headers, queryStringParameters: url.parse(req.url,true).query },
body: req.body
},
{ clientContext } //context
);
if (result.statusCode < 200 || result.statusCode > 299) {
socket.write(`HTTP/1.1 ${result.statusCode}\r\n\r\n`);
return;
}
socket.removeListener('error', onSocketError);
wss.handleUpgrade(req, socket, head, function done(ws) {
wss.emit('connection', ws, req, 'client');
});
});
// Local equivalent of AWS.ApiGatewayManagementApi functions. Add deleteConnection if required.
const clientContext = {
postToConnection ({Data, ConnectionId}) {
return new Promise((resolve, reject) => {
const ws = clients[ConnectionId];
if (ws) {
ws.send(Data, err => {
(err ? reject(err) : resolve());
});
} else {
const err = new Error('Unknown client:', ConnectionId);
err.statusCode = 410;
reject(err);
}
});
},
getConnection({ConnectionId}) {
return new Promise((resolve, reject) => {
if(clients[ConnectionId]) {
resolve({
"ConnectedAt": new Date,
"Identity": { SourceIp, "UserAgent": null },
"LastActiveAt": new Date()
});
} else {
reject({code: 'GoneException', message: 410});
}
});
},
deleteConnection({ConnectionId}) {
return new Promise((resolve, reject) => {
if(clients[ConnectionId]) {
clients[ConnectionId].close(1008);
delete clients[ConnectionId];
resolve();
} else {
reject({code: 'GoneException', message: 410});
}
});
}
};
wss.on('connection', (ws, req) => {
const connectionId = req.headers['sec-websocket-key'];
/*const result = await apiGw.invoke(
'$connect', 'WEBSOCKET',
{ //event
requestContext: { routeKey: '$connect', connectionId: req.headers['sec-websocket-key'] },
headers: { ...req.headers, queryStringParameters: url.parse(req.url,true).query },
body: req.body
},
{ clientContext } //context
);
//ws_socket.write(`HTTP/1.1 ${result.statusCode} ${result.body}\r\n\r\n`);*/
clients[connectionId] = ws;
ws.on('ping', d => {console.log(`ping ${d}`);});
ws.on('close', async () => {
try {
delete clients[connectionId];
await apiGw.invoke(
'$disconnect', 'WEBSOCKET',
{ //event
requestContext: { routeKey: '$disconnect', connectionId: req.headers['sec-websocket-key'] },
headers: req.headers,
body: req.body
}
);
} catch (e) {
console.error(e);
}
});
ws.on('message', async message => {
let routeKey = null;
let d = null;
try {
d = JSON.parse(message);
} catch(e) {
console.error('ws.on messgage error:', e.code, e.message);
await clientContext.postToConnection({
Data: JSON.stringify({ error: 'Invalid JSON:' + message }),
ConnectionId: connectionId
});
return;
}
routeKey = d[mappingKey] && wsApi.routes[d[mappingKey]] ? d[mappingKey] : '$default';
try {
if(routeKey != '$default') {
await apiGw.invoke(
routeKey,
'WEBSOCKET',
{ //event
requestContext: {routeKey, connectionId: req.headers['sec-websocket-key']},
headers: req.headers,
body: message.toString()
},
{ clientContext } //context
);
}
} catch (e) {
console.error('ws server error:', e.statusCode, e.body);
}
});
});
}
module.exports = wsApiGw;