-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathws-server.js
More file actions
486 lines (414 loc) · 13.9 KB
/
ws-server.js
File metadata and controls
486 lines (414 loc) · 13.9 KB
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/**
* Standalone WebSocket Server
*
* Deploy to Railway, Render, or any Node.js host for full WebSocket support.
*
* Features:
* - Real-time news broadcasting
* - Subscription-based filtering
* - Alert system integration
* - Health monitoring
*
* Usage:
* npm install ws
* node ws-server.js
*
* Or with environment:
* PORT=8080 node ws-server.js
*/
const WebSocket = require('ws');
const http = require('http');
const PORT = process.env.PORT || 8080;
const POLL_INTERVAL = 30000; // 30 seconds
const ALERT_EVAL_INTERVAL = 30000; // 30 seconds for alert evaluation
const NEWS_API = process.env.NEWS_API || 'https://free-crypto-news.vercel.app';
// =============================================================================
// MESSAGE TYPES
// =============================================================================
const WS_MSG_TYPES = {
// Connection
CONNECTED: 'connected',
PING: 'ping',
PONG: 'pong',
// Subscriptions
SUBSCRIBE: 'subscribe',
UNSUBSCRIBE: 'unsubscribe',
SUBSCRIBED: 'subscribed',
UNSUBSCRIBED: 'unsubscribed',
// News
NEWS: 'news',
BREAKING: 'breaking',
// Alerts
ALERT: 'alert',
SUBSCRIBE_ALERTS: 'subscribe_alerts',
UNSUBSCRIBE_ALERTS: 'unsubscribe_alerts',
ALERTS_SUBSCRIBED: 'alerts_subscribed',
ALERTS_UNSUBSCRIBED: 'alerts_unsubscribed',
};
// Client management
const clients = new Map();
// Create HTTP server for health checks
const server = http.createServer((req, res) => {
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
status: 'ok',
clients: clients.size,
uptime: process.uptime(),
}));
return;
}
if (req.url === '/stats') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(getStats()));
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Free Crypto News WebSocket Server\n\nConnect via ws://' + req.headers.host);
});
// Create WebSocket server
const wss = new WebSocket.Server({ server });
// Generate client ID
function generateClientId() {
return `ws_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
// Handle new connection
wss.on('connection', (ws, req) => {
const clientId = generateClientId();
const ip = req.socket.remoteAddress;
clients.set(clientId, {
ws,
ip,
subscription: {
sources: [],
categories: [],
keywords: [],
coins: [],
},
alertSubscriptions: new Set(), // Alert rule IDs or '*' for all
connectedAt: Date.now(),
lastPing: Date.now(),
});
console.log(`[${new Date().toISOString()}] Client connected: ${clientId} from ${ip}`);
// Send welcome message
ws.send(JSON.stringify({
type: WS_MSG_TYPES.CONNECTED,
payload: {
clientId,
message: 'Connected to Free Crypto News WebSocket',
serverTime: new Date().toISOString(),
features: ['news', 'breaking', 'alerts'],
},
}));
// Handle messages
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
handleMessage(clientId, message);
} catch (error) {
console.error('Parse error:', error.message);
}
});
// Handle close
ws.on('close', () => {
console.log(`[${new Date().toISOString()}] Client disconnected: ${clientId}`);
clients.delete(clientId);
});
// Handle errors
ws.on('error', (error) => {
console.error(`Client ${clientId} error:`, error.message);
clients.delete(clientId);
});
});
// Handle incoming message
function handleMessage(clientId, message) {
const client = clients.get(clientId);
if (!client) return;
switch (message.type) {
case 'subscribe':
case WS_MSG_TYPES.SUBSCRIBE:
handleSubscribe(clientId, message.payload);
break;
case 'unsubscribe':
case WS_MSG_TYPES.UNSUBSCRIBE:
handleUnsubscribe(clientId, message.payload);
break;
case 'ping':
case WS_MSG_TYPES.PING:
client.lastPing = Date.now();
client.ws.send(JSON.stringify({
type: WS_MSG_TYPES.PONG,
timestamp: new Date().toISOString(),
}));
break;
case WS_MSG_TYPES.SUBSCRIBE_ALERTS:
handleSubscribeAlerts(clientId, message.payload);
break;
case WS_MSG_TYPES.UNSUBSCRIBE_ALERTS:
handleUnsubscribeAlerts(clientId, message.payload);
break;
default:
console.log(`Unknown message type: ${message.type}`);
}
}
// Handle subscribe
function handleSubscribe(clientId, payload) {
const client = clients.get(clientId);
if (!client) return;
if (payload.sources) {
client.subscription.sources = [...new Set([...client.subscription.sources, ...payload.sources])];
}
if (payload.categories) {
client.subscription.categories = [...new Set([...client.subscription.categories, ...payload.categories])];
}
if (payload.keywords) {
client.subscription.keywords = [...new Set([...client.subscription.keywords, ...payload.keywords])];
}
if (payload.coins) {
client.subscription.coins = [...new Set([...client.subscription.coins, ...payload.coins])];
}
client.ws.send(JSON.stringify({
type: WS_MSG_TYPES.SUBSCRIBED,
payload: { subscription: client.subscription },
timestamp: new Date().toISOString(),
}));
console.log(`[${new Date().toISOString()}] Client ${clientId} subscribed:`, client.subscription);
}
// Handle unsubscribe
function handleUnsubscribe(clientId, payload) {
const client = clients.get(clientId);
if (!client) return;
if (payload.sources) {
client.subscription.sources = client.subscription.sources.filter(s => !payload.sources.includes(s));
}
if (payload.categories) {
client.subscription.categories = client.subscription.categories.filter(c => !payload.categories.includes(c));
}
if (payload.keywords) {
client.subscription.keywords = client.subscription.keywords.filter(k => !payload.keywords.includes(k));
}
if (payload.coins) {
client.subscription.coins = client.subscription.coins.filter(c => !payload.coins.includes(c));
}
client.ws.send(JSON.stringify({
type: WS_MSG_TYPES.UNSUBSCRIBED,
payload: { subscription: client.subscription },
timestamp: new Date().toISOString(),
}));
}
// Handle alert subscription
function handleSubscribeAlerts(clientId, payload) {
const client = clients.get(clientId);
if (!client) return;
// Subscribe to specific rule IDs or '*' for all alerts
const ruleIds = payload?.ruleIds || ['*'];
for (const ruleId of ruleIds) {
client.alertSubscriptions.add(ruleId);
}
client.ws.send(JSON.stringify({
type: WS_MSG_TYPES.ALERTS_SUBSCRIBED,
payload: {
subscribedTo: Array.from(client.alertSubscriptions),
},
timestamp: new Date().toISOString(),
}));
console.log(`[${new Date().toISOString()}] Client ${clientId} subscribed to alerts:`, Array.from(client.alertSubscriptions));
}
// Handle alert unsubscription
function handleUnsubscribeAlerts(clientId, payload) {
const client = clients.get(clientId);
if (!client) return;
const ruleIds = payload?.ruleIds;
if (!ruleIds || ruleIds.length === 0) {
// Unsubscribe from all
client.alertSubscriptions.clear();
} else {
for (const ruleId of ruleIds) {
client.alertSubscriptions.delete(ruleId);
}
}
client.ws.send(JSON.stringify({
type: WS_MSG_TYPES.ALERTS_UNSUBSCRIBED,
payload: {
subscribedTo: Array.from(client.alertSubscriptions),
},
timestamp: new Date().toISOString(),
}));
}
// Broadcast news to clients
function broadcastNews(articles, isBreaking = false) {
const type = isBreaking ? WS_MSG_TYPES.BREAKING : WS_MSG_TYPES.NEWS;
clients.forEach((client, clientId) => {
if (client.ws.readyState !== WebSocket.OPEN) return;
const sub = client.subscription;
const filteredArticles = articles.filter(article => {
// If no subscriptions, send everything
if (sub.sources.length === 0 && sub.categories.length === 0 && sub.keywords.length === 0) {
return true;
}
// Check source match
if (sub.sources.length > 0 && sub.sources.includes(article.sourceKey || article.source.toLowerCase())) {
return true;
}
// Check category match
if (sub.categories.length > 0 && sub.categories.includes(article.category)) {
return true;
}
// Check keyword match
if (sub.keywords.length > 0) {
const title = article.title.toLowerCase();
if (sub.keywords.some(kw => title.includes(kw.toLowerCase()))) {
return true;
}
}
return false;
});
if (filteredArticles.length > 0) {
client.ws.send(JSON.stringify({
type,
payload: { articles: filteredArticles },
timestamp: new Date().toISOString(),
}));
}
});
}
// Broadcast alert to subscribed clients
function broadcastAlert(alertEvent) {
let delivered = 0;
clients.forEach((client, clientId) => {
if (client.ws.readyState !== WebSocket.OPEN) return;
// Check if client is subscribed to this alert
const isSubscribed =
client.alertSubscriptions.has('*') ||
client.alertSubscriptions.has(alertEvent.ruleId);
if (isSubscribed) {
try {
client.ws.send(JSON.stringify({
type: WS_MSG_TYPES.ALERT,
data: alertEvent,
timestamp: new Date().toISOString(),
}));
delivered++;
} catch (error) {
console.error(`Failed to send alert to client ${clientId}:`, error.message);
}
}
});
if (delivered > 0) {
console.log(`[${new Date().toISOString()}] Alert ${alertEvent.id} delivered to ${delivered} clients`);
}
return delivered;
}
// Broadcast multiple alerts
function broadcastAlerts(alertEvents) {
for (const event of alertEvents) {
broadcastAlert(event);
}
}
// Get server stats
function getStats() {
let activeConnections = 0;
let alertSubscribers = 0;
const subscriptions = { sources: 0, categories: 0, keywords: 0, coins: 0, alerts: 0 };
clients.forEach((client) => {
if (client.ws.readyState === WebSocket.OPEN) {
activeConnections++;
subscriptions.sources += client.subscription.sources.length;
subscriptions.categories += client.subscription.categories.length;
subscriptions.keywords += client.subscription.keywords.length;
subscriptions.coins += client.subscription.coins.length;
subscriptions.alerts += client.alertSubscriptions.size;
if (client.alertSubscriptions.size > 0) {
alertSubscribers++;
}
}
});
return {
totalConnections: clients.size,
activeConnections,
alertSubscribers,
subscriptions,
uptime: process.uptime(),
memoryUsage: process.memoryUsage(),
};
}
// Fetch and broadcast news periodically
let lastArticleLink = '';
async function pollNews() {
try {
// Fetch latest news
const response = await fetch(`${NEWS_API}/api/news?limit=10`);
const data = await response.json();
if (data.articles && data.articles.length > 0) {
const latestLink = data.articles[0].link;
// Only broadcast if there's new content
if (latestLink !== lastArticleLink) {
lastArticleLink = latestLink;
console.log(`[${new Date().toISOString()}] Broadcasting ${data.articles.length} articles to ${clients.size} clients`);
broadcastNews(data.articles.slice(0, 5));
}
}
// Fetch breaking news
const breakingResponse = await fetch(`${NEWS_API}/api/breaking?limit=3`);
const breakingData = await breakingResponse.json();
if (breakingData.articles && breakingData.articles.length > 0) {
broadcastNews(breakingData.articles, true);
}
} catch (error) {
console.error('Poll error:', error.message);
}
}
// Cleanup stale connections
function cleanupStale() {
const now = Date.now();
const maxIdle = 5 * 60 * 1000; // 5 minutes
clients.forEach((client, clientId) => {
if (now - client.lastPing > maxIdle || client.ws.readyState !== WebSocket.OPEN) {
console.log(`[${new Date().toISOString()}] Cleaning up stale client: ${clientId}`);
clients.delete(clientId);
}
});
}
// Evaluate alerts and broadcast triggered ones
async function evaluateAndBroadcastAlerts() {
try {
const response = await fetch(`${NEWS_API}/api/alerts?action=evaluate`);
const data = await response.json();
if (data.events && data.events.length > 0) {
console.log(`[${new Date().toISOString()}] Triggered ${data.events.length} alerts`);
broadcastAlerts(data.events);
}
} catch (error) {
console.error('Alert evaluation error:', error.message);
}
}
// Start server
server.listen(PORT, () => {
console.log(`
╔═══════════════════════════════════════════════════════════╗
║ Free Crypto News WebSocket Server ║
╠═══════════════════════════════════════════════════════════╣
║ WebSocket: ws://localhost:${PORT} ║
║ Health: http://localhost:${PORT}/health ║
║ Stats: http://localhost:${PORT}/stats ║
║ Features: news, breaking news, alerts ║
╚═══════════════════════════════════════════════════════════╝
`);
// Start news polling
setInterval(pollNews, POLL_INTERVAL);
pollNews(); // Initial poll
// Start alert evaluation
setInterval(evaluateAndBroadcastAlerts, ALERT_EVAL_INTERVAL);
// Cleanup every minute
setInterval(cleanupStale, 60000);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('Shutting down...');
wss.clients.forEach((client) => {
client.close(1001, 'Server shutting down');
});
server.close(() => {
process.exit(0);
});
});