blob: 78effc9b6a67fb91bc44ff8eb12acf357957efe5 (
plain)
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
|
package roadrunner
import (
"bytes"
"sync"
)
// EventStderrOutput - is triggered when worker sends data into stderr. The context is error message ([]byte).
const EventStderrOutput = 1900
// thread safe errBuffer
type errBuffer struct {
mu sync.Mutex
buf []byte
off int
lsn func(event int, ctx interface{})
}
func newErrBuffer() *errBuffer {
buf := &errBuffer{buf: make([]byte, 0)}
return buf
}
// Listen attaches error stream even listener.
func (eb *errBuffer) Listen(l func(event int, ctx interface{})) {
eb.mu.Lock()
defer eb.mu.Unlock()
eb.lsn = l
}
// 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) - eb.off
}
// Write appends the contents of p to the errBuffer, growing the errBuffer as
// needed. The return value n is the length of p; err is always nil.
func (eb *errBuffer) Write(p []byte) (int, error) {
eb.mu.Lock()
defer eb.mu.Unlock()
eb.buf = append(eb.buf, p...)
for msg := eb.fetchMsg(); msg != nil; msg = eb.fetchMsg() {
if eb.lsn != nil {
eb.lsn(EventStderrOutput, msg)
}
}
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[eb.off:])
}
func (eb *errBuffer) fetchMsg() []byte {
if i := bytes.Index(eb.buf[eb.off:], []byte{10, 10}); i != -1 {
eb.off += i + 2
return eb.buf[eb.off-i-2 : eb.off]
}
return nil
}
|