Skip to content

Commit

Permalink
address comments
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisSchinnerl committed Jan 23, 2025
1 parent 8048907 commit a0fb68f
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions syncer/syncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,11 +374,11 @@ func (s *Syncer) allowConnect(ctx context.Context, peer string, inbound bool) er
s.mu.Lock()
defer s.mu.Unlock()

select {
case <-s.tg.Done():
return threadgroup.ErrClosed
default:
done, err := s.tg.Add()
if err != nil {
return err
}
defer done()

var addrs []net.IPAddr
if peerHost, _, err := net.SplitHostPort(peer); err != nil {
Expand Down Expand Up @@ -424,19 +424,29 @@ func (s *Syncer) alreadyConnected(id gateway.UniqueID) bool {
}

func (s *Syncer) acceptLoop(ctx context.Context) error {
ctx, done, err := s.tg.AddContext(ctx)
if err != nil {
return threadgroup.ErrClosed
}
defer done()

for {
ctx, done, err := s.tg.AddContext(ctx)
if err != nil {
select {
case <-ctx.Done():
return threadgroup.ErrClosed
default:
}

conn, err := s.l.Accept()
if err != nil {
done()
return err
}

go func() {
done, err := s.tg.Add()
if err != nil {
return
}
defer done()
defer conn.Close()
if err := s.allowConnect(ctx, conn.RemoteAddr().String(), true); err != nil {
Expand Down Expand Up @@ -663,21 +673,23 @@ func (s *Syncer) Run() error {
if err != nil {
return err
}
defer cancel()

errChan := make(chan error)
for _, fn := range []func(context.Context) error{s.acceptLoop, s.peerLoop, s.syncLoop} {
go func() {
done, err := s.tg.Add()
if err != nil {
errChan <- fn(ctx)
return
}
if err := fn(ctx); err != nil {
s.log.With(zap.Error(err)).Error("background loop exited with error")
}
errChan <- fn(ctx)
done()
}()
}
err = <-errChan
cancel()

// when one goroutine exits, shutdown and wait for the others
s.l.Close()
Expand Down

0 comments on commit a0fb68f

Please sign in to comment.