Skip to content

Commit

Permalink
feat(share/p2p/shrex): add recovery middleware to shrex-nd and shrex-…
Browse files Browse the repository at this point in the history
…eds servers (#3328)

Add recovery middleware to shrex-eds and shrex-nd server implementation
  • Loading branch information
walldiss authored and Wondertan committed Apr 21, 2024
1 parent 2dbf758 commit c48dd04
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
21 changes: 21 additions & 0 deletions share/p2p/recovery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package p2p

import (
"fmt"

"github.com/libp2p/go-libp2p/core/network"
)

// RecoveryMiddleware is a middleware that recovers from panics in the handler.
func RecoveryMiddleware(handler network.StreamHandler) network.StreamHandler {
return func(stream network.Stream) {
defer func() {
r := recover()
if r != nil {
err := fmt.Errorf("PANIC while handling request: %s", r)
log.Error(err)
}
}()
handler(stream)
}
}
5 changes: 4 additions & 1 deletion share/p2p/shrexeds/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ func NewServer(params *Parameters, host host.Host, store *eds.Store) (*Server, e

func (s *Server) Start(context.Context) error {
s.ctx, s.cancel = context.WithCancel(context.Background())
s.host.SetStreamHandler(s.protocolID, s.middleware.RateLimitHandler(s.handleStream))
handler := s.handleStream
withRateLimit := s.middleware.RateLimitHandler(handler)
withRecovery := p2p.RecoveryMiddleware(withRateLimit)
s.host.SetStreamHandler(s.protocolID, withRecovery)
return nil
}

Expand Down
5 changes: 4 additions & 1 deletion share/p2p/shrexnd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ func NewServer(params *Parameters, host host.Host, store *eds.Store) (*Server, e
ctx, cancel := context.WithCancel(context.Background())
srv.cancel = cancel

srv.handler = srv.middleware.RateLimitHandler(srv.streamHandler(ctx))
handler := srv.streamHandler(ctx)
withRateLimit := srv.middleware.RateLimitHandler(handler)
withRecovery := p2p.RecoveryMiddleware(withRateLimit)
srv.handler = withRecovery
return srv, nil
}

Expand Down

0 comments on commit c48dd04

Please sign in to comment.