github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/cluster/pubsub.go (about) 1 package cluster 2 3 import ( 4 "time" 5 6 "github.com/asynkron/protoactor-go/actor" 7 "github.com/asynkron/protoactor-go/extensions" 8 ) 9 10 const PubSubDeliveryName = "$pubsub-delivery" 11 12 var pubsubExtensionID = extensions.NextExtensionID() 13 14 type PubSub struct { 15 cluster *Cluster 16 } 17 18 func NewPubSub(cluster *Cluster) *PubSub { 19 p := &PubSub{ 20 cluster: cluster, 21 } 22 cluster.ActorSystem.Extensions.Register(p) 23 return p 24 } 25 26 // Start the PubSubMemberDeliveryActor 27 func (p *PubSub) Start() { 28 props := actor.PropsFromProducer(func() actor.Actor { 29 return NewPubSubMemberDeliveryActor(p.cluster.Config.PubSubConfig.SubscriberTimeout, p.cluster.Logger()) 30 }) 31 _, err := p.cluster.ActorSystem.Root.SpawnNamed(props, PubSubDeliveryName) 32 if err != nil { 33 panic(err) // let it crash 34 } 35 p.cluster.Logger().Info("Started Cluster PubSub") 36 } 37 38 func (p *PubSub) ExtensionID() extensions.ExtensionID { 39 return pubsubExtensionID 40 } 41 42 type PubSubConfig struct { 43 // SubscriberTimeout is a timeout used when delivering a message batch to a subscriber. Default is 5s. 44 // 45 // This value gets rounded to seconds for optimization of cancellation token creation. Note that internally, 46 // cluster request is used to deliver messages to ClusterIdentity subscribers. 47 SubscriberTimeout time.Duration 48 } 49 50 func newPubSubConfig() *PubSubConfig { 51 return &PubSubConfig{ 52 SubscriberTimeout: 5 * time.Second, 53 } 54 } 55 56 // GetPubSub returns the PubSub extension from the actor system 57 func GetPubSub(system *actor.ActorSystem) *PubSub { 58 return system.Extensions.Get(pubsubExtensionID).(*PubSub) 59 }