-
Notifications
You must be signed in to change notification settings - Fork 0
/
topic.go
126 lines (110 loc) · 2.57 KB
/
topic.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
package gopubsub
import (
"context"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"gocloud.dev/gcerrors"
"gocloud.dev/pubsub"
"gocloud.dev/pubsub/driver"
)
type ErrorCode = gcerrors.ErrorCode
const (
PubsubLocal = 1001
)
type topic struct {
name string
subs map[uuid.UUID]subscription
subsSync sync.RWMutex
}
var topics = make(map[string]*topic)
var topicsSync sync.Mutex
func openTopic(ctx context.Context, topicName string) (*topic, error) {
topicsSync.Lock()
defer topicsSync.Unlock()
if topics[topicName] == nil {
topics[topicName] = &topic{
name: topicName,
subs: make(map[uuid.UUID]subscription),
}
}
return topics[topicName], nil
}
func (m *topic) SendBatch(ctx context.Context, msgs []*driver.Message) error {
m.subsSync.RLock()
defer m.subsSync.RUnlock()
for idx, msg := range msgs {
if err := m.send(ctx, &pubsub.Message{
Body: msg.Body,
}); err != nil {
return fmt.Errorf("cannot send message #%d; messages count: %d: %w", idx, len(msgs), err)
}
}
return nil
}
func (m *topic) send(ctx context.Context, msg *pubsub.Message) (err error) {
wg := sync.WaitGroup{}
wg.Add(len(m.subs))
for _, s := range m.subs {
s := s
go func() {
c, cancel := context.WithTimeout(ctx, 10*time.Millisecond)
defer cancel()
running := true
for running {
select {
case s.C <- &driver.Message{Body: msg.Body}:
running = false
case <-c.Done():
running = false
if err == nil {
err = fmt.Errorf("cannot send message to subscription: %v", s)
} else {
err = fmt.Errorf("cannot send message to subscription: %v: %w", s, err)
}
}
}
wg.Done()
}()
}
wg.Wait()
return
}
// Close implements io.Closer.
func (t *topic) Close() error {
return nil
}
// IsRetryable implements driver.Topic.IsRetryable.
func (t *topic) IsRetryable(error) bool {
return false
}
// As implements driver.Topic.As.
func (t *topic) As(i interface{}) bool {
panic("not sure what for it is")
// if p, ok := i.(*sarama.SyncProducer); ok {
// *p = t.producer
// return true
// }
// return false
}
// ErrorAs implements driver.Topic.ErrorAs.
func (t *topic) ErrorAs(err error, i interface{}) bool {
panic("not sure what for it is")
// return errorAs(err, i)
}
// ErrorCode implements driver.Topic.ErrorCode.
func (t *topic) ErrorCode(err error) gcerrors.ErrorCode {
fmt.Printf("pubsub local: %s", err)
return PubsubLocal
}
func (m *topic) add(s subscription) func() {
m.subsSync.Lock()
defer m.subsSync.Unlock()
m.subs[s.ID] = s
return func() {
m.subsSync.Lock()
defer m.subsSync.Unlock()
delete(m.subs, s.ID)
}
}