-
Notifications
You must be signed in to change notification settings - Fork 1
/
subscriber_repository.go
68 lines (55 loc) · 1.35 KB
/
subscriber_repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package broker
import (
"context"
"fmt"
"sync"
"sync/atomic"
"github.com/ispiroglu/mercurius/internal/logger"
"go.uber.org/zap"
)
type SubscriberRepository struct {
logger *zap.Logger
StreamPools *sync.Map
poolCount atomic.Uint32
}
func NewSubscriberRepository() *SubscriberRepository {
return &SubscriberRepository{
logger: logger.NewLogger(),
StreamPools: &sync.Map{},
}
}
func (r *SubscriberRepository) Unsubscribe(subscriber *Subscriber) error {
val, ok := r.StreamPools.LoadAndDelete(subscriber.Name)
if !ok {
return fmt.Errorf("subscriber not found")
}
val.(*StreamPool).Delete()
r.poolCount.Store(
r.poolCount.Load() - 1,
)
return nil
}
func (r *SubscriberRepository) addSubscriber(ctx context.Context, id string, subName string, topicName string) (*Subscriber, error) {
s := NewSubscriber(ctx, id, subName, topicName)
var pool *StreamPool
if p, ok := r.StreamPools.Load(subName); ok {
pool = p.(*StreamPool)
} else {
pool = newStreamPool(subName)
r.StreamPools.Store(subName, pool)
}
pool.AddSubscriber(s)
r.poolCount.Add(1)
return s, nil
}
func (r *SubscriberRepository) addSub(s *Subscriber) {
var pool *StreamPool
if p, ok := r.StreamPools.Load(s.Name); ok {
pool = p.(*StreamPool)
} else {
pool = newStreamPool(s.Name)
r.StreamPools.Store(s.Name, pool)
}
pool.AddSubscriber(s)
r.poolCount.Add(1)
}