Skip to content

Commit

Permalink
feat: keep boot host alive
Browse files Browse the repository at this point in the history
  • Loading branch information
nick-bisonai committed Jul 15, 2024
1 parent 04ecbbf commit 6446098
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 17 deletions.
24 changes: 9 additions & 15 deletions node/pkg/boot/boot.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
libp2pSetup "bisonai.com/orakl/node/pkg/libp2p/setup"
libp2pUtils "bisonai.com/orakl/node/pkg/libp2p/utils"
"github.com/gofiber/fiber/v2"
"github.com/libp2p/go-libp2p/core/host"
"github.com/rs/zerolog/log"
)

Expand All @@ -39,12 +40,18 @@ func Run(ctx context.Context) error {
port = "8089"
}

h, err := libp2pSetup.NewHost(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to make host")
return err
}

refreshTicker := time.NewTicker(REFRESH_INTERVAL)
go func() {
for {
select {
case <-refreshTicker.C:
err = RefreshJob(ctx)
err = RefreshJob(ctx, h)
if err != nil {
log.Error().Err(err).Msg("Failed to refresh peers")
}
Expand All @@ -71,7 +78,7 @@ func Run(ctx context.Context) error {

}

func RefreshJob(ctx context.Context) error {
func RefreshJob(ctx context.Context, h host.Host) error {
log.Info().Msg("Refreshing peers")
peers, err := db.QueryRows[peer.PeerModel](ctx, peer.GetPeer, nil)
if err != nil {
Expand All @@ -83,14 +90,7 @@ func RefreshJob(ctx context.Context) error {
return nil
}

h, err := libp2pSetup.NewHost(ctx, libp2pSetup.WithHolePunch(), libp2pSetup.WithPort(0))
if err != nil {
log.Error().Err(err).Msg("Failed to make host")
return err
}

for _, p := range peers {

isAlive, liveCheckErr := libp2pUtils.IsHostAlive(ctx, h, p.Url)
if liveCheckErr != nil {
log.Error().Err(liveCheckErr).Msg("Failed to check peer")
Expand All @@ -109,11 +109,5 @@ func RefreshJob(ctx context.Context) error {
}
}

err = h.Close()
if err != nil {
log.Error().Err(err).Msg("Failed to close host")
return err
}

return nil
}
10 changes: 8 additions & 2 deletions node/pkg/boot/tests/peer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,13 @@ func TestRefresh(t *testing.T) {

assert.Equal(t, res.Url, url, "expected to have the same url")

err = boot.RefreshJob(ctx)
bootHost, err := libp2pSetup.NewHost(ctx)
if err != nil {
t.Fatalf("error making host: %v", err)
}
defer bootHost.Close()

err = boot.RefreshJob(ctx, bootHost)
if err != nil {
t.Fatalf("error refreshing peers: %v", err)
}
Expand All @@ -117,7 +123,7 @@ func TestRefresh(t *testing.T) {

h.Close()

err = boot.RefreshJob(ctx)
err = boot.RefreshJob(ctx, bootHost)
if err != nil {
t.Fatalf("error refreshing peers: %v", err)
}
Expand Down

0 comments on commit 6446098

Please sign in to comment.