-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprotocol.zig
4018 lines (3173 loc) · 141 KB
/
protocol.zig
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
const std = @import("std");
const debug = std.debug;
const heap = std.heap;
const fmt = std.fmt;
const io = std.io;
const mem = std.mem;
const net = std.net;
const os = std.os;
const testing = std.testing;
const assert = std.debug.assert;
const event = @import("event.zig");
const lz4 = @import("lz4.zig");
const metadata = @import("metadata.zig");
const QueryParameters = @import("QueryParameters.zig");
const snappy = @import("snappy.zig");
const testutils = @import("testutils.zig");
const log = std.log.scoped(.protocol);
// Framing format
//
// The most low level "unit" of data that can be read or written.
// This is specific to protocol v5 !
//
// See §2 in native_protocol_v5.spec.
pub const Frame = struct {
/// Indicates that the payload includes one or more complete envelopes and can be fully processed immediately.
is_self_contained: bool,
/// The frame payload, the content depends on `is_self_contained`:
/// * if self contained, the payload is one or more complete envelopes
/// * if not self contained, the payload is one part of a large envelope
payload: []const u8,
const uncompressed_header_size = 6;
const compressed_header_size = 8;
const trailer_size = 4;
const max_payload_size = 131071;
const initial_crc32_bytes = "\xFA\x2D\x55\xCA";
pub const Format = enum {
compressed,
uncompressed,
};
fn crc24(input: anytype) usize {
// Don't use @sizeOf because it contains a padding byte
const Size = @typeInfo(@TypeOf(input)).int.bits / 8;
comptime assert(Size > 0 and Size < 9);
// This is adapted from https://github.com/apache/cassandra/blob/1bd4bcf4e561144497adc86e1b48480eab6171d4/src/java/org/apache/cassandra/net/Crc.java#L119-L135
const crc24_initial = 0x875060;
const crc24_polynomial = 0x1974F0B;
var crc: usize = crc24_initial;
var buf = input;
var len: usize = Size;
while (len > 0) : (len -= 1) {
const b = buf & 0xff;
crc ^= @as(usize, @intCast(b)) << 16;
buf >>= 8;
var i: usize = 0;
while (i < 8) : (i += 1) {
crc <<= 1;
if ((crc & 0x1000000) != 0) {
crc ^= crc24_polynomial;
}
}
}
return crc;
}
fn computeCR32(payload: []const u8) u32 {
var hash = std.hash.Crc32.init();
hash.update(initial_crc32_bytes);
hash.update(payload);
return hash.final();
}
fn computeAndVerifyCRC32(payload: []const u8, trailer: *const [4]u8) !void {
const computed_crc32 = computeCR32(payload);
const expected_crc32 = mem.readInt(u32, trailer, .little);
if (computed_crc32 != expected_crc32) {
return error.InvalidPayloadChecksum;
}
}
pub const DecodeError = error{
UnexpectedEOF,
InvalidPayloadChecksum,
InvalidHeaderChecksum,
} || mem.Allocator.Error || std.posix.ReadError || lz4.DecompressError;
pub const DecodeResult = struct {
frame: Frame,
consumed: usize,
};
/// Try to decode a frame contained in the `data` slice.
///
/// If there's not enough data or if the input data is corrupted somehow, an error is returned.
/// Otherwise a result containing both the frame and the number of bytes consumed is returned.
pub fn decode(allocator: mem.Allocator, data: []const u8, format: Format) Frame.DecodeError!DecodeResult {
switch (format) {
.compressed => return decodeCompressed(allocator, data),
.uncompressed => return decodeUncompressed(data),
}
}
pub const ReadError = error{} || DecodeError;
fn decodeUncompressed(input: []const u8) Frame.DecodeError!DecodeResult {
// Read and parse header
const header_data, const buffer = if (input.len >= uncompressed_header_size)
.{ input[0..uncompressed_header_size], input[uncompressed_header_size..] }
else
return error.UnexpectedEOF;
debug.assert(header_data.len == uncompressed_header_size);
const header3b: u24 = mem.readInt(u24, header_data[0..3], .little);
const header_expected_crc = @as(usize, @intCast(mem.readInt(u24, header_data[3..uncompressed_header_size], .little)));
const payload_length: u17 = @intCast(header3b & 0x1FFFF);
const is_self_contained = header3b & (1 << 17) != 0;
const computed_header_crc = crc24(header3b);
if (computed_header_crc != header_expected_crc) {
return error.InvalidHeaderChecksum;
}
// Read payload and trailer
const payload, const trailer = if (buffer.len >= payload_length + trailer_size)
.{ buffer[0..payload_length], @as(*const [4]u8, @ptrCast(buffer[payload_length..])) }
else
return error.UnexpectedEOF;
debug.assert(payload_length < input.len);
debug.assert(payload.len == payload_length);
debug.assert(trailer.len == trailer_size);
// Verify payload CRC32
try computeAndVerifyCRC32(payload, trailer);
return .{
.frame = .{
.payload = payload,
.is_self_contained = is_self_contained,
},
.consumed = uncompressed_header_size + payload_length + trailer_size,
};
}
fn decodeCompressed(allocator: mem.Allocator, input: []const u8) Frame.DecodeError!DecodeResult {
// Read and parse header
const header_data, const buffer = if (input.len >= compressed_header_size)
.{ input[0..compressed_header_size], input[compressed_header_size..] }
else
return error.UnexpectedEOF;
debug.assert(header_data.len == compressed_header_size);
const header5b: u40 = mem.readInt(u40, header_data[0..5], .little);
const header_expected_crc = @as(usize, @intCast(mem.readInt(u24, header_data[5..compressed_header_size], .little)));
const compressed_length: u17 = @intCast(header5b & 0x1FFFF);
const uncompressed_length: u17 = @intCast(header5b >> 17 & 0x1FFFF);
const is_self_contained = header5b & (1 << 34) != 0;
const computed_header_crc = crc24(header5b);
if (computed_header_crc != header_expected_crc) {
return error.InvalidHeaderChecksum;
}
// Read payload and trailer
const payload, const trailer = if (buffer.len >= compressed_length + trailer_size)
.{ buffer[0..compressed_length], @as(*const [4]u8, @ptrCast(buffer[compressed_length..])) }
else
return error.UnexpectedEOF;
debug.assert(compressed_length < input.len);
debug.assert(payload.len == compressed_length);
debug.assert(trailer.len == trailer_size);
// Verify compressed payload CRC32
try computeAndVerifyCRC32(payload, trailer);
// Decompress payload if necessary
const final_payload = if (uncompressed_length == 0)
payload
else
try lz4.decompress(allocator, payload, @as(usize, @intCast(uncompressed_length)));
return .{
.frame = .{
.payload = final_payload,
.is_self_contained = is_self_contained,
},
.consumed = compressed_header_size + payload.len + trailer_size,
};
}
const EncodeError = error{
PayloadTooBig,
} || mem.Allocator.Error;
pub fn encode(allocator: mem.Allocator, payload: []const u8, is_self_contained: bool, format: Format) Frame.EncodeError![]const u8 {
switch (format) {
.uncompressed => return encodeUncompressed(allocator, payload, is_self_contained),
.compressed => return encodeCompressed(allocator, payload, is_self_contained),
}
}
fn encodeUncompressed(allocator: mem.Allocator, payload: []const u8, is_self_contained: bool) Frame.EncodeError![]const u8 {
if (payload.len > max_payload_size) return error.PayloadTooBig;
// Create header
var header3b: u24 = @as(u17, @intCast(payload.len));
if (is_self_contained) {
header3b |= 1 << 17;
}
const header_crc24 = crc24(header3b);
var buf: [uncompressed_header_size]u8 = undefined;
mem.writeInt(u24, buf[0..3], header3b, .little);
mem.writeInt(u24, buf[3..uncompressed_header_size], @truncate(header_crc24), .little);
const header_data = buf[0..];
// Compute trailer
const payload_crc32 = computeCR32(payload);
// Finally build the frame
var frame_data = try std.ArrayList(u8).initCapacity(allocator, uncompressed_header_size + payload.len + trailer_size);
defer frame_data.deinit();
try frame_data.appendSlice(header_data);
try frame_data.appendSlice(payload);
try frame_data.writer().writeInt(u32, payload_crc32, .little);
return frame_data.toOwnedSlice();
}
fn encodeCompressed(allocator: mem.Allocator, payload: []const u8, is_self_contained: bool) Frame.EncodeError![]const u8 {
_ = allocator;
_ = payload;
_ = is_self_contained;
return error.OutOfMemory;
}
};
test "frame reader: QUERY message" {
var arena = testutils.arenaAllocator();
defer arena.deinit();
const TestCase = struct {
data: []const u8,
format: Frame.Format,
};
const testCases = &[_]TestCase{
.{
.data = @embedFile("testdata/query_frame_uncompressed.bin"),
.format = .uncompressed,
},
.{
.data = @embedFile("testdata/query_frame_compressed.bin"),
.format = .compressed,
},
};
inline for (testCases) |tc| {
const result = try Frame.decode(arena.allocator(), tc.data, tc.format);
const frame = result.frame;
try testing.expectEqual(@as(usize, tc.data.len), result.consumed);
try testing.expect(frame.is_self_contained);
try testing.expectEqual(@as(usize, 66), frame.payload.len);
const envelope = try testReadEnvelope(arena.allocator(), frame.payload, .none);
try checkEnvelopeHeader(.v5, Opcode.query, frame.payload.len, envelope.header);
var mr = MessageReader.init(envelope.body);
const query_message = try QueryMessage.read(
arena.allocator(),
envelope.header.version,
&mr,
);
try testing.expectEqualStrings("select * from foobar.age_to_ids ;", query_message.query);
try testing.expectEqual(.One, query_message.query_parameters.consistency_level);
try testing.expect(query_message.query_parameters.values == null);
}
}
test "frame reader: QUERY message incomplete" {
var arena = testutils.arenaAllocator();
defer arena.deinit();
// Simulate reading a frame in multiple steps because the input buffer doesn't contain a complete frame
// Also simulate reading a frame in a buffer that has more data than the frame itself.
//
// This is how frames will be read in the event loop.
const frame_data = @embedFile("testdata/query_frame_compressed.bin");
const test_data = frame_data ++ [_]u8{'z'} ** 2000;
const test_format: Frame.Format = .compressed;
const tmp1 = Frame.decode(arena.allocator(), test_data[0..1], test_format);
try testing.expectError(error.UnexpectedEOF, tmp1);
const tmp2 = Frame.decode(arena.allocator(), test_data[0..10], test_format);
try testing.expectError(error.UnexpectedEOF, tmp2);
const result = try Frame.decode(arena.allocator(), test_data, test_format);
//
const frame = result.frame;
try testing.expectEqual(@as(usize, frame_data.len), result.consumed);
try testing.expect(frame.is_self_contained);
try testing.expectEqual(@as(usize, 66), frame.payload.len);
const envelope = try testReadEnvelope(arena.allocator(), frame.payload, .none);
try checkEnvelopeHeader(.v5, Opcode.query, frame.payload.len, envelope.header);
var mr = MessageReader.init(envelope.body);
const query_message = try QueryMessage.read(
arena.allocator(),
envelope.header.version,
&mr,
);
try testing.expectEqualStrings("select * from foobar.age_to_ids ;", query_message.query);
try testing.expectEqual(.One, query_message.query_parameters.consistency_level);
try testing.expect(query_message.query_parameters.values == null);
}
test "frame reader: RESULT message" {
var arena = testutils.arenaAllocator();
defer arena.deinit();
// The rows in the result message have the following columns.
// The order is important !
const MyRow = struct {
age: u32,
balance: std.math.big.int.Const,
ids: []u16,
name: []const u8,
};
const checkRowData = struct {
fn do(expAge: usize, exp_balance_str: []const u8, exp_ids: []const u16, exp_name_opt: ?[]const u8, row: MyRow) !void {
try testing.expectEqual(expAge, row.age);
var buf: [1024]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf);
var exp_balance = try std.math.big.int.Managed.init(fba.allocator());
try exp_balance.setString(10, exp_balance_str);
try testing.expect(exp_balance.toConst().eql(row.balance));
try testing.expectEqualSlices(u16, exp_ids, row.ids);
const exp_name = exp_name_opt orelse "";
try testing.expectEqualStrings(exp_name, row.name);
}
}.do;
// Uncompressed frame
{
const data = @embedFile("testdata/result_frame_uncompressed.bin");
const result = try Frame.decode(arena.allocator(), data, .uncompressed);
const frame = result.frame;
try testing.expectEqual(@as(usize, data.len), result.consumed);
try testing.expect(frame.is_self_contained);
try testing.expectEqual(@as(usize, 605), frame.payload.len);
const envelope = try testReadEnvelope(arena.allocator(), frame.payload, .none);
try checkEnvelopeHeader(.v5, Opcode.result, frame.payload.len, envelope.header);
var mr = MessageReader.init(envelope.body);
const result_message = try ResultMessage.read(
arena.allocator(),
envelope.header.version,
&mr,
);
const rows = try collectRows(
MyRow,
arena.allocator(),
result_message.result.rows,
);
try testing.expectEqual(10, rows.items.len);
try checkRowData(50, "-350956306", &[_]u16{ 0, 2, 4, 8 }, null, rows.items[0]);
try checkRowData(10, "-350956306", &[_]u16{ 0, 2, 4, 8 }, null, rows.items[1]);
try checkRowData(60, "40502020", &[_]u16{ 0, 2, 4, 8 }, "Vincent 6", rows.items[2]);
try checkRowData(80, "40502020", &[_]u16{ 0, 2, 4, 8 }, "Vincent 8", rows.items[3]);
try checkRowData(30, "-350956306", &[_]u16{ 0, 2, 4, 8 }, null, rows.items[4]);
try checkRowData(0, "40502020", &[_]u16{ 0, 2, 4, 8 }, "Vincent 0", rows.items[5]);
try checkRowData(20, "40502020", &[_]u16{ 0, 2, 4, 8 }, "Vincent 2", rows.items[6]);
try checkRowData(40, "40502020", &[_]u16{ 0, 2, 4, 8 }, "Vincent 4", rows.items[7]);
try checkRowData(70, "-350956306", &[_]u16{ 0, 2, 4, 8 }, null, rows.items[8]);
try checkRowData(90, "-350956306", &[_]u16{ 0, 2, 4, 8 }, null, rows.items[9]);
}
// Compressed frame
{
const data = @embedFile("testdata/result_frame_compressed.bin");
const result = try Frame.decode(arena.allocator(), data, .compressed);
const frame = result.frame;
try testing.expectEqual(@as(usize, data.len), result.consumed);
try testing.expect(frame.is_self_contained);
try testing.expectEqual(@as(usize, 5532), frame.payload.len);
const envelope = try testReadEnvelope(arena.allocator(), frame.payload, .none);
try checkEnvelopeHeader(.v5, Opcode.result, frame.payload.len, envelope.header);
var mr = MessageReader.init(envelope.body);
const result_message = try ResultMessage.read(
arena.allocator(),
envelope.header.version,
&mr,
);
const rows = try collectRows(
MyRow,
arena.allocator(),
result_message.result.rows,
);
try testing.expectEqual(100, rows.items.len);
}
}
test "frame write: PREPARE message" {
var arena = testutils.arenaAllocator();
defer arena.deinit();
const protocol_version = ProtocolVersion.v5;
// Encode
const frame = blk: {
// Write the message to a buffer
const message = PrepareMessage{
.query = "SELECT 1 FROM foobar",
.keyspace = "hello",
};
var mw = try MessageWriter.init(arena.allocator());
try message.write(protocol_version, &mw);
const message_data = mw.getWritten();
// Create and write the envelope to a buffer
const envelope = Envelope{
.header = EnvelopeHeader{
.version = protocol_version,
.flags = 0,
.stream = 0,
.opcode = .prepare,
.body_len = @intCast(message_data.len),
},
.body = message_data,
};
var envelope_writer_buffer = std.ArrayList(u8).init(arena.allocator());
const envelope_data = try writeEnvelope(envelope, &envelope_writer_buffer);
// Write the frame to a buffer
const frame_payload = envelope_data;
const frame = try Frame.encode(arena.allocator(), frame_payload, true, .uncompressed);
break :blk frame;
};
// Decode then verify
{
const result = try Frame.decode(arena.allocator(), frame, .uncompressed);
const envelope = try testReadEnvelope(arena.allocator(), result.frame.payload, .none);
try checkEnvelopeHeader(.v5, Opcode.prepare, result.frame.payload.len, envelope.header);
var mr = MessageReader.init(envelope.body);
const prepare_message = try PrepareMessage.read(
arena.allocator(),
envelope.header.version,
&mr,
);
try testing.expectEqualStrings("SELECT 1 FROM foobar", prepare_message.query);
try testing.expectEqualStrings("hello", prepare_message.keyspace.?);
}
}
//
//
//
pub const EnvelopeFlags = struct {
pub const compression: u8 = 0x01;
pub const tracing: u8 = 0x02;
pub const custom_payload: u8 = 0x04;
pub const warning: u8 = 0x08;
pub const use_beta: u8 = 0x10;
};
pub const EnvelopeHeader = packed struct {
version: ProtocolVersion,
flags: u8,
stream: i16,
opcode: Opcode,
body_len: u32,
};
pub const Envelope = struct {
const TracingID = [16]u8;
header: EnvelopeHeader = undefined,
tracing_id: ?TracingID = null,
warnings: ?[]const []const u8 = null,
custom_payload: ?BytesMap = null,
body: []const u8 = undefined,
const header_size = 9;
pub fn deinit(self: @This(), allocator: mem.Allocator) void {
allocator.free(self.body);
}
const ReadError = error{
UnexpectedEOF,
EnvelopeBodyIsCompressed,
} || mem.Allocator.Error || lz4.DecompressError || snappy.DecompressError || MessageReader.Error || ProtocolVersion.Error;
const ReadResult = struct {
envelope: Envelope,
consumed: usize,
};
pub fn read(allocator: mem.Allocator, reader: anytype, compression_algorithm: CompressionAlgorithm) (Envelope.ReadError || @TypeOf(reader).Error)!ReadResult {
var res = Envelope{};
res.header = hdr: {
var buf: [header_size]u8 = undefined;
const n = try reader.readAll(&buf);
if (n != header_size) return error.UnexpectedEOF;
break :hdr EnvelopeHeader{
.version = try ProtocolVersion.init(buf[0]),
.flags = buf[1],
.stream = mem.readInt(i16, @ptrCast(buf[2..4]), .big),
.opcode = @enumFromInt(buf[4]),
.body_len = mem.readInt(u32, @ptrCast(buf[5..9]), .big),
};
};
res.body = body: {
const len = @as(usize, res.header.body_len);
const tmp = try allocator.alloc(u8, len);
const n = try reader.readAll(tmp);
if (n != len) return error.UnexpectedEOF;
break :body tmp[0..n];
};
if (res.header.flags != 0) {
if (res.header.flags & EnvelopeFlags.compression == EnvelopeFlags.compression) {
switch (compression_algorithm) {
.lz4 => {
const decompressed_data = try lz4.decompress(allocator, res.body, res.body.len * 3);
res.body = decompressed_data;
},
.snappy => {
const decompressed_data = try snappy.decompress(allocator, res.body);
res.body = decompressed_data;
},
.none => return error.EnvelopeBodyIsCompressed,
}
}
var mr = MessageReader.init(res.body);
if (res.header.flags & EnvelopeFlags.tracing == EnvelopeFlags.tracing) {
var tmp: TracingID = undefined;
try mr.readUUIDInto(&tmp);
res.tracing_id = tmp;
}
if (res.header.flags & EnvelopeFlags.warning == EnvelopeFlags.warning) {
res.warnings = try mr.readStringList(allocator);
}
if (res.header.flags & EnvelopeFlags.custom_payload == EnvelopeFlags.custom_payload) {
res.custom_payload = try mr.readBytesMap(allocator);
}
res.body = res.body[mr.bytes_read..];
}
return .{
.envelope = res,
.consumed = header_size + res.header.body_len,
};
}
};
pub const WriteEnvelopeError = error{} || mem.Allocator.Error;
pub fn writeEnvelope(envelope: Envelope, out: *std.ArrayList(u8)) WriteEnvelopeError![]const u8 {
out.clearRetainingCapacity();
var buf: [Envelope.header_size]u8 = undefined;
buf[0] = @intFromEnum(envelope.header.version);
buf[1] = envelope.header.flags;
mem.writeInt(i16, @ptrCast(buf[2..4]), envelope.header.stream, .big);
buf[4] = @intFromEnum(envelope.header.opcode);
mem.writeInt(u32, @ptrCast(buf[5..9]), envelope.header.body_len, .big);
try out.appendSlice(&buf);
try out.appendSlice(envelope.body);
return out.items;
}
//
//
//
// TODO(vincent): test all error codes
pub const ErrorCode = enum(u32) {
ServerError = 0x0000,
ProtocolError = 0x000A,
AuthError = 0x0100,
UnavailableReplicas = 0x1000,
CoordinatorOverloaded = 0x1001,
CoordinatorIsBootstrapping = 0x1002,
TruncateError = 0x1003,
WriteTimeout = 0x1100,
ReadTimeout = 0x1200,
ReadFailure = 0x1300,
FunctionFailure = 0x1400,
WriteFailure = 0x1500,
CDCWriteFailure = 0x1600,
CASWriteUnknown = 0x1700,
SyntaxError = 0x2000,
Unauthorized = 0x2100,
InvalidQuery = 0x2200,
ConfigError = 0x2300,
AlreadyExists = 0x2400,
Unprepared = 0x2500,
};
pub const UnavailableReplicasError = struct {
consistency_level: Consistency,
required: u32,
alive: u32,
};
pub const FunctionFailureError = struct {
keyspace: []const u8,
function: []const u8,
arg_types: []const []const u8,
};
pub const WriteError = struct {
// TODO(vincent): document this
pub const WriteType = enum {
SIMPLE,
BATCH,
UNLOGGED_BATCH,
COUNTER,
BATCH_LOG,
CAS,
VIEW,
CDC,
};
pub const Timeout = struct {
consistency_level: Consistency,
received: u32,
block_for: u32,
write_type: WriteType,
contentions: ?u16,
};
pub const Failure = struct {
pub const Reason = struct {
endpoint: net.Address,
// TODO(vincent): what's this failure code ?!
failure_code: u16,
};
consistency_level: Consistency,
received: u32,
block_for: u32,
reason_map: []Reason,
write_type: WriteType,
};
pub const CASUnknown = struct {
consistency_level: Consistency,
received: u32,
block_for: u32,
};
};
pub const ReadError = struct {
pub const Timeout = struct {
consistency_level: Consistency,
received: u32,
block_for: u32,
data_present: u8,
};
pub const Failure = struct {
pub const Reason = struct {
endpoint: net.Address,
// TODO(vincent): what's this failure code ?!
failure_code: u16,
};
consistency_level: Consistency,
received: u32,
block_for: u32,
reason_map: []Reason,
data_present: u8,
};
};
pub const AlreadyExistsError = struct {
keyspace: []const u8,
table: []const u8,
};
pub const UnpreparedError = struct {
statement_id: []const u8,
};
pub const Value = union(enum) {
Set: []const u8,
NotSet: void,
Null: void,
};
/// This struct is intended to be used as a field in a struct/tuple argument
/// passed to query/execute.
///
/// For example if you have a prepared update query where you don't want to touch
/// the second field, you can pass a struct/tuple like this:
///
/// .{
/// .arg1 = ...,
/// .arg2 = NotSet{ .type = i64 },
/// }
///
/// TODO(vincent): the `type` field is necessary for now to make NotSet work but it's not great.
pub const NotSet = struct {
type: type,
};
pub const NamedValue = struct {
name: []const u8,
value: Value,
};
pub const Values = union(enum) {
Normal: []Value,
Named: []NamedValue,
};
pub const CQLVersion = struct {
major: u16,
minor: u16,
patch: u16,
pub fn fromString(s: []const u8) !CQLVersion {
var version = CQLVersion{
.major = 0,
.minor = 0,
.patch = 0,
};
var it = mem.splitSequence(u8, s, ".");
var pos: usize = 0;
while (it.next()) |v| {
const n = std.fmt.parseInt(u16, v, 10) catch return error.InvalidCQLVersion;
switch (pos) {
0 => version.major = n,
1 => version.minor = n,
2 => version.patch = n,
else => break,
}
pos += 1;
}
if (version.major < 3) {
return error.InvalidCQLVersion;
}
return version;
}
pub fn format(value: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
var buf: [16]u8 = undefined;
const res = try value.print(&buf);
try writer.print("{s}", .{res});
}
pub fn print(self: @This(), buf: []u8) ![]u8 {
return std.fmt.bufPrint(buf, "{d}.{d}.{d}", .{
self.major,
self.minor,
self.patch,
});
}
};
pub const ProtocolVersion = enum(u8) {
v3 = 0x3,
v4 = 0x4,
v5 = 0x5,
v6 = 0x6,
const Error = error{
InvalidProtocolVersion,
};
pub fn init(b: u8) Error!ProtocolVersion {
const tmp = b & 0x7;
if (tmp < 3 or tmp > 6) {
return error.InvalidProtocolVersion;
}
return @enumFromInt(tmp);
}
// fn fromInt(b: u8) !ProtocolVersion {
// if (b == 3) {
// return .v3;
// } else if (b == 4) {
// return .v4;
// } else if (b == 5) {
// return .v5;
// } else if (b == 6) {
// return .v6;
// }
//
// return error.InvalidProtocolVersion;
// }
// pub fn toInt(version: ProtocolVersion) u8 {
// switch (version) {
// .v3 => return 3,
// .v4 => return 4,
// .v5 => return 5,
// .v6 => return 6,
// }
// }
// pub fn isRequest(version: ProtocolVersion) bool {
// const tmp = toInt(version);
// return (tmp & 0x0F) == tmp;
// }
//
// pub fn isResponse(version: ProtocolVersion) bool {
// const tmp = toInt(version);
// return (tmp & 0xF0) == 0x80;
// }
pub fn isAtLeast(lhs: ProtocolVersion, rhs: ProtocolVersion) bool {
const lhs_n = @intFromEnum(lhs);
const rhs_n = @intFromEnum(rhs);
return lhs_n >= rhs_n;
}
pub fn lessThan(lhs: ProtocolVersion, rhs: ProtocolVersion) bool {
const lhs_n = @intFromEnum(lhs);
const rhs_n = @intFromEnum(rhs);
return lhs_n < rhs_n;
}
pub fn fromString(s: []const u8) !ProtocolVersion {
if (mem.startsWith(u8, s, "3/")) {
return .v3;
} else if (mem.startsWith(u8, s, "4/")) {
return .v4;
} else if (mem.startsWith(u8, s, "5/")) {
return .v5;
} else if (mem.startsWith(u8, s, "6/")) {
return .v6;
} else {
return error.InvalidProtocolVersion;
}
}
pub fn format(value: ProtocolVersion, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try writer.print("{s}", .{@tagName(value)});
}
};
pub const Opcode = enum(u8) {
@"error" = 0x00,
startup = 0x01,
ready = 0x02,
authenticate = 0x03,
options = 0x05,
supported = 0x06,
query = 0x07,
result = 0x08,
prepare = 0x09,
execute = 0x0a,
register = 0x0b,
event = 0x0c,
batch = 0x0d,
auth_challenge = 0x0e,
auth_response = 0x0f,
auth_success = 0x10,
};
pub const CompressionAlgorithm = enum {
lz4,
snappy,
none,
pub fn fromString(s: []const u8) !CompressionAlgorithm {
if (mem.eql(u8, "lz4", s)) {
return .lz4;
} else if (mem.eql(u8, "snappy", s)) {
return .snappy;
} else {
return error.InvalidCompressionAlgorithm;
}
}
pub fn format(value: CompressionAlgorithm, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try writer.print("{s}", .{@tagName(value)});
}
};
pub const Consistency = enum(u16) {
Any = 0x0000,
One = 0x0001,
Two = 0x0002,
Three = 0x0003,
Quorum = 0x0004,
All = 0x0005,
LocalQuorum = 0x0006,
EachQuorum = 0x0007,
Serial = 0x0008,
LocalSerial = 0x0009,
LocalOne = 0x000A,
};
pub const BatchType = enum(u8) {
Logged = 0,
Unlogged = 1,
Counter = 2,
};
pub const OptionID = enum(u16) {
Custom = 0x0000,
Ascii = 0x0001,
Bigint = 0x0002,
Blob = 0x0003,
Boolean = 0x0004,
Counter = 0x0005,
Decimal = 0x0006,
Double = 0x0007,
Float = 0x0008,
Int = 0x0009,
Timestamp = 0x000B,
UUID = 0x000C,
Varchar = 0x000D,
Varint = 0x000E,
Timeuuid = 0x000F,