-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
83 lines (74 loc) · 1.89 KB
/
command.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
package rabbitmq
import (
"bytes"
"context"
"fmt"
"github.com/hectorgabucio/taterubot-dc/kit/command"
"github.com/streadway/amqp"
"log"
"time"
)
type CommandBus struct {
Connection *amqp.Connection
Channel *amqp.Channel
}
func NewCommandBus(connectionURL string) (*CommandBus, error) {
conn, ch, err := establishConnection(connectionURL)
if err != nil {
return nil, err
}
return &CommandBus{
Connection: conn,
Channel: ch,
}, nil
}
func (c *CommandBus) Close() error {
if err := c.Connection.Close(); err != nil {
return fmt.Errorf("rabbit.close: %w", err)
}
return nil
}
func (c *CommandBus) Dispatch(ctx context.Context, command command.Command) error {
b, err := encode(command)
if err != nil {
return fmt.Errorf("err encoding command, %w", err)
}
if err := c.Channel.Publish(exchange, string(command.Type()), false, false, amqp.Publishing{
AppId: appID,
ContentType: encodingType,
Body: b.Bytes(),
Timestamp: time.Now(),
}); err != nil {
return fmt.Errorf("err publishing command to topic, %w", err)
}
return nil
}
func (c *CommandBus) Register(t command.Type, handler command.Handler) {
msgs := initializeChannelConsumption(c.Channel, string(t))
go handleCommands(msgs, handler)
}
func handleCommands(commands <-chan amqp.Delivery, handler command.Handler) {
for delivery := range commands {
var cmd command.Command
buf := bytes.NewBuffer(delivery.Body)
if err := decode(buf, &cmd); err != nil {
log.Printf("err decoding command, %v", err)
err := delivery.Ack(false)
if err != nil {
log.Println("err acking failed decoding", err)
}
return
}
log.Println("handling command", cmd)
go func() {
err := handler.Handle(context.Background(), cmd)
if err != nil {
log.Println("err goroutine handling command", err)
}
}()
err := delivery.Ack(false)
if err != nil {
log.Println("err ack command", err)
}
}
}