Skip to content

Commit

Permalink
fix(api): unified packet loss interface
Browse files Browse the repository at this point in the history
  • Loading branch information
r3inbowari committed May 15, 2024
1 parent 75c605f commit 85363d4
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
4 changes: 3 additions & 1 deletion example/packet_loss/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ func main() {
// use mixed PacketLoss
mixed, err := analyzer.RunMulti(serverList.Hosts())
checkError(err)
fmt.Printf("Mixed packets lossed: %.2f\n", mixed)
fmt.Printf("Mixed packets lossed: %.2f%%\n", mixed.LossPercent())
fmt.Printf("Mixed packets lossed: %.2f\n", mixed.Loss())
fmt.Printf("Mixed packets lossed: %s\n", mixed)
}

func checkError(err error) {
Expand Down
8 changes: 4 additions & 4 deletions speedtest/loss.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,13 @@ func NewPacketLossAnalyzer(options *PacketLossAnalyzerOptions) *PacketLossAnalyz
}

// RunMulti Mix all servers to get the average packet loss.
func (pla *PacketLossAnalyzer) RunMulti(hosts []string) (float64, error) {
func (pla *PacketLossAnalyzer) RunMulti(hosts []string) (*transport.PLoss, error) {
ctx, cancel := context.WithTimeout(context.Background(), pla.options.SamplingDuration)
defer cancel()
return pla.RunMultiWithContext(ctx, hosts)
}

func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts []string) (float64, error) {
func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts []string) (*transport.PLoss, error) {
results := make(map[string]*transport.PLoss)
mutex := &sync.Mutex{}
wg := &sync.WaitGroup{}
Expand All @@ -86,15 +86,15 @@ func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts []
}
wg.Wait()
if len(results) == 0 {
return -1, transport.ErrUnsupported
return nil, transport.ErrUnsupported
}
var pLoss transport.PLoss
for _, hostPacketLoss := range results {
pLoss.Sent += hostPacketLoss.Sent
pLoss.Dup += hostPacketLoss.Dup
pLoss.Max += hostPacketLoss.Max
}
return pLoss.Loss(), nil
return &pLoss, nil
}

func (pla *PacketLossAnalyzer) Run(host string, callback func(packetLoss *transport.PLoss)) error {
Expand Down
7 changes: 7 additions & 0 deletions speedtest/transport/tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,13 @@ func (p PLoss) Loss() float64 {
return 1 - (float64(p.Sent-p.Dup))/float64(p.Max+1)
}

func (p PLoss) LossPercent() float64 {
if p.Sent == 0 {
return -1
}
return p.Loss() * 100
}

func (client *Client) PacketLoss() (*PLoss, error) {
err := client.Write(packetLoss)
if err != nil {
Expand Down

0 comments on commit 85363d4

Please sign in to comment.