-
Notifications
You must be signed in to change notification settings - Fork 58
/
topic_message_query.go
314 lines (259 loc) · 7.84 KB
/
topic_message_query.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package hedera
/*-
*
* Hedera Go SDK
*
* Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import (
"context"
"io"
"math"
"regexp"
"sync"
"time"
"github.com/hashgraph/hedera-protobufs-go/services"
"github.com/hashgraph/hedera-protobufs-go/mirror"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var rstStream = regexp.MustCompile("(?i)\\brst[^0-9a-zA-Z]stream\\b") //nolint
// TopicMessageQuery
// Query that listens to messages sent to the specific TopicID
type TopicMessageQuery struct {
errorHandler func(stat status.Status)
completionHandler func()
retryHandler func(err error) bool
attempt uint64
maxAttempts uint64
topicID *TopicID
startTime *time.Time
endTime *time.Time
limit uint64
mu sync.Mutex
}
// NewTopicMessageQuery creates TopicMessageQuery which
// listens to messages sent to the specific TopicID
func NewTopicMessageQuery() *TopicMessageQuery {
return &TopicMessageQuery{
maxAttempts: maxAttempts,
errorHandler: _DefaultErrorHandler,
retryHandler: _DefaultRetryHandler,
completionHandler: _DefaultCompletionHandler,
}
}
// SetTopicID Sets topic ID to retrieve messages for.
// Required
func (query *TopicMessageQuery) SetTopicID(topicID TopicID) *TopicMessageQuery {
query.topicID = &topicID
return query
}
// GetTopicID returns the TopicID for this TopicMessageQuery
func (query *TopicMessageQuery) GetTopicID() TopicID {
if query.topicID == nil {
return TopicID{}
}
return *query.topicID
}
// SetStartTime Sets time for when to start listening for messages. Defaults to current time if
// not set.
func (query *TopicMessageQuery) SetStartTime(startTime time.Time) *TopicMessageQuery {
query.startTime = &startTime
return query
}
// GetStartTime returns the start time for this TopicMessageQuery
func (query *TopicMessageQuery) GetStartTime() time.Time {
if query.startTime != nil {
return *query.startTime
}
return time.Time{}
}
// SetEndTime Sets time when to stop listening for messages. If not set it will receive
// indefinitely.
func (query *TopicMessageQuery) SetEndTime(endTime time.Time) *TopicMessageQuery {
query.endTime = &endTime
return query
}
func (query *TopicMessageQuery) GetEndTime() time.Time {
if query.endTime != nil {
return *query.endTime
}
return time.Time{}
}
// SetLimit Sets the maximum number of messages to receive before stopping. If not set or set to zero it will
// return messages indefinitely.
func (query *TopicMessageQuery) SetLimit(limit uint64) *TopicMessageQuery {
query.limit = limit
return query
}
func (query *TopicMessageQuery) GetLimit() uint64 {
return query.limit
}
// SetMaxAttempts Sets the amount of attempts to try to retrieve message
func (query *TopicMessageQuery) SetMaxAttempts(maxAttempts uint64) *TopicMessageQuery {
query.maxAttempts = maxAttempts
return query
}
// GetMaxAttempts returns the amount of attempts to try to retrieve message
func (query *TopicMessageQuery) GetMaxAttempts() uint64 {
return query.maxAttempts
}
// SetErrorHandler Sets the error handler for this query
func (query *TopicMessageQuery) SetErrorHandler(errorHandler func(stat status.Status)) *TopicMessageQuery {
query.errorHandler = errorHandler
return query
}
// SetCompletionHandler Sets the completion handler for this query
func (query *TopicMessageQuery) SetCompletionHandler(completionHandler func()) *TopicMessageQuery {
query.completionHandler = completionHandler
return query
}
// SetRetryHandler Sets the retry handler for this query
func (query *TopicMessageQuery) SetRetryHandler(retryHandler func(err error) bool) *TopicMessageQuery {
query.retryHandler = retryHandler
return query
}
func (query *TopicMessageQuery) validateNetworkOnIDs(client *Client) error {
if client == nil || !client.autoValidateChecksums {
return nil
}
if query.topicID != nil {
if err := query.topicID.ValidateChecksum(client); err != nil {
return err
}
}
return nil
}
func (query *TopicMessageQuery) build() *mirror.ConsensusTopicQuery {
body := &mirror.ConsensusTopicQuery{
Limit: query.limit,
}
if query.topicID != nil {
body.TopicID = query.topicID._ToProtobuf()
}
if query.startTime != nil {
body.ConsensusStartTime = _TimeToProtobuf(*query.startTime)
} else {
body.ConsensusStartTime = &services.Timestamp{}
}
if query.endTime != nil {
body.ConsensusEndTime = _TimeToProtobuf(*query.endTime)
}
return body
}
// Subscribe subscribes to messages sent to the specific TopicID
func (query *TopicMessageQuery) Subscribe(client *Client, onNext func(TopicMessage)) (SubscriptionHandle, error) {
var once sync.Once
done := make(chan struct{})
handle := SubscriptionHandle{}
err := query.validateNetworkOnIDs(client)
if err != nil {
return SubscriptionHandle{}, err
}
pb := query.build()
messages := make(map[string][]*mirror.ConsensusTopicResponse)
channel, err := client.mirrorNetwork._GetNextMirrorNode()._GetConsensusServiceClient()
if err != nil {
return handle, err
}
go func() {
query.mu.Lock()
defer query.mu.Unlock()
var subClient mirror.ConsensusService_SubscribeTopicClient
var err error
for {
if err != nil {
handle.Unsubscribe()
if grpcErr, ok := status.FromError(err); ok { // nolint
if query.attempt < query.maxAttempts && query.retryHandler(err) {
subClient = nil
delay := math.Min(250.0*math.Pow(2.0, float64(query.attempt)), 8000)
time.Sleep(time.Duration(delay) * time.Millisecond)
query.attempt++
} else {
query.errorHandler(*grpcErr)
break
}
} else if err == io.EOF {
query.completionHandler()
break
} else {
panic(err)
}
}
if subClient == nil {
ctx, cancel := context.WithCancel(context.TODO())
handle.onUnsubscribe = cancel
once.Do(func() {
close(done)
})
subClient, err = (*channel).SubscribeTopic(ctx, pb)
if err != nil {
continue
}
}
var resp *mirror.ConsensusTopicResponse
resp, err = subClient.Recv()
if err != nil {
continue
}
if resp.ConsensusTimestamp != nil {
pb.ConsensusStartTime = _TimeToProtobuf(_TimeFromProtobuf(resp.ConsensusTimestamp).Add(1 * time.Nanosecond))
}
if pb.Limit > 0 {
pb.Limit--
}
if resp.ChunkInfo == nil || resp.ChunkInfo.Total == 1 {
onNext(_TopicMessageOfSingle(resp))
} else {
txID := _TransactionIDFromProtobuf(resp.ChunkInfo.InitialTransactionID).String()
message, ok := messages[txID]
if !ok {
message = make([]*mirror.ConsensusTopicResponse, 0, resp.ChunkInfo.Total)
}
message = append(message, resp)
messages[txID] = message
if int32(len(message)) == resp.ChunkInfo.Total {
delete(messages, txID)
onNext(_TopicMessageOfMany(message))
}
}
}
}()
<-done
return handle, nil
}
func _DefaultErrorHandler(stat status.Status) {
println("Failed to subscribe to topic with status", stat.Code().String())
}
func _DefaultCompletionHandler() {
println("Subscription to topic finished")
}
func _DefaultRetryHandler(err error) bool {
code := status.Code(err)
switch code {
case codes.NotFound, codes.ResourceExhausted, codes.Unavailable:
return true
case codes.Internal:
grpcErr, ok := status.FromError(err)
if !ok {
return false
}
return rstStream.FindIndex([]byte(grpcErr.Message())) != nil
default:
return false
}
}