diff --git a/core/lib/external/tgkit/client.go b/core/lib/external/tgkit/client.go index 247d4fa..ebde102 100644 --- a/core/lib/external/tgkit/client.go +++ b/core/lib/external/tgkit/client.go @@ -28,12 +28,21 @@ type CustomAPIProxyTransport struct { wrapped http.RoundTripper } +// Бот -> прокси-сервис. Отдельный, короткий retry-бюджет: это про +// доступность самого proxyservice.ddns.net (DNS/подключение), а не про +// доступность Telegram — за это отвечает retry внутри самого прокси +// (см. main.go прокси-сервиса, doWithRetry). +const ( + maxProxyConnectAttempts = 2 + proxyConnectRetryDelay = 500 * time.Millisecond +) + func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) { targetURL := req.URL.String() method := req.Method var proxyReq *http.Request - var err error + var bodyBytesForRetry []byte contentType := req.Header.Get("Content-Type") mediaType, params, _ := mime.ParseMediaType(contentType) @@ -81,8 +90,9 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, } } _ = writer.Close() + bodyBytesForRetry = buf.Bytes() - proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, &buf) + proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry)) if err != nil { return nil, fmt.Errorf("proxy transport: failed to create multipart request: %w", err) } @@ -133,8 +143,9 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, if err != nil { return nil, fmt.Errorf("proxy transport: failed to marshal proxy payload: %w", err) } + bodyBytesForRetry = proxyJsonBytes - proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(proxyJsonBytes)) + proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry)) if err != nil { return nil, fmt.Errorf("proxy transport: failed to create json request: %w", err) } @@ -144,20 +155,42 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, // Общие заголовки авторизации шлюза proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey) - // Выполняем запрос через базовый http-клиент - resp, err := t.wrapped.RoundTrip(proxyReq) - if err != nil { - return nil, err - } + return t.roundTripWithRetry(proxyReq, bodyBytesForRetry) +} - // Проверяем статус ответа шлюза - if resp.StatusCode != http.StatusOK { - defer resp.Body.Close() - errorBody, _ := io.ReadAll(resp.Body) - return nil, fmt.Errorf("proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody)) - } +// roundTripWithRetry повторяет попытку достучаться до самого прокси-сервиса +// при сбое подключения (DNS, connection refused/reset и т.п.). Это отдельный +// уровень отказоустойчивости от retry внутри самого прокси: там речь про +// "прокси -> Telegram", здесь — про "бот -> прокси". +func (t *CustomAPIProxyTransport) roundTripWithRetry(req *http.Request, bodyBytes []byte) (*http.Response, error) { + var lastErr error + for attempt := 1; attempt <= maxProxyConnectAttempts; attempt++ { + req.Body = io.NopCloser(bytes.NewReader(bodyBytes)) + req.ContentLength = int64(len(bodyBytes)) - return resp, nil + resp, err := t.wrapped.RoundTrip(req) + if err != nil { + lastErr = err + logrus.Warnf("tgkit: proxy connect attempt %d/%d failed: %v", attempt, maxProxyConnectAttempts, err) + if attempt < maxProxyConnectAttempts { + time.Sleep(proxyConnectRetryDelay) + } + continue + } + + if resp.StatusCode != http.StatusOK { + defer resp.Body.Close() + errorBody, _ := io.ReadAll(resp.Body) + // Не ретраим: это осмысленный ответ от прокси (например, он сам + // уже исчерпал свои попытки достучаться до Telegram) — новая + // попытка прямо сейчас с тем же результатом ничего не изменит, + // а таймаут внешнего http.Client общий на весь RoundTrip. + return nil, fmt.Errorf("proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody)) + } + + return resp, nil + } + return nil, lastErr } // Client — основной клиент библиотеки @@ -170,10 +203,24 @@ type Client struct { type ClientConfig struct { Token string Proxy *ProxyConfig // Теперь этот параметр можно оставить пустым или использовать как флаг включения прокси - Timeout time.Duration // по умолчанию 30s + Timeout time.Duration // по умолчанию defaultTimeout Debug bool } +// defaultTimeout — общий таймаут http.Client на весь round trip (бот -> прокси +// -> Telegram, включая ретраи на обоих уровнях). Должен быть заметно больше +// худшего сценария retry внутри прокси (см. main.go: до 3 попыток по 15с +// каждая + паузы ≈ до ~40с) — иначе бот отваливается раньше, чем прокси +// успевает довести дело до конца, и весь смысл ретраев на прокси теряется. +const defaultTimeout = 45 * time.Second + +// Сколько раз пробовать поднять бота при старте процесса, прежде чем сдаться. +// Единичный сетевой сбой в момент старта не должен ронять весь сервис. +const ( + maxStartupAttempts = 3 + startupRetryDelay = 3 * time.Second +) + var ( mu sync.Mutex instance *Client @@ -206,7 +253,7 @@ func newClient(cfg ClientConfig) (*Client, error) { return nil, fmt.Errorf("tgkit: token is required") } if cfg.Timeout == 0 { - cfg.Timeout = 30 * time.Second + cfg.Timeout = defaultTimeout } if cfg.Proxy != nil { @@ -218,9 +265,19 @@ func newClient(cfg ClientConfig) (*Client, error) { return nil, fmt.Errorf("tgkit: build http client: %w", err) } - bot, err := tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient) + var bot *tgbotapi.BotAPI + for attempt := 1; attempt <= maxStartupAttempts; attempt++ { + bot, err = tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient) + if err == nil { + break + } + logrus.Warnf("tgkit: init bot attempt %d/%d failed: %v", attempt, maxStartupAttempts, err) + if attempt < maxStartupAttempts { + time.Sleep(time.Duration(attempt) * startupRetryDelay) + } + } if err != nil { - return nil, fmt.Errorf("tgkit: init bot: %w", err) + return nil, fmt.Errorf("tgkit: init bot after %d attempts: %w", maxStartupAttempts, err) } bot.Debug = cfg.Debug @@ -233,7 +290,7 @@ func newClient(cfg ClientConfig) (*Client, error) { // NewFromExisting оборачивает существующий *tgbotapi.BotAPI func NewFromExisting(bot *tgbotapi.BotAPI) *Client { - return &Client{bot: bot, timeout: 30 * time.Second} + return &Client{bot: bot, timeout: defaultTimeout} } // Bot возвращает сырой *tgbotapi.BotAPI @@ -276,7 +333,12 @@ func (c *Client) Request(cfg tgbotapi.Chattable) (*tgbotapi.APIResponse, error) return c.bot.Request(cfg) } -// buildHTTPClient создаёт http.Client с поддержкой кастомного API прокси +// buildHTTPClient создаёт http.Client с поддержкой кастомного API прокси. +// +// ⚠️ ГЛАВНЫЙ ФИКС: раньше proxyCfg принимался, но никогда не использовался — +// finalTransport всегда оставался обычным прямым http.Transport, и весь +// трафик бота шёл напрямую в api.telegram.org, минуя прокси. Теперь при +// заданном proxyCfg реально оборачиваем транспорт в CustomAPIProxyTransport. func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client, error) { baseTransport := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: false}, @@ -284,8 +346,12 @@ func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client var finalTransport http.RoundTripper = baseTransport + if proxyCfg != nil { + finalTransport = &CustomAPIProxyTransport{wrapped: baseTransport} + } + return &http.Client{ Transport: finalTransport, - Timeout: timeout, // Будет работать глобальный таймаут (например, твои 15 сек или дефолтные 30) + Timeout: timeout, }, nil }