feat(proxy): tcp-режим для xray/sing-box поверх turn

This commit is contained in:
samosvalishe committed 2026-08-25 15:44:16 +03:00
1 parent e63279db18
commit f7129099f7
60 files changed
+2953 -135

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
// Package allocpace распределяет во времени вызовы TURN Allocate: квота считается на
// username, поэтому залп от всех потоков сразу упирается в неё плотнее, чем очередь.
package allocpace
import (
"context"
"sync"
"time"
)
const DefaultInterval = 200 * time.Millisecond
type Pacer struct {
mu sync.Mutex
next time.Time
step time.Duration
}
func New(step time.Duration) *Pacer {
return &Pacer{step: step}
}
// Wait возвращает false, только если ctx отменён - слот всё равно занят и не переиспользуется.
func (p *Pacer) 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 *Pacer) 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
}
@@ -0,0 +1,87 @@
package allocpace
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 := New(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 := New(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 := New(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 *Pacer
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")
}
}