forked from micro/micro
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stream.go
executable file
·182 lines (161 loc) · 4.16 KB
/
stream.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package handler
import (
"context"
"sync"
"time"
pb "github.com/2637309949/micro/v3/proto/events"
"github.com/2637309949/micro/v3/service/errors"
"github.com/2637309949/micro/v3/service/events"
"github.com/2637309949/micro/v3/service/events/util"
"github.com/2637309949/micro/v3/service/logger"
"github.com/2637309949/micro/v3/util/auth/namespace"
"github.com/google/uuid"
)
type Stream struct{}
func (s *Stream) Publish(ctx context.Context, req *pb.PublishRequest, rsp *pb.PublishResponse) error {
// authorize the request
if err := namespace.AuthorizeAdmin(ctx, namespace.DefaultNamespace, "events.Stream.Publish"); err != nil {
return err
}
// validate the request
if len(req.Topic) == 0 {
return errors.BadRequest("events.Stream.Publish", events.ErrMissingTopic.Error())
}
// parse options
var opts []events.PublishOption
if req.Timestamp > 0 {
opts = append(opts, events.WithTimestamp(time.Unix(req.Timestamp, 0)))
}
if req.Metadata != nil {
opts = append(opts, events.WithMetadata(req.Metadata))
}
// publish the event
if err := events.Publish(req.Topic, req.Payload, opts...); err != nil {
return errors.InternalServerError("events.Stream.Publish", err.Error())
}
// write the event to the store
event := events.Event{
ID: uuid.New().String(),
Metadata: req.Metadata,
Payload: req.Payload,
Topic: req.Topic,
Timestamp: time.Unix(req.Timestamp, 0),
}
if err := events.DefaultStore.Write(&event, events.WithTTL(time.Hour*24)); err != nil {
logger.Errorf("Error writing event %v to store: %v", event.ID, err)
}
return nil
}
func (s *Stream) Consume(ctx context.Context, req *pb.ConsumeRequest, rsp pb.Stream_ConsumeStream) error {
// authorize the request
if err := namespace.AuthorizeAdmin(ctx, namespace.DefaultNamespace, "events.Stream.Consume"); err != nil {
return err
}
// parse options
opts := []events.ConsumeOption{}
if req.Offset > 0 {
opts = append(opts, events.WithOffset(time.Unix(req.Offset, 0)))
}
if len(req.Group) > 0 {
opts = append(opts, events.WithGroup(req.Group))
}
if !req.AutoAck {
opts = append(opts, events.WithAutoAck(req.AutoAck, time.Duration(req.AckWait)/time.Nanosecond))
}
if req.RetryLimit > -1 {
opts = append(opts, events.WithRetryLimit(int(req.RetryLimit)))
}
// append the context
opts = append(opts, events.WithContext(ctx))
// create the subscriber
evChan, err := events.Consume(req.Topic, opts...)
if err != nil {
return errors.InternalServerError("events.Stream.Consume", err.Error())
}
type eventSent struct {
sent time.Time
event events.Event
}
ackMap := map[string]eventSent{}
mutex := sync.RWMutex{}
recvErrChan := make(chan error)
sendErrChan := make(chan error)
go func() {
// process messages from the consumer (probably just ACK messages
defer close(recvErrChan)
for {
select {
case <-ctx.Done():
return
case <-sendErrChan:
return
default:
}
req := pb.AckRequest{}
if err := rsp.RecvMsg(&req); err != nil {
return
}
mutex.RLock()
ev, ok := ackMap[req.Id]
mutex.RUnlock()
if !ok {
// not found, probably timed out after ackWait
continue
}
if req.Success {
ev.event.Ack()
} else {
ev.event.Nack()
}
mutex.Lock()
delete(ackMap, req.Id)
mutex.Unlock()
}
}()
go func() {
// process messages coming from the stream
defer close(sendErrChan)
for {
// Do any clean up of ackMap where we haven't got a response
now := time.Now()
mutex.Lock()
for k, v := range ackMap {
if v.sent.Add(2 * time.Duration(req.AckWait)).Before(now) {
delete(ackMap, k)
}
}
mutex.Unlock()
var ev events.Event
var ok bool
select {
case <-recvErrChan:
case <-rsp.Context().Done():
case <-ctx.Done():
case ev, ok = <-evChan:
}
if !ok {
return
}
if len(ev.ID) == 0 {
// ignore
continue
}
if !req.AutoAck {
// track the acks
mutex.Lock()
ackMap[ev.ID] = eventSent{event: ev, sent: time.Now()}
mutex.Unlock()
}
if err := rsp.Send(util.SerializeEvent(&ev)); err != nil {
return
}
}
}()
select {
case <-ctx.Done():
case <-recvErrChan:
case <-sendErrChan:
case <-rsp.Context().Done():
}
return nil
}