forked from hypermodeinc/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchunk.go
424 lines (381 loc) · 10.3 KB
/
chunk.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
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
/*
* Copyright 2018 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package chunker
import (
"bufio"
"bytes"
"compress/gzip"
encjson "encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"unicode"
"github.com/dgraph-io/dgraph/ee/enc"
"github.com/dgraph-io/dgraph/lex"
"github.com/dgraph-io/dgraph/x"
"github.com/pkg/errors"
)
// Chunker describes the interface to parse and process the input to the live and bulk loaders.
type Chunker interface {
Chunk(r *bufio.Reader) (*bytes.Buffer, error)
Parse(chunkBuf *bytes.Buffer) error
NQuads() *NQuadBuffer
}
type rdfChunker struct {
lexer *lex.Lexer
nqs *NQuadBuffer
}
func (rc *rdfChunker) NQuads() *NQuadBuffer {
return rc.nqs
}
type jsonChunker struct {
nqs *NQuadBuffer
inList bool
}
func (jc *jsonChunker) NQuads() *NQuadBuffer {
return jc.nqs
}
// InputFormat represents the multiple formats supported by Chunker.
type InputFormat byte
const (
// UnknownFormat is a constant to denote a format not supported by the bulk/live loaders.
UnknownFormat InputFormat = iota
// RdfFormat is a constant to denote the input to the live/bulk loader is in the RDF format.
RdfFormat
// JsonFormat is a constant to denote the input to the live/bulk loader is in the JSON format.
JsonFormat
)
// NewChunker returns a new chunker for the specified format.
func NewChunker(inputFormat InputFormat, batchSize int) Chunker {
switch inputFormat {
case RdfFormat:
return &rdfChunker{
nqs: NewNQuadBuffer(batchSize),
lexer: &lex.Lexer{},
}
case JsonFormat:
return &jsonChunker{
nqs: NewNQuadBuffer(batchSize),
}
default:
x.Panic(errors.New("unknown input format"))
return nil
}
}
// Chunk reads the input line by line until one of the following 3 conditions happens
// 1) the EOF is reached
// 2) 1e5 lines have been read
// 3) some unexpected error happened
func (*rdfChunker) Chunk(r *bufio.Reader) (*bytes.Buffer, error) {
batch := new(bytes.Buffer)
batch.Grow(1 << 20)
for lineCount := 0; lineCount < 1e5; lineCount++ {
slc, err := r.ReadSlice('\n')
if err == io.EOF {
if _, err := batch.Write(slc); err != nil {
return nil, err
}
return batch, err
}
if err == bufio.ErrBufferFull {
// This should only happen infrequently.
if _, err := batch.Write(slc); err != nil {
return nil, err
}
var str string
str, err = r.ReadString('\n')
if err == io.EOF {
if _, err := batch.WriteString(str); err != nil {
return nil, err
}
return batch, err
}
if err != nil {
return nil, err
}
if _, err := batch.WriteString(str); err != nil {
return nil, err
}
continue
}
if err != nil {
return nil, err
}
if _, err := batch.Write(slc); err != nil {
return nil, err
}
}
return batch, nil
}
// Parse is not thread-safe. Only call it serially, because it reuses lexer object.
func (rc *rdfChunker) Parse(chunkBuf *bytes.Buffer) error {
if chunkBuf == nil || chunkBuf.Len() == 0 {
return nil
}
for chunkBuf.Len() > 0 {
str, err := chunkBuf.ReadString('\n')
if err != nil && err != io.EOF {
x.Check(err)
}
nq, err := ParseRDF(str, rc.lexer)
switch {
case err == ErrEmpty:
continue // blank line or comment
case err != nil:
return errors.Wrapf(err, "while parsing line %q", str)
default:
rc.nqs.Push(&nq)
}
}
return nil
}
// Chunk tries to consume multiple top-level maps from the reader until a size threshold is
// reached, or the end of file is reached.
func (jc *jsonChunker) Chunk(r *bufio.Reader) (*bytes.Buffer, error) {
ch, err := jc.nextRune(r)
if err != nil {
return nil, err
}
// If the file starts with a list rune [, we set the inList flag, and keep consuming maps
// until we reach the threshold.
switch {
case ch == '[':
jc.inList = true
case ch == '{':
// put the rune back for it to be consumed in the consumeMap function
if err := r.UnreadRune(); err != nil {
return nil, err
}
default:
return nil, errors.Errorf("file is not JSON")
}
out := new(bytes.Buffer)
if _, err := out.WriteRune('['); err != nil {
return nil, err
}
hasMapsBefore := false
for out.Len() < 1e5 {
if hasMapsBefore {
if _, err := out.WriteRune(','); err != nil {
return nil, err
}
}
if err := jc.consumeMap(r, out); err != nil {
return nil, err
}
hasMapsBefore = true
// handle the legal termination cases, by checking the next rune after the map
ch, err := jc.nextRune(r)
if err == io.EOF {
// handles the EOF case, return the buffer which represents the top level map
if jc.inList {
return nil, errors.Errorf("JSON file ends abruptly, expecting ]")
}
if _, err := out.WriteRune(']'); err != nil {
return nil, err
}
return out, io.EOF
} else if err != nil {
return nil, err
}
if ch == ']' {
if !jc.inList {
return nil, errors.Errorf("JSON map is followed by an extraneous ]")
}
// validate that there are no more non-space chars after the ]
if slurpSpace(r) != io.EOF {
return nil, errors.New("Not all of JSON file consumed")
}
if _, err := out.WriteRune(']'); err != nil {
return nil, err
}
return out, io.EOF
}
// In the non termination cases, ensure at least one map has been consumed, and
// the only allowed char after the map is ",".
if out.Len() == 1 { // 1 represents the [ inserted before the for loop
return nil, errors.Errorf("Illegal rune found \"%c\", expecting {", ch)
}
if ch != ',' {
return nil, errors.Errorf("JSON map is followed by illegal rune \"%c\"", ch)
}
}
if _, err := out.WriteRune(']'); err != nil {
return nil, err
}
return out, nil
}
// consumeMap consumes the next map from the reader, and stores the result into the buffer out.
// After ignoring spaces, if the reader does not begin with {, no rune will be consumed
// from the reader.
func (jc *jsonChunker) consumeMap(r *bufio.Reader, out *bytes.Buffer) error {
// Just find the matching closing brace. Let the JSON-to-nquad parser in the mapper worry
// about whether everything in between is valid JSON or not.
depth := 0
for {
ch, err := jc.nextRune(r)
if err != nil {
return errors.New("Malformed JSON")
}
if depth == 0 && ch != '{' {
// We encountered a beginning rune that's not {,
// unread the char and return without consuming anything.
if err := r.UnreadRune(); err != nil {
return err
}
return nil
}
if _, err := out.WriteRune(ch); err != nil {
return err
}
switch ch {
case '{':
depth++
case '}':
depth--
case '"':
if err := slurpQuoted(r, out); err != nil {
return err
}
default:
// We just write the rune to out, and let the Go JSON parser do its job.
}
if depth <= 0 {
break
}
}
return nil
}
// nextRune ignores any number of spaces that may precede a rune
func (*jsonChunker) nextRune(r *bufio.Reader) (rune, error) {
if err := slurpSpace(r); err != nil {
return ' ', err
}
ch, _, err := r.ReadRune()
if err != nil {
return ' ', err
}
return ch, nil
}
func (jc *jsonChunker) Parse(chunkBuf *bytes.Buffer) error {
if chunkBuf == nil || chunkBuf.Len() == 0 {
return nil
}
return jc.nqs.ParseJSON(chunkBuf.Bytes(), SetNquads)
}
func slurpSpace(r *bufio.Reader) error {
for {
ch, _, err := r.ReadRune()
if err != nil {
return err
}
if !unicode.IsSpace(ch) {
x.Check(r.UnreadRune())
return nil
}
}
}
func slurpQuoted(r *bufio.Reader, out *bytes.Buffer) error {
for {
ch, _, err := r.ReadRune()
if err != nil {
return err
}
if _, err := out.WriteRune(ch); err != nil {
return err
}
if ch == '\\' {
// Pick one more rune.
esc, _, err := r.ReadRune()
if err != nil {
return err
}
if _, err := out.WriteRune(esc); err != nil {
return err
}
continue
}
if ch == '"' {
return nil
}
}
}
// FileReader returns an open reader on the given file. Gzip-compressed input is detected
// and decompressed automatically even without the gz extension. The key, if non-nil,
// is used to decrypt the file. The caller is responsible for calling the returned cleanup
// function when done with the reader.
func FileReader(file string, key x.Sensitive) (*bufio.Reader, func()) {
var f *os.File
var err error
if file == "-" {
f = os.Stdin
} else {
f, err = os.Open(file)
}
x.Check(err)
return StreamReader(file, key, f)
}
// StreamReader returns a bufio given a ReadCloser. The file is passed just to check for .gz files
func StreamReader(file string, key x.Sensitive, f io.ReadCloser) (
rd *bufio.Reader, cleanup func()) {
cleanup = func() { _ = f.Close() }
if filepath.Ext(file) == ".gz" {
r, err := enc.GetReader(key, f)
x.Check(err)
gzr, err := gzip.NewReader(r)
x.Check(err)
rd = bufio.NewReader(gzr)
cleanup = func() { _ = f.Close(); _ = gzr.Close() }
} else {
rd = bufio.NewReader(f)
buf, _ := rd.Peek(512)
typ := http.DetectContentType(buf)
if typ == "application/x-gzip" {
gzr, err := gzip.NewReader(rd)
x.Check(err)
rd = bufio.NewReader(gzr)
cleanup = func() { _ = f.Close(); _ = gzr.Close() }
}
}
return rd, cleanup
}
// IsJSONData returns true if the reader, which should be at the start of the stream, is reading
// a JSON stream, false otherwise.
func IsJSONData(r *bufio.Reader) (bool, error) {
buf, err := r.Peek(512)
if err != nil && err != io.EOF {
return false, err
}
de := encjson.NewDecoder(bytes.NewReader(buf))
_, err = de.Token()
return err == nil, nil
}
// DataFormat returns a file's data format (RDF, JSON, or unknown) based on the filename
// or the user-provided format option. The file extension has precedence.
func DataFormat(filename string, format string) InputFormat {
format = strings.ToLower(format)
filename = strings.TrimSuffix(strings.ToLower(filename), ".gz")
switch {
case strings.HasSuffix(filename, ".rdf") || format == "rdf":
return RdfFormat
case strings.HasSuffix(filename, ".json") || format == "json":
return JsonFormat
default:
return UnknownFormat
}
}