Files
upstream-centrifugo/internal/service/service.go
upstream-mirror b352a9a30d
Some checks failed
test / Lint (push) Failing after 3s
test / Test with Go 1.26.8 (push) Failing after 2s
snapshot of https://github.com/centrifugal/centrifugo.git (master, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:17:21 +05:00

59 lines
1.1 KiB
Go

package service
import (
"context"
"sync"
"golang.org/x/sync/errgroup"
)
type Service interface {
Run(ctx context.Context) error
}
// Manager manages a collection of services.
type Manager struct {
services []Service
mu sync.Mutex // Protects access to the services slice
wg *errgroup.Group
}
func NewManager() *Manager {
return &Manager{services: make([]Service, 0)}
}
// Register adds a new service to the ServiceManager.
func (sm *Manager) Register(s ...Service) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.services = append(sm.services, s...)
}
// Run runs all registered services concurrently using an errgroup.
func (sm *Manager) Run(ctx context.Context) {
sm.mu.Lock()
defer sm.mu.Unlock()
if len(sm.services) == 0 {
return
}
group, ctx := errgroup.WithContext(ctx)
for _, s := range sm.services {
s := s // Capture the service in the loop.
group.Go(func() error {
return s.Run(ctx)
})
}
sm.wg = group
}
func (sm *Manager) Wait() error {
sm.mu.Lock()
defer sm.mu.Unlock()
if len(sm.services) == 0 {
return nil
}
return sm.wg.Wait()
}