feat(proxy): tcp-режим для xray/sing-box поверх turn
This commit is contained in:
1 parent
e63279db18
commit
f7129099f7
60 files changed
+2953
-135
No files matched your search
@@ -68,7 +68,7 @@ func TURNLoop(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case pair := <-connchan:
|
||||
if !deps.allocPace.wait(ctx) {
|
||||
if !deps.allocPace.Wait(ctx) {
|
||||
return
|
||||
}
|
||||
c := make(chan error, 1)
|
||||
@@ -158,7 +158,7 @@ func dtlsSession(dtlsctx context.Context, dtlscancel context.CancelFunc, deps *D
|
||||
}()
|
||||
deps.log().Debugf("[STREAM %d] Established DTLS connection", streamID)
|
||||
|
||||
if err := clientsdb.WriteClientID(dtlsConn, params.ClientID); err != nil {
|
||||
if err := clientsdb.WriteClientID(dtlsConn, params.ClientID, clientsdb.ModeUDP); err != nil {
|
||||
return fmt.Errorf("failed to write client ID: %w", err)
|
||||
}
|
||||
if okchan != nil {
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
package udprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Квота TURN считается на username, поэтому залп Allocate от всех стримов сразу упирается
|
||||
// в неё плотнее, чем очередь: шлюз раздаёт слоты по одному на allocPaceInterval.
|
||||
const allocPaceInterval = 200 * time.Millisecond
|
||||
|
||||
type allocPacer struct {
|
||||
mu sync.Mutex
|
||||
next time.Time
|
||||
step time.Duration
|
||||
}
|
||||
|
||||
func newAllocPacer(step time.Duration) *allocPacer {
|
||||
return &allocPacer{step: step}
|
||||
}
|
||||
|
||||
// wait возвращает false, только если ctx отменён - слот всё равно занят и не переиспользуется.
|
||||
func (p *allocPacer) wait(ctx context.Context) bool {
|
||||
if p == nil {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
wait := time.Until(p.slot())
|
||||
if wait <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
t := time.NewTimer(wait)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (p *allocPacer) slot() time.Time {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
now := time.Now()
|
||||
if p.next.Before(now) {
|
||||
p.next = now
|
||||
}
|
||||
slot := p.next
|
||||
p.next = slot.Add(p.step)
|
||||
return slot
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package udprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Смысл шлюза - очередь, а не пауза: N стримов обязаны разъехаться на N-1 шагов.
|
||||
func TestAllocPacerSpacesConcurrentWaiters(t *testing.T) {
|
||||
t.Parallel()
|
||||
const (
|
||||
step = 20 * time.Millisecond
|
||||
waiters = 5
|
||||
slowdown = 3
|
||||
)
|
||||
p := newAllocPacer(step)
|
||||
|
||||
start := time.Now()
|
||||
var wg sync.WaitGroup
|
||||
elapsed := make([]time.Duration, waiters)
|
||||
for i := range waiters {
|
||||
wg.Go(func() {
|
||||
if !p.wait(context.Background()) {
|
||||
t.Errorf("waiter %d: wait returned false", i)
|
||||
return
|
||||
}
|
||||
elapsed[i] = time.Since(start)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
var last time.Duration
|
||||
for _, e := range elapsed {
|
||||
last = max(last, e)
|
||||
}
|
||||
if want := (waiters - 1) * step; last < want {
|
||||
t.Fatalf("last waiter passed after %v, want at least %v", last, want)
|
||||
}
|
||||
if limit := slowdown * waiters * step; last > limit {
|
||||
t.Fatalf("last waiter passed after %v, want under %v", last, limit)
|
||||
}
|
||||
}
|
||||
|
||||
// Первый в очереди не платит ничего: рецикл одинокого стрима не должен ждать шаг.
|
||||
func TestAllocPacerFirstSlotIsFree(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newAllocPacer(time.Second)
|
||||
|
||||
start := time.Now()
|
||||
if !p.wait(context.Background()) {
|
||||
t.Fatal("wait returned false")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 100*time.Millisecond {
|
||||
t.Fatalf("first wait took %v, want immediate", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllocPacerWaitReturnsFalseOnCancel(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newAllocPacer(time.Hour)
|
||||
p.slot() // занять первый слот, следующий уедет на час
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
if p.wait(ctx) {
|
||||
t.Fatal("wait returned true on cancelled context")
|
||||
}
|
||||
}
|
||||
|
||||
// Nil-приёмник допустим: Deps собирают и в обход Run.
|
||||
func TestAllocPacerNilIsPassthrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
var p *allocPacer
|
||||
if !p.wait(context.Background()) {
|
||||
t.Fatal("nil pacer must pass through")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if p.wait(ctx) {
|
||||
t.Fatal("nil pacer must respect cancelled context")
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/logx"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/proxy/allocpace"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/safego"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/stats"
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/transport/dtlsdial"
|
||||
@@ -51,7 +52,7 @@ type Deps struct {
|
||||
ConnectedStreams *atomic.Int32
|
||||
OnTURNServer func(ip net.IP)
|
||||
fatalCh chan error
|
||||
allocPace *allocPacer
|
||||
allocPace *allocpace.Pacer
|
||||
}
|
||||
|
||||
func (d *Deps) log() logx.Logger {
|
||||
@@ -92,7 +93,7 @@ func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, log
|
||||
ConnectedStreams: connectedStreams,
|
||||
OnTURNServer: onTURNServer,
|
||||
fatalCh: fatalCh,
|
||||
allocPace: newAllocPacer(allocPaceInterval),
|
||||
allocPace: allocpace.New(allocpace.DefaultInterval),
|
||||
}
|
||||
|
||||
runCtx, runCancel := context.WithCancel(ctx)
|
||||
|
||||
Reference in new issue
Block a user