-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathengine.go
94 lines (77 loc) · 1.74 KB
/
engine.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
package pubee
import (
"context"
"sync"
"github.com/izumin5210/pubee/marshal"
)
type Engine interface {
Publish(context.Context, interface{}, ...PublishOption)
Close(context.Context) error
}
type Message struct {
Data []byte
Metadata map[string]string
Original interface{}
}
type Interceptor func(context.Context, *Message, func(context.Context, *Message))
func New(d Driver, opts ...Option) Engine {
cfg := new(Config)
cfg.ErrorLog = defaultErrorLog
cfg.apply(opts)
return &engineImpl{
driver: d,
cfg: cfg,
}
}
type engineImpl struct {
driver Driver
cfg *Config
wg sync.WaitGroup
}
func (p *engineImpl) Publish(ctx context.Context, body interface{}, opts ...PublishOption) {
cfg := new(PublishConfig)
cfg.apply(p.cfg.PublishOpts)
cfg.apply(opts)
if l := p.cfg.ErrorLog; l != nil {
ctx = setErrorLog(ctx, l)
}
if cfg.Marshal == nil {
cfg.Marshal = marshal.Default
}
var errCh <-chan error
msg := &Message{Metadata: cfg.Metadata, Original: body}
data, err := cfg.Marshal(body)
if err != nil {
ch := make(chan error, 1)
ch <- err
errCh = ch
}
if errCh == nil {
msg.Data = data
if f := p.cfg.Interceptor; f == nil {
errCh = p.driver.Publish(ctx, msg)
} else {
f(ctx, msg, func(ctx context.Context, msg *Message) {
errCh = p.driver.Publish(ctx, msg)
})
}
}
p.wg.Add(1)
go func() {
defer p.wg.Done()
if err := <-errCh; err != nil {
GetErrorLog(ctx).Printf("failed to publish message: %v (metadata: %v)", err, msg.Metadata)
if f := p.cfg.OnFailPublishFunc; f != nil {
f(msg, err)
}
}
}()
}
func (p *engineImpl) Close(ctx context.Context) error {
if l := p.cfg.ErrorLog; l != nil {
ctx = setErrorLog(ctx, l)
}
p.driver.Flush()
p.wg.Wait()
return p.driver.Close(ctx)
}