diff --git a/commonspace/syncstatus/syncstatus.go b/commonspace/syncstatus/syncstatus.go index 4eabfb31..48299c0d 100644 --- a/commonspace/syncstatus/syncstatus.go +++ b/commonspace/syncstatus/syncstatus.go @@ -111,6 +111,11 @@ func (s *syncStatusService) Init(a *app.App) (err error) { s.spaceId = sharedState.SpaceId s.configuration = a.MustComponent(nodeconf.CName).(nodeconf.NodeConf) s.storage = a.MustComponent(spacestorage.CName).(spacestorage.SpaceStorage) + s.periodicSync = periodicsync.NewPeriodicSync( + s.updateIntervalSecs, + s.updateTimeout, + s.update, + log) return } @@ -126,11 +131,6 @@ func (s *syncStatusService) SetUpdateReceiver(updater UpdateReceiver) { } func (s *syncStatusService) Run(ctx context.Context) error { - s.periodicSync = periodicsync.NewPeriodicSync( - s.updateIntervalSecs, - s.updateTimeout, - s.update, - log) s.periodicSync.Run() return nil } @@ -290,9 +290,6 @@ func (s *syncStatusService) RemoveAllExcept(senderId string, differentRemoteIds } func (s *syncStatusService) Close(ctx context.Context) error { - if s.periodicSync == nil { - return nil - } s.periodicSync.Close() return nil } diff --git a/util/periodicsync/periodicsync.go b/util/periodicsync/periodicsync.go index b1969f63..aab8b050 100644 --- a/util/periodicsync/periodicsync.go +++ b/util/periodicsync/periodicsync.go @@ -5,6 +5,7 @@ import ( "context" "github.com/anyproto/any-sync/app/logger" "go.uber.org/zap" + "sync/atomic" "time" ) @@ -39,9 +40,11 @@ type periodicCall struct { loopDone chan struct{} periodSeconds int timeout time.Duration + isRunning atomic.Bool } func (p *periodicCall) Run() { + p.isRunning.Store(true) go p.loop(p.periodSeconds) } @@ -75,6 +78,9 @@ func (p *periodicCall) loop(periodSeconds int) { } func (p *periodicCall) Close() { + if !p.isRunning.Load() { + return + } p.loopCancel() <-p.loopDone } diff --git a/util/periodicsync/periodicsync_test.go b/util/periodicsync/periodicsync_test.go index f45a940b..240e64ac 100644 --- a/util/periodicsync/periodicsync_test.go +++ b/util/periodicsync/periodicsync_test.go @@ -45,4 +45,13 @@ func TestPeriodicSync_Run(t *testing.T) { pSync.Close() require.Equal(t, 2, times) }) + + t.Run("loop close not running", func(t *testing.T) { + secs := 0 + diffSyncer := func(ctx context.Context) (err error) { + return nil + } + pSync := NewPeriodicSync(secs, 0, diffSyncer, l) + pSync.Close() + }) }