-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopic.go
More file actions
431 lines (359 loc) · 11.7 KB
/
topic.go
File metadata and controls
431 lines (359 loc) · 11.7 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package sebtopic
import (
"context"
"fmt"
"io"
"path"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/micvbang/go-helpy/sizey"
"github.com/micvbang/go-helpy/slicey"
"github.com/micvbang/go-helpy/uint64y"
"github.com/micvbang/simple-event-broker/internal/infrastructure/logger"
"github.com/micvbang/simple-event-broker/internal/sebcache"
"github.com/micvbang/simple-event-broker/internal/sebrecords"
"github.com/micvbang/simple-event-broker/seberr"
)
type File struct {
Size int64
Path string
}
type Storage interface {
Writer(recordBatchPath string) (io.WriteCloser, error)
Reader(recordBatchPath string) (io.ReadCloser, error)
ListFiles(topicName string, extension string) ([]File, error)
}
type Compress interface {
NewWriter(io.Writer) (io.WriteCloser, error)
NewReader(io.Reader) (io.ReadCloser, error)
}
type Topic struct {
log logger.Logger
topicName string
nextOffset atomic.Uint64
mu sync.Mutex
recordBatchOffsets []uint64
backingStorage Storage
cache *sebcache.Cache
compression Compress
OffsetCond *OffsetCond
}
type Opts struct {
Compression Compress
}
func New(log logger.Logger, backingStorage Storage, topicName string, cache *sebcache.Cache, optFuncs ...func(*Opts)) (*Topic, error) {
opts := Opts{
Compression: Gzip{},
}
for _, optFunc := range optFuncs {
optFunc(&opts)
}
recordBatchOffsets, err := listRecordBatchOffsets(backingStorage, topicName)
if err != nil {
return nil, fmt.Errorf("listing record batches: %w", err)
}
topic := &Topic{
log: log.WithField("topic-name", topicName),
backingStorage: backingStorage,
topicName: topicName,
recordBatchOffsets: recordBatchOffsets,
cache: cache,
compression: opts.Compression,
OffsetCond: NewOffsetCond(0),
}
if len(recordBatchOffsets) > 0 {
newestRecordBatchOffset := recordBatchOffsets[len(recordBatchOffsets)-1]
parser, err := topic.parseRecordBatch(newestRecordBatchOffset)
if err != nil {
return nil, fmt.Errorf("reading record batch header: %w", err)
}
defer parser.Close()
nextOffset := newestRecordBatchOffset + uint64(parser.Header.NumRecords)
topic.nextOffset.Store(nextOffset)
topic.OffsetCond = NewOffsetCond(nextOffset - 1)
}
return topic, nil
}
// AddRecords writes records to the topic's backing storage and returns the ids
// of the newly added records in the same order as the records were given.
//
// NOTE: AddRecords is NOT thread safe. It's up to the caller to ensure that
// this is not called concurrently. This is normally the responsibility of a
// RecordBatcher.
func (s *Topic) AddRecords(batch sebrecords.Batch) ([]uint64, error) {
s.log.Debugf("Adding %d records (%d bytes)", batch.Len(), len(batch.Data))
recordBatchID := s.nextOffset.Load()
rbPath := RecordBatchKey(s.topicName, recordBatchID)
backingWriter, err := s.backingStorage.Writer(rbPath)
if err != nil {
return nil, fmt.Errorf("opening writer '%s': %w", rbPath, err)
}
w := backingWriter
if s.compression != nil {
w, err = s.compression.NewWriter(backingWriter)
if err != nil {
return nil, fmt.Errorf("creating compression writer: %w", err)
}
}
t0 := time.Now()
err = sebrecords.Write(w, batch)
if err != nil {
return nil, fmt.Errorf("writing record batch: %w", err)
}
if s.compression != nil {
err = w.Close()
if err != nil {
return nil, fmt.Errorf("closing compression writer: %w", err)
}
}
// once Close() returns, the data has been committed and can be retrieved by
// ReadRecord.
err = backingWriter.Close()
if err != nil {
return nil, fmt.Errorf("closing backing writer: %w", err)
}
s.log.Infof("wrote %d records (%s bytes) to %s (%s)", batch.Len(), sizey.FormatBytes(len(batch.Data)), rbPath, time.Since(t0))
nextOffset := recordBatchID + uint64(batch.Len())
offsets := make([]uint64, 0, batch.Len())
for i := recordBatchID; i < nextOffset; i++ {
offsets = append(offsets, i)
}
// once Store() returns, the newly added records are visible in
// ReadRecords(). NOTE: recordBatchIDs must also have been updated before
// this is true.
s.mu.Lock()
s.recordBatchOffsets = append(s.recordBatchOffsets, recordBatchID)
s.mu.Unlock()
s.nextOffset.Store(nextOffset)
// TODO: it would be nice to remove this from the "fastpath"
// NOTE: we are intentionally not returning caching errors to caller. It's
// (semi) fine if the file isn't written to cache since we can retrieve it
// from backing storage.
if s.cache != nil {
cacheWtr, err := s.cache.Writer(rbPath)
if err != nil {
s.log.Errorf("creating cache writer to cache (%s): %w", rbPath, err)
return offsets, nil
}
err = sebrecords.Write(cacheWtr, batch)
if err != nil {
s.log.Errorf("writing to cache (%s): %w", rbPath, err)
}
err = cacheWtr.Close()
if err != nil {
s.log.Errorf("closing cached file (%s): %w", rbPath, err)
}
}
// inform potentially waiting consumers that new offsets have been added
if len(offsets) > 0 {
s.OffsetCond.Broadcast(slicey.Last(offsets))
}
return offsets, nil
}
// ReadRecords returns records starting from startOffset and until either:
// 1) ctx is cancelled
// 2) maxRecords has been reached
// 3) softMaxBytes has been reached
//
// - maxRecords defaults to 10 if 0 is given.
// - softMaxBytes defaults to inifinity if 0 is given;
// - softMaxBytes is "soft" because it will not be honored if it means returning
// zero records; in this case, at least one record will be returned.
//
// NOTE: ReadRecords will always return all of the records that it managed
// to fetch until one of the above conditions were met. This means that the
// returned value should be used even if err is non-nil!
func (s *Topic) ReadRecords(ctx context.Context, batch *sebrecords.Batch, offset uint64, maxRecords int, softMaxBytes int) error {
if offset >= s.nextOffset.Load() {
return fmt.Errorf("offset does not exist: %w", seberr.ErrOutOfBounds)
}
if maxRecords == 0 {
maxRecords = 10
}
// make a local copy of recordBatchOffsets so that we don't have to hold the
// lock for the rest of the function.
s.mu.Lock()
recordBatchOffsets := make([]uint64, len(s.recordBatchOffsets))
copy(recordBatchOffsets, s.recordBatchOffsets)
s.mu.Unlock()
// find the batch that offset is located in
var (
batchOffset uint64
batchOffsetIndex int
)
for batchOffsetIndex = len(recordBatchOffsets) - 1; batchOffsetIndex >= 0; batchOffsetIndex-- {
curBatchOffset := recordBatchOffsets[batchOffsetIndex]
if curBatchOffset <= offset {
batchOffset = curBatchOffset
break
}
}
trackByteSize := softMaxBytes != 0
recordBatchBytes := uint32(0)
batchRecordIndex := uint32(offset - batchOffset)
firstRecord := true
moreRecords := func() bool { return batch.Len() < maxRecords }
moreBytes := func() bool { return (!trackByteSize || recordBatchBytes < uint32(softMaxBytes)) }
moreBatches := func() bool { return batchOffsetIndex < len(recordBatchOffsets) }
for moreRecords() && moreBytes() && moreBatches() {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
batchOffset = recordBatchOffsets[batchOffsetIndex]
rb, err := s.parseRecordBatch(batchOffset)
if err != nil {
return fmt.Errorf("parsing record batch: %w", err)
}
batchMaxRecords := min(uint32(maxRecords-batch.Len()), rb.Header.NumRecords-batchRecordIndex)
numRecords := batchMaxRecords
if trackByteSize {
numRecords = 0
for _, recordSize := range rb.RecordSizes[batchRecordIndex : batchRecordIndex+batchMaxRecords] {
if !firstRecord && recordBatchBytes+recordSize > uint32(softMaxBytes) {
break
}
numRecords += 1
recordBatchBytes += recordSize
firstRecord = false
}
}
// we read enough records to satisfy the request
if numRecords == 0 {
break
}
err = rb.Records(batch, batchRecordIndex, batchRecordIndex+numRecords)
if err != nil {
return fmt.Errorf("record batch '%s': %w", s.recordBatchPath(batchOffset), err)
}
// no more relevant records in batch -> prepare to check next batch
rb.Close()
batchOffsetIndex += 1
batchRecordIndex = 0
}
return nil
}
// NextOffset returns the topic's next offset (offset of the next record added).
func (s *Topic) NextOffset() uint64 {
return s.nextOffset.Load()
}
type Metadata struct {
NextOffset uint64
LatestCommitAt time.Time
}
// Metadata returns metadata about the topic
func (s *Topic) Metadata() (Metadata, error) {
var latestCommitAt time.Time
nextOffset := s.nextOffset.Load()
if nextOffset > 0 {
recordBatchID := s.offsetGetRecordBatchID(nextOffset - 1)
p, err := s.parseRecordBatch(recordBatchID)
if err != nil {
return Metadata{}, fmt.Errorf("parsing record batch: %w", err)
}
latestCommitAt = time.UnixMicro(p.Header.UnixEpochUs)
}
return Metadata{
NextOffset: nextOffset,
LatestCommitAt: latestCommitAt,
}, nil
}
func (s *Topic) parseRecordBatch(recordBatchID uint64) (*sebrecords.Parser, error) {
recordBatchPath := s.recordBatchPath(recordBatchID)
// NOTE: f is given to sebrecords.Parser, which will own it and be responsible
// for closing it.
f, err := s.cache.Reader(recordBatchPath)
if err != nil {
s.log.Infof("%s not found in cache", recordBatchPath)
}
if f == nil { // not found in cache
backingReader, err := s.backingStorage.Reader(recordBatchPath)
if err != nil {
return nil, fmt.Errorf("opening reader '%s': %w", recordBatchPath, err)
}
r := backingReader
if s.compression != nil {
r, err = s.compression.NewReader(backingReader)
if err != nil {
return nil, fmt.Errorf("creating compression reader: %w", err)
}
}
// write to cache
cacheFile, err := s.cache.Writer(recordBatchPath)
if err != nil {
return nil, fmt.Errorf("writing backing storage result to cache: %w", err)
}
_, err = io.Copy(cacheFile, r)
if err != nil {
return nil, fmt.Errorf("copying backing storage result to cache: %w", err)
}
if s.compression != nil {
r.Close()
}
err = cacheFile.Close()
if err != nil {
return nil, fmt.Errorf("closing cacheFile: %w", err)
}
err = backingReader.Close()
if err != nil {
return nil, fmt.Errorf("closing backing reader: %w", err)
}
f, err = s.cache.Reader(recordBatchPath)
if err != nil {
return nil, fmt.Errorf("reading from cache just after writing it: %w", err)
}
}
rb, err := sebrecords.Parse(f)
if err != nil {
return nil, fmt.Errorf("parsing record batch '%s': %w", recordBatchPath, err)
}
return rb, nil
}
func (s *Topic) offsetGetRecordBatchID(offset uint64) uint64 {
s.mu.Lock()
defer s.mu.Unlock()
for i := len(s.recordBatchOffsets) - 1; i >= 0; i-- {
curBatchID := s.recordBatchOffsets[i]
if curBatchID <= offset {
return curBatchID
}
}
return 0
}
func (s *Topic) recordBatchPath(recordBatchID uint64) string {
return RecordBatchKey(s.topicName, recordBatchID)
}
const recordBatchExtension = ".record_batch"
func listRecordBatchOffsets(backingStorage Storage, topicName string) ([]uint64, error) {
files, err := backingStorage.ListFiles(topicName, recordBatchExtension)
if err != nil {
return nil, fmt.Errorf("listing files: %w", err)
}
offsets := make([]uint64, 0, len(files))
for _, file := range files {
fileName := path.Base(file.Path)
offsetStr := fileName[:len(fileName)-len(recordBatchExtension)]
offset, err := uint64y.FromString(offsetStr)
if err != nil {
return nil, err
}
offsets = append(offsets, offset)
}
sort.Slice(offsets, func(i, j int) bool {
return offsets[i] < offsets[j]
})
return offsets, nil
}
// RecordBatchKey returns the symbolic path of the topicName and the recordBatchID.
func RecordBatchKey(topicName string, recordBatchID uint64) string {
return filepath.Join(topicName, fmt.Sprintf("%012d%s", recordBatchID, recordBatchExtension))
}
func WithCompress(c Compress) func(*Opts) {
return func(o *Opts) {
o.Compression = c
}
}