redis 1.5.0

Redis driver for Rust.
Documentation
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
#![cfg(feature = "json")]

use redis::json::{FphaType, JsonSetOptions};
use redis::{Commands, ExistenceCheck, JsonCommands, ValueType};
use std::assert_eq;
use std::collections::HashMap;
use std::f32::consts::PI;

use redis::{
    ErrorKind, RedisResult,
    Value::{self, *},
};
use redis_test::server::Module;

use crate::support::*;
mod support;

use serde::Serialize;
// adds json! macro for quick json generation on the fly.
use serde_json::json;

const TEST_KEY: &str = "my_json";

#[test]
fn test_module_json_serialize_error() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    #[derive(Debug, Serialize)]
    struct InvalidSerializedStruct {
        // Maps in serde_json must have string-like keys
        // so numbers and strings, anything else will cause the serialization to fail
        // this is basically the only way to make a serialization fail at runtime
        // since rust doesnt provide the necessary ability to enforce this
        pub invalid_json: HashMap<Option<bool>, i64>,
    }

    let mut test_invalid_value: InvalidSerializedStruct = InvalidSerializedStruct {
        invalid_json: HashMap::new(),
    };

    test_invalid_value.invalid_json.insert(None, 2i64);

    let set_invalid = con
        .json_set::<_, _, _, bool>(TEST_KEY, "$", &test_invalid_value)
        .unwrap_err();

    assert_eq!(set_invalid.kind(), ErrorKind::Serialize);
    assert_eq!(
        set_invalid.to_string(),
        String::from("key must be a string")
    );
}

#[test]
fn test_module_json_arr_append() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":[1i64], "nested": {"a": [1i64, 2i64]}, "nested2": {"a": 42i64}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_append: RedisResult<Value> = con.json_arr_append(TEST_KEY, "$..a", &3i64);

    assert_eq!(json_append, Ok(Array(vec![Int(2i64), Int(3i64), Nil])));
}

#[test]
fn test_module_json_arr_index() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":[1i64, 2i64, 3i64, 2i64], "nested": {"a": [3i64, 4i64]}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_arrindex: RedisResult<Value> = con.json_arr_index(TEST_KEY, "$..a", &2i64);

    assert_eq!(json_arrindex, Ok(Array(vec![Int(1i64), Int(-1i64)])));

    let update_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":[1i64, 2i64, 3i64, 2i64], "nested": {"a": false}}),
    );

    assert_eq!(update_initial, Ok(true));

    let json_arrindex_2: RedisResult<Value> =
        con.json_arr_index_ss(TEST_KEY, "$..a", &2i64, &0, &0);

    assert_eq!(json_arrindex_2, Ok(Array(vec![Int(1i64), Nil])));
}

#[test]
fn test_module_json_arr_insert() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":[3i64], "nested": {"a": [3i64 ,4i64]}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_arrinsert: RedisResult<Value> = con.json_arr_insert(TEST_KEY, "$..a", 0, &1i64);

    assert_eq!(json_arrinsert, Ok(Array(vec![Int(2), Int(3)])));

    let update_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":[1i64 ,2i64 ,3i64 ,2i64], "nested": {"a": false}}),
    );

    assert_eq!(update_initial, Ok(true));

    let json_arrinsert_2: RedisResult<Value> = con.json_arr_insert(TEST_KEY, "$..a", 0, &1i64);

    assert_eq!(json_arrinsert_2, Ok(Array(vec![Int(5), Nil])));
}

#[test]
fn test_module_json_arr_len() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a": [3i64], "nested": {"a": [3i64, 4i64]}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_arrlen: RedisResult<Value> = con.json_arr_len(TEST_KEY, "$..a");

    assert_eq!(json_arrlen, Ok(Array(vec![Int(1), Int(2)])));

    let update_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a": [1i64, 2i64, 3i64, 2i64], "nested": {"a": false}}),
    );

    assert_eq!(update_initial, Ok(true));

    let json_arrlen_2: RedisResult<Value> = con.json_arr_len(TEST_KEY, "$..a");

    assert_eq!(json_arrlen_2, Ok(Array(vec![Int(4), Nil])));
}

