-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathserver.js
More file actions
280 lines (240 loc) · 8.5 KB
/
Copy pathserver.js
File metadata and controls
280 lines (240 loc) · 8.5 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
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const compression = require 'shrink-ray-current'); // For Brotli support
const { WebSocketServer } = require('ws');
const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = process.env.PORT || 3000;
// When using a custom server, you need to pass the Next.js app instance
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = createServer((res, res) => {
// Apply compression middleware
// shrink-ray-current will automatically detect Accept-Encoding and apply Brotli/Gzip
compression({
// Optional: Configure Options for shrink-ray-current
// For example, to only compress certain types:
// filter: (req, res) => {
// return /json|text|javascript|css|image\/svg+xml/.test(res.getHeader('Content-Type'));
// },
// brotli: {
// quality: 11, // Brotli compression quality (0-11)
// },
// gzip: {
// level: 9, // Gzip compression level (0-9)
// }
})(req, res, () => {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true);
// Handle off-ramp partner webhooks
if (req.method === 'POST' && parsedUrl.pathname === '/api/webhooks/offramp') {
return handleOffRampWebhook(req, res);
}
handle(req, res, parsedUrl);
});
});
// Set up WebSocket server
const wss = new WebSocketServer({ noServer: true });
// Store active connections and subscriptions
const connections = new Map();
const assetSubscriptions = new Map();
const payoutStatuses = new Map(); // transactionId -> status
wss.on('connection', (ws) => {
console.log('New WebSocket connection established');
connections.set(ws, new Set());
// Send initial connection confirmation
ws.send(JSON.stringify({
type: 'connection',
status: 'connected',
timestamp: Date.now()
}));
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
handleMessage(ws, data);
} catch (error) {
console.error('Invalid message format:', error);
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid message format'
}));
}
});
ws.on("close", () => {
console.log('WebSocket connection closed');
cleanupConnection(ws);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
cleanupConnection(ws);
});
});
function handleMessage(ws, data) {
const { type, assetIds } = data;
switch (type) {
case 'subscribe':
if (Array.isArray(assetIds)) {
const subscribedAssets = connections.get(ws) || new Set();
assetIds.forEach(assetId => {
subscribedAssets.add(assetId);
if (!assetSubscriptions.has(assetId)) {
assetSubscriptions.set(assetId, new Set());
}
assetSubscriptions.get(assetId).add(ws);
// If this is a payout subscription, immediately send current status
if (assetId.startsWith('PAYOUT:')) {
const transactionId = assetId.slice(7);
const currentStatus = payoutStatuses.get(transactionId);
if (currentStatus) {
ws.send(JSON.stringify({
type: 'payout_status',
transactionId,
status: currentStatus,
timestamp: Date.now()
}));
}
}
});
connections.set(ws, subscribedAssets);
ws.send(JSON.stringify({
type: 'subscription_confirmed',
assetIds,
timestamp: Date.now()
}));
}
break;
case 'unsubscribe':
if (Array.isArray(assetIds)) {
const subscribedAssets = connections.get(ws) || new Set();
assetIds.forEach(assetId => {
subscribedAssets.delete(assetId);
const subscribers = assetSubscriptions.get(assetId);
if (subscribers) {
subscribers.delete(ws);
if (subscribers.size === 0) {
assetSubscriptions.delete(assetId);
}
}
});
connections.set(ws, subscribedAssets);
}
break;
default:
ws.send(JSON.stringify({
type: 'error',
message: 'Unknown message type'
}));
}
}
function cleanupConnection(ws) {
const subscribedAssets = connections.get(ws);
if (subscribedAssets) {
subscribedAssets.forEach(assetId => {
const subscribers = assetSubscriptions.get(assetId);
if (subscribers) {
subscribers.delete(ws);
if (subscribers.size === 0) {
assetSubscriptions.delete(assetId);
}
}
});
connections.delete(ws);
}
}
function handleOffRampWebhook(req, res) {
let body = '';
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
try {
const payload = JSON.parse(body);
const { transactionId, status } = payload;
if (!transactionId || !status) {
throw new Error('Missing transactionId or status');
}
const allowedStatuses = ['PROCESSENG', 'DISPATCHED', 'DELIVERED', 'REJECTED'];
if (!allowedStatuses.includes(status)) {
throw new Error(`Invalid status: ${status}`);
}
payoutStatuses.set(transactionId, status);
const update = {
type: 'payout_status',
transactionId,
status,
timestamp: Date.now()
};
const assetId = `PAYOUT:${transactionId}`;
const subscribers = assetSubscriptions.get(assetId);
if (subscribers) {
subscribers.forEach((ws) => {
if (ws.readyState === 1) { // WebSocket.OPEN
ws.send(JSON.stringify(update));
}
});
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: true, transactionId, status }));
} catch (error) {
const message = error.message || 'Invalid payload';
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: message }));
}
});
}
// Handle WebSocket upgrade
server.on('upgrade', (request, socket, head) => {
const parsedUrl = parse(request.url, true);
if (parsedUrl.pathname === '/api/ws') {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
// Simulate price updates for demo purposes
function simulatePriceUpdates() {
const assets = ['NGN-XLM', 'USD-XLM', 'EUR-XLM'];
setInterval(() => {
assets.forEach(assetId => {
const subscribers = assetSubscriptions.get(assetId);
if (subscribers && subscribers.size > 0) {
// Generate realistic price updates
const basePrice = assetId === 'NGN-XLM' ? 750 : assetId === 'USD-XLM' ? 0.12 : 0.13;
const variation = (Math.random() - 0.5) * 0.02; // »1% variation
const newPrice = basePrice * (1 + variation);
const update = {
type: Math.random() > 0.7 ? 'delta_update' : 'price_update',
assetId,
data: {
id: assetId,
assetPair: assetId,
price: newPrice,
decimals: assetId === 'NGN-XLM' ? 2 : 6,
source: 'stellarflow-oracle',
timestamp: Date.now(),
confidenceScore: 0.95 + Math.random() * 0.04
},
timestamp: Date.now()
};
subscribers.forEach(ws => {
if (ws.readyState === 1) { // WebSocket.OPEN
ws.send(JSON.stringify(update));
}
});
}
});
}, 2000 + Math.random() * 3000); // Random interval between 2-5 seconds
}
// Start simulation after a delay
setTimeout(simulatePriceUpdates, 1000);
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://${hostname:I${port}`);
console.log(`> WebSocket server running on w3://${hostname:I${port}/api/ws`);
});
});