fix context cancel problem

This commit is contained in:
guochao 2025-02-06 09:50:03 +08:00
parent 5f1d48391a
commit f3d5eb9fbd
2 changed files with 13 additions and 11 deletions

View File

@ -1,6 +1,6 @@
services: services:
cache-proxy: cache-proxy:
image: 100.64.0.2/guochao/cache-proxy:20250206 image: 100.64.0.2/guochao/cache-proxy:20250207
build: . build: .
pull_policy: always pull_policy: always

View File

@ -420,14 +420,25 @@ func (server *Server) fastesUpstream(r *http.Request, lastModified time.Time) (r
updateOnce := &sync.Once{} updateOnce := &sync.Once{}
notModifiedCh := make(chan int, 1) notModifiedCh := make(chan int, 1)
notModifiedOnce := &sync.Once{} notModifiedOnce := &sync.Once{}
resultIdx = -1
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
wg.Add(len(server.Upstreams)) wg.Add(len(server.Upstreams))
defer close(updateCh) defer close(updateCh)
defer close(notModifiedCh)
defer func() {
for cancelIdx, cancel := range cancelFuncs {
if cancelIdx == resultIdx || cancel == nil {
continue
}
cancel()
}
}()
for idx := range server.Upstreams { for idx := range server.Upstreams {
idx := idx idx := idx
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cancelFuncs[idx] = cancel cancelFuncs[idx] = cancel
logger := slog.With("upstreamIdx", idx) logger := slog.With("upstreamIdx", idx)
@ -470,13 +481,6 @@ func (server *Server) fastesUpstream(r *http.Request, lastModified time.Time) (r
updateOnce.Do(func() { updateOnce.Do(func() {
resultResponse, resultCh, resultErr = response, ch, err resultResponse, resultCh, resultErr = response, ch, err
updateCh <- idx updateCh <- idx
for cancelIdx, cancel := range cancelFuncs {
if cancelIdx == idx {
continue
}
cancel()
}
}) })
logger.Debug("voted update") logger.Debug("voted update")
@ -485,8 +489,6 @@ func (server *Server) fastesUpstream(r *http.Request, lastModified time.Time) (r
wg.Wait() wg.Wait()
resultIdx = -1
select { select {
case idx := <-updateCh: case idx := <-updateCh:
resultIdx = idx resultIdx = idx