-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopic.go
More file actions
76 lines (64 loc) · 1.62 KB
/
topic.go
File metadata and controls
76 lines (64 loc) · 1.62 KB
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
69
70
71
72
73
74
75
76
package gpubsub
import (
"sync"
"time"
)
type Topic[T any] struct {
mu sync.RWMutex
name string
subscriptions map[string]*Subscription[T]
concurrency int64
interval time.Duration
ttl time.Duration
}
func NewTopic[T any](name string, concurrency int64, interval time.Duration, ttl time.Duration) *Topic[T] {
return &Topic[T]{
name: name,
subscriptions: make(map[string]*Subscription[T]),
concurrency: concurrency,
interval: interval,
ttl: ttl,
}
}
func (t *Topic[T]) Name() string {
return t.name
}
func (t *Topic[T]) Subscriptions() map[string]*Subscription[T] {
return t.subscriptions
}
func (t *Topic[T]) Publish(body T) {
for _, s := range t.subscriptions {
message := s.newMessage(body)
s.publish(message)
}
}
func (t *Topic[T]) NewSubscription(name string) *Subscription[T] {
t.mu.Lock()
defer t.mu.Unlock()
if _, ok := t.subscriptions[name]; !ok {
t.subscriptions[name] = &Subscription[T]{
name: name,
topic: t,
ch: make(chan string, 65536),
messages: make(map[string]*Message[T]),
concurrency: t.concurrency,
interval: t.interval,
ttl: t.ttl,
}
}
return t.subscriptions[name]
}
func (t *Topic[T]) register(subscription *Subscription[T]) {
t.mu.Lock()
defer t.mu.Unlock()
if _, ok := t.subscriptions[subscription.name]; !ok {
t.subscriptions[subscription.name] = subscription
}
}
func (t *Topic[T]) unregister(subscription *Subscription[T]) {
t.mu.Lock()
defer t.mu.Unlock()
if _, ok := t.subscriptions[subscription.name]; ok {
delete(t.subscriptions, subscription.name)
}
}