Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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 reporter/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

please address lint check

"github.com/ethereum/go-ethereum/common"
"github.com/spf13/viper"
rpchttp "github.com/cometbft/cometbft/rpc/client/http"
globalfeetypes "github.com/strangelove-ventures/globalfee/x/globalfee/types"
customquery "github.com/tellor-io/layer-daemons/custom_query"
daemonflags "github.com/tellor-io/layer-daemons/flags"
Expand Down Expand Up @@ -185,6 +186,8 @@
grpcMu sync.RWMutex
grpcConn *grpc.ClientConn
grpcClient daemontypes.GrpcClient

rpcClient *rpchttp.HTTP // direct reference for WebSocket subscriptions

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Adding this import in a new branch pr-31-review

grpcManager *grpcEndpointManager
rpcMu sync.RWMutex
rpcManager *rpcEndpointManager
Expand Down Expand Up @@ -387,6 +390,10 @@
if err != nil {
return fmt.Errorf("failed to create RPC client: %w", err)
}

c.rpcClient = rpcClient

Check failure on line 394 in reporter/client/client.go

View workflow job for this annotation

GitHub Actions / golangci-lint

cannot use rpcClient (variable of type "github.com/cosmos/cosmos-sdk/client".CometRPC) as *"github.com/cometbft/cometbft/rpc/client/http".HTTP value in assignment: need type assertion (typecheck)

Check failure on line 394 in reporter/client/client.go

View workflow job for this annotation

GitHub Actions / golangci-lint

cannot use rpcClient (variable of type "github.com/cosmos/cosmos-sdk/client".CometRPC) as *"github.com/cometbft/cometbft/rpc/client/http".HTTP value in assignment: need type assertion) (typecheck)

Check failure on line 394 in reporter/client/client.go

View workflow job for this annotation

GitHub Actions / build

cannot use rpcClient (variable of type "github.com/cosmos/cosmos-sdk/client".CometRPC) as *"github.com/cometbft/cometbft/rpc/client/http".HTTP value in assignment: need type assertion
c.cosmosCtx = c.cosmosCtx.WithClient(rpcClient)

c.logger.Info("CometBFT RPC client established", "endpoint", rpcEndpoint)
c.rpcManager = rpcManager
c.setRPCClient(rpcClient)
Expand Down
126 changes: 126 additions & 0 deletions reporter/client/reporter_monitors.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,132 @@ func validatorOperatorAddress(reporterAddr string) (string, string, error) {

func (c *Client) MonitorCyclelistQuery(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()

// Try to use event-driven detection (reacts within milliseconds of each new block).
// Falls back to 200ms ticker polling if the WebSocket subscription fails.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

added fallback behavior to next listed rpc in .env in this branch https://github.com/tellor-io/layer-daemons/tree/pr-31-review

blockCh, unsubscribe, err := c.subscribeNewBlocks(ctx)
if err != nil {
c.logger.Warn("block subscription failed, falling back to polling", "error", err)
c.monitorCyclelistQueryPolling(ctx)
return
}
defer unsubscribe()
c.logger.Info("MonitorCyclelistQuery: using event-driven block subscription")

// Fallback ticker: if no block event is received for 2s (e.g. slow node), poll anyway.
const blockEventTimeout = 2 * time.Second
fallback := time.NewTimer(blockEventTimeout)
defer fallback.Stop()

prevQueryData := []byte{}

checkCycle := func() {
queryCtx, cancel := context.WithTimeout(ctx, defaultQueryTimeout)
querydata, querymeta, err := c.CurrentQuery(queryCtx)
cancel()

if err != nil || querymeta == nil {
c.logger.Error("query failed", "error", err)
return
}

mutex.Lock()
hasCommited := commitedIds[querymeta.Id]
mutex.Unlock()
if bytes.Equal(querydata, prevQueryData) || hasCommited {
return
}

txCtx, cancel := context.WithTimeout(ctx, defaultTxTimeout)
done := make(chan struct{})

c.logger.Info(fmt.Sprintf("starting to generate spot price report at %d", time.Now().Unix()))
go func() {
defer close(done)
if err := c.GenerateAndBroadcastSpotPriceReport(txCtx, querydata, querymeta); err != nil {
c.logger.Error("report generation failed", "error", err)
}
}()

select {
case <-done:
cancel()
case <-txCtx.Done():
c.logger.Error(fmt.Sprintf("report generation timed out at %d", time.Now().Unix()))
cancel()
}

prevQueryData = querydata
}

for {
select {
case <-ctx.Done():
return
case _, ok := <-blockCh:
if !ok {
// Channel closed; fall back to polling for the rest of this session.
c.logger.Warn("block subscription channel closed, falling back to polling")
c.monitorCyclelistQueryPolling(ctx)
return
}
fallback.Reset(blockEventTimeout)
checkCycle()
case <-fallback.C:
// No block event received within timeout; check anyway and reset.
fallback.Reset(blockEventTimeout)
checkCycle()
}
}
}

// subscribeNewBlocks subscribes to CometBFT NewBlock events over WebSocket.
// Returns a channel that receives one value per block, an unsubscribe func, and any error.
func (c *Client) subscribeNewBlocks(ctx context.Context) (<-chan struct{}, func(), error) {
if c.rpcClient == nil {
return nil, func() {}, fmt.Errorf("rpc client not initialized")
}
if !c.rpcClient.IsRunning() {
if err := c.rpcClient.Start(); err != nil {
return nil, func() {}, fmt.Errorf("starting rpc client for WebSocket: %w", err)
}
}
subscriber := fmt.Sprintf("reporter-cycle-monitor-%d", time.Now().UnixNano())
eventCh, err := c.rpcClient.Subscribe(ctx, subscriber, "tm.event='NewBlock'")
if err != nil {
return nil, func() {}, fmt.Errorf("subscribing to NewBlock events: %w", err)
}

blockCh := make(chan struct{}, 1)
go func() {
defer close(blockCh)
for {
select {
case <-ctx.Done():
return
case _, ok := <-eventCh:
if !ok {
return
}
// Non-blocking send: if the consumer is busy processing the previous block,
// skip this event rather than queuing up a backlog.
select {
case blockCh <- struct{}{}:
default:
}
}
}
}()

unsubscribe := func() {
_ = c.rpcClient.Unsubscribe(ctx, subscriber, "tm.event='NewBlock'")
}
return blockCh, unsubscribe, nil
}

// monitorCyclelistQueryPolling is the fallback ticker-based implementation used when
// the WebSocket block subscription is unavailable.
func (c *Client) monitorCyclelistQueryPolling(ctx context.Context) {
prevQueryData := []byte{}
retryDelay := defaultRetryDelay
ticker := time.NewTicker(defaultRetryDelay)
Expand Down
Loading