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

HandlerWithKey:recover panic in callback #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
22 changes: 20 additions & 2 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"io/ioutil"
"net/http"
"runtime/debug"
"strings"
"time"
)
Expand Down Expand Up @@ -76,10 +77,22 @@ func HandlerWithKey(cacheSize int, ttl time.Duration, keyFunc ...func(r *http.Re
}

// mark the request that actually processes the response
first := false
var (
err error
panicErr error
first bool
val interface{}
)

// process request (single flight)
val, err := cache.GetFresh(r.Context(), key, func(ctx context.Context) (interface{}, error) {
val, err = cache.GetFresh(r.Context(), key, func(ctx context.Context) (interface{}, error) {
defer func() {
// need a panic recoverer as separate recoverer middleware can't catch panics in new goroutine
if r := recover(); r != nil {
panicErr = fmt.Errorf("recovered panicking request:%#v, stack:%s", r, string(debug.Stack()))
}
}()

first = true
buf := bytes.NewBuffer(nil)
ww := &responseWriter{ResponseWriter: w, tee: buf}
Expand All @@ -94,6 +107,11 @@ func HandlerWithKey(cacheSize int, ttl time.Duration, keyFunc ...func(r *http.Re
return val, nil
})

// handle panic for first or other listeners
if panicErr != nil {
panic(fmt.Sprintf("stampede: encountered unexpected panic, %v", panicErr))
}

// the first request to trigger the fetch should return as it's already
// responded to the client
if first {
Expand Down