package service import ( "testing" "time" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" ) func TestClientFanoutAdmitsHealthyNodeBeforeSlowNodeFillsSlots(t *testing.T) { slow, healthy := 1, 2 release := make(chan struct{}) healthyStarted := make(chan struct{}) applies := make([]inboundApply, 0, inboundFanoutConcurrency+1) for i := range inboundFanoutConcurrency { applies = append(applies, inboundApply{id: i + 1, nodeID: &slow, run: func() (bool, error) { <-release return false, nil }}) } applies = append(applies, inboundApply{id: len(applies) + 1, nodeID: &healthy, run: func() (bool, error) { close(healthyStarted) return false, nil }}) done := make(chan error, 1) go func() { _, err := fanoutInboundApplies(applies) done <- err }() defer func() { close(release) if err := <-done; err != nil { t.Error(err) } }() select { case <-healthyStarted: case <-time.After(2 * time.Second): t.Fatal("healthy node waited for a slow node to free a slot") } } func TestBulkClientFanoutAdmitsHealthyNodeBeforeSlowNodeFillsSlots(t *testing.T) { setupBulkDB(t) slow := model.Node{Name: "slow", Address: "127.0.0.1", Port: 8443} healthy := model.Node{Name: "healthy", Address: "127.0.0.1", Port: 8444} if err := database.GetDB().Create(&slow).Error; err != nil { t.Fatal(err) } if err := database.GetDB().Create(&healthy).Error; err != nil { t.Fatal(err) } var ids []int for i := range inboundFanoutConcurrency { ids = append(ids, nodeInbound(t, slow.Id, 54500+i, nil).Id) } ids = append(ids, nodeInbound(t, healthy.Id, 54510, nil).Id) release, started := make(chan struct{}), make(chan struct{}) done := make(chan []int, 1) go func() { out, _ := fanoutClientInboundResults(ids, inboundFanoutConcurrency, func(i int) int { if i == len(ids)-1 { close(started) } else { <-release } return ids[i] }) done <- out }() defer func() { close(release) out := <-done for i := range ids { if out[i] != ids[i] { t.Errorf("result %d belongs to inbound %d, want %d", i, out[i], ids[i]) } } }() select { case <-started: case <-time.After(time.Second): t.Fatal("bulk fanout left the healthy inbound behind the slow node") } }