forked from abdullin/cellar
-
Notifications
You must be signed in to change notification settings - Fork 1
/
reader.go
257 lines (188 loc) · 5.19 KB
/
reader.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
package cellar
import (
"encoding/binary"
"io"
"os"
"path"
"go.uber.org/zap"
"github.com/pkg/errors"
)
type ReadFlag int
const (
RF_None ReadFlag = 0
RF_LoadBuffer ReadFlag = 1 << 1
RF_PrintChunks ReadFlag = 1 << 2
)
type Reader struct {
Folder string
Flags ReadFlag
StartPos int64
EndPos int64
LimitChunks int
cipher Cipher
decompressor Decompressor
metadb MetaDB
logger *zap.Logger
}
func NewReader(folder string, cipher Cipher, decompressor Decompressor, meta MetaDB, logger *zap.Logger) *Reader {
return &Reader{
Folder: folder,
Flags: RF_LoadBuffer,
StartPos: 0,
EndPos: 0,
LimitChunks: 0,
cipher: cipher,
decompressor: decompressor,
metadb: meta,
logger: logger,
}
}
type ReaderInfo struct {
// can be used to convert to file name
ChunkPos int64
// global start pos
StartPos int64
// global read pos
NextPos int64
}
type ReadOp func(pos *ReaderInfo, data []byte) error
func (r *Reader) Scan(op ReadOp) error {
var err error
loadBuffer := (r.Flags & RF_LoadBuffer) == RF_LoadBuffer
printChunks := (r.Flags & RF_PrintChunks) == RF_PrintChunks
b, err := r.metadb.GetBuffer()
if err != nil {
return err
}
chunks, err := r.metadb.ListChunks()
if err != nil {
return err
}
if err != nil {
return errors.Wrap(err, "db.Read")
}
if b == nil && len(chunks) == 0 {
return nil
}
info := &ReaderInfo{}
if len(chunks) > 0 {
if r.LimitChunks > 0 && len(chunks) > r.LimitChunks {
chunks = chunks[:r.LimitChunks]
}
for i, c := range chunks {
endPos := c.StartPos + c.UncompressedByteSize
if r.StartPos != 0 && endPos < r.StartPos {
// skip chunk if it ends before range we are interested in
continue
}
if r.EndPos != 0 && c.StartPos > r.EndPos {
// skip the chunk if it starts after the range we are interested in
continue
}
chunk := make([]byte, c.UncompressedByteSize)
var file = path.Join(r.Folder, c.FileName)
if printChunks {
r.logger.Info("Loading chunk %d %s with size %d",
zap.Int("CHUNK", i),
zap.String("FILENAME", c.FileName),
zap.Int64("UNCOMPRESSED SIZE", c.UncompressedByteSize))
}
if chunk, err = r.loadChunkIntoBuffer(file, c.UncompressedByteSize, chunk); err != nil {
return errors.Wrapf(err, "failed to load chunk %s", c.FileName)
}
info.ChunkPos = c.StartPos
chunkPos := 0
if r.StartPos != 0 && r.StartPos > c.StartPos {
// reader starts in the middle
chunkPos = int(r.StartPos - c.StartPos)
}
if err = replayChunk(info, chunk, op, chunkPos); err != nil {
return errors.Wrap(err, "Failed to read chunk")
}
}
}
if loadBuffer && b != nil && b.Pos > 0 {
if r.EndPos != 0 && b.StartPos > r.EndPos {
// if buffer starts after the end of our search interval - skip it
return nil
}
loc := path.Join(r.Folder, b.FileName)
var f *os.File
if f, err = os.Open(loc); err != nil {
return errors.Wrapf(err, "failed to open buffer file %s", loc)
}
curChunk := make([]byte, b.Pos)
var n int
if n, err = f.Read(curChunk); err != nil {
return errors.Wrapf(err, "failed to read %d bytes from buffer %s", b.Pos, loc)
}
if n != int(b.Pos) {
return errors.New("failed to read bytes")
}
info.ChunkPos = b.StartPos
chunkPos := 0
if r.StartPos > b.StartPos {
chunkPos = int(r.StartPos - b.StartPos)
}
if err = replayChunk(info, curChunk, op, chunkPos); err != nil {
return errors.Wrap(err, "failed to read chunk")
}
}
return nil
}
func readVarint(b []byte) (val int64, n int, err error) {
val, n = binary.Varint(b)
if n <= 0 {
err = errors.Errorf("failed to read varint %d", n)
}
return
}
func replayChunk(info *ReaderInfo, chunk []byte, op ReadOp, pos int) error {
max := len(chunk)
// while we are not at the end,
// read first len
// then pass the bytes to the op
for pos < max {
info.StartPos = int64(pos) + info.ChunkPos
recordSize, shift, err := readVarint(chunk[pos:])
if err != nil {
return errors.Cause(err)
}
// move position by the header size
pos += shift
// get chunk
record := chunk[pos : pos+int(recordSize)]
// apply chunk
pos += int(recordSize)
info.NextPos = int64(pos) + info.ChunkPos
if err = op(info, record); err != nil {
return errors.Wrap(err, "failed to execute op")
}
// shift pos
}
return nil
}
func (r Reader) loadChunkIntoBuffer(loc string, size int64, b []byte) ([]byte, error) {
var decryptor, zr io.Reader
var err error
var chunkFile *os.File
if chunkFile, err = os.Open(loc); err != nil {
return nil, errors.Wrapf(err, "failed to open chunk %s", loc)
}
defer chunkFile.Close()
if decryptor, err = r.cipher.Decrypt(chunkFile); err != nil {
return nil, errors.Wrapf(err, "failed to chain decryptor %s", loc)
}
zr, err = r.decompressor.Decompress(decryptor)
if err != nil {
return nil, errors.Wrapf(err, "failed to chain decompressor %s", loc)
}
var readBytes int
if readBytes, err = zr.Read(b); err != nil {
return nil, errors.Wrapf(err, "failed to read from chunk %s (%d)", loc, size)
}
if int64(readBytes) != size {
return nil, errors.Errorf("read %d bytes but expected %d", readBytes, size)
}
return b[0:readBytes], nil
}