fix(relay): восстановление потоков при отказах turn и занятой квоте

This commit is contained in:
samosvalishe committed 2026-09-12 17:29:09 +03:00
1 parent e72157f4f7
commit 6570cd9dd7
12 files changed
+117 -12

No files matched your search

+11 -1
View File
@@ -10,7 +10,9 @@ import (
const (
permFailMarker = "Failed to bind channel"
permOKMarker = "Channel binding successful"
turncScope = "turnc"
// Refresh сообщает об отказе раньше очередного ChannelBind.
allocFailMarker = "Failed to refresh allocation"
turncScope = "turnc"
// permFailThreshold - число последовательных провалов ChannelBind refresh до срабатывания onDead.
permFailThreshold = 2
)
@@ -40,6 +42,14 @@ type permWatchLogger struct {
func (l *permWatchLogger) note(msg string) {
switch {
case strings.Contains(msg, allocFailMarker):
l.mu.Lock()
fire := !l.fired
l.fired = true
l.mu.Unlock()
if fire && l.f.onDead != nil {
l.f.onDead()
}
case strings.Contains(msg, permFailMarker):
l.mu.Lock()
l.fails++
+29 -1
View File
@@ -64,8 +64,36 @@ func TestPermWatchIgnoresUnrelatedMessages(t *testing.T) {
log := f.NewLogger(turncScope)
log.Debug("Started refresh permission timer")
log.Debug("No permission to refresh")
log.Warnf("Failed to refresh allocation: %s", "x")
log.Debug("Refresh permissions successful")
if fired.Load() != 0 {
t.Fatalf("fired on unrelated message: %d", fired.Load())
}
}
// Провал Refresh мимо порога ChannelBind: аллокация уже мертва.
func TestPermWatchFiresOnAllocRefreshFail(t *testing.T) {
f, fired := newTestWatch(2)
log := f.NewLogger(turncScope)
log.Warnf(allocFailMarker+": %s", "all retransmissions failed")
if fired.Load() != 1 {
t.Fatalf("expected immediate fire, got %d", fired.Load())
}
log.Warnf(allocFailMarker + ": again")
if fired.Load() != 1 {
t.Fatalf("fired more than once: %d", fired.Load())
}
}
// Успешный ChannelBind не отменяет мёртвую аллокацию.
func TestPermWatchAllocFailNotResetByBindOK(t *testing.T) {
f, fired := newTestWatch(2)
log := f.NewLogger(turncScope)
log.Warnf(allocFailMarker + ": x")
log.Debug(permOKMarker)
log.Warnf(allocFailMarker + ": x")
if fired.Load() != 1 {
t.Fatalf("expected exactly 1 fire, got %d", fired.Load())
}
}
+14
View File
@@ -3,11 +3,13 @@ package turndial
import (
"context"
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/pion/stun/v3"
"github.com/pion/turn/v5"
"github.com/samosvalishe/free-turn-proxy/internal/logx"
"github.com/samosvalishe/free-turn-proxy/internal/netconn"
@@ -15,6 +17,10 @@ import (
"github.com/samosvalishe/free-turn-proxy/internal/randx"
)
// ErrAllocQuota - TURN-код 486: реквизиты валидны, но по ним уже висит предельное число
// аллокаций. Лечится ожиданием, а не сменой реквизитов (см. IsAuthError в vkauth).
var ErrAllocQuota = errors.New("turndial: allocation quota reached")
// Config задаёт параметры подключения к TURN-серверу.
type Config struct {
HostOverride string
@@ -34,6 +40,11 @@ type Stream struct {
close func() error
}
func isQuotaError(err error) bool {
turnErr, ok := errors.AsType[*stun.TurnError](err)
return ok && turnErr.ErrorCodeAttr.Code == stun.CodeAllocQuotaReached
}
// Close освобождает аллокацию, TURN-клиент и транспортное соединение.
func (s *Stream) Close() error {
if s == nil || s.close == nil {
@@ -141,6 +152,9 @@ func Open(ctx context.Context, cfg Config, peer *net.UDPAddr, user, pass, rawAdd
if cerr := closeConn(); cerr != nil {
err = fmt.Errorf("%w (close: %v)", err, cerr)
}
if isQuotaError(err) {
return nil, fmt.Errorf("%w: %w", ErrAllocQuota, err)
}
return nil, fmt.Errorf("TURN allocate: %w", err)
}
@@ -2,12 +2,30 @@ package turndial
import (
"context"
"errors"
"fmt"
"net"
"strings"
"testing"
"time"
"github.com/pion/stun/v3"
)
func TestIsQuotaError(t *testing.T) {
quota := &stun.TurnError{ErrorCodeAttr: stun.ErrorCodeAttribute{Code: stun.CodeAllocQuotaReached}}
if !isQuotaError(fmt.Errorf("allocate: %w", quota)) {
t.Fatal("wrapped 486 not recognized")
}
if isQuotaError(errors.New("486 Allocation Quota Reached")) || isQuotaError(nil) {
t.Fatal("untyped error treated as quota")
}
unauthorized := &stun.TurnError{ErrorCodeAttr: stun.ErrorCodeAttribute{Code: stun.CodeUnauthorized}}
if isQuotaError(unauthorized) {
t.Fatal("401 treated as quota")
}
}
func TestOpen_BadAddress(t *testing.T) {
peer := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 1}
_, err := Open(context.Background(), Config{}, peer, "u", "p", "not-a-host-port")