tendermint/state/txindex/indexer_service.go

74 lines
1.9 KiB
Go
Raw Normal View History

package txindex
import (
"context"
cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tendermint/types"
)
const (
subscriber = "IndexerService"
)
2018-05-11 01:09:41 -07:00
// IndexerService connects event bus and transaction indexer together in order
// to index transactions coming from event bus.
type IndexerService struct {
cmn.BaseService
idr TxIndexer
eventBus *types.EventBus
}
2018-05-11 01:09:41 -07:00
// NewIndexerService returns a new service instance.
func NewIndexerService(idr TxIndexer, eventBus *types.EventBus) *IndexerService {
is := &IndexerService{idr: idr, eventBus: eventBus}
is.BaseService = *cmn.NewBaseService(nil, "IndexerService", is)
return is
}
// OnStart implements cmn.Service by subscribing for all transactions
// and indexing them by tags.
func (is *IndexerService) OnStart() error {
2018-05-11 01:09:41 -07:00
blockHeadersCh := make(chan interface{})
if err := is.eventBus.Subscribe(context.Background(), subscriber, types.EventQueryNewBlockHeader, blockHeadersCh); err != nil {
return err
}
2018-05-11 01:09:41 -07:00
txsCh := make(chan interface{})
if err := is.eventBus.Subscribe(context.Background(), subscriber, types.EventQueryTx, txsCh); err != nil {
return err
}
go func() {
2018-05-11 01:09:41 -07:00
for {
2018-05-14 00:10:59 -07:00
e, ok := <-blockHeadersCh
if !ok {
return
}
header := e.(types.EventDataNewBlockHeader).Header
batch := NewBatch(header.NumTxs)
for i := int64(0); i < header.NumTxs; i++ {
e, ok := <-txsCh
2018-05-11 09:26:24 -07:00
if !ok {
2018-05-14 00:10:59 -07:00
is.Logger.Error("Failed to index all transactions due to closed transactions channel", "height", header.Height, "numTxs", header.NumTxs, "numProcessed", i)
2018-05-11 09:26:24 -07:00
return
}
2018-05-11 01:09:41 -07:00
txResult := e.(types.EventDataTx).TxResult
batch.Add(&txResult)
}
2018-05-14 00:10:59 -07:00
is.idr.AddBatch(batch)
is.Logger.Info("Indexed block", "height", header.Height)
}
}()
return nil
}
2017-11-29 09:22:52 -08:00
// OnStop implements cmn.Service by unsubscribing from all transactions.
func (is *IndexerService) OnStop() {
if is.eventBus.IsRunning() {
_ = is.eventBus.UnsubscribeAll(context.Background(), subscriber)
}
}