github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/cluster/consensus.go (about)

     1  // Copyright (C) 2015-2022 Asynkron AB All rights reserved
     2  
     3  package cluster
     4  
     5  import (
     6  	"context"
     7  	"sync"
     8  
     9  	"github.com/google/uuid"
    10  )
    11  
    12  // this data structure is used to host consensus check results, the
    13  // contents are protected from data races as it embeds RWMutex.
    14  type consensusResult struct {
    15  	sync.Mutex
    16  
    17  	consensus bool
    18  	value     interface{}
    19  }
    20  
    21  type ConsensusHandler interface {
    22  	GetID() string
    23  	TryGetConsensus(context.Context) (interface{}, bool)
    24  }
    25  
    26  type gossipConsensusHandler struct {
    27  	ID     string
    28  	result *consensusResult
    29  }
    30  
    31  func NewGossipConsensusHandler() *gossipConsensusHandler {
    32  	handler := gossipConsensusHandler{
    33  		ID: uuid.New().String(),
    34  		result: &consensusResult{
    35  			consensus: false,
    36  			value:     nil,
    37  		},
    38  	}
    39  
    40  	return &handler
    41  }
    42  
    43  func (hdl *gossipConsensusHandler) GetID() string { return hdl.ID }
    44  
    45  func (hdl *gossipConsensusHandler) TryGetConsensus(context.Context) (interface{}, bool) {
    46  	// wait until our result is available
    47  	hdl.result.Lock()
    48  	defer hdl.result.Unlock()
    49  
    50  	return hdl.result.value, hdl.result.consensus
    51  }
    52  
    53  func (hdl *gossipConsensusHandler) TrySetConsensus(consensus interface{}) {
    54  	hdl.result.Lock()
    55  	go func() {
    56  		defer hdl.result.Unlock()
    57  
    58  		hdl.result.value = consensus
    59  		hdl.result.consensus = true
    60  	}()
    61  }
    62  
    63  func (hdl *gossipConsensusHandler) TryResetConsensus() {
    64  	// this is a noop for now need to discuss the right
    65  	// approach for check waiting in Go as might be another
    66  	// way of expressing this
    67  }