Replace sync.WaitGroup with errgroup

This commit is contained in:
Mariano Cano
2025-07-16 10:50:08 -07:00
parent a5fd0d0cfc
commit 503f67dc61
2 changed files with 18 additions and 29 deletions

View File

@@ -13,11 +13,11 @@ import (
"net/url"
"reflect"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"golang.org/x/sync/errgroup"
"github.com/smallstep/cli-utils/step"
"github.com/smallstep/nosql"
@@ -447,45 +447,36 @@ func (ca *CA) Run() error {
}
}
var (
wg sync.WaitGroup
err error
)
wg.Add(1)
go func() {
defer wg.Done()
eg := new(errgroup.Group)
eg.Go(func() error {
ca.runCompactJob()
}()
return nil
})
if ca.insecureSrv != nil {
wg.Add(1)
go func() {
defer wg.Done()
err = errors.Join(err, ca.insecureSrv.ListenAndServe())
}()
eg.Go(func() error {
return ca.insecureSrv.ListenAndServe()
})
}
if ca.metricsSrv != nil {
wg.Add(1)
go func() {
defer wg.Done()
err = errors.Join(err, ca.metricsSrv.ListenAndServe())
}()
eg.Go(func() error {
return ca.metricsSrv.ListenAndServe()
})
}
wg.Add(1)
go func() {
defer wg.Done()
err = errors.Join(err, ca.srv.ListenAndServe())
}()
eg.Go(func() error {
return ca.srv.ListenAndServe()
})
err := eg.Wait()
// if the error is not the usual HTTP server closed error, it is
// highly likely that an error occurred when starting one of the
// CA servers, possibly because of a port already being in use or
// some part of the configuration not being correct. This case is
// handled by stopping the CA in its entirety.
if err != nil && !errors.Is(err, http.ErrServerClosed) {
if !errors.Is(err, http.ErrServerClosed) {
log.Println("shutting down due to startup error ...")
if stopErr := ca.Stop(); stopErr != nil {
err = fmt.Errorf("failed stopping CA after error occurred: %w: %w", err, stopErr)
@@ -494,8 +485,6 @@ func (ca *CA) Run() error {
}
}
wg.Wait()
return err
}

2
go.mod
View File

@@ -41,6 +41,7 @@ require (
golang.org/x/crypto v0.39.0
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0
golang.org/x/net v0.41.0
golang.org/x/sync v0.15.0
google.golang.org/api v0.240.0
google.golang.org/grpc v1.73.0
google.golang.org/protobuf v1.36.6
@@ -160,7 +161,6 @@ require (
go.opentelemetry.io/otel/trace v1.36.0 // indirect
golang.org/x/mod v0.25.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.15.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
golang.org/x/time v0.12.0 // indirect