Skip to content

Commit

Permalink
Re-register proxy on local address change event from libp2p host
Browse files Browse the repository at this point in the history
- Subscribe to local address update events from libp2p host
- On address change, shut down the existing mDNS server and re-register with updated address
  • Loading branch information
MOHANKUMAR-IT committed Dec 9, 2024
1 parent b3209ef commit 767a2c4
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions p2p/discovery/mdns/mdns.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package mdns
import (
"context"
"errors"
"github.com/libp2p/go-libp2p/core/event"
"io"
"math/rand"
"strings"
"sync"
"time"

"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
Expand Down Expand Up @@ -69,6 +71,40 @@ func (s *mdnsService) Start() error {
return err
}
s.startResolver(s.ctx)

ipEvt, err := s.host.EventBus().Subscribe(&event.EvtLocalAddressesUpdated{})
if err != nil {
if err = s.Close(); err != nil {
log.Errorf("failed to close mdns service: %s", err)
}
return err
}
go func() {
defer ipEvt.Close()
var addrUpdateDebounce sync.Once
for {
select {
case <-s.ctx.Done():
return
case evt := <-ipEvt.Out():
if _, ok := evt.(event.EvtLocalAddressesUpdated); ok {
addrUpdateDebounce.Do(func() {
time.AfterFunc(2*time.Second, func() {
addrUpdateDebounce = sync.Once{}
if s.server != nil {
s.server.Shutdown()
s.server = nil
}
if err = s.startServer(); err != nil {
log.Errorf("failed to restart mdns server: %s", err)
}
})
})
}
}
}
}()

return nil
}

Expand Down Expand Up @@ -143,6 +179,7 @@ func (s *mdnsService) startServer() error {
txts,
nil,
)

if err != nil {
return err
}
Expand Down

0 comments on commit 767a2c4

Please sign in to comment.