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

feat: (payments) make wise threadsafe and use go-mock to allow unit tests #116

Merged
merged 13 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion internal/connectors/plugins/public/wise/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type accountsState struct {
LastAccountID uint64 `json:"lastAccountID"`
}

func (p Plugin) fetchNextAccounts(ctx context.Context, req models.FetchNextAccountsRequest) (models.FetchNextAccountsResponse, error) {
func (p *Plugin) fetchNextAccounts(ctx context.Context, req models.FetchNextAccountsRequest) (models.FetchNextAccountsResponse, error) {
var oldState accountsState
if req.State != nil {
if err := json.Unmarshal(req.State, &oldState); err != nil {
Expand Down
68 changes: 68 additions & 0 deletions internal/connectors/plugins/public/wise/accounts_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package wise

import (
"encoding/json"
"fmt"

"github.com/formancehq/payments/internal/connectors/plugins/public/wise/client"
"github.com/formancehq/payments/internal/models"
"go.uber.org/mock/gomock"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

var _ = Describe("Wise Plugin Accounts", func() {
var (
plg *Plugin
m *client.MockClient
)

BeforeEach(func() {
plg = &Plugin{}

ctrl := gomock.NewController(GinkgoT())
m = client.NewMockClient(ctrl)
plg.SetClient(m)
})

Context("fetch next accounts", func() {
var (
balances []client.Balance
expectedProfileID uint64
)

BeforeEach(func() {
expectedProfileID = 123454
balances = []client.Balance{
{ID: 14556, Type: "type1"},
{ID: 3334, Type: "type2"},
}
})

It("fetches accounts from wise", func(ctx SpecContext) {
req := models.FetchNextAccountsRequest{
State: json.RawMessage(`{}`),
FromPayload: json.RawMessage(fmt.Sprintf(`{"ID":%d}`, expectedProfileID)),
PageSize: len(balances),
}
m.EXPECT().GetBalances(ctx, expectedProfileID).Return(
balances,
nil,
)

res, err := plg.FetchNextAccounts(ctx, req)
Expect(err).To(BeNil())
Expect(res.HasMore).To(BeTrue())
Expect(res.Accounts).To(HaveLen(req.PageSize))
Expect(res.Accounts[0].Reference).To(Equal(fmt.Sprint(balances[0].ID)))
Expect(res.Accounts[1].Reference).To(Equal(fmt.Sprint(balances[1].ID)))

var state accountsState

err = json.Unmarshal(res.NewState, &state)
Expect(err).To(BeNil())
Expect(fmt.Sprint(state.LastAccountID)).To(Equal(res.Accounts[len(res.Accounts)-1].Reference))
})
})
})
2 changes: 1 addition & 1 deletion internal/connectors/plugins/public/wise/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/formancehq/payments/internal/models"
)

func (p Plugin) fetchNextBalances(ctx context.Context, req models.FetchNextBalancesRequest) (models.FetchNextBalancesResponse, error) {
func (p *Plugin) fetchNextBalances(ctx context.Context, req models.FetchNextBalancesRequest) (models.FetchNextBalancesResponse, error) {
var from models.PSPAccount
if req.FromPayload == nil {
return models.FetchNextBalancesResponse{}, models.ErrMissingFromPayloadInRequest
Expand Down
73 changes: 73 additions & 0 deletions internal/connectors/plugins/public/wise/balances_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package wise

import (
"encoding/json"
"fmt"
"math/big"

"github.com/formancehq/payments/internal/connectors/plugins/public/wise/client"
"github.com/formancehq/payments/internal/models"
"go.uber.org/mock/gomock"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

var _ = Describe("Wise Plugin Balances", func() {
var (
plg *Plugin
m *client.MockClient
)

BeforeEach(func() {
plg = &Plugin{}

ctrl := gomock.NewController(GinkgoT())
m = client.NewMockClient(ctrl)
plg.SetClient(m)
})

Context("fetch next balances", func() {
var (
balance client.Balance
expectedProfileID uint64
profileVal uint64
)

BeforeEach(func() {
expectedProfileID = 123454
profileVal = 999999
balance = client.Balance{
ID: 14556,
Type: "type1",
Amount: client.BalanceAmount{Value: json.Number("44.99"), Currency: "USD"},
}
})

It("fetches balances from wise client", func(ctx SpecContext) {
req := models.FetchNextBalancesRequest{
State: json.RawMessage(`{}`),
FromPayload: json.RawMessage(fmt.Sprintf(
`{"Reference":"%d","Metadata":{"%s":"%d"}}`,
expectedProfileID,
metadataProfileIDKey,
profileVal,
)),
PageSize: 10,
}
m.EXPECT().GetBalance(ctx, profileVal, expectedProfileID).Return(
&balance,
nil,
)

res, err := plg.FetchNextBalances(ctx, req)
Expect(err).To(BeNil())
Expect(res.HasMore).To(BeFalse())
Expect(res.Balances).To(HaveLen(1)) // always returns 1
Expect(res.Balances[0].AccountReference).To(Equal(fmt.Sprint(expectedProfileID)))
expectedBalance, err := balance.Amount.Value.Float64()
Expect(err).To(BeNil())
Expect(res.Balances[0].Amount).To(BeEquivalentTo(big.NewInt(int64(expectedBalance * 100))))
})
})
})
22 changes: 12 additions & 10 deletions internal/connectors/plugins/public/wise/client/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ import (
"time"
)

type BalanceAmount struct {
Value json.Number `json:"value"`
Currency string `json:"currency"`
}

type Balance struct {
ID uint64 `json:"id"`
Currency string `json:"currency"`
Type string `json:"type"`
Name string `json:"name"`
Amount struct {
Value json.Number `json:"value"`
Currency string `json:"currency"`
} `json:"amount"`
ID uint64 `json:"id"`
Currency string `json:"currency"`
Type string `json:"type"`
Name string `json:"name"`
Amount BalanceAmount `json:"amount"`
ReservedAmount struct {
Value json.Number `json:"value"`
Currency string `json:"currency"`
Expand All @@ -34,7 +36,7 @@ type Balance struct {
Visible bool `json:"visible"`
}

func (c *Client) GetBalances(ctx context.Context, profileID uint64) ([]Balance, error) {
func (c *client) GetBalances(ctx context.Context, profileID uint64) ([]Balance, error) {
// TODO(polo): metrics
// f := connectors.ClientMetrics(ctx, "wise", "list_balances")
// now := time.Now()
Expand All @@ -55,7 +57,7 @@ func (c *Client) GetBalances(ctx context.Context, profileID uint64) ([]Balance,
return balances, nil
}

func (c *Client) GetBalance(ctx context.Context, profileID uint64, balanceID uint64) (*Balance, error) {
func (c *client) GetBalance(ctx context.Context, profileID uint64, balanceID uint64) (*Balance, error) {
// TODO(polo): metrics
// f := connectors.ClientMetrics(ctx, "wise", "list_balances")
// now := time.Now()
Expand Down
33 changes: 29 additions & 4 deletions internal/connectors/plugins/public/wise/client/client.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package client

import (
"context"
"encoding/json"
"fmt"
"net/http"
"sync"

"github.com/formancehq/payments/internal/connectors/httpwrapper"
lru "github.com/hashicorp/golang-lru/v2"
Expand All @@ -22,17 +25,38 @@ func (t *apiTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return t.underlying.RoundTrip(req)
}

type Client struct {
//go:generate mockgen -source client.go -destination client_generated.go -package client . Client
type Client interface {
GetBalance(ctx context.Context, profileID uint64, balanceID uint64) (*Balance, error)
GetBalances(ctx context.Context, profileID uint64) ([]Balance, error)
GetPayout(ctx context.Context, payoutID string) (*Payout, error)
CreatePayout(ctx context.Context, quote Quote, targetAccount uint64, transactionID string) (*Payout, error)
GetProfiles(ctx context.Context) ([]Profile, error)
CreateQuote(ctx context.Context, profileID, currency string, amount json.Number) (Quote, error)
GetRecipientAccounts(ctx context.Context, profileID uint64, pageSize int, seekPositionForNext uint64) (*RecipientAccountsResponse, error)
GetRecipientAccount(ctx context.Context, accountID uint64) (*RecipientAccount, error)
GetTransfers(ctx context.Context, profileID uint64, offset int, limit int) ([]Transfer, error)
GetTransfer(ctx context.Context, transferID string) (*Transfer, error)
CreateTransfer(ctx context.Context, quote Quote, targetAccount uint64, transactionID string) (*Transfer, error)
CreateWebhook(ctx context.Context, profileID uint64, name, triggerOn, url, version string) (*WebhookSubscriptionResponse, error)
ListWebhooksSubscription(ctx context.Context, profileID uint64) ([]WebhookSubscriptionResponse, error)
DeleteWebhooks(ctx context.Context, profileID uint64, subscriptionID string) error
TranslateTransferStateChangedWebhook(ctx context.Context, payload []byte) (Transfer, error)
TranslateBalanceUpdateWebhook(ctx context.Context, payload []byte) (BalanceUpdateWebhookPayload, error)
}

type client struct {
httpClient httpwrapper.Client

mux *sync.Mutex
recipientAccountsCache *lru.Cache[uint64, *RecipientAccount]
}

func (w *Client) endpoint(path string) string {
func (c *client) endpoint(path string) string {
return fmt.Sprintf("%s/%s", apiEndpoint, path)
}

func New(apiKey string) (*Client, error) {
func New(apiKey string) (Client, error) {
recipientsCache, _ := lru.New[uint64, *RecipientAccount](2048)
config := &httpwrapper.Config{
Transport: &apiTransport{
Expand All @@ -42,8 +66,9 @@ func New(apiKey string) (*Client, error) {
}

httpClient, err := httpwrapper.NewClient(config)
return &Client{
return &client{
httpClient: httpClient,
mux: &sync.Mutex{},
recipientAccountsCache: recipientsCache,
}, err
}
Loading