Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 | import { SDKSignerClient, ClientConfig } from 'sdk-signer-client'; import { signerConfig } from '../../config/signer'; import { Logger } from '../../utils/logger'; import { Result, ServiceResult } from '../../utils/result'; export enum SignerConnectionState { DISCONNECTED = 'disconnected', CONNECTING = 'connecting', CONNECTED = 'connected', RECONNECTING = 'reconnecting', FAILED = 'failed' } export interface SignerHealthCheck { state: SignerConnectionState; lastConnected?: number; lastError?: string; reconnectAttempts: number; nextReconnectAt?: number; } export class SignerService { private static instance: SDKSignerClient | null = null; private static connectionState: SignerConnectionState = SignerConnectionState.DISCONNECTED; private static reconnectAttempts: number = 0; private static lastConnected: number | null = null; private static lastError: string | null = null; private static reconnectTimeout: NodeJS.Timeout | null = null; private static maxReconnectAttempts: number = 10; // More attempts than the SDK default private static reconnectInterval: number = 5000; // 5 seconds private static backoffMultiplier: number = 1.5; // Exponential backoff private static maxReconnectInterval: number = 60000; // Max 60 seconds between attempts private static healthCheckInterval: NodeJS.Timeout | null = null; private static connectionCallbacks: Array<(connected: boolean) => void> = []; /** * Initialize the signer service with enhanced reconnection logic */ static async initialize(): Promise<ServiceResult<void>> { try { Logger.info('Initializing Signer service'); // Create client instance this.instance = new SDKSignerClient(signerConfig); // Set up event listeners for connection monitoring this.setupEventListeners(); // Start periodic health checks this.startHealthChecks(); // Attempt initial connection const connectResult = await this.connect(); return connectResult; } catch (error) { Logger.error('Failed to initialize Signer service', { error: error instanceof Error ? error.message : 'Unknown error' }); return Result.fromError(error instanceof Error ? error : new Error('Initialization failed'), 'SIGNER_INIT_ERROR'); } } /** * Get the signer client instance with connection validation */ static async getInstance(): Promise<ServiceResult<SDKSignerClient>> { if (!this.instance) { const initResult = await this.initialize(); if (!initResult.success) { return Result.failure('SIGNER_NOT_INITIALIZED', 'Signer service not initialized', initResult.error); } } // Check if we're connected if (this.connectionState !== SignerConnectionState.CONNECTED) { // Try to reconnect if not already attempting if (this.connectionState !== SignerConnectionState.CONNECTING && this.connectionState !== SignerConnectionState.RECONNECTING) { Logger.warn('Signer not connected, attempting reconnection'); const reconnectResult = await this.connect(); if (!reconnectResult.success) { return Result.failure('SIGNER_CONNECTION_FAILED', 'Failed to connect to signer', reconnectResult.error); } } else { return Result.failure('SIGNER_CONNECTING', 'Signer is currently connecting, please retry'); } } return Result.success(this.instance!); } /** * Connect to the signer service with retry logic */ private static async connect(): Promise<ServiceResult<void>> { if (!this.instance) { return Result.failure('SIGNER_NOT_INITIALIZED', 'Signer client not initialized'); } this.connectionState = this.reconnectAttempts === 0 ? SignerConnectionState.CONNECTING : SignerConnectionState.RECONNECTING; try { // Only log connection attempts if we've been trying for a while if (this.reconnectAttempts > 2) { Logger.info('Signer connection attempt', { attempt: this.reconnectAttempts + 1, maxAttempts: this.maxReconnectAttempts }); } await this.instance.connect(); // Connection successful - state will be updated by the 'open' event handler return Result.success(undefined); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown connection error'; this.lastError = errorMessage; // Only log detailed errors after several attempts or if we've reached the limit if (this.reconnectAttempts >= this.maxReconnectAttempts) { this.connectionState = SignerConnectionState.FAILED; Logger.error('Signer connection failed after all attempts', { attempts: this.maxReconnectAttempts, lastError: errorMessage }); return Result.failure('SIGNER_CONNECTION_FAILED', `Failed to connect after ${this.maxReconnectAttempts} attempts: ${errorMessage}`); } else if (this.reconnectAttempts > 3) { Logger.warn('Signer connection failing', { attempt: this.reconnectAttempts + 1, error: errorMessage }); } // Schedule reconnection with exponential backoff this.scheduleReconnection(); return Result.failure('SIGNER_CONNECTION_FAILED', errorMessage); } } /** * Schedule a reconnection attempt with exponential backoff */ private static scheduleReconnection(): void { if (this.reconnectTimeout) { clearTimeout(this.reconnectTimeout); } // Calculate delay with exponential backoff const baseDelay = this.reconnectInterval; const delay = Math.min( baseDelay * Math.pow(this.backoffMultiplier, this.reconnectAttempts), this.maxReconnectInterval ); this.reconnectAttempts++; // Only log scheduling if this is taking a while if (this.reconnectAttempts > 2) { Logger.debug('Next reconnection in', { delayMs: delay }); } this.reconnectTimeout = setTimeout(async () => { await this.connect(); }, delay); } /** * Set up event listeners for the signer client */ private static setupEventListeners(): void { if (!this.instance) return; try { // Listen for WebSocket close events this.instance.on('close', () => { // Don't log here - let handleDisconnection() do the logging this.handleDisconnection(); }); // Listen for WebSocket error events this.instance.on('error', (error: Error) => { // Only log if it's a new error if (this.lastError !== error.message) { Logger.error('Signer WebSocket error', { error: error.message }); } this.handleError(error); }); // Listen for successful reconnection events this.instance.on('reconnect', () => { Logger.info('Signer reconnected via SDK'); this.handleSDKReconnection(); }); // Listen for connection open events this.instance.on('open', () => { Logger.info('Signer connected'); this.handleSDKConnection(); }); Logger.debug('Signer event listeners configured'); } catch (error) { Logger.warn('Could not set up SDK event listeners', { error: error instanceof Error ? error.message : 'Unknown error' }); } } /** * Handle disconnection events from WebSocket */ private static handleDisconnection(): void { // Only handle if we were actually connected (avoid duplicate handling) if (this.connectionState === SignerConnectionState.CONNECTED) { Logger.warn('Signer disconnected - reconnecting...'); this.connectionState = SignerConnectionState.DISCONNECTED; this.notifyConnectionCallbacks(false); // Cancel any pending health checks since we know we're disconnected this.cancelScheduledOperations(); // Initiate immediate reconnection (but respect ongoing attempts) if (!this.reconnectTimeout) { this.scheduleReconnection(); } } } /** * Handle connection errors from WebSocket */ private static handleError(error: Error): void { this.lastError = error.message; // Only log detailed error if we were connected (avoid startup error spam) if (this.connectionState === SignerConnectionState.CONNECTED) { Logger.error('Signer connection error', { error: error.message }); this.handleDisconnection(); } } /** * Handle successful SDK reconnection */ private static handleSDKReconnection(): void { // The SDK handled the reconnection, update our state this.connectionState = SignerConnectionState.CONNECTED; this.lastConnected = Date.now(); this.lastError = null; this.reconnectAttempts = 0; // Clear any pending reconnection timeout since SDK handled it if (this.reconnectTimeout) { clearTimeout(this.reconnectTimeout); this.reconnectTimeout = null; } // Notify callbacks (they will handle the logging) this.notifyConnectionCallbacks(true); } /** * Handle SDK connection open events */ private static handleSDKConnection(): void { this.connectionState = SignerConnectionState.CONNECTED; this.lastConnected = Date.now(); this.lastError = null; this.reconnectAttempts = 0; // Clear any pending operations this.cancelScheduledOperations(); // Notify callbacks (they will handle the logging) this.notifyConnectionCallbacks(true); } /** * Cancel scheduled operations (reconnection, health checks during known disconnection) */ private static cancelScheduledOperations(): void { if (this.reconnectTimeout) { clearTimeout(this.reconnectTimeout); this.reconnectTimeout = null; } } /** * Start periodic health checks */ private static startHealthChecks(): void { if (this.healthCheckInterval) { clearInterval(this.healthCheckInterval); } this.healthCheckInterval = setInterval(async () => { await this.performHealthCheck(); }, 30000); // Check every 30 seconds } /** * Perform a health check on the signer connection */ private static async performHealthCheck(): Promise<void> { // Only perform health checks if we think we're connected if (!this.instance || this.connectionState !== SignerConnectionState.CONNECTED) { Logger.debug('Skipping health check - not in connected state', { state: this.connectionState, hasInstance: !!this.instance }); return; } try { // Try a simple operation to verify connection is actually working await this.instance.getPairingId(); Logger.debug('Signer health check passed'); } catch (error) { Logger.warn('Signer health check failed - connection may be stale', { error: error instanceof Error ? error.message : 'Unknown error' }); // Health check failed, but we haven't received a close/error event // This indicates a stale connection - treat as disconnection this.handleDisconnection(); } } /** * Execute a signer operation with automatic retry on connection failure */ static async executeWithRetry<T>( operation: (client: SDKSignerClient) => Promise<T>, operationName: string, maxRetries: number = 3 ): Promise<ServiceResult<T>> { let lastError: Error | null = null; for (let attempt = 1; attempt <= maxRetries; attempt++) { try { const clientResult = await this.getInstance(); if (!clientResult.success) { lastError = new Error(clientResult.error?.message || 'Failed to get signer instance'); if (attempt < maxRetries) { // Only log operation retries if it's the final attempt or taking too long if (attempt === maxRetries - 1) { Logger.warn(`${operationName} final retry attempt`, { error: lastError.message }); } // Wait before retry await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); continue; } break; } const result = await operation(clientResult.data!); // Only log success if it took multiple attempts if (attempt > 1) { Logger.info(`${operationName} succeeded after ${attempt} attempts`); } return Result.success(result); } catch (error) { lastError = error instanceof Error ? error : new Error('Unknown error'); // Only log operation failures if it's taking multiple attempts if (attempt > 1) { Logger.warn(`${operationName} attempt ${attempt} failed`, { error: lastError.message }); } // If it's a connection error, force reconnection if (lastError.message.includes('connection') || lastError.message.includes('websocket')) { this.connectionState = SignerConnectionState.DISCONNECTED; } if (attempt < maxRetries) { // Wait before retry with exponential backoff await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt - 1))); } } } Logger.error(`${operationName} failed after ${maxRetries} attempts`, { error: lastError?.message || 'Unknown error' }); return Result.fromError(lastError || new Error('Operation failed'), 'SIGNER_OPERATION_FAILED'); } /** * Get connection health status */ static getHealthStatus(): SignerHealthCheck { return { state: this.connectionState, lastConnected: this.lastConnected || undefined, lastError: this.lastError || undefined, reconnectAttempts: this.reconnectAttempts, nextReconnectAt: this.reconnectTimeout ? Date.now() + this.reconnectInterval : undefined }; } /** * Force reconnection (useful for manual recovery) */ static async forceReconnect(): Promise<ServiceResult<void>> { Logger.info('Force reconnection requested'); // Reset state this.connectionState = SignerConnectionState.DISCONNECTED; this.reconnectAttempts = 0; if (this.reconnectTimeout) { clearTimeout(this.reconnectTimeout); this.reconnectTimeout = null; } return await this.connect(); } /** * Register a callback for connection state changes */ static onConnectionChange(callback: (connected: boolean) => void): () => void { this.connectionCallbacks.push(callback); // Return unsubscribe function return () => { const index = this.connectionCallbacks.indexOf(callback); if (index > -1) { this.connectionCallbacks.splice(index, 1); } }; } /** * Notify all connection callbacks */ private static notifyConnectionCallbacks(connected: boolean): void { this.connectionCallbacks.forEach(callback => { try { callback(connected); } catch (error) { Logger.error('Error in connection callback', { error: error instanceof Error ? error.message : 'Unknown error' }); } }); } /** * Cleanup resources */ static cleanup(): void { if (this.reconnectTimeout) { clearTimeout(this.reconnectTimeout); this.reconnectTimeout = null; } if (this.healthCheckInterval) { clearInterval(this.healthCheckInterval); this.healthCheckInterval = null; } this.connectionCallbacks = []; this.connectionState = SignerConnectionState.DISCONNECTED; } } |