github.com/aergoio/aergo@v1.3.1/syncer/stubrequester.go (about)

     1  package syncer
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/pkg/errors"
     7  )
     8  
     9  type StubRequester struct {
    10  	sendCh chan interface{}
    11  	recvCh chan StubRequestResult
    12  }
    13  
    14  type StubRequestResult struct {
    15  	result interface{}
    16  	err    error
    17  }
    18  
    19  var (
    20  	ErrHubFutureTimeOut = errors.New("stub compRequester request future timeout")
    21  )
    22  
    23  func (stubResult *StubRequestResult) Result() (interface{}, error) {
    24  	return stubResult.result, stubResult.err
    25  }
    26  
    27  func NewStubRequester() *StubRequester {
    28  	compRequester := &StubRequester{}
    29  
    30  	compRequester.sendCh = make(chan interface{}, 1000)
    31  	compRequester.recvCh = make(chan StubRequestResult, 1000)
    32  
    33  	return compRequester
    34  }
    35  
    36  // handle requestFuture requset
    37  // this api must not use parallel. TODO use lock
    38  func (compRequester *StubRequester) RequestToFutureResult(targetName string, message interface{}, timeout time.Duration, tip string) (interface{}, error) {
    39  	compRequester.sendCh <- message
    40  
    41  	logger.Debug().Msg("stubcompRequester request future req")
    42  
    43  	var res StubRequestResult
    44  	select {
    45  	case res = <-compRequester.recvCh:
    46  		break
    47  	case <-time.After(timeout):
    48  		return nil, ErrHubFutureTimeOut
    49  	}
    50  
    51  	logger.Debug().Msg("stubcompRequester request future done")
    52  	return res.result, res.err
    53  }
    54  
    55  func (compRequester *StubRequester) RequestTo(targetCompName string, message interface{}) {
    56  	logger.Debug().Msg("stubcompRequester request")
    57  	compRequester.sendCh <- message
    58  }
    59  
    60  func (compRequester *StubRequester) TellTo(targetName string, message interface{}) {
    61  	logger.Debug().Msg("stubcompRequester tell")
    62  	compRequester.sendCh <- message
    63  }
    64  
    65  //act like p2p or chain or syncer
    66  func (compRequester *StubRequester) recvMessage() interface{} {
    67  	select {
    68  	case msg := <-compRequester.sendCh:
    69  		logger.Debug().Msg("compRequester received message")
    70  		return msg
    71  	}
    72  }
    73  
    74  //act like p2p or chain or syncer
    75  func (compRequester *StubRequester) sendReply(reply StubRequestResult) {
    76  	compRequester.recvCh <- reply
    77  }