#[test]
fn test_module_json_arr_pop() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a": [3i64], "nested": {"a": [3i64, 4i64]}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_arrpop: RedisResult<Value> = con.json_arr_pop(TEST_KEY, "$..a", -1);

    assert_eq!(
        json_arrpop,
        Ok(Array(vec![
            // convert string 3 to its ascii value as bytes
            BulkString(Vec::from("3".as_bytes())),
            BulkString(Vec::from("4".as_bytes()))
        ]))
    );

    let update_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":["foo", "bar"], "nested": {"a": false}, "nested2": {"a":[]}}),
    );

    assert_eq!(update_initial, Ok(true));

    let json_arrpop_2: RedisResult<Value> = con.json_arr_pop(TEST_KEY, "$..a", -1);

    assert_eq!(
        json_arrpop_2,
        Ok(Array(vec![
            BulkString(Vec::from("\"bar\"".as_bytes())),
            Nil,
            Nil
        ]))
    );
}

#[test]
fn test_module_json_arr_trim() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a": [], "nested": {"a": [1i64, 4u64]}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_arrtrim: RedisResult<Value> = con.json_arr_trim(TEST_KEY, "$..a", 1, 1);

    assert_eq!(json_arrtrim, Ok(Array(vec![Int(0), Int(1)])));

    let update_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a": [1i64, 2i64, 3i64, 4i64], "nested": {"a": false}}),
    );

    assert_eq!(update_initial, Ok(true));

    let json_arrtrim_2: RedisResult<Value> = con.json_arr_trim(TEST_KEY, "$..a", 1, 1);

    assert_eq!(json_arrtrim_2, Ok(Array(vec![Int(1), Nil])));
}

#[test]
fn test_module_json_clear() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(TEST_KEY, "$", &json!({"obj": {"a": 1i64, "b": 2i64}, "arr": [1i64, 2i64, 3i64], "str": "foo", "bool": true, "int": 42i64, "float": std::f64::consts::PI}));

    assert_eq!(set_initial, Ok(true));

    let json_clear: RedisResult<i64> = con.json_clear(TEST_KEY, "$.*");

    assert_eq!(json_clear, Ok(4));

    let checking_value: RedisResult<String> = con.json_get(TEST_KEY, "$");

    // float is set to 0 and serde_json serializes 0f64 to 0.0, which is a different string
    assert_eq!(
        checking_value,
        // i found it changes the order?
        // its not really a problem if you're just deserializing it anyway but still
        // kinda weird
        Ok("[{\"arr\":[],\"bool\":true,\"float\":0,\"int\":0,\"obj\":{},\"str\":\"foo\"}]".into())
    );
}

#[test]
fn test_module_json_del() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a": 1i64, "nested": {"a": 2i64, "b": 3i64}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_del: RedisResult<i64> = con.json_del(TEST_KEY, "$..a");

    assert_eq!(json_del, Ok(2));
}

#[test]
fn test_module_json_get() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":2i64, "b": 3i64, "nested": {"a": 4i64, "b": null}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_get: RedisResult<String> = con.json_get(TEST_KEY, "$..b");

    assert_eq!(json_get, Ok("[3,null]".into()));

    let json_get_multi: RedisResult<String> = con.json_get(TEST_KEY, &["..a", "$..b"]);

    if json_get_multi != Ok("{\"$..b\":[3,null],\"..a\":[2,4]}".into())
        && json_get_multi != Ok("{\"..a\":[2,4],\"$..b\":[3,null]}".into())
    {
        panic!("test_error: incorrect response from json_get_multi");
    }
}

#[test]
fn test_module_json_mget() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_mset(&[
        (
            format!("{TEST_KEY}-a"),
            "$",
            &json!({"a":1i64, "b": 2i64, "nested": {"a": 3i64, "b": null}}),
        ),
        (
            format!("{TEST_KEY}-b"),
            "$",
            &json!({"a":4i64, "b": 5i64, "nested": {"a": 6i64, "b": null}}),
        ),
    ]);

    assert_eq!(set_initial, Ok(true));

    let json_mget: RedisResult<Value> = con.json_mget(
        vec![format!("{TEST_KEY}-a"), format!("{TEST_KEY}-b")],
        "$..a",
    );

    assert_eq!(
        json_mget,
        Ok(Array(vec![
            BulkString(Vec::from("[1,3]".as_bytes())),
            BulkString(Vec::from("[4,6]".as_bytes()))
        ]))
    );
}

