-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
Changes from 4 commits
a334b43
1af8420
d55b93e
9d352a7
cdd2a47
4530867
8206cf1
0ab8ee1
1c2477a
793c2c1
77d953c
c5ae2e5
fa7eb52
19aadcc
c54e357
a344936
13984f9
a235b39
ebed8ee
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Planning to also add to the Gateway handler? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do you think it needs to be enabled in GW handler too? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
} | ||
|
||
|
@@ -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 { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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"` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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"` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point, İ need to improve this There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The current contract implementation reverts if there are zero subscriptions. https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/functions/dev/1_0_0/FunctionsSubscriptions.sol#L269 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When would this case happen? Should we log an error here? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
}) | ||
} |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FUN-921