You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.2 KiB

  1. package txindex
  2. import (
  3. "context"
  4. "github.com/tendermint/tendermint/types"
  5. cmn "github.com/tendermint/tmlibs/common"
  6. )
  7. const (
  8. subscriber = "IndexerService"
  9. )
  10. type IndexerService struct {
  11. cmn.BaseService
  12. idr TxIndexer
  13. eventBus *types.EventBus
  14. }
  15. func NewIndexerService(idr TxIndexer, eventBus *types.EventBus) *IndexerService {
  16. is := &IndexerService{idr: idr, eventBus: eventBus}
  17. is.BaseService = *cmn.NewBaseService(nil, "IndexerService", is)
  18. return is
  19. }
  20. // OnStart implements cmn.Service by subscribing for all transactions
  21. // and indexing them by tags.
  22. func (is *IndexerService) OnStart() error {
  23. ch := make(chan interface{})
  24. if err := is.eventBus.Subscribe(context.Background(), subscriber, types.EventQueryTx, ch); err != nil {
  25. return err
  26. }
  27. go func() {
  28. for event := range ch {
  29. // TODO: may be not perfomant to write one event at a time
  30. txResult := event.(types.TMEventData).Unwrap().(types.EventDataTx).TxResult
  31. is.idr.Index(&txResult)
  32. }
  33. }()
  34. return nil
  35. }
  36. // OnStop implements cmn.Service by unsubscribing from all transactions.
  37. func (is *IndexerService) OnStop() {
  38. if is.eventBus.IsRunning() {
  39. _ = is.eventBus.UnsubscribeAll(context.Background(), subscriber)
  40. }
  41. }