#[test]
fn test_module_json_num_incr_by() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":"b","b":[{"a":2i64}, {"a":5i64}, {"a":"c"}]}),
    );

    assert_eq!(set_initial, Ok(true));

    if ctx.protocol.supports_resp3() && ctx.supports(REDIS_CE_7_0) {
        // cannot increment a string
        let json_numincrby_a: RedisResult<Vec<Value>> = con.json_num_incr_by(TEST_KEY, "$.a", 2);
        assert_eq!(json_numincrby_a, Ok(vec![Nil]));

        let json_numincrby_b: RedisResult<Vec<Value>> = con.json_num_incr_by(TEST_KEY, "$..a", 2);

        // however numbers can be incremented
        assert_eq!(json_numincrby_b, Ok(vec![Nil, Int(4), Int(7), Nil]));
    } else {
        // cannot increment a string
        let json_numincrby_a: RedisResult<String> = con.json_num_incr_by(TEST_KEY, "$.a", 2);
        assert_eq!(json_numincrby_a, Ok("[null]".into()));

        let json_numincrby_b: RedisResult<String> = con.json_num_incr_by(TEST_KEY, "$..a", 2);

        // however numbers can be incremented
        assert_eq!(json_numincrby_b, Ok("[null,4,7,null]".into()));
    }
}

#[test]
fn test_module_json_obj_keys() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":[3i64], "nested": {"a": {"b":2i64, "c": 1i64}}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_objkeys: RedisResult<Value> = con.json_obj_keys(TEST_KEY, "$..a");

    assert_eq!(
        json_objkeys,
        Ok(Array(vec![
            Nil,
            Array(vec![
                BulkString(Vec::from("b".as_bytes())),
                BulkString(Vec::from("c".as_bytes()))
            ])
        ]))
    );
}

#[test]
fn test_module_json_obj_len() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":[3i64], "nested": {"a": {"b":2i64, "c": 1i64}}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_objlen: RedisResult<Value> = con.json_obj_len(TEST_KEY, "$..a");

    assert_eq!(json_objlen, Ok(Array(vec![Nil, Int(2)])));
}

#[test]
fn test_module_json_set() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set: RedisResult<bool> = con.json_set(TEST_KEY, "$", &json!({"key": "value"}));

    assert_eq!(set, Ok(true));
}

#[test]
fn test_module_json_str_append() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":"foo", "nested": {"a": "hello"}, "nested2": {"a": 31i64}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_strappend: RedisResult<Value> = con.json_str_append(TEST_KEY, "$..a", "\"baz\"");

    assert_eq!(json_strappend, Ok(Array(vec![Int(6), Int(8), Nil])));

    let json_get_check: RedisResult<String> = con.json_get(TEST_KEY, "$");

    assert_eq!(
        json_get_check,
        Ok("[{\"a\":\"foobaz\",\"nested\":{\"a\":\"hellobaz\"},\"nested2\":{\"a\":31}}]".into())
    );
}

#[test]
fn test_module_json_str_len() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":"foo", "nested": {"a": "hello"}, "nested2": {"a": 31i32}}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_strlen: RedisResult<Value> = con.json_str_len(TEST_KEY, "$..a");

    assert_eq!(json_strlen, Ok(Array(vec![Int(3), Int(5), Nil])));
}

#[test]
fn test_module_json_toggle() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(TEST_KEY, "$", &json!({"bool": true}));

    assert_eq!(set_initial, Ok(true));

    let json_toggle_a: RedisResult<Value> = con.json_toggle(TEST_KEY, "$.bool");
    assert_eq!(json_toggle_a, Ok(Array(vec![Int(0)])));

    let json_toggle_b: RedisResult<Value> = con.json_toggle(TEST_KEY, "$.bool");
    assert_eq!(json_toggle_b, Ok(Array(vec![Int(1)])));
}

