forked from MemeLabs/overrustlelogs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavrobuffer.go
89 lines (71 loc) · 1.96 KB
/
avrobuffer.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
package common
import (
"bytes"
"fmt"
"io"
"github.com/actgardner/gogen-avro/container"
)
// WriterConstructor ...
type WriterConstructor func(writer io.Writer, codec container.Codec, recordsPerBlock int64) (*container.Writer, error)
// AvroBuffer ...
type AvroBuffer struct {
WriterConstructor WriterConstructor
Codec container.Codec
RecordsPerBlock int64
BytesPerFile int
Writer io.Writer
avroWriter *container.Writer
buffer bytes.Buffer
recordCount int64
}
// NewAvroBuffer ...
func NewAvroBuffer(writerConstructor WriterConstructor, writer io.Writer, codec container.Codec, recordsPerBlock int64, bytesPerFile int) (*AvroBuffer, error) {
a := &AvroBuffer{
WriterConstructor: writerConstructor,
Codec: codec,
RecordsPerBlock: recordsPerBlock,
BytesPerFile: bytesPerFile,
Writer: writer,
}
if err := a.initAvroWriter(); err != nil {
return nil, err
}
return a, nil
}
func (a *AvroBuffer) initAvroWriter() (err error) {
a.avroWriter, err = a.WriterConstructor(&a.buffer, a.Codec, a.RecordsPerBlock)
if err != nil {
return fmt.Errorf("initializing avro writer: %v", err)
}
return
}
// WriteRecord ...
func (a *AvroBuffer) WriteRecord(record container.AvroRecord) error {
if err := a.avroWriter.WriteRecord(record); err != nil {
return err
}
a.recordCount++
if a.buffer.Len() >= a.BytesPerFile {
if err := a.Flush(); err != nil {
return fmt.Errorf("writing record: %v", err)
}
}
return nil
}
// Flush ...
func (a *AvroBuffer) Flush() error {
if a.recordCount%a.RecordsPerBlock != 0 {
if err := a.avroWriter.Flush(); err != nil {
return fmt.Errorf("flushing avroWriter: %v", err)
}
}
if _, err := a.Writer.Write(a.buffer.Bytes()); err != nil {
return fmt.Errorf("flushing buffer: %v", err)
}
a.buffer.Reset()
if err := a.initAvroWriter(); err != nil {
return fmt.Errorf("reinitializing writer: %v", err)
}
a.recordCount = 0
return nil
}