From 3a42c023bffd3777d5817ca970f5ae5cff9215dc Mon Sep 17 00:00:00 2001 From: alina sireneva Date: Wed, 29 Jan 2025 21:16:17 +0300 Subject: [PATCH] fix: improved reconnecting --- .../core/src/network/persistent-connection.ts | 23 +++++++++++++++---- .../core/src/network/session-connection.ts | 2 +- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/core/src/network/persistent-connection.ts b/packages/core/src/network/persistent-connection.ts index 26f732a6..93e805b7 100644 --- a/packages/core/src/network/persistent-connection.ts +++ b/packages/core/src/network/persistent-connection.ts @@ -5,7 +5,7 @@ import type { IPacketCodec, ITelegramConnection, TelegramTransport } from './tra import { FramedReader, FramedWriter } from '@fuman/io' -import { PersistentConnection as FumanPersistentConnection } from '@fuman/net' +import { ConnectionClosedError, PersistentConnection as FumanPersistentConnection } from '@fuman/net' import { Emitter, timers } from '@fuman/utils' export interface PersistentConnectionParams { @@ -140,7 +140,7 @@ export abstract class PersistentConnection { } } - private async _onClose() { + private _onClose(): void { this.log.debug('connection closed') this._updateLogPrefix() @@ -149,9 +149,12 @@ export abstract class PersistentConnection { this.onClosed() } - private async _onError(err: Error) { + private _onError(err: Error) { this._updateLogPrefix() - this.handleError(err) + + if (!(err instanceof ConnectionClosedError)) { + this.handleError(err) + } return 'reconnect' as const } @@ -231,7 +234,17 @@ export abstract class PersistentConnection { if (this._writer) { this._rescheduleInactivity() - await this._writer.write(data) + try { + await this._writer.write(data) + } catch (e: unknown) { + if (e instanceof ConnectionClosedError) { + this.log.debug('connection closed while sending, reconnecting') + this._fuman.reconnect(true) + this._sendOnceConnected.push(data) + } else { + throw e + } + } } else { this._sendOnceConnected.push(data) } diff --git a/packages/core/src/network/session-connection.ts b/packages/core/src/network/session-connection.ts index 04bac021..a4dc8a12 100644 --- a/packages/core/src/network/session-connection.ts +++ b/packages/core/src/network/session-connection.ts @@ -10,8 +10,8 @@ import { Deferred, Emitter, timers, u8 } from '@fuman/utils' import { tl } from '@mtcute/tl' import { TlBinaryReader, TlBinaryWriter, TlSerializationCounter } from '@mtcute/tl-runtime' import Long from 'long' -import { MtArgumentError, MtcuteError, MtTimeoutError } from '../types/index.js' +import { MtArgumentError, MtcuteError, MtTimeoutError } from '../types/index.js' import { createAesIgeForMessageOld } from '../utils/crypto/mtproto.js' import { EarlyTimer,