#[test]
fn test_module_json_type() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_initial: RedisResult<bool> = con.json_set(
        TEST_KEY,
        "$",
        &json!({"a":2i64, "nested": {"a": true}, "foo": "bar"}),
    );

    assert_eq!(set_initial, Ok(true));

    let json_type_a: RedisResult<Value> = con.json_type(TEST_KEY, "$..foo");
    let json_type_b: RedisResult<Value> = con.json_type(TEST_KEY, "$..a");
    let json_type_c: RedisResult<Value> = con.json_type(TEST_KEY, "$..dummy");

    if ctx.protocol.supports_resp3() && ctx.supports(REDIS_CE_7_0) {
        // In RESP3 current RedisJSON always gives response in an array.
        assert_eq!(
            json_type_a,
            Ok(Array(vec![Array(vec![BulkString(Vec::from(
                "string".as_bytes()
            ))])]))
        );

        assert_eq!(
            json_type_b,
            Ok(Array(vec![Array(vec![
                BulkString(Vec::from("integer".as_bytes())),
                BulkString(Vec::from("boolean".as_bytes()))
            ])]))
        );
        assert_eq!(json_type_c, Ok(Array(vec![Array(vec![])])));
    } else {
        assert_eq!(
            json_type_a,
            Ok(Array(vec![BulkString(Vec::from("string".as_bytes()))]))
        );

        assert_eq!(
            json_type_b,
            Ok(Array(vec![
                BulkString(Vec::from("integer".as_bytes())),
                BulkString(Vec::from("boolean".as_bytes()))
            ]))
        );
        assert_eq!(json_type_c, Ok(Array(vec![])));
    }

    // Checking the type of the key as a whole
    let key_type: RedisResult<ValueType> = con.key_type(TEST_KEY);
    assert_eq!(key_type, Ok(ValueType::JSON));
}

#[test]
fn test_module_json_set_options_json_value() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let set_result: RedisResult<bool> = con.json_set_options(
        TEST_KEY,
        "$",
        &json!({"a": 1, "b": [2, 3]}),
        &JsonSetOptions::default(),
    );
    assert_eq!(set_result, Ok(true));

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok(r#"[{"a":1,"b":[2,3]}]"#.to_string()));
}

#[test]
fn test_module_json_set_options_nx_xx() {
    let ctx = TestContext::with_modules(&[Module::Json]);
    let mut con = ctx.connection();

    let opts_xx = JsonSetOptions::default().conditional_set(ExistenceCheck::XX);
    let opts_nx = JsonSetOptions::default().conditional_set(ExistenceCheck::NX);

    // XX on a missing key should not create the key.
    let _: RedisResult<redis::Value> =
        con.json_set_options(TEST_KEY, "$", &json!({"v": 0}), &opts_xx);
    let key_exists: RedisResult<bool> = con.exists(TEST_KEY);
    assert_eq!(key_exists, Ok(false));

    // NX on a fresh key should succeed.
    assert_eq!(
        con.json_set_options::<_, _, _, bool>(TEST_KEY, "$", &json!({"v": 1}), &opts_nx),
        Ok(true),
    );
    let key_exists: RedisResult<bool> = con.exists(TEST_KEY);
    assert_eq!(key_exists, Ok(true));

    // NX again must be a no-op because the key exists.
    let _: RedisResult<redis::Value> =
        con.json_set_options(TEST_KEY, "$", &json!({"v": 999}), &opts_nx);
    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$.v");
    assert_eq!(get_result, Ok("[1]".to_string()));

    // XX on the existing key should succeed and overwrite the value.
    assert_eq!(
        con.json_set_options::<_, _, _, bool>(TEST_KEY, "$", &json!({"v": 2}), &opts_xx),
        Ok(true),
    );
    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$.v");
    assert_eq!(get_result, Ok("[2]".to_string()));
}

// FPHA integration tests.

