refactor: перенос логики сессии в internal/session и обновление mobile-фасада

This commit is contained in:
samosvalishe committed 2026-08-01 03:05:14 +03:00
1 parent 68485cbee7
commit 1f86fda104
55 files changed
+5314 -1312

No files matched your search

+13
View File
@@ -33,10 +33,21 @@ type SessionPool struct {
counter atomic.Uint64
connCounter atomic.Uint64
// active - зеркало числа живых сессий для наблюдателей вне пакета
// (watchdog и счётчик стримов в UI). nil, если хост его не просил.
active *atomic.Int32
readyOnce sync.Once
ready chan struct{}
}
// publishActive обновляет внешнее зеркало. Вызывать под p.mu.
func (p *SessionPool) publishActive() {
if p.active != nil {
p.active.Store(int32(len(p.sessions))) //nolint:gosec // сессий десятки, int32 не переполнить
}
}
// Ready возвращает канал, закрытый при первом появлении сессии в пуле.
func (p *SessionPool) Ready() <-chan struct{} {
p.mu.Lock()
@@ -53,6 +64,7 @@ func (p *SessionPool) Add(id int, s *smux.Session) *PooledSession {
ps := &PooledSession{ID: id, Sess: s}
p.mu.Lock()
p.sessions = append(p.sessions, ps)
p.publishActive()
if p.ready == nil {
p.ready = make(chan struct{})
}
@@ -71,6 +83,7 @@ func (p *SessionPool) Remove(ps *PooledSession) {
break
}
}
p.publishActive()
p.mu.Unlock()
}
+46
View File
@@ -0,0 +1,46 @@
package tcpfwd
import (
"sync/atomic"
"testing"
)
// Зеркало активных сессий - единственный источник "сколько каналов поднято" для
// watchdog и UI в tcp-режиме: раньше счётчик оставался нулевым и сессию убивал
// таймаут подключения.
func TestSessionPoolMirrorsActiveCount(t *testing.T) {
var active atomic.Int32
pool := &SessionPool{active: &active}
first := pool.Add(1, nil)
if got := active.Load(); got != 1 {
t.Fatalf("active = %d, want 1", got)
}
second := pool.Add(2, nil)
if got := active.Load(); got != 2 {
t.Fatalf("active = %d, want 2", got)
}
pool.Remove(first)
if got := active.Load(); got != 1 {
t.Fatalf("active after remove = %d, want 1", got)
}
pool.Remove(second)
if got := active.Load(); got != 0 {
t.Fatalf("active after drain = %d, want 0", got)
}
if pool.Count() != 0 {
t.Fatalf("Count() = %d, want 0", pool.Count())
}
}
func TestSessionPoolWithoutMirror(t *testing.T) {
pool := &SessionPool{}
ps := pool.Add(1, nil)
pool.Remove(ps)
if pool.Count() != 0 {
t.Fatalf("Count() = %d, want 0", pool.Count())
}
}
+6 -1
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"github.com/samosvalishe/free-turn-proxy/internal/client/ish"
@@ -46,6 +47,10 @@ type Deps struct {
DTLSDialer *dtlsdial.Dialer
Log logx.Logger
BondHandler BondHandler
// ConnectedStreams, если задан, зеркалит число живых сессий пула. Тот же
// счётчик, что udprelay ведёт для своих стримов: хосту нужен один источник
// "сколько каналов поднято" независимо от режима.
ConnectedStreams *atomic.Int32
}
func (d *Deps) log() logx.Logger {
@@ -59,7 +64,7 @@ func (d *Deps) log() logx.Logger {
// первого подключения, затем принимает локальные TCP-соединения и форвардит
// каждое как smux-поток (round-robin) или bonded по всем активным сессиям.
func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) error {
pool := &SessionPool{}
pool := &SessionPool{active: deps.ConnectedStreams}
var wgMaint sync.WaitGroup
for i := range numSessions {
+8 -8
View File
@@ -7,7 +7,6 @@ package udprelay
import (
"context"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
@@ -78,18 +77,19 @@ func (d *Deps) log() logx.Logger {
return d.Log
}
// Run - точка входа UDP-режима. Биндит listenAddr, распределяет входящие пакеты
// в общую очередь и запускает numStreams пар (DTLSLoop, TURNLoop).
// Run - точка входа UDP-режима. Читает пакеты локального пира из listenConn,
// распределяет их в общую очередь и запускает numStreams пар (DTLSLoop, TURNLoop).
//
// listenConn - канал до локального пира (WireGuard/Xray). Вызывающий решает,
// что это: UDP-сокет на cfg.Proxy.Listen или пара в памяти, когда туннель
// поднят внутри процесса. Run владеет им и закрывает при отмене ctx.
//
// connectedStreams принадлежит вызывающему (provider может читать через свой
// StreamsAlive-аналог) и инкрементируется/декрементируется в oneTURN.
// Возвращается после выхода всех потоков (т.е. при отмене ctx).
// При фатальной provider-ошибке возвращает ErrFatal - вызывающий делает
// os.Exit без вмешательства udprelay в хост-процесс.
func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, logger logx.Logger, connectedStreams *atomic.Int32, params *Params, peer *net.UDPAddr, listenAddr string, numStreams int) error {
listenConn, err := (&net.ListenConfig{}).ListenPacket(ctx, "udp", listenAddr)
if err != nil {
return fmt.Errorf("udprelay listen %s: %w", listenAddr, err)
}
func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, logger logx.Logger, connectedStreams *atomic.Int32, params *Params, peer *net.UDPAddr, listenConn net.PacketConn, numStreams int) error {
context.AfterFunc(ctx, func() {
if closeErr := listenConn.Close(); closeErr != nil {
logger.Errorf("udprelay: close local connection: %s", closeErr)