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

     1  package zk
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  
     7  	"github.com/asynkron/protoactor-go/cluster"
     8  )
     9  
    10  const (
    11  	metaKeyID  = "id"
    12  	metaKeySeq = "seq"
    13  )
    14  
    15  type Node struct {
    16  	ID      string            `json:"id"`
    17  	Name    string            `json:"name"`
    18  	Host    string            `json:"host"`
    19  	Address string            `json:"address"`
    20  	Port    int               `json:"port"`
    21  	Kinds   []string          `json:"kinds"`
    22  	Meta    map[string]string `json:"-"`
    23  	Alive   bool              `json:"alive"`
    24  }
    25  
    26  func NewNode(name, host string, port int, kinds []string) *Node {
    27  	return &Node{
    28  		ID:      name,
    29  		Name:    name,
    30  		Address: host,
    31  		Host:    host,
    32  		Port:    port,
    33  		Kinds:   kinds,
    34  		Meta:    map[string]string{},
    35  		Alive:   true,
    36  	}
    37  }
    38  
    39  func (n *Node) GetAddress() (host string, port int) {
    40  	host = n.Host
    41  	port = n.Port
    42  	if host == "" {
    43  		host = n.Address
    44  	}
    45  	return
    46  }
    47  
    48  func (n *Node) GetAddressString() string {
    49  	h, p := n.GetAddress()
    50  	return fmt.Sprintf("%v:%v", h, p)
    51  }
    52  
    53  func (n *Node) Equal(other *Node) bool {
    54  	if n == nil || other == nil {
    55  		return false
    56  	}
    57  	if n == other {
    58  		return true
    59  	}
    60  	return n.ID == other.ID
    61  }
    62  
    63  func (n *Node) GetMeta(name string) (string, bool) {
    64  	if n.Meta == nil {
    65  		return "", false
    66  	}
    67  	val, ok := n.Meta[name]
    68  	return val, ok
    69  }
    70  
    71  func (n *Node) GetSeq() int {
    72  	if seqStr, ok := n.GetMeta(metaKeySeq); ok {
    73  		return strToInt(seqStr)
    74  	}
    75  	return 0
    76  }
    77  
    78  func (n *Node) MemberStatus() *cluster.Member {
    79  	host, port := n.GetAddress()
    80  	kinds := n.Kinds
    81  	if kinds == nil {
    82  		kinds = []string{}
    83  	}
    84  	return &cluster.Member{
    85  		Id:    n.ID,
    86  		Host:  host,
    87  		Port:  int32(port),
    88  		Kinds: kinds,
    89  	}
    90  }
    91  
    92  func (n *Node) SetMeta(name string, val string) {
    93  	if n.Meta == nil {
    94  		n.Meta = map[string]string{}
    95  	}
    96  	n.Meta[name] = val
    97  }
    98  
    99  func (n *Node) Serialize() ([]byte, error) {
   100  	data, err := json.Marshal(n)
   101  	if err != nil {
   102  		return nil, err
   103  	}
   104  	return data, nil
   105  }
   106  
   107  func (n *Node) Deserialize(data []byte) error {
   108  	return json.Unmarshal(data, n)
   109  }