-
Notifications
You must be signed in to change notification settings - Fork 4
/
unbuffered.go
211 lines (182 loc) · 4.76 KB
/
unbuffered.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
package fluent
import (
"context"
"io"
"net"
"time"
pdebug "github.com/lestrrat-go/pdebug"
"github.com/pkg/errors"
)
// NewUnbuffered creates an unbuffered client. Unlike the normal
// buffered client, an unbuffered client handles the Post() method
// synchronously, and does not attempt to buffer the payload.
//
// - fluent.WithAddress
// - fluent.WithDialTimeout
// - fluent.WithMarshaler
// - fluent.WithMaxConnAttempts
// - fluent.WithNetwork
// - fluent.WithSubSecond
// - fluent.WithTagPrefix
//
// Please see their respective documentation for details.
func NewUnbuffered(options ...Option) (client *Unbuffered, err error) {
if pdebug.Enabled {
g := pdebug.Marker("fluent.NewUnbuffered").BindError(&err)
defer g.End()
}
var c = &Unbuffered{
address: "127.0.0.1:24224",
dialTimeout: 3 * time.Second,
maxConnAttempts: 64,
marshaler: marshalFunc(msgpackMarshal),
network: "tcp",
writeTimeout: 3 * time.Second,
}
var connectOnStart bool
//nolint:forcetypeassert
for _, opt := range options {
switch opt.Ident() {
case identAddress{}:
c.address = opt.Value().(string)
case identDialTimeout{}:
c.dialTimeout = opt.Value().(time.Duration)
case identMarshaler{}:
c.marshaler = opt.Value().(marshaler)
case identMaxConnAttempts{}:
c.maxConnAttempts = opt.Value().(uint64)
case identNetwork{}:
v := opt.Value().(string)
switch v {
case "tcp", "unix":
default:
return nil, errors.Errorf(`invalid network type: %s`, v)
}
c.network = v
case identSubSecond{}:
c.subsecond = opt.Value().(bool)
case identTagPrefix{}:
c.tagPrefix = opt.Value().(string)
case identConnectOnStart{}:
connectOnStart = opt.Value().(bool)
}
}
if connectOnStart {
if _, err := c.connect(true); err != nil {
return nil, errors.Wrap(err, `failed to connect on start`)
}
}
return c, nil
}
// Close cloes the currenct cached connection, if any
func (c *Unbuffered) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return nil
}
c.conn.Close()
c.conn = nil
return nil
}
// Shutdown is an alias to Close(). Since an unbuffered
// Client does not have any pending buffers at any given moment,
// we do not have to do anything other than close
func (c *Unbuffered) Shutdown(_ context.Context) error {
return c.Close()
}
func (c *Unbuffered) connect(force bool) (net.Conn, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn != nil {
if !force {
return c.conn, nil
}
c.conn.Close()
}
conn, err := dial(context.Background(), c.network, c.address, c.dialTimeout)
if err != nil {
return nil, err
}
c.conn = conn
return conn, nil
}
func (c *Unbuffered) serialize(msg *Message) ([]byte, error) {
if p := c.tagPrefix; len(p) > 0 {
msg.Tag = p + "." + msg.Tag
}
return c.marshaler.Marshal(msg)
}
// Post posts the given structure after encoding it along with the given tag.
//
// If you would like to specify options to `Post()`, you may pass them at the
// end of the method. Currently you can use the following:
//
// fluent.WithTimestamp: allows you to set arbitrary timestamp values
func (c *Unbuffered) Post(tag string, v interface{}, options ...Option) (err error) {
if pdebug.Enabled {
g := pdebug.Marker("fluent.Unbuffered.Post").BindError(&err)
defer g.End()
}
var t time.Time
//nolint:forcetypeassert
for _, opt := range options {
switch opt.Ident() {
case identTimestamp{}:
t = opt.Value().(time.Time)
}
}
if t.IsZero() {
t = time.Now()
}
msg := makeMessage(tag, v, t, c.subsecond, false)
defer releaseMessage(msg)
serialized, err := c.serialize(msg)
if err != nil {
return errors.Wrap(err, `failed to serialize payload`)
}
var attempt uint64
WRITE:
attempt++
if pdebug.Enabled {
pdebug.Printf("Attempt %d/%d", attempt, c.maxConnAttempts)
}
payload := serialized
if attempt > c.maxConnAttempts {
return errors.New(`exceeded max connection attempts`)
}
conn, err := c.connect(attempt > 1)
if err != nil {
goto WRITE
}
if pdebug.Enabled {
pdebug.Printf("Successfully connected to server")
}
if pdebug.Enabled {
pdebug.Printf("Going to write %d bytes", len(payload))
}
for len(payload) > 0 {
n, err := conn.Write(payload)
if err != nil {
if err == io.EOF {
goto WRITE // Try again
}
return errors.Wrap(err, `failed to write serialized payload`)
}
if pdebug.Enabled {
pdebug.Printf("Wrote %d bytes", n)
}
payload = payload[n:]
}
// All done!
return nil
}
// Ping sends a ping message. A ping for an unbuffered client is completely
// analogous to sending a message with Post
func (c *Unbuffered) Ping(tag string, v interface{}, options ...Option) (err error) {
if pdebug.Enabled {
g := pdebug.Marker("fluent.Unbuffered.Ping").BindError(&err)
defer g.End()
}
return c.Post(tag, v, options...)
}