Updated proxy configuration #169

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-10-01 14:57:11 +03:00
2 changed files with 223 additions and 105 deletions

View File

@ -3,6 +3,7 @@ package tgkit
import (
"bitrix_balancer_api/core/variables"
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
@ -12,6 +13,7 @@ import (
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
@ -25,36 +27,61 @@ type APIProxyRequest struct {
Method string `json:"method"`
Body interface{} `json:"body,omitempty"`
}
type CustomAPIProxyTransport struct {
wrapped http.RoundTripper
// Поля для fallback-механизма на бесплатные прокси
mu sync.RWMutex
fallbackMode bool
fallbackProxyURL string
fallbackTransport http.RoundTripper
}
// Бот -> прокси-сервис. Отдельный, короткий retry-бюджет: это про
// доступность самого proxyservice.ddns.net (DNS/подключение), а не про
// доступность Telegram — за это отвечает retry внутри самого прокси
// (см. main.go прокси-сервиса, doWithRetry).
const (
maxProxyConnectAttempts = 2
proxyConnectRetryDelay = 500 * time.Millisecond
defaultTimeout = 120 * time.Second
maxStartupAttempts = 3
startupRetryDelay = 3 * time.Second
)
var (
mu sync.Mutex
instance *Client
)
func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// 1. Сразу считываем оригинальное тело запроса в память.
// Это критично, так как при падении шлюза нам нужно будет отправить
// эти же оригинальные данные через резервный бесплатный прокси.
var rawOriginalBody []byte
if req.Body != nil {
rawOriginalBody, _ = io.ReadAll(req.Body)
_ = req.Body.Close()
}
t.mu.RLock()
fallbackMode := t.fallbackMode
fallbackTrans := t.fallbackTransport
currentFallbackURL := t.fallbackProxyURL
t.mu.RUnlock()
// Если мы уже перешли на бесплатный прокси — идем по резервному пути
if fallbackMode && fallbackTrans != nil {
return t.executeFallback(req, rawOriginalBody, fallbackTrans, currentFallbackURL)
}
// === Стандартный путь через приватный шлюз ===
targetURL := req.URL.String()
method := req.Method
var proxyReq *http.Request
var bodyBytesForRetry []byte
contentType := req.Header.Get("Content-Type")
mediaType, params, _ := mime.ParseMediaType(contentType)
if mediaType == "multipart/form-data" && req.Body != nil {
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
return nil, fmt.Errorf("proxy transport: failed to read multipart body: %w", err)
}
_ = req.Body.Close()
if mediaType == "multipart/form-data" && len(rawOriginalBody) > 0 {
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
@ -62,7 +89,7 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response,
_ = writer.WriteField("method", method)
boundary := params["boundary"]
mr := multipart.NewReader(bytes.NewReader(bodyBytes), boundary)
mr := multipart.NewReader(bytes.NewReader(rawOriginalBody), boundary)
for {
part, err := mr.NextPart()
if err == io.EOF {
@ -75,14 +102,12 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response,
partBytes, _ := io.ReadAll(part)
if part.FileName() != "" {
// Если это файл, создаем файловую часть с сохранением имени и заголовков
filePart, err := writer.CreateFormFile(part.FormName(), part.FileName())
if err != nil {
return nil, fmt.Errorf("proxy transport: create form file: %w", err)
}
_, _ = filePart.Write(partBytes)
} else {
// Если обычное поле
fieldPart, err := writer.CreateFormField(part.FormName())
if err != nil {
return nil, fmt.Errorf("proxy transport: create form field: %w", err)
@ -93,6 +118,7 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response,
_ = writer.Close()
bodyBytesForRetry = buf.Bytes()
var err error
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)
@ -101,39 +127,28 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response,
} else {
var originalBody interface{} = map[string]interface{}{}
if req.Body != nil {
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
return nil, fmt.Errorf("proxy transport: failed to read body: %w", err)
}
_ = req.Body.Close()
if len(bodyBytes) > 0 {
// Проверяем, JSON ли это
var raw json.RawMessage
if err := json.Unmarshal(bodyBytes, &raw); err == nil {
originalBody = raw
} else {
// Если это url-encoded строка, превращаем в map
values, err := url.ParseQuery(string(bodyBytes))
if err == nil && len(values) > 0 {
bodyMap := make(map[string]interface{})
for key, val := range values {
if len(val) == 1 {
bodyMap[key] = val[0]
} else if len(val) > 1 {
bodyMap[key] = val
}
if len(rawOriginalBody) > 0 {
var raw json.RawMessage
if err := json.Unmarshal(rawOriginalBody, &raw); err == nil {
originalBody = raw
} else {
values, err := url.ParseQuery(string(rawOriginalBody))
if err == nil && len(values) > 0 {
bodyMap := make(map[string]interface{})
for key, val := range values {
if len(val) == 1 {
bodyMap[key] = val[0]
} else if len(val) > 1 {
bodyMap[key] = val
}
originalBody = bodyMap
} else {
originalBody = string(bodyBytes)
}
originalBody = bodyMap
} else {
originalBody = string(rawOriginalBody)
}
}
}
// Собираем JSON-payload для handleJSON на шлюзе
proxyReqPayload := APIProxyRequest{
URL: targetURL,
Method: method,
@ -153,16 +168,18 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response,
proxyReq.Header.Set("Content-Type", "application/json")
}
// Общие заголовки авторизации шлюза
proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey)
return t.roundTripWithRetry(proxyReq, bodyBytesForRetry)
resp, err := t.roundTripWithRetry(proxyReq, bodyBytesForRetry)
if err != nil {
// Главный шлюз умер окончательно. Инициируем поиск бесплатного прокси.
logrus.Warnf("tgkit: custom gateway failed (%v), switching to free fallback proxies.", err)
return t.switchToFallbackAndExecute(req, rawOriginalBody, "")
}
return resp, nil
}
// 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++ {
@ -172,7 +189,7 @@ func (t *CustomAPIProxyTransport) roundTripWithRetry(req *http.Request, bodyByte
resp, err := t.wrapped.RoundTrip(req)
if err != nil {
lastErr = err
logrus.Warnf("tgkit: proxy connect attempt %d/%d failed: %v", attempt, maxProxyConnectAttempts, err)
logrus.Warnf("tgkit: gateway connect attempt %d/%d failed: %v", attempt, maxProxyConnectAttempts, err)
if attempt < maxProxyConnectAttempts {
time.Sleep(proxyConnectRetryDelay)
}
@ -182,10 +199,6 @@ func (t *CustomAPIProxyTransport) roundTripWithRetry(req *http.Request, bodyByte
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))
}
@ -194,6 +207,156 @@ func (t *CustomAPIProxyTransport) roundTripWithRetry(req *http.Request, bodyByte
return nil, lastErr
}
// executeFallback перенаправляет оригинальный запрос напрямую в Telegram через найденный бесплатный прокси
func (t *CustomAPIProxyTransport) executeFallback(req *http.Request, body []byte, trans http.RoundTripper, currentProxyURL string) (*http.Response, error) {
newReq := req.Clone(req.Context())
if len(body) > 0 {
newReq.Body = io.NopCloser(bytes.NewReader(body))
newReq.ContentLength = int64(len(body))
}
resp, err := trans.RoundTrip(newReq)
if err != nil {
// Бесплатный прокси отвалился во время работы. Ищем новый.
logrus.Warnf("tgkit: fallback proxy %s disconnected (%v), searching for a new one...", currentProxyURL, err)
return t.switchToFallbackAndExecute(req, body, currentProxyURL)
}
return resp, nil
}
// switchToFallbackAndExecute блокирует транспорт, находит самый быстрый прокси и обновляет конфигурацию
func (t *CustomAPIProxyTransport) switchToFallbackAndExecute(req *http.Request, body []byte, failedProxyURL string) (*http.Response, error) {
t.mu.Lock()
// Если другая горутина уже нашла новый прокси, пока мы ждали мьютекс, используем его
if t.fallbackMode && t.fallbackProxyURL != failedProxyURL {
savedTrans := t.fallbackTransport
currentURL := t.fallbackProxyURL
t.mu.Unlock()
return t.executeFallback(req, body, savedTrans, currentURL)
}
logrus.Infof("tgkit: searching for the fastest free proxy...")
newProxyURL, err := findFastestFreeProxy()
if err != nil {
t.mu.Unlock()
return nil, fmt.Errorf("failed to find a working free proxy: %w", err)
}
parsedURL, _ := url.Parse(newProxyURL)
newTrans := &http.Transport{
Proxy: http.ProxyURL(parsedURL),
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // Бесплатные прокси часто имеют кривые сертификаты
}
t.fallbackMode = true
t.fallbackProxyURL = newProxyURL
t.fallbackTransport = newTrans
savedTrans := newTrans
t.mu.Unlock()
logrus.Infof("tgkit: successfully switched to free proxy: %s", newProxyURL)
return t.executeFallback(req, body, savedTrans, newProxyURL)
}
// findFastestFreeProxy скачивает списки бесплатных прокси, конкурентно пингует их и возвращает первый успешный
func findFastestFreeProxy() (string, error) {
sources := []string{
"https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/http.txt",
"https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt",
"https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=5000&country=all&ssl=all&anonymity=all",
}
var proxies []string
for _, src := range sources {
resp, err := http.Get(src)
if err == nil {
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
lines := strings.Split(string(body), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
proxies = append(proxies, line)
}
}
}
if len(proxies) > 100 {
break // Собрали достаточное количество для тестирования
}
}
if len(proxies) == 0 {
return "", fmt.Errorf("could not fetch proxies from public sources")
}
resultCh := make(chan string, 1)
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
limit := 100
if len(proxies) < limit {
limit = len(proxies)
}
for i := 0; i < limit; i++ {
p := proxies[i]
if !strings.HasPrefix(p, "http") && !strings.HasPrefix(p, "socks") {
p = "http://" + p
}
wg.Add(1)
go func(proxyUrl string) {
defer wg.Done()
u, err := url.Parse(proxyUrl)
if err != nil {
return
}
// Пингуем api.telegram.org. Кто первый установит соединение и ответит - тот и победитель
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.telegram.org", nil)
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(u),
DialContext: (&net.Dialer{Timeout: 3 * time.Second}).DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: 4 * time.Second,
}
resp, err := client.Do(req)
if err == nil {
_ = resp.Body.Close()
if resp.StatusCode < 500 {
select {
case resultCh <- proxyUrl:
cancel() // Отменяем проверки остальных прокси, победитель найден
default:
}
}
}
}(p)
}
go func() {
wg.Wait()
close(resultCh)
}()
select {
case best, ok := <-resultCh:
if !ok {
return "", fmt.Errorf("all %d tested proxies failed to reach Telegram", limit)
}
return best, nil
case <-time.After(8 * time.Second):
return "", fmt.Errorf("timeout waiting for a fast proxy (tested %d proxies)", limit)
}
}
// Client — основной клиент библиотеки
type Client struct {
bot *tgbotapi.BotAPI
@ -201,54 +364,31 @@ type Client struct {
}
// ClientConfig — конфигурация клиента
type ProxyConfig struct{} // Заглушка, если структура была в другом файле
type ClientConfig struct {
Token string
Proxy *ProxyConfig // Теперь этот параметр можно оставить пустым или использовать как флаг включения прокси
Timeout time.Duration // по умолчанию defaultTimeout
Proxy *ProxyConfig
Timeout time.Duration
Debug bool
}
// defaultTimeout — общий таймаут http.Client на весь round trip (бот -> прокси
// -> Telegram, включая ретраи на обоих уровнях). Должен быть заметно больше
// худшего сценария retry внутри прокси (см. main.go: до 3 попыток по 15с
// каждая + паузы ≈ до ~40с) — иначе бот отваливается раньше, чем прокси
// успевает довести дело до конца, и весь смысл ретраев на прокси теряется.
const defaultTimeout = 120 * time.Second
// Сколько раз пробовать поднять бота при старте процесса, прежде чем сдаться.
// Единичный сетевой сбой в момент старта не должен ронять весь сервис.
const (
maxStartupAttempts = 3
startupRetryDelay = 3 * time.Second
)
var (
mu sync.Mutex
instance *Client
)
func GetClient(cfg ClientConfig) (*Client, error) {
if instance != nil {
return instance, nil
}
mu.Lock()
defer mu.Unlock()
if instance != nil {
return instance, nil
}
client, err := newClient(cfg)
if err != nil {
return nil, err
}
instance = client
return instance, nil
}
// New создаёт нового клиента
func newClient(cfg ClientConfig) (*Client, error) {
if cfg.Token == "" {
return nil, fmt.Errorf("tgkit: token is required")
@ -282,81 +422,66 @@ func newClient(cfg ClientConfig) (*Client, error) {
}
bot.Debug = cfg.Debug
return &Client{
bot: bot,
timeout: cfg.Timeout,
}, nil
return &Client{bot: bot, timeout: cfg.Timeout}, nil
}
// NewFromExisting оборачивает существующий *tgbotapi.BotAPI
func NewFromExisting(bot *tgbotapi.BotAPI) *Client {
return &Client{bot: bot, timeout: defaultTimeout}
}
// Bot возвращает сырой *tgbotapi.BotAPI
func (c *Client) Bot() *tgbotapi.BotAPI {
return c.bot
}
// Self возвращает информацию о боте
func (c *Client) Self() tgbotapi.User {
return c.bot.Self
}
// GetUpdates возвращает канал обновлений
func (c *Client) GetUpdates(timeout int) tgbotapi.UpdatesChannel {
u := tgbotapi.NewUpdate(0)
u.Timeout = timeout
return c.bot.GetUpdatesChan(u)
}
// AnswerCallback отвечает на callback query
func (c *Client) AnswerCallback(callbackID string, text string) error {
cb := tgbotapi.NewCallback(callbackID, text)
_, err := c.bot.Request(cb)
return err
}
// DeleteMessage удаляет сообщение
func (c *Client) DeleteMessage(chatID int64, messageID int) error {
_, err := c.bot.Request(tgbotapi.NewDeleteMessage(chatID, messageID))
return err
}
// GetFileDirectURL возвращает прямую ссылку на файл
func (c *Client) GetFileDirectURL(fileID string) (string, error) {
return c.bot.GetFileDirectURL(fileID)
}
// Request выполняет произвольный запрос к API
func (c *Client) Request(cfg tgbotapi.Chattable) (*tgbotapi.APIResponse, error) {
return c.bot.Request(cfg)
}
func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client, error) {
baseTransport := &http.Transport{
// Добавляем таймаут на само подключение!
// Если прокси не отвечает 10 секунд, считаем попытку неудачной и ретраим.
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
TLSHandshakeTimeout: 10 * time.Second, // Таймаут на SSL-рукопожатие
ResponseHeaderTimeout: 60 * time.Second, // Ждем ответ от прокси не больше 60с
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 60 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
}
var finalTransport http.RoundTripper = baseTransport
if proxyCfg != nil {
finalTransport = &CustomAPIProxyTransport{wrapped: baseTransport}
}
return &http.Client{
Transport: finalTransport,
Timeout: timeout, // Общий лимит на все телодвижения бота (120s)
Timeout: timeout,
}, nil
}

View File

@ -43,13 +43,6 @@ type MessageOptions struct {
Silent bool
}
// ProxyConfig — настройки прокси
type ProxyConfig struct {
URL string // socks5://user:pass@host:port или http://host:port
Username string
Password string
}
// SentMessage — результат отправки
type SentMessage struct {
MessageID int