-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdestination.go
105 lines (90 loc) · 2.5 KB
/
destination.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
package nrelay
import (
"log"
"time"
"github.com/nats-io/nats.go"
"github.com/octu0/chanque"
"github.com/pkg/errors"
)
const (
defaultWorkerCapacity int = 1024
defaultWorkerMaxMsgSize int = 32
defaultFlushTimeout time.Duration = 50 * time.Millisecond
)
type Destination interface {
Open(num int) error
Close() error
Workers() []chanque.Worker
}
// check interface
var (
_ Destination = (*SingleDestination)(nil)
)
type SingleDestination struct {
executor *chanque.Executor
url string
natsOpts []nats.Option
logger *log.Logger
conns []*nats.Conn
workers []chanque.Worker
}
func (d *SingleDestination) Open(num int) error {
conns := make([]*nats.Conn, 0, num)
workers := make([]chanque.Worker, 0, num)
for i := 0; i < num; i += 1 {
conn, err := nats.Connect(d.url, d.natsOpts...)
if err != nil {
return errors.WithStack(err)
}
d.logger.Printf("debug: nats destination connect %s", d.url)
conns = append(conns, conn)
workers = append(workers, d.createWorker(conn))
}
d.conns = conns
d.workers = workers
return nil
}
func (d *SingleDestination) Close() error {
for _, worker := range d.workers {
worker.CloseEnqueue()
}
for _, worker := range d.workers {
worker.ShutdownAndWait()
}
for _, conn := range d.conns {
conn.Flush()
conn.Drain()
}
return nil
}
func (d *SingleDestination) Workers() []chanque.Worker {
return d.workers
}
func (d *SingleDestination) createWorker(conn *nats.Conn) chanque.Worker {
return chanque.NewDefaultWorker(
d.createWorkerHandler(conn),
chanque.WorkerExecutor(d.executor),
chanque.WorkerCapacity(defaultWorkerCapacity),
chanque.WorkerMaxDequeueSize(defaultWorkerMaxMsgSize),
chanque.WorkerPostHook(d.createWorkerPostHook(conn)),
chanque.WorkerAbortQueueHandler(func(param interface{}) {
d.logger.Printf("error: destination queue aborted: %v", param)
}),
)
}
func (d *SingleDestination) createWorkerHandler(conn *nats.Conn) chanque.WorkerHandler {
return func(param interface{}) {
msg := param.(*nats.Msg)
if err := conn.Publish(msg.Subject, msg.Data); err != nil {
d.logger.Printf("warn: failed to publish subj:%s err:%+v", msg.Subject, err)
}
}
}
func (d *SingleDestination) createWorkerPostHook(conn *nats.Conn) chanque.WorkerHook {
return func() {
conn.FlushTimeout(defaultFlushTimeout)
}
}
func NewSingleDestination(executor *chanque.Executor, url string, natsOpts []nats.Option, logger *log.Logger) *SingleDestination {
return &SingleDestination{executor, url, natsOpts, logger, nil, nil}
}