-
Notifications
You must be signed in to change notification settings - Fork 0
/
inmemory.go
188 lines (160 loc) · 4.46 KB
/
inmemory.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
package send
import (
"errors"
"io"
"sync"
"github.com/tychoish/grip/level"
"github.com/tychoish/grip/message"
)
const (
readHeadNone = -1
readHeadTruncated = -2
)
// ErrorTruncated means that the limited buffer capacity was overwritten.
var ErrorTruncated = errors.New("buffer was truncated")
// InMemorySender represents an in-memory buffered sender with a fixed message capacity.
type InMemorySender struct {
Base
buffer []message.Composer
mutex sync.RWMutex
writeHead int
readHead int
readHeadCaughtUp bool
totalBytesSent int64
}
// NewInMemorySender creates an in-memory buffered sender with the given capacity.
func NewInMemorySender(name string, p level.Priority, capacity int) (Sender, error) {
if capacity <= 0 {
return nil, errors.New("cannot have capacity <= 0")
}
s := &InMemorySender{
buffer: make([]message.Composer, 0, capacity),
readHead: readHeadNone,
}
s.SetName(name)
s.SetPriority(p)
s.SetErrorHandler(ErrorHandlerFromSender(MakeStdError()))
s.SetFormatter(MakeDefaultFormatter())
return s, nil
}
func (s *InMemorySender) overflow() bool {
return len(s.buffer) == cap(s.buffer)
}
// GetCount returns at most count messages in the buffer as a stream. It returns
// the messages and the number of messages returned. If the function is called
// and reaches the end of the buffer, it returns io.EOF. If the position it is
// currently reading at has been truncated, this returns ErrorTruncated. To
// continue reading, the read stream must be reset using ResetRead.
func (s *InMemorySender) GetCount(count int) ([]message.Composer, int, error) {
if count <= 0 {
return nil, 0, errors.New("cannot have count <= 0")
}
s.mutex.Lock()
defer s.mutex.Unlock()
if len(s.buffer) == 0 {
return nil, 0, io.EOF
}
switch s.readHead {
case readHeadNone:
if !s.overflow() {
s.readHead = 0
} else {
s.readHead = s.writeHead
}
case readHeadTruncated:
return nil, 0, ErrorTruncated
}
remaining := s.writeHead - s.readHead
if remaining < 0 {
remaining += len(s.buffer)
} else if remaining == 0 && !s.readHeadCaughtUp {
remaining = len(s.buffer)
}
if remaining < count {
count = remaining
}
if count == 0 {
return nil, 0, io.EOF
}
defer func() {
s.readHead = (s.readHead + count) % cap(s.buffer)
s.readHeadCaughtUp = s.readHead == s.writeHead
}()
start := s.readHead
end := s.readHead + count
if end > len(s.buffer) {
end = end - len(s.buffer)
return append(s.buffer[start:len(s.buffer)], s.buffer[0:end]...), count, nil
}
return s.buffer[start:end], count, nil
}
// ResetRead resets the read stream used in GetCount.
func (s *InMemorySender) ResetRead() {
s.mutex.RLock()
defer s.mutex.RUnlock()
s.readHead = readHeadNone
s.readHeadCaughtUp = false
}
// Get returns all the current messages in the buffer.
func (s *InMemorySender) Get() []message.Composer {
s.mutex.RLock()
defer s.mutex.RUnlock()
start := s.writeHead - len(s.buffer)
if start < 0 {
start = start + len(s.buffer)
tmp := append([]message.Composer{}, s.buffer[start:len(s.buffer)]...)
return append(tmp, s.buffer[:s.writeHead]...)
}
return s.buffer[start:s.writeHead]
}
// GetString returns all the current messages in the buffer as formatted strings.
func (s *InMemorySender) GetString() ([]string, error) {
msgs := s.Get()
strs := make([]string, 0, len(msgs))
for _, msg := range msgs {
str, err := s.GetFormatter()(msg)
if err != nil {
return nil, err
}
strs = append(strs, str)
}
return strs, nil
}
// GetRaw returns all the current messages in the buffer as empty interfaces.
func (s *InMemorySender) GetRaw() []any {
msgs := s.Get()
raw := make([]any, 0, len(msgs))
for _, msg := range msgs {
raw = append(raw, msg.Raw())
}
return raw
}
// Send adds the given message to the buffer. If the buffer is at max capacity,
// it truncates the oldest message.
func (s *InMemorySender) Send(msg message.Composer) {
if !ShouldLog(s, msg) {
return
}
s.mutex.Lock()
defer s.mutex.Unlock()
if s.writeHead == s.readHead {
if s.readHeadCaughtUp {
s.readHeadCaughtUp = false
} else {
s.readHead = readHeadTruncated
}
}
if !s.overflow() {
s.buffer = append(s.buffer, msg)
} else {
s.buffer[s.writeHead] = msg
}
s.writeHead = (s.writeHead + 1) % cap(s.buffer)
s.totalBytesSent += int64(len(msg.String()))
}
// TotalBytesSent returns the total number of bytes sent.
func (s *InMemorySender) TotalBytesSent() int64 {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.totalBytesSent
}