forked from StephanU/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.go
69 lines (61 loc) · 1.34 KB
/
timeout.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
package reader
import (
"errors"
"time"
)
var (
errTimeout = errors.New("timeout")
)
// timeoutProcessor will signal some configurable timeout error if no
// new line can be returned in time.
type Timeout struct {
reader Reader
timeout time.Duration
signal error
running bool
ch chan lineMessage
}
type lineMessage struct {
line Message
err error
}
// NewTimeout returns a new timeout reader from an input line reader.
func NewTimeout(reader Reader, signal error, t time.Duration) *Timeout {
if signal == nil {
signal = errTimeout
}
return &Timeout{
reader: reader,
signal: signal,
timeout: t,
ch: make(chan lineMessage, 1),
}
}
// Next returns the next line. If no line was returned before timeout, the
// configured timeout error is returned.
// For handline timeouts a goroutine is started for reading lines from
// configured line reader. Only when underlying reader returns an error, the
// goroutine will be finished.
func (p *Timeout) Next() (Message, error) {
if !p.running {
p.running = true
go func() {
for {
message, err := p.reader.Next()
p.ch <- lineMessage{message, err}
if err != nil {
break
}
}
}()
}
select {
case msg := <-p.ch:
if msg.err != nil {
p.running = false
}
return msg.line, msg.err
case <-time.After(p.timeout):
return Message{}, p.signal
}
}