forked from Jollyfant/node-seedlink-data-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseedlink-websocket.js
400 lines (282 loc) · 9.39 KB
/
seedlink-websocket.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
* nodejs-seedlink-data-proxy
*
* Seedlink server proxy written for NodeJS. Connects to
* multiple seedlink servers and broadcasts unpacked data samples
* over HTML5 websockets.
*
* Copyright: ORFEUS Data Center, 2019
* Author: Mathijs Koymans
* Licensed under MIT
*
*/
"use strict";
const __VERSION__ = "1.1.1";
const SeedlinkWebsocket = function(configuration, callback) {
/*
* Class SeedlinkWebsocket
* Websocket server that relays unpacked data from arbitrary
* Seedlink server to the browser
*/
const { Server } = require("ws");
this.configuration = configuration;
// Get process environment variables (Docker)
var host = process.env.SERVICE_HOST || this.configuration.HOST;
var port = Number(process.env.SERVICE_PORT) || Number(this.configuration.PORT);
this.host = host;
this.port = port;
this.name = configuration.__NAME__;
// Create a websocket server
this.websocket = new Server({ host, port });
// Create a logger
this.logger = this.setupLogger();
// Create all channels
this.createSeedlinkProxies();
// Enable pinging of clients
this.enableHeartbeat();
// When a connection is made to the websocket
this.websocket.on("connection", this.attachSocketHandlers.bind(this));
// Signal received: close server
process.once("SIGINT", this.close.bind(this));
process.once("SIGTERM", this.close.bind(this));
// Callback if passed
if(callback instanceof Function) {
callback.call(this);
}
}
SeedlinkWebsocket.prototype.close = function() {
/*
* Function SeedlinkWebsocket.close
* Attaches listeners to the websocket
*/
// Clear the heartbeat interval otherwise the process
clearInterval(this.interval);
this.websocket.close()
}
SeedlinkWebsocket.prototype.attachSocketHandlers = function(socket, request) {
/*
* Function SeedlinkWebsocket.attachSocketHandlers
* Attaches listeners to the websocket
*/
function heartbeat() {
/*
* Function heartbeat
* Sets heartbeat state to received
*/
this.__receivedHeartbeat = true;
}
// User feedback that connection is ok
socket.emit("write", "Connected to Seedlink Proxy.");
socket.__receivedHeartbeat = true;
// Socket was closed: unsubscribe from all rooms
socket.on("close", () => this.unsubscribeAll(socket));
// Called when writing to socket
socket.on("write", function(object) {
// Map the item to write to a JSON object
var json = this.mapMessage(object);
// Write a log for exported mSEED record
if(!json.success && !json.error) {
this.logRecordMessage(request, json);
}
// Write the data over socket (NOOP callback)
socket.send(JSON.stringify(json), Function.prototype);
}.bind(this));
// Message has been received: try parsing JSON
socket.on("message", function(message) {
try {
this.handleIncomingMessage(socket, message);
} catch(exception) {
socket.emit("write", exception);
}
}.bind(this));
// Set the pong listener
socket.on("pong", heartbeat);
}
SeedlinkWebsocket.prototype.mapMessage = function(object) {
/*
* Function SeedlinkWebsocket.mapMessage
* Maps the socket message to write to a JSON object
*/
// An error was passed
if(object instanceof Error) {
return new Object({"error": (this.configuration.__DEBUG__ ? object.stack : object.message)});
}
// String or object was passed
if(typeof(object) === "string") {
return new Object({"success": object});
}
// An unpacked mSEED record was passed
return object;
}
SeedlinkWebsocket.prototype.setupLogger = function() {
/*
* Function SeedlinkWebsocket.setupLogger
* Sets up the service logfile
*/
// Lazy module loading
const fs = require("fs");
const path = require("path");
var logDirectory = path.join(__dirname, "logs");
// Check if the log directory exists else create it
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
return fs.createWriteStream(path.join(logDirectory, "service.log"), {"flags": "a"});
}
SeedlinkWebsocket.prototype.logRecordMessage = function(request, json) {
/*
* Function SeedlinkWebsocket.logRecordMessage
* Writes websocket mSEED record messages to logfile
*/
function extractClientIP(request) {
/*
* Function SeedlinkWebsocket.logRecordMessage::extractClientIP
* Extracts the client IP from the request headers
*/
return request.connection.remoteAddress || request.headers["x-forwarded-for"] || null;
}
var requestLog = new Object({
"timestamp": new Date().toISOString(),
"network": json.network,
"station": json.station,
"location": json.location,
"channel": json.channel,
"nSamples": json.data.length,
"agent": request.headers["user-agent"] || null,
"client": extractClientIP(request),
"version": __VERSION__
});
return this.logger.write(JSON.stringify(requestLog) + "\n");
}
SeedlinkWebsocket.prototype.handleIncomingMessage = function(socket, message) {
/*
* Function SeedlinkWebsocket.handleIncomingMessage
* Code to handle messages send to the server over the websocket
*/
const OPERATIONS = new Array(
"subscribe",
"unsubscribe",
"channels",
"info"
);
function formatInfoString(x) {
/*
* Function SeedlinkWebsocket.handleIncomingMessage::formatInfoString
* Formats information string for a Seedlink proxy channel
*/
return new Array(x.network, x.station, x.location, x.channel).join(".");
}
function isAllowed(x) {
/*
* Function SeedlinkWebsocket.handleIncomingMessage::isAllowed
* Returns whether a requested operation is allowed by the websocket server
*/
return OPERATIONS.includes(x);
}
var json = JSON.parse(message);
// Confirm that the operation is allowed
if(!Object.keys(json).every(isAllowed)) {
throw new Error("Invalid operation requested. Expected: " + OPERATIONS.join(", "));
}
// Handle the requested operations
if(json.subscribe) {
this.subscribe(json.subscribe, socket);
}
if(json.unsubscribe) {
this.unsubscribe(json.unsubscribe, socket);
}
// Write information on the selectors
if(json.info) {
if(this.channelExists(json.info)) {
socket.emit("write", this.getSeedlinkProxy(json.info).selectors.map(formatInfoString).join(" "));
}
}
// Request to show the available channels
if(json.channels) {
socket.emit("write", Object.keys(this.channels).sort().join(" "));
}
}
SeedlinkWebsocket.prototype.enableHeartbeat = function() {
/*
* Function SeedlinkWebsocket.enableHeartbeat
* Enable heartbeat polling each connected websocket
*/
this.interval = setInterval(function() {
this.websocket.clients.forEach(this.checkHeartbeat);
}.bind(this), this.configuration.HEARTBEAT_INTERVAL_MS);
}
SeedlinkWebsocket.prototype.checkHeartbeat = function(socket) {
/*
* Function SeedlinkWebsocket.checkHeartbeat
* Checks whether the socket is still alive and responds to ping messages with pong
*/
// Socket did not response to heartbeat since last check
if(!socket.__receivedHeartbeat) {
return socket.terminate();
}
// Set up for a new heartbeat
socket.__receivedHeartbeat = false;
// Ping the socket
socket.ping();
}
SeedlinkWebsocket.prototype.unsubscribeAll = function(socket) {
/*
* Function SeedlinkWebsocket.unsubscribeAll
* Unsubscribes socket from all channels
*/
// Go over all channels and unsubscribe the socket
Object.values(this.channels).forEach(function(channel) {
this.unsubscribe(channel.name, socket);
}, this);
}
SeedlinkWebsocket.prototype.createSeedlinkProxies = function() {
/*
* Function SeedlinkWebsocket.createSeedlinkProxies
* Initializes the configured seedlink proxies
*/
const SeedlinkProxy = require("./lib/seedlink-proxy");
// Create a map for the available channels
this.channels = new Object();
// Read the channel configuration and create new sleeping proxies
require("./channel-config").forEach(function(channel) {
this.channels[channel.name] = new SeedlinkProxy(channel);
}, this);
}
SeedlinkWebsocket.prototype.getSeedlinkProxy = function(channel) {
/*
* Function SeedlinkWebsocket.getSeedlinkProxy
* Returns the particular seedlink proxy with an identifier
*/
return this.channels[channel];
}
SeedlinkWebsocket.prototype.unsubscribe = function(channel, socket) {
/*
* Function SeedlinkWebsocket.unsubscribe
* Unsubscribes from a particular data Seedlink stream
*/
// Sanity check if the channel exists
if(!this.channelExists(channel)) {
return socket.emit("write", new Error("Invalid channel unsubscription requested: " + channel));
}
// Get the particular seedlink proxy
this.getSeedlinkProxy(channel).removeSocket(socket);
}
SeedlinkWebsocket.prototype.channelExists = function(channel) {
/*
* Function SeedlinkWebsocket.channelExists
* Checks whether a channel name has been configured
*/
return this.channels.hasOwnProperty(channel);
}
SeedlinkWebsocket.prototype.subscribe = function(channel, socket) {
/*
* Function SeedlinkWebsocket.subscribe
* Subscribes from a particular data Seedlink stream
*/
if(!this.channelExists(channel)) {
return socket.emit("write", new Error("Invalid channel subscription requested: " + channel));
}
// Add the socket to the channel
this.getSeedlinkProxy(channel).addSocket(socket);
}
// Expose the class
module.exports.Server = SeedlinkWebsocket;
module.exports.__VERSION__ = __VERSION__;