Skip to content

Commit

Permalink
Merge pull request #2 from Nuklai/patch/reconnect
Browse files Browse the repository at this point in the history
impl socket reconnection and retry for `sendFunds`
  • Loading branch information
Developerayo authored Oct 29, 2024
2 parents 60c4e4f + 21a4a52 commit 3f8c521
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"fmt"
"sync"
"time"
"strings"

"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/logging"
Expand Down Expand Up @@ -110,6 +111,46 @@ func (m *Manager) Run(ctx context.Context) error {
return ctx.Err()
}

func (m *Manager) WebSocketreconnect() error {
if m.scli != nil {
m.log.Info("Closing old WS connection.")
m.scli.Close()
}
scli, err := rpc.NewWebSocketClient(
m.config.NuklaiRPC,
rpc.DefaultHandshakeTimeout,
pubsub.MaxPendingMessages,
pubsub.MaxReadMessageSize,
)
if err != nil {
return err
}
m.scli = scli
m.log.Info("WS connection re-established.")
return nil
}

func (m *Manager) sendFundsRetry(ctx context.Context, destination codec.Address, amount uint64) (ids.ID, uint64, error) {
var lastErr error
for retries := 0; retries < 3; retries++ {
txID, maxFee, err := m.sendFunds(ctx, destination, amount)
if err == nil {
return txID, maxFee, nil
}

if strings.Contains(err.Error(), "closed") {
if reconnErr := m.WebSocketreconnect(); reconnErr != nil {
m.log.Error("Error reconnecting to WS", zap.Error(reconnErr))
continue
}
}

lastErr = err
time.Sleep(time.Second * time.Duration(retries+1))
}
return ids.Empty, 0, fmt.Errorf("failed after retries: %w", lastErr)
}

func (m *Manager) updateDifficulty() {
m.l.Lock()
defer m.l.Unlock()
Expand Down Expand Up @@ -221,7 +262,7 @@ func (m *Manager) SolveChallenge(ctx context.Context, solver codec.Address, salt
return ids.Empty, 0, errors.New("duplicate solution")
}

txID, maxFee, err := m.sendFunds(ctx, solver, m.config.Amount)
txID, maxFee, err := m.sendFundsRetry(ctx, solver, m.config.Amount)
if err != nil {
m.log.Error("Failed to send funds", zap.Error(err))
return ids.Empty, 0, err
Expand Down

0 comments on commit 3f8c521

Please sign in to comment.