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

     1  package cluster
     2  
     3  import (
     4  	"github.com/asynkron/protoactor-go/actor"
     5  	cmap "github.com/orcaman/concurrent-map"
     6  )
     7  
     8  type PidCacheValue struct {
     9  	cache cmap.ConcurrentMap
    10  }
    11  
    12  func NewPidCache() *PidCacheValue {
    13  	pidCache := &PidCacheValue{
    14  		cache: cmap.New(),
    15  	}
    16  
    17  	return pidCache
    18  }
    19  
    20  func key(identity string, kind string) string {
    21  	return identity + "." + kind
    22  }
    23  
    24  func (c *PidCacheValue) Get(identity string, kind string) (*actor.PID, bool) {
    25  	k := key(identity, kind)
    26  	v, ok := c.cache.Get(k)
    27  
    28  	if !ok {
    29  		return nil, false
    30  	}
    31  
    32  	return v.(*actor.PID), true
    33  }
    34  
    35  func (c *PidCacheValue) Set(identity string, kind string, pid *actor.PID) {
    36  	k := key(identity, kind)
    37  	c.cache.Set(k, pid)
    38  }
    39  
    40  func (c *PidCacheValue) RemoveByValue(identity string, kind string, pid *actor.PID) {
    41  	k := key(identity, kind)
    42  
    43  	c.cache.RemoveCb(k, func(key string, v interface{}, exists bool) bool {
    44  		if !exists {
    45  			return false
    46  		}
    47  
    48  		existing, _ := v.(*actor.PID)
    49  
    50  		return existing.Equal(pid)
    51  	})
    52  }
    53  
    54  func (c *PidCacheValue) Remove(identity string, kind string) {
    55  	k := key(identity, kind)
    56  	c.cache.Remove(k)
    57  }
    58  
    59  func (c *PidCacheValue) RemoveByMember(member *Member) {
    60  	addr := member.Address()
    61  
    62  	for item := range c.cache.IterBuffered() {
    63  		pid, _ := item.Val.(*actor.PID)
    64  		if pid.Address == addr {
    65  			c.cache.Remove(item.Key)
    66  		}
    67  	}
    68  }