forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 59
/
frame.go
2103 lines (1744 loc) · 45.6 KB
/
frame.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
// Copyright (c) 2012 The gocql Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gocql
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"runtime"
"strings"
"time"
)
type unsetColumn struct{}
// UnsetValue represents a value used in a query binding that will be ignored by Cassandra.
//
// By setting a field to the unset value Cassandra will ignore the write completely.
// The main advantage is the ability to keep the same prepared statement even when you don't
// want to update some fields, where before you needed to make another prepared statement.
//
// UnsetValue is only available when using the version 4 of the protocol.
var UnsetValue = unsetColumn{}
type namedValue struct {
name string
value interface{}
}
// NamedValue produce a value which will bind to the named parameter in a query
func NamedValue(name string, value interface{}) interface{} {
return &namedValue{
name: name,
value: value,
}
}
const (
protoDirectionMask = 0x80
protoVersionMask = 0x7F
protoVersion1 = 0x01
protoVersion2 = 0x02
protoVersion3 = 0x03
protoVersion4 = 0x04
protoVersion5 = 0x05
maxFrameSize = 256 * 1024 * 1024
)
type protoVersion byte
func (p protoVersion) request() bool {
return p&protoDirectionMask == 0x00
}
func (p protoVersion) response() bool {
return p&protoDirectionMask == 0x80
}
func (p protoVersion) version() byte {
return byte(p) & protoVersionMask
}
func (p protoVersion) String() string {
dir := "REQ"
if p.response() {
dir = "RESP"
}
return fmt.Sprintf("[version=%d direction=%s]", p.version(), dir)
}
type frameOp byte
const (
// header ops
opError frameOp = 0x00
opStartup frameOp = 0x01
opReady frameOp = 0x02
opAuthenticate frameOp = 0x03
opOptions frameOp = 0x05
opSupported frameOp = 0x06
opQuery frameOp = 0x07
opResult frameOp = 0x08
opPrepare frameOp = 0x09
opExecute frameOp = 0x0A
opRegister frameOp = 0x0B
opEvent frameOp = 0x0C
opBatch frameOp = 0x0D
opAuthChallenge frameOp = 0x0E
opAuthResponse frameOp = 0x0F
opAuthSuccess frameOp = 0x10
)
func (f frameOp) String() string {
switch f {
case opError:
return "ERROR"
case opStartup:
return "STARTUP"
case opReady:
return "READY"
case opAuthenticate:
return "AUTHENTICATE"
case opOptions:
return "OPTIONS"
case opSupported:
return "SUPPORTED"
case opQuery:
return "QUERY"
case opResult:
return "RESULT"
case opPrepare:
return "PREPARE"
case opExecute:
return "EXECUTE"
case opRegister:
return "REGISTER"
case opEvent:
return "EVENT"
case opBatch:
return "BATCH"
case opAuthChallenge:
return "AUTH_CHALLENGE"
case opAuthResponse:
return "AUTH_RESPONSE"
case opAuthSuccess:
return "AUTH_SUCCESS"
default:
return fmt.Sprintf("UNKNOWN_OP_%d", f)
}
}
const (
// result kind
resultKindVoid = 1
resultKindRows = 2
resultKindKeyspace = 3
resultKindPrepared = 4
resultKindSchemaChanged = 5
// rows flags
flagGlobalTableSpec int = 0x01
flagHasMorePages int = 0x02
flagNoMetaData int = 0x04
// query flags
flagValues byte = 0x01
flagSkipMetaData byte = 0x02
flagPageSize byte = 0x04
flagWithPagingState byte = 0x08
flagWithSerialConsistency byte = 0x10
flagDefaultTimestamp byte = 0x20
flagWithNameValues byte = 0x40
flagWithKeyspace byte = 0x80
// prepare flags
flagWithPreparedKeyspace uint32 = 0x01
// header flags
flagCompress byte = 0x01
flagTracing byte = 0x02
flagCustomPayload byte = 0x04
flagWarning byte = 0x08
flagBetaProtocol byte = 0x10
)
// DEPRECATED use Consistency type, SerialConsistency is now an alias for backwards compatibility.
type SerialConsistency = Consistency
type Consistency uint16
const (
Any Consistency = 0x00
One Consistency = 0x01
Two Consistency = 0x02
Three Consistency = 0x03
Quorum Consistency = 0x04
All Consistency = 0x05
LocalQuorum Consistency = 0x06
EachQuorum Consistency = 0x07
Serial Consistency = 0x08
LocalSerial Consistency = 0x09
LocalOne Consistency = 0x0A
)
func (c Consistency) String() string {
switch c {
case Any:
return "ANY"
case One:
return "ONE"
case Two:
return "TWO"
case Three:
return "THREE"
case Quorum:
return "QUORUM"
case All:
return "ALL"
case LocalQuorum:
return "LOCAL_QUORUM"
case EachQuorum:
return "EACH_QUORUM"
case Serial:
return "SERIAL"
case LocalSerial:
return "LOCAL_SERIAL"
case LocalOne:
return "LOCAL_ONE"
default:
return fmt.Sprintf("UNKNOWN_CONS_0x%x", uint16(c))
}
}
func (c Consistency) IsSerial() bool {
return c == Serial || c == LocalSerial
}
func (c Consistency) MarshalText() (text []byte, err error) {
return []byte(c.String()), nil
}
func (c *Consistency) UnmarshalText(text []byte) error {
switch string(text) {
case "ANY":
*c = Any
case "ONE":
*c = One
case "TWO":
*c = Two
case "THREE":
*c = Three
case "QUORUM":
*c = Quorum
case "ALL":
*c = All
case "LOCAL_QUORUM":
*c = LocalQuorum
case "EACH_QUORUM":
*c = EachQuorum
case "SERIAL":
*c = Serial
case "LOCAL_SERIAL":
*c = LocalSerial
case "LOCAL_ONE":
*c = LocalOne
default:
return fmt.Errorf("invalid consistency %q", string(text))
}
return nil
}
func ParseConsistency(s string) Consistency {
var c Consistency
if err := c.UnmarshalText([]byte(strings.ToUpper(s))); err != nil {
panic(err)
}
return c
}
// ParseConsistencyWrapper wraps gocql.ParseConsistency to provide an err
// return instead of a panic
func ParseConsistencyWrapper(s string) (consistency Consistency, err error) {
err = consistency.UnmarshalText([]byte(strings.ToUpper(s)))
return
}
// MustParseConsistency is the same as ParseConsistency except it returns
// an error (never). It is kept here since breaking changes are not good.
// DEPRECATED: use ParseConsistency if you want a panic on parse error.
func MustParseConsistency(s string) (Consistency, error) {
c, err := ParseConsistencyWrapper(s)
if err != nil {
panic(err)
}
return c, nil
}
const (
apacheCassandraTypePrefix = "org.apache.cassandra.db.marshal."
)
var (
ErrFrameTooBig = errors.New("frame length is bigger than the maximum allowed")
)
const maxFrameHeaderSize = 9
func readInt(p []byte) int32 {
return int32(p[0])<<24 | int32(p[1])<<16 | int32(p[2])<<8 | int32(p[3])
}
type frameHeader struct {
version protoVersion
flags byte
stream int
op frameOp
length int
warnings []string
}
func (f frameHeader) String() string {
return fmt.Sprintf("[header version=%s flags=0x%x stream=%d op=%s length=%d]", f.version, f.flags, f.stream, f.op, f.length)
}
func (f frameHeader) Header() frameHeader {
return f
}
const defaultBufSize = 128
type ObservedFrameHeader struct {
Version protoVersion
Flags byte
Stream int16
Opcode frameOp
Length int32
// StartHeader is the time we started reading the frame header off the network connection.
Start time.Time
// EndHeader is the time we finished reading the frame header off the network connection.
End time.Time
// Host is Host of the connection the frame header was read from.
Host *HostInfo
}
func (f ObservedFrameHeader) String() string {
return fmt.Sprintf("[observed header version=%s flags=0x%x stream=%d op=%s length=%d]", f.Version, f.Flags, f.Stream, f.Opcode, f.Length)
}
// FrameHeaderObserver is the interface implemented by frame observers / stat collectors.
//
// Experimental, this interface and use may change
type FrameHeaderObserver interface {
// ObserveFrameHeader gets called on every received frame header.
ObserveFrameHeader(context.Context, ObservedFrameHeader)
}
// a framer is responsible for reading, writing and parsing frames on a single stream
type framer struct {
proto byte
// flags are for outgoing flags, enabling compression and tracing etc
flags byte
compres Compressor
headSize int
// if this frame was read then the header will be here
header *frameHeader
// if tracing flag is set this is not nil
traceID []byte
// holds a ref to the whole byte slice for buf so that it can be reset to
// 0 after a read.
readBuffer []byte
buf []byte
customPayload map[string][]byte
flagLWT int
rateLimitingErrorCode int
tabletsRoutingV1 bool
}
func newFramer(compressor Compressor, version byte) *framer {
buf := make([]byte, defaultBufSize)
f := &framer{
buf: buf[:0],
readBuffer: buf,
}
var flags byte
if compressor != nil {
flags |= flagCompress
}
if version == protoVersion5 {
flags |= flagBetaProtocol
}
version &= protoVersionMask
headSize := 8
if version > protoVersion2 {
headSize = 9
}
f.compres = compressor
f.proto = version
f.flags = flags
f.headSize = headSize
f.header = nil
f.traceID = nil
f.tabletsRoutingV1 = false
return f
}
func newFramerWithExts(compressor Compressor, version byte, cqlProtoExts []cqlProtocolExtension) *framer {
f := newFramer(compressor, version)
if lwtExt := findCQLProtoExtByName(cqlProtoExts, lwtAddMetadataMarkKey); lwtExt != nil {
castedExt, ok := lwtExt.(*lwtAddMetadataMarkExt)
if !ok {
Logger.Println(
fmt.Errorf("Failed to cast CQL protocol extension identified by name %s to type %T",
lwtAddMetadataMarkKey, lwtAddMetadataMarkExt{}))
return f
}
f.flagLWT = castedExt.lwtOptMetaBitMask
}
if rateLimitErrorExt := findCQLProtoExtByName(cqlProtoExts, rateLimitError); rateLimitErrorExt != nil {
castedExt, ok := rateLimitErrorExt.(*rateLimitExt)
if !ok {
Logger.Println(
fmt.Errorf("Failed to cast CQL protocol extension identified by name %s to type %T",
rateLimitError, rateLimitExt{}))
return f
}
f.rateLimitingErrorCode = castedExt.rateLimitErrorCode
}
if tabletsExt := findCQLProtoExtByName(cqlProtoExts, tabletsRoutingV1); tabletsExt != nil {
_, ok := tabletsExt.(*tabletsRoutingV1Ext)
if !ok {
Logger.Println(
fmt.Errorf("Failed to cast CQL protocol extension identified by name %s to type %T",
tabletsRoutingV1, tabletsRoutingV1Ext{}))
return f
}
f.tabletsRoutingV1 = true
}
return f
}
type frame interface {
Header() frameHeader
}
func readHeader(r io.Reader, p []byte) (head frameHeader, err error) {
_, err = io.ReadFull(r, p[:1])
if err != nil {
return frameHeader{}, err
}
version := p[0] & protoVersionMask
if version < protoVersion1 || version > protoVersion5 {
return frameHeader{}, fmt.Errorf("gocql: unsupported protocol response version: %d", version)
}
headSize := 9
if version < protoVersion3 {
headSize = 8
}
_, err = io.ReadFull(r, p[1:headSize])
if err != nil {
return frameHeader{}, err
}
p = p[:headSize]
head.version = protoVersion(p[0])
head.flags = p[1]
if version > protoVersion2 {
if len(p) != 9 {
return frameHeader{}, fmt.Errorf("not enough bytes to read header require 9 got: %d", len(p))
}
head.stream = int(int16(p[2])<<8 | int16(p[3]))
head.op = frameOp(p[4])
head.length = int(readInt(p[5:]))
} else {
if len(p) != 8 {
return frameHeader{}, fmt.Errorf("not enough bytes to read header require 8 got: %d", len(p))
}
head.stream = int(int8(p[2]))
head.op = frameOp(p[3])
head.length = int(readInt(p[4:]))
}
return head, nil
}
// explicitly enables tracing for the framers outgoing requests
func (f *framer) trace() {
f.flags |= flagTracing
}
// explicitly enables the custom payload flag
func (f *framer) payload() {
f.flags |= flagCustomPayload
}
// reads a frame form the wire into the framers buffer
func (f *framer) readFrame(r io.Reader, head *frameHeader) error {
if head.length < 0 {
return fmt.Errorf("frame body length can not be less than 0: %d", head.length)
} else if head.length > maxFrameSize {
// need to free up the connection to be used again
_, err := io.CopyN(ioutil.Discard, r, int64(head.length))
if err != nil {
return fmt.Errorf("error whilst trying to discard frame with invalid length: %v", err)
}
return ErrFrameTooBig
}
if cap(f.readBuffer) >= head.length {
f.buf = f.readBuffer[:head.length]
} else {
f.readBuffer = make([]byte, head.length)
f.buf = f.readBuffer
}
// assume the underlying reader takes care of timeouts and retries
n, err := io.ReadFull(r, f.buf)
if err != nil {
return fmt.Errorf("unable to read frame body: read %d/%d bytes: %v", n, head.length, err)
}
if head.flags&flagCompress == flagCompress {
if f.compres == nil {
return NewErrProtocol("no compressor available with compressed frame body")
}
f.buf, err = f.compres.Decode(f.buf)
if err != nil {
return err
}
}
f.header = head
return nil
}
func (f *framer) parseFrame() (frame frame, err error) {
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
err = r.(error)
}
}()
if f.header.version.request() {
return nil, NewErrProtocol("got a request frame from server: %v", f.header.version)
}
if f.header.flags&flagTracing == flagTracing {
f.readTrace()
}
if f.header.flags&flagWarning == flagWarning {
f.header.warnings = f.readStringList()
}
if f.header.flags&flagCustomPayload == flagCustomPayload {
f.customPayload = f.readBytesMap()
}
// assumes that the frame body has been read into rbuf
switch f.header.op {
case opError:
frame = f.parseErrorFrame()
case opReady:
frame = f.parseReadyFrame()
case opResult:
frame, err = f.parseResultFrame()
case opSupported:
frame = f.parseSupportedFrame()
case opAuthenticate:
frame = f.parseAuthenticateFrame()
case opAuthChallenge:
frame = f.parseAuthChallengeFrame()
case opAuthSuccess:
frame = f.parseAuthSuccessFrame()
case opEvent:
frame = f.parseEventFrame()
default:
return nil, NewErrProtocol("unknown op in frame header: %s", f.header.op)
}
return
}
func (f *framer) parseErrorFrame() frame {
code := f.readInt()
msg := f.readString()
errD := errorFrame{
frameHeader: *f.header,
code: code,
message: msg,
}
switch code {
case ErrCodeUnavailable:
cl := f.readConsistency()
required := f.readInt()
alive := f.readInt()
return &RequestErrUnavailable{
errorFrame: errD,
Consistency: cl,
Required: required,
Alive: alive,
}
case ErrCodeWriteTimeout:
cl := f.readConsistency()
received := f.readInt()
blockfor := f.readInt()
writeType := f.readString()
return &RequestErrWriteTimeout{
errorFrame: errD,
Consistency: cl,
Received: received,
BlockFor: blockfor,
WriteType: writeType,
}
case ErrCodeReadTimeout:
cl := f.readConsistency()
received := f.readInt()
blockfor := f.readInt()
dataPresent := f.readByte()
return &RequestErrReadTimeout{
errorFrame: errD,
Consistency: cl,
Received: received,
BlockFor: blockfor,
DataPresent: dataPresent,
}
case ErrCodeAlreadyExists:
ks := f.readString()
table := f.readString()
return &RequestErrAlreadyExists{
errorFrame: errD,
Keyspace: ks,
Table: table,
}
case ErrCodeUnprepared:
stmtId := f.readShortBytes()
return &RequestErrUnprepared{
errorFrame: errD,
StatementId: copyBytes(stmtId), // defensively copy
}
case ErrCodeReadFailure:
res := &RequestErrReadFailure{
errorFrame: errD,
}
res.Consistency = f.readConsistency()
res.Received = f.readInt()
res.BlockFor = f.readInt()
if f.proto > protoVersion4 {
res.ErrorMap = f.readErrorMap()
res.NumFailures = len(res.ErrorMap)
} else {
res.NumFailures = f.readInt()
}
res.DataPresent = f.readByte() != 0
return res
case ErrCodeWriteFailure:
res := &RequestErrWriteFailure{
errorFrame: errD,
}
res.Consistency = f.readConsistency()
res.Received = f.readInt()
res.BlockFor = f.readInt()
if f.proto > protoVersion4 {
res.ErrorMap = f.readErrorMap()
res.NumFailures = len(res.ErrorMap)
} else {
res.NumFailures = f.readInt()
}
res.WriteType = f.readString()
return res
case ErrCodeFunctionFailure:
res := &RequestErrFunctionFailure{
errorFrame: errD,
}
res.Keyspace = f.readString()
res.Function = f.readString()
res.ArgTypes = f.readStringList()
return res
case ErrCodeCDCWriteFailure:
res := &RequestErrCDCWriteFailure{
errorFrame: errD,
}
return res
case ErrCodeCASWriteUnknown:
res := &RequestErrCASWriteUnknown{
errorFrame: errD,
}
res.Consistency = f.readConsistency()
res.Received = f.readInt()
res.BlockFor = f.readInt()
return res
case ErrCodeInvalid, ErrCodeBootstrapping, ErrCodeConfig, ErrCodeCredentials, ErrCodeOverloaded,
ErrCodeProtocol, ErrCodeServer, ErrCodeSyntax, ErrCodeTruncate, ErrCodeUnauthorized:
// TODO(zariel): we should have some distinct types for these errors
return errD
default:
if f.rateLimitingErrorCode != 0 && code == f.rateLimitingErrorCode {
res := &RequestErrRateLimitReached{
errorFrame: errD,
}
res.OpType = OpType(f.readByte())
res.RejectedByCoordinator = f.readByte() != 0
return res
} else {
panic(fmt.Errorf("unknown error code: 0x%x", errD.code))
}
}
}
func (f *framer) readErrorMap() (errMap ErrorMap) {
errMap = make(ErrorMap)
numErrs := f.readInt()
for i := 0; i < numErrs; i++ {
ip := f.readInetAdressOnly().String()
errMap[ip] = f.readShort()
}
return
}
func (f *framer) writeHeader(flags byte, op frameOp, stream int) {
f.buf = f.buf[:0]
f.buf = append(f.buf,
f.proto,
flags,
)
if f.proto > protoVersion2 {
f.buf = append(f.buf,
byte(stream>>8),
byte(stream),
)
} else {
f.buf = append(f.buf,
byte(stream),
)
}
// pad out length
f.buf = append(f.buf,
byte(op),
0,
0,
0,
0,
)
}
func (f *framer) setLength(length int) {
p := 4
if f.proto > protoVersion2 {
p = 5
}
f.buf[p+0] = byte(length >> 24)
f.buf[p+1] = byte(length >> 16)
f.buf[p+2] = byte(length >> 8)
f.buf[p+3] = byte(length)
}
func (f *framer) finish() error {
if len(f.buf) > maxFrameSize {
// huge app frame, lets remove it so it doesn't bloat the heap
f.buf = make([]byte, defaultBufSize)
return ErrFrameTooBig
}
if f.buf[1]&flagCompress == flagCompress {
if f.compres == nil {
panic("compress flag set with no compressor")
}
// TODO: only compress frames which are big enough
compressed, err := f.compres.Encode(f.buf[f.headSize:])
if err != nil {
return err
}
f.buf = append(f.buf[:f.headSize], compressed...)
}
length := len(f.buf) - f.headSize
f.setLength(length)
return nil
}
func (f *framer) writeTo(w io.Writer) error {
_, err := w.Write(f.buf)
return err
}
func (f *framer) readTrace() {
f.traceID = f.readUUID().Bytes()
}
type readyFrame struct {
frameHeader
}
func (f *framer) parseReadyFrame() frame {
return &readyFrame{
frameHeader: *f.header,
}
}
type supportedFrame struct {
frameHeader
supported map[string][]string
}
// TODO: if we move the body buffer onto the frameHeader then we only need a single
// framer, and can move the methods onto the header.
func (f *framer) parseSupportedFrame() frame {
return &supportedFrame{
frameHeader: *f.header,
supported: f.readStringMultiMap(),
}
}
type writeStartupFrame struct {
opts map[string]string
}
func (w writeStartupFrame) String() string {
return fmt.Sprintf("[startup opts=%+v]", w.opts)
}
func (w *writeStartupFrame) buildFrame(f *framer, streamID int) error {
f.writeHeader(f.flags&^flagCompress, opStartup, streamID)
f.writeStringMap(w.opts)
return f.finish()
}
type writePrepareFrame struct {
statement string
keyspace string
customPayload map[string][]byte
}
func (w *writePrepareFrame) buildFrame(f *framer, streamID int) error {
if len(w.customPayload) > 0 {
f.payload()
}
f.writeHeader(f.flags, opPrepare, streamID)
f.writeCustomPayload(&w.customPayload)
f.writeLongString(w.statement)
var flags uint32 = 0
if w.keyspace != "" {
if f.proto > protoVersion4 {
flags |= flagWithPreparedKeyspace
} else {
panic(fmt.Errorf("the keyspace can only be set with protocol 5 or higher"))
}
}
if f.proto > protoVersion4 {
f.writeUint(flags)
}
if w.keyspace != "" {
f.writeString(w.keyspace)
}
return f.finish()
}
func (f *framer) readTypeInfo() TypeInfo {
// TODO: factor this out so the same code paths can be used to parse custom
// types and other types, as much of the logic will be duplicated.
id := f.readShort()
simple := NativeType{
proto: f.proto,
typ: Type(id),
}
if simple.typ == TypeCustom {
simple.custom = f.readString()
if cassType := getApacheCassandraType(simple.custom); cassType != TypeCustom {
simple.typ = cassType
}
}
switch simple.typ {
case TypeTuple:
n := f.readShort()
tuple := TupleTypeInfo{
NativeType: simple,
Elems: make([]TypeInfo, n),
}
for i := 0; i < int(n); i++ {
tuple.Elems[i] = f.readTypeInfo()
}
return tuple
case TypeUDT:
udt := UDTTypeInfo{
NativeType: simple,
}
udt.KeySpace = f.readString()
udt.Name = f.readString()
n := f.readShort()
udt.Elements = make([]UDTField, n)
for i := 0; i < int(n); i++ {
field := &udt.Elements[i]
field.Name = f.readString()
field.Type = f.readTypeInfo()
}
return udt
case TypeMap, TypeList, TypeSet:
collection := CollectionType{
NativeType: simple,
}
if simple.typ == TypeMap {
collection.Key = f.readTypeInfo()
}
collection.Elem = f.readTypeInfo()
return collection
}
return simple
}
type preparedMetadata struct {
resultMetadata
// LWT query detected
lwt bool
// proto v4+
pkeyColumns []int
keyspace string
table string
}
func (r preparedMetadata) String() string {
return fmt.Sprintf("[prepared flags=0x%x pkey=%v paging_state=% X columns=%v col_count=%d actual_col_count=%d lwt=%t]",
r.flags, r.pkeyColumns, r.pagingState, r.columns, r.colCount, r.actualColCount, r.lwt)
}
func (f *framer) parsePreparedMetadata() preparedMetadata {
// TODO: deduplicate this from parseMetadata
meta := preparedMetadata{}
meta.flags = f.readInt()
meta.colCount = f.readInt()
if meta.colCount < 0 {
panic(fmt.Errorf("received negative column count: %d", meta.colCount))
}
meta.actualColCount = meta.colCount
if f.proto >= protoVersion4 {
pkeyCount := f.readInt()
pkeys := make([]int, pkeyCount)
for i := 0; i < pkeyCount; i++ {
pkeys[i] = int(f.readShort())
}
meta.pkeyColumns = pkeys
}
meta.lwt = meta.flags&f.flagLWT == f.flagLWT
if meta.flags&flagHasMorePages == flagHasMorePages {
meta.pagingState = copyBytes(f.readBytes())
}
if meta.flags&flagNoMetaData == flagNoMetaData {
return meta
}