forked from roadrunner-server/roadrunner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_buffer.go
113 lines (95 loc) · 2.29 KB
/
error_buffer.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
package roadrunner
import (
"sync"
"time"
)
const (
// EventStderrOutput - is triggered when worker sends data into stderr. The context
// is error message ([]byte).
EventStderrOutput = 1900
// WaitDuration - for how long error buffer should attempt to aggregate error messages
// before merging output together since lastError update (required to keep error update together).
WaitDuration = 100 * time.Millisecond
)
// thread safe errBuffer
type errBuffer struct {
mu sync.Mutex
buf []byte
last int
wait *time.Timer
update chan interface{}
stop chan interface{}
lsn func(event int, ctx interface{})
}
func newErrBuffer() *errBuffer {
eb := &errBuffer{
buf: make([]byte, 0),
update: make(chan interface{}),
wait: time.NewTimer(WaitDuration),
stop: make(chan interface{}),
}
go func() {
for {
select {
case <-eb.update:
eb.wait.Reset(WaitDuration)
case <-eb.wait.C:
eb.mu.Lock()
if len(eb.buf) > eb.last {
if eb.lsn != nil {
eb.lsn(EventStderrOutput, eb.buf[eb.last:])
eb.buf = eb.buf[0:0]
}
eb.last = len(eb.buf)
}
eb.mu.Unlock()
case <-eb.stop:
eb.wait.Stop()
eb.mu.Lock()
if len(eb.buf) > eb.last {
if eb.lsn != nil {
eb.lsn(EventStderrOutput, eb.buf[eb.last:])
}
eb.last = len(eb.buf)
}
eb.mu.Unlock()
return
}
}
}()
return eb
}
// Listen attaches error stream even listener.
func (eb *errBuffer) Listen(l func(event int, ctx interface{})) {
eb.mu.Lock()
eb.lsn = l
eb.mu.Unlock()
}
// Len returns the number of buf of the unread portion of the errBuffer;
// buf.Len() == len(buf.Bytes()).
func (eb *errBuffer) Len() int {
eb.mu.Lock()
defer eb.mu.Unlock()
// currently active message
return len(eb.buf)
}
// Write appends the contents of pool to the errBuffer, growing the errBuffer as
// needed. The return value n is the length of pool; err is always nil.
func (eb *errBuffer) Write(p []byte) (int, error) {
eb.mu.Lock()
eb.buf = append(eb.buf, p...)
eb.mu.Unlock()
eb.update <- nil
return len(p), nil
}
// Strings fetches all errBuffer data into string.
func (eb *errBuffer) String() string {
eb.mu.Lock()
defer eb.mu.Unlock()
return string(eb.buf)
}
// Close aggregation timer.
func (eb *errBuffer) Close() error {
close(eb.stop)
return nil
}