github.com/koko1123/flow-go-1@v0.29.6/network/relay/relayer.go (about)

     1  package relay
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"golang.org/x/sync/errgroup"
     7  
     8  	"github.com/koko1123/flow-go-1/model/flow"
     9  	"github.com/koko1123/flow-go-1/network"
    10  	"github.com/koko1123/flow-go-1/network/channels"
    11  )
    12  
    13  type Relayer struct {
    14  	destinationConduit network.Conduit
    15  	messageProcessor   network.MessageProcessor
    16  }
    17  
    18  // TODO: currently, any messages received from the destination network on the relay channel will be
    19  // ignored. If a usecase arises, we should implement a mechanism to forward these messages to a handler.
    20  type noopProcessor struct{}
    21  
    22  func (n *noopProcessor) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error {
    23  	return nil
    24  }
    25  
    26  var _ network.MessageProcessor = (*Relayer)(nil)
    27  
    28  func NewRelayer(destinationNetwork network.Network, channel channels.Channel, processor network.MessageProcessor) (*Relayer, error) {
    29  	conduit, err := destinationNetwork.Register(channel, &noopProcessor{})
    30  
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	return &Relayer{
    36  		messageProcessor:   processor,
    37  		destinationConduit: conduit,
    38  	}, nil
    39  
    40  }
    41  
    42  func (r *Relayer) Process(channel channels.Channel, originID flow.Identifier, event interface{}) error {
    43  	g := new(errgroup.Group)
    44  
    45  	g.Go(func() error {
    46  		if err := r.messageProcessor.Process(channel, originID, event); err != nil {
    47  			return fmt.Errorf("failed to relay message to message processor: %w", err)
    48  		}
    49  
    50  		return nil
    51  	})
    52  
    53  	g.Go(func() error {
    54  		if err := r.destinationConduit.Publish(event, flow.ZeroID); err != nil {
    55  			return fmt.Errorf("failed to relay message to network: %w", err)
    56  		}
    57  
    58  		return nil
    59  	})
    60  
    61  	return g.Wait()
    62  }
    63  
    64  func (r *Relayer) Close() error {
    65  	return r.destinationConduit.Close()
    66  }