|
8 | 8 | import { WebSocket, MessageEvent, ErrorEvent } from 'ws'; |
9 | 9 | import { bigIntUtils } from '@hathor/wallet-lib'; |
10 | 10 | import { FullNodeEvent, FullNodeEventSchema, WebSocketSendEvent } from './types'; |
11 | | -import { FULLNODE_HOST, USE_SSL, WINDOW_SIZE } from './config'; |
| 11 | +import { FULLNODE_HOST, USE_SSL, WINDOW_SIZE, CONNECTION_TIMEOUT_MS } from './config'; |
12 | 12 |
|
13 | 13 | export interface BatchConfig { |
14 | 14 | batchStart: number; |
@@ -43,6 +43,28 @@ export function createWorker(config: BatchConfig, callbacks: WorkerCallbacks): W |
43 | 43 | let isRunning = false; |
44 | 44 | let eventsSinceLastAck = 0; |
45 | 45 | let lastReceivedEventId = 0; |
| 46 | + let activityTimeout: ReturnType<typeof setTimeout> | null = null; |
| 47 | + |
| 48 | + const resetActivityTimeout = (): void => { |
| 49 | + if (activityTimeout) { |
| 50 | + clearTimeout(activityTimeout); |
| 51 | + } |
| 52 | + if (isRunning && CONNECTION_TIMEOUT_MS > 0) { |
| 53 | + activityTimeout = setTimeout(() => { |
| 54 | + if (isRunning) { |
| 55 | + onError(new Error(`Connection timeout: no activity for ${CONNECTION_TIMEOUT_MS}ms`)); |
| 56 | + stop(); |
| 57 | + } |
| 58 | + }, CONNECTION_TIMEOUT_MS); |
| 59 | + } |
| 60 | + }; |
| 61 | + |
| 62 | + const clearActivityTimeout = (): void => { |
| 63 | + if (activityTimeout) { |
| 64 | + clearTimeout(activityTimeout); |
| 65 | + activityTimeout = null; |
| 66 | + } |
| 67 | + }; |
46 | 68 |
|
47 | 69 | const getWsUrl = (): string => { |
48 | 70 | const protocol = USE_SSL ? 'wss://' : 'ws://'; |
@@ -74,9 +96,11 @@ export function createWorker(config: BatchConfig, callbacks: WorkerCallbacks): W |
74 | 96 | ...(lastAckEventId !== undefined && { last_ack_event_id: lastAckEventId }), |
75 | 97 | }; |
76 | 98 | sendMessage(startMessage); |
| 99 | + resetActivityTimeout(); |
77 | 100 | }; |
78 | 101 |
|
79 | 102 | socket.onmessage = (socketEvent: MessageEvent) => { |
| 103 | + resetActivityTimeout(); |
80 | 104 | try { |
81 | 105 | const rawData = bigIntUtils.JSONBigInt.parse(socketEvent.data.toString()); |
82 | 106 | const parseResult = FullNodeEventSchema.safeParse(rawData); |
@@ -140,6 +164,7 @@ export function createWorker(config: BatchConfig, callbacks: WorkerCallbacks): W |
140 | 164 |
|
141 | 165 | const stop = (): void => { |
142 | 166 | isRunning = false; |
| 167 | + clearActivityTimeout(); |
143 | 168 | if (socket) { |
144 | 169 | socket.close(); |
145 | 170 | socket = null; |
|
0 commit comments