Skip to content

Commit

Permalink
fix: closed race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
franklinkim committed Oct 3, 2023
1 parent d30495d commit 17c41a7
Showing 1 changed file with 41 additions and 28 deletions.
69 changes: 41 additions & 28 deletions serviceenabler.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ type ServiceEnabler struct {
syncEnabled bool
syncEnabledLock sync.RWMutex
enabledFn func() bool
closed bool
syncClosed bool
syncClosedLock sync.RWMutex
}

func NewServiceEnabler(l *zap.Logger, name string, serviceFn ServiceFunc, enabledFn func() bool) *ServiceEnabler {
Expand All @@ -38,6 +39,44 @@ func (w *ServiceEnabler) Name() string {
return w.name
}

func (w *ServiceEnabler) Start(ctx context.Context) error {
w.watch()
w.ctx = ctx
if w.enabled() {
if err := w.enable(w.ctx); err != nil {
return err
}
} else {
w.l.Info("skipping disabled dynamic service")
}
return nil
}

func (w *ServiceEnabler) Close(ctx context.Context) error {
l := log.WithServiceName(w.l, w.Name())
w.setClosed(true)
if w.enabled() {
if err := w.disable(w.ctx); err != nil {
return err
}
} else {
l.Info("skipping disabled dynamic service")
}
return nil
}

func (w *ServiceEnabler) closed() bool {
w.syncClosedLock.RLock()
defer w.syncClosedLock.RUnlock()
return w.syncClosed
}

func (w *ServiceEnabler) setClosed(v bool) {
w.syncClosedLock.Lock()
defer w.syncClosedLock.Unlock()
w.syncClosed = v
}

func (w *ServiceEnabler) enabled() bool {
w.syncEnabledLock.RLock()
defer w.syncEnabledLock.RUnlock()
Expand Down Expand Up @@ -66,7 +105,7 @@ func (w *ServiceEnabler) disable(ctx context.Context) error {
func (w *ServiceEnabler) watch() {
go func() {
for {
if w.closed {
if w.closed() {
break
}
time.Sleep(time.Second)
Expand All @@ -86,29 +125,3 @@ func (w *ServiceEnabler) watch() {
}
}()
}

func (w *ServiceEnabler) Start(ctx context.Context) error {
w.watch()
w.ctx = ctx
if w.enabled() {
if err := w.enable(w.ctx); err != nil {
return err
}
} else {
w.l.Info("skipping disabled dynamic service")
}
return nil
}

func (w *ServiceEnabler) Close(ctx context.Context) error {
l := log.WithServiceName(w.l, w.Name())
w.closed = true
if w.enabled() {
if err := w.disable(w.ctx); err != nil {
return err
}
} else {
l.Info("skipping disabled dynamic service")
}
return nil
}

0 comments on commit 17c41a7

Please sign in to comment.