// The value travels as a JSON array of numbers.
// The `FPHA <TYPE>` token is a storage hint that asks the server to pack the array internally as bf16/fp16/fp32/fp64 lanes.
// Round-trip via `JSON.GET` returns the array as a JSON array of numbers.
#[rstest::rstest]
#[case::fp32(FphaType::Fp32)]
#[case::fp64(FphaType::Fp64)]
#[case::bf16(FphaType::Bf16)]
#[case::fp16(FphaType::Fp16)]
fn test_module_json_set_fpha_roundtrip(#[case] fpha_type: FphaType) {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[1.0_f32, 2.0, -3.5],
            &JsonSetOptions::default().fpha(fpha_type)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[1.0,2.0,-3.5]]".to_string()));
}

#[test]
fn test_module_json_set_fpha_empty_payload() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[0_f32; 0],
            &JsonSetOptions::default().fpha(FphaType::Fp32)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[]]".to_string()));
}

#[test]
fn test_module_json_set_fpha_with_existence_check() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    // XX against a missing key must not create it.
    let opts_xx = JsonSetOptions::default()
        .fpha(FphaType::Fp32)
        .conditional_set(ExistenceCheck::XX);
    let _: RedisResult<redis::Value> = con.json_set_options(TEST_KEY, "$", &[1.0_f32], &opts_xx);
    let key_exists: RedisResult<bool> = con.exists(TEST_KEY);
    assert_eq!(key_exists, Ok(false));

    // NX on the same missing key creates it.
    let opts_nx = JsonSetOptions::default()
        .fpha(FphaType::Fp32)
        .conditional_set(ExistenceCheck::NX);
    assert_eq!(
        con.json_set_options::<_, _, _, bool>(TEST_KEY, "$", &[1.0_f32, 2.0, 3.0], &opts_nx),
        Ok(true),
    );
    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[1.0,2.0,3.0]]".to_string()));
}

// FP16 storage range is ±65504.
// A value outside that range must be rejected by the server with an out-of-range error.
#[test]
fn test_module_json_set_fpha_fp16_overflow() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    let set_result: RedisResult<redis::Value> = con.json_set_options(
        TEST_KEY,
        "$",
        &[70000.0_f32],
        &JsonSetOptions::default().fpha(FphaType::Fp16),
    );
    let error = set_result.unwrap_err();
    assert!(
        error.to_string().contains("out of range for F16"),
        "unexpected error message: {error}",
    );

    let key_exists: RedisResult<bool> = con.exists(TEST_KEY);
    assert_eq!(key_exists, Ok(false));
}

// Per the FPHA docs:
// "If at least one value in the FP array does not fit the FPHA type, the command errors."

// Verify that a single out-of-range element in an otherwise valid payload rejects the whole command and leaves the key untouched.
#[test]
fn test_module_json_set_fpha_fp16_partial_overflow() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    let set_result: RedisResult<redis::Value> = con.json_set_options(
        TEST_KEY,
        "$",
        &[1.0_f32, 2.0, 70000.0, 3.0],
        &JsonSetOptions::default().fpha(FphaType::Fp16),
    );
    assert!(
        set_result.is_err(),
        "expected server error, got {set_result:?}"
    );

    let key_exists: RedisResult<bool> = con.exists(TEST_KEY);
    assert_eq!(key_exists, Ok(false));
}

// 65504 is the largest finite value representable in IEEE-754 binary16.
#[test]
fn test_module_json_set_fpha_fp16_max_boundary() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[65504.0_f32],
            &JsonSetOptions::default().fpha(FphaType::Fp16)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[65504.0]]".to_string()));
}

// 3.4e38 is near the largest finite value representable in IEEE-754 binary32.
#[test]
fn test_module_json_set_fpha_fp32_max_boundary() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[3.4e38_f32],
            &JsonSetOptions::default().fpha(FphaType::Fp32)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[3.4e38]]".to_string()));
}

// 2^20 (= 1048576) is exactly representable in bf16 and well above FP16's ±65504 limit.
// The same value would be rejected under FPHA FP16 but under FPHA BF16 it round-trips losslessly.
#[test]
fn test_module_json_set_fpha_bf16_above_fp16_range() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[1048576.0_f32],
            &JsonSetOptions::default().fpha(FphaType::Bf16)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[1048576.0]]".to_string()));
}

