test_websocket_updates.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /**
  2. * Integration test for WebSocket session updates
  3. * Tests the complete flow of real-time WebSocket communication for hedging sessions
  4. */
  5. import { describe, it, expect, beforeAll, afterAll, beforeEach } from '@jest/globals';
  6. import WebSocket from 'ws';
  7. import { HedgingManager } from '../../src/core/HedgingManager';
  8. import { WebSocketManager } from '../../src/services/WebSocketManager';
  9. import { SessionUpdateMessage, SessionSubscription } from '../../src/types/hedging';
  10. describe('WebSocket Session Updates Integration', () => {
  11. let hedgingManager: HedgingManager;
  12. let webSocketManager: WebSocketManager;
  13. let testSessionId: string;
  14. let wsServer: any;
  15. let wsPort: number = 8080;
  16. beforeAll(async () => {
  17. // Initialize hedging manager
  18. hedgingManager = new HedgingManager({
  19. accounts: './config/accounts.json',
  20. hedging: './config/hedging-config.json',
  21. marketData: './config/market-data-config.json'
  22. });
  23. // Initialize WebSocket manager
  24. webSocketManager = new WebSocketManager({
  25. port: wsPort,
  26. heartbeatInterval: 30000,
  27. reconnectInterval: 5000,
  28. maxReconnectAttempts: 5,
  29. connectionTimeout: 10000
  30. });
  31. await hedgingManager.initialize();
  32. await webSocketManager.initialize();
  33. });
  34. afterAll(async () => {
  35. if (hedgingManager) {
  36. await hedgingManager.shutdown();
  37. }
  38. if (webSocketManager) {
  39. await webSocketManager.shutdown();
  40. }
  41. if (wsServer) {
  42. wsServer.close();
  43. }
  44. });
  45. beforeEach(async () => {
  46. // Create a test session for each test
  47. const sessionRequest = {
  48. name: 'WebSocket Test Session',
  49. accountIds: ['account-1', 'account-2'],
  50. volumeTarget: 10000,
  51. strategy: {
  52. symbol: 'ETH/USD',
  53. volumeDistribution: 'equal' as const,
  54. priceRange: { min: 0.001, max: 0.01 },
  55. timing: { minInterval: 30, maxInterval: 120, orderSize: { min: 100, max: 500 } },
  56. riskLimits: { maxPositionSize: 0.1, stopLossThreshold: 0.05, maxSlippage: 0.02 },
  57. orderTypes: { primary: 'limit' as const, fallback: 'market' as const }
  58. }
  59. };
  60. try {
  61. const session = await hedgingManager.createSession(sessionRequest);
  62. testSessionId = session.id;
  63. } catch (error) {
  64. testSessionId = 'mock-session-id';
  65. }
  66. });
  67. describe('WebSocket Connection', () => {
  68. it('should establish WebSocket connection', (done) => {
  69. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`);
  70. ws.on('open', () => {
  71. expect(ws.readyState).toBe(WebSocket.OPEN);
  72. ws.close();
  73. done();
  74. });
  75. ws.on('error', (error) => {
  76. // This test should fail initially since WebSocket server doesn't exist yet
  77. expect(error.message).toContain('ECONNREFUSED');
  78. done();
  79. });
  80. });
  81. it('should authenticate WebSocket connection', (done) => {
  82. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  83. headers: {
  84. 'Authorization': 'Bearer test-api-key'
  85. }
  86. });
  87. ws.on('open', () => {
  88. // Send authentication message
  89. const authMessage = {
  90. type: 'authenticate',
  91. token: 'test-api-key'
  92. };
  93. ws.send(JSON.stringify(authMessage));
  94. });
  95. ws.on('message', (data) => {
  96. const message = JSON.parse(data.toString());
  97. if (message.type === 'authenticated') {
  98. expect(message.success).toBe(true);
  99. ws.close();
  100. done();
  101. }
  102. });
  103. ws.on('error', (error) => {
  104. // This test should fail initially since WebSocket server doesn't exist yet
  105. expect(error.message).toContain('ECONNREFUSED');
  106. done();
  107. });
  108. });
  109. it('should reject unauthenticated connections', (done) => {
  110. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`);
  111. ws.on('open', () => {
  112. // Don't send authentication
  113. setTimeout(() => {
  114. expect(ws.readyState).toBe(WebSocket.CLOSED);
  115. done();
  116. }, 1000);
  117. });
  118. ws.on('error', (error) => {
  119. // This test should fail initially since WebSocket server doesn't exist yet
  120. expect(error.message).toContain('ECONNREFUSED');
  121. done();
  122. });
  123. });
  124. });
  125. describe('Session Subscription', () => {
  126. it('should subscribe to session updates', (done) => {
  127. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  128. headers: {
  129. 'Authorization': 'Bearer test-api-key'
  130. }
  131. });
  132. ws.on('open', () => {
  133. // Authenticate first
  134. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  135. });
  136. ws.on('message', (data) => {
  137. const message = JSON.parse(data.toString());
  138. if (message.type === 'authenticated') {
  139. // Subscribe to session updates
  140. const subscription: SessionSubscription = {
  141. type: 'subscribe',
  142. sessionId: testSessionId,
  143. channels: ['status', 'orders', 'risk', 'metrics']
  144. };
  145. ws.send(JSON.stringify(subscription));
  146. } else if (message.type === 'subscribed') {
  147. expect(message.success).toBe(true);
  148. expect(message.channels).toEqual(['status', 'orders', 'risk', 'metrics']);
  149. ws.close();
  150. done();
  151. }
  152. });
  153. ws.on('error', (error) => {
  154. // This test should fail initially since WebSocket server doesn't exist yet
  155. expect(error.message).toContain('ECONNREFUSED');
  156. done();
  157. });
  158. });
  159. it('should validate subscription channels', (done) => {
  160. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  161. headers: {
  162. 'Authorization': 'Bearer test-api-key'
  163. }
  164. });
  165. ws.on('open', () => {
  166. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  167. });
  168. ws.on('message', (data) => {
  169. const message = JSON.parse(data.toString());
  170. if (message.type === 'authenticated') {
  171. // Subscribe with invalid channel
  172. const invalidSubscription = {
  173. type: 'subscribe',
  174. sessionId: testSessionId,
  175. channels: ['invalid_channel']
  176. };
  177. ws.send(JSON.stringify(invalidSubscription));
  178. } else if (message.type === 'error') {
  179. expect(message.error.code).toBe('INVALID_CHANNEL');
  180. ws.close();
  181. done();
  182. }
  183. });
  184. ws.on('error', (error) => {
  185. // This test should fail initially since WebSocket server doesn't exist yet
  186. expect(error.message).toContain('ECONNREFUSED');
  187. done();
  188. });
  189. });
  190. });
  191. describe('Real-time Updates', () => {
  192. it('should receive status updates', (done) => {
  193. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  194. headers: {
  195. 'Authorization': 'Bearer test-api-key'
  196. }
  197. });
  198. let updateReceived = false;
  199. ws.on('open', () => {
  200. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  201. });
  202. ws.on('message', (data) => {
  203. const message = JSON.parse(data.toString());
  204. if (message.type === 'authenticated') {
  205. // Subscribe to status updates
  206. ws.send(JSON.stringify({
  207. type: 'subscribe',
  208. sessionId: testSessionId,
  209. channels: ['status']
  210. }));
  211. } else if (message.type === 'session_update' && message.channel === 'status') {
  212. const updateMessage: SessionUpdateMessage = message;
  213. expect(updateMessage.sessionId).toBe(testSessionId);
  214. expect(updateMessage.channel).toBe('status');
  215. expect(updateMessage.data.status).toBeDefined();
  216. expect(updateMessage.timestamp).toBeDefined();
  217. updateReceived = true;
  218. ws.close();
  219. done();
  220. }
  221. });
  222. ws.on('error', (error) => {
  223. // This test should fail initially since WebSocket server doesn't exist yet
  224. expect(error.message).toContain('ECONNREFUSED');
  225. done();
  226. });
  227. // Timeout if no update received
  228. setTimeout(() => {
  229. if (!updateReceived) {
  230. ws.close();
  231. done();
  232. }
  233. }, 5000);
  234. });
  235. it('should receive order updates', (done) => {
  236. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  237. headers: {
  238. 'Authorization': 'Bearer test-api-key'
  239. }
  240. });
  241. let updateReceived = false;
  242. ws.on('open', () => {
  243. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  244. });
  245. ws.on('message', (data) => {
  246. const message = JSON.parse(data.toString());
  247. if (message.type === 'authenticated') {
  248. // Subscribe to order updates
  249. ws.send(JSON.stringify({
  250. type: 'subscribe',
  251. sessionId: testSessionId,
  252. channels: ['orders']
  253. }));
  254. } else if (message.type === 'session_update' && message.channel === 'orders') {
  255. const updateMessage: SessionUpdateMessage = message;
  256. expect(updateMessage.sessionId).toBe(testSessionId);
  257. expect(updateMessage.channel).toBe('orders');
  258. expect(updateMessage.data.orders).toBeDefined();
  259. expect(Array.isArray(updateMessage.data.orders)).toBe(true);
  260. updateReceived = true;
  261. ws.close();
  262. done();
  263. }
  264. });
  265. ws.on('error', (error) => {
  266. // This test should fail initially since WebSocket server doesn't exist yet
  267. expect(error.message).toContain('ECONNREFUSED');
  268. done();
  269. });
  270. // Timeout if no update received
  271. setTimeout(() => {
  272. if (!updateReceived) {
  273. ws.close();
  274. done();
  275. }
  276. }, 5000);
  277. });
  278. it('should receive risk updates', (done) => {
  279. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  280. headers: {
  281. 'Authorization': 'Bearer test-api-key'
  282. }
  283. });
  284. let updateReceived = false;
  285. ws.on('open', () => {
  286. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  287. });
  288. ws.on('message', (data) => {
  289. const message = JSON.parse(data.toString());
  290. if (message.type === 'authenticated') {
  291. // Subscribe to risk updates
  292. ws.send(JSON.stringify({
  293. type: 'subscribe',
  294. sessionId: testSessionId,
  295. channels: ['risk']
  296. }));
  297. } else if (message.type === 'session_update' && message.channel === 'risk') {
  298. const updateMessage: SessionUpdateMessage = message;
  299. expect(updateMessage.sessionId).toBe(testSessionId);
  300. expect(updateMessage.channel).toBe('risk');
  301. expect(updateMessage.data.riskBreaches).toBeDefined();
  302. expect(Array.isArray(updateMessage.data.riskBreaches)).toBe(true);
  303. updateReceived = true;
  304. ws.close();
  305. done();
  306. }
  307. });
  308. ws.on('error', (error) => {
  309. // This test should fail initially since WebSocket server doesn't exist yet
  310. expect(error.message).toContain('ECONNREFUSED');
  311. done();
  312. });
  313. // Timeout if no update received
  314. setTimeout(() => {
  315. if (!updateReceived) {
  316. ws.close();
  317. done();
  318. }
  319. }, 5000);
  320. });
  321. it('should receive metrics updates', (done) => {
  322. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  323. headers: {
  324. 'Authorization': 'Bearer test-api-key'
  325. }
  326. });
  327. let updateReceived = false;
  328. ws.on('open', () => {
  329. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  330. });
  331. ws.on('message', (data) => {
  332. const message = JSON.parse(data.toString());
  333. if (message.type === 'authenticated') {
  334. // Subscribe to metrics updates
  335. ws.send(JSON.stringify({
  336. type: 'subscribe',
  337. sessionId: testSessionId,
  338. channels: ['metrics']
  339. }));
  340. } else if (message.type === 'session_update' && message.channel === 'metrics') {
  341. const updateMessage: SessionUpdateMessage = message;
  342. expect(updateMessage.sessionId).toBe(testSessionId);
  343. expect(updateMessage.channel).toBe('metrics');
  344. expect(updateMessage.data.metrics).toBeDefined();
  345. expect(updateMessage.data.metrics.volume).toBeDefined();
  346. expect(updateMessage.data.metrics.orders).toBeDefined();
  347. expect(updateMessage.data.metrics.performance).toBeDefined();
  348. expect(updateMessage.data.metrics.risk).toBeDefined();
  349. updateReceived = true;
  350. ws.close();
  351. done();
  352. }
  353. });
  354. ws.on('error', (error) => {
  355. // This test should fail initially since WebSocket server doesn't exist yet
  356. expect(error.message).toContain('ECONNREFUSED');
  357. done();
  358. });
  359. // Timeout if no update received
  360. setTimeout(() => {
  361. if (!updateReceived) {
  362. ws.close();
  363. done();
  364. }
  365. }, 5000);
  366. });
  367. });
  368. describe('Connection Management', () => {
  369. it('should handle connection heartbeat', (done) => {
  370. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  371. headers: {
  372. 'Authorization': 'Bearer test-api-key'
  373. }
  374. });
  375. let heartbeatReceived = false;
  376. ws.on('open', () => {
  377. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  378. });
  379. ws.on('message', (data) => {
  380. const message = JSON.parse(data.toString());
  381. if (message.type === 'authenticated') {
  382. // Subscribe to updates
  383. ws.send(JSON.stringify({
  384. type: 'subscribe',
  385. sessionId: testSessionId,
  386. channels: ['status']
  387. }));
  388. } else if (message.type === 'heartbeat') {
  389. expect(message.timestamp).toBeDefined();
  390. heartbeatReceived = true;
  391. ws.close();
  392. done();
  393. }
  394. });
  395. ws.on('error', (error) => {
  396. // This test should fail initially since WebSocket server doesn't exist yet
  397. expect(error.message).toContain('ECONNREFUSED');
  398. done();
  399. });
  400. // Timeout if no heartbeat received
  401. setTimeout(() => {
  402. if (!heartbeatReceived) {
  403. ws.close();
  404. done();
  405. }
  406. }, 10000);
  407. });
  408. it('should handle connection reconnection', (done) => {
  409. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  410. headers: {
  411. 'Authorization': 'Bearer test-api-key'
  412. }
  413. });
  414. ws.on('open', () => {
  415. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  416. });
  417. ws.on('message', (data) => {
  418. const message = JSON.parse(data.toString());
  419. if (message.type === 'authenticated') {
  420. // Subscribe to updates
  421. ws.send(JSON.stringify({
  422. type: 'subscribe',
  423. sessionId: testSessionId,
  424. channels: ['status']
  425. }));
  426. // Simulate connection drop and reconnect
  427. setTimeout(() => {
  428. ws.close();
  429. // Reconnect
  430. const ws2 = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  431. headers: {
  432. 'Authorization': 'Bearer test-api-key'
  433. }
  434. });
  435. ws2.on('open', () => {
  436. ws2.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  437. });
  438. ws2.on('message', (data) => {
  439. const message = JSON.parse(data.toString());
  440. if (message.type === 'authenticated') {
  441. ws2.close();
  442. done();
  443. }
  444. });
  445. ws2.on('error', (error) => {
  446. // This test should fail initially since WebSocket server doesn't exist yet
  447. expect(error.message).toContain('ECONNREFUSED');
  448. done();
  449. });
  450. }, 1000);
  451. }
  452. });
  453. ws.on('error', (error) => {
  454. // This test should fail initially since WebSocket server doesn't exist yet
  455. expect(error.message).toContain('ECONNREFUSED');
  456. done();
  457. });
  458. });
  459. it('should handle multiple concurrent connections', (done) => {
  460. const connections: WebSocket[] = [];
  461. let connectedCount = 0;
  462. // Create multiple connections
  463. for (let i = 0; i < 5; i++) {
  464. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  465. headers: {
  466. 'Authorization': 'Bearer test-api-key'
  467. }
  468. });
  469. ws.on('open', () => {
  470. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  471. });
  472. ws.on('message', (data) => {
  473. const message = JSON.parse(data.toString());
  474. if (message.type === 'authenticated') {
  475. connectedCount++;
  476. if (connectedCount === 5) {
  477. // Close all connections
  478. connections.forEach(conn => conn.close());
  479. done();
  480. }
  481. }
  482. });
  483. ws.on('error', (error) => {
  484. // This test should fail initially since WebSocket server doesn't exist yet
  485. expect(error.message).toContain('ECONNREFUSED');
  486. done();
  487. });
  488. connections.push(ws);
  489. }
  490. });
  491. });
  492. describe('Error Handling', () => {
  493. it('should handle invalid session ID', (done) => {
  494. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/invalid-session-id`, {
  495. headers: {
  496. 'Authorization': 'Bearer test-api-key'
  497. }
  498. });
  499. ws.on('open', () => {
  500. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  501. });
  502. ws.on('message', (data) => {
  503. const message = JSON.parse(data.toString());
  504. if (message.type === 'error') {
  505. expect(message.error.code).toBe('SESSION_NOT_FOUND');
  506. ws.close();
  507. done();
  508. }
  509. });
  510. ws.on('error', (error) => {
  511. // This test should fail initially since WebSocket server doesn't exist yet
  512. expect(error.message).toContain('ECONNREFUSED');
  513. done();
  514. });
  515. });
  516. it('should handle malformed messages', (done) => {
  517. const ws = new WebSocket(`ws://localhost:${wsPort}/ws/sessions/${testSessionId}`, {
  518. headers: {
  519. 'Authorization': 'Bearer test-api-key'
  520. }
  521. });
  522. ws.on('open', () => {
  523. ws.send(JSON.stringify({ type: 'authenticate', token: 'test-api-key' }));
  524. });
  525. ws.on('message', (data) => {
  526. const message = JSON.parse(data.toString());
  527. if (message.type === 'authenticated') {
  528. // Send malformed message
  529. ws.send('invalid json');
  530. } else if (message.type === 'error') {
  531. expect(message.error.code).toBe('INVALID_MESSAGE_FORMAT');
  532. ws.close();
  533. done();
  534. }
  535. });
  536. ws.on('error', (error) => {
  537. // This test should fail initially since WebSocket server doesn't exist yet
  538. expect(error.message).toContain('ECONNREFUSED');
  539. done();
  540. });
  541. });
  542. });
  543. });