-
-
Notifications
You must be signed in to change notification settings - Fork 172
/
record_formatter.go
1613 lines (1490 loc) · 43.9 KB
/
record_formatter.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kgo
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
"unsafe"
)
////////////
// WRITER //
////////////
// RecordFormatter formats records.
type RecordFormatter struct {
fns []func([]byte, *FetchPartition, *Record) []byte
calls int64
}
// AppendRecord appends a record to b given the parsed format and returns the
// updated slice.
func (f *RecordFormatter) AppendRecord(b []byte, r *Record) []byte {
for _, fn := range f.fns {
b = fn(b, nil, r)
}
return b
}
// AppendPartitionRecord appends a record and partition to b given the parsed
// format and returns the updated slice.
func (f *RecordFormatter) AppendPartitionRecord(b []byte, p *FetchPartition, r *Record) []byte {
for _, fn := range f.fns {
b = fn(b, p, r)
}
return b
}
// NewRecordFormatter returns a formatter for the given layout, or an error if
// the layout is invalid.
//
// The formatter is very powerful, as such there is a lot to describe. This
// documentation attempts to be as succinct as possible.
//
// Similar to the fmt package, record formatting is based off of slash escapes
// and percent "verbs" (copying fmt package lingo). Slashes are used for common
// escapes,
//
// \t \n \r \\ \xNN
//
// printing tabs, newlines, carriage returns, slashes, and hex encoded
// characters.
//
// Percent encoding opts in to printing aspects of either a record or a fetch
// partition:
//
// %t topic
// %T topic length
// %k key
// %K key length
// %v value
// %V value length
// %h begin the header specification
// %H number of headers
// %p partition
// %o offset
// %e leader epoch
// %d timestamp (date, formatting described below)
// %x producer id
// %y producer epoch
//
// For AppendPartitionRecord, the formatter also undersands the following three
// formatting options:
//
// %[ partition log start offset
// %| partition last stable offset
// %] partition high watermark
//
// The formatter internally tracks the number of times AppendRecord or
// AppendPartitionRecord have been called. The special option %i prints the
// iteration / call count:
//
// %i format iteration number (starts at 1)
//
// Lastly, there are three escapes to print raw characters that are usually
// used for formatting options:
//
// %% percent sign
// %{ left brace (required if a brace is after another format option)
// %} right brace
//
// Header specification
//
// Specifying headers is essentially a primitive nested format option,
// accepting the key and value escapes above:
//
// %K header key length
// %k header key
// %V header value length
// %v header value
//
// For example, "%H %h{%k %v }" will print the number of headers, and then each
// header key and value with a space after each.
//
// Verb modifiers
//
// Most of the previous verb specifications can be modified by adding braces
// with a given modifier, e.g., "%V{ascii}". All modifiers are described below.
//
// Numbers
//
// All number verbs accept braces that control how the number is printed:
//
// %v{ascii} the default, print the number as ascii
//
// %v{hex64} print 16 hex characters for the number
// %v{hex32} print 8 hex characters for the number
// %v{hex16} print 4 hex characters for the number
// %v{hex8} print 2 hex characters for the number
// %v{hex4} print 1 hex characters for the number
// %v{hex} print as many hex characters as necessary for the number
//
// %v{big64} print the number in big endian uint64 format
// %v{big32} print the number in big endian uint32 format
// %v{big16} print the number in big endian uint16 format
// %v{big8} alias for byte
//
// %v{little64} print the number in little endian uint64 format
// %v{little32} print the number in little endian uint32 format
// %v{little16} print the number in little endian uint16 format
// %v{little8} alias for byte
//
// %v{byte} print the number as a single byte
//
// All numbers are truncated as necessary per each given format.
//
// Timestamps
//
// Timestamps can be specified in three formats: plain number formatting,
// native Go timestamp formatting, or strftime formatting. Number formatting is
// follows the rules above using the millisecond timestamp value. Go and
// strftime have further internal format options:
//
// %d{go##2006-01-02T15:04:05Z07:00##}
// %d{strftime[%F]}
//
// An arbitrary amount of pounds, braces, and brackets are understood before
// beginning the actual timestamp formatting. For Go formatting, the format is
// simply passed to the time package's AppendFormat function. For strftime, all
// "man strftime" options are supported. Time is always in UTC.
//
// Text
//
// Topics, keys, and values have "base64", "hex", and "unpack" formatting
// options:
//
// %t{hex}
// %k{unpack{<bBhH>iIqQc.$}}
// %v{base64}
//
// Unpack formatting is inside of enclosing pounds, braces, or brackets, the
// same way that timestamp formatting is understood. The syntax roughly follows
// Python's struct packing/unpacking rules:
//
// x pad character (does not parse input)
// < parse what follows as little endian
// > parse what follows as big endian
//
// b signed byte
// B unsigned byte
// h int16 ("half word")
// H uint16 ("half word")
// i int32
// I uint32
// q int64 ("quad word")
// Q uint64 ("quad word")
//
// c any character
// . alias for c
// s consume the rest of the input as a string
// $ match the end of the line (append error string if anything remains)
//
// Unlike python, a '<' or '>' can appear anywhere in the format string and
// affects everything that follows. It is possible to switch endianness
// multiple times. If the parser needs more data than available, or if the more
// input remains after '$', an error message will be appended.
//
func NewRecordFormatter(layout string) (*RecordFormatter, error) {
var f RecordFormatter
var literal []byte // non-formatted raw text to output
var i int
for len(layout) > 0 {
i++
c, size := utf8.DecodeRuneInString(layout)
rawc := layout[:size]
layout = layout[size:]
switch c {
default:
literal = append(literal, rawc...)
continue
case '\\':
c, n, err := parseLayoutSlash(layout)
if err != nil {
return nil, err
}
layout = layout[n:]
literal = append(literal, c)
continue
case '%':
}
if len(layout) == 0 {
return nil, errors.New("invalid escape sequence at end of layout string")
}
cNext, size := utf8.DecodeRuneInString(layout)
if cNext == '%' || cNext == '{' || cNext == '}' {
literal = append(literal, byte(cNext))
layout = layout[size:]
continue
}
var (
isOpenBrace = len(layout) > 2 && layout[1] == '{'
handledBrace bool
escaped = layout[0]
)
layout = layout[1:]
// We are entering a format string. If we have any built
// literal before, this is now raw text that we will append.
if len(literal) > 0 {
l := literal
literal = nil
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, _ *Record) []byte { return append(b, l...) })
}
if isOpenBrace { // opening a brace: layout continues after
layout = layout[1:]
}
switch escaped {
default:
return nil, fmt.Errorf("unknown escape sequence %%%s", string(escaped))
case 'T', 'K', 'V', 'H', 'p', 'o', 'e', 'i', 'x', 'y', '[', '|', ']':
// Numbers default to ascii, but we support a bunch of
// formatting options. We parse the format here, and
// then below is switching on which field to print.
var numfn func([]byte, int64) []byte
if handledBrace = isOpenBrace; handledBrace {
numfn2, n, err := parseNumWriteLayout(layout)
if err != nil {
return nil, err
}
layout = layout[n:]
numfn = numfn2
} else {
numfn = writeNumASCII
}
switch escaped {
case 'T':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, int64(len(r.Topic))) })
})
case 'K':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, int64(len(r.Key))) })
})
case 'V':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, int64(len(r.Value))) })
})
case 'H':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, int64(len(r.Headers))) })
})
case 'p':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, int64(r.Partition)) })
})
case 'o':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, r.Offset) })
})
case 'e':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, int64(r.LeaderEpoch)) })
})
case 'i':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, _ *Record) []byte {
return numfn(b, atomic.AddInt64(&f.calls, 1))
})
case 'x':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, r.ProducerID) })
})
case 'y':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, int64(r.ProducerEpoch)) })
})
case '[':
f.fns = append(f.fns, func(b []byte, p *FetchPartition, _ *Record) []byte {
return writeP(b, p, func(b []byte, p *FetchPartition) []byte { return numfn(b, p.LogStartOffset) })
})
case '|':
f.fns = append(f.fns, func(b []byte, p *FetchPartition, _ *Record) []byte {
return writeP(b, p, func(b []byte, p *FetchPartition) []byte { return numfn(b, p.LastStableOffset) })
})
case ']':
f.fns = append(f.fns, func(b []byte, p *FetchPartition, _ *Record) []byte {
return writeP(b, p, func(b []byte, p *FetchPartition) []byte { return numfn(b, p.HighWatermark) })
})
}
case 't', 'k', 'v':
var appendFn func([]byte, []byte) []byte
if handledBrace = isOpenBrace; handledBrace {
switch {
case strings.HasPrefix(layout, "base64}"):
appendFn = appendBase64
layout = layout[len("base64}"):]
case strings.HasPrefix(layout, "hex}"):
appendFn = appendHex
layout = layout[len("hex}"):]
case strings.HasPrefix(layout, "unpack"):
unpack, rem, err := nomOpenClose(layout[len("unpack"):])
if err != nil {
return nil, fmt.Errorf("unpack parse err: %v", err)
}
if len(rem) == 0 || rem[0] != '}' {
return nil, fmt.Errorf("unpack missing closing } in %q", layout)
}
layout = rem[1:]
appendFn, err = parseUnpack(unpack)
if err != nil {
return nil, fmt.Errorf("unpack formatting parse err: %v", err)
}
default:
return nil, fmt.Errorf("unknown %%%s{ escape", string(escaped))
}
} else {
appendFn = appendPlain
}
switch escaped {
case 't':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return appendFn(b, []byte(r.Topic)) })
})
case 'k':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return appendFn(b, r.Key) })
})
case 'v':
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return appendFn(b, r.Value) })
})
}
case 'h':
if !isOpenBrace {
return nil, errors.New("missing open brace sequence on %h signifying how headers are written")
}
handledBrace = true
// Headers can have their own internal braces, so we
// must look for a matching end brace.
braces := 1
at := 0
for braces != 0 && len(layout[at:]) > 0 {
switch layout[at] {
case '{':
if at > 0 && layout[at-1] != '%' {
braces++
}
case '}':
if at > 0 && layout[at-1] != '%' {
braces--
}
}
at++
}
if braces > 0 {
return nil, fmt.Errorf("invalid header specification: missing closing brace in %q", layout)
}
spec := layout[:at-1]
layout = layout[at:]
inf, err := NewRecordFormatter(spec)
if err != nil {
return nil, fmt.Errorf("invalid header specification %q: %v", spec, err)
}
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
reuse := new(Record)
for _, header := range r.Headers {
reuse.Key = []byte(header.Key)
reuse.Value = header.Value
b = inf.AppendRecord(b, reuse)
}
return b
})
case 'd':
// For datetime parsing, we support plain millis in any
// number format, strftime, or go formatting. We
// default to plain ascii millis.
handledBrace = isOpenBrace
if !handledBrace {
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return strconv.AppendInt(b, r.Timestamp.UnixNano()/1e6, 10) })
})
continue
}
switch {
case strings.HasPrefix(layout, "strftime"):
tfmt, rem, err := nomOpenClose(layout[len("strftime"):])
if err != nil {
return nil, fmt.Errorf("strftime parse err: %v", err)
}
if len(rem) == 0 || rem[0] != '}' {
return nil, fmt.Errorf("%%d{strftime missing closing } in %q", layout)
}
layout = rem[1:]
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return strftimeAppendFormat(b, tfmt, r.Timestamp.UTC()) })
})
case strings.HasPrefix(layout, "go"):
tfmt, rem, err := nomOpenClose(layout[len("go"):])
if err != nil {
return nil, fmt.Errorf("go parse err: %v", err)
}
if len(rem) == 0 || rem[0] != '}' {
return nil, fmt.Errorf("%%d{go missing closing } in %q", layout)
}
layout = rem[1:]
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return r.Timestamp.UTC().AppendFormat(b, tfmt) })
})
default:
numfn, n, err := parseNumWriteLayout(layout)
if err != nil {
return nil, fmt.Errorf("unknown %%d{ time specification in %q", layout)
}
layout = layout[n:]
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, r *Record) []byte {
return writeR(b, r, func(b []byte, r *Record) []byte { return numfn(b, r.Timestamp.UnixNano()/1e6) })
})
}
}
// If we opened a brace, we require a closing brace.
if isOpenBrace && !handledBrace {
return nil, fmt.Errorf("unhandled open brace %q", layout)
}
}
// Ensure we print any trailing text.
if len(literal) > 0 {
f.fns = append(f.fns, func(b []byte, _ *FetchPartition, _ *Record) []byte { return append(b, literal...) })
}
return &f, nil
}
func appendPlain(dst, src []byte) []byte {
return append(dst, src...)
}
func appendBase64(dst, src []byte) []byte {
fin := append(dst, make([]byte, base64.RawStdEncoding.EncodedLen(len(src)))...)
base64.RawStdEncoding.Encode(fin[len(dst):], src)
return fin
}
func appendHex(dst, src []byte) []byte {
fin := append(dst, make([]byte, hex.EncodedLen(len(src)))...)
hex.Encode(fin[len(dst):], src)
return fin
}
// nomOpenClose extracts a middle section from a string beginning with repeated
// delimiters and returns it as with remaining (past end delimiters) string.
func nomOpenClose(src string) (middle, remaining string, err error) {
if len(src) == 0 {
return "", "", errors.New("empty layout")
}
delim := src[0]
openers := 1
for openers < len(src) && src[openers] == delim {
openers++
}
switch delim {
case '{':
delim = '}'
case '[':
delim = ']'
case '(':
delim = ')'
}
src = src[openers:]
end := strings.Repeat(string(delim), openers)
idx := strings.Index(src, end)
if idx < 0 {
return "", "", fmt.Errorf("missing end delim %q", end)
}
middle = src[:idx]
return middle, src[idx+len(end):], nil
}
func parseUnpack(layout string) (func([]byte, []byte) []byte, error) {
// take dst, src; return dst
// %!q(eof)
// take 8 bytes, decode it, print decoded
var fns []func([]byte, []byte) ([]byte, int)
little := true
var sawEnd bool
for i := range layout {
if sawEnd {
return nil, errors.New("already saw end-of-input parsing character")
}
var need int
var signed bool
cs := layout[i : i+1]
switch cs[0] {
case 'x':
continue
case '<':
little = true
continue
case '>':
little = false
continue
case 'b':
need = 1
signed = true
case 'B':
need = 1
case 'h':
need = 2
signed = true
case 'H':
need = 2
case 'i':
need = 4
signed = true
case 'I':
need = 4
case 'q':
need = 8
signed = true
case 'Q':
need = 8
case 'c', '.':
fns = append(fns, func(dst, src []byte) ([]byte, int) {
if len(src) < 1 {
return append(dst, "%!c(no bytes available)"...), 0
}
return append(dst, src[0]), 1
})
continue
case 's':
sawEnd = true
fns = append(fns, func(dst, src []byte) ([]byte, int) {
return append(dst, src...), len(src)
})
continue
case '$':
fns = append(fns, func(dst, src []byte) ([]byte, int) {
if len(src) != 0 {
dst = append(dst, "%!$(not end-of-input)"...)
}
return dst, len(src)
})
sawEnd = true
continue
default:
return nil, fmt.Errorf("invalid unpack parsing character %s", cs)
}
islittle := little
fns = append(fns, func(dst, src []byte) ([]byte, int) {
if len(src) < need {
return append(dst, fmt.Sprintf("%%!%%s(have %d bytes, need %d)", len(src), need)...), len(src)
}
var ul, ub uint64
var il, ib int64
switch need {
case 1:
ul = uint64(src[0])
ub = ul
il = int64(byte(ul))
ib = int64(byte(ub))
case 2:
ul = uint64(binary.LittleEndian.Uint16(src))
ub = uint64(binary.BigEndian.Uint16(src))
il = int64(int16(ul))
ib = int64(int16(ub))
case 4:
ul = uint64(binary.LittleEndian.Uint32(src))
ub = uint64(binary.BigEndian.Uint32(src))
il = int64(int32(ul))
ib = int64(int32(ub))
case 8:
ul = binary.LittleEndian.Uint64(src)
ub = binary.BigEndian.Uint64(src)
il = int64(ul)
ib = int64(ub)
}
u := ub
i := ib
if islittle {
u = ul
i = il
}
if signed {
return strconv.AppendInt(dst, i, 10), need
}
return strconv.AppendUint(dst, u, 10), need
})
}
return func(dst, src []byte) []byte {
for _, fn := range fns {
var n int
dst, n = fn(dst, src)
src = src[n:]
}
return dst
}, nil
}
func parseNumWriteLayout(layout string) (func([]byte, int64) []byte, int, error) {
braceEnd := strings.IndexByte(layout, '}')
if braceEnd == -1 {
return nil, 0, errors.New("missing brace end } to close number format specification")
}
end := braceEnd + 1
switch layout = layout[:braceEnd]; layout {
case "ascii":
return writeNumASCII, end, nil
case "hex64":
return writeNumHex64, end, nil
case "hex32":
return writeNumHex32, end, nil
case "hex16":
return writeNumHex16, end, nil
case "hex8":
return writeNumHex8, end, nil
case "hex4":
return writeNumHex4, end, nil
case "hex":
return writeNumHex, end, nil
case "big64":
return writeNumBig64, end, nil
case "big32":
return writeNumBig32, end, nil
case "big16":
return writeNumBig16, end, nil
case "byte", "big8", "little8":
return writeNumByte, end, nil
case "little64":
return writeNumLittle64, end, nil
case "little32":
return writeNumLittle32, end, nil
case "little16":
return writeNumLittle16, end, nil
default:
return nil, 0, fmt.Errorf("invalid output number layout %q", layout)
}
}
func writeR(b []byte, r *Record, fn func([]byte, *Record) []byte) []byte {
if r == nil {
return append(b, "<nil>"...)
}
return fn(b, r)
}
func writeP(b []byte, p *FetchPartition, fn func([]byte, *FetchPartition) []byte) []byte {
if p == nil {
return append(b, "<nil>"...)
}
return fn(b, p)
}
func writeNumASCII(b []byte, n int64) []byte { return strconv.AppendInt(b, n, 10) }
const hexc = "0123456789abcdef"
func writeNumHex64(b []byte, n int64) []byte {
u := uint64(n)
return append(b,
hexc[(u>>60)&0xf],
hexc[(u>>56)&0xf],
hexc[(u>>52)&0xf],
hexc[(u>>48)&0xf],
hexc[(u>>44)&0xf],
hexc[(u>>40)&0xf],
hexc[(u>>36)&0xf],
hexc[(u>>32)&0xf],
hexc[(u>>28)&0xf],
hexc[(u>>24)&0xf],
hexc[(u>>20)&0xf],
hexc[(u>>16)&0xf],
hexc[(u>>12)&0xf],
hexc[(u>>8)&0xf],
hexc[(u>>4)&0xf],
hexc[u&0xf],
)
}
func writeNumHex32(b []byte, n int64) []byte {
u := uint64(n)
return append(b,
hexc[(u>>28)&0xf],
hexc[(u>>24)&0xf],
hexc[(u>>20)&0xf],
hexc[(u>>16)&0xf],
hexc[(u>>12)&0xf],
hexc[(u>>8)&0xf],
hexc[(u>>4)&0xf],
hexc[u&0xf],
)
}
func writeNumHex16(b []byte, n int64) []byte {
u := uint64(n)
return append(b,
hexc[(u>>12)&0xf],
hexc[(u>>8)&0xf],
hexc[(u>>4)&0xf],
hexc[u&0xf],
)
}
func writeNumHex8(b []byte, n int64) []byte {
u := uint64(n)
return append(b,
hexc[(u>>4)&0xf],
hexc[u&0xf],
)
}
func writeNumHex4(b []byte, n int64) []byte {
u := uint64(n)
return append(b,
hexc[u&0xf],
)
}
func writeNumHex(b []byte, n int64) []byte {
return strconv.AppendUint(b, uint64(n), 16)
}
func writeNumBig64(b []byte, n int64) []byte {
u := uint64(n)
return append(b, byte(u>>56), byte(u>>48), byte(u>>40), byte(u>>32), byte(u>>24), byte(u>>16), byte(u>>8), byte(u))
}
func writeNumLittle64(b []byte, n int64) []byte {
u := uint64(n)
return append(b, byte(u), byte(u>>8), byte(u>>16), byte(u>>24), byte(u>>32), byte(u>>40), byte(u>>48), byte(u>>56))
}
func writeNumBig32(b []byte, n int64) []byte {
u := uint64(n)
return append(b, byte(u>>24), byte(u>>16), byte(u>>8), byte(u))
}
func writeNumLittle32(b []byte, n int64) []byte {
u := uint64(n)
return append(b, byte(u), byte(u>>8), byte(u>>16), byte(u>>24))
}
func writeNumBig16(b []byte, n int64) []byte { u := uint64(n); return append(b, byte(u>>8), byte(u)) }
func writeNumLittle16(b []byte, n int64) []byte {
u := uint64(n)
return append(b, byte(u), byte(u>>8))
}
func writeNumByte(b []byte, n int64) []byte { u := uint64(n); return append(b, byte(u)) }
////////////
// READER //
////////////
// RecordReader reads records from an io.Reader.
type RecordReader struct {
r *bufio.Reader
buf []byte
fns []readParse
done bool
}
// NewRecordReader returns a record reader for the given layout, or an error if
// the layout is invalid.
//
// Similar to the RecordFormatter, the RecordReader parsing is quite powerful.
// There is a bit less to describe in comparison to RecordFormatter, but still,
// this documentation attempts to be as succinct as possible.
//
// Similar to the fmt package, record parsing is based off of slash escapes and
// percent "verbs" (copying fmt package lingo). Slashes are used for common
// escapes,
//
// \t \n \r \\ \xNN
//
// reading tabs, newlines, carriage returns, slashes, and hex encoded
// characters.
//
// Percent encoding reads into specific values of a Record:
//
// %t topic
// %T topic length
// %k key
// %K key length
// %v value
// %V value length
// %h begin the header specification
// %H number of headers
// %p partition
// %o offset
// %e leader epoch
// %d timestamp
// %x producer id
// %y producer epoch
//
// If using length / number verbs (i.e., "sized" verbs), they must occur before
// what they are sizing.
//
// There are three escapes to parse raw characters, rather than opting into
// some formatting option:
//
// %% percent sign
// %{ left brace
// %} right brace
//
// Unlike record formatting, timestamps can only be read as numbers because Go
// or strftime formatting can both be variable length and do not play too well
// with delimiters. Timestamps numbers are read as milliseconds.
//
// Numbers
//
// All size numbers can be parsed in the following ways:
//
// %v{ascii} parse numeric digits until a non-numeric
//
// %v{hex64} read 16 hex characters for the number
// %v{hex32} read 8 hex characters for the number
// %v{hex16} read 4 hex characters for the number
// %v{hex8} read 2 hex characters for the number
// %v{hex4} read 1 hex characters for the number
//
// %v{big64} read the number as big endian uint64 format
// %v{big32} read the number as big endian uint32 format
// %v{big16} read the number as big endian uint16 format
// %v{big8} alias for byte
//
// %v{little64} read the number as little endian uint64 format
// %v{little32} read the number as little endian uint32 format
// %v{little16} read the number as little endian uint16 format
// %v{little8} read the number as a byte
//
// %v{byte} read the number as a byte
//
// %v{3} read 3 characters (any number)
//
// Header specification
//
// Similar to number formatting, headers are parsed using a nested primitive
// format option, accepting the key and value escapes previously mentioned.
//
// Text
//
// Topics, keys, and values can be decoded uding "base64" and "hex" formatting
// options. Any size specification is the size of the encoded value actually
// being read.
//
// %T%t{hex} - 4abcd reads four hex characters "abcd"
// %V%v{base64} - 2z9 reads two base64 characters "z9"
//
// As well, these text options can be parsed with regular expressions:
//
// %k{re[\d*]}%v{re[\s+]}
//
func NewRecordReader(reader io.Reader, layout string) (*RecordReader, error) {
r := &RecordReader{r: bufio.NewReader(reader)}
if err := r.parseReadLayout(layout); err != nil {
return nil, err
}
return r, nil
}
// ReadRecord reads the next record in the reader and returns it, or returns a
// parsing error.
//
// This will return io.EOF only if the underlying reader returns io.EOF at the
// start of a new record. If an io.EOF is returned mid record, this returns
// io.ErrUnexpectedEOF. It is expected for this function to be called until it
// returns io.EOF.
func (r *RecordReader) ReadRecord() (*Record, error) {
rec := new(Record)
return rec, r.ReadRecordInto(rec)
}
// ReadRecordInto reads the next record into the given record and returns any
// parsing error
//
// This will return io.EOF only if the underlying reader returns io.EOF at the
// start of a new record. If an io.EOF is returned mid record, this returns
// io.ErrUnexpectedEOF. It is expected for this function to be called until it
// returns io.EOF.
func (r *RecordReader) ReadRecordInto(rec *Record) error {
if r.done {
return io.EOF
}
return r.next(rec)
}
// SetReader replaces the underlying reader with the given reader.
func (r *RecordReader) SetReader(reader io.Reader) {
r.r = bufio.NewReader(reader)
r.done = false
}
const (
parsesTopic parseRecordBits = 1 << iota
parsesTopicSize
parsesKey
parsesKeySize
parsesValue
parsesValueSize
parsesHeaders
parsesHeadersNum
)
// The record reading format must be either entirely sized or entirely unsized.
// This type helps us track what's what.
type parseRecordBits uint8
func (p *parseRecordBits) set(r parseRecordBits) { *p |= r }
func (p parseRecordBits) has(r parseRecordBits) bool { return p&r != 0 }
func (r *RecordReader) parseReadLayout(layout string) error {
if len(layout) == 0 {
return errors.New("RecordReader: invalid empty format")
}
var (
// If we are reading by size, we parse the layout size into one
// of these variables. When reading, we use the captured
// variable's value.
topicSize = new(uint64)
keySize = new(uint64)
valueSize = new(uint64)
headersNum = new(uint64)
bits parseRecordBits
literal []byte // raw literal we are currently working on
addLiteral = func() {
if len(r.fns) > 0 && r.fns[len(r.fns)-1].read.empty() {
r.fns[len(r.fns)-1].read.delim = literal
} else if len(literal) > 0 {
r.fns = append(r.fns, readParse{
read: readKind{exact: literal},
})
}
literal = nil
}
)
for len(layout) > 0 {
c, size := utf8.DecodeRuneInString(layout)