|
| 1 | +// Copyright (c) 2023-2024 Nibi, Inc. |
| 2 | +package pubsub |
| 3 | + |
| 4 | +import ( |
| 5 | + "sync" |
| 6 | + "sync/atomic" |
| 7 | + |
| 8 | + "github.com/pkg/errors" |
| 9 | + |
| 10 | + coretypes "github.com/cometbft/cometbft/rpc/core/types" |
| 11 | +) |
| 12 | + |
| 13 | +type UnsubscribeFunc func() |
| 14 | + |
| 15 | +// EventBus manages topics and subscriptions. A "topic" is a named channel of |
| 16 | +// communication. A "subscription" is the action taken by a subscriber to express |
| 17 | +// interest in receiving messages broadcasted from a specific topic. |
| 18 | +type EventBus interface { |
| 19 | + // AddTopic: Adds a new topic with the specified name and message source |
| 20 | + AddTopic(name string, src <-chan coretypes.ResultEvent) error |
| 21 | + // RemoveTopic: Removes the specified topic and all its related data, |
| 22 | + // ensuring clean up of resources. |
| 23 | + RemoveTopic(name string) |
| 24 | + Subscribe(name string) (<-chan coretypes.ResultEvent, UnsubscribeFunc, error) |
| 25 | + Topics() []string |
| 26 | +} |
| 27 | + |
| 28 | +// memEventBus is an implemention of the `EventBus` interface. |
| 29 | +type memEventBus struct { |
| 30 | + topics map[string]<-chan coretypes.ResultEvent |
| 31 | + topicsMux *sync.RWMutex |
| 32 | + subscribers map[string]map[uint64]chan<- coretypes.ResultEvent |
| 33 | + subscribersMux *sync.RWMutex |
| 34 | + currentUniqueID uint64 |
| 35 | +} |
| 36 | + |
| 37 | +// NewEventBus returns a fresh imlpemention of `memEventBus`, which implements |
| 38 | +// the `EventBus` interface for managing Ethereum topics and subscriptions. |
| 39 | +func NewEventBus() EventBus { |
| 40 | + return &memEventBus{ |
| 41 | + topics: make(map[string]<-chan coretypes.ResultEvent), |
| 42 | + topicsMux: new(sync.RWMutex), |
| 43 | + subscribers: make(map[string]map[uint64]chan<- coretypes.ResultEvent), |
| 44 | + subscribersMux: new(sync.RWMutex), |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// GenUniqueID atomically increments and returns a unique identifier for a new subscriber. |
| 49 | +// This ID is used internally to manage subscriber-specific channels. |
| 50 | +func (m *memEventBus) GenUniqueID() uint64 { |
| 51 | + return atomic.AddUint64(&m.currentUniqueID, 1) |
| 52 | +} |
| 53 | + |
| 54 | +// Topics returns a list of all topics currently managed by the EventBus. The |
| 55 | +// list is safe for concurrent access and is a snapshot of current topic names. |
| 56 | +func (m *memEventBus) Topics() (topics []string) { |
| 57 | + m.topicsMux.RLock() |
| 58 | + defer m.topicsMux.RUnlock() |
| 59 | + |
| 60 | + topics = make([]string, 0, len(m.topics)) |
| 61 | + for topicName := range m.topics { |
| 62 | + topics = append(topics, topicName) |
| 63 | + } |
| 64 | + |
| 65 | + return topics |
| 66 | +} |
| 67 | + |
| 68 | +// AddTopic adds a new topic with the specified name and message source |
| 69 | +func (m *memEventBus) AddTopic(name string, src <-chan coretypes.ResultEvent) error { |
| 70 | + m.topicsMux.RLock() |
| 71 | + _, ok := m.topics[name] |
| 72 | + m.topicsMux.RUnlock() |
| 73 | + |
| 74 | + if ok { |
| 75 | + return errors.New("topic already registered") |
| 76 | + } |
| 77 | + |
| 78 | + m.topicsMux.Lock() |
| 79 | + m.topics[name] = src |
| 80 | + m.topicsMux.Unlock() |
| 81 | + |
| 82 | + go m.publishTopic(name, src) |
| 83 | + |
| 84 | + return nil |
| 85 | +} |
| 86 | + |
| 87 | +// RemoveTopic: Removes the specified topic and all its related data, ensuring |
| 88 | +// clean up of resources. |
| 89 | +func (m *memEventBus) RemoveTopic(name string) { |
| 90 | + m.topicsMux.Lock() |
| 91 | + delete(m.topics, name) |
| 92 | + m.topicsMux.Unlock() |
| 93 | +} |
| 94 | + |
| 95 | +// Subscribe attempts to create a subscription to the specified topic. It returns |
| 96 | +// a channel to receive messages, a function to unsubscribe, and an error if the |
| 97 | +// topic does not exist. |
| 98 | +func (m *memEventBus) Subscribe(name string) (<-chan coretypes.ResultEvent, UnsubscribeFunc, error) { |
| 99 | + m.topicsMux.RLock() |
| 100 | + _, ok := m.topics[name] |
| 101 | + m.topicsMux.RUnlock() |
| 102 | + |
| 103 | + if !ok { |
| 104 | + return nil, nil, errors.Errorf("topic not found: %s", name) |
| 105 | + } |
| 106 | + |
| 107 | + ch := make(chan coretypes.ResultEvent) |
| 108 | + m.subscribersMux.Lock() |
| 109 | + defer m.subscribersMux.Unlock() |
| 110 | + |
| 111 | + id := m.GenUniqueID() |
| 112 | + if _, ok := m.subscribers[name]; !ok { |
| 113 | + m.subscribers[name] = make(map[uint64]chan<- coretypes.ResultEvent) |
| 114 | + } |
| 115 | + m.subscribers[name][id] = ch |
| 116 | + |
| 117 | + unsubscribe := func() { |
| 118 | + m.subscribersMux.Lock() |
| 119 | + defer m.subscribersMux.Unlock() |
| 120 | + delete(m.subscribers[name], id) |
| 121 | + } |
| 122 | + |
| 123 | + return ch, unsubscribe, nil |
| 124 | +} |
| 125 | + |
| 126 | +func (m *memEventBus) publishTopic(name string, src <-chan coretypes.ResultEvent) { |
| 127 | + for { |
| 128 | + msg, ok := <-src |
| 129 | + if !ok { |
| 130 | + m.closeAllSubscribers(name) |
| 131 | + m.topicsMux.Lock() |
| 132 | + delete(m.topics, name) |
| 133 | + m.topicsMux.Unlock() |
| 134 | + return |
| 135 | + } |
| 136 | + m.publishAllSubscribers(name, msg) |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +// closeAllSubscribers closes all subscriber channels associated with the |
| 141 | +// specified topic and removes the topic from the subscribers map. This function |
| 142 | +// is typically called when a topic is deleted or no longer available to ensure |
| 143 | +// all resources are released properly and to prevent goroutine leaks. It ensures |
| 144 | +// thread-safe execution by locking around the operation. |
| 145 | +func (m *memEventBus) closeAllSubscribers(name string) { |
| 146 | + m.subscribersMux.Lock() |
| 147 | + defer m.subscribersMux.Unlock() |
| 148 | + |
| 149 | + subscribers := m.subscribers[name] |
| 150 | + delete(m.subscribers, name) |
| 151 | + // #nosec G705 |
| 152 | + for _, sub := range subscribers { |
| 153 | + close(sub) |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +// publishAllSubscribers sends a message to all subscribers of the specified |
| 158 | +// topic. It uses a non-blocking send operation to deliver the message to |
| 159 | +// subscriber channels. If a subscriber's channel is not ready to receive the |
| 160 | +// message (i.e., the channel is full), the message is skipped for that |
| 161 | +// subscriber to avoid blocking the publisher. This function ensures thread-safe |
| 162 | +// access to subscribers by using a read lock. |
| 163 | +func (m *memEventBus) publishAllSubscribers(name string, msg coretypes.ResultEvent) { |
| 164 | + m.subscribersMux.RLock() |
| 165 | + defer m.subscribersMux.RUnlock() |
| 166 | + subscribers := m.subscribers[name] |
| 167 | + // #nosec G705 |
| 168 | + for _, sub := range subscribers { |
| 169 | + select { |
| 170 | + case sub <- msg: |
| 171 | + default: |
| 172 | + } |
| 173 | + } |
| 174 | +} |
0 commit comments