-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.go
168 lines (155 loc) · 4.2 KB
/
registry.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package notificationcenter
import (
"context"
"io"
"log"
"sync"
"sync/atomic"
"github.com/pkg/errors"
"go.uber.org/multierr"
)
// Error list...
var (
ErrInvalidRegisterParameter = errors.New(`invalid register parameter`)
ErrUndefinedPublisherInterface = errors.New(`undefined publisher interface`)
ErrUndefinedSubscriberInterface = errors.New(`undefined subscriber interface`)
ErrInterfaceAlreadySubscribed = errors.New("[notificationcenter] interface already subscribed")
)
// Registry provides functionality of access to pub/sub
// interfaces by string names.
type Registry struct {
mx sync.RWMutex
closeEventCount int32
closeEvent chan bool
publishers map[string]Publisher
subscribers map[string]Subscriber
}
// NewRegistry init new registry object
func NewRegistry() *Registry {
return &Registry{
closeEvent: make(chan bool),
publishers: map[string]Publisher{},
subscribers: map[string]Subscriber{},
}
}
// Publisher returns pub interface by name if exists or Nil otherwise
func (r *Registry) Publisher(name string) Publisher {
r.mx.RLock()
defer r.mx.RUnlock()
return r.publishers[name]
}
// Subscriber returns sub interface by name if exists or Nil otherwise
func (r *Registry) Subscriber(name string) Subscriber {
r.mx.RLock()
defer r.mx.RUnlock()
return r.subscribers[name]
}
// Register one or more Publisher or Subscriber services.
// As input parameters must be order of parameters {Name, interface}
//
// Example:
// ```
// nc.Register(
// "events", kafka.MustNewSubscriber(),
// "notifications", nats.MustNewSubscriber(),
// )
// ```
func (r *Registry) Register(params ...any) error {
var name string
r.mx.Lock()
defer r.mx.Unlock()
for i, p := range params {
switch v := p.(type) {
case string:
if name != "" {
return errors.Wrap(ErrInvalidRegisterParameter, "pubsub-name")
}
name = v
case Publisher:
if _, ok := r.publishers[name]; ok {
return errors.Wrap(ErrInterfaceAlreadySubscribed, name)
}
r.publishers[name] = v
name = ""
case Subscriber:
if _, ok := r.subscribers[name]; ok {
return errors.Wrap(ErrInterfaceAlreadySubscribed, name)
}
r.subscribers[name] = v
name = ""
default:
return errors.Wrapf(ErrInvalidRegisterParameter, "%d:%t", i, v)
}
}
return nil
}
// Publish one or more messages to the pub-service
func (r *Registry) Publish(ctx context.Context, name string, messages ...any) error {
pub := r.Publisher(name)
if pub == nil {
return errors.Wrapf(ErrUndefinedPublisherInterface, name)
}
return pub.Publish(ctx, messages...)
}
// Subscribe new handler on some particular subscriber interface by name
func (r *Registry) Subscribe(ctx context.Context, name string, receiver any) error {
if sub := r.Subscriber(name); sub != nil {
return sub.Subscribe(ctx, ReceiverFrom(receiver))
}
return errors.Wrap(ErrUndefinedSubscriberInterface, name)
}
// Listen runs subscribers listen interface
func (r *Registry) Listen(ctx context.Context) (err error) {
var w sync.WaitGroup
r.mx.RLock()
for name, sub := range r.subscribers {
w.Add(1)
go func(ctx context.Context, name string, sub Subscriber) {
defer w.Done()
if err = sub.Listen(ctx); err != nil {
log.Println(name, err)
}
}(ctx, name, sub)
}
r.mx.RUnlock()
w.Wait()
return err
}
// Close notification center
func (r *Registry) Close() error {
var errors error
r.mx.Lock()
defer r.mx.Unlock()
for _, pub := range r.publishers {
if cl, ok := pub.(io.Closer); ok {
if err := cl.Close(); err != nil {
errors = multierr.Append(errors, err)
}
}
}
for _, sub := range r.subscribers {
if cl, ok := sub.(io.Closer); ok {
if err := cl.Close(); err != nil {
errors = multierr.Append(errors, err)
}
}
}
for i := int32(0); i < atomic.LoadInt32(&r.closeEventCount); i++ {
r.closeEvent <- true
}
return errors
}
// OnClose event will be executed only after closing all interfaces
//
// Usecases in the application makes subsribing for the finishing event very convinient
//
// ```go
// func myDatabaseObserver() {
// <- notificationcenter.OnClose()
// // ... Do something
// }
// ```
func (r *Registry) OnClose() <-chan bool {
atomic.AddInt32(&r.closeEventCount, 1)
return (<-chan bool)(r.closeEvent)
}