-
Notifications
You must be signed in to change notification settings - Fork 530
/
Copy pathdata_writer.go
87 lines (71 loc) · 1.99 KB
/
data_writer.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
package v2
import (
"bytes"
"io"
"github.com/grafana/tempo/tempodb/backend"
"github.com/grafana/tempo/tempodb/encoding/common"
)
type dataWriter struct {
outputWriter io.Writer
pool WriterPool
compressedBuffer *bytes.Buffer
compressionWriter io.WriteCloser
objectRW common.ObjectReaderWriter
objectBuffer *bytes.Buffer
}
// NewDataWriter creates a paged page writer
func NewDataWriter(writer io.Writer, encoding backend.Encoding) (common.DataWriter, error) {
pool, err := GetWriterPool(encoding)
if err != nil {
return nil, err
}
compressedBuffer := &bytes.Buffer{}
compressionWriter, err := pool.GetWriter(compressedBuffer)
if err != nil {
return nil, err
}
return &dataWriter{
outputWriter: writer,
pool: pool,
compressionWriter: compressionWriter,
compressedBuffer: compressedBuffer,
objectRW: NewObjectReaderWriter(),
objectBuffer: &bytes.Buffer{},
}, nil
}
// Write implements DataWriter
func (p *dataWriter) Write(id common.ID, obj []byte) (int, error) {
return p.objectRW.MarshalObjectToWriter(id, obj, p.objectBuffer)
}
// CutPage implements DataWriter
func (p *dataWriter) CutPage() (int, error) {
// compress the raw object buffer
buffer := p.objectBuffer.Bytes()
_, err := p.compressionWriter.Write(buffer)
if err != nil {
return 0, err
}
// force flush everything
p.compressionWriter.Close()
// now marshal the buffer as a page to the output
bytesWritten, err := marshalPageToWriter(p.compressedBuffer.Bytes(), p.outputWriter, constDataHeader)
if err != nil {
return 0, err
}
// reset buffers for the next write
p.objectBuffer.Reset()
p.compressedBuffer.Reset()
p.compressionWriter, err = p.pool.ResetWriter(p.compressedBuffer, p.compressionWriter)
if err != nil {
return 0, err
}
return bytesWritten, err
}
// Complete implements DataWriter
func (p *dataWriter) Complete() error {
if p.compressionWriter != nil {
p.pool.PutWriter(p.compressionWriter)
p.compressionWriter = nil
}
return nil
}