-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreply.cpp
More file actions
1113 lines (928 loc) · 33.8 KB
/
reply.cpp
File metadata and controls
1113 lines (928 loc) · 33.8 KB
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
/*
* qb - C++ Actor Framework
* Copyright (C) 2011-2025 isndev (cpp.actor). All rights reserved.
*
* 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.
*/
#include <stdexcept>
#include <sstream>
#include "reply.h"
namespace qb::redis {
/**
* @brief Creates an error message for type mismatch errors
* @param expect_type The expected Redis reply type
* @param reply The actual Redis reply received
* @return Formatted error message describing the mismatch
*/
std::string
ParseError::_err_info(const std::string &expect_type, const redisReply &reply) {
return "expect " + expect_type + " reply, but got " +
reply::type_to_string(reply.type) + " reply";
}
namespace reply {
/**
* @brief Converts a Redis reply type code to a string representation
* @param type Redis reply type code
* @return String representation of the reply type
*/
std::string
type_to_string(int type) {
switch (type) {
case REDIS_REPLY_ERROR:
return "ERROR";
case REDIS_REPLY_NIL:
return "NULL";
case REDIS_REPLY_STRING:
return "STRING";
case REDIS_REPLY_STATUS:
return "STATUS";
case REDIS_REPLY_INTEGER:
return "INTEGER";
case REDIS_REPLY_ARRAY:
return "ARRAY";
default:
return "UNKNOWN";
}
}
/**
* @brief Extracts a status string from a Redis reply
* @param reply The Redis reply to extract status from
* @return The status structure containing the status string
* @throws ParseError if the reply is not a status reply
* @throws ProtoError if the status string is null
*/
status
to_status(redisReply &reply) {
if (!qb::redis::is_status(reply)) {
throw ParseError("STATUS", reply);
}
if (reply.str == nullptr) {
throw ProtoError("A null status reply");
}
// Create status from string representation
return status(std::string(reply.str, reply.len));
}
/**
* @brief Parses a Redis reply into a string_view
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return String view of the reply content
* @throws ParseError if the reply is not a string or status reply
* @throws ProtoError if the string is null
*/
std::string_view
parse(ParseTag<std::string_view>, redisReply &reply) {
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
if (!qb::redis::is_string(reply) && !qb::redis::is_status(reply) &&
!qb::redis::is_verb(reply) && !qb::redis::is_bignum(reply)) {
throw ParseError("STRING or STATUS or VERB or BIGNUM", reply);
}
#else
if (qb::redis::is_array(reply)) // pong in consumer
return "PONG";
if (!qb::redis::is_string(reply) && !qb::redis::is_status(reply)) {
throw ParseError("STRING or STATUS", reply);
}
#endif
if (reply.str == nullptr) {
throw ProtoError("A null string reply");
}
// Old version hiredis' *redisReply::len* is of type int.
// So we CANNOT have something like: *return {reply.str, reply.len}*.
return {reply.str, reply.len};
}
/**
* @brief Parses a Redis reply into a std::string
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return String copy of the reply content
*/
std::string
parse(ParseTag<std::string>, redisReply &reply) {
if (is_integer(reply))
return std::to_string(reply.integer);
auto str = parse(ParseTag<std::string_view>{}, reply);
return {str.data(), str.size()};
}
/**
* @brief Parses a Redis reply into a long long integer
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Integer value of the reply
* @throws ParseError if the reply is not an integer reply
*/
long long
parse(ParseTag<long long>, redisReply &reply) {
if (!qb::redis::is_integer(reply)) {
throw ParseError("INTEGER", reply);
}
return reply.integer;
}
/**
* @brief Parses a Redis reply into a double
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Double value of the reply
* @throws ParseError if the reply cannot be converted to a double
*/
double
parse(ParseTag<double>, redisReply &reply) {
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
if (qb::redis::is_double(reply)) {
return reply.dval;
} else {
// Return by string reply.
#endif
try {
return std::stod(parse<std::string>(reply));
} catch (const std::invalid_argument &) {
throw ProtoError("not a double reply");
} catch (const std::out_of_range &) {
throw ProtoError("double reply out of range");
}
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
}
#endif
}
/**
* @brief Parses a Redis reply into a boolean
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Boolean value of the reply
* @throws ParseError if the reply is not a boolean or integer reply
* @throws ProtoError if the integer value is not 0 or 1
*/
bool
parse(ParseTag<bool>, redisReply &reply) {
if (is_nil(reply))
return false;
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
long long ret = 0;
if (qb::redis::is_bool(reply) || qb::redis::is_integer(reply)) {
ret = reply.integer;
} else {
throw ProtoError("BOOL or INTEGER");
}
#else
auto ret = parse<long long>(reply);
#endif
if (ret == 1) {
return true;
} else if (ret == 0) {
return false;
} else {
throw ProtoError("Invalid bool reply: " + std::to_string(ret));
}
}
/**
* @brief Parses a Redis reply into a message structure
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Message structure containing channel and message content
* @throws ProtoError if the reply structure doesn't match expected format
*/
message
parse(ParseTag<message>, redisReply &reply) {
auto ptr = reply_ptr(&reply);
if (reply.elements != 3) {
throw ProtoError("Expect 3 sub replies");
}
assert(reply.element != nullptr);
auto *channel_reply = reply.element[1];
if (channel_reply == nullptr) {
throw ProtoError("Null channel reply");
}
auto channel = qb::redis::parse<std::string_view>(*channel_reply);
auto *msg_reply = reply.element[2];
if (msg_reply == nullptr) {
throw ProtoError("Null message reply");
}
auto message = qb::redis::parse<std::string_view>(*msg_reply);
return {"", channel, message, std::move(ptr)};
}
/**
* @brief Parses a Redis reply into a pattern message structure
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Pattern message structure containing pattern, channel and message content
* @throws ProtoError if the reply structure doesn't match expected format
*/
pmessage
parse(ParseTag<pmessage>, redisReply &reply) {
auto ptr = reply_ptr(&reply);
if (reply.elements != 4) {
throw ProtoError("Expect 4 sub replies");
}
assert(reply.element != nullptr);
auto *pattern_reply = reply.element[1];
if (pattern_reply == nullptr) {
throw ProtoError("Null pattern reply");
}
auto pattern = qb::redis::parse<std::string_view>(*pattern_reply);
auto *channel_reply = reply.element[2];
if (channel_reply == nullptr) {
throw ProtoError("Null channel reply");
}
auto channel = qb::redis::parse<std::string_view>(*channel_reply);
auto *msg_reply = reply.element[3];
if (msg_reply == nullptr) {
throw ProtoError("Null message reply");
}
auto message = qb::redis::parse<std::string_view>(*msg_reply);
return {pattern, channel, message, std::move(ptr)};
}
/**
* @brief Parses a Redis reply into a subscription structure
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Subscription structure containing channel and count information
* @throws ProtoError if the reply structure doesn't match expected format
*/
subscription
parse(ParseTag<subscription>, redisReply &reply) {
if (reply.elements != 3) {
throw ProtoError("Expect 3 sub replies");
}
assert(reply.element != nullptr);
auto *channel_reply = reply.element[1];
if (channel_reply == nullptr) {
throw ProtoError("Null channel reply");
}
auto channel = qb::redis::parse<std::optional<std::string>>(*channel_reply);
auto *num_reply = reply.element[2];
if (num_reply == nullptr) {
throw ProtoError("Null num reply");
}
auto num = qb::redis::parse<long long>(*num_reply);
return {std::move(channel), num};
}
/**
* @brief Parses a Redis reply into a status structure
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Status structure containing the status string
*/
status
parse(ParseTag<status>, redisReply &reply) {
if (!qb::redis::is_status(reply)) {
throw ParseError("STATUS", reply);
}
if (reply.str == nullptr) {
throw ProtoError("A null status reply");
}
// Create status from string representation
return status(std::string(reply.str, reply.len));
}
inline std::vector<char>
parse(ParseTag<std::vector<char>>, redisReply &reply) {
if (!qb::redis::is_string(reply)) {
throw ParseError("STRING", reply);
}
if (reply.len == 0 || reply.str == nullptr) {
return {};
}
return std::vector<char>(reply.str, reply.str + reply.len);
}
inline std::chrono::milliseconds
parse(ParseTag<std::chrono::milliseconds>, redisReply &reply) {
if (!qb::redis::is_integer(reply)) {
throw ParseError("INTEGER", reply);
}
return std::chrono::milliseconds(reply.integer);
}
inline std::chrono::seconds
parse(ParseTag<std::chrono::seconds>, redisReply &reply) {
if (!qb::redis::is_integer(reply)) {
throw ParseError("INTEGER", reply);
}
return std::chrono::seconds(reply.integer);
}
/**
* @brief Parses a Redis reply into a geo_pos
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return GeoPos value containing longitude and latitude
* @throws ParseError if the reply is not an array with 2 elements
*/
qb::redis::geo_pos
parse(ParseTag<qb::redis::geo_pos>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);
}
if (reply.elements != 2 || reply.element == nullptr) {
throw ProtoError("Invalid GEO position reply");
}
auto *longitude_reply = reply.element[0];
auto *latitude_reply = reply.element[1];
if (longitude_reply == nullptr || latitude_reply == nullptr) {
throw ProtoError("Null longitude or latitude reply");
}
return qb::redis::geo_pos{parse<double>(*longitude_reply),
parse<double>(*latitude_reply)};
}
qb::redis::stream_id
parse(ParseTag<qb::redis::stream_id>, redisReply &reply) {
if (!qb::redis::is_string(reply)) {
throw ParseError("STRING", reply);
}
if (reply.len == 0 || reply.str == nullptr) {
return {};
}
std::string id_str(reply.str, reply.len);
auto pos = id_str.find('-');
if (pos == std::string::npos) {
throw ProtoError("Invalid stream ID format: " + id_str);
}
qb::redis::stream_id id;
try {
id.timestamp = std::stoll(id_str.substr(0, pos));
id.sequence = std::stoll(id_str.substr(pos + 1));
} catch (const std::exception &) {
throw ProtoError("Invalid stream ID: " + id_str);
}
return id;
}
/**
* @brief Parses a Redis reply into a stream_entry
* @param tag Type tag for stream_entry
* @param reply Redis reply to parse
* @return Parsed stream_entry
*/
qb::redis::stream_entry
parse(ParseTag<qb::redis::stream_entry>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);
}
if (reply.elements != 2 || reply.element == nullptr) {
throw ProtoError("Invalid stream entry reply");
}
auto *id_reply = reply.element[0];
auto *fields_reply = reply.element[1];
if (id_reply == nullptr || fields_reply == nullptr) {
throw ProtoError("Null ID or fields reply");
}
qb::redis::stream_entry entry;
entry.id = parse<qb::redis::stream_id>(*id_reply);
entry.fields = parse<qb::unordered_map<std::string, std::string>>(*fields_reply);
return entry;
}
namespace detail {
/**
* @brief Checks if a Redis array reply is a flat array
*
* A flat array is an array whose elements are not arrays themselves.
* This is used for determining how to parse key-value pairs from Redis.
*
* @param reply The Redis reply to check
* @return true if the reply is a flat array, false otherwise
*/
bool
is_flat_array(redisReply &reply) {
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
assert(qb::redis::is_array(reply) || qb::redis::is_map(reply) ||
qb::redis::is_set(reply));
#else
assert(qb::redis::is_array(reply));
#endif
// Empty array reply.
if (reply.element == nullptr || reply.elements == 0) {
return false;
}
auto *sub_reply = reply.element[0];
// Null element.
if (sub_reply == nullptr) {
return false;
}
return !qb::redis::is_array(*sub_reply);
}
} // namespace detail
/**
* @brief Parses a Redis reply into a score
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Score value of the reply
* @throws ParseError if the reply is not a double or integer reply
*/
qb::redis::score
parse(ParseTag<qb::redis::score>, redisReply &reply) {
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
if (!qb::redis::is_double(reply) && !qb::redis::is_integer(reply) &&
!qb::redis::is_string(reply)) {
throw ParseError("DOUBLE or INTEGER or STRING", reply);
}
#else
if (!qb::redis::is_integer(reply) && !qb::redis::is_string(reply)) {
throw ParseError("INTEGER or STRING", reply);
}
#endif
return qb::redis::score{parse<double>(reply)};
}
/**
* @brief Parses a Redis reply into a score_member
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return ScoreMember value of the reply
* @throws ParseError if the reply is not an array with 2 elements
*/
qb::redis::score_member
parse(ParseTag<qb::redis::score_member>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);
}
if (reply.elements != 2 || reply.element == nullptr) {
throw ProtoError("Invalid score-member reply, expect array with 2 elements");
}
auto *member_reply = reply.element[0];
auto *score_reply = reply.element[1];
if (score_reply == nullptr || member_reply == nullptr) {
throw ProtoError("Null score or member reply");
}
qb::redis::score_member sm;
sm.score = parse<double>(*score_reply);
sm.member = parse<std::string>(*member_reply);
return sm;
}
/**
* @brief Parses a Redis reply into a search_result
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return SearchResult value of the reply
* @throws ParseError if the reply is not an array
*/
qb::redis::search_result
parse(ParseTag<qb::redis::search_result>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);
}
qb::redis::search_result result;
if (reply.elements == 0 || reply.element == nullptr) {
return result;
}
// First element is the key
auto *key_reply = reply.element[0];
if (key_reply == nullptr) {
throw ProtoError("Null key reply in search result");
}
result.key = parse<std::string>(*key_reply);
// Remaining elements are field-value pairs
for (size_t i = 1; i < reply.elements; i += 2) {
if (i + 1 >= reply.elements) {
break; // Avoid out of bounds if we have an odd number of elements
}
auto *field_reply = reply.element[i];
auto *value_reply = reply.element[i + 1];
if (field_reply == nullptr || value_reply == nullptr) {
throw ProtoError("Null field or value reply in search result");
}
result.fields.push_back(parse<std::string>(*field_reply));
result.values.push_back(parse<std::string>(*value_reply));
}
return result;
}
/**
* @brief Parses a Redis reply into a cluster_node
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return ClusterNode value of the reply
* @throws ParseError if the reply format is invalid
*/
qb::redis::cluster_node
parse(ParseTag<qb::redis::cluster_node>, redisReply &reply) {
if (!qb::redis::is_string(reply)) {
throw ParseError("STRING", reply);
}
qb::redis::cluster_node node;
std::string node_info = parse<std::string>(reply);
// Parse node info string
// Format: <id> <ip:port@cport> <flags> <master> <ping-sent> <pong-recv> <epoch>
// <link-state> <slot> <slot> ... <slot>
std::istringstream iss(node_info);
std::string token;
// Node ID
if (!(iss >> node.id)) {
throw ProtoError("Failed to parse node ID from: " + node_info);
}
// IP:port@cport
if (!(iss >> token)) {
throw ProtoError("Failed to parse node address from: " + node_info);
}
size_t colon_pos = token.find(':');
size_t at_pos = token.find('@');
if (colon_pos == std::string::npos) {
throw ProtoError("Invalid address format (missing colon): " + token);
}
node.ip = token.substr(0, colon_pos);
std::string port_str;
if (at_pos != std::string::npos) {
port_str = token.substr(colon_pos + 1, at_pos - colon_pos - 1);
} else {
port_str = token.substr(colon_pos + 1);
}
try {
node.port = std::stoi(port_str);
} catch (const std::exception &) {
throw ProtoError("Invalid port: " + port_str);
}
// Flags
if (!(iss >> token)) {
throw ProtoError("Failed to parse node flags from: " + node_info);
}
size_t start = 0;
size_t comma_pos;
do {
comma_pos = token.find(',', start);
if (comma_pos == std::string::npos) {
node.flags.push_back(token.substr(start));
break;
}
node.flags.push_back(token.substr(start, comma_pos - start));
start = comma_pos + 1;
} while (true);
// Master
if (!(iss >> node.master)) {
throw ProtoError("Failed to parse node master from: " + node_info);
}
// Ping sent
if (!(iss >> node.ping_sent)) {
throw ProtoError("Failed to parse ping sent from: " + node_info);
}
// Pong received
if (!(iss >> node.pong_received)) {
throw ProtoError("Failed to parse pong received from: " + node_info);
}
// Epoch
if (!(iss >> node.epoch)) {
throw ProtoError("Failed to parse epoch from: " + node_info);
}
// Link state
if (!(iss >> node.link_state)) {
throw ProtoError("Failed to parse link state from: " + node_info);
}
// Slots
while (iss >> token) {
node.slots.push_back(token);
}
return node;
}
/**
* @brief Parses a Redis reply into a memory_info
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return MemoryInfo value of the reply
* @throws ParseError if the reply is not an array or the format is invalid
*/
qb::redis::memory_info
parse(ParseTag<qb::redis::memory_info>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);
}
qb::redis::memory_info info;
// INFO reply is typically an array of string pairs
if (reply.elements == 0 || reply.element == nullptr) {
return info;
}
qb::unordered_map<std::string, std::string> info_map;
// Parse all key-value pairs
for (size_t i = 0; i < reply.elements; i += 2) {
if (i + 1 >= reply.elements) {
break;
}
auto *key_reply = reply.element[i];
auto *val_reply = reply.element[i + 1];
if (key_reply == nullptr || val_reply == nullptr) {
continue;
}
std::string key = parse<std::string>(*key_reply);
std::string val = parse<std::string>(*val_reply);
info_map[key] = val;
}
// Extract memory info from the map
auto get_size_t = [&info_map](const std::string &key) -> size_t {
auto it = info_map.find(key);
if (it == info_map.end())
return 0;
try {
return std::stoull(it->second);
} catch (const std::exception &) {
return 0;
}
};
info.used_memory = get_size_t("used_memory");
info.used_memory_peak = get_size_t("used_memory_peak");
info.used_memory_lua = get_size_t("used_memory_lua");
info.used_memory_scripts = get_size_t("used_memory_scripts");
info.number_of_keys = get_size_t("db0"); // This is a simplification
info.number_of_expires = get_size_t("expired_keys");
info.number_of_connected_clients = get_size_t("connected_clients");
info.number_of_slaves = get_size_t("connected_slaves");
info.number_of_replicas = get_size_t("connected_slaves"); // Same as slaves
info.number_of_commands_processed = get_size_t("total_commands_processed");
info.total_connections_received = get_size_t("total_connections_received");
info.total_commands_processed = get_size_t("total_commands_processed");
info.instantaneous_ops_per_sec = get_size_t("instantaneous_ops_per_sec");
info.total_net_input_bytes = get_size_t("total_net_input_bytes");
info.total_net_output_bytes = get_size_t("total_net_output_bytes");
info.instantaneous_input_kbps = get_size_t("instantaneous_input_kbps");
info.instantaneous_output_kbps = get_size_t("instantaneous_output_kbps");
return info;
}
/**
* @brief Parses a Redis reply into a pipeline_result
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return PipelineResult value of the reply
* @throws ParseError if the reply is not an array
*/
qb::redis::pipeline_result
parse(ParseTag<qb::redis::pipeline_result>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);
}
qb::redis::pipeline_result result;
if (reply.elements == 0 || reply.element == nullptr) {
return result;
}
result.replies.reserve(reply.elements);
for (size_t i = 0; i < reply.elements; ++i) {
auto *sub_reply = reply.element[i];
if (sub_reply == nullptr) {
result.all_succeeded = false;
continue;
}
if (qb::redis::is_error(*sub_reply)) {
result.all_succeeded = false;
}
result.replies.push_back(reply_ptr(sub_reply));
}
return result;
}
/**
* @brief Parses a Redis reply into a qb::json object
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return A qb::json object representing the Redis reply
*/
qb::json
parse(ParseTag<qb::json>, redisReply &reply) {
// Handle different Redis reply types
if (qb::redis::is_nil(reply)) {
return qb::json(nullptr);
}
else if (qb::redis::is_integer(reply)) {
return qb::json(reply.integer);
}
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
else if (qb::redis::is_double(reply)) {
return qb::json(reply.dval);
}
else if (qb::redis::is_bool(reply)) {
return qb::json(reply.integer != 0);
}
#endif
else if (qb::redis::is_string(reply) || qb::redis::is_status(reply)) {
if (reply.str == nullptr) {
throw ProtoError("Null string reply");
}
std::string str(reply.str, reply.len);
// Try to parse strings that might be JSON objects or arrays
if (str.size() > 1 && ((str[0] == '{' && str[str.size() - 1] == '}') ||
(str[0] == '[' && str[str.size() - 1] == ']'))) {
try {
return qb::json::parse(str);
} catch (...) {
// If parsing fails, fall through to other conversion attempts
}
}
// Try to convert string values to appropriate types
// Handle boolean values
if (str == "true") {
return qb::json(true);
} else if (str == "false") {
return qb::json(false);
}
// Try numeric conversion for strings that look like numbers
if (str.find_first_not_of("-0123456789.") == std::string::npos) {
try {
if (str.find('.') != std::string::npos) {
// Try as double
return qb::json(std::stod(str));
} else {
// Try as integer
return qb::json(std::stoll(str));
}
} catch (...) {
// Silent catch, will return as string
}
}
// Default to returning as string
return qb::json(str);
}
else if (qb::redis::is_array(reply)) {
// If array has 0 elements or null elements
if (reply.elements == 0 || reply.element == nullptr) {
return qb::json::array();
}
// For Lua tables coming from Redis (via EVAL), we need special handling.
// When Redis returns a Lua table, it converts it to an array with alternating
// keys and values IF the table has string keys.
// First check if this could be an object (even number of elements)
bool is_object = (reply.elements % 2 == 0) && (reply.elements > 0);
// Check if all keys are strings to determine if this is a Lua table object
if (is_object) {
bool all_keys_are_strings = true;
for (size_t i = 0; i < reply.elements; i += 2) {
auto *key_reply = reply.element[i];
if (!key_reply || !qb::redis::is_string(*key_reply)) {
all_keys_are_strings = false;
break;
}
}
// If all keys are strings, treat as object
if (all_keys_are_strings) {
qb::json obj = qb::json::object();
for (size_t i = 0; i < reply.elements; i += 2) {
auto *key_reply = reply.element[i];
auto *val_reply = reply.element[i + 1];
if (key_reply == nullptr || val_reply == nullptr) {
throw ProtoError("Null reply in object");
}
std::string key = parse<std::string>(*key_reply);
qb::json value = parse<qb::json>(*val_reply);
obj[key] = value;
}
return obj;
}
}
// Otherwise, treat as regular array
qb::json arr = qb::json::array();
for (size_t i = 0; i < reply.elements; ++i) {
auto *element_reply = reply.element[i];
if (element_reply == nullptr) {
arr.push_back(nullptr);
} else {
arr.push_back(parse<qb::json>(*element_reply));
}
}
return arr;
}
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
else if (qb::redis::is_map(reply)) {
qb::json obj = qb::json::object();
for (size_t i = 0; i < reply.elements; ++i) {
auto *key_reply = reply.element[i]->element[0];
auto *val_reply = reply.element[i]->element[1];
if (key_reply == nullptr || val_reply == nullptr) {
throw ProtoError("Null reply in map");
}
std::string key = parse<std::string>(*key_reply);
qb::json value = parse<qb::json>(*val_reply);
obj[key] = value;
}
return obj;
}
#endif
// Default case for unsupported types
throw ProtoError("Unsupported Redis reply type for JSON conversion");
}
/**
* @brief Parses a Redis reply into a vector of score_member
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Vector of score_member values
* @throws ParseError if the reply is not an array
*/
std::vector<qb::redis::score_member>
parse(ParseTag<std::vector<qb::redis::score_member>>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);
}
if (reply.element == nullptr) {
throw ProtoError("Null array reply");
}
if (reply.elements % 2) {
throw ProtoError("Invalid array length for string-double pairs");
}
std::vector<qb::redis::score_member> result;
result.reserve(reply.elements / 2);
auto copy_reply = reply;
for (size_t i = 0; i < reply.elements; i += 2) {
copy_reply.elements = 2;
copy_reply.element = reply.element + i;
result.push_back(parse<qb::redis::score_member>(copy_reply));
}
return result;
}
/**
* @brief Parses a Redis reply into a vector of string-double pairs
* @param tag Parse tag type (unused, for template specialization)
* @param reply The Redis reply to parse
* @return Vector of string-double pairs
* @throws ParseError if the reply is not an array
*/
std::vector<std::pair<std::string, double>>
parse(ParseTag<std::vector<std::pair<std::string, double>>>, redisReply &reply) {
if (!qb::redis::is_array(reply)) {
throw ParseError("ARRAY", reply);