2024-02-13 11:11:10 +00:00
|
|
|
package api
|
2021-05-08 23:37:32 +00:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2023-05-20 19:58:18 +00:00
|
|
|
"net/netip"
|
2024-02-13 11:11:10 +00:00
|
|
|
|
|
|
|
|
"github.com/qdm12/gluetun/internal/models"
|
2021-05-08 23:37:32 +00:00
|
|
|
)
|
|
|
|
|
|
2022-06-12 00:09:01 +00:00
|
|
|
// FetchMultiInfo obtains the public IP address information for every IP
|
2021-05-08 23:37:32 +00:00
|
|
|
// addresses provided and returns a slice of results with the corresponding
|
|
|
|
|
// order as to the IP addresses slice order.
|
|
|
|
|
// If an error is encountered, all the operations are canceled and
|
|
|
|
|
// an error is returned, so the results returned should be considered
|
|
|
|
|
// incomplete in this case.
|
2024-10-19 15:21:14 +02:00
|
|
|
func FetchMultiInfo(ctx context.Context, fetcher InfoFetcher, ips []netip.Addr) (
|
2024-10-11 19:20:48 +00:00
|
|
|
results []models.PublicIP, err error,
|
|
|
|
|
) {
|
2021-05-08 23:37:32 +00:00
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
|
|
|
|
|
|
type asyncResult struct {
|
|
|
|
|
index int
|
2024-02-13 11:11:10 +00:00
|
|
|
result models.PublicIP
|
2021-05-08 23:37:32 +00:00
|
|
|
err error
|
|
|
|
|
}
|
|
|
|
|
resultsCh := make(chan asyncResult)
|
|
|
|
|
|
|
|
|
|
for i, ip := range ips {
|
2023-05-20 19:58:18 +00:00
|
|
|
go func(index int, ip netip.Addr) {
|
2021-05-08 23:37:32 +00:00
|
|
|
aResult := asyncResult{
|
|
|
|
|
index: index,
|
|
|
|
|
}
|
2024-02-13 11:11:10 +00:00
|
|
|
aResult.result, aResult.err = fetcher.FetchInfo(ctx, ip)
|
2021-05-08 23:37:32 +00:00
|
|
|
resultsCh <- aResult
|
|
|
|
|
}(i, ip)
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-13 11:11:10 +00:00
|
|
|
results = make([]models.PublicIP, len(ips))
|
2024-10-11 18:28:00 +00:00
|
|
|
for range len(ips) {
|
2021-05-08 23:37:32 +00:00
|
|
|
aResult := <-resultsCh
|
|
|
|
|
if aResult.err != nil {
|
|
|
|
|
if err == nil {
|
|
|
|
|
// Cancel on the first error encountered
|
|
|
|
|
err = aResult.err
|
|
|
|
|
cancel()
|
|
|
|
|
}
|
|
|
|
|
continue // ignore errors after the first one
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
results[aResult.index] = aResult.result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
close(resultsCh)
|
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
|
|
return results, err
|
|
|
|
|
}
|