mirror of
https://github.com/matrix-org/dendrite.git
synced 2026-01-06 13:43:09 -06:00
Ensure every HTTP server context has a timeout.
Code that uses http.NewRequestWithContext will see the same deadline.
This commit is contained in:
parent
a53c9300aa
commit
1d6501ae30
|
|
@ -92,6 +92,7 @@ type BaseDendrite struct {
|
||||||
const NoListener = ""
|
const NoListener = ""
|
||||||
|
|
||||||
const HTTPServerTimeout = time.Minute * 5
|
const HTTPServerTimeout = time.Minute * 5
|
||||||
|
const HTTPServerRequestTimeout = HTTPServerTimeout
|
||||||
const HTTPClientTimeout = time.Second * 30
|
const HTTPClientTimeout = time.Second * 30
|
||||||
|
|
||||||
type BaseDendriteOptions int
|
type BaseDendriteOptions int
|
||||||
|
|
@ -384,6 +385,7 @@ func (b *BaseDendrite) SetupAndServeHTTP(
|
||||||
externalAddr, _ := externalHTTPAddr.Address()
|
externalAddr, _ := externalHTTPAddr.Address()
|
||||||
|
|
||||||
externalRouter := mux.NewRouter().SkipClean(true).UseEncodedPath()
|
externalRouter := mux.NewRouter().SkipClean(true).UseEncodedPath()
|
||||||
|
externalRouter.Use(timeoutMiddleware)
|
||||||
internalRouter := externalRouter
|
internalRouter := externalRouter
|
||||||
|
|
||||||
externalServ := &http.Server{
|
externalServ := &http.Server{
|
||||||
|
|
@ -521,6 +523,15 @@ func (b *BaseDendrite) SetupAndServeHTTP(
|
||||||
logrus.Infof("Stopped HTTP listeners")
|
logrus.Infof("Stopped HTTP listeners")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// timeoutMiddleware is a Gorilla middleware that adds a timeout to all request contexts.
|
||||||
|
func timeoutMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), HTTPServerRequestTimeout)
|
||||||
|
defer cancel()
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (b *BaseDendrite) WaitForShutdown() {
|
func (b *BaseDendrite) WaitForShutdown() {
|
||||||
sigs := make(chan os.Signal, 1)
|
sigs := make(chan os.Signal, 1)
|
||||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue