From f78a7cb2cbe34bae15505053cb640016aa30027d Mon Sep 17 00:00:00 2001 From: Dreamacro <8615343+Dreamacro@users.noreply.github.com> Date: Mon, 27 Feb 2023 19:13:26 +0800 Subject: [PATCH] Feature: add meanDelay on URLTest --- adapter/adapter.go | 15 ++++++++++++--- constant/adapters.go | 7 ++++--- hub/route/proxies.go | 5 +++-- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/adapter/adapter.go b/adapter/adapter.go index c41cff4..094d9eb 100644 --- a/adapter/adapter.go +++ b/adapter/adapter.go @@ -101,12 +101,13 @@ func (p *Proxy) MarshalJSON() ([]byte, error) { // URLTest get the delay for the specified URL // implements C.Proxy -func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) { +func (p *Proxy) URLTest(ctx context.Context, url string) (delay, meanDelay uint16, err error) { defer func() { p.alive.Store(err == nil) record := C.DelayHistory{Time: time.Now()} if err == nil { - record.Delay = t + record.Delay = delay + record.MeanDelay = meanDelay } p.history.Put(record) if p.history.Len() > 10 { @@ -156,7 +157,15 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) { return } resp.Body.Close() - t = uint16(time.Since(start) / time.Millisecond) + delay = uint16(time.Since(start) / time.Millisecond) + + resp, err = client.Do(req) + if err != nil { + return + } + resp.Body.Close() + meanDelay = uint16(time.Since(start) / time.Millisecond / 2) + return } diff --git a/constant/adapters.go b/constant/adapters.go index dd75442..8200e46 100644 --- a/constant/adapters.go +++ b/constant/adapters.go @@ -101,8 +101,9 @@ type ProxyAdapter interface { } type DelayHistory struct { - Time time.Time `json:"time"` - Delay uint16 `json:"delay"` + Time time.Time `json:"time"` + Delay uint16 `json:"delay"` + MeanDelay uint16 `json:"meanDelay"` } type Proxy interface { @@ -110,7 +111,7 @@ type Proxy interface { Alive() bool DelayHistory() []DelayHistory LastDelay() uint16 - URLTest(ctx context.Context, url string) (uint16, error) + URLTest(ctx context.Context, url string) (uint16, uint16, error) // Deprecated: use DialContext instead. Dial(metadata *Metadata) (Conn, error) diff --git a/hub/route/proxies.go b/hub/route/proxies.go index 0cafd8b..6b07d88 100644 --- a/hub/route/proxies.go +++ b/hub/route/proxies.go @@ -109,7 +109,7 @@ func getProxyDelay(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout)) defer cancel() - delay, err := proxy.URLTest(ctx, url) + delay, meanDelay, err := proxy.URLTest(ctx, url) if ctx.Err() != nil { render.Status(r, http.StatusGatewayTimeout) render.JSON(w, r, ErrRequestTimeout) @@ -123,6 +123,7 @@ func getProxyDelay(w http.ResponseWriter, r *http.Request) { } render.JSON(w, r, render.M{ - "delay": delay, + "delay": delay, + "meanDelay": meanDelay, }) }