// Values that serde_json emits in scientific notation must be accepted by the server and round-tripped back as scientific notation.
// Note: serde emits `6.022e+23` while the server omits the `+`.
#[test]
fn test_module_json_set_fpha_fp32_scientific_notation() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[1e-10_f32, 6.022e23_f32],
            &JsonSetOptions::default().fpha(FphaType::Fp32)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[1e-10,6.022e23]]".to_string()));
}

// Demonstrate the lossy nature of FPHA BF16 storage.

// bf16 has a 7-bit mantissa.
// Around 100 its step size is 0.5, so 100.7 snaps to 100.5
// pi (3.1415927) snaps to 3.14.
#[test]
fn test_module_json_set_fpha_bf16_truncation() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[100.7_f32, PI],
            &JsonSetOptions::default().fpha(FphaType::Bf16)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[100.5,3.14]]".to_string()));
}

// fp16 has a 10-bit mantissa, so it preserves more precision than bf16.
// Around 1.0 its step size is ~0.001, which snaps 1.0009766 to 1.001, pi still snaps to 3.14.
#[test]
fn test_module_json_set_fpha_fp16_truncation() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &[1.0009766_f32, PI],
            &JsonSetOptions::default().fpha(FphaType::Fp16)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[1.001,3.14]]".to_string()));
}

// The FPHA hint applies to any serializable value, not just flat slices.
// A 2-D matrix exercises the docs' "all FP arrays in value" wording - the hint is applied to every inner array.
// With BF16, 100.7 snaps to 100.5 and pi snaps to 3.14 within their respective inner arrays.
#[test]
fn test_module_json_set_fpha_matrix() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    let matrix: &[&[f32]] = &[&[1.0, 100.7], &[PI, 4.0]];
    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &matrix,
            &JsonSetOptions::default().fpha(FphaType::Bf16)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[[[1.0,100.5],[3.14,4.0]]]".to_string()));
}

// An object holding multiple FP-array fields gets the storage hint applied to each field independently.
#[test]
fn test_module_json_set_fpha_object_with_array_fields() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &serde_json::json!({"weights": [1.0, 2.0, 3.0], "bias": [0.5, 0.25]}),
            &JsonSetOptions::default().fpha(FphaType::Fp16)
        ),
        Ok(true),
    );

    // `serde_json::Value::Object` is a BTreeMap, so keys serialize in
    // alphabetical order (`bias` before `weights`) regardless of input order.
    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(
        get_result,
        Ok(r#"[{"bias":[0.5,0.25],"weights":[1.0,2.0,3.0]}]"#.to_string()),
    );
}

// Per the FPHA docs:
// "If at least one value in the FP array does not fit the FPHA type, the command errors."

// Verify that a single out-of-range value causes the entire command to fail without modifying the key, even when the offending value appears in a nested array.
#[test]
fn test_module_json_set_fpha_nested_partial_overflow() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    let matrix: &[&[f32]] = &[&[1.0, 2.0], &[70000.0, 3.0]];
    let set_result: RedisResult<redis::Value> = con.json_set_options(
        TEST_KEY,
        "$",
        &matrix,
        &JsonSetOptions::default().fpha(FphaType::Fp16),
    );
    assert!(
        set_result.is_err(),
        "expected server error, got {set_result:?}"
    );

    let key_exists: RedisResult<bool> = con.exists(TEST_KEY);
    assert_eq!(key_exists, Ok(false));
}

// A scalar (not an array) is also a valid FPHA payload server-side.
#[test]
fn test_module_json_set_fpha_scalar() {
    let ctx =
        run_test_if_version_supported!([&[REDIS_CE_8_8][..], &[REDIS_JSON_8_8]], &[Module::Json]);
    let mut con = ctx.connection();

    assert_eq!(
        con.json_set_options::<_, _, _, bool>(
            TEST_KEY,
            "$",
            &1.5_f32,
            &JsonSetOptions::default().fpha(FphaType::Fp32)
        ),
        Ok(true),
    );

    let get_result: RedisResult<String> = con.json_get(TEST_KEY, "$");
    assert_eq!(get_result, Ok("[1.5]".to_string()));
}