Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace multierr dep with stnd lib as much as possible #11818

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
rename errors to pkgerrors for non standlib and replace multierr.Comb…
…ine with errors.Join
  • Loading branch information
poopoothegorilla committed Jan 18, 2024
commit 558613d8558fd7899f06e8fdab814975dee8fd0a
3 changes: 1 addition & 2 deletions common/txmgr/broadcaster.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"github.com/jpillora/backoff"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/multierr"
"gopkg.in/guregu/null.v4"

"github.com/smartcontractkit/chainlink-common/pkg/chains/label"
Expand Down Expand Up @@ -669,7 +668,7 @@ func (eb *Broadcaster[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, SEQ, FEE]) hand
`Urgent resolution required, Chainlink is currently operating in a degraded state and may miss transactions`, "attempt", attempt)
nextSequence, e := eb.client.PendingSequenceAt(ctx, etx.FromAddress)
if e != nil {
err = multierr.Combine(e, err)
err = errors.Join(e, err)
return fmt.Errorf("failed to fetch latest pending sequence after encountering unknown RPC error while sending transaction: %w", err), true
}
if nextSequence.Int64() > (*etx.Sequence).Int64() {
Expand Down
13 changes: 6 additions & 7 deletions common/txmgr/confirmer.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/multierr"

"github.com/smartcontractkit/chainlink-common/pkg/chains/label"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
Expand Down Expand Up @@ -608,13 +607,13 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Reb
// It is safe to process separate keys concurrently
// NOTE: This design will block one key if another takes a really long time to execute
wg.Add(len(ec.enabledAddresses))
errors := []error{}
errs := []error{}
var errMu sync.Mutex
for _, address := range ec.enabledAddresses {
go func(fromAddress ADDR) {
if err := ec.rebroadcastWhereNecessary(ctx, fromAddress, blockHeight); err != nil {
errMu.Lock()
errors = append(errors, err)
errs = append(errs, err)
errMu.Unlock()
ec.lggr.Errorw("Error in RebroadcastWhereNecessary", "err", err, "fromAddress", fromAddress)
}
Expand All @@ -625,7 +624,7 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Reb

wg.Wait()

return multierr.Combine(errors...)
return errors.Join(errs...)
}

func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) rebroadcastWhereNecessary(ctx context.Context, address ADDR, blockHeight int64) error {
Expand Down Expand Up @@ -938,14 +937,14 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Ens
// It is safe to process separate keys concurrently
// NOTE: This design will block one key if another takes a really long time to execute
var wg sync.WaitGroup
errors := []error{}
errs := []error{}
var errMu sync.Mutex
wg.Add(len(ec.enabledAddresses))
for _, address := range ec.enabledAddresses {
go func(fromAddress ADDR) {
if err := ec.handleAnyInProgressAttempts(ctx, fromAddress, head.BlockNumber()); err != nil {
errMu.Lock()
errors = append(errors, err)
errs = append(errs, err)
errMu.Unlock()
ec.lggr.Errorw("Error in handleAnyInProgressAttempts", "err", err, "fromAddress", fromAddress)
}
Expand All @@ -956,7 +955,7 @@ func (ec *Confirmer[CHAIN_ID, HEAD, ADDR, TX_HASH, BLOCK_HASH, R, SEQ, FEE]) Ens

wg.Wait()

return multierr.Combine(errors...)
return errors.Join(errs...)
}

func hasReceiptInLongestChain[
Expand Down
4 changes: 2 additions & 2 deletions core/chains/evm/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils_test

import (
"context"
"errors"
"math/big"
"strings"
"sync/atomic"
Expand All @@ -11,7 +12,6 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/stretchr/testify/assert"
"go.uber.org/multierr"

"github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils"
"github.com/smartcontractkit/chainlink/v2/core/internal/testutils"
Expand Down Expand Up @@ -101,7 +101,7 @@ func TestClient_ParseEthereumAddress(t *testing.T) {
assert.True(t, a1 == a2)
_, lowerErr := parse(strings.ToLower(address))
_, upperErr := parse(strings.ToUpper(address))
shouldBeError := multierr.Combine(lowerErr, upperErr)
shouldBeError := errors.Join(lowerErr, upperErr)
assert.Error(t, shouldBeError)
assert.True(t, strings.Contains(shouldBeError.Error(), no0xPrefix))
}
Expand Down
13 changes: 6 additions & 7 deletions core/chains/legacyevm/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"time"

gotoml "github.com/pelletier/go-toml/v2"
"go.uber.org/multierr"

"github.com/jmoiron/sqlx"

Expand Down Expand Up @@ -345,13 +344,13 @@ func (c *chain) Close() error {
merr = c.balanceMonitor.Close()
}
c.logger.Debug("Chain: stopping logBroadcaster")
merr = multierr.Combine(merr, c.logBroadcaster.Close())
merr = errors.Join(merr, c.logBroadcaster.Close())
c.logger.Debug("Chain: stopping headTracker")
merr = multierr.Combine(merr, c.headTracker.Close())
merr = errors.Join(merr, c.headTracker.Close())
c.logger.Debug("Chain: stopping headBroadcaster")
merr = multierr.Combine(merr, c.headBroadcaster.Close())
merr = errors.Join(merr, c.headBroadcaster.Close())
c.logger.Debug("Chain: stopping evmTxm")
merr = multierr.Combine(merr, c.txm.Close())
merr = errors.Join(merr, c.txm.Close())
c.logger.Debug("Chain: stopping client")
c.client.Close()
c.logger.Debug("Chain: stopped")
Expand All @@ -360,15 +359,15 @@ func (c *chain) Close() error {
}

func (c *chain) Ready() (merr error) {
merr = multierr.Combine(
merr = errors.Join(
c.StateMachine.Ready(),
c.txm.Ready(),
c.headBroadcaster.Ready(),
c.headTracker.Ready(),
c.logBroadcaster.Ready(),
)
if c.balanceMonitor != nil {
merr = multierr.Combine(merr, c.balanceMonitor.Ready())
merr = errors.Join(merr, c.balanceMonitor.Ready())
}
return
}
Expand Down
6 changes: 3 additions & 3 deletions core/cmd/cosmos_transaction_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,22 @@ func (s *Shell) CosmosSendNativeToken(c *cli.Context) (err error) {

amount, err := sdk.NewDecFromStr(c.Args().Get(1))
if err != nil {
return s.errorOut(multierr.Combine(
return s.errorOut(errors.Join(
fmt.Errorf("invalid coin: %w", err)))
}

unparsedFromAddress := c.Args().Get(2)
fromAddress, err := sdk.AccAddressFromBech32(unparsedFromAddress)
if err != nil {
return s.errorOut(multierr.Combine(
return s.errorOut(errors.Join(
fmt.Errorf("while parsing withdrawal source address %v",
unparsedFromAddress), err))
}

unparsedDestinationAddress := c.Args().Get(3)
destinationAddress, err := sdk.AccAddressFromBech32(unparsedDestinationAddress)
if err != nil {
return s.errorOut(multierr.Combine(
return s.errorOut(errors.Join(
fmt.Errorf("while parsing withdrawal destination address %v",
unparsedDestinationAddress), err))
}
Expand Down
8 changes: 4 additions & 4 deletions core/cmd/evm_transaction_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,31 +144,31 @@ func (s *Shell) SendEther(c *cli.Context) (err error) {

value, err = stringutils.ToInt64(c.Args().Get(0))
if err != nil {
return s.errorOut(multierr.Combine(
return s.errorOut(errors.Join(
errors.New("while parsing WEI transfer amount"), err))
}

amount = assets.NewEthValue(value)
} else {
amount, err = assets.NewEthValueS(c.Args().Get(0))
if err != nil {
return s.errorOut(multierr.Combine(
return s.errorOut(errors.Join(
errors.New("while parsing ETH transfer amount"), err))
}
}

unparsedFromAddress := c.Args().Get(1)
fromAddress, err := utils.ParseEthereumAddress(unparsedFromAddress)
if err != nil {
return s.errorOut(multierr.Combine(
return s.errorOut(errors.Join(
fmt.Errorf("while parsing withdrawal source address %v",
unparsedFromAddress), err))
}

unparsedDestinationAddress := c.Args().Get(2)
destinationAddress, err := utils.ParseEthereumAddress(unparsedDestinationAddress)
if err != nil {
return s.errorOut(multierr.Combine(
return s.errorOut(errors.Join(
fmt.Errorf("while parsing withdrawal destination address %v",
unparsedDestinationAddress), err))
}
Expand Down
25 changes: 13 additions & 12 deletions core/cmd/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/tls"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
Expand All @@ -24,7 +25,7 @@ import (
"github.com/Masterminds/semver/v3"
"github.com/getsentry/sentry-go"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
pkgerrors "github.com/pkg/errors"
"github.com/urfave/cli"
"go.uber.org/multierr"
"go.uber.org/zap/zapcore"
Expand Down Expand Up @@ -308,7 +309,7 @@ func takeBackupIfVersionUpgrade(dbUrl url.URL, rootDir string, cfg periodicbacku

databaseBackup, err := periodicbackup.NewDatabaseBackup(dbUrl, rootDir, cfg, lggr)
if err != nil {
return errors.Wrap(err, "takeBackupIfVersionUpgrade failed")
return pkgerrors.Wrap(err, "takeBackupIfVersionUpgrade failed")
}

//Because backups can take a long time we must start a "fake" health report to prevent
Expand Down Expand Up @@ -343,7 +344,7 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err
}

if err := sentryInit(config.Sentry()); err != nil {
return errors.Wrap(err, "failed to initialize sentry")
return pkgerrors.Wrap(err, "failed to initialize sentry")
}

ws := config.WebServer()
Expand All @@ -353,7 +354,7 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err

handler, err := web.NewRouter(app, prometheus)
if err != nil {
return errors.Wrap(err, "failed to create web router")
return pkgerrors.Wrap(err, "failed to create web router")
}
server := server{handler: handler, lggr: app.GetLogger()}

Expand Down Expand Up @@ -381,15 +382,15 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err
<-gCtx.Done()
var err error
if server.httpServer != nil {
err = errors.WithStack(server.httpServer.Shutdown(context.Background()))
err = pkgerrors.WithStack(server.httpServer.Shutdown(context.Background()))
}
if server.tlsServer != nil {
err = multierr.Combine(err, errors.WithStack(server.tlsServer.Shutdown(context.Background())))
err = errors.Join(err, pkgerrors.WithStack(server.tlsServer.Shutdown(context.Background())))
}
return err
})

return errors.WithStack(g.Wait())
return pkgerrors.WithStack(g.Wait())
}

func sentryInit(cfg config.Sentry) error {
Expand Down Expand Up @@ -455,15 +456,15 @@ func (s *server) run(ip net.IP, port uint16, writeTimeout time.Duration) error {
s.lggr.Infow(fmt.Sprintf("Listening and serving HTTP on %s", addr), "ip", ip, "port", port)
s.httpServer = createServer(s.handler, addr, writeTimeout)
err := s.httpServer.ListenAndServe()
return errors.Wrap(err, "failed to run plaintext HTTP server")
return pkgerrors.Wrap(err, "failed to run plaintext HTTP server")
}

func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, requestTimeout time.Duration) error {
addr := fmt.Sprintf("%s:%d", ip.String(), port)
s.lggr.Infow(fmt.Sprintf("Listening and serving HTTPS on %s", addr), "ip", ip, "port", port)
s.tlsServer = createServer(s.handler, addr, requestTimeout)
err := s.tlsServer.ListenAndServeTLS(certFile, keyFile)
return errors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)")
return pkgerrors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)")
}

func createServer(handler *gin.Engine, addr string, requestTimeout time.Duration) *http.Server {
Expand Down Expand Up @@ -812,7 +813,7 @@ func (t *promptingAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lg
// Load list of users to determine which to assume, or if a user needs to be created
dbUsers, err := orm.ListUsers()
if err != nil {
return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization")
return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization")
}

// If there are no users in the database, prompt for initial admin user creation
Expand Down Expand Up @@ -871,14 +872,14 @@ func (f fileAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lggr log
// Load list of users to determine which to assume, or if a user needs to be created
dbUsers, err := orm.ListUsers()
if err != nil {
return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization")
return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization")
}

// If there are no users in the database, create initial admin user from session request from file creds
if len(dbUsers) == 0 {
user, err2 := sessions.NewUser(request.Email, request.Password, sessions.UserRoleAdmin)
if err2 != nil {
return user, errors.Wrap(err2, "failed to instantiate new user")
return user, pkgerrors.Wrap(err2, "failed to instantiate new user")
}
return user, orm.CreateUser(&user)
}
Expand Down
11 changes: 6 additions & 5 deletions core/cmd/solana_transaction_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package cmd
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strconv"

solanaGo "github.com/gagliardetto/solana-go"
"github.com/pkg/errors"
pkgerrors "github.com/pkg/errors"
"github.com/urfave/cli"
"go.uber.org/multierr"

Expand Down Expand Up @@ -72,16 +73,16 @@ func (s *Shell) SolanaSendSol(c *cli.Context) (err error) {
unparsedFromAddress := c.Args().Get(1)
fromAddress, err := solanaGo.PublicKeyFromBase58(unparsedFromAddress)
if err != nil {
return s.errorOut(multierr.Combine(
errors.Errorf("while parsing withdrawal source address %v",
return s.errorOut(errors.Join(
pkgerrors.Errorf("while parsing withdrawal source address %v",
unparsedFromAddress), err))
}

unparsedDestinationAddress := c.Args().Get(2)
destinationAddress, err := solanaGo.PublicKeyFromBase58(unparsedDestinationAddress)
if err != nil {
return s.errorOut(multierr.Combine(
errors.Errorf("while parsing withdrawal destination address %v",
return s.errorOut(errors.Join(
pkgerrors.Errorf("while parsing withdrawal destination address %v",
unparsedDestinationAddress), err))
}

Expand Down
4 changes: 2 additions & 2 deletions core/internal/testutils/pgtest/txdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"flag"
"fmt"
"io"
Expand All @@ -13,7 +14,6 @@ import (
"testing"

"github.com/jmoiron/sqlx"
"go.uber.org/multierr"

"github.com/smartcontractkit/chainlink/v2/core/config/env"
"github.com/smartcontractkit/chainlink/v2/core/store/dialects"
Expand Down Expand Up @@ -351,7 +351,7 @@ func (s stmt) Query(args []driver.Value) (driver.Rows, error) {
}
rows, err := s.st.Query(mapArgs(args)...)
defer func() {
err = multierr.Combine(err, rows.Close())
err = errors.Join(err, rows.Close())
}()
if err != nil {
return nil, err
Expand Down
Loading