Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Resolve race condition in HTTP server handling #21

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions xhttp/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ package xhttp

import (
"context"
"errors"
"log"
"net"
"net/http"
"sync"
"sync/atomic"
"time"

"oss.terrastruct.com/util-go/xcontext"
Expand All @@ -22,15 +25,52 @@ func NewServer(log *log.Logger, h http.Handler) *http.Server {
}
}

type safeServer struct {
*http.Server
running int32
mu sync.Mutex
}

func newSafeServer(s *http.Server) *safeServer {
return &safeServer{
Server: s,
}
}

func (s *safeServer) ListenAndServe(l net.Listener) error {
s.mu.Lock()
defer s.mu.Unlock()

if !atomic.CompareAndSwapInt32(&s.running, 0, 1) {
return errors.New("server is already running")
}
defer atomic.StoreInt32(&s.running, 0)

return s.Serve(l)
}

func (s *safeServer) Shutdown(ctx context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()

if atomic.LoadInt32(&s.running) == 0 {
return nil
}

return s.Server.Shutdown(ctx)
}

func Serve(ctx context.Context, shutdownTimeout time.Duration, s *http.Server, l net.Listener) error {
s.BaseContext = func(net.Listener) context.Context {
return ctx
}

ss := newSafeServer(s)

serverClosed := make(chan struct{})
var serverError error
go func() {
serverError = s.Serve(l)
serverError = ss.ListenAndServe(l)
close(serverClosed)
}()

Expand All @@ -40,8 +80,7 @@ func Serve(ctx context.Context, shutdownTimeout time.Duration, s *http.Server, l
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(xcontext.WithoutCancel(ctx), shutdownTimeout)
defer cancel()

err := s.Shutdown(shutdownCtx)
err := ss.Shutdown(shutdownCtx)
<-serverClosed // Wait for server to exit
if err != nil {
return err
Expand Down
Loading