ZaStoGram_desktop/Telegram/SourceFiles/mtproto/transport/connection_tcp.h
loop-uh de04277eb8
All checks were successful
Desktop source guards / guards (push) Successful in 8s
Гнать фронт наперегонки с релеем, пока релей не ответил
По логу ПК 02.10 первый запуск тратил 1+2+4 с бюджетов на прямые релеи,
до которых не доходил даже TCP, и только после их подавления пробовал
фронты Cloudflare. В VM релей, отвечавший отказом сразу, вообще не
подавлялся: две минуты попыток с растущей паузой, фронты не открывались.

- Пока релей датацентра не ответил в этой сети или сбоит, сессия через
  500 мс открывает рядом с ним тестовое соединение через фронт. Работающий
  релей успевает раньше, и фронт не открывается вовсе.
- Релей сохраняет более высокий приоритет: подключившемуся фронту даётся
  обычное ожидание лучшего соединения, бюджет на подключение не меньше
  4,5 с, чтобы фронт успел пройти TLS и апгрейд.
- Релей, проигравший гонку без TCP, считается недоступным, как при
  истёкшем бюджете. Через несколько раундов он подавляется, и фронты
  набираются сразу, без гонки и ожидания.
- Отказ релея на уровне TCP (сброс, reject, нет такого хоста) учитывается
  так же, как таймаут.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:27:00 +03:00

117 lines
3 KiB
C++

/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "mtproto/transport/connection_abstract.h"
#include "mtproto/auth/mtproto_auth_key.h"
namespace MTP {
namespace details {
class AbstractSocket;
enum class HandshakePhase;
class TcpConnection : public AbstractConnection {
public:
TcpConnection(
not_null<RuntimeEnvironment*> runtime,
QThread *thread,
const ProxyData &proxy,
const ProxyStealthOptions &stealth);
ConnectionPointer clone(const ProxyData &proxy) override;
crl::time pingTime() const override;
crl::time fullConnectTimeout() const override;
void sendData(mtpBuffer &&buffer, SendDataContext context) override;
void disconnectFromServer() override;
void connectToServer(
const QString &address,
int port,
const bytes::vector &protocolSecret,
int16 protocolDcId,
bool protocolForFiles,
ConnectionStartContext context = {}) override;
void timedOut() override;
void markProxyMtprotoPayloadReceived() override;
HandshakePhase handshakePhase() const override;
ProxyConnectionAttempt proxyConnectionAttempt() const override;
ProxyTransportFailure proxyTransportFailure() const override;
ReceiveWaitVerdict receiveWaitVerdict(
crl::time waitStartedAt) const override;
bool isConnected() const override;
int32 debugState() const override;
QString transport() const override;
QString tag() const override;
~TcpConnection();
private:
enum class Status {
Waiting = 0,
Ready,
Finished,
};
void socketRead();
bytes::const_span prepareConnectionStartPrefix(bytes::span buffer);
void socketPacket(bytes::const_span bytes);
void socketConnected();
void socketDisconnected();
void socketError(int errorCode);
void socketProgress(HandshakePhase phase);
mtpBuffer parsePacket(bytes::const_span bytes);
void ensureAvailableInBuffer(int amount);
static uint32 fourCharsToUInt(char ch1, char ch2, char ch3, char ch4) {
char ch[4] = { ch1, ch2, ch3, ch4 };
return binary::Read<uint32>(bytes::make_span(ch));
}
const ProxyStealthOptions _stealth;
ProxyConnectionAttempt _mtproxyAttempt;
MtProxyAttemptPlan _mtproxyPlan;
ProxyTransportFailure _timeoutFailure;
crl::time _mtproxyAttemptStartedAt = 0;
bool _wssFront = false;
std::unique_ptr<AbstractSocket> _socket;
bool _connectionStarted = false;
int _offsetBytes = 0;
int _readBytes = 0;
int _leftBytes = 0;
bytes::vector _smallBuffer;
bytes::vector _largeBuffer;
bool _usingLargeBuffer = false;
uchar _sendKey[CTRState::KeySize];
CTRState _sendState;
uchar _receiveKey[CTRState::KeySize];
CTRState _receiveState;
class Protocol;
std::unique_ptr<Protocol> _protocol;
int16 _protocolDcId = 0;
Status _status = Status::Waiting;
MTPint128 _checkNonce;
QString _address;
int32 _port = 0;
crl::time _pingTime = 0;
rpl::lifetime _connectedLifetime;
rpl::lifetime _lifetime;
};
} // namespace details
} // namespace MTP