-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpipecat.go
244 lines (214 loc) · 5.32 KB
/
pipecat.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
package main
import (
"bufio"
"fmt"
"log"
"os"
"sync"
"time"
"encoding/base64"
"github.com/codegangsta/cli"
"github.com/streadway/amqp"
)
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
func prepare(amqpURI string, queueName string, createQueue bool) (*amqp.Connection, *amqp.Channel) {
conn, err := amqp.Dial(amqpURI)
failOnError(err, "Failed to connect to AMQP broker")
channel, err := conn.Channel()
failOnError(err, "Failed to open a channel")
if createQueue == true {
_, err = channel.QueueDeclare(
queueName, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare queue")
}
return conn, channel
}
func publish(c *cli.Context) {
queueName := c.Args().First()
if queueName == "" {
fmt.Println("Please provide name of the queue")
os.Exit(1)
}
conn, channel := prepare(c.String("amqpuri"), queueName, !c.Bool("no-create-queue"))
defer conn.Close()
defer channel.Close()
// It is better to have a durable delivery mode and let user disable it
// even though it is not the RabbitMQ default
deliveryMode := uint8(2)
if c.Bool("transient") {
deliveryMode = 1
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
msgBody := []byte(line)
if c.Bool("base64") {
var encodeErr error
msgBody, encodeErr = base64.StdEncoding.DecodeString(line)
failOnError(encodeErr, "Fail to decode base64")
}
err := channel.Publish(
c.String("exchange"), // exchange
queueName, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: msgBody,
DeliveryMode: deliveryMode,
})
failOnError(err, "Failed to publish a message")
fmt.Println(line)
}
err := scanner.Err()
failOnError(err, "Failed to read from stdin")
}
func consume(c *cli.Context) {
queueName := c.Args().First()
if queueName == "" {
fmt.Println("Please provide name of the queue")
os.Exit(1)
}
conn, channel := prepare(c.String("amqpuri"), queueName, !c.Bool("no-create-queue"))
defer conn.Close()
defer channel.Close()
var mutex sync.Mutex
unackedMessages := make([]amqp.Delivery, 100)
msgs, err := channel.Consume(
queueName, // queue
"", // consumer
c.Bool("autoack"), // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register consumer")
ackMessages := func() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
ackedLine := scanner.Text()
// O(n²) complexity for the win!
mutex.Lock() // use channels some day
for i, msg := range unackedMessages {
unackedLine := fmt.Sprintf("%s", msg.Body)
if c.Bool("base64") {
unackedLine = base64.StdEncoding.EncodeToString([]byte(unackedLine))
}
if unackedLine == ackedLine {
msg.Ack(false)
// discard message
unackedMessages = append(unackedMessages[:i], unackedMessages[i+1:]...)
break
}
}
mutex.Unlock()
}
err := scanner.Err()
failOnError(err, "Failed to read from stdin")
}
forever := make(chan bool)
consumeMessages := func() {
timeout := time.Second * time.Duration(c.Int("timeout"))
for {
select {
case msg := <-msgs:
if !c.Bool("autoack") {
mutex.Lock()
unackedMessages = append(unackedMessages, msg)
mutex.Unlock()
}
line := fmt.Sprintf("%s", msg.Body)
if c.Bool("base64") {
line = base64.StdEncoding.EncodeToString([]byte(line))
}
fmt.Println(line)
case <-time.After(timeout):
if c.Bool("non-blocking") {
forever <- false
return
}
}
}
}
if c.Bool("autoack") {
go consumeMessages()
} else {
go ackMessages()
go consumeMessages()
}
<-forever
}
func main() {
app := cli.NewApp()
app.Name = "pipecat"
app.Usage = "Connect unix pipes and message queues"
app.Version = "0.3.1"
globalFlags := []cli.Flag{
cli.StringFlag{
Name: "amqpuri",
Value: "amqp://guest:guest@localhost:5672/",
Usage: "AMQP URI",
EnvVar: "AMQP_URI",
},
cli.StringFlag{
Name: "exchange",
Value: "",
Usage: "AMQP Exchange to publish to (default: \"\")",
EnvVar: "AMQP_EXCHANGE",
},
cli.BoolFlag{
Name: "no-create-queue",
Usage: "Don't create queue",
},
cli.BoolFlag{
Name: "autoack",
Usage: "Ack all received messages directly",
},
cli.BoolFlag{
Name: "non-blocking",
Usage: "Stop consumer after timeout",
},
cli.BoolFlag{
Name: "transient",
Usage: "Publish messages with transient delivery mode",
},
cli.IntFlag{
Name: "timeout",
Value: 1,
Usage: "Timeout to wait for messages",
},
cli.BoolFlag{
Name: "base64",
Usage: "Encode to Base64 string in consumer mode. Decode from Base64 string in publish mode",
},
}
app.Commands = []cli.Command{
{
Name: "publish",
Aliases: []string{"p"},
Usage: "Publish messages to queue",
Flags: globalFlags,
Action: publish,
},
{
Name: "consume",
Flags: globalFlags,
Aliases: []string{"c"},
Usage: "Consume messages from queue",
Action: consume,
},
}
app.Run(os.Args)
}