github.com/koko1123/flow-go-1@v0.29.6/consensus/hotstuff/notifications/pubsub/qc_created_distributor.go (about)

     1  package pubsub
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/koko1123/flow-go-1/consensus/hotstuff"
     7  	"github.com/koko1123/flow-go-1/model/flow"
     8  )
     9  
    10  type OnQCCreatedConsumer = func(qc *flow.QuorumCertificate)
    11  
    12  // QCCreatedDistributor subscribes for qc created event from hotstuff and distributes it to subscribers
    13  // Objects are concurrency safe.
    14  // NOTE: it can be refactored to work without lock since usually we never subscribe after startup. Mostly
    15  // list of observers is static.
    16  type QCCreatedDistributor struct {
    17  	qcCreatedConsumers []OnQCCreatedConsumer
    18  	lock               sync.RWMutex
    19  }
    20  
    21  var _ hotstuff.QCCreatedConsumer = (*QCCreatedDistributor)(nil)
    22  
    23  func NewQCCreatedDistributor() *QCCreatedDistributor {
    24  	return &QCCreatedDistributor{
    25  		qcCreatedConsumers: make([]OnQCCreatedConsumer, 0),
    26  	}
    27  }
    28  
    29  func (d *QCCreatedDistributor) AddConsumer(consumer OnQCCreatedConsumer) {
    30  	d.lock.Lock()
    31  	defer d.lock.Unlock()
    32  	d.qcCreatedConsumers = append(d.qcCreatedConsumers, consumer)
    33  }
    34  
    35  func (d *QCCreatedDistributor) OnQcConstructedFromVotes(qc *flow.QuorumCertificate) {
    36  	d.lock.RLock()
    37  	defer d.lock.RUnlock()
    38  	for _, consumer := range d.qcCreatedConsumers {
    39  		consumer(qc)
    40  	}
    41  }