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

Functions: tracking subscriptions #10613

Merged
merged 19 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
7 changes: 7 additions & 0 deletions core/scripts/functions/templates/oracle.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ maxSecretsSizesList = [10_240, 20_480, 51_200, 102_400, 307_200, 512_000, 1_048_
updateFrequencySec = 30
updateTimeoutSec = 10

[pluginConfig.OnchainSubscriptions]
blockConfirmations = 1
routerAddress = "{{router_contract_address}}"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have multiple places in the jobspec where there are duplicate definitions of the router contract address. How hard would it be to exclusively use the router address specified under contractID everywhere?
(This is out of scope for this PR, but may be a good backlog ticket as it may add misconfiguration risk)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, this would be a good improvement.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a ticket to tech debt epic please!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FUN-921

queryFrequencySec = 30
queryTimeoutSec = 10
queryRangeSize = 100

[pluginConfig.RateLimiter]
globalBurst = 5
globalRPS = 10
Expand Down
38 changes: 22 additions & 16 deletions core/services/functions/connector_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,33 @@ import (
type functionsConnectorHandler struct {
utils.StartStopOnce

connector connector.GatewayConnector
signerKey *ecdsa.PrivateKey
nodeAddress string
storage s4.Storage
allowlist functions.OnchainAllowlist
rateLimiter *hc.RateLimiter
lggr logger.Logger
connector connector.GatewayConnector
signerKey *ecdsa.PrivateKey
nodeAddress string
storage s4.Storage
allowlist functions.OnchainAllowlist
subscriptions functions.OnchainSubscriptions
rateLimiter *hc.RateLimiter
lggr logger.Logger
}

var (
_ connector.Signer = &functionsConnectorHandler{}
_ connector.GatewayConnectorHandler = &functionsConnectorHandler{}
)

func NewFunctionsConnectorHandler(nodeAddress string, signerKey *ecdsa.PrivateKey, storage s4.Storage, allowlist functions.OnchainAllowlist, rateLimiter *hc.RateLimiter, lggr logger.Logger) (*functionsConnectorHandler, error) {
if signerKey == nil || storage == nil || allowlist == nil || rateLimiter == nil {
return nil, fmt.Errorf("signerKey, storage, allowlist and rateLimiter must be non-nil")
func NewFunctionsConnectorHandler(nodeAddress string, signerKey *ecdsa.PrivateKey, storage s4.Storage, allowlist functions.OnchainAllowlist, rateLimiter *hc.RateLimiter, subscriptions functions.OnchainSubscriptions, lggr logger.Logger) (*functionsConnectorHandler, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Planning to also add to the Gateway handler?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think it needs to be enabled in GW handler too?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's a must. But it should be very easy to add there as optional and the more bad requests we can stop in Gateway, the less unnecessary load we put on the nodes.

if signerKey == nil || storage == nil || allowlist == nil || rateLimiter == nil || subscriptions == nil {
return nil, fmt.Errorf("signerKey, storage, allowlist, rateLimiter and subscriptions must be non-nil")
}
return &functionsConnectorHandler{
nodeAddress: nodeAddress,
signerKey: signerKey,
storage: storage,
allowlist: allowlist,
rateLimiter: rateLimiter,
lggr: lggr.Named("FunctionsConnectorHandler"),
nodeAddress: nodeAddress,
signerKey: signerKey,
storage: storage,
allowlist: allowlist,
rateLimiter: rateLimiter,
subscriptions: subscriptions,
lggr: lggr.Named("FunctionsConnectorHandler"),
}, nil
}

Expand All @@ -68,6 +70,10 @@ func (h *functionsConnectorHandler) HandleGatewayMessage(ctx context.Context, ga
h.lggr.Errorw("request rate-limited", "id", gatewayId, "address", fromAddr)
return
}
if h.subscriptions.GetSubscription(fromAddr) == nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to check against sub balance. So we need required balance in the config and probably a more specific API than GetSubscription().

h.lggr.Errorw("request is not backed with a valid subscription", "id", gatewayId, "address", fromAddr)
return
bolekk marked this conversation as resolved.
Show resolved Hide resolved
}

h.lggr.Debugw("handling gateway request", "id", gatewayId, "method", body.Method)

Expand Down
10 changes: 9 additions & 1 deletion core/services/functions/connector_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"testing"

"github.com/smartcontractkit/chainlink/v2/core/gethwrappers/functions/generated/functions_router"
"github.com/smartcontractkit/chainlink/v2/core/internal/testutils"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/functions"
Expand All @@ -31,10 +32,11 @@ func TestFunctionsConnectorHandler(t *testing.T) {
connector := gcmocks.NewGatewayConnector(t)
allowlist := gfmocks.NewOnchainAllowlist(t)
rateLimiter, err := hc.NewRateLimiter(hc.RateLimiterConfig{GlobalRPS: 100.0, GlobalBurst: 100, PerSenderRPS: 100.0, PerSenderBurst: 100})
subscriptions := gfmocks.NewOnchainSubscriptions(t)
require.NoError(t, err)
allowlist.On("Start", mock.Anything).Return(nil)
allowlist.On("Close", mock.Anything).Return(nil)
handler, err := functions.NewFunctionsConnectorHandler(addr.Hex(), privateKey, storage, allowlist, rateLimiter, logger)
handler, err := functions.NewFunctionsConnectorHandler(addr.Hex(), privateKey, storage, allowlist, rateLimiter, subscriptions, logger)
require.NoError(t, err)

handler.SetConnector(connector)
Expand Down Expand Up @@ -73,6 +75,9 @@ func TestFunctionsConnectorHandler(t *testing.T) {
}
storage.On("List", ctx, addr).Return(snapshot, nil).Once()
allowlist.On("Allow", addr).Return(true).Once()
subscriptions.On("GetSubscription", mock.Anything).Return(
&functions_router.IFunctionsSubscriptionsSubscription{},
)
connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) {
msg, ok := args[2].(*api.Message)
require.True(t, ok)
Expand Down Expand Up @@ -129,6 +134,9 @@ func TestFunctionsConnectorHandler(t *testing.T) {

storage.On("Put", ctx, &key, &record, signature).Return(nil).Once()
allowlist.On("Allow", addr).Return(true).Once()
subscriptions.On("GetSubscription", mock.Anything).Return(
&functions_router.IFunctionsSubscriptionsSubscription{},
)
connector.On("SendToGateway", ctx, "gw1", mock.Anything).Run(func(args mock.Arguments) {
msg, ok := args[2].(*api.Message)
require.True(t, ok)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

200 changes: 200 additions & 0 deletions core/services/gateway/handlers/functions/subscriptions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
package functions

import (
"context"
"fmt"
"math/big"
"sync"
"time"

"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/pkg/errors"

evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client"
"github.com/smartcontractkit/chainlink/v2/core/gethwrappers/functions/generated/functions_router"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/job"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)

type OnchainSubscriptionsConfig struct {
RouterAddress common.Address `json:"routerAddress"`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Allowlist has "ContractAddress" but "Router" is slightly better. So up to you if you prefer consistency or a slightly more specific name.

BlockConfirmations uint `json:"blockConfirmations"`
QueryFrequencySec uint `json:"queryFrequencySec"`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To follow allowlist config fields, I'd suggest "UpdateFrequencySec", "UpdateTimeoutSec" and "UpdateRangeSec".

QueryTimeoutSec uint `json:"queryTimeoutSec"`
QueryRangeSize uint `json:"queryRangeSize"`
}
bolekk marked this conversation as resolved.
Show resolved Hide resolved

// OnchainSubscriptions maintains a mirror of all subscriptions fetched from the blockchain (EVM-only).
// All methods are thread-safe.
//
//go:generate mockery --quiet --name OnchainSubscriptions --output ./mocks/ --case=underscore
type OnchainSubscriptions interface {
job.ServiceCtx

// GetSubscription returns a subscription for the given user address, or null if not found
GetSubscription(common.Address) *functions_router.IFunctionsSubscriptionsSubscription
}

type onchainSubscriptions struct {
utils.StartStopOnce

config OnchainSubscriptionsConfig
subscriptions map[common.Address]*functions_router.IFunctionsSubscriptionsSubscription
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One user could have many subscriptions. Therefore, how are we planning to approach this if we are only mapping each user's address to 1 subscription? Are we only going to keep the subscription with the maximum balance for each user?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, İ need to improve this

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should store all of them.

client evmclient.Client
router *functions_router.FunctionsRouter
blockConfirmations *big.Int
lggr logger.Logger
closeWait sync.WaitGroup
rwMutex sync.RWMutex
stopCh utils.StopChan
}

func NewOnchainSubscriptions(client evmclient.Client, config OnchainSubscriptionsConfig, lggr logger.Logger) (OnchainSubscriptions, error) {
if client == nil {
return nil, errors.New("client is nil")
}
if lggr == nil {
return nil, errors.New("logger is nil")
}
router, err := functions_router.NewFunctionsRouter(config.RouterAddress, client)
if err != nil {
return nil, fmt.Errorf("unexpected error during functions_router.NewFunctionsRouter: %s", err)
}
return &onchainSubscriptions{
config: config,
subscriptions: make(map[common.Address]*functions_router.IFunctionsSubscriptionsSubscription),
client: client,
router: router,
blockConfirmations: big.NewInt(int64(config.BlockConfirmations)),
lggr: lggr.Named("OnchainSubscriptions"),
stopCh: make(utils.StopChan),
}, nil
}

func (s *onchainSubscriptions) Start(ctx context.Context) error {
return s.StartOnce("OnchainSubscriptions", func() error {
s.lggr.Info("starting onchain subscriptions")
if s.config.QueryFrequencySec == 0 {
return errors.New("OnchainSubscriptionsConfig.UpdateFrequencySec must be greater than 0")
}
if s.config.QueryTimeoutSec == 0 {
return errors.New("OnchainSubscriptionsConfig.UpdateTimeoutSec must be greater than 0")
}
if s.config.QueryRangeSize == 0 {
return errors.New("OnchainSubscriptionsConfig.QueryRangeSize must be greater than 0")
}

s.closeWait.Add(1)
go s.queryLoop()

return nil
})
}

func (s *onchainSubscriptions) Close() error {
return s.StopOnce("OnchainSubscriptions", func() (err error) {
s.lggr.Info("closing onchain subscriptions")
close(s.stopCh)
s.closeWait.Wait()
return nil
})
}

func (s *onchainSubscriptions) GetSubscription(address common.Address) *functions_router.IFunctionsSubscriptionsSubscription {
s.rwMutex.RLock()
defer s.rwMutex.RUnlock()
subscription, ok := s.subscriptions[address]
if !ok {
return nil
}
return subscription
}

func (s *onchainSubscriptions) queryLoop() {
defer s.closeWait.Done()

ticker := time.NewTicker(time.Duration(s.config.QueryFrequencySec) * time.Second)
defer ticker.Stop()

var start uint64 = 1

queryFunc := func() {
ctx, cancel := utils.ContextFromChanWithTimeout(s.stopCh, time.Duration(s.config.QueryTimeoutSec)*time.Second)
defer cancel()

latestBlockHeight, err := s.client.LatestBlockHeight(ctx)
if err != nil || latestBlockHeight == nil {
s.lggr.Errorw("Error calling LatestBlockHeight", "err", err, "latestBlockHeight", latestBlockHeight.Int64())
return
}

blockNumber := big.NewInt(0).Sub(latestBlockHeight, s.blockConfirmations)

count, err := s.getSubscriptionsCount(ctx, blockNumber)
if err != nil {
s.lggr.Errorw("Error getting subscriptions count", "err", err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could cache this and use previous value if fetching fails.

return
}
if count == 0 {
s.lggr.Info("Router has no subscriptions yet")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will log errors when that happens right?

return
}

if start > count {
start = 1
}

end := start + uint64(s.config.QueryRangeSize)
if end > count {
end = count
}
if err := s.querySubscriptionsRange(ctx, blockNumber, start, end); err != nil {
s.lggr.Errorw("Error querying subscriptions", "err", err, "start", start, "end", end)
return
}

start = end + 1
}

for {
bolekk marked this conversation as resolved.
Show resolved Hide resolved
select {
case <-s.stopCh:
return
case <-ticker.C:
queryFunc()
}
}
}

func (s *onchainSubscriptions) querySubscriptionsRange(ctx context.Context, blockNumber *big.Int, start, end uint64) error {
subscriptions, err := s.router.GetSubscriptionsInRange(&bind.CallOpts{
Pending: false,
BlockNumber: blockNumber,
Context: ctx,
}, start, end)
if err != nil {
return errors.Wrap(err, "unexpected error during functions_router.GetSubscriptionsInRange")
}

s.rwMutex.Lock()
defer s.rwMutex.Unlock()
for _, subscription := range subscriptions {
if subscription.Owner == utils.ZeroAddress {
continue
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When would this case happen? Should we log an error here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If subscription is cancelled I guess. I need to test it better though

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is for cancelled subs. But we shouldn't continue, we need to still store it as cancelled. Otherwise we'll keep using previous values.

}
subscription := subscription
KuphJr marked this conversation as resolved.
Show resolved Hide resolved
s.subscriptions[subscription.Owner] = &subscription
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should check the balance and only save the subscription with the highest balance here? Although maybe we should also re-work this as we are currently holding the rwMutext here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's save all but have an API to retrieve highest balance. In the future we are also going to look at flags stored within subscriptions.

}

bolekk marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

func (s *onchainSubscriptions) getSubscriptionsCount(ctx context.Context, blockNumber *big.Int) (uint64, error) {
return s.router.GetSubscriptionCount(&bind.CallOpts{
Pending: false,
BlockNumber: blockNumber,
Context: ctx,
})
}
Loading
Loading