|
| 1 | +package endpointselect |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/tls" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "log/slog" |
| 9 | + "net" |
| 10 | + "net/http" |
| 11 | + "sort" |
| 12 | + "sync" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/quic-go/quic-go" |
| 16 | + "github.com/quic-go/quic-go/http3" |
| 17 | +) |
| 18 | + |
| 19 | +const ( |
| 20 | + // DefaultProbeTimeout is the default timeout for each endpoint probe. |
| 21 | + DefaultProbeTimeout = 3 * time.Second |
| 22 | + // DefaultMaxConcurrent is the default maximum number of concurrent probes. |
| 23 | + DefaultMaxConcurrent = 10 |
| 24 | +) |
| 25 | + |
| 26 | +// Option configures a LatencySelector. |
| 27 | +type Option func(*latencyOptions) |
| 28 | + |
| 29 | +type latencyOptions struct { |
| 30 | + probeTimeout time.Duration |
| 31 | + maxConcurrent int |
| 32 | + insecureSkip bool |
| 33 | +} |
| 34 | + |
| 35 | +// WithProbeTimeout sets the timeout for each endpoint probe. |
| 36 | +func WithProbeTimeout(timeout time.Duration) Option { |
| 37 | + return func(o *latencyOptions) { |
| 38 | + o.probeTimeout = timeout |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// WithMaxConcurrent sets the maximum number of concurrent probes. |
| 43 | +func WithMaxConcurrent(max int) Option { |
| 44 | + return func(o *latencyOptions) { |
| 45 | + o.maxConcurrent = max |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// WithInsecureSkipVerify sets whether to skip TLS certificate verification. |
| 50 | +func WithInsecureSkipVerify(skip bool) Option { |
| 51 | + return func(o *latencyOptions) { |
| 52 | + o.insecureSkip = skip |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// LatencySelector selects endpoints based on QUIC handshake latency. |
| 57 | +type LatencySelector struct { |
| 58 | + opts latencyOptions |
| 59 | +} |
| 60 | + |
| 61 | +// NewLatencySelector creates a new LatencySelector. |
| 62 | +func NewLatencySelector(opts ...Option) *LatencySelector { |
| 63 | + options := latencyOptions{ |
| 64 | + probeTimeout: DefaultProbeTimeout, |
| 65 | + maxConcurrent: DefaultMaxConcurrent, |
| 66 | + } |
| 67 | + for _, opt := range opts { |
| 68 | + opt(&options) |
| 69 | + } |
| 70 | + return &LatencySelector{opts: options} |
| 71 | +} |
| 72 | + |
| 73 | +// Select returns the endpoint with the lowest latency. |
| 74 | +func (s *LatencySelector) Select(ctx context.Context, endpoints []string) (string, error) { |
| 75 | + addr, _, err := s.SelectWithResults(ctx, endpoints) |
| 76 | + return addr, err |
| 77 | +} |
| 78 | + |
| 79 | +// SelectWithResults returns the endpoint with the lowest latency along with all probe results. |
| 80 | +func (s *LatencySelector) SelectWithResults(ctx context.Context, endpoints []string) (string, []ProbeResult, error) { |
| 81 | + if len(endpoints) == 0 { |
| 82 | + return "", nil, errors.New("no endpoints provided") |
| 83 | + } |
| 84 | + if len(endpoints) == 1 { |
| 85 | + return endpoints[0], []ProbeResult{{ |
| 86 | + Addr: endpoints[0], |
| 87 | + ProbedAt: time.Now(), |
| 88 | + }}, nil |
| 89 | + } |
| 90 | + |
| 91 | + results := s.probeAll(ctx, endpoints) |
| 92 | + |
| 93 | + // Sort by latency (errors go to the end). |
| 94 | + sort.Slice(results, func(i, j int) bool { |
| 95 | + // Errors go to the end. |
| 96 | + if results[i].Error != nil && results[j].Error != nil { |
| 97 | + return false |
| 98 | + } |
| 99 | + if results[i].Error != nil { |
| 100 | + return false |
| 101 | + } |
| 102 | + if results[j].Error != nil { |
| 103 | + return true |
| 104 | + } |
| 105 | + return results[i].Latency < results[j].Latency |
| 106 | + }) |
| 107 | + |
| 108 | + // Find the first successful result. |
| 109 | + for _, r := range results { |
| 110 | + if r.Error == nil { |
| 111 | + slog.Info("Selected endpoint based on latency", |
| 112 | + slog.String("addr", r.Addr), |
| 113 | + slog.Duration("latency", r.Latency)) |
| 114 | + return r.Addr, results, nil |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // All probes failed - return error with details. |
| 119 | + return "", results, errors.New("all endpoint probes failed") |
| 120 | +} |
| 121 | + |
| 122 | +// probeAll probes all endpoints concurrently and returns the results. |
| 123 | +func (s *LatencySelector) probeAll(ctx context.Context, endpoints []string) []ProbeResult { |
| 124 | + results := make([]ProbeResult, len(endpoints)) |
| 125 | + var wg sync.WaitGroup |
| 126 | + |
| 127 | + // Semaphore to limit concurrent probes. |
| 128 | + sem := make(chan struct{}, s.opts.maxConcurrent) |
| 129 | + |
| 130 | + for i, endpoint := range endpoints { |
| 131 | + wg.Add(1) |
| 132 | + go func(idx int, addr string) { |
| 133 | + defer wg.Done() |
| 134 | + |
| 135 | + // Acquire semaphore. |
| 136 | + select { |
| 137 | + case sem <- struct{}{}: |
| 138 | + defer func() { <-sem }() |
| 139 | + case <-ctx.Done(): |
| 140 | + results[idx] = ProbeResult{ |
| 141 | + Addr: addr, |
| 142 | + Error: ctx.Err(), |
| 143 | + ProbedAt: time.Now(), |
| 144 | + } |
| 145 | + return |
| 146 | + } |
| 147 | + |
| 148 | + results[idx] = s.probe(ctx, addr) |
| 149 | + }(i, endpoint) |
| 150 | + } |
| 151 | + |
| 152 | + wg.Wait() |
| 153 | + return results |
| 154 | +} |
| 155 | + |
| 156 | +// probe measures the round-trip latency to a single endpoint by making |
| 157 | +// an HTTP/3 request to the /ping endpoint. |
| 158 | +func (s *LatencySelector) probe(ctx context.Context, addr string) ProbeResult { |
| 159 | + result := ProbeResult{ |
| 160 | + Addr: addr, |
| 161 | + ProbedAt: time.Now(), |
| 162 | + } |
| 163 | + |
| 164 | + probeCtx, cancel := context.WithTimeout(ctx, s.opts.probeTimeout) |
| 165 | + defer cancel() |
| 166 | + |
| 167 | + // Extract hostname from address for TLS ServerName. |
| 168 | + serverName := "proxy" |
| 169 | + if host, _, err := net.SplitHostPort(addr); err == nil && net.ParseIP(host) == nil { |
| 170 | + serverName = host |
| 171 | + } |
| 172 | + |
| 173 | + tlsConfig := &tls.Config{ |
| 174 | + ServerName: serverName, |
| 175 | + NextProtos: []string{http3.NextProtoH3}, |
| 176 | + InsecureSkipVerify: s.opts.insecureSkip, |
| 177 | + } |
| 178 | + |
| 179 | + quicConfig := &quic.Config{ |
| 180 | + EnableDatagrams: true, |
| 181 | + InitialPacketSize: 1350, |
| 182 | + } |
| 183 | + |
| 184 | + start := time.Now() |
| 185 | + |
| 186 | + // Dial QUIC connection. |
| 187 | + qConn, err := quic.DialAddr(probeCtx, addr, tlsConfig, quicConfig) |
| 188 | + if err != nil { |
| 189 | + result.Error = err |
| 190 | + slog.Debug("Endpoint probe failed (QUIC dial)", |
| 191 | + slog.String("addr", addr), |
| 192 | + slog.Any("error", err)) |
| 193 | + return result |
| 194 | + } |
| 195 | + defer qConn.CloseWithError(0, "probe complete") |
| 196 | + |
| 197 | + // Make HTTP/3 request to /ping endpoint. |
| 198 | + tr := &http3.Transport{EnableDatagrams: true} |
| 199 | + hConn := tr.NewClientConn(qConn) |
| 200 | + |
| 201 | + req, err := http.NewRequestWithContext(probeCtx, "GET", "https://proxy/ping", nil) |
| 202 | + if err != nil { |
| 203 | + result.Error = err |
| 204 | + slog.Debug("Endpoint probe failed (request creation)", |
| 205 | + slog.String("addr", addr), |
| 206 | + slog.Any("error", err)) |
| 207 | + return result |
| 208 | + } |
| 209 | + |
| 210 | + resp, err := hConn.RoundTrip(req) |
| 211 | + if err != nil { |
| 212 | + result.Error = err |
| 213 | + slog.Debug("Endpoint probe failed (HTTP/3 request)", |
| 214 | + slog.String("addr", addr), |
| 215 | + slog.Any("error", err)) |
| 216 | + return result |
| 217 | + } |
| 218 | + defer resp.Body.Close() |
| 219 | + |
| 220 | + if resp.StatusCode != http.StatusOK { |
| 221 | + result.Error = fmt.Errorf("ping returned status %d", resp.StatusCode) |
| 222 | + slog.Debug("Endpoint probe failed (bad status)", |
| 223 | + slog.String("addr", addr), |
| 224 | + slog.Int("status", resp.StatusCode)) |
| 225 | + return result |
| 226 | + } |
| 227 | + |
| 228 | + result.Latency = time.Since(start) |
| 229 | + |
| 230 | + slog.Debug("Endpoint probe succeeded", |
| 231 | + slog.String("addr", addr), |
| 232 | + slog.Duration("latency", result.Latency)) |
| 233 | + |
| 234 | + return result |
| 235 | +} |
0 commit comments