HandleBoost 同时发起多路拨号,挑选最先成功的连接并套上单边加速。
(conn net.Conn, rule *config.Rule)
| 103 | |
| 104 | // HandleBoost 同时发起多路拨号,挑选最先成功的连接并套上单边加速。 |
| 105 | func HandleBoost(conn net.Conn, rule *config.Rule) { |
| 106 | defer conn.Close() |
| 107 | |
| 108 | decisionBegin := time.Now() |
| 109 | |
| 110 | if addr, ok, exp := loadBoostWinner(rule.Name); ok { |
| 111 | // 命中缓存后,判断是否需要后台懒惰校验。 |
| 112 | var triggerLazy bool |
| 113 | if !exp.IsZero() { |
| 114 | lifeLeft := time.Until(exp) |
| 115 | if lifeLeft < boostRevalidateAfter { |
| 116 | triggerLazy = true |
| 117 | } |
| 118 | } |
| 119 | if cachedConn, err := outboundDial(addr); err == nil { |
| 120 | if tc, ok := cachedConn.(*net.TCPConn); ok { |
| 121 | _ = tc.SetNoDelay(true) |
| 122 | _ = tc.SetKeepAlive(true) |
| 123 | _ = tc.SetKeepAlivePeriod(30 * time.Second) |
| 124 | } |
| 125 | storeBoostWinner(rule.Name, addr) |
| 126 | fields := []zap.Field{ |
| 127 | zap.String("ruleName", rule.Name), |
| 128 | zap.String("remoteAddr", conn.RemoteAddr().String()), |
| 129 | zap.String("targetAddr", cachedConn.RemoteAddr().String()), |
| 130 | zap.Int64("decisionTime(ms)", time.Since(decisionBegin).Milliseconds()), |
| 131 | zap.Bool("boostCacheHit", true), |
| 132 | } |
| 133 | if triggerLazy { |
| 134 | fields = append(fields, zap.Bool("boostLazyRefresh", true)) |
| 135 | } |
| 136 | utils.Logger.Debug("建立连接", fields...) |
| 137 | |
| 138 | if triggerLazy { |
| 139 | go lazyRevalidate(rule) |
| 140 | } |
| 141 | |
| 142 | defer cachedConn.Close() |
| 143 | |
| 144 | go func() { |
| 145 | io.Copy(conn, cachedConn) |
| 146 | conn.Close() |
| 147 | cachedConn.Close() |
| 148 | }() |
| 149 | io.Copy(cachedConn, conn) |
| 150 | return |
| 151 | } |
| 152 | // 缓存线路拨号失败:直接从缓存移除,下次重新竞速 |
| 153 | boostWinnerCache.Delete(rule.Name) |
| 154 | } |
| 155 | |
| 156 | // 并发拨号选择最快线路 |
| 157 | ctx, cancel := context.WithCancel(context.Background()) |
| 158 | defer cancel() |
| 159 | switchBetter := make(chan dialResult, 1) |
| 160 | for _, v := range rule.Targets { |
| 161 | go func(address string) { |
| 162 | if tryGetQuickConn, err := outboundDial(address); err == nil { |
no test coverage detected