-
Notifications
You must be signed in to change notification settings - Fork 2
/
circular.go
303 lines (234 loc) · 6.54 KB
/
circular.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Package circular provides a buffer with circular semantics.
package circular
import (
"fmt"
"math"
"slices"
"sync"
"sync/atomic"
"github.com/siderolabs/gen/optional"
)
// Buffer implements circular buffer with a thread-safe writer,
// that supports multiple readers each with its own offset.
type Buffer struct {
// waking up streaming readers on new writes
cond *sync.Cond
// channel for persistence commands from the writer to the persistence goroutine
commandCh chan persistenceCommand
// compressed chunks, ordered from the smallest offset to the largest
chunks []chunk
// the last uncompressed chunk, might grow up to MaxCapacity, then used
// as circular buffer
data []byte
// buffer options
opt Options
// waitgroup to wait for persistence goroutine to finish
wg sync.WaitGroup
// closed flag (to disable writes after close)
closed atomic.Bool
// synchronizing access to data, off, chunks
mu sync.Mutex
// write offset, always goes up, actual offset in data slice
// is (off % cap(data))
off int64
}
// NewBuffer creates new Buffer with specified options.
func NewBuffer(opts ...OptionFunc) (*Buffer, error) {
buf := &Buffer{
opt: defaultOptions(),
}
for _, o := range opts {
if err := o(&buf.opt); err != nil {
return nil, err
}
}
if buf.opt.InitialCapacity > buf.opt.MaxCapacity {
return nil, fmt.Errorf("initial capacity (%d) should be less or equal to max capacity (%d)", buf.opt.InitialCapacity, buf.opt.MaxCapacity)
}
if buf.opt.SafetyGap >= buf.opt.MaxCapacity {
return nil, fmt.Errorf("safety gap (%d) should be less than max capacity (%d)", buf.opt.SafetyGap, buf.opt.MaxCapacity)
}
buf.data = make([]byte, buf.opt.InitialCapacity)
buf.cond = sync.NewCond(&buf.mu)
if err := buf.load(); err != nil {
return nil, err
}
buf.run()
return buf, nil
}
// Close closes the buffer and waits for persistence goroutine to finish.
func (buf *Buffer) Close() error {
if buf.closed.Swap(true) {
return nil
}
if buf.commandCh != nil {
close(buf.commandCh)
}
buf.wg.Wait()
return nil
}
// Write implements io.Writer interface.
//
//nolint:gocognit
func (buf *Buffer) Write(p []byte) (int, error) {
l := len(p)
if l == 0 {
return 0, nil
}
if buf.closed.Load() {
return 0, ErrClosed
}
buf.mu.Lock()
defer buf.mu.Unlock()
if buf.off < int64(buf.opt.MaxCapacity) {
if buf.off+int64(l) > int64(cap(buf.data)) && cap(buf.data) < buf.opt.MaxCapacity {
// grow buffer to ensure write fits, but limit with max capacity
size := cap(buf.data) * 2
for size < int(buf.off)+l {
size *= 2
}
if size > buf.opt.MaxCapacity {
size = buf.opt.MaxCapacity
}
data := make([]byte, size)
copy(data, buf.data)
buf.data = data
}
}
var n int
for n < l {
rotate := false
i := int(buf.off % int64(buf.opt.MaxCapacity))
nn := buf.opt.MaxCapacity - i
if nn > len(p) {
nn = len(p)
} else {
rotate = true
}
copy(buf.data[i:], p[:nn])
buf.off += int64(nn)
n += nn
p = p[nn:]
if rotate && buf.opt.NumCompressedChunks > 0 {
// we can't reuse any of the chunk buffers, as they might be referenced by readers
compressed, err := buf.opt.Compressor.Compress(buf.data, nil)
if err != nil {
return n, err
}
var maxID int64
for _, c := range buf.chunks {
maxID = max(c.id, maxID)
}
buf.chunks = append(buf.chunks, chunk{
compressed: compressed,
startOffset: buf.off - int64(buf.opt.MaxCapacity),
size: int64(buf.opt.MaxCapacity),
id: maxID + 1,
})
if buf.commandCh != nil {
buf.commandCh <- persistenceCommand{
chunkID: maxID + 1,
data: compressed,
}
}
if len(buf.chunks) > buf.opt.NumCompressedChunks {
if buf.commandCh != nil {
buf.commandCh <- persistenceCommand{
chunkID: buf.chunks[0].id,
drop: true,
}
}
buf.chunks = slices.Delete(buf.chunks, 0, 1)
}
}
}
buf.cond.Broadcast()
return n, nil
}
// Capacity returns number of bytes allocated for the buffer.
func (buf *Buffer) Capacity() int {
buf.mu.Lock()
defer buf.mu.Unlock()
return cap(buf.data)
}
// MaxCapacity returns maximum number of (decompressed) bytes (including compressed chunks) that can be stored in the buffer.
func (buf *Buffer) MaxCapacity() int {
return buf.opt.MaxCapacity * (buf.opt.NumCompressedChunks + 1)
}
// NumCompressedChunks returns number of compressed chunks.
func (buf *Buffer) NumCompressedChunks() int {
buf.mu.Lock()
defer buf.mu.Unlock()
return len(buf.chunks)
}
// TotalCompressedSize reports the overall memory used by the circular buffer including compressed chunks.
func (buf *Buffer) TotalCompressedSize() int64 {
buf.mu.Lock()
defer buf.mu.Unlock()
var size int64
for _, c := range buf.chunks {
size += int64(len(c.compressed))
}
return size + int64(cap(buf.data))
}
// TotalSize reports overall number of bytes available for reading in the buffer.
//
// TotalSize might be higher than TotalCompressedSize, because compressed chunks
// take less memory than uncompressed data.
func (buf *Buffer) TotalSize() int64 {
buf.mu.Lock()
defer buf.mu.Unlock()
if len(buf.chunks) == 0 {
if buf.off < int64(cap(buf.data)) {
return buf.off
}
return int64(cap(buf.data))
}
return buf.off - buf.chunks[0].startOffset
}
// Offset returns current write offset (number of bytes written).
func (buf *Buffer) Offset() int64 {
buf.mu.Lock()
defer buf.mu.Unlock()
return buf.off
}
// GetStreamingReader returns Reader object which implements io.ReadCloser, io.Seeker.
//
// StreamingReader starts at the most distant position in the past available.
func (buf *Buffer) GetStreamingReader() *Reader {
r := buf.GetReader()
r.endOff = math.MaxInt64
r.streaming = true
return r
}
// GetReader returns Reader object which implements io.ReadCloser, io.Seeker.
//
// Reader starts at the most distant position in the past available and goes
// to the current write position.
func (buf *Buffer) GetReader() *Reader {
buf.mu.Lock()
defer buf.mu.Unlock()
if len(buf.chunks) > 0 {
oldestChunk := buf.chunks[0]
return &Reader{
buf: buf,
chunk: optional.Some(oldestChunk),
startOff: oldestChunk.startOffset,
endOff: buf.off,
off: oldestChunk.startOffset,
}
}
off := buf.off - int64(buf.opt.MaxCapacity-buf.opt.SafetyGap)
if off < 0 {
off = 0
}
return &Reader{
buf: buf,
startOff: off,
endOff: buf.off,
off: off,
}
}