This repository has been archived by the owner on Dec 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathexample.go
196 lines (166 loc) · 6.03 KB
/
example.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
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"flag"
"fmt"
"os"
"runtime/debug"
"time"
"github.com/apache/thrift/lib/go/thrift"
"github.com/uber/cherami-client-go/client/cherami"
cthrift "github.com/uber/cherami-thrift/.generated/go/cherami"
)
var host = flag.String("host", "127.0.0.1", "cherami-frontend host IP")
var port = flag.Int("port", 4922, "cherami-frontend port")
// helper function to print out a thrift object in json
func jsonify(obj thrift.TStruct) string {
transport := thrift.NewTMemoryBufferLen(1024)
protocol := thrift.NewTSimpleJSONProtocol(transport)
obj.Write(protocol)
protocol.Flush()
transport.Flush()
return transport.String()
}
func exitIfError(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
debug.PrintStack()
os.Exit(1)
}
}
func main() {
flag.Parse()
// First, create the client to interact with Cherami
// Here we directly connect to cherami running on host:port
cClient, err := cherami.NewClient("cherami-example", *host, *port, &cherami.ClientOptions{
Timeout: time.Minute,
AuthProvider: cherami.NewBypassAuthProvider(),
})
exitIfError(err)
// Now, create a destination with timestamp to avoid collision.
path := fmt.Sprintf("/test/test_%d", time.Now().UnixNano())
dType := cthrift.DestinationType_PLAIN
consumedMessagesRetention := int32(3600)
unconsumedMessagesRetention := int32(7200)
ownerEmail := "cherami-client-example@cherami"
desc, err := cClient.CreateDestination(&cthrift.CreateDestinationRequest{
Path: &path,
Type: &dType,
ConsumedMessagesRetention: &consumedMessagesRetention,
UnconsumedMessagesRetention: &unconsumedMessagesRetention,
OwnerEmail: &ownerEmail,
})
exitIfError(err)
fmt.Printf("%v\n", jsonify(desc))
// Create a consumer group for that destination
name := fmt.Sprintf("%s_reader", path)
startTime := int64(0)
lockTimeout := int32(60)
maxDelivery := int32(3)
skipOlder := int32(3600)
cdesc, err := cClient.CreateConsumerGroup(&cthrift.CreateConsumerGroupRequest{
DestinationPath: &path,
ConsumerGroupName: &name,
StartFrom: &startTime,
LockTimeoutInSeconds: &lockTimeout,
MaxDeliveryCount: &maxDelivery,
SkipOlderMessagesInSeconds: &skipOlder,
OwnerEmail: &ownerEmail,
})
exitIfError(err)
fmt.Printf("%v\n", jsonify(cdesc))
// To publish, we need to create a Publisher for the specific destination
publisher := cClient.CreatePublisher(&cherami.CreatePublisherRequest{
Path: path,
})
err = publisher.Open()
exitIfError(err)
// We will do async publishing, so we need to have a channel to receive
// publish receipts. Spin up a goroutine to print the receipt or error.
receiptCh := make(chan *cherami.PublisherReceipt)
go func() {
for receipt := range receiptCh {
if receipt.Error != nil {
fmt.Fprintf(os.Stdout, "Error for publish ID %s is %s. With context userMsgID: %s\n", receipt.ID, receipt.Error.Error(), receipt.UserContext["userMsgID"])
} else {
fmt.Fprintf(os.Stdout, "Receipt for publish ID %s is %s. With context userMsgID: %s\n", receipt.ID, receipt.Receipt, receipt.UserContext["userMsgID"])
}
}
}()
// To consume, we need to create a Consumer object to handle the consumption
// from the destination. The Consumer is part of the Consumer Group.
consumer := cClient.CreateConsumer(&cherami.CreateConsumerRequest{
Path: path,
ConsumerGroupName: name,
ConsumerName: "",
PrefetchCount: 1,
Options: &cherami.ClientOptions{
Timeout: 15 * time.Second,
},
})
// The messages will be delivered via a channel. Spin up a goroutine to print out the message content.
ch := make(chan cherami.Delivery, 1)
_, err = consumer.Open(ch)
doneCh := make(chan struct{})
go func() {
i := 0
for delivery := range ch {
msg := delivery.GetMessage()
fmt.Fprintf(os.Stdout, "msg: '%s', ack_token: %s\n", string(msg.GetPayload().GetData()), delivery.GetDeliveryToken())
delivery.Ack()
i++
if i == 10 {
doneCh <- struct{}{}
return
}
}
}()
// Start publishing
for i := 0; i < 10; i++ {
var id string
data := fmt.Sprintf("message %d", i)
userMsgID := fmt.Sprintf("user-msg-%d", i)
id, err = publisher.PublishAsync(&cherami.PublisherMessage{
Data: []byte(data),
UserContext: map[string]string{"userMsgID": userMsgID},
}, receiptCh)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
break
}
fmt.Fprintf(os.Stdout, "Local publish ID for message '%s': %s. With context userMsgID: %s\n", data, id, userMsgID)
}
publisher.Close()
close(receiptCh)
// Wait for all messages are consumed.
<-doneCh
// Clean up consumer group and destination. System will take care of actual deleting of messages.
err = cClient.DeleteConsumerGroup(&cthrift.DeleteConsumerGroupRequest{
DestinationPath: &path,
ConsumerGroupName: &name,
})
exitIfError(err)
err = cClient.DeleteDestination(&cthrift.DeleteDestinationRequest{
Path: &path,
})
exitIfError(err)
println("end")
}