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:
cache-proxy:
image: 100.64.0.2/guochao/cache-proxy:20250206
image: 100.64.0.2/guochao/cache-proxy:20250207
build: .
pull_policy: always

View File

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