github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/utils/shutdowner.go (about) 1 package utils 2 3 import ( 4 "context" 5 6 "github.com/hashicorp/go-multierror" 7 ) 8 9 // NopShutdown implements the Shutdowner interface but does not execute any 10 // process on shutdown. 11 var NopShutdown = NewGroupShutdown() 12 13 // Shutdowner is an interface with a Shutdown method to gracefully shutdown 14 // a running process. 15 type Shutdowner interface { 16 Shutdown(ctx context.Context) error 17 } 18 19 // GroupShutdown allow to group multiple Shutdowner into a single one. 20 type GroupShutdown struct { 21 s []Shutdowner 22 } 23 24 // NewGroupShutdown returns a new GroupShutdown 25 func NewGroupShutdown(s ...Shutdowner) *GroupShutdown { 26 return &GroupShutdown{s} 27 } 28 29 // Shutdown closes all the encapsulated [Shutdowner] in parallel an returns 30 // the concatenated errors. 31 func (g *GroupShutdown) Shutdown(ctx context.Context) error { 32 errs := new(multierror.Group) 33 34 for _, s := range g.s { 35 // Shadow the variable to avoid a datarace 36 s := s 37 38 errs.Go(func() error { return s.Shutdown(ctx) }) 39 } 40 41 return errs.Wait().ErrorOrNil() 42 }