Выпуск WDTT Plus v17
This commit is contained in:
1 parent
4be5f36c88
commit
abf0a0f130
33 files changed
+763
-262
No files matched your search
+63
-11
@@ -60,6 +60,38 @@ func workerDistributionByHash(workerCount, hashCount int) []int {
|
||||
return distribution
|
||||
}
|
||||
|
||||
func workerHashCandidates(hashes []string, hashIndex, requestedWorkers int, fallback bool) []string {
|
||||
if len(hashes) == 0 {
|
||||
return nil
|
||||
}
|
||||
primary := ((hashIndex % len(hashes)) + len(hashes)) % len(hashes)
|
||||
if !fallback || len(hashes) == 1 {
|
||||
return []string{hashes[primary]}
|
||||
}
|
||||
|
||||
groupCount := requestedWorkers / workersPerGroup
|
||||
if groupCount < 1 {
|
||||
groupCount = 1
|
||||
}
|
||||
primaryCount := min(groupCount, len(hashes))
|
||||
result := make([]string, 0, len(hashes))
|
||||
result = append(result, hashes[primary])
|
||||
|
||||
// Prefer hashes that have no primary group. With 18 workers and four
|
||||
// hashes this gives group 1 hash 3 as its first reserve and group 2 hash 4,
|
||||
// so one degraded group does not move onto the other group's live hash.
|
||||
unusedCount := len(hashes) - primaryCount
|
||||
for offset := 0; offset < unusedCount; offset++ {
|
||||
index := primaryCount + (primary+offset)%unusedCount
|
||||
result = append(result, hashes[index])
|
||||
}
|
||||
for offset := 1; offset < primaryCount; offset++ {
|
||||
index := (primary + offset) % primaryCount
|
||||
result = append(result, hashes[index])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// startPacer распределяет первичные подключения всех групп по общей шкале
|
||||
// времени. Это позволяет готовить группы параллельно, не создавая всплеск из
|
||||
// десятков одновременных DTLS/TURN-handshake.
|
||||
@@ -238,6 +270,15 @@ func workerRetryDelayAfterCredentialRefresh(err error, result credentialRefreshR
|
||||
return refreshedCredsRetryMin + time.Duration(slot)*refreshedCredsRetrySlot + jitter
|
||||
}
|
||||
|
||||
func shouldRotateTurnCandidateAfterSessionError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
message := strings.ToUpper(err.Error())
|
||||
return strings.Contains(message, "WRAP_AUTH_TIMEOUT") ||
|
||||
strings.Contains(message, "DTLS ХЕНДШЕЙК")
|
||||
}
|
||||
|
||||
type workerPolicyRetryGate struct {
|
||||
mu sync.Mutex
|
||||
blockedUntil time.Time
|
||||
@@ -432,16 +473,7 @@ func WorkerGroup(
|
||||
}
|
||||
}
|
||||
|
||||
hashCandidates := []string{tp.Hashes[hashIndex%len(tp.Hashes)]}
|
||||
if hashFallback && len(tp.Hashes) > 1 {
|
||||
hashCandidates = make([]string, 0, len(tp.Hashes))
|
||||
for offset := 0; offset < len(tp.Hashes); offset++ {
|
||||
hashCandidates = append(
|
||||
hashCandidates,
|
||||
tp.Hashes[(hashIndex+offset)%len(tp.Hashes)],
|
||||
)
|
||||
}
|
||||
}
|
||||
hashCandidates := workerHashCandidates(tp.Hashes, hashIndex, requestedWorkers, hashFallback)
|
||||
selectedHash := 0
|
||||
hash := hashCandidates[selectedHash]
|
||||
log.Printf("[ГРУППА #%d] Запрос реквизитов подключения", groupID)
|
||||
@@ -595,6 +627,7 @@ func WorkerGroup(
|
||||
|
||||
shouldGetConfig := getConfig
|
||||
attempt := 0
|
||||
turnCandidateRetry := 0
|
||||
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
@@ -624,7 +657,8 @@ func WorkerGroup(
|
||||
configDelivered, sessErr := RunSession(ctx, tp, peer, d, localPort,
|
||||
getConf, cc, requireConfig, onConfigDelivered, wid, &credsSnapshot,
|
||||
deviceID, password, deviceInfo,
|
||||
transportSession, stats, turnStreamFirst, turnCapacityGate.reset)
|
||||
transportSession, stats, turnStreamFirst, turnCandidateRetry,
|
||||
turnCapacityGate.reset)
|
||||
refreshResult := credentialRefreshNone
|
||||
|
||||
if getConf {
|
||||
@@ -639,6 +673,10 @@ func WorkerGroup(
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
relayHandshakeFailed := shouldRotateTurnCandidateAfterSessionError(sessErr)
|
||||
if relayHandshakeFailed {
|
||||
turnCandidateRetry++
|
||||
}
|
||||
if maxWorkers, limited := workerPolicyLimit(sessErr); limited {
|
||||
if shouldRetryWorkerPolicy(maxWorkers, requestedWorkers) {
|
||||
startedRound, round, waitErr := policyRetryGate.wait(ctx, wid)
|
||||
@@ -697,9 +735,23 @@ func WorkerGroup(
|
||||
return
|
||||
}
|
||||
continue
|
||||
} else if relayHandshakeFailed &&
|
||||
hashFallback &&
|
||||
len(credsSnapshot.TurnURLs) > 0 &&
|
||||
turnCandidateRetry%len(credsSnapshot.TurnURLs) == 0 {
|
||||
log.Printf("[ВОРКЕР #%d] Ошибка (попытка %d): %s", wid, attempt, errStr)
|
||||
log.Printf(
|
||||
"[ВОРКЕР #%d] [TURN] Все relay-пути текущего VK-хеша не провели DTLS; пробуем резервный хеш",
|
||||
wid,
|
||||
)
|
||||
refreshResult = refreshCreds("TURN relay handshake timeout", credsRevision)
|
||||
} else {
|
||||
log.Printf("[ВОРКЕР #%d] Ошибка (попытка %d): %s", wid, attempt, errStr)
|
||||
}
|
||||
if refreshResult == credentialRefreshApplied ||
|
||||
refreshResult == credentialRefreshSuperseded {
|
||||
turnCandidateRetry = 0
|
||||
}
|
||||
|
||||
// Если ошибка STUN (credentials invalid), воркер не сможет переподключиться. Завершаем.
|
||||
isStunDeath := strings.Contains(errStrLower, "error 29") ||
|
||||
|
||||
@@ -81,6 +81,29 @@ func TestWorkerDistributionByHashUsesAllHashesWithoutOverloadingOne(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerHashCandidatesPreferUnusedManagedProfileHashes(t *testing.T) {
|
||||
hashes := []string{"hash-1", "hash-2", "hash-3", "hash-4"}
|
||||
|
||||
first := workerHashCandidates(hashes, 0, 18, true)
|
||||
second := workerHashCandidates(hashes, 1, 18, true)
|
||||
if !reflect.DeepEqual(first, []string{"hash-1", "hash-3", "hash-4", "hash-2"}) {
|
||||
t.Fatalf("first group candidates = %v", first)
|
||||
}
|
||||
if !reflect.DeepEqual(second, []string{"hash-2", "hash-4", "hash-3", "hash-1"}) {
|
||||
t.Fatalf("second group candidates = %v", second)
|
||||
}
|
||||
if first[1] == second[1] {
|
||||
t.Fatalf("independent groups unexpectedly share first reserve: %v / %v", first, second)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerHashCandidatesKeepOrdinaryProfileOnPrimaryHash(t *testing.T) {
|
||||
hashes := []string{"hash-1", "hash-2", "hash-3", "hash-4"}
|
||||
if got := workerHashCandidates(hashes, 1, 18, false); !reflect.DeepEqual(got, []string{"hash-2"}) {
|
||||
t.Fatalf("ordinary profile candidates = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartPacerWaitHonorsCancellation(t *testing.T) {
|
||||
pacer := newStartPacer(time.Hour)
|
||||
if err := pacer.wait(context.Background()); err != nil {
|
||||
@@ -376,6 +399,28 @@ func TestWrapHandshakeTimeoutAllowsFourFlightsBeforeFastRetry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTurnCandidateRotationIsLimitedToPostAllocateHandshakeFailures(t *testing.T) {
|
||||
for _, err := range []error{
|
||||
errors.New("WRAP_AUTH_TIMEOUT: отдельный DTLS-канал не ответил вовремя"),
|
||||
errors.New("DTLS хендшейк до VPS example.test:56000 не прошёл: timeout"),
|
||||
} {
|
||||
if !shouldRotateTurnCandidateAfterSessionError(err) {
|
||||
t.Fatalf("expected TURN candidate rotation for %q", err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, err := range []error{
|
||||
nil,
|
||||
errors.New("TURN Allocate: error 508 Insufficient Capacity"),
|
||||
errors.New("401 Unauthorized"),
|
||||
errors.New("use of closed network connection"),
|
||||
} {
|
||||
if shouldRotateTurnCandidateAfterSessionError(err) {
|
||||
t.Fatalf("unexpected TURN candidate rotation for %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigFirstStartGateBlocksEveryWorkerExceptTheConfigWorker(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
+2
-2
@@ -355,7 +355,7 @@ func main() {
|
||||
hashFallback := flag.Bool(
|
||||
"hash-fallback",
|
||||
false,
|
||||
"использовать остальные VK-хеши как резерв единственной группы",
|
||||
"использовать остальные VK-хеши как резерв групп",
|
||||
)
|
||||
|
||||
deviceID := flag.String("device-id", "unknown", "уникальный ID устройства")
|
||||
@@ -515,7 +515,7 @@ func main() {
|
||||
}
|
||||
*numW = (*numW / workersPerGroup) * workersPerGroup
|
||||
useConfigFirstStart := *configFirstStart
|
||||
useHashFallback := *hashFallback && *numW == workersPerGroup
|
||||
useHashFallback := *hashFallback
|
||||
|
||||
var masqueManager *warpMasqueManager
|
||||
if *turnStreamFirst && *rtMasque {
|
||||
|
||||
@@ -387,6 +387,7 @@ func RunSession(
|
||||
deviceID, password, deviceInfo, transportSession string,
|
||||
stats *Stats,
|
||||
preferTURNStream bool,
|
||||
turnCandidateRetry int,
|
||||
onTURNAllocated func(),
|
||||
) (bool, error) {
|
||||
configDelivered := false
|
||||
@@ -394,9 +395,10 @@ func RunSession(
|
||||
if len(creds.TurnURLs) == 0 {
|
||||
return false, fmt.Errorf("нет TURN URL в учетных данных")
|
||||
}
|
||||
candidates := sessionTURNCandidatesWithPreference(
|
||||
candidates := sessionTURNCandidatesForAttempt(
|
||||
creds.TurnURLs,
|
||||
sessionID,
|
||||
turnCandidateRetry,
|
||||
tp,
|
||||
preferTURNStream,
|
||||
)
|
||||
|
||||
@@ -160,11 +160,27 @@ func sessionTURNCandidatesWithPreference(
|
||||
sessionID int,
|
||||
tp *TurnParams,
|
||||
preferStream bool,
|
||||
) []turnEndpoint {
|
||||
return sessionTURNCandidatesForAttempt(rawURLs, sessionID, 0, tp, preferStream)
|
||||
}
|
||||
|
||||
// sessionTURNCandidatesForAttempt rotates only the first TURN candidate after
|
||||
// a relay accepted Allocate but did not carry the following DTLS handshake.
|
||||
// The initial attempt keeps the historical endpoint order unchanged.
|
||||
func sessionTURNCandidatesForAttempt(
|
||||
rawURLs []string,
|
||||
sessionID int,
|
||||
retryOffset int,
|
||||
tp *TurnParams,
|
||||
preferStream bool,
|
||||
) []turnEndpoint {
|
||||
if len(rawURLs) == 0 {
|
||||
return nil
|
||||
}
|
||||
selectedIndex := sessionID % len(rawURLs)
|
||||
if retryOffset < 0 {
|
||||
retryOffset = 0
|
||||
}
|
||||
selectedIndex := (sessionID + retryOffset) % len(rawURLs)
|
||||
if selectedIndex < 0 {
|
||||
selectedIndex = 0
|
||||
}
|
||||
|
||||
@@ -122,3 +122,25 @@ func TestSessionTURNCandidatesApplyOverride(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionTURNCandidatesRotateAfterRelayHandshakeTimeout(t *testing.T) {
|
||||
raw := []string{
|
||||
"turn:one.example:3478?transport=udp",
|
||||
"turn:two.example:3478?transport=udp",
|
||||
"turn:three.example:3478?transport=udp",
|
||||
}
|
||||
|
||||
initial := sessionTURNCandidatesForAttempt(raw, 1, 0, nil, false)
|
||||
retry := sessionTURNCandidatesForAttempt(raw, 1, 1, nil, false)
|
||||
wrapped := sessionTURNCandidatesForAttempt(raw, 1, len(raw), nil, false)
|
||||
|
||||
if initial[0].Host != "two.example" {
|
||||
t.Fatalf("initial candidate changed: %#v", initial)
|
||||
}
|
||||
if retry[0].Host != "three.example" {
|
||||
t.Fatalf("retry did not rotate candidate: %#v", retry)
|
||||
}
|
||||
if wrapped[0].Host != initial[0].Host {
|
||||
t.Fatalf("candidate rotation did not wrap: initial=%#v wrapped=%#v", initial, wrapped)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user